Bitmap to Mat gives wrong colors back
Asked Answered
C

1

6

So I make a bitmap from a blob with the next code:

byte[] blob = contact.getMP();
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Bitmap scalen = Bitmap.createScaledBitmap(bitmap, 320, 240, false);

and it gives back the next output, which is good

enter image description here

Then I do the following to make the bitmap into a Mat, but then my colors just change...

//Mat ImageMat = new Mat();
Mat ImageMat = new Mat(320, 240, CvType.CV_32F);
Utils.bitmapToMat(scalen, ImageMat);

I have no idea why, nor another way to make the bitmap into a Mat. What is wrong? enter image description here

Cleat answered 18/5, 2013 at 22:46 Comment(4)
Looks like the blue and red channels are swapped. Are you sure your Mat is storing image as RGB (Java's default) instead of BGR (Opencv's default)Trowel
any updates on this question ?Cirenaica
Have you found solution for this? i am facing same problem.Frendel
As a side note: 1) I believe your commented line is better 2) Mat ImageMat = new Mat(320, 240, CvType.CV_32F); will allocate a matrix which is not suitable to receive the output of bitmapToMat, the type should be CV_8UC4. Coincidentally the same number of bytes :) See doc iopencv.com/docs/java/2.4.9/org/opencv/android/Utils.htmlScandal
W
14

The format of color channels in Android Bitmap are RGB But in opencv Mat, the channels are BGR by default.

So when you do Utils.bitmapToMat(), [B,G,R] values are stored in [R,G,B] channels. The red and blue channels are interchanged.

One possible solution is to apply cvtcolor on the opencv Mat you got as below: Imgproc.cvtColor(ImageMat, ImageMat, Imgproc.COLOR_BGR2RGB);

It worked for me.

Worldling answered 19/2, 2015 at 23:5 Comment(3)
Fun fact: Android.camera2 jpegs converted to bitmaps and then converted to mats keep their RGB channels in tact.Motheaten
Need to be double-confirmed, but it seems Utils.bitmapToMat creates RGB Mat. ( github.com/opencv/opencv/blob/master/modules/java/generator/src/… )Darn
Imgproc.cvtColor(ImageMat, ImageMat, Imgproc.COLOR_BGR2RGB); will a eat lot of cpu timeSuburbanite

© 2022 - 2024 — McMap. All rights reserved.