python直方图均衡_Python实现图像直方图均衡化算法

效果图

代码

#!/usr/bin/env python3

# coding=utf-8

import matplotlib.image as mpimg

from matplotlib import pyplot as plt

import sys

import numpy as np

def equalization(gray_value):

"""

传入灰度值,对灰度值做均衡化,不需要返回,直接修改传入的参数

:param gray_value:

"""

# 统计灰度直方图

gray = np.zeros(256)

row, column = gray_value.shape

for i in range(row):

for j in range(column):

gray[gray_value[i][j]] += 1

# 计算灰度占比

gray /= (row * column)

# 显示灰度直方图

plt.subplot(2, 2, 2)

plt.plot(gray)

cumsum = np.cumsum(gray) # 计算累积和

# 均衡化

# equa_t[i]=j表示原灰度值i经过均衡化后转化为灰度值j

# 255×累积和四舍五入为int型

equa_t = np.array((255 * cumsum + 0.5)).astype(np.int32)

# 统计均衡化后的灰度数量

equa_gray = np.zeros(256)

for i in range(256):

equa_gray[equa_t[i]] += gray[i]

# 显示均衡化后的直方图

plt.subplot(2, 2, 4)

plt.plot(equa_gray)

# 对原灰度矩阵做均衡化

for i in range(row):

for j in range(column):

gray_value[i][j] = equa_t[gray_value[i][j]]

def run(img_path):

img_array = mpimg.imread(img_path)

plt.subplot(2, 2, 1)

plt.imshow(img_array)

img_array *= 255

img_array = img_array.astype(np.int32)

equalization(img_array[:, :, 0])

equalization(img_array[:, :, 1])

equalization(img_array[:, :, 2])

img_array = img_array.astype(np.float64)

img_array /= 255

plt.subplot(2, 2, 3)

plt.imshow(img_array)

if __name__ == "__main__":

if sys.argv.__len__() <= 1:

png = input("请输入要处理的图片名:\n")

else:

png = sys.argv[1]

run(png)

plt.show()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值