Python – Get Vector Features Inside a Specific Extent

extentsgdalogrpythonsql

The problem:

I have a very large vector layer with many features and a much smaller raster layer in a defined region. I want to get only those vector features which are within the raster layers extent (extent = (xmin,xmax,ymin,ymax) ).

Is there anything like a standard SQL-query (something like SELECT * FROM layer WHERE EXTENT < extent) or another command (some test?) i could use to get only those features that are within a given extent?

EDIT:
Added python code to do a bounding box intersection test for vector features using just gdal and ogr python binding

Best Answer

You don't need a SQL-query to do that, only Python with, once again, the modules Fiona and Shapely of Sean Gillies.

I want only the records which are within the blue frame (analogy of a raster layer).

enter image description here

See the Fiona user Manual, the filter() method returns an iterator over records that intersect a given (minx, miny, maxx, maxy) bounding box:

from shapely.geometry import mapping, shape
import fiona
# Read the original Shapefile
input = fiona.open('data.shp', 'r')
# bounds of the original shapefile
input.bounds
(258018.9133083854, 158162.863836, 268763.670357, 162621.686305)
# clip the shapefile with the raster bounds 
clipped = input.filter(bbox=((262236.3101588468, 159973.80344954136, 263491.7250217228, 160827.485556297)))
# create the clipped shapefile with the same schema
clipped_schema = input.schema.copy()
with fiona.collection('clipped.shp', 'w', 'ESRI Shapefile', clipped_schema) as output:
    for elem in clipped:
           output.write({'properties': elem['properties'],'geometry': mapping(shape(elem['geometry']))})

Result:

enter image description here