Write PNG file from a raster using rasterio

pythonraster-conversionrasterio

I have an image, which has 3 bands (RGB). I stack the image using numpy and try to write it as PNG. But I'm confused with how to work with the resulting image indexes.

import rasterio
import numpy as np

with rasterio.open(local_raster, 'r') as ds:
    red = ds.read(2)
    green = ds.read(4)
    blue = ds.read(6)

    rgb = np.dstack((red, green, blue))
    with rasterio.open('data/example_thumb.png', 'w',
            driver='PNG',
            height=rgb.shape[0],
            width=rgb.shape[1],
            count=1,
            dtype='uint8',
            nodata=0,) as dst:
            dst.write(rgb, 1)

I have this error:

ValueError: Source shape (1, 830, 793, 3) is inconsistent 
with given indexes 1

How to properly write the image as PNG using rasterio?

Best Answer

You're trying to write three bands into the first (and only) band of a single band output raster and you need to reshape your rgb array from (rows, cols, bands) to (bands, rows, cols).

You probably want something like:

from rasterio.plot import reshape_as_raster
with rasterio.open('data/example_thumb.png', 'w',
        driver='PNG',
        height=rgb.shape[0],
        width=rgb.shape[1],
        count=3,
        dtype='uint8',
        nodata=0,) as dst:
        dst.write(reshape_as_raster(rgb))

Note that you may need to rescale your rgb data to fit the 0-255 uint8 range.

Related Question