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

后端 未结 2 1527
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 18:26

A lot of OpenCV functions are defined as

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

So if I want to process and overwrite the s

相关标签:
2条回答
  • 2021-01-17 19:03

    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.

    0 讨论(0)
  • 2021-01-17 19:28

    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

    0 讨论(0)
提交回复
热议问题