Histogram equalization

The purpose of histogram equalization is to map the gray level of the original image uniformly to the whole range of gray level, so as to obtain an image with balanced distribution of gray level. This equalization realizes the statistical probability equalization of gray value and visual equalization of human visual system (HSV).

Generally speaking, histogram equalization can achieve the purpose of enhancing image display effect. The most common ones are fog removal. Next, we will achieve gray image and color image fog respectively.

Achieve gray image defogging

In OpenCV, it provides the function cv2.equalizehist () for histogram equalization, which is fully defined as follows:

def equalizeHist(src, dst=None) :
Copy the code

SRC: Original image, must be 8-bit single channel original image

DST: return value, which returns the result of histogram averaging

Next, we use this function to realize histogram equalization of grayscale images. The code is as follows:

import cv2
import matplotlib.pyplot as plt

img = cv2.imread("45.jpg".0)
equ = cv2.equalizeHist(img)

cv2.imshow("1",img)
cv2.imshow("2",equ)
plt.figure("Original image histogram")
plt.hist(img.ravel(), 256)
plt.figure("Equalization image histogram")
plt.hist(equ.ravel(), 256)
plt.show()

cv2.waitKey()
cv2.destroyAllWindows()
Copy the code

After running, the effect is as follows:

The left is the original image, and the right is the processed image. You can see the fog in the foreground of the image, which has been basically removed. However, let’s look at the histogram distribution before and after the processing.

Realize color image defogging

Although the grayscale image above achieves the basic effect of defogging, to be honest, most of the actual scenes we use color images the most. Therefore, to master the color image histogram equalization processing, is our real combat skills.

Let’s use the code to achieve color image histogram equalization, the code is as follows:

import cv2
import matplotlib.pyplot as plt

img = cv2.imread("50.jpg")

blue = img[:, :, 0]
green = img[:, :, 1]
red = img[:, :, 2]
blue_equ = cv2.equalizeHist(blue)
green_equ = cv2.equalizeHist(green)
red_equ = cv2.equalizeHist(red)
equ = cv2.merge([blue_equ, green_equ, red_equ])

cv2.imshow("1",img)
cv2.imshow("2",equ)
plt.figure("Original image histogram")
plt.hist(img.ravel(), 256)
plt.figure("Equalization image histogram")
plt.hist(equ.ravel(), 256)
plt.show()

cv2.waitKey()
cv2.destroyAllWindows()
Copy the code

Here, we just need to use the equalizeHist() function to equalize each color of the color image. Of course, it’s important to note that after we’ve processed each color, we need to merge the images again. After running, the effect is as follows: