【发布时间】:2020-10-03 06:14:11
【问题描述】:
以下代码在鼠标单击时返回x,y 坐标的值。我想将 x 坐标存储在一个数组 a[10] 中,将 y 坐标存储在另一个数组 b[10] 中。
为此,我尝试使用 for 循环,但 x,y 坐标未显示在数组中。
如何将这些坐标存储在数组中?
我想在图像上单击鼠标 10 次,我想将所有 10 个坐标存储在数组中。在我的代码中,当我单击鼠标一次时,这个 x,y 坐标存储在数组中 10 次。
#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
using namespace cv;
using namespace std;
int i;int x;int y;
int a[10];int b[10];
void CallBackFunc(int event, int x, int y, int flags, void* userdata);
int main(int argc, char** argv)
{
// Read image from file
Mat img = imread("G:/qt-program/CA2.jpg");
//Create a window
namedWindow("My Window", 1);
//set the callback function for any mouse event
setMouseCallback("My Window", CallBackFunc, NULL);
//show the image
imshow("My Window", img);
// Wait until user press some key
waitKey(0);
return 0;
}
void CallBackFunc(int event, int x, int y, int flags, void* userdata)
{
if ( event == EVENT_LBUTTONDOWN )
{
cout << "Left button of the mouse is clicked - position (" << x << ", " << y << ")" << endl;
for ( i = 0; i < 10; ++i){
a[i]=x;
b[i]=y;
}
for ( i = 0; i < 10; ++i){
cout << a[i] << endl;
cout << b[i] << endl;
}
}
}
【问题讨论】:
-
您将当前 x 和 y 存储到数组中的所有单元格中,但您需要存储在下一个单元格中。您可以为数组中下一个单元格的索引创建全局变量。
-
所以当鼠标点击时这个函数会被调用。单击时鼠标的位置将是一个点,比如说(x,y),您正在运行一个循环 10 次以将相同的 x 和 y 存储在您的数组中。
-
我想在图像上单击鼠标 10 次,我想将所有 10 个坐标存储在数组中。在我的代码中,当我单击鼠标一次时,这个 x,y 坐标存储在数组中 10 次.