直方图均衡化处理(python代码),pycharm中matplotlib显示灰度图像的颜色不对

直方图均衡化算法

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
# 直方图均衡化
def histeq(imarr):
    hist, bins = np.histogram(imarr, 255)
    cdf = np.cumsum(hist)
    cdf = 255 * (cdf / cdf[-1])
    res = np.interp(imarr.flatten(), bins[:-1], cdf)
    res = res.reshape(imarr.shape)
    return res, hist


img = Image.open("E:/pythontupian/6.jpg")
gray_image = img.convert('L')
gray_arr = np.array(gray_image)

plt.imshow(Image.fromarray(gray_arr),cmap='gray')
plt.axis("off")
plt.show()

plt.hist(gray_arr.flatten(), 256)  # flatten可以将矩阵转化成一维序列
plt.show()

res, hist = histeq(gray_arr)
plt.imshow(Image.fromarray(res))
plt.axis("off")
plt.show()

plt.hist(res.flatten(), 256)  # flatten可以将矩阵转化成一维序列
plt.show()

结果显示

原始灰度图:
在这里插入图片描述
原始灰度图的直方图:
在这里插入图片描述
均衡化后灰度图:
在这里插入图片描述
均衡化后的直方图:

在这里插入图片描述
使用plt.imshow()显示的时候要注意,设置cmap参数为‘gray’,如果不用的话可能会出现下面的错误:
在这里插入图片描述
具体原因可以了解一下cmap的用法。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值