2

I wish to create a Python script that opens a multiband satellite tiff image, then selects the bands the RGB image will be displayed with and then from this point and then I can collect my data from the image. However, I keep getting this error: "TypeError: Invalid shape (3, 1301, 1950) for image data". Note that this error doesn't appear when it is a single band image and the image displays without any problem. What's the matter with my code?

import gdal
import matplotlib.pyplot as plt

# Open the Sentinel-2 image using GDAL
sentinel_ds = gdal.Open(r'C:\Users\GNR\Desktop\file_example_TIFF_10MB (2).tiff')

# Get the band count and band descriptions
band_count = sentinel_ds.RasterCount
band_descriptions = [sentinel_ds.GetRasterBand(i+1).GetDescription() for i in range(band_count)]

# Print the band count and descriptions
print(f'The image has {band_count} bands:')
for i, desc in enumerate(band_descriptions):
    print(f'Band {i+1}: {desc}')

# Select the Red, Green, and Blue bands (bands 4, 3, and 2)
red_band = sentinel_ds.GetRasterBand(4).ReadAsArray()
green_band = sentinel_ds.GetRasterBand(3).ReadAsArray()
blue_band = sentinel_ds.GetRasterBand(2).ReadAsArray()

# Create an RGB image from the bands
rgb_image = plt.imshow([red_band, green_band, blue_band])

# Display the RGB image
plt.show()
2
  • 1
    Which line throws the error? Commented Mar 21, 2023 at 19:51
  • The one I am trying to display the image with, : rgb_image = plt.imshow([red_band, green_band, blue_band]). Commented Mar 21, 2023 at 20:10

1 Answer 1

4

You need to reshape the list as ( width, height, z (bands) ). Currently, it is (bands, width, height). That's why you're getting the error.

import numpy as np

...

bands = np.array([red_band, green_band, blue_band]).transpose(1, 2, 0)

rgb_image = plt.imshow(bands)

plt.show()

Your Answer

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

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