Question

I'm interested in finding the coordinates (X,Y) for my whole, entire binary image, and not the CoM for each component seperatly. How can I make it efficiently? I guess using regionprops, but couldn't find the correct way to do so.

Was it helpful?

Solution

You can define all regions as a single region for regionprops

props = regionprops( double( BW ), 'Centroid' ); 

According to the data type of BW regionprops decides whether it should label each connected component as a different region or treat all non-zeros as a single region with several components.


Alternatively, you can compute the centroid by yourself

[y x] = find( BW );
cent = [mean(x) mean(y)];

OTHER TIPS

Just iterate over all the pixels calculate the average of their X and Y coordinate

void centerOfMass (int[][] image, int imageWidth, int imageHeight)
{
    int SumX = 0;
    int SumY = 0;
    int num  = 0; 
    for (int i=0; i<imageWidth; i++)
    {
        for (int j=0; j<imageHeight; j++)
        {
            if (image[i][j] == WHITE)
            {
               SumX = SumX + i;
               SumY = SumY + j; 
               num = num+1;
            }
        }
    }

    SumX = SumX / num;
    SumY = SumY / num;
    // The coordinate (SumX,SumY) is the center of the image mass
}

Extending this method to gray scale images in range of [0..255]: Instead of

if (image[i][j] == WHITE)
                {
                   SumX = SumX + i;
                   SumY = SumY + j; 
                   num = num+1;
                }

Use the following calculation

SumX = SumX + i*image[i][j];
SumY = SumY + j*image[i][j]; 
num = num+image[i][j];

In this case a pixel of value 100 has 100 times higher weight than dark pixel with value 1, so dark pixels contribute a rather small fraction to the center of mass calculation. Please note that in this case, if your image is large you might hit a 32 bits integer overflow so in that case use long int sumX, sumY variables instead of int.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top