微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我们如何创建输入栅格的掩码版本,其中落入其中一个字段的像素设置为 ` & 其他设置为 0?

如何解决我们如何创建输入栅格的掩码版本,其中落入其中一个字段的像素设置为 ` & 其他设置为 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。