Reputation: 2445
I am trying to add two Mat objects together, but I am facing an error.
This is the working code:
Mat src1, src2, dst;
/// Read image ( same size, same type )
src1 = imread("lion.png");
src2 = imread("bluebell.png");
dst = src1 + 0.5 * src2;
imshow("Blend", dst);
waitKey(0);
return 0;
Both src1
and src2
have the same type which is CV_8UC3
. But when I try this:
Mat src1, src2, src3, dst;
/// Read image
src1 = imread("lion.png");
src2 = imread("bluebell.png", IMREAD_GRAYSCALE);
src2.convertTo(src3, COLOR_GRAY2RGB);
cout << "src1.type " << src1.type() << endl;
cout << "src2.type " << src2.type() << endl;
cout << "src3.type " << src3.type() << endl;
dst = src1 + 0.5 * src3;
imshow("Blend", dst);
waitKey(0);
return 0;
It doesn't work. Because src2
and src3
both have type 0
which is CV_8U
. But I want src3
to have type 16
which is CV_8UC3
(according to here). This code brings this error:
OpenCV Error: Sizes of input arguments do not match (The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array') in cv::arithm_op
How can I convert a grayscale image to a colored one with exact type of CV_8UC3
?
Upvotes: 0
Views: 2072
Reputation: 20938
You cannot change number of channels by calling convertTo
. According to reference:
desired output matrix type or, rather, the depth since the number of channels are the same as the input has; if rtype is negative, the output matrix will have the same type as the input.
When you have matrix with one channel in grayscale, you can use cv::merge
to create 3 channels image by putting this one component for BGR channels in new matrix:
src1 = imread("lion.png");
src2 = imread("bluebell.png", IMREAD_GRAYSCALE); // one channel
cv::merge(std::vector<cv::Mat>{src2, src2, src2}, src2);
// blue, green,red as output 3-channels mat
dst = src1 + 0.5 * src2;
By calling convertTo
, you can convert data type of storing values, for example from integer to float.
Upvotes: 2