(Arcgis)Python3.8批量裁剪利用shp文件裁剪tif栅格影像数据

使用环境:
pycharm2020
arcgis pro 中的python3.8

一、pycharm中设置python编译器。左上角"文件"------"设置"------找到python interpreter------找到arcgis pro安装文件夹中的python

python 复制代码
D:\ArcGIS Pro\bin\Python\envs\arcgispro-py3\python.exe

使用arcgis pro原因 :自带arcpy库,不需要进行pip install安装。(我是有python官网上的,但是不知道为什么装不了arcpy,所以用的这个方法)(代码是python3编写的,如果用arcgis 10.x版本,是python2需要自行修改)

二、python编程

设置 input_folder 变量为包含要裁剪的栅格影像数据的文件夹路径。shapefile 变量应该是用于裁剪的 shapefile 文件的路径。output_folder 变量是用于存储裁剪后的影像数据的文件夹路径。

代码会循环处理输入文件夹中的每个 .tif 文件,使用 Extract by Mask 工具将其裁剪为指定的 shapefile 边界,并将结果保存到输出文件夹中。

请确保在运行代码之前,你已经安装了 ArcPy 库,并根据你的实际情况修改了文件夹路径和文件名。
文件夹路径中如果包含了非UTF-8编码(中文)的字符,第一行加上# -*- coding: utf-8 -*-

python 复制代码
# -*- coding: utf-8 -*-

import arcpy
import os

# 设置工作环境
arcpy.env.workspace = r"C:\path\to\workspace"
arcpy.CheckOutExtension("Spatial")

# 输入文件夹路径和shapefile路径
input_folder = r"C:\path\to\input_folder"
shapefile = r"C:\path\to\shapefile.shp"

# 输出文件夹路径
output_folder = r"C:\path\to\output_folder"
if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# 获取输入文件夹中的所有tif文件
tif_files = [file for file in os.listdir(input_folder) if file.endswith(".tif")]

# 循环处理每个tif文件
for tif_file in tif_files:
    # 输入tif文件路径
    input_tif = os.path.join(input_folder, tif_file)
    
    # 输出tif文件路径
    output_tif = os.path.join(output_folder, tif_file)
    
    # 使用Extract by Mask工具进行裁剪
    arcpy.gp.ExtractByMask_sa(input_tif, shapefile, output_tif)
    
    print(f"Cropped {tif_file} successfully!")

print("All files cropped successfully!")
相关推荐
默_笙4 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003964 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技4 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时4 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊4 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1234 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero074 天前
Jev 与 Laya
python·语言模型