如何将 x.y 坐标的值存储在不同的数组中

how to store values of x.y coordinates in different arrays

本文关键字:数组 存储 坐标      更新时间:2023-10-16

下面的代码在鼠标单击时返回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;
}
}

}

评论很好地解释了你的问题。如果您需要确切的解决方案,只需将CallBackFunc()功能替换为以下内容:

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;                
a[i]=x;
b[i]=y;
i++;
if(i==10)        
for ( i = 0; i < 10; ++i){
cout << a[i] << endl;
cout << b[i] << endl;
}        
}    
}

上面的函数显示 a[i] 和 b[i] 像这样- 单击鼠标左键 - 位置 (45, 187( 单击鼠标左键 - 位置 (103, 98( 单击鼠标左键 - 位置 (228, 33( 单击鼠标左键 - 位置 (397, 54( 单击鼠标左键 - 位置 (479, 117( 单击鼠标左键 - 位置 (523, 189( 45 187 103 98 228 33 397 54 479 117 523 189
但我需要 a[i] ={45,103,228,397,479,523} 和 b[i]={187,98,33,54,117,189} ,两种模式相同吗?

您将当前的 x 和 y 存储到数组中的所有单元格中,但您需要存储在下一个单元格中。您可以为数组中下一个单元格的索引创建全局变量,即执行类似操作(伪代码(

int a[10]();
int b[10]();
int nextInd = 0;
...
CallBack(event, x, y, ...) {
if (...) {
if (nextInd >= 10) nextInd=0;
a[nextInd] = x;
b[nextInd++] = y;
} 
}