Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

-- coding: utf-8 -- import arcpy import os import glob import re import datetime…

  1. User

    -- coding: utf-8 --

    import arcpy import os import glob import re import datetime

    arcpy.CheckOutExtension('Spatial')

    class BatchClip: def init(self, inws, outws, mask): self.inws = inws self.outws = outws self.mask = mask print(self.inws)

    def clip(self):
        if not os.path.exists(self.outws):
            os.mkdir(self.outws)
        rasters = glob.glob(os.path.join(self.inws, ".tif"))
        print(rasters)
        shps = glob.glob(os.path.join(self.mask, ".shp"))
    
    
        for shp in shps:
            for ras in rasters:
                nameT = os.path.basename(ras) + ".tif"
                outname = os.path.join(self.outws, nameT)
                out_extract = arcpy.sa.ExtractByMask(ras, shp)
                out_extract.save(outname)
                print(os.path.basename(ras) + " ---- down")
    
        print(" ----Batchclip down ----")
    

    class RasterReclassify: def init(self, workspace): # Set workspace arcpy.env.workspace = workspace

    def reclassify_rasters(self, index):
        folder = arcpy.env.workspace[-4:]
        folder_name = "reclassify" + folder
        folder_path = os.path.dirname(arcpy.env.workspace)
        output_path = os.path.join(folder_path, folder_name)
    
        if not os.path.exists(output_path):
            os.mkdir(output_path)
        print(output_path)
    
        rasterlist = arcpy.ListRasters("", "tif")
    
        if rasterlist is not None:
            for raster in rasterlist:
                inRaster = arcpy.Raster(raster)
                print(inRaster)
                time = inRaster.name[:8]
                print(time)
                out = os.path.join(output_path, time + "_" + index + ".tif")
                print(out)
    
            if index == "ndvi":
                # NDVI
                outCon = arcpy.sa.Con(inRaster <= 0.19, 1,
                                      arcpy.sa.Con((inRaster > 0.19) & (inRaster <= 0.39), 2,
                                                   arcpy.sa.Con((inRaster > 0.39) & (inRaster <= 0.55), 3,
                                                                arcpy.sa.Con((inRaster > 0.55) & (inRaster <= 0.75), 4,
                                                                             arcpy.sa.Con((inRaster > 0.75), 5)))))
    
            elif index == "gndvi":
                # GNDVI
                outCon = arcpy.sa.Con(inRaster <= 0.2, 1,
                                      arcpy.sa.Con((inRaster > 0.2) & (inRaster <= 0.4), 2,
                                                   arcpy.sa.Con((inRaster > 0.4) & (inRaster <= 0.6), 3,
                                                                arcpy.sa.Con((inRaster > 0.6) & (inRaster <= 0.8), 4,
                                                                             arcpy.sa.Con((inRaster > 0.8), 5)))))
    
            elif index == "vci":
                # VCI
                outCon = arcpy.sa.Con(inRaster <= 0.15, 1,
                                      arcpy.sa.Con((inRaster > 0.15) & (inRaster <= 0.3), 2,
                                                   arcpy.sa.Con((inRaster > 0.3) & (inRaster <= 0.45), 3,
                                                                arcpy.sa.Con((inRaster > 0.45) & (inRaster <= 0.6), 4,
                                                                             arcpy.sa.Con((inRaster > 0.6), 5)))))
    
            elif index == "chlor":
                # Chlor
                outCon = arcpy.sa.Con(inRaster <= 12, 1,
                                      arcpy.sa.Con((inRaster > 12) & (inRaster <= 21), 2,
                                                   arcpy.sa.Con((inRaster > 21) & (inRaster <= 32), 3,
                                                                arcpy.sa.Con((inRaster > 32) & (inRaster <= 43), 4,
                                                                             arcpy.sa.Con((inRaster > 43), 5)))))
    
            outCon.save(out)
    

    print("---raclassify down---")

    class RasterToPolygonConverter: def init(self, input_raster_path, output_shp_path): self.input_raster_path = input_raster_path self.output_shp_path = output_shp_path

    def convert_raster_to_polygon(self):
        # Set workspace
        arcpy.env.workspace = self.input_raster_path
        
        # Create output folder if it doesn’t exist
        if not os.path.exists(self.output_shp_path):
            os.mkdir(self.output_shp_path)
    
        # List raster files
        rasters = arcpy.ListRasters("", "tif")
        for raster in rasters:
            # Extract catchment name from raster filename
            catchment_name = raster[:8]
            print(catchment_name)
    
            # Set output shapefile path
            shp_out_name = os.path.join(self.output_shp_path, catchment_name)
            print(shp_out_name)
    
            # Convert raster to polygon
            arcpy.RasterToPolygon_conversion(raster, shp_out_name, "true", "Value")
            print("finished")
    

    print("---polygon down---")

    class Dissolve: def init(self): pass

    def dissolve_shapefiles(self, input_workspace, output_workspace):
        arcpy.env.workspace = input_workspace
        shps = arcpy.ListFiles("*.shp")
        
        if shps is not None:
            for shp in shps:
                catchment_name = shp[:8]
                shp_out_name = os.path.join(output_workspace, catchment_name)
    
                arcpy.Dissolve_management(shp, shp_out_name, "gridcode")
                print("Finished dissolving", catchment_name)
    

    class FieldCalculator: def init(self, input_polygon): self.input_polygon = input_polygon

    def calculate_fields(self):
        current_year = datetime.datetime.now().year
        if not os.path.exists(self.input_polygon):
            return
    
        path_list = os.listdir(self.input_polygon)
    
        for i in range(len(path_list)):
            landid = path_list[i][-4:]
            print(landid)
    
            path = os.path.join(self.input_polygon, path_list[i])
            shps = glob.glob(os.path.join(path, "*.shp"))
    
            for shp in shps:
                print(shp)
                catchment_name = shp[-12:-4]
    
                print(catchment_name)
    
                date = int(catchment_name)
    
                # arcpy.DeleteField_management(shp, [“LandId”])
    
                field_names = [f.name for f in arcpy.ListFields(shp)]
    
                if 'date' not in field_names:
                    arcpy.AddField_management(shp, 'date', 'Long')
                    arcpy.CalculateField_management(shp, 'date', expression=date, expression_type="python", code_block="")
    
                if 'landId' not in field_names:
                    arcpy.AddField_management(shp, 'landId', 'Short’')
                    arcpy.CalculateField_management(shp, 'landId', 0, expression_type="python")
    
                if 'landName' not in field_names:
                    arcpy.AddField_management(shp, 'landName', 'TEXT')
    
                if 'crop' not in field_names:
                    arcpy.AddField_management(shp, 'crop', 'TEXT')
    
                if 'Area' not in field_names:
                    arcpy.AddField_management(shp, 'Area', 'Double')
    
                if 'Area_mu' not in field_names:
                    arcpy.AddField_management(shp, 'Area_mu', 'Double')
    
                if 'year' not in field_names:
                    arcpy.AddField_management(shp, 'year', 'Double')
                arcpy.CalculateField_management(shp, 'year', current_year, expression_type="python")
    

    print("---dbf down---") def main(): # Set input and output paths inws = r"F:\GEE\wurenlongchang\tif\wurenlongchang_GDVI" outws = r"F:\GEE\wurenlongchang" mask = r"F:\GEE\wurenlongchang\1_shp"

    # Batch clip rasters
    batch_clip = BatchClip(inws, outws, mask)
    batch_clip.clip()
    
    # Reclassify rasters
    reclassify_workspace = os.path.join(outws, "ndvi")
    rr = RasterReclassify(reclassify_workspace)
    rr.reclassify_rasters("ndvi")
    rr.reclassify_rasters("gndvi")
    # rr.reclassify_rasters("vci")
    rr.reclassify_rasters("chlor")
    
    # Convert rasters to polygons
    polygon_workspace = os.path.join(outws, "reclassifyndvi")
    folder = polygon_workspace[-4:]
    folder_name = "polygon" + folder
    output_polygon_path = os.path.join(outws, folder_name)
    converter = RasterToPolygonConverter(polygon_workspace, output_polygon_path)
    converter.convert_raster_to_polygon()
    
    # Dissolve polygons
    dissolve_workspace = os.path.join(outws, "polygonndvi")
    folder = dissolve_workspace[-4:]
    folder_name = "dissolve" + folder
    output_dissolve_path = os.path.join(outws, folder_name)
    dissolve = Dissolve()
    dissolve.dissolve_shapefiles(reclassify_workspace, output_dissolve_path)
    
    # Calculate fields
    field_calculator = FieldCalculator(output_dissolve_path)
    field_calculator.calculate_fields()
    

    if name == "main": main() 如何读取inws中的文件

  2. Assistant

    要读取inws中的文件,可以使用glob模块的glob函数来获取所有指定类型的文件路径。在BatchClip类的clip方法中添加以下代码:

    def clip(self):
        if not os.path.exists(self.outws):
            os.mkdir(self.outws)
        rasters = glob.glob(os.path.join(self.inws, "*.tif"))
        print(rasters)
        shps = glob.glob(os.path.join(self.mask, "*.shp"))
    
        for shp in shps:
            for ras in rasters:
                nameT = os.path.basename(ras) + ".tif"
                outname = os.path.join(self.outws, nameT)
                out_extract = arcpy.sa.ExtractByMask(ras, shp)
                out_extract.save(outname)
                print(os.path.basename(ras) + " ---- down")
    
        print(" ----Batchclip down ----")
    

    在clip方法中,使用glob.glob函数来获取inws路径下所有以".tif"结尾的文件路径。

  3. User

    print(rasters)无结果怎么弄

  4. Assistant

    如果print(rasters)没有结果输出,可能是因为inws路径下没有以".tif"结尾的文件。请确保inws路径下存在要处理的文件,并且文件的格式是正确的。

    另外,你也可以添加一些调试相关的输出信息,来查看代码的执行情况。例如,在BatchClip类的__init__方法中,添加以下代码:

    print("Input workspace:", self.inws)
    

    这样,在初始化BatchClip类的时候,就会打印出inws的值,以确认输入路径是否正确。

  5. User

    arcgisscripting.ExecuteError: Failed to execute. Parameters are not valid. ERROR 000964: Specified extent is invalid Failed to execute (ExtractByMask).

  6. Assistant

    根据报错信息说明,ExtractByMask工具中指定的范围无效。这可能是因为传递给该工具的栅格数据和矢量数据存在不匹配的空间参考或范围。请确保要素类(shp文件)和栅格数据具有相同的空间参考,且空间参考正确。

    解决此问题的方法是确保要素类和栅格数据使用相同的空间参考(投影)和坐标系。你可以尝试使用arcpy.Describe函数来获取inws中第一个栅格数据和矢量数据的空间参考,然后进行比较。例如:

    desc_raster = arcpy.Describe(rasters[0])
    desc_shp = arcpy.Describe(shps[0])
    
    if desc_raster.spatialReference.name != desc_shp.spatialReference.name:
        print("Spatial references do not match: {} and {}".format(desc_raster.spatialReference.name, desc_shp.spatialReference.name))
        # 进行空间参考匹配操作,参考arcpy的空间参考匹配方法
    else:
        print("Spatial references match!")
    

    根据提示的空间参考不匹配的情况,可以使用适当的空间参考匹配工具来确保栅格数据和矢量数据具有相同的空间参考。

  7. User

    去除文件路径只提取文件名

  8. Assistant

    要从文件路径中提取文件名,你可以使用os.path.basename()函数。这个函数可以接收一个路径作为参数,并返回路径中的最后一个目录或文件。

    在你的代码中,需要对os.path.basename()函数进行一些修改。首先,在clip()方法中的for循环中添加以下代码:

    for shp in shps:
        shp_name = os.path.basename(shp)
        for ras in rasters:
            ras_name = os.path.basename(ras)
            nameT = ras_name + ".tif"
            outname = os.path.join(self.outws, nameT)
            out_extract = arcpy.sa.ExtractByMask(ras, shp)
            out_extract.save(outname)
            print(ras_name + " ---- down")
    

    这样,shp_name和ras_name变量将分别保存shp和ras的文件名,然后在print语句中使用它们。这样就可以只打印文件名,而不是整个文件路径。

  9. User

    RuntimeError: ERROR 000872: Output Raster: Dataset F:\GEE\wurenlongchang\mask_GDVI3156_20230806.tif already exists and cannot be overwritten since the Overwrite existing datasets option is disabled.

  10. Assistant

    根据报错信息提供的内容可以看出,输出的栅格数据已经存在并且禁止覆盖现有数据,这是因为覆盖现有数据的选项被禁用了。

    要解决这个问题,有两种方法:

    1. 开启覆盖现有数据的选项: 在代码的开头,添加以下语句来启用覆盖现有数据的选项:

      arcpy.env.overwriteOutput = True
      
    2. 修改输出栅格数据的文件名: 在 clip() 方法中你可以修改输出栅格数据的文件名,使其与已有的数据文件名不重复。例如,你可以在以下位置修改代码:

      for shp in shps:
          shp_name = os.path.basename(shp)
          for ras in rasters:
              ras_name = os.path.basename(ras)
              nameT = ras_name + "_" + shp_name + ".tif"  # 修改输出文件名
              outname = os.path.join(self.outws, nameT)
              out_extract = arcpy.sa.ExtractByMask(ras, shp)
              out_extract.save(outname)
              print(ras_name + " ---- down")
      

    这样,输出的栅格数据文件名将包括原始文件名和shp文件名,确保了不会与已有的数据文件重复。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.