Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV operation with src, dst Mat and memory allocation [duplicate]

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 659
jeff Avatar asked Nov 18 '25 19:11

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 57
Miki Avatar answered Nov 20 '25 10:11

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 32
CodeMouse92 Avatar answered Nov 20 '25 11:11

CodeMouse92



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!