Sub topic 1
How OpenCV Represents an Image
In OpenCV's Python bindings, an image is a NumPy array. There is no special image class. If you understand the array's shape, data type, and axis order, you can predict how almost every OpenCV function will behave. Most bugs in beginner OpenCV code come from misreading one of these three properties.
Prerequisites
This chapter assumes you have the following:
- Basic Python syntax and functions.
opencv-pythonandnumpyinstalled with pip (pip install opencv-python numpy).- Basic familiarity with NumPy arrays and indexing, including
shape,dtype, and slicing. - An understanding of pixels, width, height, and color channels.
The examples that load a file expect a photo.jpg in the working directory. The first examples build an image from scratch, so you can run them without any file.
An image is a NumPy array
A color image is a three-dimensional array of shape (height, width, channels). Each pixel is a short vector of channel values.
import cv2
import numpy as np
# 200 rows (height), 300 columns (width), 3 channels
img = np.zeros((200, 300, 3), dtype=np.uint8)
print(type(img)) # <class 'numpy.ndarray'>
print(img.shape) # (200, 300, 3)
print(img.dtype) # uint8
print(img.ndim) # 3
print(img.size) # 180000 values (200 * 300 * 3)
print(img.nbytes) # 180000 bytes, because uint8 uses one byte per valueAn image of all zeros is black. OpenCV's functions accept any array of this form, so arrays you build yourself work as well as arrays loaded from disk.
The three axes mean different things:
| Axis | Name | Meaning | Size for the array above |
|---|---|---|---|
| 0 | rows | Height, the vertical axis (y) | 200 |
| 1 | columns | Width, the horizontal axis (x) | 300 |
| 2 | channels | Color components per pixel | 3 |
The array is stored row by row in memory. This is why OpenCV loops and NumPy slices that walk along a row are fast, and why a vertical slice touches memory with a stride.
Loading an image and checking it
cv2.imread reads a file and returns the array. It does not raise an exception when the file is missing, unreadable, or in an unsupported format. It returns None. If you skip the check, the failure shows up later as a confusing AttributeError: 'NoneType' object has no attribute 'shape'.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
print(img.shape) # (height, width, 3)
print(img.dtype) # uint8
h, w = img.shape[:2]
b, g, r = img[0, 0] # channel order is blue, green, redUse img.shape[:2] to get height and width. It works for both color and grayscale images, which have different numbers of axes.
The next chapter covers loading in more detail. For now, note two defaults of imread:
- With no flag, it returns a 3-channel, 8-bit image. A PNG with transparency loses its alpha channel. Pass
cv2.IMREAD_UNCHANGEDto keep it, and you get four channels. - It applies the EXIF orientation stored in the file by default. A phone photo can therefore come back with different dimensions than the raw pixel data suggests.
cv2.IMREAD_IGNORE_ORIENTATIONturns this off.
Channel order is BGR, not RGB
OpenCV stores the three channels as blue, green, red. This is a historical choice, and it is the default for loading, saving, and drawing.
import cv2
import numpy as np
img = np.zeros((200, 300, 3), dtype=np.uint8)
img[:, :] = (255, 0, 0) # B=255, G=0, R=0
print(img[0, 0]) # [255 0 0]
cv2.imwrite("blue.png", img) # a pure blue imageThe tuple (255, 0, 0) is blue here. In an RGB library it would be red. The same convention applies to the color tuples you pass to drawing functions, so (0, 0, 255) draws red.
The convention matters when you move arrays between libraries. Matplotlib, Pillow, and most deep learning frameworks expect RGB. If you pass a BGR array to them, red and blue swap and skin tones look blue. Convert explicitly:
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)You may also see img[:, :, ::-1] used to reverse the channels. It is shorter, but it returns a view with negative strides. Some OpenCV functions reject such arrays or behave unexpectedly. Wrap it in np.ascontiguousarray(...) if you use it before calling OpenCV again.
Indexing is (row, column), points are (x, y)
NumPy indexes an array as [row, column], which means [y, x]. OpenCV drawing and geometry functions take points as (x, y). Both orders appear in the same program, and mixing them up is the most common coordinate bug.
import numpy as np
img = np.zeros((200, 300, 3), dtype=np.uint8) # height 200, width 300
img[10, 20] = (0, 255, 0) # row 10 (y), column 20 (x): a green pixel
print(img[10, 20]) # [ 0 255 0]
print(img[10, 20, 1]) # 255, the green channel only
# The largest valid indices are height - 1 and width - 1
print(img[199, 299]) # last pixel, fine
# img[200, 0] # IndexError: row 200 is out of boundsA third order exists in cv2.resize, which takes its target size as (width, height). The following table summarizes where each order applies.
| Where | Order | Example |
|---|---|---|
| `img.shape` | (height, width, channels) | `(200, 300, 3)` |
| NumPy indexing and slicing | [row, column] = [y, x] | `img[10, 20]` |
| Drawing points | (x, y) | `cv2.circle(img, (20, 10), ...)` |
| `cv2.resize` `dsize` | (width, height) | `cv2.resize(img, (300, 200))` |
Whenever you write a coordinate, ask yourself which of these conventions the function uses.
Grayscale images have no channel axis
A grayscale image has one value per pixel. OpenCV represents it as a two-dimensional array, not a (h, w, 1) array.
import cv2
gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError("Could not read photo.jpg")
print(gray.shape) # (height, width)
print(gray.ndim) # 2
print(gray[0, 0]) # a single integer, 0 to 255Code that assumes three axes breaks on these arrays. img.shape[2] raises an IndexError, and unpacking h, w, c = img.shape raises a ValueError. If a function must handle both kinds, check img.ndim. If you need to draw a colored annotation on a grayscale image, convert it to BGR first with cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR). Otherwise only the first channel value is used and the color is lost.
Data type and value range
Loaded images are uint8: unsigned 8-bit integers from 0 to 255. Arithmetic on uint8 arrays wraps around in NumPy but saturates in OpenCV.
import cv2
import numpy as np
a = np.array([[200]], dtype=np.uint8)
b = np.array([[100]], dtype=np.uint8)
print(a + b) # [[44]] wraps around: 300 - 256
print(cv2.add(a, b)) # [[255]] saturates at the maximumBecause of this, brightness changes written as img + 50 produce dark speckles where bright pixels overflow. Use cv2.add or convert to a wider type first.
Many numerical workflows convert to float32 and scale to the range 0 to 1:
import cv2
import numpy as np
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
f = img.astype(np.float32) / 255.0
print(f.dtype, f.min(), f.max()) # float32, values within 0.0 to 1.0
back = np.clip(f * 255.0, 0, 255).astype(np.uint8)Convert back to uint8 before saving or displaying. cv2.imwrite expects 8-bit data for common formats like JPEG, and cv2.imshow treats floats as the range 0 to 1, so a float image holding values up to 255 shows as nearly all white.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `AttributeError: 'NoneType' object has no attribute 'shape'` | `imread` failed silently: wrong path, wrong working directory, or unsupported file | Check `img is None` right after loading, and print the absolute path |
| Colors look swapped (blue skin) | BGR array shown with an RGB library | Convert with `cv2.COLOR_BGR2RGB` |
| `IndexError` on `img[x, y]` | Row and column swapped | Index as `img[y, x]` |
| `ValueError: not enough values to unpack` | Grayscale image given to code that expects 3 axes | Check `img.ndim` or convert with `COLOR_GRAY2BGR` |
| Bright spots turn dark after adding a constant | `uint8` wraparound | Use `cv2.add` or work in `float32` |
| Float image looks all white | `imshow` expects floats in 0 to 1 | Scale to 0 to 1, or convert to `uint8` |
Exercises
Exercise
An image loaded with cv2.imread has shape (480, 640, 3). What are its width and height in pixels, which index addresses the pixel in row 100 and column 200, and what point would you pass to cv2.circle to draw on that same pixel?
Show answer
Height is 480 and width is 640, because the shape is (height, width, channels). The pixel is img[100, 200] (row, then column). Drawing functions take (x, y), so you would pass (200, 100) as the center.
Exercise
You load a photo with cv2.imread, pass it unchanged to matplotlib's plt.imshow, and the sky appears orange. Why does this happen, and what is the one-line fix?
Show answer
OpenCV stores channels in BGR order, but matplotlib assumes RGB, so the blue and red channels are swapped. Convert before plotting: rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB), then call plt.imshow(rgb).
Exercise
Given a = np.array([[250]], dtype=np.uint8), what do a + 10 and cv2.add(a, np.array([[10]], dtype=np.uint8)) return, and why do they differ?
Show answer
a + 10 gives 4, because NumPy wraps uint8 arithmetic modulo 256 (260 - 256). cv2.add gives 255, because OpenCV saturates results to the uint8 range 0 to 255.