【问题标题】:Assertion failed when OutputArray::create() run in thread当 OutputArray::create() 在线程中运行时断言失败
【发布时间】:2020-02-18 06:05:52
【问题描述】:
#include <iostream>
#include <opencv2/opencv.hpp>
#include <thread>

using namespace std;
using namespace cv;

void testThread(OutputArray image){
    image.create(100,32,CV_8U);
}
// void testThread(Mat image){
//     image.create(100,32,CV_8U);
// }
// void testThread(Mat& image){
//     image.create(100,32,CV_8U);
// }
int main(int argc,char** argv){
    Mat left= imread("./left.png",CV_8U);
    Mat right=imread("./right.png",CV_8U) ;

    thread t1(testThread,left);
    thread t2(testThread,right);
    t1.join();
    t2.join();

    // testThread(left);
    // testThread(right);

    return 0;
}

为什么串行执行正常,并行抛出异常? 此外,如果您将 testThread 的原型更改为第二个原型,它也会在并行中正常执行,但第三个原型会失败。 打印到控制台的异常信息如下:

OpenCV(3.4.1) Error: Assertion failed (!fixedSize() || ((Mat*)obj)->size.operator()() == Size(_cols, _rows)) in create, file /home/linjiaqin/software/opencv-3.4.1/modules/core/src/matrix_wrap.cpp, line 1240
terminate called after throwing an instance of 'cv::Exception'
  what():  OpenCV(3.4.1) /home/linjiaqin/software/opencv-3.4.1/modules/core/src/matrix_wrap.cpp:1240: error: (-215) !fixedSize() || ((Mat*)obj)->size.operator()() == Size(_cols, _rows) in function create

【问题讨论】:

  • 对不起,我忘了取消注释“Mat right”,我只想测试一个线程。
  • 我不明白。那么它只能串行吗?

标签: c++ multithreading opencv opencv3.0


【解决方案1】:

你有悬空引用。

OutputArray 类有一个构造函数,它通过引用获取 Mat

_OutputArray(Mat& m);

当您创建线程时,您传递 left - 作为 Mat 实例。因为线程体的签名采用OutputArray,它可以采用Mat,这个Mat作为参数被创建为副本。然后OutputArray 通过引用获取这个临时对象。当thread开始执行时,OutputArray指的是被销毁的临时Mat实例(thread只需要存储OutputArray,没有临时的Mat)。

解决方案?只需将原始的left 传递给OutputArray

thread t1(testThread, OutputArray(left));
t1.join();

在上面的代码中,没有创建Mat 的临时实例作为left 的副本。

【讨论】:

  • 谢谢,我知道了!
  • 那你为什么问这个问题?我向你解释了你的错误在哪里。悬空引用会产生未定义的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
相关资源
最近更新 更多