2013-02-13 20 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