Histogram equalization and adaptive histogram equalization

前言: Hello everyone, I am Dream. Equalization is a technique commonly used in digital image processing to enhance the visual effect and contrast of an image. 直方图均衡化, today we will implement the sumof the same image自适应直方图均衡化, learn the basic principles and implementation process of the two , let's take a look~

1. Histogram equalization

Histogram Equalization is an image processing technique that enhances the contrast and visual effect of an image by redistributing the gray level of the image . It 整个adjusts the gray value distribution of pixels based on the gray histogram of the image. Through 增加较暗区域的亮度和减少较亮区域的亮度, histogram equalization can 使图像的灰度级别分布更均匀enhance the detail and contrast of the image.

1. Get the grayscale image

Generate a single-channel grayscale image from a three-channel color image
First, we use the functions in the PIL library Image.open()to read the color image and convert it into an array. We then take the height and width of the image and create an uint8all-black array of the same size as the original image and of data type gray_imgto hold the grayscale image.

Next, we iterate over each pixel, average the values ​​of the three channels, and save the result to a grayscale image. Since the three channels of the RGB image have the same weight, averaging the values ​​of the three channels can obtain a more accurate gray value.

We then convert the grayscale image to a PIL image object and use plt.imshow()functions from the Matplotlib library to display both color and grayscale images. Image.save()Finally, we save the grayscale image as a file using a function from the PIL library .

import numpy as np
import cv2
from PIL import Image
import matplotlib.pyplot as plt

# 读取彩色图像
img = Image.open('image.jpg')

# 将图像转换为数组
img_arr = np.array(img)

# 获取图像的高度和宽度
h, w, _ = img_arr.shape

# 创建一个新的数组,用于保存灰度图像
gray_img = np.zeros((h, w), dtype=np.uint8)

# 遍历每个像素,将三个通道的值求平均,并保存到灰度图像中
for i in range(h):
    for j in range(w):
        gray_img[i, j] = int(np.mean(img_arr[i, j]))

# 将灰度图像转换为PIL图像对象
gray_pil_img = Image.fromarray(gray_img)
plt.imshow(img)
plt.title('imge')
plt.axis('off')
plt.show()
plt.imshow(gray_pil_img, cmap='gray')
plt.title('gray_pil_imge')
plt.axis('off')
plt.show()
# 保存灰度图像
gray_pil_img.save('gray_image.jpg')

insert image description here
insert image description here

2. Histogram Statistics

Use the functions in the PIL library Image.open()to read the grayscale image and use convert('L')the method to convert the image to grayscale. Then, we get the width and height of the image, and create a list of all 0s with a length of 256 hist, which is used to save the histogram statistics.

Next, traverse each pixel, obtain its gray value, and add 1 to the corresponding histogram counter. Finally, we output the histogram statistics, i.e. the number of pixels that occur at each gray value.

# 读取灰度图像
gray_img = Image.open('gray_image.jpg').convert('L')
width, height = gray_img.size

# 统计直方图
hist = [0] * 256
for y in range(height):
    for x in range(width):
        pixel = gray_img.getpixel((x, y))
        hist[pixel] += 1
print(hist)
# 输出直方图统计结果
for i in range(len(hist)):
    print("灰度值 %d: %d 个像素" % (i, hist[i]))

insert image description here

3. Draw a histogram

# 绘制直方图
plt.bar(range(256), hist)
plt.show()

insert image description here

4. Histogram equalization

Make the picture have better visual effects and higher contrast, that is, the grayscale distribution of pixels is
more histogram()even equ_imgEach element represents the number of pixels corresponding to the gray level.

Next, we create an empty list lutto hold the grayscale mapping table. Then, by traversing equ_imgthe list, divide the number of pixels of each gray level by 255 to obtain a step size step, indicating the proportion of each gray level in the equalized histogram. Next, we define a variable n, initialized to 0, to record the number of pixels currently accumulated.

In the inner loop, we iterate through the 256 gray levels and divide the current accumulated number of pixels by the step size stepto get a map value n / step. This mapping value represents the gray level corresponding to the current gray level in the equalized histogram.

Finally, we use the method in the PIL library to map the grayscale image point()according to the mapping table lutto obtain an equalized image equ_img. Here, lutthe values ​​in the list are used as a grayscale map, and 'L'the parameter indicates that the mode of the output image is the grayscale mode.

In this way, after the histogram equalization process, the gray level distribution of the image will be more uniform, and the contrast and details of the image will be enhanced.

# 直方图均衡化
equ_img = gray_img.histogram()
lut = []
for b in range(0, len(equ_img), 256):
    step = sum(equ_img[b:b+256]) / 255
    n = 0
    for i in range(256):
        lut.append(n / step)
        n += equ_img[b+i]
equ_img = gray_img.point(lut, 'L')

# 显示原始图像和均衡化后的图像
plt.imshow(gray_img, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.show()

plt.imshow(equ_img, cmap='gray')
plt.title('Equalized Image')
plt.axis('off')
plt.show()

# 保存原始图像和均衡化后的图像
gray_img.save('Original.jpg')
equ_img.save('Equalized.jpg')

# 统计均衡化后的直方图
hist_equ = equ_img.histogram()

# 绘制均衡化前后的直方图
plt.hist(gray_img.histogram(), 256, [0, 256])
plt.title('Original Image')
plt.xlim([0, 256])
plt.show()

plt.hist(hist_equ, 256, [0, 256])
plt.title('Equalized Image')
plt.xlim([0, 256])
plt.show()

insert image description here
insert image description here
insert image description here
insert image description here

2. Adaptive histogram equalization

Adaptive Histogram Equalization (Adaptive Histogram Equalization) is a variant of histogram equalization that takes into account local differences in different regions of the image . Different from histogram equalization, adaptive histogram equalization divides the image 分成多个小块, and in 每个小块内独立地应用直方图均衡化. In this way, adaptive histogram equalization can be better 保留图像的细节,并避免过度增强噪声. Adaptive histogram equalization can 自动调整每个小块的灰度级别achieve finer image enhancement according to the local characteristics of the image.

1. Adaptive Histogram Equalization (AHE)

AHE is a local histogram equalization method, which divides the image into several small areas, and performs histogram equalization processing on each small area, thereby enhancing the contrast of the image. The core idea of ​​the algorithm is to calculate a histogram in each small region and transform it into a cumulative distribution function (CDF), and then stretch the CDF to increase the contrast. Therefore, AHE can effectively enhance the local detail information in the image.
Here, our input parameters include the original image imgand the window size window_size. First, the function iterates through each pixel to get window_sizea window of size centered on that pixel. If the window is out of bounds, the pixel is skipped. Then, compute the histogram of the window and compute its cumulative distribution function. Next, the CDF is normalized and stretched to increase the contrast of pixels within the window. Finally, put the equalized pixel values ​​back into the original image to obtain the equalized result.

# 自适应直方图均衡化(AHE)
def adaptive_histogram_equalization(img, window_size):
    # 获取图像大小
    height, width = img.shape[:2]
    # 创建一个全黑的图像
    result = np.zeros((height, width), dtype=np.uint8)
    # 遍历每个像素
    for i in range(height):
        for j in range(width):
            # 获取窗口中心点
            center_x, center_y = i + window_size // 2, j + window_size // 2
            # 如果窗口越界,则跳过
            if center_x < window_size // 2 or center_x >= height - window_size // 2 or center_y < window_size // 2 or center_y >= width - window_size // 2:
                continue
            # 获取窗口
            window = img[center_x - window_size // 2:center_x + window_size // 2 + 1, center_y - window_size // 2:center_y + window_size // 2 + 1]
            # 计算窗口的直方图
            hist, _ = np.histogram(window.ravel(), 256, [0, 256])
            # 计算累积分布函数
            cdf = hist.cumsum()
            # 归一化
            cdf_normalized = cdf * 255 / cdf[-1]
            # 将均衡化后的像素值放回原图中
            result[i][j] = cdf_normalized[img[i][j]]
    return result

2. Restricted Contrast Adaptive Histogram Equalization (CRHE)

CRHE adds contrast limitation on the basis of AHE. It does this by limiting the pixel values ​​after AHE to avoid excessively increased contrast that would cause noise. The core idea of ​​the algorithm is to first use AHE to enhance the contrast of the image, and then use the method of limiting the contrast to truncate the pixel value, so as to control the increase of the contrast.
In the code, input parameters include the original image img, window size window_size, and contrast limiting factor clip_limit. First, call the self-implemented adaptive histogram equalization function adaptive_histogram_equalizationto perform histogram equalization processing on the original image, and obtain the equalized result. Next, use functions in the OpenCV library cv2.createCLAHEto create a contrast-limited CLAHE object and process the equalized image as input.

# 限制对比度自适应直方图均衡化(CRHE)
def contrast_limited_adaptive_histogram_equalization(img, window_size, clip_limit):
    # 使用自己实现的自适应直方图均衡化
    ahe_img = adaptive_histogram_equalization(img, window_size)
    # 使用OpenCV库实现限制对比度自适应直方图均衡化
    clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=(window_size, window_size))
    result = clahe.apply(ahe_img)
    return result

3. Read pictures

# 读取图片
img = cv2.imread("image.jpg", cv2.IMREAD_GRAYSCALE)

4. Adaptive histogram equalization

First create an imgall black image of the same size as the original image ahe_resultto hold the processed result. Then, use a loop to traverse multiple window sizes, call the adaptive histogram equalization function in turn adaptive_histogram_equalizationto process the original image, and add the processed results ahe_resultto . Finally, the average value of the equalization results of multiple sizes is obtained as the final equalization result.

We used windows of different sizes, 50, 100, 150 and 200. Finally, the average of these four results is taken as the final result. This method can improve the equalization effect, because windows of different sizes can capture local detail information of different scales in the image, thereby enhancing the contrast and detail information of the image, avoiding A window that is too large or too small can have a big impact on the results.

# 自适应直方图均衡化
# 创建一个和原始图像大小相同的全零数组ahe_result,用于存储最终的自适应直方图均衡化结果

ahe_result = np.zeros_like(img)

# 遍历不同的窗口大小,从50到200,步长为50
for window_size in range(50, 201, 50):
    # 对原始图像img进行自适应直方图均衡化操作,使用当前窗口大小window_size
    ahe_img = adaptive_histogram_equalization(img, window_size)
    # 将每次处理后的图像ahe_img累加到ahe_result中
    ahe_result += ahe_img

# 将ahe_result除以4取整,得到最终的自适应直方图均衡化结果
ahe_result //= 4

5. Limit Contrast Adaptive Histogram Equalization

First create an imgall black image of the same size as the original image crhe_resultto hold the processed result. Then, use a loop to traverse multiple window sizes, sequentially call the limited contrast adaptive histogram equalization function to process the original image, and add the processed results to crhe_result. In this example, set the contrast limit factor clip_limitto 2.0.
We used windows of different sizes, 50, 100, 150 and 200. Finally, the average of these four results is taken as the final result, so as to avoid a large impact on the result by too large or too small window.

# 限制对比度自适应直方图均衡化
# 创建一个和原始图像大小相同的全零数组crhe_result,用于存储最终的限制对比度自适应直方图均衡化结果

crhe_result = np.zeros_like(img)

# 遍历不同的窗口大小,从50到200,步长为50
for window_size in range(50, 201, 50):
    # 对原始图像img进行限制对比度自适应直方图均衡化操作,使用当前窗口大小window_size和对比度限制参数2.0
    crhe_img = contrast_limited_adaptive_histogram_equalization(img, window_size, 2.0)
    # 将每次处理后的图像crhe_img累加到crhe_result中
    crhe_result += crhe_img

# 将crhe_result除以4取整,得到最终的限制对比度自适应直方图均衡化结果
crhe_result //= 4

6. Visualize the results

# 显示结果
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(12, 8))
ax[0].imshow(img, cmap='gray')
ax[0].set_title('Original1 Image')
ax[1].imshow(ahe_result, cmap='gray')
ax[1].set_title('AHE1 Image')
ax[2].imshow(crhe_result, cmap='gray')
ax[2].set_title('CRHE1 Image')
plt.show()

insert image description here

3. Comparative summary

Both histogram equalization (Histogram Equalization) and adaptive histogram equalization (Adaptive Histogram Equalization) are used 图像增强的技术for the purpose of 改善图像的对比度和视觉效果. The main difference between them is the way and locality of processing images .

Histogram equalization is one 全局way of doing it 基于整个图像的灰度直方图来调整像素的灰度值分布. Histogram equalization enhances the contrast and detail of an image by making the gray levels more evenly distributed throughout the image. It uses the cumulative distribution function to map the gray levels in the original image to a new gray range, thereby equalizing the image.

However, histogram equalization is a global approach, which does not take into account the local differences in different regions in the image. This can cause over-enhancement or loss of detail in certain areas of the image. In order to solve this problem, adaptive histogram equalization came into being.

Adaptive histogram equalization is one 局部of the best methods when processing images 会考虑到不同区域的灰度分布情况. It divides the image into many small regions and applies histogram equalization to each region independently. In this way, adaptive histogram equalization can better preserve image details and avoid over-amplification of noise.

A common variant of adaptive histogram equalization is adaptive histogram equalization (CLAHE), which uses contrast limiting in each small region to prevent excessive amplification of noise. The core idea of ​​CLAHE is to divide the image into many small blocks, then perform local histogram equalization on each small block, and crop the pixel value to limit the degree of contrast enhancement. In this way, CLAHE effectively controls the enhancement of noise while enhancing image details.

In summary, histogram equalization is a global method that enhances image contrast through the grayscale histogram of the entire image. On the other hand, adaptive histogram equalization is a local method that enhances the image by performing independent histogram equalization on small patches of the image, and controls the amplification of noise by contrast limiting .

Guess you like

Origin blog.csdn.net/weixin_51390582/article/details/132372072