19

Is there any way to know in advance if an image used as an input to a system is in RGB or BGR format?

I am using OpenCV with java API and I would like to convert an input image into grayscale or L*a*b* color space, but in OpenCV you have to specify first whether the image you want to convert is in RGB or BGR.

The type of the image I am using is either .jpg or .png.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • Depends on the type of image you are using... Which image type are you using ? – CoderNeji Jun 12 '15 at 12:03
  • @CoderNeji please see the update section above – Amrmsmb Jun 12 '15 at 12:04
  • I think @Jean-BaptisteYunès gave you the right answer process the image as buffered image first and then you can set flags accordingly for RGB or BGR format – CoderNeji Jun 12 '15 at 12:11
  • If you load image with OpenCV functions it will be BGR, as far as i know there's still no function to check the color space. – Aristu Jun 12 '15 at 17:36

3 Answers3

26

If you are reading in the image file, or you have access to the code that reads in the file, know it is:

  • BGR order if you used cv2.imread()
  • RGB order if you used mpimg.imread() (assuming import matplotlib.image as mpimg)

If you don't know how the file was opened, the accepted answer BufferedImage is great for Java.
I would like to find a way to do the same in Python!

gsamaras
  • 71,951
  • 46
  • 188
  • 305
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
  • It's important to note that with matplotlib, RGB is specifically for JPG images. PNG images will load as BGRA. – VoteCoffee Feb 11 '21 at 21:00
9

When you use opencv (imread, VideoCapture), the images are loaded in the BGR color space.

Alexander Leon VI
  • 499
  • 1
  • 4
  • 18
  • 1
    Your answer is correct, but you might add some supporting documentation: http://docs.opencv.org/java/2.4.9/org/opencv/highgui/Highgui.html#imread(java.lang.String) "Note: In the case of color images, the decoded images will have the channels stored in B G R order." – beaker Jun 12 '15 at 15:05
  • In the future I will try to do it, thanks for advicing – Alexander Leon VI Jun 12 '15 at 20:39
2

If your image is a BufferedImage then you can ask for his type with getType(), and test against the several constants (see: BufferedImage).

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69