脚本如何批量转换地理信息格式

wen 实用脚本 5

本文目录导读:

脚本如何批量转换地理信息格式

  1. 使用 GDAL/OGR(命令行工具)
  2. Python 使用 Fiona/Shapely
  3. 使用 QGIS 进行批量转换
  4. 批量格式转换脚本模板
  5. 高级功能:坐标系转换
  6. 注意事项

使用 GDAL/OGR(命令行工具)

安装 GDAL

# Ubuntu/Debian
sudo apt-get install gdal-bin
# macOS
brew install gdal
# Windows
# 下载 OSGeo4W 安装包

批量转换脚本

Python 脚本使用 GDAL:

import os
import glob
from osgeo import ogr, osr
def batch_convert_shp_to_geojson(input_dir, output_dir):
    """批量将Shapefile转换为GeoJSON"""
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)
    # 查找所有shp文件
    shp_files = glob.glob(os.path.join(input_dir, "*.shp"))
    for shp_file in shp_files:
        # 生成输出文件名
        base_name = os.path.splitext(os.path.basename(shp_file))[0]
        output_file = os.path.join(output_dir, f"{base_name}.geojson")
        # 转换命令
        cmd = f"ogr2ogr -f 'GeoJSON' '{output_file}' '{shp_file}'"
        os.system(cmd)
        print(f"转换完成: {shp_file} -> {output_file}")
# 使用示例
batch_convert_shp_to_geojson("./input_shp", "./output_geojson")

常用格式转换命令

# Shapefile 转 GeoJSON
ogr2ogr -f "GeoJSON" output.geojson input.shp
# GeoJSON 转 Shapefile
ogr2ogr -f "ESRI Shapefile" output.shp input.geojson
# Shapefile 转 KML
ogr2ogr -f "KML" output.kml input.shp
# 批量转换所有文件
for f in *.shp; do
    ogr2ogr -f "GeoJSON" "${f%.shp}.geojson" "$f"
done

Python 使用 Fiona/Shapely

import fiona
import glob
import os
def batch_convert_formats(input_dir, output_dir, input_format, output_format):
    """通用批量格式转换函数"""
    # 格式映射
    format_ext = {
        'GeoJSON': '.geojson',
        'ESRI Shapefile': '.shp',
        'KML': '.kml',
        'GPKG': '.gpkg'
    }
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)
    # 查找输入文件
    input_ext = format_ext.get(input_format, '.shp')
    files = glob.glob(os.path.join(input_dir, f"*{input_ext}"))
    for input_file in files:
        base_name = os.path.splitext(os.path.basename(input_file))[0]
        output_file = os.path.join(
            output_dir, 
            f"{base_name}{format_ext[output_format]}"
        )
        # 读取并转换
        with fiona.open(input_file, 'r') as source:
            # 获取坐标系信息
            crs = source.crs
            # 写入新格式
            with fiona.open(
                output_file, 
                'w',
                driver=output_format,
                schema=source.schema,
                crs=crs
            ) as dest:
                for feature in source:
                    dest.write(feature)
        print(f"转换完成: {input_file} -> {output_file}")
# 使用示例
batch_convert_formats("./input", "./output", "ESRI Shapefile", "GeoJSON")

使用 QGIS 进行批量转换

QGIS 处理模型

  1. 打开 QGIS → 处理工具箱 → 模型设计器
  2. 创建模型:
    • 添加文件选择器(输入目录)
    • 添加矢量图层迭代器
    • 添加"转换格式"算法
    • 添加输出文件管理器

QGIS Python 脚本

from qgis.core import *
import processing
import os
def batch_convert_qgis(input_dir, output_dir, target_format='GeoJSON'):
    """在QGIS中批量转换"""
    QgsApplication.processingRegistry().addProvider(
        QgsNativeAlgorithms(QgsApplication.instance())
    )
    # 遍历文件
    for root, dirs, files in os.walk(input_dir):
        for file in files:
            if file.endswith('.shp'):
                input_path = os.path.join(root, file)
                base_name = os.path.splitext(file)[0]
                output_path = os.path.join(output_dir, f"{base_name}.geojson")
                # 使用处理算法转换
                params = {
                    'INPUT': input_path,
                    'OUTPUT': output_path
                }
                processing.run("native:convertformat", params)
# 在QGIS Python控制台中运行
batch_convert_qgis("./input", "./output")

批量格式转换脚本模板

#!/bin/bash
# batch_convert.sh - 批量地理数据格式转换
# 配置参数
INPUT_DIR="./input"
OUTPUT_DIR="./output"
SOURCE_FORMAT="shp"
TARGET_FORMAT="geojson"
# 创建输出目录
mkdir -p "$OUTPUT_DIR"
# 批量转换
for file in "$INPUT_DIR"/*.$SOURCE_FORMAT; do
    if [ -f "$file" ]; then
        filename=$(basename "$file" ".$SOURCE_FORMAT")
        output_file="$OUTPUT_DIR/$filename.$TARGET_FORMAT"
        echo "转换中: $file -> $output_file"
        ogr2ogr -f "GeoJSON" "$output_file" "$file"
        if [ $? -eq 0 ]; then
            echo "✓ 转换成功: $filename"
        else
            echo "✗ 转换失败: $filename"
        fi
    fi
done
echo "批量转换完成!"

高级功能:坐标系转换

def batch_convert_with_reprojection(input_dir, output_dir, target_epsg=4326):
    """批量转换并重投影"""
    import pyproj
    from functools import partial
    from shapely.ops import transform
    from shapely.geometry import shape, mapping
    for shp_file in glob.glob(os.path.join(input_dir, "*.shp")):
        with fiona.open(shp_file) as source:
            # 源坐标系
            source_crs = pyproj.CRS(source.crs)
            target_crs = pyproj.CRS(f"EPSG:{target_epsg}")
            # 创建投影转换器
            project = pyproj.Transformer.from_crs(
                source_crs, target_crs, always_xy=True
            ).transform
            # 准备输出
            output_file = os.path.join(
                output_dir,
                f"{os.path.basename(shp_file)[:-4]}_wgs84.geojson"
            )
            # 转换几何并写入
            with fiona.open(
                output_file, 'w',
                driver='GeoJSON',
                schema=source.schema,
                crs=f"EPSG:{target_epsg}"
            ) as dest:
                for feature in source:
                    geom = shape(feature['geometry'])
                    transformed_geom = transform(project, geom)
                    feature['geometry'] = mapping(transformed_geom)
                    dest.write(feature)

注意事项

  1. 编码问题:中文数据注意编码设置
  2. 性能优化:大量数据考虑使用并行处理
  3. 错误处理:添加异常捕捉和日志记录
  4. 依赖管理:使用虚拟环境管理Python包

这些脚本可以满足大部分批量转换需求,根据实际情况调整参数即可。

抱歉,评论功能暂时关闭!