直方图显示了不同数值的像素出现的次数。在 Matplotlib 中有 hist() 函数提供了绘制直方图的接口。
我们使用 Matplotlib 来绘制 paojie.jpg 的直方图吧!
代码:
1 import cv2 2 import numpy as np 3 import matplotlib.pyplot as plt 4 5 # Gray scale 6 def BGR2GRAY(img): 7 b = img[:, :, 0].copy() 8 g = img[:, :, 1].copy() 9 r = img[:, :, 2].copy() 10 11 # Gray scale 12 out = 0.2126 * r + 0.7152 * g + 0.0722 * b 13 out = out.astype(np.uint8) 14 15 return out 16 17 # Read image 18 img = cv2.imread("../paojie.jpg").astype(np.float) 19 # BGR2GRAY 20 img = BGR2GRAY(img) 21 # Display histogram 22 # numpy中的ravel() 将多维数组转换为一维数组,不会产生副本 23 plt.hist(img.ravel(), bins=255, rwidth=0.8, range=(0, 255)) 24 plt.xlabel('Gray value') 25 plt.ylabel('number') 26 plt.title(r'Histogram of paojie.jpg') 27 plt.savefig("out.jpg") 28 plt.show()
实验结果:
参考内容:
https://www.jianshu.com/p/8fe1a7c2458f