在ArcGIS中,可以利用ArcToolbox中的数据管理下的投影工具对栅格影像数据和矢量文件进行投影转换,也可以进行批量投影操作。
本代码和ArcGIS实现的功能一样,都是对栅格影像和矢量文件进行批量投影,所调用的工具是 Project_management 和 ProjectRaster_management 函数。代码如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import arcpy
arcpy.CheckOutExtension("spatial")
"""
================ 参数说明 =====================
shape_path: 待投影shape文件夹
raster_path: 待投影栅格文件夹
save_path: 保存文件夹
reference_file: 投影参考文件, 可以是shape文件, 也可以是栅格文件, 主要是为了获取投影参数
==============================================
"""
# shape文件批量投影
def batch_shape_proj(shape_path, save_path, reference_file):
try:
if not os.path.exists(save_path):
os.mkdir(save_path)
for file_list in os.listdir(shape_path):
if file_list.endswith('.shp'):
shape = shape_path + '/' + file_list # 待投影文件
outPath = save_path + "/" + file_list.split('.')[-2] + "_proj.shp"
coordinate_system = arcpy.Describe(reference_file).spatialReference
arcpy.Project_management(shape, outPath, coordinate_system)
except arcpy.ExecuteError:
print(arcpy.GetMessages())
# 栅格数据批量投影
def batch_raster_proj(raster_path, save_path, reference_file):
try:
if not os.path.exists(save_path):
os.mkdir(save_path)
for file_list in os.listdir(raster_path):
if file_list.endswith('.tif'):
raster = raster_path + '/' + file_list # 待投影文件
outPath = save_path + "/" + file_list.split('.')[-2] + "_proj.tif"
coordinate_system = arcpy.Describe(reference_file).spatialReference
arcpy.ProjectRaster_management(raster, outPath, coordinate_system, "BILINEAR", "", "", "#", "#")
except arcpy.ExecuteError:
print(arcpy.GetMessages())
代码很简单。注意,这里需要提供一个已有的投影文件用于获取投影信息,如果没有的话,使用自定义的投影信息应该也是可以的。