Ask Your Question
0

Get mean coordinates of active pixels

asked 2016-05-25 12:59:28 -0600

I would like to retrieve the mean coordinates of pixels in a binary image/mat which are not 0. Is there an existing way of doing this in OpenCV?

Regards, Rupert

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2016-05-25 13:27:15 -0600

updated 2016-05-25 14:26:18 -0600

You could use image moments for that: http://docs.opencv.org/2.4/modules/im...

EDIT : begging @FooBar 's indulgence, i add a sample code

@sturkmen

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

using namespace cv;

Point getCentroid( InputArray Points )
{
    Point Coord;
    Moments mm = moments( Points, false );
    double moment10 = mm.m10;
    double moment01 = mm.m01;
    double moment00 = mm.m00;
    Coord.x = int(moment10 / moment00);
    Coord.y = int(moment01 / moment00);
    return Coord;
}

int main( int argc, char* argv[] )
{
    Mat src = imread( argv[1] );

    Mat gray;
    cvtColor( src, gray, CV_BGR2GRAY );
    gray = gray > 127;

    Mat nonzeropixels;
    findNonZero( gray, nonzeropixels );

    Point pt = getCentroid( nonzeropixels );
    rectangle(src, pt,pt, Scalar(0, 255, 0), 2);

    imshow("result",src);
    waitKey();

    return 0;
}

test image and result image ( green dot is centroid of white blobs )

image description image description

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2016-05-25 12:59:28 -0600

Seen: 1,097 times

Last updated: May 25 '16