Conversion between any/all of BGR, RGB, and GBR may be necessary when working with
- Matplotlib pyplot.imshow():
M x N x 3image, where last dimension is RGB.
M x N x 3image, where last dimension is BGR
- Scientific Cameras: some output
M X N x 3image, where last dimension is GBR
Note: as in any programming language, operations on memory-contiguous arrays are most efficient. In particular, OpenCV in-place operations require a contiguous array from Python to avoid unexpected results. The safest approach is to always make a copy of the array as in the examples below.
.copy() to avoid unexpected results if using OpenCV.
If just using Matplotlib,
.copy() is not necessary–but performance (speed) may benefit from .copy().
BGR to RGB: OpenCV image to Matplotlib
rgb = bgr[...,::-1].copy()
RGB to BGR: Matplotlib image to OpenCV
bgr = rgb[...,::-1].copy()
RGB to GBR:
gbr = rgb[...,[2,0,1]].copy()
The axis order convention 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, where the last axis is typically an alpha channel