函数:
numpy.histogram(a, bins=10, range=None, normed=None, weights=None, density=None)
参数说明:
返回:
(length(hist)+1)
?。代码示例:
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读取图像
image = cv2.imread(r"D:\Desktop\00aa\1.png", 0)
# 统计灰度值分布
hist, bins = np.histogram(image.flatten(), bins=range(256))
# 绘制直方图
plt.figure(figsize=(10, 6))
plt.bar(bins[:-1], hist, width=1, color='gray')
plt.xlabel('Gray Level')
plt.ylabel('Pixel Count')
plt.title('Gray Level Histogram')
plt.show()
我们也可以用OpenCv方法:
cv2.calcHist(images, channels, mask, histSize, ranges)
参数:
代码示例:
import cv2 as cv
import matplotlib.pyplot as plt
src = cv.imread(r"D:\Desktop\00aa\1.png", 0) # 直接以灰度图方式读入
img = src.copy()
# 统计灰度图
greyScale_map = cv.calcHist([img], [0], None, [256], [0, 256]).squeeze()
# 绘制灰度图
plt.figure(figsize=(10, 6), dpi=100)
plt.bar(range(len(greyScale_map)), greyScale_map, color='gray')
plt.xlabel('Gray Level')
plt.ylabel('Pixel Count')
plt.title('Gray Level Histogram')
plt.show()