The principles and display, masking, equalization, and adaptive equalization of OpenCV histograms

Histograms play a vital role in digital image processing and computer vision, used to analyze and improve the quality and contrast of images. OpenCV provides a wealth of functions and functions for processing histograms, including operations such as histogram calculation, display, masking, equalization and adaptive equalization. In this article, we’ll dive into the mechanics of these operations to better understand their role and application.
The principle of histogram

A histogram is a statistical tool used to describe the distribution of pixel values in an image. It graphically represents the frequency or number of occurrences of different pixel values. The horizontal axis of a histogram usually represents a pixel value, while the vertical axis represents the frequency or probability of occurrence of that pixel value.

The calculation of the histogram includes the following steps:

Image grayscale: Convert color images to grayscale images to make them easier to process.
Pixel value statistics: Traverse each pixel of the image and add its pixel value to the counter of the corresponding pixel value.
Normalization: Convert the frequency of pixel values in the counter into a probability distribution, usually by dividing by the total number of pixels.

By analyzing the histogram, we can understand information such as contrast, brightness, and color distribution of the image, which is very useful for subsequent image processing.
Histogram display

Histogram display is a visualization tool that presents the grayscale distribution of an image by drawing a histogram. In OpenCV, one can use plotting libraries such as Matplotlib to display histograms. The horizontal axis of the histogram represents the pixel value, and the vertical axis represents the frequency or probability of the pixel value. By looking at the histogram, we can quickly understand the brightness and contrast of the image.
Histogram equalization

Histogram equalization is a method used to improve image contrast. The principle is to enhance the contrast of the image by redistributing pixel values so that they are more evenly distributed throughout the range.

The steps of histogram equalization include:

Calculate the histogram of the original image.
Computes the cumulative distribution function (CDF), which maps pixel values to new values.
Use CDF to map each pixel value of the image to an equalized value.

This process can improve the overall contrast of the image, especially when the pixel values are unevenly distributed, the contrast improvement effect is significant.
Application of Histogram Equalization

Histogram equalization has wide applications in many image processing tasks, including:

Image enhancement: Make details more clearly visible by increasing the contrast of the image.
Image preprocessing: Improve image quality in tasks such as image segmentation, object recognition, and target tracking.
Medical image processing: used to improve medical images such as X-rays, MRI and CT scans.
Remote sensing image processing: used to improve satellite images and aerial images for better ground object detection and geographic information system (GIS) applications.

Limitations of Histogram Equalization

While histogram equalization is very effective in many situations, it has some limitations:

Potential to increase noise: On images with a wide distribution of pixel values, equalization may increase the visibility of noise.
Not suitable for all images: For images that already have good contrast, equalization may not bring a noticeable improvement.
Equalization is a global operation: it ignores local features of the image and is therefore not suitable for all applications.

Histogram equalization and adaptive equalization

Adaptive equalization is an improved histogram equalization method that takes into account the local characteristics of the image. The idea of adaptive equalization is to divide the image into small blocks and equalize each small block instead of processing the entire image. This helps preserve the local contrast of the image and avoids problems that global equalization can introduce.

The steps of adaptive equalization include:

Divide the image into multiple non-overlapping regions or blocks.
To equalize each block, you can use the histogram equalization method described above.
Finally, all blocks are merged to obtain the adaptive equalized image.

Adaptive equalization is more suitable for images with large local contrast differences, but it also requires more computing resources.
in conclusion

Histograms are an important tool in image processing and computer vision, used to analyze and improve the contrast and brightness of images. OpenCV provides various histogram-related functions, including calculation, display, masking, equalization and adaptive equalization. These techniques can be applied in many fields, from image enhancement to medical image processing to improve image

Histogram

1 Grayscale histogram





1.1 Drawing and calculation of histogram

Code implementation

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

#Read directly as grayscale image

img =cv.imread("lena.png",0)

#statistical grayscale image
histr = cv.calcHist([img],[0],None,[256],[0,256])
'''
 Calculate the histogram of a grayscale image using OpenCV's calcHist function. The calcHist function accepts the following parameters:
[img]: The image whose histogram needs to be calculated, passed in list form.
[0]: Specifies the index of the channel. Because we are dealing with grayscale images, there is only one channel, and the index is 0.
None: used to specify the mask, usually not needed, so set to None.
[256]: Specify the size of the histogram, which means the histogram has 256 bins, ranging from 0 to 255.
[0, 256]: Specifies the range of pixel values, which means that all pixel values are within the range of 0 to 255.
The return value of the function histr is an array containing the histogram statistics.
'''
#draw grayscale image
plt.figure(figsize=(10,6),dpi=100)
'''Specifies the size of the canvas to be 10x6 inches and the resolution to be 100dpi. '''
plt.plot(histr)
'''To draw a histogram, pass the histr array as a parameter to the plot function. This will plot a line chart containing grayscale histogram statistics'''
plt.grid()
'''Add grid lines to improve image readability'''
plt.show()

Result display

2 Application of mask

2.1 code implementation`

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['SimHei']

img = cv.imread("lena.png",0)

#Create mask
mask = np.zeros(img.shape[:2],np.uint8) #Create a blank mask with the same size as the image, the data type is uint8
mask[100:256,100:256]=255 #Set the area of interest on the mask and set the pixel value to 255.

#mask
mask_img = cv.bitwise_and(img,img,mask=mask) #The function performs a bitwise AND operation on the original image and the mask to obtain the masked image
#Statistical mask image grayscale image
mask_histr = cv.calcHist([img],[0],mask,[256],[1,256]) # Function calculates the grayscale histogram of the masked image. The mask parameter mask is passed in here, and only the pixels in the mask area are counted.

#Image display
fig,axes = plt.subplots(nrows=2,ncols=2,figsize=(5,4))
axes[0,0].imshow(img,cmap=plt.cm.gray) #Show the original image in the first subimage, using grayscale color mapping plt.cm.gray
axes[0,0].set_title("original image")

axes[0,1].imshow(mask,cmap=plt.cm.gray)
axes[0,1].set_title("Mask data")

axes[1,0].imshow(mask_img,cmap=plt.cm.gray)
axes[1,0].set_title("Data after mask")

axes[1,1].plot(mask_histr) #Draw the grayscale histogram of the masked image in the fourth subgraph
axes[1,1].grid() #Add grid lines to improve the readability of the image.
axes[1,1].set_title("Grayscale Histogram")
plt.show()

2.2 Result display

3 Histogram equalization


It improves the visual effect of the image by redistributing the gray levels of the image so that the pixel values of each gray level in the image are evenly distributed throughout the entire range.

The functions of histogram equalization include:

Enhance image contrast: Histogram equalization can stretch the pixel values of each gray level in the original image, making the brightness changes in the image more obvious, thus enhancing the contrast of the image.

Enhance detail information: Histogram equalization can increase the pixel values of low-contrast areas in the image, making details more clearly visible. This is useful for image analysis and image recognition tasks.

Removing background noise: Histogram equalization can adjust the gray level distribution of the image to reduce the impact of background noise. This is very effective for some application scenarios where target objects need to be extracted.

Enhance the visual effect of the image: Histogram equalization can make the overall visual effect of the image more vivid and vivid, and improve the viewing quality of the image.

3.1 code implementation

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['SimHei']

#Read directly as grayscale image
img = cv.imread("lena.png",0)
histr_1 = cv.calcHist([img],[0],None,[256],[0,256])

#EQUALIZATION
dst = cv.equalizeHist(img)

histr_2 = cv.calcHist([dst],[0],None,[256],[0,256])

#show
fig,axes = plt.subplots(nrows=2,ncols=2,figsize=(5,4),dpi=100)

axes[0,0].imshow(img,cmap=plt.cm.gray)
axes[0,0].set_title("original image")
axes[0,1].plot(histr_1)
axes[0,1].grid()
axes[0,1].set_title("Original image-grayscale histogram")

axes[1,0].imshow(dst,cmap=plt.cm.gray)
axes[1,0].set_title("Equalization results")
axes[1,1].plot(hisr_2)
axes[1,1].grid()
axes[1,1].set_title("Equalized Histogram")
plt.show()

3.2 Result Display

4Adaptive equalization



4.1 Code Implementation

import matplotlib.pyplot as plt
import numpy as np
import cv2 as cv
from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['SimHei']

img = cv.imread("lena.png",0)

#Create an adaptive equalization object and apply it to the image
clahe = cv.createCLAHE(clipLimit=2.0,tileGridSize=(8,8)) #clipLimit parameter specifies the contrast limit, and tileGridSize parameter specifies the grid size for image division
cl1 = clahe.apply(img) #Apply adaptive equalization to image img and save the result in variable cl1

#Image display
fig,axes = plt.subplots(nrows=1,ncols=2,figsize=(5,4),dpi=100)
axes[0].imshow(img,cmap=plt.cm.gray)
axes[0].set_title("original image")
axes[1].imshow(cl1,cmap=plt.cm.gray)
axes[1].set_title("Adaptive equalization results")
plt.show()

4.2 Operation results