【问题标题】:OpenCV Drawing a circle to track a ball issueOpenCV绘制一个圆圈来跟踪一个球问题
【发布时间】: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) 制作一个恒定的中心并将其用作参数,这也是不行的。帮助?谢谢!

-托尼

【问题讨论】:

    标签: c++ opencv


    【解决方案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
    

    【讨论】:

    • 不确定这是问题所在,因为算法工作正常(至少看起来如此) - 我想我记得读过 Mat::create() 只覆盖数据,如果不是已经一样了 - 一旦我第一次将 fGround 复制到 bGround , create() 语句会再做任何事情吗?无论如何, bGround 必须具有相同的大小和类型,否则您不能在它们上使用 absdiff。有没有更好的办法?
    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2013-09-20
    • 1970-01-01
    • 2013-12-02
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多