OpenCV: transforming 3 channel image into 4 channel

I think it should be like this:

cv::Mat source = cv::imread(path);
cv::Mat newSrc = cv::Mat(source.rows,source.cols,CV_8UC4);

int from_to[] = { 0,0, 1,1, 2,2, 3,3 };
cv::mixChannels(&source,1,&newSrc,1,from_to, source.channels());

In C++11 you can use initializer lists to provide multiple matrices for batch conversion inline:

cv::mixChannels({{source}}, {{newSrc}}, from_to, source.channels());

We set 3 pairs to be copied, so this leaves the 4 channel empty in newsrc. And 1 in the second and forth parameter means that the pointers source and newSrc point to one element to be processed. The last parameter gives the length of from_to.


You can convert 3 channel image to 4 channel as follows:

cv::Mat source = cv::imread(path);

cv::Mat newSrc(source.size(), CV_MAKE_TYPE(source.depth(), 4));

int from_to[] = { 0,0, 1,1, 2,2, 2,3 };

cv::mixChannels(&source,1,&newSrc,1,from_to,4);

This way channel 4 will be a duplicate of channel 3. By using a negative number in the from_to list, the output channel is zero filled. eg:

int from_to[] = { 0,0, 1,1, 2,2, -1,3 };

What is the 4th channel supposed to contain? How about:

VideoCapture cap(0);
Mat frame;
cap >> frame;

Mat RGBA(frame.size(), CV_8UC4, camData);
cv::cvtColor(frame, RGBA, CV_BGR2RGBA, 4);