均衡化
H= imread('001.png');
%判断是否为三通道彩色图片 若是 则将其灰度化
if length(size(H))>2
H=rgb2gray(H);
end
%获取图片的尺寸 便于计算总像素数 即m*n
[m,n]=size(H);
%生成一个一行256列的矩阵
p=zeros(1,256);
% 统计各灰度的像素个数
%find(H==i) 是在图像矩阵里面寻找灰度为i的点坐标
% 因为矩阵是从1开始的 所以为p(i+1)
for i=0:255
p(i+1)=length(find(H==i))/(m*n);
end
% 累加概率值,当前CDF=前一CDF+当前PDF
s=zeros(1,256);
s(1)=p(1);
for i=2:256
s(i)=p(i)+s(i-1);
end
%对s中的数先乘以255,再取整
a=round(s*255);
b=H;
%更新原图像的灰度
for i=0:255
b(H==i)=a(i+1);
end
subplot(2,2,1);
imshow(H);
title('原图');
subplot(2,2,2);
% 显示原图的直方图
imhist(H);
title('原图直方图');
subplot(2,2,3);
imshow(b)
title('均衡化后图像');
subplot(2,2,4);
imhist(b);
title('均衡化后的直方图');
规定化,也叫直方图匹配
%灰度图直方图匹配matlab(不使用histeq)
clear
im = imread('original.bmp');
imRef = imread('reference.jpg');
hist = imhist(im); % Compute histograms
histRef = imhist(imRef);
cdf = cumsum(hist) / numel(im); % Compute CDFs
cdfRef = cumsum(histRef) / numel(imRef);
% Compute the mapping
M = zeros(1,256);
for idx = 1 : 256
[tmp,ind] = min(abs(cdf(idx) - cdfRef));
M(idx) = ind-1;
end
% Now apply the mapping to get first image to make
% the image look like the distribution of the second image
imMatch = M(double(im)+1);
figure;%显示原图像、匹配图像和匹配后的图像
subplot(1,3,1),imshow(im,[]);title('原图像');
subplot(1,3,2),imshow(imRef,[]);title('匹配图像');
subplot(1,3,3),imshow(imMatch,[]);title('匹配之后图像');
figure;%显示原图像、匹配图像和匹配后图像的直方图
subplot(3,1,1),imhist(im,64);title('原图像直方图');
subplot(3,1,2),imhist(imRef,64);title('匹配图像直方图');
subplot(3,1,3),imhist(uint8(imMatch),64);title('匹配之后图像直方图');