直方图均衡化-Python实现

需要均衡的图像

将下面的图像进行直方图均衡

1 3 9 9 8
2 1 3 7 3
3 6 0 6 4
6 8 2 0 5
2 9 2 6 0

均衡化计算过程

使用python进行直方图均衡化:

# -*- coding: utf-8 -*-

# @Time    : 2020/3/7 23:30
# @Author  : focksor
# @Email   : focksor@outlook.com

# 原始图像
img = [
    [1, 3, 9, 9, 8],
    [2, 1, 3, 7, 3],
    [3, 6, 0, 6, 4],
    [6, 8, 2, 0, 5],
    [2, 9, 2, 6, 0],
]


counter = {}

# 统计各级灰度频数
for i in range(10):
    counter[i] = [i for line in img for i in line].count(i)
print("各级频数:", counter)

# 计算各级灰度概率
pixel_num = sum(counter.values())
for k in counter.keys():
    counter[k] /= pixel_num
print("各级概率:", counter)

# 求各级累积概率
sum_probability = {}
for k in counter.keys():
    print(k, [counter[i] for i in counter.keys() if i <= k])
    sum_probability[k] = sum([counter[i] for i in counter.keys() if i <= k])
print("累计概率:", sum_probability)

# 打印灰阶映射表
for i in sum_probability.keys():
    sum_probability[i] = round(sum_probability[i] * 9)
print("映射到灰阶:")
for i in range(10):
    print(i, "->", sum_probability[i])

# 将原图像中的灰阶映射到均衡后的灰阶
for i, line in enumerate(img):
    for j, pixel in enumerate(line):
        img[i][j] = sum_probability[img[i][j]]
print("均衡化后图像:")
for line in img:
    print(line)

各级频数: {0: 3, 1: 2, 2: 4, 3: 4, 4: 1, 5: 1, 6: 4, 7: 1, 8: 2, 9: 3}
各级概率: {0: 0.12, 1: 0.08, 2: 0.16, 3: 0.16, 4: 0.04, 5: 0.04, 6: 0.16, 7: 0.04, 8: 0.08, 9: 0.12}
累计概率: {0: 0.12, 1: 0.2, 2: 0.36, 3: 0.52, 4: 0.56, 5: 0.6000000000000001, 6: 0.7600000000000001, 7: 0.8000000000000002, 8: 0.8800000000000001, 9: 1.0}
映射到灰阶:
0 -> 1
1 -> 2
2 -> 3
3 -> 5
4 -> 5
5 -> 5
6 -> 7
7 -> 7
8 -> 8
9 -> 9
均衡化后图像:
[2, 5, 9, 9, 8]
[3, 2, 5, 7, 5]
[5, 7, 1, 7, 5]
[7, 8, 3, 1, 5]
[3, 9, 3, 7, 1]

posted @ 2020-03-12 16:59  focksor  阅读(758)  评论(0编辑  收藏