What is histogram equalization in Python?

Histogram equalization is a process where the intensity values of an image are adjusted to create a higher overall contrast.

Digital Image Processing is a significant aspect of data science. It is used to enhance and modify images so that their attributes are more easily understandable.

Artificial Intelligence also makes use of digital image processing to make for a consistent and advantageous dataset.

Image histograms are largely used to obtain information about image attributes. Image contrast can be determined by looking at the range of pixel intensity values that the histogram bars are spread over.

If the range is low, image contrast is also low. Meanwhile, a higher range of pixel intensity values means a higher contrast.

An example of a low contrast image is shown below.

import cv2
import matplotlib.pyplot as plt
img = cv2.imread('/image_1.jpg',0)
hist1 = cv2.calcHist([img],[0],None,[256],[0,256])
plt.subplot(221),plt.imshow(img);
plt.subplot(222),plt.plot(hist1);

Histogram equalization is done by using the following formula: Sk=T(rk)=j=0kPin(rj)=(L1)MNj=0knjS_k=T(r_k)=\sum_{j=0}^kP_{in}(r_j)=\frac{(L-1)}{MN}\sum_{j=0}^kn_j
where k=0,1,2,......,L1k=0,1,2,......,L-1

  • L: The maximum intensity level of the image. For a 8-bit image, L is 256.
  • M: The width of the image.
  • N: The height of the image.
  • n: The frequency corresponding to each intensity level.
  • rj: The range of values from 0 to L-1.
  • pin: The total frequency that corresponds to a specific value of rj.
  • rk: The new frequencies.
  • sk: The new equalized histogram.

Code example

import cv2
import matplotlib.pyplot as plt
img = cv2.imread('/image_1.jpg',0)
hist1 = cv2.calcHist([img],[0],None,[256],[0,256])
img_2 = cv2.equalizeHist(img)
hist2 = cv2.calcHist([img_2],[0],None,[256],[0,256])
plt.subplot(221),plt.imshow(img);
plt.subplot(222),plt.plot(hist1);
plt.subplot(223),plt.imshow(img_2);
plt.subplot(224),plt.plot(hist2);

Explanation

  • Line 1: import cv2 imports the OpenCV library into the python file.

  • Line 2: import matplotlib.pyplot as plt imports the matplotlib library into the python file.

  • Line 4 The function cv2.imread() reads the image and returns the image data in img.

  • Line 5 The function cv2.calcHist() calculates the intensity distribution of the image.

  • Line 6 The function cv2.equalizeHist() stretch out the intensity range of the image in order to improve contrast.

  • Line 8-11: Plotting the images and their histogram.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved