import arcpy
import os
import time
# ======== 用户需修改以下参数 ========
input_folder = r"C:\Path\To\Your\TIFs" # 替换为包含栅格文件的文件夹路径
output_folder = r"C:\Path\To\Output" # 替换为输出文件夹路径
threshold = 0.5 # 分类阈值
# ===================================
def process_raster(input_raster, output_path, threshold):
"""处理单个栅格文件"""
try:
# 使用Con函数进行二值化
out_raster = arcpy.sa.Con(
arcpy.Raster(input_raster) >= threshold,
1,
0
)
# 保存结果
out_raster.save(output_path)
# 验证输出
if not arcpy.Exists(output_path):
raise Exception("输出文件创建失败")
return True
except Exception as e:
arcpy.AddWarning("处理 {} 时出错: {}".format(
os.path.basename(input_raster),
str(e)
))
return False
def main():
try:
start_time = time.time()
# 检查Spatial Analyst扩展许可
if arcpy.CheckExtension("Spatial") == "Available":
arcpy.CheckOutExtension("Spatial")
else:
raise Exception("Spatial Analyst扩展许可不可用")
# 创建输出文件夹(如果不存在)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 设置环境参数
arcpy.env.workspace = input_folder
arcpy.env.overwriteOutput = True
arcpy.env.cellSize = "MAXOF"
arcpy.env.parallelProcessingFactor = "75%" # 使用75%的CPU核心提高效率
# 获取所有栅格文件(支持多种格式)
raster_files = arcpy.ListRasters("*", "ALL")
if not raster_files:
raise Exception("输入文件夹中未找到栅格文件")
arcpy.AddMessage("找到 {} 个栅格文件,开始处理...".format(len(raster_files)))
arcpy.AddMessage("使用阈值: {} 进行二分类".format(threshold))
success_count = 0
processed_count = 0
# 处理每个栅格
for raster in raster_files:
try:
input_path = os.path.join(input_folder, raster)
output_name = "Binary_{}.tif".format(os.path.splitext(raster)[0])
output_path = os.path.join(output_folder, output_name)
processed_count += 1
arcpy.AddMessage("正在处理 {}/{}: {}".format(
processed_count,
len(raster_files),
raster
))
if process_raster(input_path, output_path, threshold):
success_count += 1
except Exception as e:
arcpy.AddWarning("处理 {} 时发生严重错误: {}".format(raster, str(e)))
# 结果汇总
elapsed_time = round(time.time() - start_time, 2)
arcpy.AddMessage("\n处理完成!")
arcpy.AddMessage("成功处理: {}/{} 个文件".format(success_count, len(raster_files)))
arcpy.AddMessage("耗时: {} 秒".format(elapsed_time))
arcpy.AddMessage("输出目录: {}".format(output_folder))
if success_count < len(raster_files):
arcpy.AddWarning("部分文件处理失败,请检查警告信息")
except Exception as e:
arcpy.AddError("程序运行出错: {}".format(str(e)))
finally:
# 释放扩展许可
arcpy.CheckInExtension("Spatial")
arcpy.ResetEnvironments()
if __name__ == "__main__":
main()