Numpy / OpenCV image BGR to RGB

Conversion between any/all of BGR, RGB, and GBR may be necessary when working with

  • Matplotlib expects M x N x 3 image, where last dimension is RGB.
  • OpenCV expects M x N x 3 image, where last dimension is BGR
  • Scientific Cameras, some of which output an M X N x 3 image, where last dimension is GBR

Python BGR to RGB code

BGR to RGB

OpenCV image to Matplotlib

rgb = bgr[...,::-1]

RGB to BGR

Matplotlib image to OpenCV

bgr = rgb[...,::-1]

RGB to GBR

gbr = rgb[...,[2,0,1]]

Axis order for Python images

  • 3-D: W x H x 3, where the last axis is color (e.g. RGB)
  • 4-D: W x H x 3 x 1 is typically an alpha channel

Leave a Comment