如何将 x.y 坐标的值存储在不同的数组中
how to store values of x.y coordinates in different arrays
下面的代码在鼠标单击时返回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;
}
}
相关文章:
- 多维数组存储三种不同的数据类型?
- C++将原始字符数组存储在元组中
- 将十六进制字符数组存储在字节数组中,而无需更改为 ASCII 或其他任何东西
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- 如何将元素的索引从2D数组存储到1D数组中,然后交换这些值
- 如何将JSON数组存储在Arduino程序中
- 如何在AVR(例如:ATMega)或Arduino微控制器上制作2D PROGMEM阵列的1D PROGMEM数组(存储
- 使用 char 数组存储数据
- 使用平面数组存储的元组容器
- 数组 存储并要求用户搜索它
- 将值从一个 char 数组存储到另一个 char 数组
- 如何使字符串数组存储在向量中
- 将构造的静态数组存储在多个文件中的内存中
- 将整数数组存储在堆上并通过指针访问它们
- c++声明一个数据类型的字节数组,该数组存储在字符串中
- 使用指针数组存储阶乘计算的所有中间结果
- 使用异构数组存储不同的子类
- 读取文件内容,存储在数组中,向数组添加更多内容,然后将新数组存储在文件C++中
- 尝试将复杂数组存储到类 c++ 中
- 在字节数组存储中嵌入 int/string