6

I have 3 variables namely R, G, B. I want to make a PNG image based on the three using rasterio. I tried using np.dstack to stack the 3 images and use the result to write it.

Using rasterio, I tried to write it this way:

rgb = np.dstack((Nr,Ng,Nb))  
finame = "Image_RGB.png"
with rasterio.Env():
    with rasterio.open(finame, 'w',
        driver='PNG',
        height=rgb.shape[0],
        width=rgb.shape[1],
        count=1,
        dtype=rgb.dtype,
        nodata=0,
        compress='deflate') as dst:
        dst.write(rgb, 1)

But I get this error:

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

2 Answers 2

6

Two things are going wrong here:

  1. Rasterio is channels first, while you have channels last. In other words, the shape of the rgb should be (3, 830, 793) not (830, 793, 3).
  2. You set count=1 and do dst.write(rgb, 1). This makes it try to write the rgb as the first band of the output file. Instead you want count=3 and dst.write(rgb).

This is a bit late for you, but maybe others will still be helped by my answer.

-1

Based on Arthur's answer and the original code, this is one solution for this issue , the last row should be:

        dst.write(np.rollaxis(rgb, 2,0))
1
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jun 27, 2022 at 0:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.