Rasterio – How to Plot RGB Channels Using Rasterio in Python

matplotlibpythonrasterrasteriorgb

When plotting and RGB image using rasterio, I have seen that it is necessary to normalize the values first (0-1) and the use show. I am using the following code for that:

def norm(band):
    band_min, band_max = band.min(), band.max()
    return ((band - band_min)/(band_max - band_min))

b2 = norm(S_images[0].astype(numpy.float))
b3 = norm(S_images[1].astype(numpy.float))
b4 = norm(S_images[2].astype(numpy.float))

# Create RGB
rgb = numpy.dstack((b4,b3,b2))

# Visualize RGB
plt.imshow(rgb)

When reading the rasterio.plot.show documentation, there is a paramter called `adjust'

adjust ('linear' | None) – If the plotted data is an RGB image, adjust
the values of each band so that they fall between 0 and 1 before
plotting. If ‘linear’, values will be adjusted by the min / max of
each band. If None, no adjustment will be applied.

Is this parameter doing the same as my norm function? Does it work only if I load a multi-chanel RGB image or can I use it when providing a np.stack?

Best Answer

Yes you can pass an array. The documentation specifies:

rasterio.plot.show(source, etc...)

Parameters

  • source (array or dataset object opened in 'r' mode or Band or tuple(dataset, bidx))

Yes, it's the same. Demo using rasterio.plot.adjust_band that show uses to do the adjustment:

import rasterio.plot as rp
import numpy as np

def norm(band):
    band_min, band_max = band.min(), band.max()
    return ((band - band_min)/(band_max - band_min))

arr = np.arange(255, dtype=np.float32)
print(np.all(rp.adjust_band(arr) == norm(arr)))

True
Related Question