Sub topic 1
How OpenCV represents an image
OpenCV represents a color image as a NumPy array. The array stores pixel values in rows and columns, so image processing becomes array processing.
Prerequisites
This chapter assumes basic Python syntax, functions, package installation with pip, and basic NumPy array indexing. You should know that an image has a width, height, and color channels.
The image array model
A typical color image has three dimensions:
- Height: the number of rows of pixels.
- Width: the number of columns of pixels.
- Channels: the values that describe each pixel's color.
OpenCV uses the shape order (height, width, channels). For example, (480, 640, 3) means 480 pixels high, 640 pixels wide, with three color channels.
OpenCV normally stores color channels in BGR order:
- B: blue
- G: green
- R: red
This differs from the RGB order used by many other libraries. A pixel with the value (255, 0, 0) is blue in OpenCV, not red.
Most images loaded from common formats use the uint8 data type. Each channel stores an integer from 0 through 255. Zero means no intensity, and 255 means full intensity.
| Image value | Meaning |
|---|---|
| `shape == (480, 640, 3)` | 480 rows, 640 columns, three color channels |
| `dtype == uint8` | Each channel uses an 8-bit integer |
| `image[y, x]` | Pixel at row `y`, column `x` |
| `image[y, x] == (b, g, r)` | Pixel values in blue, green, red order |
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
print(img.shape)
print(img.dtype)
height, width = img.shape[:2]
blue, green, red = img[0, 0]
print(f"width={width}, height={height}")
print(f"top-left pixel: B={blue}, G={green}, R={red}")NumPy indexing uses [row, column], which is [y, x]. This is different from the coordinate convention used by many OpenCV drawing functions, where points are written as (x, y).
Color and grayscale arrays
A grayscale image has one intensity value per pixel, so its shape has only two dimensions: (height, width). It does not have a third channel dimension.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(img.shape) # For example: (480, 640, 3)
print(gray.shape) # For example: (480, 640)
print(gray.dtype) # uint8If you pass an OpenCV BGR array directly to a library that expects RGB, the colors may appear swapped. Convert it explicitly when needed:
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)Understanding these conventions prevents errors when reading pixels, passing arrays between libraries, or drawing on an image.
Exercise
An image has shape == (720, 1280, 3) and dtype == uint8. What do these values describe, and what does image[20, 40] return?
Show answer
The image is 720 pixels high, 1280 pixels wide, and has three BGR channels. image[20, 40] returns the BGR values for the pixel at column 40 and row 20.