直方图均衡化-Python实现
Posted focksor
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了直方图均衡化-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] = 0
# 统计各级灰度频数
for line in img:
for i in line:
counter[i] += 1
print("各级频数:", counter)
# 计算各级灰度概率
pixel_num = sum(counter.values())
for k in counter.keys():
counter[k] /= pixel_num
print("各级概率:", counter)
# 求各级累积概率
sum_probability = {}
for i in range(10):
sum_probability[i] = 0
for k in counter.keys():
if k <= i:
sum_probability[i] += counter[k]
print("累计概率:", sum_probability)
# 打印灰阶映射表
for i in sum_probability:
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)
以上是关于直方图均衡化-Python实现的主要内容,如果未能解决你的问题,请参考以下文章
python库skimage 实现图像直方图全局均衡化局部均衡化
OpenCV使用python实现限制对比度的自适应直方图均衡化
跟我学Python丨图像增强及运算:局部直方图均衡化和自动色彩均衡化处理