Thursday, March 24, 2016

How to apply Threshold to an image in MATLAB ?

Exercise: Apply thresholding to the original image such that r1= r2=mean gray level. Display the result. (Hint: use built-in function im2bw.)

 CODE:

clc; clear all;

%% Reading an image
a1=imread('contrast.jpg');
a=double(a1);
[row,col]=size(a);

%% Calculating mean gray level
sum = 0;
for i=1:row
    for j=1:col
        sum=sum+a(i,j);
    end
end
avg=sum/(row*col);

%% Transformation function
t=0:255;
x1=0*(t>=0 & t<avg); 
x2=255*(t>=avg & t<=255);
x=x1+x2;

%% Obtaining contrast stretched image
for n=1:row
    for m=1:col
        out(n,m)=x(a1(n,m)+1);
    end
end

out1=im2bw(a1);

plot(x)
grid on;
xlabel('Intensity in input image');
ylabel('Intensity in output image')
title('Transformation function')

figure()
subplot(311), imshow(a1), title('Original image')
subplot(312), imshow(uint8(out)), title('Thresholding(using code)')
subplot(313), imshow(out1), title('Thresholding(using im2bw)')


OUTPUT RESULT:


Transformation Function

No comments:

Post a Comment