|
| 1 | +import rasterio |
| 2 | +import csv |
| 3 | +import numpy as np |
| 4 | +from tqdm import tqdm |
| 5 | + |
| 6 | +# Input GeoTIFF file |
| 7 | +tiff_file = "C:/Users/printer_admin/Downloads/small_area.tif" |
| 8 | +csv_file = "C:/Users/printer_admin/Downloads/satz_01.csv" |
| 9 | + |
| 10 | +# Open the raster file |
| 11 | +with rasterio.open(tiff_file) as src: |
| 12 | + band = src.read(1) # Read first band (grayscale values) |
| 13 | + transform = src.transform # Affine transformation |
| 14 | + nodata_value = src.nodata # NoData value |
| 15 | + crs = src.crs # Coordinate Reference System |
| 16 | + |
| 17 | + # Open CSV file for writing |
| 18 | + with open(csv_file, mode="w", newline="") as file: |
| 19 | + writer = csv.writer(file) |
| 20 | + writer.writerow(["longitude", "latitude", "value"]) # CSV Header |
| 21 | + |
| 22 | + # Use progress bar |
| 23 | + progress_bar = tqdm(total=band.shape[0], desc="Processing", unit="rows") |
| 24 | + |
| 25 | + # Convert pixel indices to geographic coordinates |
| 26 | + for row in range(band.shape[0]): |
| 27 | + for col in range(band.shape[1]): |
| 28 | + x, y = transform * (col, row) # Convert pixel to geographic coordinates |
| 29 | + value = band[row, col] |
| 30 | + |
| 31 | + # Preserve NoData value |
| 32 | + if value == nodata_value: |
| 33 | + continue # Skip NoData values (optional) |
| 34 | + |
| 35 | + writer.writerow([x, y, value]) |
| 36 | + progress_bar.update(1) |
| 37 | + |
| 38 | +transform_list = list(transform) |
| 39 | +# Save metadata separately |
| 40 | +metadata_file = "C:/Users/printer_admin/Downloads/tz_metadata.txt" |
| 41 | +with open(metadata_file, "w") as meta_file: |
| 42 | + meta_file.write(f"CRS: {crs.to_wkt()}\n") |
| 43 | + meta_file.write(f"Transform: {transform_list}\n") |
| 44 | + meta_file.write(f"NoData: {nodata_value}\n") |
| 45 | + |
| 46 | +print(f"✅ TIFF converted to CSV: {csv_file}") |
| 47 | +print(f"📜 Metadata saved to: {metadata_file}") |
0 commit comments