Return to Snippet

Revision: 69518
at July 7, 2015 07:00 by engrhassan2k13


Initial Code
%read image
img1 = rgb2gray(imread('dino.jpg'));%use your image here
imshow(img1);

%parameter initialization for EM-Algo
temp =[];
phi1 = 0.5;
phi2 = 0.5;
u1  = 0;
u2 = 50;
sig1 = 2;
sig2 = 3;
tempimg1 = reshape(img1,1,numel(img1));
tempimg1 = double(tempimg1);
img = double (img1);


for k = 1 : 3

for i = 1 : numel(img1)
       %Expectation Step 
       prob1 =  -0.9181-reallog(sig1)-(  (( img(i)- u1 )^2)/(2*(sig1^2))  );
       prob2 =  -0.9181-reallog(sig2)-(  (( img(i)- u2 )^2)/(2*(sig2^2))  );
       
       probc1 = ( prob1*phi1 ) / ( (prob1*phi1)+ (prob2*phi2) );
       probc2 = ( prob2*phi2 )/( (prob1*phi1) + (prob2*phi2) );
       
       temp = [temp ; probc1 probc2];
    
end
       %Maximization Step

       phi1 = ( sum(temp(:,1)) )*(1/numel(img));
       phi2 = (sum(temp(:,2)))*(1/numel(img));
      
       
       u1 = ( sum((temp(:,1)').*tempimg1) )/( sum(temp(:,1)) );
       u2 = ( sum((temp(:,2)').*tempimg1) )/( sum(temp(:,2)) );
       
       var1 =   ( sum( ( (tempimg1 - u1).^2  ).*( temp(:,1)' ) ) ) / ( sum(temp(:,1)) ); 
       sig1 = sqrt(var1);
       var2 =   ( sum( ( (tempimg1 - u2).^2  ).*( temp(:,2)' ) ) ) / ( sum(temp(:,2)) );
       sig2 = sqrt(var2);
       
       temp = [];
       
end
       
%Thresholding
thresh = ((u2 + u1)/2);

for m = 1 : numel(img1)
    if img1(m) > thresh
        img1(m) = 255;
    else
        img1(m) = 0;
    end
end

figure;
imshow(img1);

Initial URL

                                

Initial Description
This code uses the Expectation Maximization algorithm for automatically thresholding an image.

Initial Title
Automatic Thresholding with Expectation Maximization Algorithm in Matlab

Initial Tags

                                

Initial Language
MatLab