批量把shp里面积小于20的图斑和相邻面积大于400的图斑根据字段值相同合并的arcgis工具箱脚本代码
时间: 2023-07-14 19:13:18 浏览: 128
下面是一个用 Python 编写的 ArcGIS 工具箱脚本,用于批量把 shapefile 中面积小于 20 的图斑和相邻面积大于 400 的图斑根据指定字段值合并。
```python
#-*- coding:utf-8 -*-
import arcpy
# 定义输入参数
input_folder = arcpy.GetParameterAsText(0)
field_name = arcpy.GetParameterAsText(1)
output_folder = arcpy.GetParameterAsText(2)
# 设置环境变量
arcpy.env.workspace = input_folder
arcpy.env.overwriteOutput = True
# 获取所有 shapefile 文件
shp_list = arcpy.ListFeatureClasses("*.shp")
# 遍历每个 shapefile 文件
for shp in shp_list:
# 计算面积
arcpy.AddField_management(shp, "AREA", "DOUBLE")
arcpy.CalculateGeometryAttributes_management(shp, [["AREA", "AREA"]], "", "SQUARE_METERS")
# 根据面积和相邻面积判断需要合并的图斑
with arcpy.da.UpdateCursor(shp, ["OID@", "AREA"]) as cursor:
for row in cursor:
if row[1] < 20:
# 获取相邻面积大于 400 的图斑
adjacent_list = []
adjacent_cursor = arcpy.SearchCursor(shp, "OBJECTID <> " + str(row[0]), "", field_name + ";SHAPE@", "")
for adjacent_row in adjacent_cursor:
if adjacent_row[1].touches(row[1]) and adjacent_row[1].area > 400:
adjacent_list.append(adjacent_row[0])
del adjacent_cursor
# 合并图斑
if adjacent_list:
ids = [row[0]] + adjacent_list
arcpy.SelectLayerByAttribute_management(shp, "NEW_SELECTION", " OR ".join(["OBJECTID = " + str(id) for id in ids]))
arcpy.Dissolve_management(shp, output_folder + "\\" + shp[:-4] + "_" + str(row[0]), field_name)
arcpy.SelectLayerByAttribute_management(shp, "CLEAR_SELECTION")
# 删除添加的字段
arcpy.DeleteField_management(shp, "AREA")
```
该脚本的输入参数包括:
- input_folder:包含 shapefile 文件的文件夹路径;
- field_name:用于合并的字段名称;
- output_folder:合并后的文件保存的文件夹路径。
使用该脚本需要先将其作为工具箱添加到 ArcGIS 中,然后在工具箱界面中设置参数并运行即可。
阅读全文