Histogram Equalization in OpenCV
From learning to earning – Courses that prepare you for job - Enroll now
In this article, we’ll understand the Histogram equalization technique in OpenCV. An image histogram is the global description of the aspects of the image. The image histogram provides high quality information about the image. The relative frequency of the occurrence of each gray level of the image is accurately represented by the Image Histogram. Histogram equalization is a technique that adjusts the intensities of an image and enhances the contrast of the image.
What is an image Histogram?
The histogram for any image acts as the graphical representation of the distribution of the intensity of the image. The histogram plots the number of pixels according to the intensity values. The image histogram describes an image by its intensity distribution. The image histogram for each intensity value considered quantifies the number of pixels.
Analyzing an image using histogram
The histogram for an image refers to a visual depiction of the intensity values of the pixels. The histogram of an image is a way of analysing the image. It is used to understand the global description of the image.
Implementation
# Importing OpenCV import cv2 # Importing numpy import numpy as np # Importing matplotlib.pyplot import matplotlib.pyplot as plt # Reading the image img = cv2.imread(r"C:\Users\tushi\Downloads\PythonGeeks\deer.png") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img_1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Setting the grid size plt.figure(figsize=(20,20)) # Plotting the original image plt.subplot(221) plt.title('Original') plt.imshow(img) # Plotting the histogram for the image img_hist = cv2.calcHist([img_1],[0],None,[256],[0,256]) plt.subplot(222) plt.title('Histogram 1') plt.plot(img_hist) # Plotting the histogram using the ravel function plt.subplot(223) plt.hist(img_1.ravel(), 256, [0,256]) plt.title('Histogram 2') # Plotting the histogram for colors in the image for i, col in enumerate(['r', 'g', 'b']): hist = cv2.calcHist([img], [i], None, [256], [0, 256]) plt.subplot(224) plt.title('Color Histogram') plt.plot(hist, color = col) plt.xlim([0, 256])
What is Histogram Equalization in OpenCV?
Histogram equalization is an image processing method to adjust the contrast of an image using its intensity distribution histogram.
The equalization method increases the value of global contrast when the close contrast values represent the usable data for the image. Through the adjustments of the contrast values of the image, the intensity distribution of the image becomes clearer. Local regions of the image with lower contrast values gain a higher contrast value.
Histogram equalization method effectively spreads the frequent intensity values of the image. The histogram equalization method effectively spreads out the clustered intensity values. This improves the contrast of the image, while the intensity range of the image is stretched. Images with both dark or bright backgrounds and foregrounds benefit from this method.
cv2.equalizeHist() function in OpenCV performs histogram equalization to improve the contrast of the images and stretch the intensity range for the image histogram. The function takes a grayscale image as the input and returns an equalized image.
Working of Histogram equalization
Histogram equalization maps one distribution of the given histogram to another distribution (distribution with more wide and uniform intensity value distribution) to achieve the spreading of intensity values over the entire range.
To achieve the equalization effect, remapping is done using the cumulative distribution function.
For the histogram H(i), the cumulative distribution H'(i) is given by:
H'(i)=∑0≤j<iH(j)
To use the cumulative distribution function for remapping, normalization of the Histogram H’i has to be done. The maximum intensity value for an image should be 255. Simple remapping procedure is followed and intensity values for the equalized image are obtained.
equalized(x,y)=H'(src(x,y))
Procedure of histogram equalization technique:
1. The intensity values for each pixel of the image are used to compute an image histogram.
2. The cluttered intensity values are evenly distributed and the range of intensity values is increased.
3. Remapping of the histogram is done using the cumulative distribution function.
4. The output obtained is a histogram equalized image with increased global contrast.
Syntax
cv2.equalizeHist(src, dst)
Parameters
- src: Source image or input image
- dst: Output image of the same size and type as the input image
1. Histogram equalization of grayscale image
The cv2.equalizeHist() function takes a grayscale image as input. Therefore we can simply provide a grayscale image for equalization. The equalized image in the output has improved contrast as compared to the original image. The cv2.equalizeHist() function returns an image with improved contrast and stretches the intensity range for the image histogram.
Implementation
# Importing OpenCV import cv2 # Importing numpy import numpy as np # Reading the image img = cv2.imread(r"C:\Users\tushi\Downloads\PythonGeeks\low contrast.jpg",0) # Displaying the original image cv2.imshow('Original', img) cv2.waitKey(0) cv2.destroyAllWindows()
# Applying the Histogram equalization using the cv2.equalizeHist() function final_image = cv2.equalizeHist(img) # Displaying the image cv2.imshow('Histogram Equalization', final_img) cv2.waitKey(0) cv2.destroyAllWindows()
2. Histogram equalization of color image
The channels of the RGB color space represent the intensity of the associated color and not the brightness of the whole image. The application of histogram equalization on the color channels will not give us the desired results. The brightness of the image has to be separated from the color channels and then histogram equalization can be applied.
Implementation
# Importing OpenCV import cv2 # Reading the image image = cv2.imread(r"C:\Users\tushi\Downloads\PythonGeeks\deer.png") # Displaying the original image cv2.imshow('Original', image) cv2.waitKey(0) cv2.destroyAllWindows() # Convert image from RGB to HSV img_hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) # Histogram equalisation on the V-channel img_hsv[:, :, 2] = cv2.equalizeHist(img_hsv[:, :, 2]) # Convert image back from HSV to RGB image = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2RGB)
# Displaying the image cv2.imshow("Histogram Equalization", image) cv2.waitKey(0) cv2.destroyAllWindows()
3. Histogram equalization of a video
The histogram equalization of a video is done similarly to a color image. The Histogram equalization has to be performed on each frame of the video. The channels of the RGB color space of the frame of the video represent the intensity of the associated color and not the brightness of the whole image.
The application of histogram equalization on the color channels will not give us the desired results. The brightness of the image has to be separated from the color channels and then histogram equalization can be applied.
Implementation
# Importing OpenCV import cv2 # Reading the video cap = cv2.VideoCapture(0) while True: # Capturing each frame of the video ret,frame = cap.read() # Displaying the video frame by frame cv2.imshow('frame', frame) # Convert image from RGB to HSV img_hsv = cv2.cvtColor(frame, cv2.COLOR_RGB2HSV) # Histogram equalisation on the V-channel img_hsv[:, :, 2] = cv2.equalizeHist(img_hsv[:, :, 2]) # convert image back from HSV to RGB image = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2RGB) cv2.imshow('Histogram Equalization',image) key = cv2.waitKey(1) if key == ord('q'): break cap.release() cv2.destroyAllWindows()
Adaptive Histogram Equalization (AHE) and Contrastive Limited Adaptive Equalization
The adaptive histogram equalization method makes use of an adaptive function to compute numerous image histograms, each equivalent and referring to different regions of the image. By combining these computed histograms, adaptive Histogram equalization improves the contrasts of the image by spreading the intensity value of each pixel. Adaptive histogram equalization works better than standard function to improve contrasts of local regions and enhance the edges.
Contrastive Limited Adaptive Equalization is an extension of Adaptive histogram equalization method and deals with problem of over-amplification of the contrast. This method divides the image into smaller parts, called tiles. Bilinear interpolation is used to remove the artificial boundaries and combine the neighbouring tiles.
In this method, the limitation of contrast implication is done by clipping the histogram at predefined values and then the cumulative distribution function is calculated. The predefined values for the clipping, also called the clip limit, are obtained by the normalization of the histogram or by determining the size of the neighborhood of the tiles.
Syntax
cv2.createCLAHE(clipLimit, tileGridSize)
Parameters
- clipLimit: Threshold value for clipping the histogram and achieve contrast limiting
- tileGridSize: Size of the grid made for the histogram equalization. The image is divided into smaller regions called tiles and the number of tiles per row and column are defined using this parameter.
Implementation
# Importing OpenCV import cv2 # Importing numpy import numpy as np # Reading the image img = cv2.imread(r"C:\Users\tushi\Downloads\PythonGeeks\low contrast.jpg",0) # Displaying the original image cv2.imshow('Original', img) cv2.waitKey(0) cv2.destroyAllWindows() # Applying the Contrastive Limited Adaptive Equalization using cv2.createCLAHE function img_Clahe = cv2.createCLAHE(clipLimit=10) final_img = img_Clahe.apply(img) # Displaying the CLAHE image cv2.imshow('CLAHE img', final_img) cv2.waitKey(0) cv2.destroyAllWindows()
Conclusion
In this article, we learned about image histograms. We learned about Analyzing images using histograms and the Histogram equalization function in OpenCV. Furthermore, we thoroughly understood the working of this function and also saw the implementation of the function in OpenCV. We discussed the Adaptive Histogram Equalization (AHE) and Contrastive Limited Adaptive Equalization methods in OpenCV to improve the contrast on an image.