[英]how to mask the specific array data based on the shapefile
http://i4.tietuku.com/84ea2afa5841517a.png
整個區域有40x40的網格網絡,我想提取紫色區域內的數據。 換句話說,我想將管理邊界之外的數據屏蔽到 np.nan 中。
我標記了網格編號,然后將特定的數組數據選擇到 np.nan 中。
http://i4.tietuku.com/523df4783bea00e2.png
value[0,:] = np.nan
value[1,:] = np.nan
.
.
.
.
有人可以告訴我一種更簡單的方法來實現目標嗎?
在這里找到了一個答案,它可以將柵格數據繪制到 shapefile 中,但數據本身不會改變。
我已經在一些答案的啟發下解決了這個問題。
對此目標感興趣的人,請查看我問過的這兩篇文章:
1. 輸入/輸出矢量 shapefile 的測試點
2. 如何使用設置底圖多邊形的剪切路徑
關鍵步驟是測試我已經轉換為 shapely.polygon 的 shapefile 內部/外部的點。
步驟 1. 柵格化 shapefile
創建一個函數,該函數可以確定坐標(x, y)
處的點是否在該區域內。 有關如何將 shapefile 柵格化為與目標蒙版尺寸相同的數組的更多詳細信息,請參見此處
def point_is_in_mask(mask, point):
# this is just pseudocode
return mask.contains(point)
第 2 步。 創建您的面具
mask = np.zeros((height, width))
value = np.zeros((height, width))
for y in range(height):
for x in range(width):
if not point_is_in_mask(mask, (x, y)):
value[y][x] = np.nan
最好是使用matplotlib
:
def outline_to_mask(line, x, y):
"""Create mask from outline contour
Parameters
----------
line: array-like (N, 2)
x, y: 1-D grid coordinates (input for meshgrid)
Returns
-------
mask : 2-D boolean array (True inside)
"""
import matplotlib.path as mplp
mpath = mplp.Path(line)
X, Y = np.meshgrid(x, y)
points = np.array((X.flatten(), Y.flatten())).T
mask = mpath.contains_points(points).reshape(X.shape)
return mask
或者,您可以使用上述答案中建議的shapely
包含方法。 您可以通過遞歸細分空間來加速計算,如本要點所示(但 matplotlib 解決方案在我的測試中快了 1.5 倍):
https://gist.github.com/perrette/a78f99b76aed54b6babf3597e0b331f8
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.