????????不多說,這是之前項目需求的代碼,已經是去年的了一直沒來的及發,今天抽出來一丟丟的空擋發一下。主要就是利用線矢量等距離生成點矢量,或者直接將線矢量等分生成點矢量,這個需求其實極限一下就是線轉點了(將距離設置小一點)。順便將點生成矩形面的代碼也給出來,這里的矩形就直接中心點往外擴的固定距離,可以按自己的需求修改。
1.線等分取點代碼
? ? ? ? 這里注意一下,我是提前知道的了線段的長度,所以可以直接用num_points = int(length/150) + 1 取到我希望的間距,這個代碼是用來等分線段的,但是你計算好后也可以實現等距離!
# -*- coding: utf-8 -*-
"""
@Time : 2024/11/22 17:10
@Auth : RS迷途小書童
@File :Vector Line Select Points.py
@IDE :PyCharm
@Purpose:線矢量數據等距離取點/線等分取點,另加入點創建矢量面代碼
@Web:博客地址:https://blog.csdn.net/m0_56729804
"""
import numpy as np
import geopandas as gpd
from shapely import geometry
from shapely.geometry import Point, LineString, Polygondef create_point(folder_path): # 線矢量等距離取點""":param folder_path: 輸入需要等分的矢量線文件:return: None"""# shp_files = [f for f in os.listdir(folder_path) if f.endswith('.shp')]# os.mkdir(r"Dom_clip/%s" % files[:2])gdf = gpd.read_file(folder_path) # 讀取shp文件lines = gdf[gdf.geometry.type == 'LineString'] # 選擇線要素line = LineString(lines.geometry.values[0].coords) # 提取線的坐標并轉換為LineString對象length = line.length # 計算線的長度print("當前線矢量長度為:", length)num_points = int(length/150) + 1 # 設定你想要等分的點數distances = np.linspace(0, length, num_points)points = line.interpolate(distances) # 計算等距點的坐標for point in points: # 打印點的坐標print(point.x, point.y)number = 1 # 創建面的編號create_shp(point.x, point.y, number) # 調用創建面的函數number += 1 # 創建面的編號
2.點創建面矩形代碼
? ? ? ? 我這里直接是從上一步獲得的中心點上下左右同時外擴獲取的,你們可以按照需求來。
# -*- coding: utf-8 -*-
"""
@Time : 2024/11/22 17:10
@Auth : RS迷途小書童
@File :Vector Line Select Points.py
@IDE :PyCharm
@Purpose:線矢量數據等距離取點/線等分取點,另加入點創建矢量面代碼
@Web:博客地址:https://blog.csdn.net/m0_56729804
"""
import numpy as np
import geopandas as gpd
from shapely import geometry
from shapely.geometry import Point, LineString, Polygondef create_shp(x, y, number1): # 創建面shp""":param x: 輸入面矢量中心點x:param y: 輸入面矢量中心點y:param number1: 保存新矢量的編號:return: None"""distance = 78 # 矩形的大小shp = gpd.GeoSeries([geometry.Polygon([(x - distance, y + distance), (x + distance, y + distance),(x + distance, y - distance), (x - distance, y - distance)])],crs='EPSG:32651') # 指定坐標系為WGS84/UTM 51N# 左上、右上、左下、右下 32651右&上為正shp.to_file(r'彭俊喜/%s.shp' % number1, driver='ESRI Shapefile', encoding='utf-8')# 導出數據為shapefile文件
3.總結
? ? ? ? 上面兩個程序是可以組合到一起的,實現線等距離取點,用點生成矩形。只要懂點代碼知識稍微改改即可。我會不定期地在博客上分享一些自己在進行RS、GIS工作時使用到的代碼以及學習經驗。如果大家感興趣可以點個關注,有什么問題可以評論或者私信!