如何使用opencv检测实时Feed中的鼠标点击

时间:2015-10-09 18:58:25

标签: c++ callback opencv3.0

我是Opencv的新手,我正在调试一个简单的程序,可以在摄像机的实时流上使用setMouseCallback函数计算鼠标点击的数量和位置,但是一旦程序启动,它就会被击中并且由于鼠标移动而不是点击,鼠标点击的位置和数量会更新。我在下面包括我的程序,如果有人指出错误并为我提供上述程序的解决方案,我将不胜感激。

#include "opencv2\highgui.hpp"
#include "opencv2\core.hpp"
#include "opencv2\imgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;

#define window "LiveFeed"
Mat frame;

void cbmouse(int event, int x, int y, int flags, void*userdata)
{
    static int count = 0;
    char text[] = "count999";
    if (event = EVENT_LBUTTONDOWN)
    {
        while (1)
        {
            circle(frame, Point(x, y), 4, Scalar(0, 0, 255), 2);
            count++;
            sprintf(text, "count%d", count);
            putText(frame, text, Point(x + 5, y + 2), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 0), 2);
            imshow(window, frame);
            if (waitKey(33) == 27)
            break;
        }
    }
    return;
}

int main(int argc, char*argv[])
{
    VideoCapture video(0);
    namedWindow(window);
    while (1)
    {
        video >> frame;
        imshow(window, frame);
        setMouseCallback(window, cbmouse, NULL);
        if (waitKey(33) == 27)
            break;
    }
}

1 个答案:

答案 0 :(得分:0)

也许您只需要更正if (event == EVENT_LBUTTONDOWN)

但我做了一些改进。请尝试以下代码。(我不确定,您是否要在首次点击时冻结实时Feed?)

#include "opencv2\highgui.hpp"
#include "opencv2\core.hpp"
#include "opencv2\imgproc.hpp"

using namespace cv;
using namespace std;

#define window "LiveFeed"
Mat frame;

vector<Point> pts;

void drawClickedPoints( Mat img )
{

    for(size_t i = 0; i < pts.size(); i++)
    {
        circle(img, pts[i], 4, Scalar(0, 0, 255), 2);
        putText(frame, format("count%d", i), Point(pts[i].x + 5, pts[i].y + 2), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 0), 2);
    }

}
void cbmouse(int event, int x, int y, int flags, void*userdata)
{
    if (event == EVENT_LBUTTONDOWN)
    {
        pts.push_back(Point(x,y));
    }
}

int main(int argc, char*argv[])
{
    VideoCapture video(0);
    namedWindow(window);
    setMouseCallback(window, cbmouse, NULL);
    while (1)
    {
        video >> frame;
        drawClickedPoints(frame);
        imshow(window, frame);
        if (waitKey(33) == 27)
            break;
    }
}