簡體   English   中英

如何從光柵 python 中的巨大 .tif 文件中獲取掩碼?

[英]How to get mask from a huge .tif file in rasterio python?

我有一個大 (~3GB) 的 .tif 文件,其中嵌入了地理信息。
我有一些多邊形(由 GPS 坐標表示)保存在 .shp 文件中,這些文件描述了我感興趣的圖像中的特定區域。

我想獲得每個多邊形所指的圖像的裁剪,以及該裁剪上多邊形的蒙版。

我可以根據多邊形的邊界框讀取窗口,
但后來我無法匹配從 rasterio.read 函數創建的 numpy 數組內的多邊形:

from math import ceil
import rasterio
import fiona

with fiona.open("shapes.shp", "r") as shapefile:
    shapes = [feature["geometry"] for feature in shapefile]

tif_fn = 'large_file.tif'
my_tif = rasterio.open(tif_fn)

bound_1 = rasterio.features.bounds(shapes[0])
bbox_1 = rasterio.windows.from_bounds(*bound_1, my_tif.transform)
window_transform1 = rasterio.windows.transform(window=bbox_1, transform=my_tif.transform)
mask = rasterio.features.geometry_mask([shapes[0]],out_shape=(ceil(bbox_1.width), ceil(bbox_1.height)), 
                                       transform=window_transform, invert=True)
img_crop = my_tif.read([1,2,3], window=bbox_1) # pretty fast, ~2 seconds

plt.imshow(img_crop)
plt.imshow(mask,alpha=0.2)
plt.show() # bad match of image and mask... 

我已經嘗試根據本教程rasterio.mask.maskcrop=True一起使用,但是在大文件上花費的時間太長。 (~50 秒)

# takes 50 seconds...
out_image, out_transform = rasterio.mask.mask(my_tif, shapes, crop=True, filled=True) 
out_meta = rsrc.meta

有沒有辦法制作一個子數據集對象並從中獲取掩碼?
或者一種將裁剪和蒙版放在一起的方法?

謝謝!

第一個選項只是固定的,只需使用裁剪的圖像形狀作為蒙版:

img_crop = my_tif.read([1,2,3], window=bbox_1) # pretty fast, ~2 seconds
mask = rasterio.features.geometry_mask([shapes[0]],out_shape=(img_crop.shape[1], img_crop.shape[2]), 
                                       transform=window_transform1, invert=True)

rasterio.mask.mask的問題在於我試圖為我的所有形狀制作一個面具,而不是為每個形狀制作一個面具。 我需要像這樣更改代碼:

# takes 6 seconds, way better.
out_image, out_transform = rasterio.mask.mask(my_tif, [shapes[0]], crop=True, filled=True) 
out_meta = rsrc.meta
original_image_cropped = my_tif.read([1,2,3], window=bbox_1)
plt.imshow(original_image[[0,1,2]])
plt.imshow(out_image[0], alpha=0.2)
plt.show()

# out_image is the crop, and read 

請注意,我只屏蔽了一種形狀,而不是所有形狀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM