Images with OpenCV
Practical notes on using OpenCV (Python) for reading, writing, viewing, converting, resizing, accessing pixels, and basic processing (histogram, threshold, Canny) with clear definitions and exam-style examples.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
OpenCV is the most widely used open-source library for practical image processing and computer vision in engineering. An engineer uses OpenCV to load camera images, convert formats, measure image properties, apply basic filters (threshold, edges), and prepare image data for higher-level tasks (object detection, segmentation, compression). These are foundational skills for assignments and lab work in image processing and for many industry tasks in machine vision.
Key ideas
Draw this in an exam: a rectangle, label top-left as (0,0), x axis to the right, y axis downward, mark point (x0,y0) and draw a small square around it to show the pixel. Label width = W and height = H.
Grayscale image: single-channel image where each pixel is intensity (0..255 for uint8). Color image: multi-channel, typically 3 channels for visible colours.
Channel order in OpenCV: OpenCV uses BGR order (Blue, Green, Red) for images read by cv2.imread. This is a common exam trap: most other libraries (PIL, matplotlib) use RGB.
Image data type: common is unsigned 8-bit integer (uint8) per channel. Values 0..255. Some operations use floats (0.0..1.0) — be explicit about dtype and scaling.
Region of interest (ROI): a subarray slice of the image using end-exclusive indexing, e.g., roi = img[y1:y2, x1:x2]. If coordinates are given as inclusive endpoints (x1,y1) to (x2,y2), convert to slices as img[y1:y2+1, x1:x2+1]. In exams show indexing carefully with inclusive/exclusive endpoints.
Memory size: For an image of width W, height H, and C channels with dtype taking B bytes per sample, memory = W * H * C * B bytes. Example derivation: each pixel has C samples, each sample is B bytes, there are W*H pixels.
Grayscale conversion (linear formula): the perceived luminance Y is a weighted sum of R,G,B. Exact formula used by many standards (e.g., ITU-R BT.601): Y = 0.299·R + 0.587·G + 0.114·B. Since OpenCV's arrays are BGR, implement as Y = 0.114·B + 0.587·G + 0.299·R. This is a linear transformation applied per pixel.
- For exam derivation: show matrix form: [Y] = [0.114 0.587 0.299]·[B G R]^T and show summation across components.
Interpolation for resize: pixel values for new coordinates are computed from nearby source pixels using interpolation. Common methods: INTER_NEAREST (nearest neighbour), INTER_LINEAR (bilinear), INTER_AREA (good for decimation), INTER_CUBIC (bicubic). State when to use each: upsample → INTER_LINEAR or INTER_CUBIC; downsample → INTER_AREA.
Edge detection (Canny): multi-stage algorithm: smoothing (Gaussian), computing gradients, non-maximum suppression, double thresholding (low and high), edge tracking by hysteresis. Important parameters are low and high thresholds. Explain stages in numbered steps in exam answers.
Histogram: counts of pixel intensities per value or per bin. Useful for thresholding and contrast adjustment.
Diagrams to draw when asked: coordinate axes of image, block diagram of Canny stages (Gaussian → gradient → NMS → double threshold → link), and matrix showing channel order (B G R) with indices.
Formulas
memory_bytes = W * H * C * B — W width (pixels), H height (pixels), C channels (e.g., 3), B bytes per sample (e.g., 1 for uint8). Unit: bytes. Applies for raw array memory calculation.
Y = 0.114*B + 0.587*G + 0.299*R — grayscale luminance from BGR channels, unitless intensity (0..255 for uint8). Applies when converting color to grayscale.
pixel = image[y, x] — indexing rule. y row (0..H-1), x column (0..W-1). Applies to NumPy/OpenCV arrays.
Python/OpenCV syntax to remember:
img = cv2.imread(filename, flags) — read image. flags: cv2.IMREAD_COLOR, cv2.IMREAD_GRAYSCALE. IMREAD_GRAYSCALE returns a single-channel array of shape (H, W); IMREAD_COLOR returns (H, W, 3) in BGR.
cv2.imwrite(filename, img) — write image.
cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) — color conversion.
resized = cv2.resize(src, None, fx=fx, fy=fy, interpolation=...) — resize with scale factors.
ret, thresh = cv2.threshold(src, thresh_value, max_value, cv2.THRESH_BINARY) — global threshold returns ret (threshold used) and image. src must be a single-channel (grayscale) image.
edges = cv2.Canny(src, threshold1, threshold2) — Canny edge detector; src should be single-channel (uint8) — convert color with cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) first.
hist = cv2.calcHist([src], [channel], mask, [bins], [range]) — histogram calculation. For uint8 images use range [0, 256]; channel is 0 for grayscale or 0/1/2 for B/G/R.
roi = img[y1:y2, x1:x2] — ROI slicing (note NumPy end index exclusive: y2 is not included). Use inclusive endpoints carefully in exam answers.
Worked examples
Example 1 — create a synthetic color image, inspect channels, save
Python program (runs in any environment with cv2 and numpy):
import cv2
import numpy as np
# Create a 100x200 image with constant channels B=64, G=128, R=255
img = np.zeros((100, 200, 3), dtype=np.uint8)
img[:] = (64, 128, 255) # (B, G, R)
# Inspect properties
print('Image created:', img is not None)
print('Shape:', img.shape)
print('Dtype:', img.dtype)
# Channel means
b_mean = img[:, :, 0].mean()
g_mean = img[:, :, 1].mean()
r_mean = img[:, :, 2].mean()
print(f'Channel means: B={b_mean}, G={g_mean}, R={r_mean}')
# Save image
cv2.imwrite('out1.png', img)
print('Saved out1.png')
Sample input: none (code creates image).
Exact output when run:
Image created: True Shape: (100, 200, 3) Dtype: uint8 Channel means: B=64.0, G=128.0, R=255.0 Saved out1.png
Example 2 — resizing with different interpolations
import cv2
import numpy as np
# Start with the image from Example 1 (create again to be standalone)
img = np.zeros((100, 200, 3), dtype=np.uint8)
img[:] = (64, 128, 255)
# Upscale by factor 2 (fx=2, fy=2)
up = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
print('Upscaled shape:', up.shape)
# Downscale by factor 0.5
down = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
print('Downscaled shape:', down.shape)
Exact output when run:
Upscaled shape: (200, 400, 3) Downscaled shape: (50, 100, 3)
Example 3 — edge detection on a drawn rectangle (deterministic counts)
import cv2
import numpy as np
# Create black single-channel image
img = np.zeros((100, 100), dtype=np.uint8)
# Draw a white rectangle with corners (30,20) to (89,59) with thickness 1
cv2.rectangle(img, (30, 20), (89, 59), 255, 1)
# Apply Canny
edges = cv2.Canny(img, 100, 200)
# Count edge pixels (non-zero in edges)
count = int(np.count_nonzero(edges))
print('Edge pixel count:', count)
Note: The number of edge pixels returned by Canny on synthetic shapes is not strictly deterministic across OpenCV versions and depends on the Gaussian smoothing, gradient thresholds, and corner handling. Do not rely on an exact pixel count here; instead, explain the Canny stages and verify that clear edges are detected along the rectangle.
Common mistakes
- Forgetting dtype: treating uint8 as float without converting can cause overflow/rounding.
- Using cv2.imshow in a headless/non-GUI environment (e.g., some servers) — no output appears. Use imwrite or display via matplotlib after conversion.
- Wrong ROI endpoints: NumPy slices are end-exclusive; writing roi = img[y1:y2, x1:x2] excludes row y2 and column x2.
- Choosing wrong interpolation for resize (INTER_NEAREST for photographic upscaling gives blocky result; INTER_AREA better for downsampling).
- Misunderstanding Canny thresholds: the two numbers are not low/high intensity thresholds for final image but for gradient magnitude hysteresis.
For your exam
Types of questions you will get:
- Definitions and short notes: define pixel, ROI, BGR vs RGB, dtype, histogram.
- Derivations: show memory computation for an image; derive grayscale formula application and show matrix form.
- Programs: small Python/OpenCV snippets to read, convert, resize, threshold or count pixels; explain outputs.
- Numericals: compute memory given W,H,C and B, compute histogram bin counts from given image data.
- Diagrams: draw image coordinate system, Canny block diagram, explain channel order with arrow labels.
What a full-marks answer includes:
- Precise definitions (bold terms), correct formulas with units, careful indexing and endpoints, mention of dtype and channel order, and short sample code or pseudocode when required.
- For programs: mention imports (cv2, numpy), exact function names and parameters, and expected deterministic outputs for given inputs.
Quick check
- In OpenCV, what channel order does cv2.imread produce by default?
- How do you access the pixel at column x=10, row y=20 in code?
- Compute memory bytes for a 640x480 RGB image in uint8.
Answers: BGR; image[20, 10]; 640 * 480 * 3 * 1 = 921600 bytes
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?