【问题标题】:loop error in converting shapefiles to raster for entire folder set将整个文件夹集的 shapefile 转换为栅格时出现循环错误
【发布时间】:2018-12-20 22:03:59
【问题描述】:

我的代码从 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.")

【问题讨论】:

  • 你能调试并找出错误是在哪一行抛出的吗?
  • 你能发布更多的错误信息吗?
  • 我要调试的第一件事是你的 shapefile 列表是否真的只包含 .shp 文件(只需将其打印到控制台)。
  • ... 使用 ogr.Open(shapefiles) 您正在打开一个列表。支持吗?不应该是 ogr.Open(i)。我在这里不是一个好的命名。对于 shapefile 中的 shapefile 会更好。我认为开始循环并打开 shapefile 还没有意义。

标签: python gis raster shapefile


【解决方案1】:

你的循环应该像这样开始

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

我将它重命名为 ds,因为一旦加载了 ogr,它就不再是 shapefile,而是 ogr 数据源。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 2021-05-07
    • 2019-08-27
    • 1970-01-01
    相关资源
    最近更新 更多