程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Using Python to realize the vector to cut the grid one by one, and form the grid file corresponding to the map

編輯:Python

In daily work , Requirements for clipping grids using vectors , But in most cases, the grid is cropped based on a complete single vector , Cut the grid without using a patch in the vector , So do the following work .
1、 Split the vector into shp
Here we use the county vector . The code is as follows :

from osgeo import gdal
import osgeo.ogr as ogr
input_shape = r"C:/ classification / County projection .shp"
driver = ogr.GetDriverByName("ESRI Shapefile")
dataSource = driver.Open(input_shape, 1)
layer = dataSource.GetLayer()
print('the length of layer:', len(layer))
for i, feature in enumerate(layer):
# newly build DataSource,Layer
fid = feature.GetField('DISTNAME')# Read the current Feature The attribute value of a field
out_ds = driver.CreateDataSource(fid+".shp")
out_lyr = out_ds.CreateLayer(fid+".shp", layer.GetSpatialRef(), ogr.wkbPolygon)
def_feature = out_lyr.GetLayerDefn()
# Generate Shapefile file
# current_union = layer[0].Clone()
geometry = feature.GetGeometryRef()
current_union = geometry.Clone()
current_union = current_union.Union(geometry).Clone()
out_feature = ogr.Feature(def_feature)
out_feature.SetGeometry(current_union)
out_lyr.ResetReading()
out_lyr.CreateFeature(out_feature)

The effect is as follows , The original is a complete layer , Split into separate layers .
Primitive vector :

Split vector :

2、 Use the split vector to cycle and crop the grid
The mask extraction method used here is used for clipping , Crop irregular ranges , Non circumscribed rectangle .
The code is as follows :

from osgeo import gdal
import osgeo.ogr as ogr
# tif Input path , Open file
input_raster = r"C:/DEM/ slope .tif"
# Grid file path , Open the grid file
input_raster=gdal.Open(input_raster)
# Match file name , You can write and read folder files to replace
name =[' Kaixian ',..........., ' Shizhu Tujia Autonomous County ']
for n in name:
# Start cutting , One line of code
ds = gdal.Warp(n+".tif",# Generated grid
input_raster,
format = 'GTiff',
# Vector files
cutlineDSName = n+".shp",
#cutlineWhere="FIELD = 'whatever'",
dstNodata = 0)

Original grid :

Split the grid :

3、 Grid by grid statistics
Count the corresponding information one by one according to personal needs , What we do here is statistical slope spectrum information entropy .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved