A NumPy array, or ndarray, is an efficient n-dimensional array whose items have a specified data type. In OpenCV, captured camera frames are ndarrays, so the image can be inspected, saved, and passed directly to image-processing functions. section 8.3.1
For an OpenCV image array, inspect:
- shape, which reports image height, width, and color-component count; (480, 640, 3) describes a 480-pixel-high, 640-pixel-wide color image. section 8.3.1
- dtype, which reports the type of every array item; uint8 stores each color component as an 8-bit value from 0 to 255. section 8.3.1
- color channel order: OpenCV drawing uses BGR tuples rather than the more common RGB order. section 8.3.2
Create a drawable image
Create a black 640×480 color image with np.zeros(shape=(480, 640, 3), dtype=np.uint8). The zero-filled array becomes a black BGR canvas; OpenCV can then draw circles, lines, rectangles, and text onto the same ndarray before displaying it. section 8.3.2 section 8.3.2
Listing 8.1 draw.py: Drawing shapes of different sizes and positions using OpenCV
#!/usr/bin/env python3
import string
import numpy as np
import cv2
BLUE = (255, 0, 0)
GREEN = (0, 255, 0)
RED = (0, 0, 255)
img = np.zeros(shape=(480, 640, 3), dtype=np.uint8)
cv2.circle(img, center=(200, 110), radius=100, color=RED)
cv2.line(img, pt1=(0, 0), pt2=(200, 110), color=GREEN)
cv2.rectangle(img, pt1=(50, 250), pt2=(350, 350), color=BLUE)
text = string.ascii_lowercase
font = cv2.FONT_HERSHEY_SIMPLEX
pos = (10, 380)
cv2.putText(img, text, org=pos, fontFace=font, fontScale=1, color=RED)
cv2.imshow('preview', img)
cv2.waitKey()
This runnable script creates a uint8 ndarray, draws colored shapes and lowercase text onto it, and displays the finished image. section 8.3.2



