Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
RGB vs BGR
RGB and BGR are the same three colour channels in a different order. Understanding this difference prevents one of the most common bugs in Computer Vision code.
The BGR vs RGB Difference
RGB (Red, Green, Blue):
- The standard colour model used by most image formats and libraries
- Matplotlib, PIL/Pillow, and web browsers all use RGB
- Channel 0 = Red, Channel 1 = Green, Channel 2 = Blue
BGR (Blue, Green, Red):
- OpenCV's default channel order — a historical quirk from early camera APIs
- Channel 0 = Blue, Channel 1 = Green, Channel 2 = Red
The pixel values are identical — only the order differs. If you ignore this, you will get colour distortions when displaying OpenCV images with matplotlib.
Machine Learning follows a structured pipeline from data to deployment
Converting Between RGB and BGR
import cv2
import matplotlib.pyplot as plt
image_bgr = cv2.imread("photo.jpg") # Loaded in BGR
# Convert BGR to RGB for display with matplotlib
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
# What happens if you display BGR as RGB (the wrong way):
# Red and blue channels are swapped — reds look blue, blues look red
# Correct display with matplotlib:
plt.subplot(1, 2, 1)
plt.imshow(image_bgr) # WRONG: blue-ish tint
plt.title("BGR displayed as RGB — WRONG")
plt.subplot(1, 2, 2)
plt.imshow(image_rgb) # CORRECT
plt.title("BGR converted to RGB — CORRECT")
plt.show()
# Other common conversions
gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2HSV)
lab = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2LAB)
rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
back_bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)