I have a source raster and an ERSI shape file, want to crop the raster into the circle.
raster = gdal.Open("raster.tif", gdal.GA_ReadOnly) #read raster
projection=raster.GetProjectionRef()
VectorDriver = ogr.GetDriverByName('ESRI Shapefile') #intialize vector
VectorDataset = VectorDriver.Open("boxes.shp", 1)
layer = VectorDataset.GetLayer()
feature=layer[0] #select the first polygon (the circle shown in image)
geom = feature.GetGeometryRef()
minX, maxX, minY, maxY = geom.GetEnvelope()
OutTile = gdal.Warp("cut", raster, format='GTiff', outputBounds=[minX, minY, maxX, maxY],xRes=0.05,yRes=0.05,dstSRS=projection)
But when I plot the OutTile, it shows only the corners of the polygon. I also tried the "cutline" argument, but then it croped the whole raster.
Best Answer
If you create a clipping layer with only the circular feature to use, your code can be simplified in this way (I use my own paths):
On the other hand, you don't need to explicitly read raster or get drivers, datasets or ogr features. You can use creation parameters of resulting raster inside gdal.Warp function.
In my case, involved layers look in Map View of QGIS as follow (but it is not necessary to load them for running script):
After running above script, resulting layer loaded in QGIS looks as expected:
Editing Note:
I added two more features to my original layer:
and after running same script, resulting layer loaded in QGIS is also looking as expected: