Python图像处理(二)【直方图均衡化】
1.直方图均衡化
获取图片及显示图片的通用方法如下:
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
#获取图片
def getimg():
return Image.open("f:/pic/timg.jpg")
#显示图片
def showimg(img, isgray=False):
plt.axis("off")
if isgray == True:
plt.imshow(img, cmap='gray')
else:
plt.imshow(img)
plt.show()
直方图均衡化方法
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
1.1.灰度图像均衡化
img = getimg()
gray_image = img.convert('L')
gray_arr = np.array(gray_image)
res,hist = histeq(gray_arr)
showimg(Image.fromarray(res))
1.2.彩色图像均衡化
1.2.1.合并RGB三通道像素的直方图均衡化
def rgb_histeq1(im):
imarr = np.array(im)
imarr2 = imarr.flatten()
hist, bins = np.histogram(imarr2, 255)
cdf = np.cumsum(hist)
cdf = 255* (cdf/cdf[-1])
imarr3 = np.interp(imarr2, bins[:-1], cdf)
imarr3 = imarr3.reshape(imarr.shape)
return Image.fromarray(imarr3.astype('uint8'), mode='RGB')
img2 = rgb_histeq1(img)
showimg(img2)
1.2.2.RGB三通道各自均衡化
def rgb_histeq2(im):
imarr = np.array(im)
r_arr = imarr[...,0]
g_arr = imarr[...,1]
b_arr = imarr[...,2]
r_res, r_hist = histeq(r_arr)
g_res, g_hist = histeq(g_arr)
b_res, b_hist = histeq(b_arr)
new_imarr = np.zeros(imarr.shape, dtype='uint8')
new_imarr[...,0] = r_res
new_imarr[...,1] = g_res
new_imarr[...,2] = b_res
return Image.fromarray(new_imarr, mode='RGB')
img = getimg()
img3 = rgb_histeq2(img)
showimg(img3)
1.2.3.取RGB三通道像素平均值的直方图均衡化
def rgb_histeq3(im):
imarr = np.array(im)
r_arr = imarr[...,0]
g_arr = imarr[...,1]
b_arr = imarr[...,2]
#取三个通道的平均值
imarr2 = np.average(imarr, axis=2)
hist, bins = np.histogram(imarr2, 255)
cdf = np.cumsum(hist)
cdf = 255 * (cdf/cdf[-1])
r_res = np.interp(r_arr, bins[:-1], cdf)
g_res = np.interp(g_arr, bins[:-1], cdf)
b_res = np.interp(b_arr, bins[:-1], cdf)
new_imarr = np.zeros(imarr.shape, dtype="uint8")
new_imarr[...,0] = r_res
new_imarr[...,1] = g_res
new_imarr[...,2] = b_res
return Image.fromarray(new_imarr, mode='RGB')
img = getimg()
img4 = rgb_histeq3(img)
showimg(img4)