A histogram stretch operation does exactly what its name says. It redistributes the pixel values across the whole scale. By doing so, we have more values at the higher-intensity level and the image becomes brighter. So, in this example, we'll reuse our histogram function, but we'll add another function called stretch() that takes an image array, creates the histogram, and then spreads out the range of values for each band. We'll run these functions on swap.tif and save the result in an image called stretched.tif:
import gdal_array
import operator
from functools import reduce
def histogram(a, bins=list(range(0, 256))):
fa = a.flat
n = gdal_array.numpy.searchsorted(gdal_array.numpy.sort(fa), bins)
n = gdal_array.numpy.concatenate([n, [len(fa)]])
hist = n[1:]-n[:-1]
return hist
def stretch(a):
"""
Performs a histogram stretch...