Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV changing Mat inside a function (Mat scope)

Tags:

opencv

I am passing a Mat to another function and changing it inside the called function. I had expected that being a more complex type it was automatically passed by reference so that the matrix would have changed in the calling function, but it doesn't. Could someone point me at the explanation of how to correctly return a changed Mat from a function?

Here's the code snippet:

void callingFunction(Mat img)
{
  Mat tst(100,500,CV_8UC3, Scalar(0,255,0));
  saveImg(tst, "Original image", true);
  testImg(tst);
  saveImg(tst, "Want it to be same as inside testImg but is same as Original", true);
}

void testImg(Mat img)
{
  int rs = 50; // rows
  int cs = 100; // columns
  img = Mat(rs, cs, CV_8UC3, Scalar(255,0,0));
  Mat roi(img, Rect(0, 0, cs, rs/2));
  roi = Scalar(0,0,255); // change a subsection to a different color

  saveImg(img, "inside testImg", true);
}

Thanks!

like image 971
zzzz Avatar asked Jun 27 '12 21:06

zzzz


1 Answers

You have to define Mat as parameter-reference (&). Here's edited code:

void callingFunction(Mat& img)
{
  Mat tst(100,500,CV_8UC3, Scalar(0,255,0));
  saveImg(tst, "Original image", true);
  testImg(tst);
  saveImg(tst, "Want it to be same as inside testImg but is same as Original", true);
}

void testImg(Mat& img)
{
  int rs = 50; // rows
  int cs = 100; // columns
  img = Mat(rs, cs, CV_8UC3, Scalar(255,0,0));
  Mat roi(img, Rect(0, 0, cs, rs/2));
  roi = Scalar(0,0,255); // change a subsection to a different color

  saveImg(img, "inside testImg", true);
}
like image 177
ArtemStorozhuk Avatar answered Dec 01 '22 19:12

ArtemStorozhuk