Posted By

engrhassan2k13 on 07/07/15

Automatic Thresholding with Expectation Maximization Algorithm in Matlab

/ Published in: MatLab

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

`%read imageimg1 = rgb2gray(imread('dino.jpg'));%use your image hereimshow(img1); %parameter initialization for EM-Algotemp =[];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 %Thresholdingthresh = ((u2 + u1)/2); for m = 1 : numel(img1)    if img1(m) > thresh        img1(m) = 255;    else        img1(m) = 0;    endend figure;imshow(img1);`