计算灰度直方图和RGB三个通道的灰度直方图
Tips
1.计算灰度
cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate ]])
imaes:输入的图像
channels:选择图像的通道
mask:掩膜,是一个大小和image一样的np数组,其中把需要处理的部分指定为1,不需要处理的部分指定为0,一般设置为None,表示处理整幅图像
histSize:使用多少个bin(柱子),一般为256
ranges:像素值的范围,一般为[0,255]表示0~255
2.展示图像,窗口停留和关闭
cv2.imshow()
cv2.waitKey()
cv2.destroyAllWindows()
2-2
用calcHist计算,matplotlib画图
from cv2 import cv2
import matplotlib.pyplot as plt
import numpy as npimg = cv2.imread("C:\\test\\1.jpg")
cv2.imshow(' ', img)
cv2.waitKey()
cv2.destroyAllWindows()b, g, r = cv2.split(img)
# 保存图片
cv2.imwrite('C:\\test\\Blue.jpg',b)
cv2.imwrite('C:\\test\\Green.jpg',g)
cv2.imwrite('C:\\test\\Red.jpg', r)
# 展示结果
r = cv2.imshow("Red", r)
g = cv2.imshow("Green", g)
b = cv2.imshow("Blue", b)
cv2.waitKey()
cv2.destroyAllWindows()
color = ['r', 'g', 'b']
# 最终结果
for i,col in enumerate(color):histr = cv2.calcHist([img], [i], None, [256], [0, 255])plt.bar(range(256), height=np.ravel(histr), width=1, color=col)plt.xlim(0, 256)plt.ylim(0, 2500)plt.show()
2-4
import numpy as np
from PIL import Imagef = np.array([[100, 76, 0, 132, 7, 7], [28, 7, 7, 7, 7, 243], [28, 243, 7, 100, 7, 28], [100, 7, 7, 0, 7, 100]])
f = np.array(f, dtype='uint8')
f = Image.fromarray(f)
f.save('C:\\test\\tem.bmp','bmp')
import numpy as np
from PIL import Image
from cv2 import cv2
import matplotlib.pyplot as pltf = np.array([[100, 76, 0, 132, 7, 7],[28, 7, 7, 7, 7, 243],[28, 243, 7, 100, 7, 28],[100, 7, 7, 0, 7, 100],[100, 7, 7, 0, 132, 0],[132, 132, 132, 100, 7, 100]])plt.hist(f.ravel(),256)
plt.show()