liveBook · Manning

NumPy array

As explained in Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi

An ndarray is a NumPy multidimensional array containing values of a specified data type.

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

How Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi covers it

How deep it goes
Explains shape and dtype through camera images, then creates a zero-filled array for drawing without covering ndarray internals.
Examples
Uses a 640×480 camera frame and a black uint8 canvas with a circle, line, rectangle, and lowercase alphabet.
What you can do after
Apply it via NumPy and OpenCV to inspect captured images and create drawable image buffers.
How it connects
Connects NumPy arrays to OpenCV, camera capture, image shape, dtype, BGR color encoding, and drawing functions.

Also explained in

Compare how 4 books explain NumPy array →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi. The section links point to the parts of the book it draws on.