[英]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
才會更改。 您可能無法像在示例中所示在主函數中顯示它,因為在更新坐標之前已到達函數的末尾。
在您的代碼中,您沒有顯示任何imshow
或waitKey
。 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.