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

后端 未结 2 1526
没有蜡笔的小新
没有蜡笔的小新 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: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

提交回复
热议问题