gdal的绘制大致直方图是仅查看概览或者抽样像素的一个子集
import os
from osgeo import gdal
import matplotlib.pyplot as plt
import numpy as np
# Don't forget to change directory.
os.chdir(r'D:\DeskTop\learn_py_must\Learn_GDAL\osgeopy-data\osgeopy-data\Switzerland')
ds = gdal.Open('dem_class2.tif')
band = ds.GetRasterBand(1)
# 获取直方图数据
approximate_hist = band.GetHistogram()
exact_hist = band.GetHistogram(approx_ok=False)
for i in range(len(approximate_hist[1:6])):
print(i)
print(approximate_hist[i+1:i+2])
print(exact_hist[i+1:i+2])
x = np.arange(len((approximate_hist[1:6]))) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2-0.05, approximate_hist[1:6], width, label='Approximate Histogram')
rects2 = ax.bar(x + width/2+0.05, exact_hist[1:6], width, label='Exact Histogram')
plt.xlabel('Pixel Value')
plt.ylabel('Frequency')
plt.title('Raster Histogram')
plt.legend()
plt.show()
# # 将数据转换为列表以便绘制
# bins = [i+1 for i in range(len(approximate_hist[1:6]))]
# plt.figure(figsize=(10, 5))
# plt.bar(bins, approximate_hist[1:6], alpha=0.5, color='b', label='Approximate Histogram')
# plt.bar(bins, exact_hist[1:6], alpha=0.5, color='r', label='Exact Histogram')
#
# plt.xlabel('Pixel Value')
# plt.ylabel('Frequency')
# plt.title('Raster Histogram')
# plt.legend()
# plt.show()
结果