Reputation: 2455
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?
Upvotes: 2
Views: 283
Reputation: 5815
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.
Upvotes: 1