繁体   English   中英

使用opencv / C ++实时保存和使用单击鼠标的坐标

[英]Saving and using the coordinates of clicked mouse on real-time using opencv/ C++

我是C ++和opencv的新手,我试图使用单击鼠标的坐标,然后使用Kalman过滤器跟踪该对象。

问题是我无法在实时视频中访问单击对象的鼠标的x和y坐标。

有很多代码显示了如何执行此操作,但对我没有用。

这是我的代码:

void CallBackFunc(int event, int x, int y, int flags, void* leftCoordinate){
   Point *p = (Point*) leftCoordinate;
   if  ( event == EVENT_LBUTTONDOWN )
   {
        cout << "Left button position (" << x << ", " << y << ")" << endl;
        p->x = x;
        p->y = y;
        cout << "this is the pointer  : " << *p << endl;
   }
}

int main(int argc, const char** argv )
{
        // Getting the video here

        Point TestP;
        setMouseCallback("Original", CallBackFunc, &TestP);

        cout << "The coordinates : x = " << TestP.x << " y = " << TestP.y << endl;
}

问题是,TestP始终为空,我需要在main中使用x和y坐标。

我非常感谢您的帮助。 谢谢

似乎您的主要功能将在您单击图像之前退出。 仅当调用回调(即单击图像)时, TestP才会更改。 您可能无法像在示例中所示在主函数中显示它,因为在更新坐标之前已到达函数的末尾。

在您的代码中,您没有显示任何imshowwaitKey imshow对捕获鼠标事件至关重要,而需要waitKey来刷新事件队列。

要在OpenCV中使用鼠标回调,通常更容易使用全局变量。 我知道,通常这不是一个好习惯,但是在这种情况下,它可以很好地工作并使事情变得更容易。 请记住,OpenCV的HighGui模块并不意味着建立一个全功能的图形用户界面,但基本上只是为了帮助调试。 如果需要完整的GUI,则应依赖Qt之类的GUI库。

看一下这段代码。 它将打印出单击的点坐标,并在视频流中显示最后单击的坐标:

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;

Mat frame;
Point pt(-1,-1);
bool newCoords = false;

void mouse_callback(int  event, int  x, int  y, int  flag, void *param)
{
    if (event == EVENT_LBUTTONDOWN)
    {
        // Store point coordinates
        pt.x = x;
        pt.y = y;
        newCoords = true;
    }
}

int main(int, char**)
{
    VideoCapture cap(0); // open the default camera
    if (!cap.isOpened())  // check if we succeeded
        return -1;

    Mat edges;
    namedWindow("img", 1);

    // Set callback
    setMouseCallback("img", mouse_callback);

    for (;;)
    {
        cap >> frame; // get a new frame from camera

        // Show last point clicked, if valid
        if (pt.x != -1 && pt.y != -1)
        {
            circle(frame, pt, 3, Scalar(0, 0, 255));

            if (newCoords)
            {
                std::cout << "Clicked coordinates: " << pt << std::endl;
                newCoords = false;
            }
        }

        imshow("img", frame);

        // Exit if 'q' is pressed
        if ((waitKey(1) & 0xFF) == 'q') break;
    }
    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM