Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV: OutputArray usage without copy

I need to extend kernel from one channel to more channels. For example from

0  1 0
1 -4 1
0  1 0

to

0 0 0  1  1  1 0 0 0
1 1 1 -4 -4 -4 1 1 1
0 0 0  1  1  1 0 0 0

following standard three channels cv::Mat.

I have following code:

void createKernel(InputArray _A, InputArray _B, OutputArray _kernel, const int chn)
{
    Mat A = _A.getMat();
    Mat B = _B.getMat();
    Mat kernel;
    Mat kernelOneChannel = A * B;
    std::vector<Mat> channels;

    for (int i = 0; i < chn; i++)
    {
        channels.push_back(kernelOneChannel);
    }

    merge(channels, kernel);    
    kernel.copyTo(_kernel);
}

One channel kernel is copied to std:vector as many times based on the chn. After that is one multi channel cv::Mat created.

My question is about the last line kernel.copyTo(_kernel). In many examples what I have seen, this is the way how to deal with Outputarray. Is this copyTo really needed? It seems to me like waste of memory and time to copy already computed kernel to the _kernel. Is there any solution without this data copy from one structure to another?

My question is strictly related to OpenCV and mentioned structures.

Thanks in advance.

like image 454
tucna Avatar asked Nov 21 '25 20:11

tucna


1 Answers

In your specific case you can pass _kernel variable directly to merge call to avoid unnessesary copy:

merge(channels, _kernel)

In general case the OutputArray object is supposed to be used in the following way:

_outArr.create(size, type);
Mat outMat = _outArr.getMat();

Now the outMat variable can be filled without extra copies.

like image 113
jet47 Avatar answered Nov 23 '25 10:11

jet47



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!