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

user1393500
  • 199
  • 1
  • 3
  • 16
  • 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 '13 at 07:37
  • any updates on this question ? – Ankur Gautam Jan 14 '14 at 13:22
  • Have you found solution for this? i am facing same problem. – Muhammad Hassaan Oct 03 '18 at 05: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 https://iopencv.com/docs/java/2.4.9/org/opencv/android/Utils.html – Antonio Feb 19 '21 at 17:01

1 Answers1

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.

JSong
  • 348
  • 3
  • 19
VK_nandi
  • 165
  • 1
  • 9
  • Fun fact: Android.camera2 jpegs converted to bitmaps and then converted to mats keep their RGB channels in tact. – Sipty Mar 25 '15 at 11:04
  • Need to be double-confirmed, but it seems Utils.bitmapToMat creates RGB Mat. ( https://github.com/opencv/opencv/blob/master/modules/java/generator/src/cpp/utils.cpp#L45 ) – JSong Jul 25 '18 at 03:07
  • 1
    `Imgproc.cvtColor(ImageMat, ImageMat, Imgproc.COLOR_BGR2RGB);` will a eat lot of cpu time – user924 Jun 04 '19 at 12:46