简介
客户要求用python编写一个工具
1、支持输入条件筛选镶嵌数据集
2、按照行政区进行裁切
3、对裁切之后的影像压缩打包
解题思路
1、连接sde数据库
GeoScene Pro 或者ArcGIS Pro 软件可以直接连接sde数据库,会在本地创建链接文件,可以直接使用
arcpy.env.workspace = "C:/Users/admin/Documents/GeoScene/Projects/project/localhost.sde"
2、获取想要裁切的镶嵌数据集
arcpy.ListDatasets("*2013*", "Mosaic")
3、arcpy裁切栅格的函数有很多,这里我使用的是 SplitRaster 分割栅格 ,分割函数十分稳定,裁切之后影像颜色和未裁切时相同,源栅格的大部分属性都会保留。
具体用法可以查看官方文档:分割函数
arcpy.management.SplitRaster(in_raster, tif_path, timestamp, "POLYGON_FEATURES", "TIFF", "NEAREST", "1 1", "2048 2048", 0, "PIXELS", None, None, in_template_dataset, "NONE", "DEFAULT", '')
需要注意SplitRaster函数用于分割栅格数据集的要素类为图层文件,需要创建shp文件保存到个人文件数据库也就是gdb里,存放到文件夹是会报错滴!!!!!
4、压缩打包
使用的shutil里的make_archive
shutil.make_archive(zip_path, f'{fm}', besave_dir)
整体代码
import arcpy
import os
import shutil
import time
def creatFolder(path):
if os.path.exists(path):
del_files(path)
else:
os.mkdir(path)
def compressed(besave_dir, fm,zip_path):
if os.path.exists(besave_dir):
zip_name = shutil.make_archive(zip_path, f'{fm}', besave_dir)
print(zip_name) # 返回文件的最终路径
def del_files(dir_path):
for root, dirs, files in os.walk(dir_path, topdown=False):
# 第一步:删除文件
for name in files:
os.remove(os.path.join(root, name)) # 删除文件
# 第二步:删除空文件夹
for name in dirs:
os.rmdir(os.path.join(root, name)) # 删除一个空目录
def init(clip_path,tif_path,zip_path,in_raster,points):
timestamp = int(time.time() * 1000)
arcpy.CreateFileGDB_management(clip_path, "temporary.gdb")
temporary = clip_path+"/temporary.gdb"
ring = arcpy.Array([arcpy.Point(*p) for p in points])
features = []
features.append(arcpy.Polygon(ring))
arcpy.CopyFeatures_management(features, temporary+"/ce.shp")
in_template_dataset = temporary+'/shp'
arcpy.management.SplitRaster(in_raster, tif_path, timestamp, "POLYGON_FEATURES", "TIFF", "NEAREST", "1 1","2048 2048", 0, "PIXELS", None, None, in_template_dataset, "NONE", "DEFAULT", '')
zip_path_name = zip_path + str(timestamp) # 压缩后的文件名
compressed(tif_path, "zip", zip_path_name)
del_files(tif_path)
if __name__ == "__main__":
arcpy.env.workspace = "C:/Users/admin/Documents/GeoScene/Projects/project/localhost.sde"
clip_path = "D:/dateba"
tif_path = "D:/tif"
zip_path = "D:/download"
creatFolder(clip_path)
creatFolder(tif_path)
judge = '2013'
mosaic_datasets = arcpy.ListDatasets("*2013*", "Mosaic")
points = [
[
11058714.772300001,
3128925.2192000002
],
[
11178716.530499998,
3152019.2776999995
],
[
11203160.599300001,
3018088.5518000014
],
[
11216132.921399999,
2855393.9120999984
],
[
11020241.0812,
2881538.5130000003
],
[
11004980.439300001,
2988313.4239000008
],
[
11058714.772300001,
3128925.2192000002
]
]
init(clip_path,tif_path,zip_path,mosaic_datasets ,points)