灰度直方图是图像灰度级的函数,用来描述每个灰度级在图像矩阵中的像素个数或者占有率。对于8位图来说, 图像的灰度级范围是0-255之间的整数,通过定义函数calcGrayHist来计算灰度直方图。
#-*-coding:utf-8-*-
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
def calcGrayHist(image):
gray= cv.cvtColor(image, cv.COLOR_BGR2GRAY)
rows, cols= gray.shape
#存储灰度直方图
grayHist= np.zeros([256], np.uint64)
for r in range(rows):
for c in range(cols):
grayHist[gray[r][c]]+= 1
return grayHist
if __name__== "__main__":
print("---------------Hello python ------------")
filename= ("basketball.jpg")
src= cv.imread(filename)
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
grayHist= calcGrayHist(src)
x_range= range(256)
plt.plot(x_range, grayHist,'r',linewidth=2,c='black')
y_maxvalue= np.max(grayHist)
plt.axis([0,255,0, y_maxvalue])
plt.xlabel('gray Level')
plt.ylabel('number of pixels')
plt.show()
网友评论