Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV: How to convert CV_8UC1 mat to CV_8UC3

Tags:

opencv

How to convert CV_8UC1 Mat to CV_8UC3 with OpenCV?

Mat dst;
Mat src(height, width, CV_8UC1, (unsigned char*) captureClient->data());
src.convertTo(dst, CV_8UC3);

but dst.channels() = 1

like image 707
Grammer Avatar asked Jan 30 '13 14:01

Grammer


People also ask

What is CV_8UC3 in OpenCV?

So, here is the meaning of the CV_8UC3: we want to use unsigned char types('U') that are 8 bit long and each pixel has 3 of these to form the 3 channels. The Scalar is four element short vector. Here is a single channel array with 8 bit unsigned integers.

What is a CV :: mat?

In OpenCV the main matrix class is called Mat and is contained in the OpenCV-namespace cv. This matrix is not templated but nevertheless can contain different data types. These are indicated by a certain type-number. Additionally, OpenCV provides a templated class called Mat_, which is derived from Mat.

What is use of mat class in OpenCV?

The Mat class of OpenCV library is used to store the values of an image. It represents an n-dimensional array and is used to store image data of grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms, etc.


3 Answers

I've found that the best way to do this is:

cvtColor(src, dst, COLOR_GRAY2RGB);

The image will look the same as when it was grayscale CV_8UC1 but it will be a 3 channel image of type CV_8UC3.

like image 164
Kevin Avatar answered Sep 21 '22 21:09

Kevin


From the documentation on convertTo

void Mat::convertTo(Mat& m, int rtype, double alpha=1, double beta=0) const

rtype – The desired destination matrix type, or rather, the depth (since the number of channels will be the same with the source one). If rtype is negative, the destination matrix will have the same type as the source.

You want to create a matrix for each of the 3 channels you want to create and then use the merge function. See the answers to this question

like image 37
Hammer Avatar answered Sep 20 '22 21:09

Hammer


The convention is, that for the type CV_8UC3, the pixels values range from 0 to 255, and for type CV_32FC3 from 0.0 to 1.0. Thus you need to use a scaling factor of 255.0, instead of 1.0:

Mat::convertTo(newImage, CV_32FC1, 255.0);
like image 3
sensors Avatar answered Sep 20 '22 21:09

sensors