Why does openCV's convertto function not work?
Asked Answered
S

3

14

I have an image which has 4 channels and is in 4 * UINT8 format.

I am trying to convert it to 3 channel float and I am using this code:

images.convertTo(images,CV_32FC3,1/255.0);

After the conversion, the image is in a float format but still has 4 channels. How can I get rid of 4th (alpha) channel in OpenCV?

Stewart answered 4/3, 2014 at 13:59 Comment(0)
A
22

As @AldurDisciple said, Mat::convertTo() is intended to be used for changing the data type of a Mat, not for changing the number of channels.

To work out, you should split it into two steps:

cvtColor(image, image, CV_BGRA2BGR);       // 1. change the number of channels
image.convertTo(image, CV_32FC3, 1/255.0); // 2. change type to float and scale
Applejack answered 4/3, 2014 at 16:23 Comment(2)
Hello sir, What does 1/255.0 ? it is useful for which thing ?Dealfish
@Kabyle 1/255.0 here is the scale factor, which will convert values [0, 255] to [0, 1]. See Mat::convertTo()'s doc for details.Applejack
R
2

The function convertTo is intended to be used to change the data type of a Mat, exclusively. As mentionned in the documentation (link), the number of channels of the output image is always the same as the input image.

If you want to change the datatype and reduce the number of channels, you should use a combination of split, merge, and convertTo:

cv::Mat img_8UC4;

cv::Mat chans[4];
cv::split(img_8UC4,chans);

cv::Mat img_8UC3;
cv::merge(chans,3,img_8UC3);

cv::Mat img_32FC3;
img_8UC3.convertTo(img_32FC3);

Another approach may be to recode the algorithm yourself, which is quite easy and probably more efficient.

Rummel answered 4/3, 2014 at 14:8 Comment(0)
A
0

OpenCV's cvtColor function allows you to convert the type and number of channels of a Mat.

void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0 )

So something like this would convert a colored 4 channel to a colored 3 channel:

cvtColor(image, image, CV_BGRA2BGR, 3);

Or it is probably more efficient to use the mixChannels function, if you check the documentation its example shows how to split a channel out.

Then if you really want to change it to a specific type:

image.convertTo(image,CV_32F);
Asynchronism answered 4/3, 2014 at 14:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.