Python OpenCV 图像直方图显示问题及解决方法
import cv2 import numpy as np import matplotlib.pyplot as plt
img = cv2.imread('C:/Users/LENOVO/Desktop/c.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
计算彩色图像的直方图
hist1 = plt.hist(img.ravel(), 256) hist2 = cv2.calcHist([img], [0], None, [256], [0, 255]) hist3 = cv2.calcHist([gray], [0], None, [256], [0, 255]) cumulative_hist = np.cumsum(hist3)
将累积直方图归一化到[0,1]范围内
hist3 = cumulative_hist / cumulative_hist[-1]
显示两个直方图
plt.subplot(2, 1, 1) plt.imshow(img) plt.subplot(2, 2, 2) plt.hist(img.ravel(), 256) plt.subplot(2, 2, 3) plt.plot(hist2) plt.subplot(2, 2, 4) plt.plot(hist3) plt.show() 为什么最后只显示三个直方图,如何修改使得img正确显示内容:最后只显示了三个直方图是因为在plt.subplot()函数中,第一个参数代表子图的行数,第二个参数代表子图的列数,第三个参数代表子图的编号。因此,在第一个plt.subplot()中,应该将第三个参数改为1,即plt.subplot(2, 1, 1)。
修改后的代码如下:
import cv2 import numpy as np import matplotlib.pyplot as plt
img = cv2.imread('C:/Users/LENOVO/Desktop/c.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
计算彩色图像的直方图
hist1 = plt.hist(img.ravel(), 256) hist2 = cv2.calcHist([img], [0], None, [256], [0, 255]) hist3 = cv2.calcHist([gray], [0], None, [256], [0, 255]) cumulative_hist = np.cumsum(hist3)
将累积直方图归一化到[0,1]范围内
hist3 = cumulative_hist / cumulative_hist[-1]
显示两个直方图和原始图像
plt.subplot(2, 2, 1) plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.subplot(2, 2, 2) plt.hist(img.ravel(), 256) plt.subplot(2, 2, 3) plt.plot(hist2) plt.subplot(2, 2, 4) plt.plot(hist3) plt.show()
原文地址: https://www.cveoy.top/t/topic/jtic 著作权归作者所有。请勿转载和采集!