将OpenCV Matrix分配到数据结构中

时间:2017-05-09 12:26:40

标签: c++ multithreading opencv

我使用OpenCV构建一个多线程系统,它创建一些图像,将它们分配到一个向量中,并将每个图像发送到另一个线程。

这就是它的样子:

std::vector<cv::Mat> images;
for (int i = 0 ; i < 10 ; i++) {
    images.push_back(cv::Mat(/* bla bla */));
    cv::Mat& mat = images.back();
    std::thread(some_function_name, &mat)
}
// Wait here for all threads to join (didn't show its code)

似乎当线程获得指向Mat对象的指针时,Mat对象不再存在。是否有可能虽然它被立即分配给向量,但它实际上在循环结束时被销毁了,因为它从堆栈中被擦掉了?

1 个答案:

答案 0 :(得分:2)

您的问题实际上是您在循环中调用push_back这可能会导致重新分配。如果发生这种情况,将复制基础数据,因此任何指针或引用都将失效。

要解决此问题,一种方法是提前调整数组大小

std::vector<cv::Mat> images(10);
for (int i = 0 ; i < 10 ; i++) {
    images[i] = cv::Mat(/* bla bla */);
    cv::Mat& mat = images.at(i);
    std::thread(some_function_name, &mat)
}
// Wait here for all threads to join (didn't show its code)