为什么包装 setMouseCallback 会导致 Mat 对象为空
Why does wrapping setMouseCallback cause Mat object to be empty?
我不明白为什么包装setMouseCallback
会导致onMouse
中的Mat
对象为空,而直接在main
中调用setMouseCallback
则不然。
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
void onMouse(int event, int x, int y, int flags, void* param)
{
Mat* image = reinterpret_cast<Mat*>(param);
if (image->empty())
cout << "The image is empty." << endl;
}
void Wrapper(Mat input)
{
setMouseCallback("Input Window", onMouse, reinterpret_cast<void*>(&input));
}
int main()
{
Mat input = imread("filename.jpg", IMREAD_UNCHANGED);
namedWindow("Input Window", WINDOW_NORMAL);
imshow("Input Window", input);
// Wrapper(input); // A
//setMouseCallback("Input Window", onMouse, reinterpret_cast<void*>(&input)); //B
waitKey(0);
}
编辑
亚历克西斯·威尔克(Alexis Wilke(回答中的推理是有道理的,但可能不是100%正确的。在下面的代码中,我包装了整个代码,这样就不需要Mat
传递给Wrapper
但问题仍然存在。那么是什么原因造成的呢?
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
void onMouse(int event, int x, int y, int flags, void* param)
{
Mat* image = reinterpret_cast<Mat*>(param);
if (image->empty())
cout << "The image is empty." << endl;
}
void Wrapper()
{
Mat input = imread("filename.jpg", IMREAD_UNCHANGED);
namedWindow("Input Window", WINDOW_NORMAL);
imshow("Input Window", input);
setMouseCallback("Input Window", onMouse, reinterpret_cast<void*>(&input));
}
int main()
{
Wrapper();
waitKey(0);
}
你的意思是用引用值声明Wrapper()
,而不是通过复制来声明值:
void Wrapper(Mat & input)
{
setMouseCallback("Input Window", onMouse, reinterpret_cast<void*>(&input));
}
查看附加&
?
如果没有&
,您将传递一份input
的副本,并且您的原始副本不会被修改。
Mat input;
Wrapper(input); // without the `&`, input is copied and whatever happens
// to the copy is not known by the caller
您也可以使用指针:
void Wrapper(Mat * input)
虽然我怀疑你正在使用引用来避免指针。
原因未知
,但以下解决了问题!
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
void onMouse(int event, int x, int y, int flags, void* param)
{
Mat* image = reinterpret_cast<Mat*>(param);
if (image->empty())
cout << "The image is empty." << endl;
}
void Wrapper()
{
Mat input = imread("filename.jpg", IMREAD_UNCHANGED);
namedWindow("Input Window", WINDOW_NORMAL);
imshow("Input Window", input);
setMouseCallback("Input Window", onMouse, reinterpret_cast<void*>(&input));
waitKey(0);
}
int main()
{
Wrapper();
}
相关文章:
- 如何将 cv::mat 对象从 python 模块传递到 c++ 函数并返回返回的 cv::mat 类型为对象?
- OpenCV Otsu的阈值:计算多个Mat对象的单个阈值
- 当我更改其他 Mat 对象时,垫子值会更改
- 无法在类中分配 cv::Mat 对象C++
- 将 Mat 对象C++传递给 Unity
- 为什么包装 setMouseCallback 会导致 Mat 对象为空
- OpenCV Mat对象复制速度更快
- 在cv::Mat对象上循环时,内存位置出现cv::异常
- OpenCV-C++中Mat对象的平均值
- OpenCV格式化程序类和Mat对象的cout产生链接器错误:体系结构x86_64的未定义符号:libopencv_co
- 如何从XML文件(OpenCV)将一定数量的行读入Mat对象
- 在 Java 客户端中创建 Mat 对象,使用 opencv 从C++服务器发送
- 通过套接字将 Mat 对象从 c++ 发送到 Java
- 为什么OpenCV Mat对象在嵌套for循环中指定了预期值后却不包含这些值
- 如何将像素设置为cv::Mat对象中的值
- 将Mat对象从androidjava传递到本机cpp部分
- I'm试图将像素数据转换为OpenCV Mat对象
- 如何在Android中从文件中读取OpenCV Mat对象
- Zeros Mat 对象具有除零以外的一些值
- 如何调整空的 cv::Mat 对象