1 Star 1 Fork 0

Haixu He/shapefile文件裁剪tif文件

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
ChoosePoint.py 2.89 KB
一键复制 编辑 原始数据 按行查看 历史
Haixu He 提交于 2022-08-12 02:37 . update ChoosePoint.py.
# Author:hhx
# Date:2022/8/12 10:14
# Description:在多个面属性的shp文件里面选点,判断是否在shp内
import shapefile
from shapely import geometry
import pandas as pd
from mpl_toolkits.basemap import Basemap
import matplotlib
import numpy as np
import pylab as plt
from osgeo import osr
from tqdm import tqdm
def CreatePolygonz(points):
"""创建面文件:points为一个列表;返回面文件读取信息"""
outshp = 'temp/temp.shp'
w = shapefile.Writer(outshp) # 注意,这里的参数不可以是shapeType = 5,必须是文件路径,否则会报错
# 设置字段,最大长度为254,C为字符串
w.field('FIRST_FLD')
w.field('SECOND_FLD', 'C', '40')
w.poly([points])
w.record('First', 'Point')
# 保存
w.close()
# 设置投影,通过.prj文件设置,需要写入一个wkt字符串
##gdal的GetProjection()返回的是wkt字符串,需要ImportFromWkt
# projstr="""PROJCS["WGS_1984_UTM_zone_50N",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32650"]]'"""
proj = osr.SpatialReference()
proj.ImportFromEPSG(4326)
# 或 proj.ImportFromProj4(proj4str)等其他的来源
wkt = proj.ExportToWkt()
# 写出prj文件
f = open(outshp.replace(".shp", ".prj"), 'w')
f.write(wkt)
f.close()
shp = shapefile.Reader(outshp)
return shp
if __name__ == '__main__':
# 取得深圳的shape
sz_shp = shapefile.Reader(r'shp/水体')
shapes = sz_shp.shapes()
print('共计{}个面要素'.format(len(shapes)))
in_shape_points = []
for index in tqdm(range(len(shapes))):
geo = shapes[index]
new_shp = CreatePolygonz(geo.points)
lon_0, lat_0, lon_1, lat_1 = new_shp.bbox
linear_lon = np.linspace(lon_0, lon_1, 50) # 经向50个点
linear_lat = np.linspace(lat_0, lat_1, 25) # 纬向25个点
grid_lon, grid_lat = np.meshgrid(linear_lon, linear_lat) # 构成了一个坐标矩阵,实际上也就是一个网格,两者是同型矩阵
flat_lon = grid_lon.flatten() # 将坐标展成一维
flat_lat = grid_lat.flatten()
flat_points = np.column_stack((flat_lon, flat_lat))
in_shape_points = []
for pt in flat_points:
# make a point and see if it's in the polygon
if geometry.Point(pt).within(geometry.shape(shapes)):
in_shape_points.append(pt)
selected_lon = [elem[0] for elem in in_shape_points]
selected_lat = [elem[1] for elem in in_shape_points]
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/HaixuHe/shapefile-clipping-tif-file.git
git@gitee.com:HaixuHe/shapefile-clipping-tif-file.git
HaixuHe
shapefile-clipping-tif-file
shapefile文件裁剪tif文件
master

搜索帮助