图像处理——手动实现直方图均衡化

实现目标:

手动实现直方图均衡化,使用了部分常见函数,具体步骤都做了注释。


代码如下:

"""
Created on 2023/3/20 09:52
@author: liuwenq
实验一_空间域图像增强方法_直方图均衡化:遍历图像每个像素的灰度,算出每个灰度的概率(n/MN-n是每个灰度的个数,MN是像素总数),用L-1乘以所得概率得到新的灰度
"""
import cv2
import imutils
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")

# 图像获取和处理
img = cv2.imread('E:/12.PNG')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  

# 直方图统计
def pix_gray(img_gray):
    h = img_gray.shape[0]  #读取矩阵第一维度的长度
    w = img_gray.shape[1]  #读取矩阵第二维度的长度
    gray_level = np.zeros(256)
    gray_level2 = np.zeros(256)

    for i in range(1, h - 1):
        for j in range(1, w - 1):
            gray_level[img_gray[i, j]] += 1  # 统计灰度级为img_gray[i,j]的个数

    for i in range(1, 256):
        gray_level2[i] = gray_level2[i - 1] + gray_level[i]  # 统计灰度级小于img_gray[i,j]的个数
    print(gray_level)
    return gray_level2

# 直方图均衡化
def hist_gray(img_gary):
    h, w = img_gary.shape
    print(h)
    print(w)
    gray_level2 = pix_gray(img_gray)
    print(gray_level2)
    lut = np.zeros(256)
    for i in range(256):
        lut[i] = 255.0 / (h * w) * gray_level2[i]  # 得到新的灰度级
    lut = np.uint8(lut + 0.5)
    print(lut)
    out = cv2.LUT(img_gray, lut)
    return out

result_img = hist_gray(img_gray)
#输出结果
cv2.imshow('origin img', imutils.resize(img_gray,400))
cv2.imshow('result img', imutils.resize(result_img,400))

#输出直方图
source_hist = cv2.calcHist([img_gray],[0],None,[256],[0,256])   #原始灰度图的直方图
equ_hist=cv2.calcHist([result_img],[0],None,[256],[0,256])  #均衡化后的直方图
fig=plt.figure()
ax1=fig.add_subplot(1,2,1)
ax1.plot(source_hist)
ax2=fig.add_subplot(1,2,2)
ax2.plot(equ_hist)
plt.show()

if cv2.waitKey(0)==27:
    cv2.destroyAllWindows()

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值