Wednesday 28 February 2024

OpenCV: Compute histogram for pixel intensities in BGR images

Using histogram, we can visualize the distribution on pixel intensities in an image.

 

Using cv2.calcHist method, we can compute histogram from an image or specific portion of the image.

 

Why histogram needed?

Using histogram, we can visualize the distribution on pixel intensities in an image.

 

Signature

cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])

 

Following table summarizes the parameters of calcHist method.

 

Parameter

Description

images

It is a list of source images from which you want to calculate the histogram.

channels

Specifies which color channels of image you want to consider while calculating histogram.

 

For a grayscale image, it is set to [0].

 

For a BGR image, you can specify [0], [1], or [2] for the blue, green, and red channels.

mask

It is used to calculate histogram for specific region in the image. This is set to None, if you want to calculate histogram for entire image.

histSize

Specifies number of bins in the histogram.

ranges

Specify range of pixel values in each channel.

 

For grayscale images, it is usually [0, 256] to cover the full range of pixel values.

 

For color images, you might use [0, 256] for each channel.

hist

This is optional, specifies an output parameter where the calculated histogram is stored

accumulate

This is optional parameter. If set to True, the histogram is not cleared in the beginning but is accumulated. This can be useful when you want to calculate histograms for multiple images and accumulate them.

 

Example

image = cv.imread('flowers.jpeg')

colors = ('b', 'g', 'r')
for index, color in enumerate(colors):
    hist = cv.calcHist([image], [index], None, [256], [0,256])
    plt.plot(hist, color=color)
    plt.xlim([0, 256])

 

Above snippet calculate the histogram for all the three color channels.

 

Find the below working application.

 

bgr_image_histogram.py

 

import cv2 as cv
import matplotlib.pyplot as plt

image = cv.imread('flowers.jpeg')

colors = ('b', 'g', 'r')
for index, color in enumerate(colors):
    hist = cv.calcHist([image], [index], None, [256], [0,256])
    plt.plot(hist, color=color)
    plt.xlim([0, 256])

cv.imshow('Image', image)
plt.title('Histogram for image')
plt.xlabel('bins')
plt.ylabel('Number of Pixels')
plt.xlim([0, 256])

plt.show()
cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

 

Output

Original image

 



Histogram



Previous                                                    Next                                                    Home

No comments:

Post a Comment