我正在自学OpenCV,并且今天编写了以下代码,用于跟踪球在我的计算机网络摄像头中滚动,并(尝试)在其质心上绘制一个填充的灰色圆圈:
#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;
}
然而,正如所附图像所证明的那样 - 圆圈永远不会从屏幕顶部移开 - 换句话说,centroid.y组件始终为零。我在屏幕上写了一堆计算步骤,看起来好像是对rowSum的搜索和添加以及计数和这样的工作 - 这些都是非零的。但是,只要你计算出质心或在圆圈中调用它,那就不行了。甚至更奇怪,我试图为圆点P =(285,285)创建一个恒定的中心并将其用作参数,这也是一个不行的。救命?谢谢!
托尼
答案 0 :(得分:1)
fGround.copyTo(bGround); //move forward in time
// so, that's your idea. compare bg & fg, get the centroid of the diff.
// but then, if you follow your while loop there, (waitkey, back to the top ... )
bGround.create(fGround.size(), fGround.type());
// aww, so you're never using, what you copied before
absdiff(bGround, fGround, diff);
// so, in the end, you're always comparing fGround to an empty bGround img