
// This scilab code is used to perform image segmentation using Otsu Thresholding method 

//The scilab environment for this is : Scilab 6.0.1

//Toolbox used: Image Processing and Computer Vision Toolbox ver. 1.1
              

//OS used : Windows 10 64 bit
// 
//Reference book name : Digital Image Processing
//book author: Rafael C. Gonzalez and Richard E. Woods

//clc //to clear command window.
//clear all //to kill previously defined variables.
//xdel(winsid())//to close all currently open figure(s).

//This code uses harewood.jpg image file for processing
//clc;
//clear all;
//I=imread('nutsBolts.jpg');
I=imread('harewood.jpg');                   // Reads input image
//I=rgb2gray(I);

Ihist=imhist(I);                            // Calculate histogram
Ihist=Ihist';                               // Transpose the histogram output
s=length(I);                                // Calculates Total number of pixels
t=0:255;                                    // set counter t as 0 to 255
sumA=0.0;                                   // Initialize the sum variable
for t=1:256                                 // Calculate sum of pixels in histogram output
    sumA = sumA+ t*Ihist(t);
end
sumB = 0;                                   // Initialize another variable as summation
wB = 0;                                     // Initialize weight background variable
wF = 0;                                     // Initialize weight foreground variable
varMax = 0;                                 // Initialize maximum value for threshold
threshold = 0;                              // Initialize threshold to zero


// This for block calucates threshold using Otsu Thresholding method
for t=1:256
   wB = wB + Ihist(t);               // Weight Background
   if (wB == 0) 
       continue;
   end
   wF = s - wB;                 // Weight Foreground
   if (wF == 0) 
       break;
   end
   sumB = sumB + (t * Ihist(t));
   mB = sumB / wB;            // Mean Background
   mF = (sumA - sumB) / wF;    // Mean Foreground
   // Calculate Between Class Variance
   varBetween = wB * wF * (mB - mF) * (mB - mF);
   // Check if new maximum found
   if (varBetween > varMax)
      varMax = varBetween;
      threshold = t;
   end
end
//n=(threshold - max(I))/ (max(I)-min(I));
R=im2bw(I,threshold/256);                       // Binarize image with given threshold
imshow(R);                                      // Show resultant binarized image
//
