本文用MATLAB实现直方图匹配,程序如下:
clear;
% matching dst‘s histogram to src‘s histogram.
path = ‘C:\Users\admin\Desktop\HDRdataset\Oneplus\rgb\0726\18\‘;
src = imread([path, ‘172.jpg‘]);
dst = imread([path, ‘173.jpg‘]);
% figure; imshow(src); title(‘src‘);
% figure; imshow(dst); title(‘dst‘);
[H, W, colorChannel] = size(src);
out = zeros(H, W, colorChannel);
figure; set(gcf,‘Position‘,[100,100,800,800], ‘color‘,‘w‘); %原点的位置x,原点的位置y,宽,高,其坐标为points
for k = 1: colorChannel
disp(k);
hist_src = imhist(src(:, :, k));
subplot(3, 3, 1 + 3*(k-1));
plot(hist_src); title([‘hist of src ‘, num2str(k)]);
cumHist_src = []; %src的累积直方图
for i=1:256
cumHist_src = [cumHist_src sum(hist_src(1:i))];
end
dst1 = dst(:, :, k);
hist_dst = imhist(dst1); %dst的直方图
subplot(3, 3, 2 + 3*(k-1));
plot(hist_dst); title([‘hist of dst ‘, num2str(k)]);
cumHist_dts = []; %dst的累积直方图
for i=1:256
cumHist_dts = [cumHist_dts sum(hist_dst(1:i))];
end
for i=1:256
tmp{i} = cumHist_src - cumHist_dts(i);
tmp{i} = abs(tmp{i});
[a, index(i)] = min(tmp{i}); %找到两个累积直方图距离最近的点
end
imgn = zeros(H,W);
for i = 1:H
for j = 1:W
imgn(i,j) = index(dst1(i,j)+1)-1; %由原图的灰度通过索引映射到新的灰度
end
end
subplot(3, 3, 3 + 3*(k-1));
plot(imhist(imgn)); title([‘hist of new ‘, num2str(k)]); %新图的直方图
out(:, :, k) = imgn;
end
out=uint8(out);
imwrite(out, [path, ‘new.jpg‘]);
% figure; imshow(out); title(‘out‘)
disp(‘Done‘);
原文:https://www.cnblogs.com/picassooo/p/11504937.html