Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use the same variable as input and output in C++ OpenCV?

A lot of OpenCV functions are defined as

function(InputArray src, OutputArray dst, otherargs..)

So if I want to process and overwrite the same image, can I do this:

function(myImg, myImg);

is it safe to do this way?

Thanks

Edit:

I'm asking for the standard functions in OpenCV like threshold, blur etc. So I think they should have been implemented accordingly, right?

like image 963
jeff Avatar asked Oct 06 '15 16:10

jeff


2 Answers

Yes, in OpenCV it is safe.


Internally, a function like:

void somefunction(InputArray _src, OutputArray _dst);

will do something like:

Mat src = _src.getMat();
_dst.create( src.size(), src.type() );
Mat dst = _dst.getMat();

// dst filled with values

So, if src and dst are:

  • the same image, create won't actually do anything, and the modifications are effectively in-place. Some functions may clone the src image internally if the operation cannot be in-place (e.g. findConturs in OpenCV > 3.2) to guarantee the correct behavior.
  • different images, create will create a new matrix dst without modifying src.

Documentation states where this default behavior doesn't hold.

A notable example is findContours, that modify the src matrix. You cope with this usually passing src.clone() in input, so that only the cloned matrix is modified, but not the one you cloned from.

From OpenCV 3.2, findContours doesn't modify the input image.


Thanks to Fernando Bertoldi for reviewing the answer

like image 99
Miki Avatar answered Oct 09 '22 16:10

Miki


EDIT: Now that the question was updated, I realize this is rather irrelevant. I'll leave it here, however, in case someone searching for a related issue comes along.


In general with C++, whether that situation is safe really depends on the body of the function in question. If you are reading from and writing to the same variable directly, you could wind up with some serious logic issues.

However, if you are using a temporary variable to hold the original value before overwriting it, it should be fine.

A MASSIVE word of warning if you're working with arrays, however. If you are trying to store the entire contents of the array in a temporary variable, you have to be careful you're storing the actual array, and not just the pointer to it. In many situations, it would generally be advisable to store individual values in the array temporarily (such as in a swap function). I can't give much further advice in this regard, however, as it all depends on what you're trying to do.

In short, it all depends on your function's implementation.

like image 31
CodeMouse92 Avatar answered Oct 09 '22 16:10

CodeMouse92