from matplotlib import pyplot as plt
import cv2
girl = cv2.imread("girl.jpg")
cv2.imshow("girl", girl)# girl.ravel()函数是将图像的三位数组降到一维上去,#256为bins的数目,[0, 256]为范围
plt.hist(girl.ravel(),256,[0,256])
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
效果展示:
直方图绘制 方法2
from matplotlib import pyplot as plt
import cv2
import numpy as np
img = cv2.imread('girl.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(img_gray, cmap=plt.cm.gray)
hist = cv2.calcHist([img],[0],None,[256],[0,256])
plt.figure()
plt.title("Grayscale Histogram")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")
plt.plot(hist)
plt.xlim([0,256])
plt.show()
效果展示:
三通道直方图绘制
Python代码
from matplotlib import pyplot as plt
import cv2
girl = cv2.imread("girl.jpg")
cv2.imshow("girl", girl)
color =("b","g","r")#使用for循环遍历color列表,enumerate枚举返回索引和值for i, color inenumerate(color):
hist = cv2.calcHist([girl],[i],None,[256],[0,256])
plt.title("girl")
plt.xlabel("Bins")
plt.ylabel("num of perlex")
plt.plot(hist, color = color)
plt.xlim([0,260])
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()