Today I will talk about two algorithms for counting the number of objects in the image. This topic is intended primarily for those who are just beginning to engage in image processing. For professionals, I will not say anything new.
In the process of high-level image processing, the task of counting the number of objects often arises. Of course, it can be solved with the help of the algorithm of recursive tagging of regions (the method of marks).
mark ( dot, label )
Start
if (the point does not belong to the background and is not marked ) then
Start
assign a label to a point ( point, label ) ;
mark (a point above, a label ) ;
mark ( dot below, label ) ;
mark ( dot to the left, label ) ;
mark ( dot to the right, label ) ;
end
end
The above algorithm must be applied to each pixel of the original image, changing the label after each object found. After executing the algorithm, the number of objects will be equal to the number of labels used.
This algorithm allows not only to count the number of objects, but also to separate them from each other. It is easy to see that this algorithm uses recursion, which means that we have two potential problems. First, the speed of the algorithm may be insufficient for processing data in real time, and secondly, we may potentially lack the stack size, especially if we are talking about the implementation of this algorithm in hardware (FPGA).
The second method of counting objects is based on calculating the difference between the number of external and internal angles. The outer corner is a neighborhood of 2 * 2 pixels containing three pixels of the background and one pixel of the object, the inner corner is a neighborhood of 2 * 2 pixels containing three pixels of the object and one pixel of the background.
External corner patterns:

Interior corner patterns:

The number of objects in the image is calculated as a quarter of the difference in the number of external and internal angles.
The resources required to run this algorithm are minimal. In the software implementation, a single pass through the entire image is required, while in the hardware implementation, only two counters are additionally required.
It is important to understand that this algorithm works correctly only if there are no background pixels inside the object. Such pixels are called “pepper” noise and are easily eliminated by the methods of mathematical morphology.
And as always, you can
download a program that implements the described algorithms :

PS If the topic is interesting, I can write a topic about the implementation of image processing algorithms on FPGAs.