# 作者:喵酱
# 开发时间:2022/4/16 13:32
"""导入需要用的python库"""
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
plt.rcParams['font.sans-serif'] = ['FangSong'] # 设置字体以便正确显示中文
def get_pdf(img):
"""获取图像的概率密度"""
N = img.shape[0] * img.shape[1] # 计算图像总像素个数
return [np.sum(img == i)/N for i in range(256)] # 计算概率密度
def hist_equal(in_img):
"""直方图均衡"""
pdf = get_pdf(in_img) # 获取图像的概率密度
out_img = np.copy(in_img) # 构造输出图像
sum_n = 0 # 存储相同像素值的像素个数
for i in range(256):
sum_n = sum_n + pdf[i]
out_img[(in_img == i)] = sum_n*255
return out_img
img = np.asarray(Image.open('la.tif')) # 读入原图
img2 = hist_equal(img) # 对原图直方图均衡化
# 显示图像
plt.subplot(221)
plt.title('原始图像')
plt.imshow(img, cmap='gray')
plt.subplot(222)
plt.title('原图灰度直方图')
plt.hist(img) # 绘制直方图
plt.subplot(223)
plt.title('直方图均衡化图像')
plt.imshow(img2, cmap='gray')
plt.subplot(224)
plt.title('直方图均衡化后图像的灰度直方图')
plt.hist(img2) # 绘制直方图
plt.show()