I'm teaching myself OpenCV and wrote the following code today to track a ball rolling across my computer webcam feed and (attempt to) draw a filled in grey circle on to it's centroid:
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
Point getBlobCentroid(Mat blobImage);
int main()
{
Mat bGround, fGround, diff;
Point p = (500, 280);
VideoCapture cap(0);
while (true)
{
cap >> fGround; //assign frame from camera to newest image
cvtColor(fGround, fGround, CV_BGR2GRAY); //convert to grayscale
bGround.create(fGround.size(), fGround.type());
absdiff(bGround, fGround, diff); //subtract current frame from old frame
threshold(diff, diff, 50, 255, CV_THRESH_BINARY); //convert to binary
erode(diff, diff, NULL, Point(-1,-1), 3, 0, BORDER_DEFAULT);
imshow("Thresholded", diff);
circle(fGround, getBlobCentroid(diff), 6, 127, -1, 8, 16);
imshow("Natural Image with Tracking", fGround);
fGround.copyTo(bGround); //move forward in time
waitKey(1);
}
return 0;
}
Point getBlobCentroid(Mat blobImage)
{
int rowSum=0, colSum=0, count = 1;
for(int i=0; i<blobImage.rows; i++)
{
for (int j=0; j<blobImage.cols; j++)
{
if (blobImage.at<uchar>(i,j) == 255)
{
rowSum+=i;
colSum+=j;
count++;
}
}
}
Point centroid = (rowSum, colSum)/count;
return centroid;
}
However, as evidenced by the attached image - the circle never moves away from the top of the screen - in other words, the centroid.y component is always zero. I wrote a bunch of steps of the calculation to the screen, and it appears as though the searching and additions to rowSum and count and such work - those are nonzero. However, as soon as you calculate the centroid or call it in the circle, that's a no go. Even weirder, I tried making a constant center for the circle Point p = (285, 285) and using that as an argument, and that was a no go as well. Help? Thanks!
-Tony