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

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)
    – Max
    Jul 12, 2013 at 7:37
  • any updates on this question ? Jan 14, 2014 at 13:22
  • Have you found solution for this? i am facing same problem. Oct 3, 2018 at 5:43
  • 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.html
    – Antonio
    Feb 19, 2021 at 17:01

1 Answer 1

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.

3
  • Fun fact: Android.camera2 jpegs converted to bitmaps and then converted to mats keep their RGB channels in tact.
    – Sipty
    Mar 25, 2015 at 11:04
  • Need to be double-confirmed, but it seems Utils.bitmapToMat creates RGB Mat. ( github.com/opencv/opencv/blob/master/modules/java/generator/src/… )
    – JSong
    Jul 25, 2018 at 3:07
  • 1
    Imgproc.cvtColor(ImageMat, ImageMat, Imgproc.COLOR_BGR2RGB); will a eat lot of cpu time
    – user924
    Jun 4, 2019 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.