function auto_objects(img_name,output_name) % AUTO_OBJECTS utility % % Used to segment objects in a black background image. % usage is auto_objects(image_name,output_filename) % % By Yan Levasseur, ETS 2004 % yan AT leyan DOT org % Verifying number of inputs if(nargin ~=2) error('Incorrect number of inputs : usage is ''auto_objects(img_name,output_name)'''); end % Reading the image from file img = imread(img_name); [Height,Width,Bands] = size(img); % Computing graythreshold value level = graythresh(img); level = level * 0.6; % Threshold arbitrary adjustment (after a few tries) % This can be modified for your need % Computing a binary image as the result of thresholding bw = im2bw(img,level); % Creating labels for the image's regions lab = bwlabel(bw); % Computing statistics of all of the image's regions stats = regionprops(lab,'Area','BoundingBox','FilledImage'); % Fixed minimum area to be considered object area_min = 500; % This can be modified for your need count = 1; % For each of the objects in 'stats' for i=1:length(stats) if(stats(i).Area > area_min) % Objects with small area are discarded % Segementing the object in RGB image % BoundingBox contains the objects' coordinates BB = stats(i).BoundingBox; corner_x = ceil(BB(1)); length_x = BB(3); corner_y = ceil(BB(2)); length_y = BB(4); % We use the FilledImage to get the entire object even if % there are holes or segmented regions inside the objects' contour FI = stats(i).FilledImage; % Final image size final=zeros(length_y,length_x); % Copying the object from orininal image into another image for j=1:Bands final(:,:,j) = double(FI).*double(img(corner_y : corner_y + length_y - 1, ... corner_x : corner_x + length_x - 1,j)); end % Return in a image compatible type final = uint8(final); % Computing the image's number (name) no = '000'; chiffre = sprintf('%i',count); lc = length(chiffre); no(4-lc:3)=chiffre; fichier = sprintf('%s%s.bmp',output_name,no); % Write the image to 'bmp' format image file imwrite(final,fichier,'bmp'); % You can change format here % Little code to print '.' for each object processed fprintf('.',fichier); if(mod(count,20)==0) fprintf('\n'); end % Here we count the number of object count = count+1; end end % Print of the total number of objects processed fprintf('\n%i objects have been written to files.\n',count-1); % End of function return