Simple contrast adjustment

5 views (last 30 days)
David
David on 1 Feb 2012
Edited: DGM on 9 Nov 2022
I'd like to do a simple contrast adjustment of a grayscale image. For values less than 70 it has to be black, otherwise apply a slope function.
function image_out=Equalization(image_in)
im2=im2uint8(image_in);
[sx,sy]=size(im2);
image_out=im2uint8(im2);
for x=1:sx
for y=1:sy;
if im2(x,y) < 70
image_out(x,y)=0;
else
pixel=round(1 ./ (0.9 ./ im2(x,y)));
image_out(x,y)= pixel;
end
end
end
end
The values resulting from the slope function are always 1, what I am doing wrong?

Answers (1)

DGM
DGM on 9 Nov 2022
Edited: DGM on 9 Nov 2022
If you're working with uint8, then all the pixel values are within [0 255]. The moment you try to do 0.9/im2(x,y), you end up with a small number less than 1, rounded to the nearest integer. Unless you're taking care with intermediate calculations and avoiding issues with mixed variable classes, it's probably simplest to just do the math in a floating point class.
You could simplify the arithmetic to fix the problem ...
% observe the behavior of the function in uint8-scale
inpict = im2uint8(linspace(0,1,100));
outpict = Equalization_0(inpict);
plot(inpict,outpict); grid on
xlim([0 255]); ylim([0 255]);
function image_out = Equalization_0(image_in)
% these parameters should probably be made externally configurable
th = 70;
slope = 1/0.9;
im2 = im2uint8(image_in);
[sy,sx,~] = size(im2); % array coordinates are [y x]
image_out = zeros(sy,sx,'uint8');
for y = 1:sy
for x = 1:sx
if im2(y,x) < th
image_out(y,x) = 0;
else
% simplify the arithmetic
% explicit rounding is unnecessary
image_out(y,x) = slope*im2(y,x);
end
end
end
end
... but I doubt that's expected either. You probably intended something more like this.
image_out(y,x) = slope*(im2(y,x) - th); % this line needs to be offset!
Of course, this whole thing could be greatly simplified. None of the loops are necessary at all, and there are basic considerations that should be made as well.
% observe the behavior of the function in uint8-scale
inpict = im2uint8(linspace(0,1,100));
th = 70/255;
slope = 1/0.9;
outpict = Equalization_1(inpict,th,slope);
plot(inpict,outpict); grid on
xlim([0 255]); ylim([0 255]);
function image_out = Equalization_1(image_in,th,slope) % parameters are adjustable!
% perform contrast operation
image_out = slope*(im2double(image_in)-th);
% clamp data to standard range!
image_out = max(min(image_out,1),0);
% if you really want the output to always be uint8
image_out = im2uint8(image_out);
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!