opencv彩色图像直方图均衡化算法实现

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

彩色图像直方图均衡化的主要步骤和灰度直方图均衡化的步骤一样,区别就在于彩色图像需要分别计算BGR三个通道.

import cv2
import numpy as np

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

count_b = np.zeros(256, np.float) # 因为是概率, 有可能是浮点数
count_g = np.zeros(256, np.float)
count_r = np.zeros(256, np.float)


# 统计像素个数并计算概率
for i in range(height):
    for j in range(width):
        (b, g, r) = img[i, j]

        index_b = int(b)
        index_g = int(g)
        index_r = int(r)

        count_b[index_b] = count_b[index_b] + 1
        count_g[index_g] = count_g[index_g] + 1
        count_r[index_r] = count_r[index_r] + 1

total = height * width # 总像素个数
count_b =  count_b / total  # 计算概率
count_g =  count_g / total
count_r =  count_r / total

# 计算累计概率
sum_b = sum_g = sum_r = float(0)
for i in range(256):
    sum_b += count_b[i]
    count_b[i] = sum_b # 计算出累积概率

    sum_g += count_g[i]
    count_g[i] = sum_g

    sum_r += count_r[i]
    count_r[i] = sum_r

# 计算映射表
mapl_b = np.uint16(255 * count_b)
mapl_g = np.uint16(255 * count_g)
mapl_r = np.uint16(255 * count_r)

# 将图像进行映射
dst = np.zeros((height, width, 3), np.uint8)
for i in range(height):
    for j in range(width):
        (b, g, r) = img[i, j]
        b = mapl_b[b]
        g = mapl_g[g]
        r = mapl_r[r]

        dst[i, j] = (b, g, r)

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

原图如下:
原图像
直方图均衡化之后的图像:
直方图均衡化过后

猜你喜欢

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