My code creates a raster from a shapefile, but now I have tried to get it to loop through all the shapefiles in a particular folder, but I am still getting an error in the loop. Please can someone take a look?
This is the error I get:
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.")
Your loop should start like this
for shapefile in shapefiles:
ds = ogr.Open(shapefile)
ds_layer = ds.GetLayer()
I renamed it to ds since it will not be a shapefile anymore but a ogr datasource once loaded with ogr.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.