Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Ok, can you guarantee they are above a certain size? Can you guarantee that they are distinct and well separated, like they are in that image? Then it's easy.

  • Take your mask, and do a morphological Close. This will fill in a lot of the holes in the boxes. The idea is to make each of them one connected blob. It doesn't look like any of them are split, but it's not impossible with the noise I see in that image.
  • Perform Connected Components. Now you have another mask, with numeric labels.
  • Get rid of any below an appropriate size. Just a guess, but 10x10 bounding box should cover it.
  • Count remaining. Either do the above twice, once on red and once on blue, or compare your final results with the individual ones.

If you have a red and a blue touching, you should do it twice, to separate the two when you do connected components.

Note: If you do connectedcomponentswithstats, you get the bounding box and area as a return value and you don't even need to look at the map.

If the assumptions don't hold, it gets more complicated, but based on your sample image, this should work. If you need it to run really fast, there are possibly some shortcuts to take. But this is a good start, see if it works.