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?
You declare a couple of vectors of
3elements (size) each, but do not initialize their values:What's the initial value of these first
3elements?After this, you
push_backanother3elements into the same vector:So,
channels2has now6elements. And here's the question: Are all these elements of samedata typeandsize? They must be if you want to merge them together! If you want to merge just theBGRchannels, you can do this instead:Of course, if you declare the vector with an initial capacity (
size) and initial values, you can index each element usingstd::vector<>::operator[]instead of usingpush_back. Either use one method but do not mix them up.