Python-Opencv中的图像直方图

Python-Opencv中的图像直方图

直方图(histogram)

hist函数

matplotlib.pyplot.hist( x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=u’bar’, align=u’mid’, orientation=u’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False,hold=None, **kwargs)

其中:

  • x : (n,) array or sequence of (n,) arrays
    这个参数是指定每个bin(箱子)分布的数据,对应x轴
  • bins : integer or array_like, optional
    这个参数指定bin(箱子)的个数,也就是总共有几条条状图
  • normed : boolean, optional
    If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e.,n/(len(x)`dbin)
    这个参数指定密度,也就是每个条状图的占比例比,默认为1
  • color : color or array_like of colors or None, optional
    这个指定条状图的颜色

代码实现

from matplotlib import pyplot as plt
import cv2 as cv

girl = cv.imread("girl.jpg")
cv.imshow("girl", girl)
# girl.ravel()函数是将图像的三位数组降到一维上去,256为bins的数目,[0, 256]为范围
plt.hist(girl.ravel(), 256, [0, 256])
plt.show()
cv.waitKey(0)
cv.destroyAllWindows()

Python-Opencv中的图像直方图
由于该图片亮度较高,并且纯色白色,黄色占多数,故三通道中的值都很高,所以直方图中也可以看出三通道值靠近255的占大多数。

calcHist函数

calculate histogram,从函数名中我们就知道是calcHist函数是用来计算图像直方图的。

其中参数:

  • image输入图像,传入时应该用中括号[ ]括起来
  • channels::传入图像的通道,如果是灰度图像,那就不用说了,只有一个通道,值为0,如果是彩色图像(有3个通道),那么值为0,1,2,中选择一个,对应着BGR各个通道。这个值也得用[ ]传入。
  • mask:掩膜图像。如果统计整幅图,那么为none。主要是如果要统计部分图的直方图,就得构造相应的炎掩膜来计算。
  • histsize:灰度级的个数,需要中括号,比如[256]
  • ranges:像素值的范围,通常[0,256],有的图像如果不是0-256,比如说你来回各种变换导致像素值负值、很大,则需要调整后才可以。

代码实现

from matplotlib import pyplot as plt
import cv2 as cv

girl = cv.imread("girl.jpg")
cv.imshow("girl", girl)
color = ("b", "g", "r")
for i, color in enumerate(color):
    hist = cv.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()
cv.waitKey(0)
cv.destroyAllWindows()

Python-Opencv中的图像直方图
可以统计每一个通道其所对应值得频数,从该图片中我们能看到操场为红色,故红色通道中靠近255的较多,女生的衣服为大面积白色,所以三个通道对应的值都应该靠近255,并且白色为大面积,所以频数也大,女生的裤子为黄色,其中红色通道和绿色通道靠近255。故可以看到BGR三个通道靠近255的都是占多数。

初学Opencv,如有错误地方和改进地方,真诚地邀请您提出来,谢谢!

本文结束…