Python-OpenCV 图像处理(九):图像直方图:一维与多维

import cv2
import numpy as np
from matplotlib import pyplot as plt

__author__ = "zxsuperstar"
__email__ = "[email protected]"

"""
图像直方图:一维与多维
"""
def plt_demo(image):
    plt.hist(image.ravel(),256,[0,256])
    plt.show("直方图")


def image_hist(image):
    color = ("blue","green","red")
    for i ,color in enumerate(color):
        hist = cv2.calcHist([image],[i],None,[256],[0,256])
        plt.plot(hist,color=color)
        plt.xlim([0,256])
    plt.show()


if __name__ == "__main__":
    src = cv2.imread("t.jpg") #blue green red
    # cv2.namedWindow("image", cv2.WINDOW_AUTOSIZE)
    cv2.imshow("image",src)
    # plt_demo(src)
    image_hist(src)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

1.numpy的ravel函数功能是将多维数组降为一维数组。

2.matplotlib.pyplot.hist函数主要是计算直方图。

hist函数原型: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参数表示箱子的下限和上限。即横坐标显示的范围,范围之外的将被舍弃。

3.enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据下标和数据,一般用在 for 循环当中。

4.cv2.calcHist的原型为:calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]]) -> hist

images参数表示输入图像,传入时应该用中括号[ ]括起来

channels参数表示传入图像的通道,如果是灰度图像,那就不用说了,只有一个通道,值为0,如果是彩色图像(有3个通道),那么值为0,1,2,中选择一个,对应着BGR各个通道。这个值也得用[ ]传入。

mask参数表示掩膜图像。如果统计整幅图,那么为None。主要是如果要统计部分图的直方图,就得构造相应的掩膜来计算。

histSize参数表示灰度级的个数,需要中括号,比如[256]

ranges参数表示像素值的范围,通常[0,256]。此外,假如channels为[0,1],ranges为[0,256,0,180],则代表0通道范围是0-256,1通道范围0-180。

hist参数表示计算出来的直方图。

猜你喜欢

转载自blog.csdn.net/zx_good_night/article/details/88654357