栅格化几何示例不起作用

Rasterize Geometry Example not working

我正在尝试重新创建 this rasterio example

import numpy as np
import rasterio
from rasterio.features import rasterize
from rasterio.transform import IDENTITY

rows = cols = 10

geometry = {
    'type': 'Polygon',
    'coordinates': [[(2, 2), (2, 4.25), (4.25, 4.25), (4.25, 2), (2, 2)]]
}


with rasterio.Env():
    result = rasterize([geometry], out_shape=(rows, cols))
    with rasterio.open(
            "test.tif",
            'w',
            driver='GTiff',
            width=cols,
            height=rows,
            count=1,
            dtype=np.uint8,
            nodata=0,
            transform=IDENTITY,
            crs={'init': "EPSG:4326"}) as out:
        out.write(result.astype(np.uint8), indexes=1)

我已经检查了 rasterize (print(result)) 的结果,这看起来很正常,并且会导致 2x2 像素的正方形:

[[0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 1 1 0 0 0 0 0 0]
 [0 0 1 1 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]]

但我得到的是全黑图像(nodata 图像)。

虽然我无法定义黑色 .tif 图像的原因,但我得出的结论是该过程按预期进行,我们可以使用 matplolib.pyplot.

看到视觉结果

示例必须修改如下才能使用pyplot:

import rasterio
from matplotlib import pyplot
from rasterio.features import rasterize
from rasterio.transform import IDENTITY

rows = cols = 10

geometry = {
    'type': 'Polygon',
    'coordinates': [[(2, 2), (2, 4.25), (4.25, 4.25), (4.25, 2), (2, 2)]]
}


with rasterio.Env():
    result = rasterize([geometry], out_shape=(rows, cols))
    with rasterio.open(
            "test.tif",
            'w+', # Open the file in read/write mode
            driver='GTiff',
            width=cols,
            height=rows,
            count=1,
            dtype=rasterio.uint8,
            nodata=0,
            transform=IDENTITY,
            crs={'init': "EPSG:4326"}) as out:
        out.write(result.astype(rasterio.uint8), indexes=1)
        # Plot the image.
        pyplot.imshow(out.read(1))
        pyplot.show()