python - 如何从 rasterio python 中的巨大 .tif 文件中获取掩码?
问题描述
我有一个大 (~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.mask
使用with ,但是在大文件上花费的时间太长了。(约 50 秒)crop=True
# 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
请注意,我只掩盖了一种形状,而不是全部。
推荐阅读
- php - 如何在phtml中创建垂直文本
- php - PHP & MySQL:如何将用户输入与数据库中的数据进行比较?
- python - Python。将字符串转换为包含 numpy 数组的字典
- python - 如何使用 lambda 和 map_fn 在 4d 张量的每个 2d 切片上应用 keras 层?
- mysql - 从远程服务器获取数据库并在本地部署的脚本
- python - Azure git 如何使 Python 脚本无缓冲
- visual-studio - Visual Studio 2019 中的延迟自动编译
- python - 从网页投资下载数据的问题
- postgresql - Postgres 游标中的获取限制
- c# - Letsencrypt Stage PEM 与 fszlin/certes