1 计算原理
通过直方图均衡,可以将图像像素的直方图(PDF)调整为均匀分布(uniform distribution),如图示:
其中,
h
(
i
)
h(i)
h(i)为图像的直方图(PDF),
H
(
i
)
为
图
像
的
累
计
直
方
图
(
C
D
F
)
H(i)为图像的累计直方图(CDF)
H(i)为图像的累计直方图(CDF)
记某像素点的值为p,对各像素点做以下操作:
f
(
p
)
=
⌊
H
(
p
)
K
−
1
H
W
+
0.5
⌋
f(p) = \lfloor H(p)\dfrac{K - 1}{HW} + 0.5 \rfloor
f(p)=⌊H(p)HWK−1+0.5⌋
其中H为图像高,W为图像宽,K为灰度等级(256);0.5为四舍五入,也可以不加。
2 代码实现
%% Generating an image with limited gray scale
% define the size of the image with 256*256
w = 256;
h = 256;
orgIMG = uint8(normrnd(128,20,[256,256]));
% uint8: 0~255 -> 0~255
% mat2gray: 0~255 -> 0~1 (0~255/255)
figure(1);
subplot(1,3,1);
imshow(orgIMG);
title('Original img');
subplot(1,3,2);
imhist(orgIMG);
orgHist = imhist(orgIMG);
axis([0 255 0 1400]);
title('Histogram of the original img (~PDF)');
subplot(1,3,3);
orgHistSum = zeros([1 255]);
for i = 1:256
orgHistSum(i) = sum(orgHist(1:i));
end
% Remove the match caps
h1 = stem(0:255,orgHistSum);
h1.Marker = 'none';
title('Accumulative Histogram of the original img (~CDF)');
%% Doing linear histogram equalization
newIMG = double(orgIMG);
newIMG = uint8(floor(orgHistSum(newIMG).*(255/(w*h))+0.5));
figure(2);
subplot(1,3,1);
imshow(newIMG);
title('Modified img');
subplot(1,3,2);
imhist(newIMG);
newHist = imhist(newIMG);
axis([0 255 0 1400]);
title('Histogram of the modified img (~PDF)');
subplot(1,3,3);
newHistSum = zeros([1 255]);
for i = 1:256
newHistSum(i) = sum(newHist(1:i));
end
h2 = stem(0:255,newHistSum);
h2.Marker = 'none';
title('Accumulative Histogram of the modified img (~CDF)');
3 效果展示
原图:
处理后:
4 源码下载
源码下载地址:点击此处