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 cv2import matplotlib.pyplot as pltimg = 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:
where
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.import cv2import matplotlib.pyplot as pltimg = 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);
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.