Vyktor
Vyktor

Reputation: 20997

OpenCV - assign operator "not working"?

I have one function to compute convolution (to test whether we are using correct settings for filter2D), I think the function body is not important, so here's just header and the end:

template<typename T>
cv::Mat conv(const cv::Mat &input, const cv::Mat &kernel) {
    cv::Mat output(input); // or should I rather use output( input.rows, input.cols, input.depth())?

    ...
    return output;
}

cv::Mat result = conv( input, kernel);

At this point, I have completely useless results in result (those aren't even random data, they have some strange pattern which got repeated every time I run the function).

When I rewrite function to:

template<typename T>
void conv(const cv::Mat &input, cv::Mat &output, const cv::Mat &kernel) {
   ...
}

cv::Mat result(input);
conv( input, result, kernel);

Everything works just fine and result matrix contains exactly what it should.

So my question is: What's wrong on first approach? Am I doing something wrong? Why isn't assign operator/return from function working?

*Note: OpenCv version: extra/opencv 2.3.1_a-3 (archlinux package)*

Something similar happened to me when I was loading external data from opencv storage and data got lost until I used data( loaded.clone())

Upvotes: 4

Views: 532

Answers (1)

ypnos
ypnos

Reputation: 52337

Well, it seems that filter2d, or whatever you do, does not work 'in-place', that is, when input and output are the same. With your first line in the function,

cv::Mat output(input); // or should I rather use output( input.rows, input.cols, input.depth())?

you make output point to the same data as input! It is not a clone, it is another reference!

What you want to do is written in your comment. Another option may be (depending on your code) to let output completely uninitialized, as typically C++ OpenCV functions will initialize their output matrices for you, if they are empty.

Note that your conv(), even when giving a proper results, would always destroy your input matrix on the way. OpenCV does not respect const in its internal data reference meachanism. Yes, it is bad design.

Upvotes: 1

Related Questions