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!
Reading an Image
The first step in any Computer Vision pipeline is loading an image from disk. OpenCV's cv2.imread() is the standard way to do this in Python.
cv2.imread() Explained
cv2.imread(path, flag) loads an image from the file path you specify.
The flag controls how the image is read:
- cv2.IMREAD_COLOR (1): load as colour BGR — default behaviour
- cv2.IMREAD_GRAYSCALE (0): load as grayscale
- cv2.IMREAD_UNCHANGED (-1): load as-is, including alpha channel if present
Common mistake: cv2.imread() does NOT raise an error if the file is not found. Instead it returns None. Always check the return value before using the image.
Machine Learning follows a structured pipeline from data to deployment
Reading Images Safely
import cv2
import sys
def load_image(path, flag=cv2.IMREAD_COLOR):
"""Load an image with proper error handling."""
image = cv2.imread(path, flag)
if image is None:
print(f"Error: Could not load image from '{path}'")
print("Check: Does the file exist? Is the path correct?")
sys.exit(1)
print(f"Loaded: {path}")
print(f"Shape: {image.shape}")
print(f"Data type: {image.dtype}")
return image
# Load as colour (default — BGR format)
img_colour = load_image("photo.jpg")
# Load as grayscale
img_gray = load_image("photo.jpg", cv2.IMREAD_GRAYSCALE)
print(f"Grayscale shape: {img_gray.shape}") # (H, W) — no channel dim
# Load with alpha channel (PNG with transparency)
# img_rgba = load_image("image.png", cv2.IMREAD_UNCHANGED)
# print(f"RGBA shape: {img_rgba.shape}") # (H, W, 4)