# Basic Object Counting in Images

by 4hathacker  |  in Image Processing at  8:32 PM

Hello...!!!

During image analysis, many a times it will be required to count the number of objects present in that image. Its an easy task for large or medium sized objects if present in the images. But what if the objects were very tiny or microscopic in size?

In that case, counting of objects becomes a tedious and error prone process for human beings. Therefore, we need suitable algorithms which can count for humans the number of objects present in the image. Repetitive counting for large data sets provides us accuracy and less error using image processing algorithms.

In this article, a gentle introduction to algorithmic approach using morphological operations is discussed for counting of image objects. The example images used here were taken from databases at www.imageprocessingplace.com or DIPUM tutorials.

To count the objects in a test image, load the test image using imread(). The test image loaded should be converted to grayscale from RGB color space. This was the most important step for approching the image analysis because it has less complexity for coding, luminance and intensity information only and good way for learners to grasp. Colors have their importance but it depends on the requirement and algorithm.

figure, imshow(A), title('Original image')               % showing original image
I = rgb2gray(A);                                             % coins.jpg is rgb while rice.jpg is already in grayscale
I = imclearborder(I);
I = wiener2(I,[5 5]);                                       % Adaptive Wiener filtering to overcome noise
bw = im2bw(I, graythresh(I));
figure, imshow(bw), title('BW image')
bw2 = imfill(bw, 'holes');
bw3 = imopen(bw2, strel('disk',2));
bw4 = bwareaopen(bw3, 100);                     % only used if connected components are present
bw4_perim = bwperim(bw4);
figure, imshow(bw4_perim), title('bw4_perim')
[L, num] = bwlabel(bw4_perim);
disp(['Number of objects detected: ' num2str(num)]);    % shows count = 10 for coins and 52 for rice

After that, proper adjustments were made to the contrast level using adapthisteq(). Objects on borders were the cause of noise and other problems. They were eliminated using imclearborder(). To overcome noise, some adaptive filtering techniques like Weiner Filtering using 5X5 or 3X3 windows were equally important. Then, automatic thresholding using Otsu's Method was done, for too small objects. Some sort of opening and closing operations were performed as per the requirement if objects were connected too close to each other. Visualisation of perimeter of objects would be helpful in distinguishing different object boundaries and finally lead to the counting using bwlabel().

The examples discussed in the article were the easiest examples to grasp the basics of object counting in images. Later some different examples will be entertained in the upcoming posts.