(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!")
相关推荐
花酒锄作田5 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪9 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽9 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战10 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋16 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama