Skip to article frontmatterSkip to article content
# โ”€โ”€โ”€ โ‘  imports โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
import geopandas as gpd
from pathlib import Path
import shutil, os
# โ”€โ”€โ”€ โ‘ก ๅ‚ๆ•ฐ้…็ฝฎ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
input_root  = Path(r'D:/gis/to_transform')     # ๅพ…่ฝฌๆขๆ–‡ไปถๆ น็›ฎๅฝ•
output_root = Path(r'D:/gis/transformed')      # ่พ“ๅ‡บๆ น็›ฎๅฝ•
output_root.mkdir(parents=True, exist_ok=True)

target_crs = 'EPSG:4326'          # ็›ฎๆ ‡๏ผšWGS-84
assumed_source_crs = None         # ๅฆ‚ๆžœๆ•ฐๆฎๆœฌ่บซๆฒก CRS๏ผŒ่ฏทๅœจ่ฟ™้‡Œๅกซๅฆ‚ 'EPSG:4547' ็ญ‰
# โ”€โ”€โ”€ โ‘ข ๆ ธๅฟƒๅ‡ฝๆ•ฐ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def transform_vector(in_path: Path):
    """Read vector file, re-project to `target_crs`, write to mirror location."""
    try:
        gdf = gpd.read_file(in_path)
    except Exception as e:
        print(f'[ERR] {in_path.name}: {e}')
        return
    
    if gdf.crs is None:
        if not assumed_source_crs:
            print(f'[SKIP] {in_path.name}: no CRS & no assumed_source_crs.')
            return
        gdf = gdf.set_crs(assumed_source_crs)
    
    if str(gdf.crs).upper() == str(target_crs).upper():
        print(f'[=] {in_path.name}: already in {target_crs}')
        return
    
    gdf_out = gdf.to_crs(target_crs)
    rel     = in_path.relative_to(input_root)
    out_path = (output_root / rel).with_suffix('.shp')  # ๅง‹็ปˆๅ†™ Shapefile
    out_path.parent.mkdir(parents=True, exist_ok=True)
    gdf_out.to_file(out_path)
    print(f'[OK] {in_path} โ†’ {out_path}')
# โ”€โ”€โ”€ โ‘ฃ ๆ‰นๅค„็†ๆ‰ง่กŒ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
vector_exts = {'.shp', '.geojson', '.json', '.gpkg'}
files = [p for p in input_root.rglob('*') if p.suffix.lower() in vector_exts]

print(f'Total vector files: {len(files)}')
for vec in files:
    transform_vector(vec)