Why is Utils.bitmapToMat changing Mat type?

asked 2019-08-22 01:12:46 -0500

DirkDenzer gravatar image

I'm working with Android and the OpenCV Android library. I have a Bitmap of config RGB_565 and want to convert it to a 3 channel Mat. In order to do so, I have the following code:

Bitmap bmp = Bitmap.createBitmap(bitmaps[0].getWidth(),bitmaps[0].getHeight(), Bitmap.Config.RGB_565);
Mat raw = new Mat(bmp.getHeight(),bmp.getWidth(),CvType.CV_8UC3);
Utils.bitmapToMat(bmp,raw);

However after the call to Utils.bitmapToMat the type of raw changes to CvType.CV_8UC4 which then has 4 channels. But for my processing it is supposed to be 3 channels. Why is that and is that normal?

I figured I can convert it back with

if(raw.channels() != 1 && raw.channels() != 3)
{
    Imgproc.cvtColor(raw,raw,Imgproc.COLOR_BGRA2BGR);
}

but I'm not sure if this is good practice or correct.

The reason why it is confusing is that I have the exact same code in C# for Unity, which is based on OpenCV Java, and I get the expected result. With the code in Android Java I'm not getting the same result which is strange as it is a 1 to 1 copy of the C# one. So only difference is where the image is coming from (Unity a Texture2D Android a Bitmap) and this strange fact that the channels switch (which they don't in Unity)

For completeness this is the framework used in Unity https://assetstore.unity.com/packages...

So questions are: Why is that happening? Is that normal? What can I do about it? Is it okay to just convert it back and can I expect it to work normal that way?

Thank you!

edit retag flag offensive close merge delete