将shapefile转换为整个文件夹集的栅格时出现循环错误

问题描述 投票:0回答:1

我的代码从shapefile创建一个栅格,但现在我试图让它循环遍历特定文件夹中的所有shapefile,但我仍然在循环中收到错误。有人可以看看吗?

这是我得到的错误:

RuntimeError: not a string.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 14 14:17:53 2018

@author: me
"""
from osgeo import ogr, gdal
import subprocess
import os 

#change directory
os.chdir('/Users/SpatialDataET')

#Name of folder containing all shapefiles to be transformed
folder = 'region_shapes'
#Accesses all shapefiles in the folder (even if there are 100 or 1000 shapefiles)
shapefiles = [folder + '/' + file for file in os.listdir(folder) if 'shp' in file]

#creates object/folder for storing rasterized version (fills in later)
OutputImages = 'Imagefolder'

#Create an output directory (puts the new geotiffs into a separate folder) if none exists 
if not os.path.exists(OutputImages):
    os.mkdir(OutputImages)

#reference with which to grab resolution (x/y spacing, projection and geotransformation)
RefImage = '/Users/ETa_CMRSET_mm-month-1_monthly_2000.01.01.tif'
gdalformat = 'GTiff'
datatype = gdal.GDT_Byte
burnVal = 1 #value for the output image pixels

# Get projection info from reference image
Image = gdal.Open(RefImage, gdal.GA_ReadOnly)

for i in shapefiles:
    shapefiles[i][-9:-3] = ogr.Open(shapefiles)
    Shapefile_layer = Shapefile.GetLayer()

    # Rasterize
    print("Rasterising shapefile...")
    Output = gdal.GetDriverByName(gdalformat).Create(OutputImages, Image.RasterXSize, Image.RasterYSize, 1, datatype, options=['COMPRESS=DEFLATE'])
    Output.SetProjection(Image.GetProjectionRef())
    Output.SetGeoTransform(Image.GetGeoTransform()) 

    # Write data to band 1
    Band = Output.GetRasterBand(1)
    Band.SetNoDataValue(0)
    gdal.RasterizeLayer(Output, [1], Shapefile_layer, burn_values=[burnVal])

    # Close datasets
    Band = None
    Output = None
    Image = None
    Shapefile = None

    # Build image overviews
    subprocess.call("gdaladdo --config COMPRESS_OVERVIEW DEFLATE "+OutputImages+" 2 4 8 16 32 64", shell=True)

print("Done.")
python gis raster shapefile
1个回答
0
投票

你的循环应该像这样开始

for shapefile in shapefiles:
   ds = ogr.Open(shapefile)
   ds_layer = ds.GetLayer()

我将它重命名为ds,因为它不再是shapefile,而是一个用ogr加载的ogr数据源。

© www.soinside.com 2019 - 2024. All rights reserved.