function results = HistogramMatching(I1,I2)
[h1,w1] = size(I1);
[h2,w2] = size(I2);
histI1 = imhist(I1)/(h1*w1);
histI2 = imhist(I2)/(h2*w2);
s1=zeros(1,256);
s1(1)=histI1(1);
s2=zeros(1,256);
s2(1)=histI2(1);
% 求原图图均衡的映射表,比如原图中像素值为100的点在新图中对应的像素值是多少
for index = 2:256
s1(index) = s1(index-1) + histI1(index);
end
% 求匹配图均衡的映射表
for index = 2:256
s2(index) = s2(index-1) + histI2(index);
end
M = zeros(1,256);
for i = 1 : 256
[~,pix] = min(abs(s1(i) - s2));%匹配图均衡化后距离该像素最近的那个像素的对应的原像素
M(i) = pix-1;%最终的映射表
end
results = M(double(I1)+1);
results = uint8(results);
end
I1,I2为灰度图像
效果如下: