Hi all,
I am trying to find the centroid of a blob using openCV.
Well i did it, but centroid doesn’t seem to be where expected !
(see uploaded picture)
here is my code
in update() : solution 1 - find center of blob box area
if(kinect.isFrameNew())
{
// load grayscale depth image from the kinect source
grayImage.setFromPixels(kinect.getDepthPixels(), kinect.width, kinect.height);
grayImage.mirror(false, true);
flippedDepthImg = grayImage;
// we do two thresholds - one for the far plane and one for the near plane
// we then do a cvAnd to get the pixels which are a union of the two thresholds
grayThreshNear = grayImage;
grayThreshFar = grayImage;
grayThreshNear.threshold(nearThreshold, true);
grayThreshFar.threshold(farThreshold);
cvAnd(grayThreshNear.getCvImage(), grayThreshFar.getCvImage(), grayImage.getCvImage(), NULL);
}
// update the cv images
grayImage.flagImageChanged();
// find contours
contourFinder.findContours(grayImage, 50, (kinect.width*kinect.height)/2, 5, false);
if (contourFinder.nBlobs > 0)
{
// SOLUTION 1
ofRectangle bRect = contourFinder.blobs.at(0).boundingRect;
pos.x = bRect.x + (bRect.width / 2);
pos.y = bRect.y + (bRect.height / 2);
// END SOLUTION 1
}
in update() : solution 2 - using centroid() method
if(kinect.isFrameNew())
{
// load grayscale depth image from the kinect source
grayImage.setFromPixels(kinect.getDepthPixels(), kinect.width, kinect.height);
grayImage.mirror(false, true);
flippedDepthImg = grayImage;
// we do two thresholds - one for the far plane and one for the near plane
// we then do a cvAnd to get the pixels which are a union of the two thresholds
grayThreshNear = grayImage;
grayThreshFar = grayImage;
grayThreshNear.threshold(nearThreshold, true);
grayThreshFar.threshold(farThreshold);
cvAnd(grayThreshNear.getCvImage(), grayThreshFar.getCvImage(), grayImage.getCvImage(), NULL);
}
// update the cv images
grayImage.flagImageChanged();
// find contours
contourFinder.findContours(grayImage, 50, (kinect.width*kinect.height)/2, 5, false);
if (contourFinder.nBlobs > 0)
{
// SOLUTION 2
pos = contourFinder.blobs.at(0).centroid;
// END SOLUTION 2
}
in draw() :
void ofApp::draw()
{
ofSetColor(255, 255, 255);
flippedDepthImg.draw(10, 10, 497, 369);
contourFinder.draw(10, 10, 497, 369);
ofSetColor(255, 0, 0);
ofEllipse(pos, 5, 5);
}
Red dot in the picture is the centroid.
In either the first or second solution, centroid is in the same place.
isn’t the centroid supposed to be in the center of the box ?
I am using oF 0.8.3 on mac + xcode 5
Thanks for your help