English 中文(简体)
OpenCV Python - Histogram
  • 时间:2024-12-22

OpenCV Python - Histogram


Previous Page Next Page  

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.

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.

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

In OpenCV pbrary, 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

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

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

    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.

    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.

    histSize − This represents our BIN count.

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

Histogram using Matplotpb

A histogram plot can be obtained either with the help of Matplotpb’s pyplot.plot() function or by calpng Polypnes() function from OpenCV pbrary.

Example

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 matplotpb 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.xpm([0,256])
plt.show()

Output

Histogram Advertisements