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

标签: pythondatabasemachine-learningarcgis

解决方案


这是一个详细的解决方案,我使用内联注释来回答它

"""
    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

推荐阅读