画彩色图像灰度直方图,图片放在D盘根目录下,没有直接使用hist函数,使用numpy数组自己计算的,加深理解。
import cv2
import numpy as np
import sys
import matplotlib.pyplot as plt
def calcGrayHist(image):
#获得灰度图像矩阵的高、宽
rows,cols=image.shape
#储存
grayHist=np.zeros([256],np.uint64)
for r in range(rows):
for c in range(cols):
grayHist[image[r][c]]+=1
return grayHist
if __name__=='__main__': ##启动语句
a= cv2.imread('D:/2.png', cv2.IMREAD_UNCHANGED) # 路径名中不能有中文,会出错,cv2.
image1 = cv2.split(a)[0]
image2 = cv2.split(a)[1]
image3 = cv2.split(a)[2]
#计算灰度直方图
grayHist1=calcGrayHist(image1)
grayHist2 = calcGrayHist(image2)
grayHist3 = calcGrayHist(image3)
#画灰度直方图
x_range=range(256)
plt.plot(x_range, grayHist1,'r',linewidth=2,c='blue')
plt.plot(x_range, grayHist2, 'r', linewidth=2, c='green')
plt.plot(x_range, grayHist3, 'r', linewidth=2, c='red')
#设置坐标轴范围
y_maxValue=np.max(np.array([np.max(grayHist1),np.max(grayHist2),np.max(grayHist3)]))
plt.axis([0,255,0,y_maxValue])
plt.xlabel('gray Level')
plt.ylabel("number of pixels")
plt.show()