2

I am trying to merge single-channel images into one multiple-channel image. But it shows an error at the merge function:

cv::Exception at memory location

code:

#include <vector>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

int main() {
    Mat input = imread("a jpeg image");
    Mat B, G, R, merged;
    vector<Mat> channels(3), channels2(3);

    //-- split
    split(input, channels);
    B = channels[0];
    G = channels[1];
    R = channels[2];

    //-- merge
    channels2.push_back(B);
    channels2.push_back(G);
    channels2.push_back(R);

    merge(channels2, merged);
    imshow("merged", merged);

    waitKey(0);
    return 0;
}

I am using Visual Studio on Windows. How can I fix this?

P.S. My final goal is to merge 4 images (i.e., Blue, Green, Hue, and Gray-scale) into a 4-channel and use it as input for the mean function. Would this work with Mat object? Or the 3rd channel has to be Red, 4th channel has to be alpha?

1 Answer 1

1

You declare a couple of vectors of 3 elements (size) each, but do not initialize their values:

vector<Mat> channels(3), channels2(3);

What's the initial value of these first 3 elements?

After this, you push_back another 3 elements into the same vector:

channels2.push_back(B);
channels2.push_back(G);
channels2.push_back(R);

So, channels2 has now 6 elements. And here's the question: Are all these elements of same data type and size? They must be if you want to merge them together! If you want to merge just the BGR channels, you can do this instead:

std::vector<cv::Mat> channels2; //Notice I declared an empty vector

//Push the individual channels into the vector:
channels2.push_back(B);
channels2.push_back(G);
channels2.push_back(R);

//Merge the channels
cv::Mat outputMat;
cv::merge( channels2, outputMat);

Of course, if you declare the vector with an initial capacity (size) and initial values, you can index each element using std::vector<>::operator[] instead of using push_back. Either use one method but do not mix them up.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. The vector should have been empty.
@HadiGhahremanNezhad No problem, man! We all miss little things, happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.