Object Counting – Image Processing

Thanks to Malinda Vania for finding all the functions used here.
Added some documentation to make further development easier.

function object_count(imgfile)
img = imread(imgfile);

% Converts RGB image to B&W
imgbw = im2bw(img);

%============== Filters image ===============%
for a = 1 : 6
  imgbw = medfilt2(imgbw);
end

%============= Counts objects ===============%
% Detects all object bounds (edges) in image,
% including hole bounds.
totalbound = bwboundaries(imgbw, 'holes');

% Detects all object bounds, excluding hole bounds.
objectcount = bwboundaries(imgbw, 'noholes');

% Outputs the result.
total_objects = size(objectcount, 1)
hole_objects = size(totalbound, 1) - size(objectcount, 1)
solid_objects = size(objectcount, 1) - hole_objects

%============= Image Labeling ===============%
L = bwlabel(imgbw, 8);

%============= Euler numbers ================%
s = regionprops(L, 'EulerNumber');
fprintf('Object NumbertEuler NumbertDescriptionn');
for i = 1 : total_objects
  fprintf('%dtttt%dtttt', i, s(i).EulerNumber);
  if (s(i).EulerNumber == 1) fprintf('solidn');
  else fprintf('holedn');
  end
end

%=========== Colorizes the regions ==========%
% Takes the pixels
PxList = regionprops(L, 'PixelList');

% Converts B&W image to RGB.
imgRGB = uint8(zeros(size(imgbw, 1), size(imgbw, 2), 3));

% For each object, do
for i = 1 : total_objects

  % Takes pixel list of this object
  plist = PxList(i).PixelList;

  % If the region has a hole
  if (s(i).EulerNumber == 0)
    % For each pixels
    for j = 1 : size(plist, 1)
        % Colorizes it with red
        imgRGB(plist(j, 2), plist(j, 1), 1) = 255;
    end

  % If the region has no hole
  else
    % For each pixels
    for j = 1 : size(plist, 1)
        % Colorizes it with green
        imgRGB(plist(j, 2), plist(j, 1), 2) = 255;
    end
  end
end

%=========== Displays the result ===========%
figure('Name', 'Membedakan Objek Padat dan Berlubang', 'NumberTitle', 'off');
subplot(1, 2, 1), imshow(img), title('Citra Asli');
subplot(1, 2, 2), imshow(imgRGB), title('Citra Hasil');

5 thoughts on “Object Counting – Image Processing”

  1. …. lupa komen trus… fotomu kok sok imut ngono… XD

    ty for the documentation, help me understand the script a lot..

    文君

  2. tim,

    I’m sorry I forgot to mention that this script is a Matlab script. Have you typed and execute it correctly? What type of error did you get when running it?
    I’m not that good at Matlab myself. I may not be able to solve your problem, but I’ll try.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.