smcs
smcs

Reputation: 2004

OpenCV: How to pass a multi-channel matrix as a function argument?

I have a function with this signature: process(Mat_<float>&). I can pass a single channel matrix to it like this:

Mat img = cv::imread(inPath, 0);
Mat_<float> imgReal;
img.convertTo(imgReal, CV_32F, 1.0/255.0);
process(imgReal);

No complaints. But how can I pass a matrix of type CV_32FC2 with two channels? The matrix is created like this:

Mat img = cv::imread(inPath, 0);
Mat_<float> imgReal;
img.convertTo(imgReal, CV_32F, 1.0/255.0);
Mat imgImag = Mat(imgReal.rows, imgReal.cols, CV_32F, float(0));
vector<Mat> channels;
channels.push_back(imgReal);
channels.push_back(imgImag);
Mat imgComplex = Mat(imgReal.rows, imgReal.cols, CV_32FC2);
merge(channels,imgComplex);
process(imgComplex);

Now when I call process(imgComplex), the compiler throws main.cpp:140:74: error: invalid initialization of non-const reference of type ‘cv::Mat_<float>&’ from an rvalue of type ‘cv::Mat_<float>’

What exactly is the cause of that?

Upvotes: 0

Views: 183

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123431

Your situation is similar to this:

struct asdf {
    asdf(int x){} // converting constructor
};
process(asdf& x) {}

Given this, the following is allowed

asdf x = 3;   // calls converting constructor
process(x);   // pass lvalue

but what is not allowed is this:

int x = 3;
process(x);   // attempts to call converting constructor 
              // and pass the result (rvalue!) to process

Because the rvalue resulting from the conversion is not allowed to bind to a non-const reference. As a fix, either change the signature of process (would be process(int&) for this example) or do the conversion and calling the funtion in two steps (analog to the first snippet).

Upvotes: 1

Related Questions