【发布时间】:2013-02-14 04:22:24
【问题描述】:
我正在自学 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 和 count 的搜索和添加等工作 - 这些都是非零的。但是,一旦您计算出质心或在圆圈中调用它,那就不行了。更奇怪的是,我尝试为圆点 p = (285, 285) 制作一个恒定的中心并将其用作参数,这也是不行的。帮助?谢谢!
-托尼
【问题讨论】: