Search code examples
algorithmmultidimensional-arrayneighbours

How to find the number of blobs in a 2d matrix?


How can I find the number of blobs in a 2d matrix? SIZE MxN

A blob is a block of continuous X pixels. where the matrix contains X and O

XOOOXO
OXOXOX
XXOOXO

I would like to use 8-neighbourship (see here). So I would expect 2 blobs to be found in above example.


Solution

  • The idea is simple: Mark each continuous blob and count how many blobs were marked.

    Here is some pseudo-code (you did not specify a programming language) to get you started:

    numBlobs = 0;
    foreach(item in matrix)
    {
        res = Visit(item);
        if(res > 0) 
        {
            numBlobs = numBlobs + 1;
        }
    }
    return numBlobs;
    

    The Visit function/method looks like this:

    Visit(item)
    {
        marked = 0;
        if(item.IsX() && !IsItemMarked(neighbour))
        {
            MarkItemAsVisited(item);
            marked = 1;
            foreach(neighbour in GetNeighbours(item))
            {
                marked = marked + Visit(neighbour);
            }
        }
        return marked;
    }
    

    All you have to do is to implement the other fucntions/methods but they are pretty straightforward.