代码
import cv2 as cv import matplotlib.pyplot as plt img = cv.imread("./lena.jpg") img_gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY) grayDict = {} for key in range(256): grayDict[key] = 0 for i in range(img_gray.shape[0]): for j in range(img_gray.shape[1]): grayDict[img_gray[i][j]] += 1 plt.figure(dpi=300) plt.xticks(range(0,255,25)) plt.bar(list(grayDict.keys()), list(grayDict.values())) plt.savefig("hist.png") plt.show()
效果
原图:
灰度直方图: