1 计算原理
和AutomaticContrastAdjustment相似,目的是将图像的一定范围内的灰度
[
a
^
l
o
w
,
a
^
h
i
g
h
]
[\hat{a}_{low}, \hat{a}_{high}]
[a^low,a^high]映射(map)到区间
[
a
m
i
n
,
a
m
a
x
]
[a_{min}, a_{max}]
[amin,amax],如下图示:
- 首先计算分位数
a
^
l
o
w
\hat{a}_{low}
a^low和
a
^
h
i
g
h
\hat{a}_{high}
a^high:
a ^ l o w = m i n { i ∣ H ( i ) ≥ H W s l o w } \hat{a}_{low} = min\{ i | H(i) \geq HWs_{low}\} a^low=min{i∣H(i)≥HWslow}
a ^ h i g h = m a x { i ∣ H ( i ) ≤ H W ( 1 − s h i g h ) } \hat{a}_{high} = max\{ i | H(i) \leq HW(1 - s_{high})\} a^high=max{i∣H(i)≤HW(1−shigh)}
其中, s l o w s_{low} slow和 s h i g h s_{high} shigh人为给定。 - 然后,记某像素点的值为p,对各像素点做以下操作:
f ( p ) = { a m i n p < a ^ l o w a m i n + ( p − a ^ l o w ) ∗ a m a x − a m i n a ^ h i g h − a ^ l o w a ^ l o w ≤ p ≤ a ^ h i g h a m a x p > a ^ h i g h f(p) = \begin{cases} a_{min} & {p < \hat{a}_{low}}\\ a_{min} + (p - \hat{a}_{low})*\dfrac{a_{max} - a_{min}}{\hat{a}_{high} - \hat{a}_{low}} & {\hat{a}_{low} \leq p \leq \hat{a}_{high}}\\ a_{max} & {p > \hat{a}_{high}} \end{cases} f(p)=⎩⎪⎪⎨⎪⎪⎧aminamin+(p−a^low)∗a^high−a^lowamax−aminamaxp<a^lowa^low≤p≤a^highp>a^high
2 代码实现
%------------------------------------%
% %
% modified contrast adjustment %
% %
%------------------------------------%
%% 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,2,1);
imshow(orgIMG);
title('Original img');
subplot(1,2,2);
imhist(orgIMG);
orgHist = imhist(orgIMG);
axis([0 255 0 1400]);
title('Histogram of the original img');
%% Doing automatic contrast adjustment
% Define parameters
a_min = 0; % a_min <- 0~a_max
a_max = 255; % a_max <- a_min~255
s_low = 0.01;
s_high = 0.02;
a_low_hat = 0;
a_high_hat = 0;
% calculating a_low_hat
for i = 1:256
if a_low_hat > w*h*s_low
a_low_hat = i-1;
break;
else
a_low_hat = a_low_hat + orgHist(i);
end
end
% calculating a_high_hat
for i = 1:256
if a_high_hat > w*h*(1-s_high)
a_high_hat = i-1;
break;
else
a_high_hat = a_high_hat + orgHist(i);
end
end
smaller = find(orgIMG < a_low_hat);
orgIMG(smaller) = a_min;
larger = find(orgIMG > a_high_hat);
orgIMG(larger) = a_max;
newIMG = double(orgIMG);
newIMG = uint8(a_min + (newIMG-a_low_hat).*(a_max-a_min)/(a_high_hat-a_low_hat));
figure(2);
subplot(1,2,1);
imshow(newIMG);
title('Modified img');
subplot(1,2,2);
imhist(newIMG);
axis([0 255 0 1400]);
title('Histogram of the modified img');
3 效果展示
原图:
处理后:
4 源码下载
源码下载地址:点击此处