首页 > 解决方案 > 将 opencv Mat 传递给函数时,引用非常量的初始值必须是左值

问题描述

我有一个垫子。我想根据 Rect 定义的某些区域更新垫子。当我像下面显示的代码一样传递它时,我得到了提到的错误。

void temp2(Mat &A){
  //this function updates the value of A in the region defined by the rect.
 for(i = 0 to A.rows){
  Vec2f *p = reinterpret_cast<Vec2f * >(A.ptr(i));
  for(j = 0 to A.cols){
   //  p[j] = Vec2f(5,5);
}
}
}
void temp1(Mat &A){
  Point a(0,0), b(10,10);
  Rect t(a,b);
  temp2(A(t));
}

void temp(Mat &A){
  A  = Mat(500, 500, CV_32FC2, Scalar(-1.0, -1.0));
  temp1(A);
}
int main(){
  
 Mat A;
 temp(A);

}

我查找了解决方案,它说要在 temp2 函数中制作 mat A const。我不能在 temp2 函数中制作 mat A const,因为我必须更新由 temp2 函数中的 rect 定义的 mat 的特定区域。如何以这种方式更新特定区域?

标签: c++opencv

解决方案


这不适合你吗?

 /* Renamed arg to reflect what's happening.
    Let it be A if you so wish but it's not
    the original A from temp(). 
  */   
void temp2(Mat &extractedFromA){
  // Do stuff
}
void temp1(Mat &A){
  Point a(0,0), b(10,10);
  Rect t(a,b);
  Mat extracted = A(t);
  temp2(extracted);
}

您正在使用API

Mat cv::Mat::operator() (const Rect & roi)const

这意味着在调用A(t)时,A未修改(因为上面的 API 是一个 const 方法)并产生一个Mat对象,这是您需要在 中操作的,而不是传入temp2()的原始对象。此外,对 所做的更改应反映回原始内容,因为您仅在它们之间共享标题。Atemp1()extracted MatMat A

此外,您可能遇到的错误是,由于A(t)产生了一个临时对象,并且在将其传递给 时temp2(),您试图将其绑定到非 const 左值引用。将其作为 const 左值引用可以解决它,但这显然对您没有帮助。


推荐阅读