2013-02-13 19 views
1

我在教自己OpenCV,今天写了下面的代码来跟踪一个滚过我的计算机摄像头feed的球并且(尝试)在它的质心上绘制一个填充的灰色圆圈: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)建立一个不变的中心,并用它作为参数,那也是不行的。帮帮我?谢谢!

托尼

回答

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 
+0

不知道这就是问题所在,因为算法是否正常工作(至少它似乎是) - 我想我还记得读取垫::创建()仅覆盖数据和如果它不是相同的 - 一旦我第一次将fGround复制到bGround时,create()语句是否会执行任何操作?无论如何,bGround必须是相同的尺寸和类型,否则你不能使用absdiff。有更好的方法吗? – TonyRo 2013-02-14 16:21:25