b i n s i z e = 图 像 中 不 同 像 素 值 的 个 数 b i n 的 数 目 bin_{size}=\frac{图像中不同像素值的个数}{bin的数目} binsize=bin的数目图像中不同像素值的个数
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
def histogram_demo(image):
plt.hist(image.ravel(), 256, [0, 256])#ravel函数功能是将多维数组降为一维数组
plt.show()
image = cv.imread('./data/lena.jpg', 1)
cv.imshow('souce image', image)
histogram_demo(image)
cv.waitKey(0)
cv.destroyAllWindows()
注意:
hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, hold=None, data=None, **kwargs)
x参数表示是一个数组或一个序列,是指定每个bin(箱子)分布的数据
bins参数表示指定bin(箱子)的个数,也就是总共有几条条状图
range参数表示箱子的下限和上限。即横坐标显示的范围,范围之外的将被舍弃。
def image_hist(image): #画三通道图像的直方图
color = ("blue", "green", "red")#画笔颜色的值可以为大写或小写或只写首字母或大小写混合
for i, color in enumerate(color):
hist = cv.calcHist([image], [i], None, [256], [0, 256])
plt.plot(hist, color=color)
plt.xlim([0, 256])
plt.show()
image = cv.imread('./data/lena.jpg', 1)
cv.imshow('souce image', image)
image_hist(image)
cv.waitKey(0)
cv.destroyAllWindows()
注意:
4. enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据下标和数据,一般用在 for 循环当中。
5. cv2.calcHist的原型为:
calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])