import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
#创建黑色图,观察像素分布
img = np.zeros((200,200),np.uint8)
plt.hist(img.ravel(),256,(0,255))
plt.show()
#黑色图中,创建灰色矩形,观察分布
img = np.zeros((200,200),np.uint8)
cv.rectangle(img,(0,100),(200,200),(255),-1)
cv.rectangle(img,(0,50),(100,100),(127),-1)
plt.hist(img.ravel(),256,(0,255))
plt.show()
cv.imshow("image",img)
cv.waitKey(0)
cv.destroyAllWindows()
#用网络图片观察
img = cv.imread(r"C:\Users\amy\Desktop\OpenCV\opencv-master\samples\data\lena.jpg",0)
plt.hist(img.ravel(),256,(0,255))
plt.show()
cv.imshow("image",img)
cv.waitKey(0)
cv.destroyAllWindows()
#观察彩色图片每个通道的像素分布
img = cv.imread(r"C:\Users\amy\Desktop\OpenCV\opencv-master\samples\data\lena.jpg")
b,g,r = cv.split(img)
plt.hist(b.ravel(),256,(0,255))
plt.hist(g.ravel(),256,(0,255))
plt.hist(r.ravel(),256,(0,255))
plt.show()
cv.imshow("image",img)
cv.imshow("b",b)
cv.imshow("g",g)
cv.imshow("r",r)
cv.waitKey(0)
cv.destroyAllWindows()
#利用cv的calHist函数观察
img = cv.imread(r"C:\Users\amy\Desktop\OpenCV\opencv-master\samples\data\lena.jpg")
color = ("b","g","r")
for i,col in enumerate(color):
hist = cv.calcHist([img],[i],None,[256],[0,256])
plt.plot(hist,color = col)
plt.xlim([0,256])
plt.show()
cv.imshow("image",img)
cv.waitKey(0)
cv.destroyAllWindows()