Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy grayscale image to RGB images red channel in OpenCV?

Tags:

c++

image

opencv

I have two input images, which are greyscale and I am creating one more image, which is RGB and should contain in the red channel one of the grey image and in the green the other.

Mat img, img2;
img =imread("above.jpg", CV_LOAD_IMAGE_GRAYSCALE);
img2 =imread("left.jpg", CV_LOAD_IMAGE_GRAYSCALE);

Mat * aboveLeft = new Mat(img.rows, img.cols, CV_LOAD_IMAGE_COLOR);

int from_to [] = {0,1};
cv::mixChannels(&img, 1, aboveLeft, 3, from_to, 1);

I've tried to use the mixChannels command, to write img input into aboveLeft's first channel, but I couldn't figure out the right syntax and get assertion errors.

Is this the right way to fill in a channel?

like image 928
user1767754 Avatar asked May 20 '14 20:05

user1767754


2 Answers

I assume img and img2 has same size and type.

cv::Mat img = cv::imread("above.jpg", CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat img2 = cv::imread("left.jpg", CV_LOAD_IMAGE_GRAYSCALE);

std::vector<cv::Mat> images(3);
Mat black = Mat::zeros(img.rows, img.cols, img.type());
images.at(0) = black; //for blue channel
images.at(1) = img;   //for green channel
images.at(2) = img2;  //for red channel

cv::Mat colorImage;
cv::merge(images, colorImage);
like image 64
guneykayim Avatar answered Nov 07 '22 11:11

guneykayim


Assuming that you have 3 grayscale matrices, you can use cv::merge():

cv::Mat blue, green, red;
std::vector<cv::Mat> images(3);

// OpenCV works natively with BGR ordering
images.at(0) = blue;
images.at(1) = green;
images.at(2) = red;

cv::Mat color;
cv::merge(images, color);

As pointed out in the comments, you need to find a way to figure out what you want for the blue channel!

like image 39
sansuiso Avatar answered Nov 07 '22 12:11

sansuiso