Opencv Python 简明教程

OpenCV Python - Histogram

直方图显示了图像中的强度分布。它在 X 轴上绘制像素值(0 至 255),在 Y 轴上绘制像素数。

Histogram shows the intensity distribution in an image. It plots the pixel values (0 to 255) on X axis and number of pixels on Y axis.

通过使用直方图,可以理解指定图像的对比度、亮度和强度分布。直方图中的柱状条表示 X 轴上值的增量部分。

By using histogram, one can understand the contrast, brightness and intensity distribution of the specified image. The bins in a histogram represent incremental parts of the values on X axis.

在我们的案例中,它是像素值,默认柱状条大小为 1。

In our case, it is the pixel value and the default bin size is one.

在 OpenCV 库中,函数 cv2.calcHist() 根据输入图像计算直方图。函数的命令如下 −

In OpenCV library, the function cv2.calcHist() function which computes the histogram from the input image. The command for the function is as follows −

cv.calcHist(images, channels, mask, histSize, ranges)

Parameters

函数 cv2.calcHist() 的参数如下 −

The cv2.calcHist() function’s parameters are as follows −

  1. images − It is the source image of type uint8 or float32, in square brackets, i.e., "[img]".

  2. channels − It is the index of the channel for which we calculate histogram. For a grayscale image, its value is [0]. For BGR images, you can pass [0], [1] or [2] to calculate the histogram of each channel.

  3. mask − Mask image is given as "None" for full image. For a particular region of image, you have to create a mask image for that and give it as a mask.

  4. histSize − This represents our BIN count.

  5. ranges − Normally, it is [0,256].

Histogram using Matplotlib

直方图图可以通过 Matplotlib 的 pyplot.plot() 函数或通过从 OpenCV 库调用 Polylines() 函数获得。

A histogram plot can be obtained either with the help of Matplotlib’s pyplot.plot() function or by calling Polylines() function from OpenCV library.

Example

通过以下程序计算图像的每个通道的直方图(lena.jpg),并绘制每个通道的强度分布 −

Following program computes histogram for each channel in the image (lena.jpg) and plots the intensity distribution for each channel −

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('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()

Output

histogram