空间过滤器(Spatial filters)
使用Spatial Filters
来实现根据空间位置的筛选。
先设置两个shp文件,其中的要素需要相交。
import os
from osgeo import ogr, gdal
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
gdal.SetConfigOption("SHAPE_ENCODING", "UTF8")
driver = ogr.GetDriverByName('ESRI SHAPEFILE')
# 定义两个shp的路径
country_shp_path = 'shp/province_1.shp'
polygon_shp_path = 'shp/province_line.shp'
# 定义两个shp数据集
country_shp = driver.Open(country_shp_path)
polygon_shp = driver.Open(polygon_shp_path)
# 定义两个shp的layer
country_layer = country_shp.GetLayer(0)
polygon_layer = polygon_shp.GetLayer(0)
# print(country_layer.GetFeatureCount()) # 37
# print(polygon_layer.GetFeatureCount()) # 1
# --------------------------------------------------
# --------------------------------------------------
polygon_feats = polygon_layer.GetFeature(0)
polygon_ref = polygon_feats.GetGeometryRef() # 获取当前要素的边界WKT
# 过滤覆盖的要素,并生成图层
country_layer.SetSpatialFilter(polygon_ref)
# --------------------------------------------------
# --------------------------------------------------
# 生成重叠的shp文件,复制图层
output_path = 'shp/demo24_cover.shp'
if os.path.exists(output_path):
driver.DeleteDataSource(output_path)
else:
print('THIS SHP IS NOT EXIST!')
cover_shp = driver.CreateDataSource(output_path)
cover_layer = cover_shp.CopyLayer(country_layer, 'cover')
# 释放内存
cover_shp.Release()
polygon_shp.Release()
country_shp.Release()
-
首先需要获取重叠两个shp文件的图层。
-
获得叠加图层的空间坐标
polygon_ref = polygon_feats.GetGeometryRef()
-
使用函数对原有图层进行筛选
country_layer.SetSpatialFilter(polygon_ref)
,此时的country_layer
是已经被筛选过后的。 -
直接
CopyLayer
这个图层形成新的shp文件。
所有的空间图层操作函数,比如裁剪、擦除、做差等全部是Layer层处理。
SetSpatialFilterRect(<minx>, <miny>, <maxx>, <maxy>)
这个函数可以设定周围四个边界点形成矩形框。
效果和shp筛选一致。
注意:
经过SetSpatialFilter
后的layer
并不是完整的。
若需要对layer
执行其他操作,那么需要将其进行筛选清空。
country_layer.SetSpatialFilter(None)
OGR中使用SQL语句查询
简单的查询使用空间过滤器,复杂的查询则需要使用SQL语句。
以下代码示例,如何从shp文件中查询一个图层。
driver = ogr.GetDriverByName('ESRI SHAPEFILE')
country_shp_path = 'shp/province_1.shp'
country_shp = driver.Open(country_shp_path)
country_layer = country_shp.GetLayer(0)
country_layer_name = country_layer.GetName()
result = country_shp.ExecuteSQL("select * from %s" % country_layer_name)
...
country_shp.ReleaseResultRest(result)
主要的SQL语句:
result = country_shp.ExecuteSQL("select * from %s" % country_layer_name)
在使用完毕查询结果后,需要释放结果。
country_shp.ReleaseResultRest(result)
根据属性条件查询
对图层进行属性查询。
driver = ogr.GetDriverByName('ESRI SHAPEFILE')
country_shp_path = 'shp/province_1.shp'
country_shp = driver.Open(country_shp_path)
country_layer = country_shp.GetLayer(0)
country_layer.SetAttributeFilter("Name = 'Hubei'" )
...
country_shp.ReleaseResultSet(country_layer)
对图层直接使用SetAttributeFilter
函数,输入筛选属性的内容。
在筛选前后用以下方式查看是否选中指定要素。
print(country_layer.GetFeatureCount()) # 37
...
print(country_layer.GetFeatureCount()) # 1