python - 我们如何创建输入栅格的掩码版本,其中落入其中一个字段的像素设置为 ` & 其他为 0?
问题描述
我认为一切都写得很好,但似乎我错过了一些东西。当我试图断言它时,我仍然得到错误的答案。查看代码
def masked_raster(input_file, raster_file):
# Create a masked version of the input raster where pixels falling within one of the fields are set to `1` and pixels outside the fields are set to `0`
with fiona.open(input_file, "r") as shapefile:
geoms = [feature["geometry"] for feature in shapefile]
with rasterio.open(raster_file) as src:
out_img, out_transform = mask(src, geoms, invert = True, crop=False, all_touched= True)
out_meta = src.meta.copy()
out_meta.update({"driver": "GTiff",
"height": out_img.shape[1],
"width": out_img.shape[2],
"transform": out_transform})
return out_img
def reproject_raster(raster_file, dst_crs):
# Reproject the input raster to the provided CRS
with rasterio.open('masked2.tif', "w", **out_meta) as dst:
dst.write(out_image)
dst = src
return dst
要测试我使用的代码:
assert masked_raster('crops.geojson', 'crops.tif')[0].sum() == 1144636.0, "Sorry wrong answer"
assert str(reproject_raster('crops.tif', 'EPSG:4326').crs) == 'EPSG:4326', "Sorry wrong answer"
解决方案
这是一个详细的解决方案,我使用内联注释来回答它
"""
Solution
"""
import fiona
import rasterio
import rasterio.mask
import pycrs
def masked_raster(input_file, raster_file):
# Create a masked version of the input raster where pixels falling within one of the fields are set to `1` and pixels outside the fields are set to `0`
#open the geojson file with fiona
with fiona.open("crops.geojson", "r") as geojson:
#creating features
features = [feature["geometry"] for feature in geojson]
#open raster file with rasterio
with rasterio.open("crops.tif") as src:
#clip the raster with polygon
out_img, out_transform = rasterio.mask.mask(src, features, crop=True)
#copy meta data of the src
out_meta = src.meta.copy()
return out_img
def reproject_raster(raster_file, dst_crs):
# Reproject the input raster to the provided CRS
#import rioxarray module and crs
import rioxarray
from rasterio.crs import CRS
#open raster file ("crops.tif") using rioxaarray
raster_file = rioxarray.open_rasterio(raster_file, masked=True).squeeze()
#create the crs object
crs_wgs84 = CRS.from_string(dst_crs)
raster_4326 = raster_file.rio.set_crs(crs_wgs84)
#convert DataArray to RasterArray to be able to use .crs on the output
dst = raster_4326.rio
return dst
推荐阅读
- azure - Azure 可用性集
- javascript - .find() 多重选择器无法添加道具
- javascript - 无法使用 setState 或 forceUpdate 重新渲染/刷新组件
- jpa - Spring Data 如何使用 org.springframework.data.domain.ExampleMatcher 实现 not/not in/negate
- javascript - JS 地理位置无法正常运行
- node.js - Shelljs exec 在 git cherry-pick 上失败
- javascript - 单击时放大 SVG 并将单击的元素居中在视口中(d3.js)
- laravel - 在 laravel 中扩展的模型中定义主键的别名
- scala - java.lang.RuntimeException:com.datastax.bdp.fs.model.NoSuchFileException:找不到文件:/tmp/hive/
- django - 上下文处理器不适用于 Django 中的 Jinja2