File size: 13,050 Bytes
9bc98d9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | import json
from pathlib import Path
import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import rasterio
from dbfread import DBF
from matplotlib.colors import Normalize
from osgeo import gdal
from rasterio.features import rasterize
from rasterio.transform import from_bounds
def process_tif(input_path: Path, move_list: list[Path] = None, nodata: float = None) -> list[Path]:
"""
Process a single TIFF file by standardising and generating a PNG preview.
Args:
input_path (Path): Path to the TIFF file.
move_list (list[Path], optional): List to append generated files to.
nodata (float, optional): Overwriting nodata value.
Returns:
list[Path]: Updated list of processed files.
"""
if move_list is None:
move_list = []
new_move_list = move_list[:]
if input_path.suffix.lower() not in [".tif", ".tiff", ".asc"] or input_path.is_dir():
print(f"⚠️ Skipped non-TIFF file: {input_path}")
return new_move_list
try:
with rasterio.open(input_path) as src:
data = src.read(1) # preserve original dtype
if nodata is None:
nodata = src.nodata if src.nodata is not None else src.meta.get("nodata")
# Save standardized compressed TIFF
standardized_path = input_path.with_name(input_path.stem + ".standardized.tif")
with rasterio.open(standardized_path, "w", **src.meta, compress="deflate") as dst:
dst.write(data, 1)
new_move_list.append(standardized_path)
# Save PNG preview
step = max(1, int(max(data.shape) / 1000))
data_vis = data[::step, ::step]
if nodata is not None:
mask = np.isclose(data_vis, nodata)
data_vis = np.where(mask, np.nan, data_vis)
norm = Normalize(
vmin=np.nanpercentile(data_vis, 2),
vmax=np.nanpercentile(data_vis, 98)
)
scaled = np.uint8(np.clip(norm(data_vis) * 255, 0, 255))
rgb = np.stack([scaled] * 3, axis=-1)
rgb[np.isnan(data_vis)] = [255, 0, 255]
png_path = input_path.with_suffix(".png")
plt.imsave(png_path, rgb)
new_move_list.append(png_path)
print(f"✅ Processed {input_path.name}")
except Exception as e:
print(f"❌ Failed to process {input_path.name}: {e}")
return new_move_list
def process_excel(input_path: Path, skip_rows=0, move_list: list[Path] = None) -> list[Path]:
"""
Convert Excel file to CSV, skipping header rows automatically if requested.
Args:
input_path (Path): Path to the Excel file.
skip_rows (int or 'auto'): Number of rows to skip before header, or 'auto' to detect.
move_list (list[Path], optional): List to append output CSV to.
Returns:
list[Path]: Updated list of processed files.
"""
if move_list is None:
move_list = []
new_move_list = move_list[:]
if input_path.suffix.lower() not in [".xls", ".xlsx"]:
print(f"⚠️ Skipped non-Excel file: {input_path.name}")
return new_move_list
try:
# Auto-detect header if needed
if skip_rows == "auto":
peek = pd.read_excel(input_path, nrows=5, header=None)
skip_rows = 0
for _, row in peek.iterrows():
if all(isinstance(cell, str) for cell in row if pd.notna(cell)):
break
skip_rows += 1
# Convert Excel to CSV
df = pd.read_excel(input_path, skiprows=skip_rows)
df.columns = df.columns.str.replace(r'[\r\n]+', ' ', regex=True).str.strip()
csv_path = input_path.with_name(input_path.stem + ".csv")
df.to_csv(csv_path, index=False)
new_move_list.append(csv_path)
print(f"✅ Converted Excel to CSV: {csv_path.name}")
except Exception as e:
print(f"❌ Failed to process {input_path.name}: {e}")
return new_move_list
def process_dbf(input_path: Path, move_list: list[Path] = None) -> list[Path]:
"""
Convert DBF file to CSV.
Args:
input_path (Path): Path to the DBF file.
move_list (list[Path], optional): List to append output CSV to.
Returns:
list[Path]: Updated list of processed files.
"""
if move_list is None:
move_list = []
new_move_list = move_list[:]
if input_path.suffix.lower() != ".dbf":
print(f"⚠️ Skipped non-DBF file: {input_path.name}")
return new_move_list
try:
# Read DBF file
df = pd.DataFrame(iter(DBF(input_path)))
# Clean column names
df.columns = df.columns.str.replace(r'[\r\n]+', ' ', regex=True).str.strip()
# Save as CSV
csv_path = input_path.with_name(input_path.stem + ".csv")
df.to_csv(csv_path, index=False)
new_move_list.append(csv_path)
print(f"✅ Converted DBF to CSV: {csv_path.name}")
except Exception as e:
print(f"❌ Failed to process {input_path.name}: {e}")
return new_move_list
def process_shp(input_path: Path, move_list: list[Path] = None,
drop_geometry=False) -> list[Path]:
"""
Process a single Shapefile by extracting the attribute table and saving a meta.
Args:
input_path (Path): Path to the Shapefile (.shp).
move_list (list[Path], optional): List to append output files to.
drop_geometry (bool, optional): Whether to drop geometry columns.
Returns:
list[Path]: Updated list of processed files.
"""
if move_list is None:
move_list = []
new_move_list = move_list[:]
if input_path.suffix.lower() != ".shp":
print(f"⚠️ Skipped non-Shapefile: {input_path.name}")
return new_move_list
try:
# Read the shapefile
gdf = gpd.read_file(input_path)
# Save attribute table (drop geometry)
df = gdf.drop(columns=gdf.geometry.name, errors='ignore') if drop_geometry else gdf
csv_path = input_path.with_name(input_path.stem + ".shp.csv")
df.to_csv(csv_path, index=False)
new_move_list.append(csv_path)
# Save basic meta as JSON
meta = {
"n_features": len(gdf),
"crs": str(gdf.crs),
"bounds": gdf.total_bounds.tolist(), # [minx, miny, maxx, maxy]
"fields": list(df.columns)
}
json_path = input_path.with_name(input_path.stem + ".meta.json")
with open(json_path, "w") as f:
json.dump(meta, f, indent=2)
new_move_list.append(json_path)
print(f"✅ Processed Shapefile: {input_path.name}")
except Exception as e:
print(f"❌ Failed to process {input_path.name}: {e}")
return new_move_list
def process_rdc_rst(rdc_path: Path, move_list: list[Path] = None, nodata: float = None) -> list[Path]:
"""
Process an RDC/RST pair by standardising and generating a PNG preview.
Args:
rdc_path (Path): Path to the RDC file.
move_list (list[Path], optional): List to append generated files to.
nodata (float, optional): Overwriting nodata value.
Returns:
list[Path]: Updated list of processed files.
"""
if move_list is None:
move_list = []
new_move_list = move_list[:]
if rdc_path.suffix.lower() != ".rdc":
print(f"⚠️ Skipped non-RDC file: {rdc_path}")
return new_move_list
# Parse RDC metadata
try:
with open(rdc_path, "r") as f:
lines = f.readlines()
meta_dict = {}
for line in lines:
if ":" in line:
key, value = line.split(":", 1)
meta_dict[key.strip().lower()] = value.strip()
cols = int(meta_dict["columns"])
rows = int(meta_dict["rows"])
min_x = float(meta_dict["min. x"])
max_y = float(meta_dict["max. y"])
if nodata is None:
nodata_str = meta_dict.get("flag value", "none")
nodata = None if nodata_str.lower() == "none" else float(nodata_str)
# Resolution handling
try:
res = float(meta_dict["resolution"])
except ValueError:
# Compute resolution from extents
res_x = (float(meta_dict["max. x"]) - float(meta_dict["min. x"])) / cols
res_y = (float(meta_dict["max. y"]) - float(meta_dict["min. y"])) / rows
if not np.isclose(res_x, res_y):
print(f"⚠️ WARNING: non-square pixel! res_x={res_x}, res_y={res_y}")
res = res_x # or res_y — assume square pixels
# Define geotransform: (min_x, res, 0, max_y, 0, -res)
geotransform = (min_x, res, 0, max_y, 0, -res)
except Exception as e:
print(f"❌ Failed to parse RDC: {rdc_path.name}: {e}")
return new_move_list
# Read RST with GDAL
try:
rst_path = rdc_path.with_suffix(".rst")
ds = gdal.Open(str(rst_path))
band = ds.GetRasterBand(1)
data = band.ReadAsArray()
# Apply nodata mask
if nodata is not None:
data = np.ma.masked_equal(data, nodata)
# Save standardized compressed TIFF
standardized_path = rdc_path.with_name(rdc_path.stem + ".standardized.tif")
driver = gdal.GetDriverByName("GTiff")
out_ds = driver.Create(
str(standardized_path), cols, rows, 1, gdal.GDT_Float32, options=["COMPRESS=DEFLATE"]
)
out_ds.SetGeoTransform(geotransform)
out_ds.SetProjection("") # No CRS info in RDC, can leave empty or set if known
out_band = out_ds.GetRasterBand(1)
out_band.WriteArray(data)
if nodata is not None:
out_band.SetNoDataValue(nodata)
out_ds.FlushCache()
new_move_list.append(standardized_path)
# Save PNG preview
step = max(1, int(max(data.shape) / 1000))
data_vis = data[::step, ::step]
if nodata is not None:
mask = np.isclose(data_vis, nodata)
data_vis = np.where(mask, np.nan, data_vis)
norm = Normalize(
vmin=np.nanpercentile(data_vis, 2),
vmax=np.nanpercentile(data_vis, 98)
)
scaled = np.uint8(np.clip(norm(data_vis) * 255, 0, 255))
rgb = np.stack([scaled] * 3, axis=-1)
rgb[np.isnan(data_vis)] = [255, 0, 255]
png_path = rdc_path.with_suffix(".png")
plt.imsave(png_path, rgb)
new_move_list.append(png_path)
print(f"✅ Processed RDC/RST pair: {rdc_path.name}")
except Exception as e:
print(f"❌ Failed to process RDC/RST pair: {rdc_path.name}: {e}")
return new_move_list
def rasterize_shp(shp_path, columns, resolution_m=1000, out_dir=None, crs="EPSG:3035"):
"""
Rasterize specified columns from a shapefile into GeoTIFF rasters.
Parameters
----------
shp_path : str or Path
Path to the shapefile (.shp).
columns : list of str
List of column names in the shapefile to rasterize.
resolution_m : float, optional
Pixel size in meters (default = 1000, i.e. 1 km resolution).
out_dir : str or Path, optional
Output directory for GeoTIFFs. If None, same directory as shapefile.
crs : str or int, optional
Target coordinate reference system (default = 'EPSG:3035').
Output
------
Saves GeoTIFFs named '<shapefile_stem>__<column>.tif' in the output directory.
"""
shp_path = Path(shp_path)
out_dir = Path(out_dir) if out_dir else shp_path.parent
out_dir.mkdir(parents=True, exist_ok=True)
gdf = gpd.read_file(shp_path)
gdf = gdf.to_crs(crs)
missing_cols = [c for c in columns if c not in gdf.columns]
if missing_cols:
raise ValueError(f"Missing columns in shapefile: {missing_cols}")
minx, miny, maxx, maxy = gdf.total_bounds
width = int((maxx - minx) / resolution_m)
height = int((maxy - miny) / resolution_m)
transform = from_bounds(minx, miny, maxx, maxy, width, height)
stem = shp_path.stem
for col in columns:
print(f"Rasterizing '{col}' ...")
shapes = ((geom, val) for geom, val in zip(gdf.geometry, gdf[col]))
out_path = out_dir / f"{stem}__{col}.tif"
with rasterio.open(
out_path,
"w",
driver="GTiff",
height=height,
width=width,
count=1,
dtype="float32",
crs=gdf.crs,
transform=transform,
nodata=-9999,
) as dst:
raster = rasterize(
shapes=shapes,
out_shape=(height, width),
transform=transform,
fill=-9999,
dtype="float32",
)
dst.write(raster, 1)
print(f"✅ Saved → {out_path}")
print("🎉 Rasterization complete.")
|