发布时间:2021-09-22 22:29:14编辑:run阅读(8405)
直方图匹配是指一幅图像的直方图与另一个参考(模版)图像的直方图相匹配的过程。
实现直方图匹配过程的算法:
1 计算每个图像的累积直方图
2 已知输入(将要调整的)图像中任意像素值Xi,在输出图像中通过匹配输入图像的直方图与模版图像的直方图找到对应的像素值Xj
3 已知Xi像素值的累积直方图值G(Xi),找到一个像素值Xj, 使其累积分布值H(Xj)在参照图中等于G(Xi), 即H(Xj) = G(Xi)
4 输入值Xi由Xj替代
from skimage.io import imread
from skimage.color import rgb2gray
from skimage.exposure import cumulative_distribution
import matplotlib.pylab as pylab
import numpy as np
pylab.rcParams['font.sans-serif'] = ['KaiTi']
pylab.rcParams['axes.unicode_minus'] = False
def cdf(im):
    c, b = cumulative_distribution(im)
    c = np.insert(c, 0, [0]*b[0])
    c = np.append(c, [1]*(255-b[-1]))
    return c
def hist_matching(c, c_t, im):
    pixels = np.arange(256)
    new_pixels = np.interp(c, c_t, pixels)
    im = (np.reshape(new_pixels[im.ravel()], im.shape)).astype(np.uint8)
    return im
def plot_image(image, title=''):
    pylab.title(title, size=20)
    pylab.imshow(image)
    pylab.axis('off')
pylab.gray()
im = (rgb2gray(imread(r'D:\image_processing\image4\4.jpg'))*255).astype(np.uint8)
im_t = (rgb2gray(imread(r'D:\image_processing\image4\a.jpg'))*255).astype(np.uint8)
pylab.figure(figsize=(20, 15))
pylab.subplot(2, 3, 1)
plot_image(im, '输入图像')
pylab.subplot(2, 3, 2)
plot_image(im_t, '模版图像')
c = cdf(im)
c_t = cdf(im_t)
pylab.subplot(2, 3, 3)
p = np.arange(256)
pylab.plot(p, c, 'r.-', label='输入图像')
pylab.plot(p, c_t, 'b.-', label='模版图像')
pylab.legend(prop={'size': 20})
pylab.title('累积分布函数', size=20)
im = hist_matching(c, c_t, im)
pylab.subplot(2, 3, 4)
plot_image(im, '直方图匹配的输出图像')
c1 = cdf(im)
pylab.subplot(2, 3, 5)
pylab.plot(np.arange(256), c, 'r.-', label='输入图像')
pylab.plot(np.arange(256), c_t, 'b.-', label='模版图像')
pylab.plot(np.arange(256), c1, 'g.-', label='输出图像')
pylab.legend(prop={'size': 20})
pylab.title('累积分布函数', size=20)
pylab.show()
 51256
 50693
 41291
 38112
 32573
 29476
 28338
 23200
 23166
 21495
 1568°
 2287°
 1896°
 1833°
 2148°
 1879°
 2568°
 4303°
 4157°
 2963°