I am working both with QGIS and GDAL lib in python. I've clipped a scence from QGIS and exported it as TIF format.
I've tried something to read the histogram of this image:
dataset = gdal.Open("/content/drive/MyDrive/work/6539633101/ClippedDup.tif")
num_bands = dataset.RasterCount
for i in range(1, num_bands+1):
band = dataset.GetRasterBand(i)
hist = band.GetHistogram()
print(f"Histogram of Band {i}: {hist}")
I got the histogram like this.
Image
What should I do
What do you expect to happen? The data you use doesn't contain any values within the valid range of the histogram you request. You can include those by setting:
hist = band.GetHistogram(include_out_of_range=True)
That will put all values in the very last bin, as expected.
You should probably either scale the data, or set the range/bins you want for the histogram, if the current result isn't what you want. See the documentation for all available options:
https://gdal.org/doxygen/classGDALRasterBand.html#aa21dcb3609bff012e8f217ebb7c81953
Alternatively, you can read the data and use something like Numpy (np.histogram
) to calculate the histogram.
You can test this for example with something like:
from osgeo import gdal
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8,3), facecolor="w")
vmin = 200
vmax = 1400
n_bins = 50
step = int((vmax-vmin)/n_bins)
ds = gdal.Open("/content/drive/MyDrive/work/6539633101/ClippedDup.tif")
num_bands = ds.RasterCount
for i in range(1, num_bands+1):
band = ds.GetRasterBand(i)
hist = band.GetHistogram(min=vmin, max=vmax, buckets=n_bins, include_out_of_range=True)
ax.step(range(vmin, vmax, step), hist, label=f"Band {i}")
ax.legend()