opencv灰度图像直方图均衡化算法实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/missyougoon/article/details/81775251

灰度图像直方图均衡化,主要步骤:
1. 计算每一个灰度级的概率
2. 计算每一个灰度级的累计概率
3. 计算映射表
4. 将图像像素值通过映射表进行映射
对于直方图均衡化原理,参考博文:直方图均衡化原理
代码实现如下:

import cv2
import numpy as np

img = cv2.imread('image0.jpg', 1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('src', gray)
count = np.zeros(256, np.float) # 因为是概率, 有可能是浮点数

# 统计像素个数并计算概率
for i in range(height):
    for j in range(width):
        pixel = gray[i, j]
        index = int(pixel)
        count[index] = count[index] + 1

total = height * width # 总像素个数
count =  count / total  # 计算概率
# 计算累计概率
sum = float(0)
for i in range(256):
    sum += count[i]
    count[i] = sum # 计算出累积概率

# 计算映射表
mapl = np.uint16(255 * count)

# 将图像进行映射
for i in range(height):
    for j in range(width):
        pixel = gray[i, j]
        gray[i, j] = mapl[pixel]


cv2.imshow('dst', gray)
cv2.waitKey(0)

原图如下:
灰度图像直方图均衡化原图
灰度图像直方图均衡化后效果如下:
灰度图像直方图均衡化效果图

猜你喜欢

转载自blog.csdn.net/missyougoon/article/details/81775251