我有以下功能:
void MyClass::myFunc(cv::OutputArray dst) const {
cv::Mat result;
...
dst.assign(result);
}
如果我這樣運行它:
cv::Mat result;
myFunc(result);
otherFunc(result);
它作業正常,并otherFunc收到result由myFunc.
但如果我std::async這樣使用:
cv::Mat result;
auto resultFuture = std::async(&MyClass::myFunc, this, result);
resultFuture.wait();
otherFunc(result);
otherFunc接收空result。我究竟做錯了什么?
uj5u.com熱心網友回復:
根本原因是通過參考 (&) 將引數傳遞給要運行的函式std::async是有問題的。您可以在此處閱讀相關資訊:通過參考將引數傳遞給 std::async 失敗(在您的情況下,沒有編譯錯誤,但該鏈接通常解釋了該問題)。
在您的情況下,您使用cv::OutputArray在 opencv 中定義為參考型別:
typedef const _OutputArray& OutputArray;
我假設您想要參考語意,因為您希望您的result物件由myFunc.
解決方案是使用std::ref.
但是由于result您傳遞的物件是 a cv::Mat,因此最好更直接地myFunc接收 a cv::Mat&。
我還設法使用 a 生成了一個解決方案cv::OutputArray,但它需要一個丑陋的演員表(除了std::ref)。它在 MSVC 上運行良好,但我不確定它是否普遍有效。
下面是演示這兩個選項的代碼。如果可以的話,我建議使用第一種方法。您可以在初始化后otherFunc(result);列印尺寸的位置呼叫。result
#include <opencv2/core/core.hpp>
#include <future>
#include <iostream>
// Test using a cv::Mat &:
class MyClass1
{
void myFunc(cv::Mat & dst) const
{
cv::Mat result(4, 3, CV_8UC1);
result = 1; // ... initialize some values
dst = result; // instead of using cv::OutputArray::assign
}
public:
void test()
{
cv::Mat result;
std::cout << "MyClass1: before: " << result.cols << " x " << result.rows << std::endl;
auto resultFuture = std::async(&MyClass1::myFunc, this, std::ref(result));
resultFuture.wait();
// Here result will be properly set.
std::cout << "MyClass1: after: " << result.cols << " x " << result.rows << std::endl;
}
};
// Test using a cv::OutputArray:
class MyClass2
{
void myFunc(cv::OutputArray dst) const
{
cv::Mat result(4, 3, CV_8UC1);
result = 1; // ... initialize some values
dst.assign(result);
}
public:
void test()
{
cv::Mat result;
std::cout << "MyClass2: before: " << result.cols << " x " << result.rows << std::endl;
auto resultFuture = std::async(&MyClass2::myFunc, this, std::ref(static_cast<cv::OutputArray>(result)));
resultFuture.wait();
// Here result will be properly set.
std::cout << "MyClass2: after: " << result.cols << " x " << result.rows << std::endl;
}
};
int main()
{
// Test receiving a cv::Mat&:
MyClass1 m1;
m1.test();
// Test receiving a cv::OutputArray:
MyClass2 m2;
m2.test();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/479044.html
