-
作业要求
编写一个图像直方图均衡化程序,g=histequal4e(I),其中I是8比特图像 -
代码
'''
# 8th
编写一个图像直方图均衡化程序,g=histequal4e(I),其中I是8比特图像
'''
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
#einstein.tif
#lena512color.jpg
# mandril_color.jpg
src = Image.open("mandril_color.jpg").convert('L') # 转换成灰度
src = np.array(src)
#print(src)
src_dim_1 = src.flatten() # 变成一维,用于绘制直方图
# 直方图均衡化函数
def histequal4e(img):
src_size = src.shape
img_dim_1 = img.flatten()
pixel_num = len(img_dim_1)
eq_img = np.zeros(src_size) # 创建画布
index_set = np.zeros(256,dtype=int) # 0-255 全零索引 用于存储对应灰度值的个数
sum_index_set = np.zeros(256,dtype=int) # 0-255 全零索引 用于存储对应灰度值的个数
# 统计频率
for i in range(pixel_num):
index_set[img_dim_1[i]] = index_set[img_dim_1[i]] + 1
# 求和
for h in range(len(index_set)):
sum_index_set[h] = sum_index_set[h-1] + index_set[h]
sum_index_set = list(map(int,sum_index_set/max(sum_index_set)*255))
#print("sumindex",sum_index_set)
# 画布赋值
for m in range(src_size[0]):
for n in range(src_size[1]):
eq_img[m][n] = sum_index_set[img[m][n]]
return eq_img
eq_img = histequal4e(src)
eq_dim_1 = eq_img.flatten()
# 显示灰度图
plt.subplot(221), plt.imshow(src, 'gray'), plt.title('Src')
plt.axis('off')
plt.subplot(222), plt.imshow(eq_img, 'gray'), plt.title('EqImg')
plt.axis('off')
plt.subplot(223)
plt.title('SrcImg Hist')
n, bins, patches = plt.hist(src_dim_1 , bins=256, density=0, edgecolor='black', alpha=1, histtype='bar')
plt.subplot(224)
plt.title('EqImg Hist')
n, bins, patches = plt.hist(eq_dim_1 , bins=256, density=0, edgecolor='black', alpha=1, histtype='bar')
'''
plt.text(212,208, "Src Hist", size=10, rotation=0.,ha="right", va="top",bbox=dict(boxstyle="square",ec=(1., 0.5, 0.5),fc=(0.2, 0.8, 0.8),))
plt.text(265,5626, "EqImg Hist", size=10, rotation=0.,ha="right", va="top",bbox=dict(boxstyle="square",ec=(1., 0.5, 0.5),fc=(0.2, 0.8, 0.8),))
plt.draw()
'''
plt.show()
# Liu Yaohua - 2019.10.31 in UCAS
来源:CSDN
作者:LuckyANTenna
链接:https://blog.csdn.net/m0_38139098/article/details/104748349