Python OpenCV Histogram of Grayscale Image
In this post, you will learn how to compute the histogram of an image using Python OpenCV or cv2.calchist function.
A histogram is a graphical representation showing how frequently various color values occur in an image. It is a graph or plot which represents the intensity distribution of an image. It is a plot with pixel values (ranging from 0 to 255, not always) in the X-axis and the corresponding number of pixels in the image on the Y-axis.
Python OpenCV provides cv2.calcHist() function to calculate the histogram of one or more arrays. We can use this function to calculate the histogram of both single channel images and multi-channel images. In this article, we have used only single channel image.
Syntax of calcHist()
cv2.calcHist(images, channels, mask, histSize, ranges)
images: It is an image source of type uint8 or float32.
channels: It represents the index of the channel. It is given in a square bracket. For the grayscale image, its value is .
mask: It represents a mask image. To find the histogram of the full image, it is given as "None".
histSize: It represents the number of bins provided as a list.
ranges: It represents the range of intensity values.
- OpenCV (cv2)
Example of grayscale image histogram without Mask
Here is the code for calculating the histogram of a full grayscale image. In this case, hist is a (256,1) array. Each value of the array corresponds to the number of pixels with the corresponding tone value.
In this example, the matplotlib library is used to plot the histograms. It provides the hist() function for plotting.
import cv2 import numpy as np from matplotlib import pyplot as plt # image path path = r'cat.jpg' # using imread() img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) cv2.imshow('Cat',img) dst = cv2.calcHist(img, , None, , [0,256]) plt.hist(img.ravel(),256,[0,256]) plt.title('Histogram for gray scale image') plt.show()
Example of grayscale image histogram with mask
The mask consists of a black image with the same dimensions as the loaded image and some white regions corresponding to the image where we want to calculate the histogram. The following code creates a mask-
mask = np.zeros(img.shape[:2], np.uint8) mask[100:300, 100:400] = 255
Here is the complete code to draw a histogram of the image with mask. In this example, it will be very clear for you to draw a histogram with and without a mask.
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('nature.jpg',0) # create a mask mask = np.zeros(img.shape[:2], np.uint8) mask[100:300, 100:400] = 255 masked_img = cv2.bitwise_and(img,img,mask = mask) # Calculate histogram with mask and without mask hist_full = cv2.calcHist([img],,None,,[0,256]) hist_mask = cv2.calcHist([img],,mask,,[0,256]) plt.subplot(221), plt.imshow(img, 'gray') plt.subplot(222), plt.imshow(mask,'gray') plt.subplot(223), plt.imshow(masked_img, 'gray') plt.subplot(224), plt.plot(hist_full), plt.plot(hist_mask) plt.xlim([0,256]) plt.show()
Related ArticlesBitwise and OpenCV
Capture a video in Python OpenCV and save
Python OpenCV Histogram of Color Image
Arithmetic Operations on Images using Python OpenCV
Contour Detection using Python OpenCV
Python overlay two images
Python OpenCV Gaussian Blur Filtering
Python OpenCV Overview and Examples
Draw different shapes on image using Python OpenCV
How to convert MySQL query result to JSON in Python
How to display data from MongoDB in HTML table using Python
CRUD operations in Python using MongoDB connector
Write Python Pandas Dataframe to CSV
Quick Introduction to Python Pandas
Python Pandas DataFrame
Python3 Tkinter Messagebox
Python get visitor information by IP address