I am trying to clip a shapefile (containing multiple polygons) to a raster's extent. A similar question was asked as Clipping polygon precisely to raster (extent) using GDAL?, with an answer that I have not been able to effectively use. In my case, I have a large raster file that contains one shapefile which holds over 6000 polygons. I split my raster up into equal segments (600x600). I want to also split the polygons up into their respective new .tif
file.
The code below does run without any errors though it saves over each shapefile that is saved. So my variable i
is not increasing. When I import the shapefile into QGIS it loads correctly, but has no data. So it is a blank shapefile. If I zoom to layer, it does not zoom. So I am not sure what is going on.
Any suggestions?
import gdal
import subprocess
import os
# define file paths
Ras_path = 'D:/images/'
i = 0
for Raster in os.listdir('D:/images/'):
src = gdal.Open(Ras_path + Raster)
ulx, xres, xskew, uly, yskew, yres = src.GetGeoTransform()
sizeX = src.RasterXSize * xres
sizeY = src.RasterYSize * yres
lrx = ulx + sizeX
lry = uly + sizeY
src = None
extent = '{0} {1} {2} {3}'.format(ulx, lry, lrx, uly);
#i = 0
inVectorPath = 'D:/data/shape_merge/compiled.shp'
outVectorPath = 'D:/data/split_shape/' + str(i) + '.shp'
i = i + 1
# make clip command with ogr2ogr - default to shapefile format
cmd = 'ogr2ogr ' + outVectorPath + ' ' + inVectorPath + ' -clipsrc ' + extent
# call the command
subprocess.call(cmd, shell=True)
As @mikewatt commented, I did have my i = 0
inside my loop so it wasn't incrementing correctly. After the fix I am running into an error:
ERROR 1: Failed to create file D:/data/split_shape\103.shp: No such file or directory
ERROR 1: Terminating translation prematurely after failed
translation of layer compiled (use -skipfailures to skip errors)
i
to zero on every iteration, hence why it's not incrementing on every iteration-skipfailures
to my code? :gis.stackexchange.com/questions/103161/… Though, I am not sure where to input this???cmd
line to:cmd = 'ogr2ogr ' + outVectorPath + ' ' + inVectorPath + ' -clipsrc ' + extent + ' ' + ' -skipfailures '