๐๏ธ Computer Vision with OpenCV
in Python
Learn OpenCV and computer vision basics: images as arrays, BGR vs RGB, grayscale, thresholding, blur, edges, histograms, contours, video and Haar cascades.
What this lesson is about
OpenCV is the most widely used library for computer vision: reading images, changing them, finding edges and shapes, detecting faces and processing video from a file or a webcam. In Python you use it through the cv2 module. It powers things like document scanners, barcode readers, motion detectors, quality-inspection scripts and the pre-processing step in front of many machine learning models.
The idea that makes the whole library click is simple: an image is just a NumPy array of numbers. A grayscale picture is a grid of brightness values, and a colour picture is a grid of three-number pixels. Once you see that, filters and detectors stop being magic. A blur is an average of neighbouring numbers, an edge is a place where the numbers jump, and a threshold is a comparison that turns brightness into black or white.
OpenCV needs the compiled cv2 package, a camera or image files, and often a window to display results, none of which exist inside a web page. So I teach this lesson in two layers. The examples you can press Run on rebuild the core ideas, such as grayscale conversion, thresholding, convolution, Sobel edges, histograms and bounding boxes, with plain NumPy on tiny matrices you can read number by number. Beside them I show the real cv2 calls as static code to run on your own computer, where you can use your own pictures.
What you will learn
- โExplain how an image is stored as a NumPy array with shape, dtype and channels
- โUnderstand why OpenCV uses BGR order and how to convert to RGB
- โConvert colour to grayscale and see the weighted formula behind it
- โApply thresholding to turn brightness into a black-and-white mask
- โUnderstand convolution kernels, blur and Sobel edge detection on small matrices
- โRead an intensity histogram and see what contrast stretching does
- โFind bounding boxes of regions, and know how
findContoursdoes it for you - โWrite the real
imread,VideoCapture,Cannyand Haar cascade code
Why programmers should learn this
- โ Cameras are everywhere, so scripts that can read, clean and measure images are useful in hobby projects, research labs, factories and apps alike.
- โ Classic computer vision techniques are fast, need no training data and run on small devices, which makes them a good first choice before reaching for a neural network.
- โ Even deep learning pipelines rely on OpenCV-style steps such as resizing, colour conversion, normalising and drawing boxes on results.
- โ Learning how a filter works on a matrix of numbers builds intuition for convolutional neural networks, which apply the same operation with learned kernels.
- โ Image code is wonderfully visual feedback: a mistake in your logic shows up as a strange picture, which makes debugging a very satisfying way to learn.
An image is an array of numbers
A digital image is a grid of pixels. In a grayscale image each pixel is one number, usually from 0 (black) to 255 (white), stored as an unsigned 8-bit integer, which NumPy calls uint8. A colour image has three numbers per pixel, one for each colour channel, so its array has shape (height, width, 3). Notice that the height comes first, then the width: rows before columns, exactly like a matrix.
To address a pixel you use image[row, column], which means image[y, x]. This reverses the (x, y) order you may know from coordinates, and it is a source of endless confusion, so say it out loud: row first. Slicing works too, so image[0:2, 1:4] is a small rectangle cut out of the picture, a technique called a region of interest.
The example builds a tiny six-by-eight 'image' by hand so every pixel can be printed. In real code cv2.imread returns exactly this kind of array from a file on disk. Watch the uint8 dtype in particular: arithmetic on it can wrap around, a gotcha we will meet again shortly.
import numpy as np
img = np.zeros((6, 8), dtype=np.uint8) # 6 rows, 8 columns, all black
img[1:4, 2:6] = 200 # a bright rectangle
img[4, 0] = 255 # one white pixel
print(img.shape, img.dtype)
print(img)
print("pixel at row 2, col 3:", img[2, 3])
print("region of interest:")
print(img[1:3, 2:5])
print("mean brightness:", round(float(img.mean()), 3))
color = np.zeros((2, 3, 3), dtype=np.uint8)
print("colour shape:", color.shape, "-> height, width, channels")(6, 8) uint8 [[ 0 0 0 0 0 0 0 0] [ 0 0 200 200 200 200 0 0] [ 0 0 200 200 200 200 0 0] [ 0 0 200 200 200 200 0 0] [255 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0]] pixel at row 2, col 3: 200 region of interest: [[200 200 200] [200 200 200]] mean brightness: 55.312 colour shape: (2, 3, 3) -> height, width, channels
Line by line
- 1NumPy is all we need to represent an image.
- 3-5Create a 6 by 8 grayscale image filled with zeros (black), then paint a bright rectangle using slices and set a single pixel to white. Slices are
[rows, columns]. - 7-8
shapeis(6, 8), which is height then width, and the dtype isuint8. Printing the array shows the picture as numbers. - 9Read one pixel. Row 2 and column 3 sits inside the rectangle, so it prints 200.
- 10-12Cut out a region of interest with a slice and compute the average brightness of the whole image.
- 14-15A colour image adds a third axis of length 3. This one is 2 rows by 3 columns of three-channel pixels.
Real photographs are big: a 12-megapixel photo is about 36 million numbers. That is why vectorised NumPy and OpenCV code, which avoids Python loops over pixels, matters so much.
BGR versus RGB
Most of the world stores colour as red, green, blue. OpenCV, for historical reasons, does it the other way round: blue, green, red. When cv2.imread loads a file, image[y, x] gives you [blue, green, red]. If you hand that array to Matplotlib or Pillow, which expect RGB, the reds and blues swap and skin turns blue. It is a rite of passage for every OpenCV beginner.
The fix is to reverse the channel axis. Because a colour image is an array, reversing the last axis with img[:, :, ::-1] does it, and cv2.cvtColor(img, cv2.COLOR_BGR2RGB) does the same thing in a more explicit way. I prefer cvtColor in real code because the intent is written in the name, and I show both so that you can see there is no magic.
In the runnable example I create a one-pixel-high image containing a pure red pixel written the OpenCV way, then convert it and show that the numbers reorder. The static block below it is the real file-reading code, including the single most important line in OpenCV scripts: checking whether imread returned None.
import numpy as np
# One row of three pixels, written in OpenCV's BGR order
bgr = np.array([[[0, 0, 255], # pure red (B=0, G=0, R=255)
[0, 255, 0], # pure green
[255, 0, 0]]], # pure blue
dtype=np.uint8)
rgb = bgr[:, :, ::-1] # reverse the channel axis
print("BGR:", bgr.tolist())
print("RGB:", rgb.tolist())
b, g, r = bgr[:, :, 0], bgr[:, :, 1], bgr[:, :, 2]
print("blue channel :", b.tolist())
print("red channel :", r.tolist())BGR: [[[0, 0, 255], [0, 255, 0], [255, 0, 0]]] RGB: [[[255, 0, 0], [0, 255, 0], [0, 0, 255]]] blue channel : [[0, 0, 255]] red channel : [[255, 0, 0]]
Line by line
- 3-6Build a 1 by 3 image. Each pixel lists blue, green, red in that order, so the first pixel
[0, 0, 255]is pure red as OpenCV sees it. - 8-10Reversing the last axis with
::-1swaps the first and third numbers. The red pixel becomes[255, 0, 0], which is how RGB tools expect red to look. - 12-14Split the channels by indexing the last axis. In BGR, channel 0 is blue and channel 2 is red.
import cv2
img = cv2.imread("photo.jpg") # BGR, uint8, shape (height, width, 3)
if img is None:
raise SystemExit("Could not read photo.jpg: check the path")
print(img.shape, img.dtype)
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # for Matplotlib or Pillow
cv2.imwrite("copy.png", img) # save (expects BGR)
small = cv2.resize(img, (320, 240)) # (width, height) order!
cv2.imshow("preview", small) # needs a desktop window
cv2.waitKey(0)
cv2.destroyAllWindows()Line by line
- 1Import OpenCV. The package is installed as
opencv-pythonbut imported ascv2. - 3-5
imreadreturnsNone, not an error, when the file is missing or unreadable, so check it right away. - 7-9Print the array shape, convert to RGB for other libraries, and write a copy.
imwritepicks the format from the extension. - 11
resizetakes the new size as(width, height), the opposite of the array's(height, width)shape order. - 12-14Show the picture in a window, wait for a key press, then close the windows. This only works on a computer with a display.
cv2.resize wants (width, height) while img.shape reports (height, width). Mixing them up produces a stretched picture without any error message.
Grayscale conversion
Many algorithms do not care about colour. Edge detection, thresholding and face detection work on brightness alone, and a single channel is three times less data to process. Converting to grayscale means collapsing the three colour values of each pixel into one brightness value.
You might expect a plain average of the three channels, but human eyes are far more sensitive to green than to blue, so the standard conversion is a weighted sum: roughly 0.299 times red, plus 0.587 times green, plus 0.114 times blue. OpenCV's cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) uses these weights. A bright pure green therefore looks much brighter in grayscale than a pure blue of the same channel value.
In the example I apply the formula to a small BGR image with NumPy. The weights are written in B, G, R order because the data is BGR. I round and convert back to uint8, which is what OpenCV would return. If you run the real function on the same pixels you get the same numbers, because a formula is all it is.
import numpy as np
# 2x3 image in BGR order
bgr = np.array([
[[255, 0, 0], [0, 255, 0], [0, 0, 255]], # blue, green, red
[[255, 255, 255], [0, 0, 0], [128, 128, 128]], # white, black, gray
], dtype=np.uint8)
weights = np.array([0.114, 0.587, 0.299]) # B, G, R
gray = np.round(bgr @ weights).astype(np.uint8)
print(gray)
plain_mean = np.round(bgr.mean(axis=2)).astype(np.uint8)
print("simple average for comparison:")
print(plain_mean)[[ 29 150 76] [255 0 128]] simple average for comparison: [[ 85 85 85] [255 0 128]]
Line by line
- 3-6Make a two-row BGR image with a blue, a green and a red pixel on the first row, and white, black and mid-gray on the second.
- 8-10The matrix product
bgr @ weightsmultiplies each pixel's three channels by the weights and adds them, giving one brightness per pixel. Round and cast back touint8. - 12-14Compute a naive average for comparison. Pure blue, green and red all come out as 85, while the weighted version says green is far brighter than blue.
import cv2
img = cv2.imread("photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # shape (height, width)
print(gray.shape)
# or load straight as grayscale
gray2 = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)Line by line
- 3-4Convert a loaded colour image to a single channel. The result has only two dimensions.
- 7If you only need grayscale, asking
imreadfor it directly saves a step and some memory.
Thresholding: black or white
Thresholding is the simplest segmentation tool in computer vision: pick a number, and turn every pixel brighter than it white and every other pixel black. The result is a mask, an array of just two values that marks which pixels belong to something interesting, such as dark text on pale paper or a bright object on a dark table.
In NumPy it is a single comparison. img > 100 returns an array of True and False, and multiplying by 255 or using np.where turns that into the familiar 0 and 255 image. OpenCV's cv2.threshold does the same and adds modes, for example inverting the result, and an automatic mode called Otsu's method that picks the threshold for you by looking at the histogram of the image.
A single global threshold struggles when lighting is uneven, such as a page with a shadow across it. For that, cv2.adaptiveThreshold computes a separate threshold for each small neighbourhood. The example below shows the core idea on a matrix you can inspect, followed by the real calls.
import numpy as np
img = np.array([
[ 12, 30, 45, 60, 210],
[ 20, 90, 180, 200, 220],
[ 25, 110, 190, 230, 240],
[ 15, 40, 170, 250, 255],
], dtype=np.uint8)
mask = np.where(img > 100, 255, 0).astype(np.uint8)
print(mask)
print("bright pixels:", int((mask == 255).sum()), "of", mask.size)
inverted = 255 - mask
print(inverted[0])
# Otsu-style idea: try every threshold, keep the one that best separates two groups
best_t, best_score = 0, -1.0
for t in range(1, 255):
low, high = img[img <= t], img[img > t]
if len(low) == 0 or len(high) == 0:
continue
w0, w1 = len(low) / img.size, len(high) / img.size
score = w0 * w1 * (low.mean() - high.mean()) ** 2 # between-class variance
if score > best_score:
best_t, best_score = t, score
print("auto threshold:", best_t)[[ 0 0 0 0 255] [ 0 0 255 255 255] [ 0 255 255 255 255] [ 0 0 255 255 255]] bright pixels: 11 of 20 [255 255 255 255 0] auto threshold: 110
Line by line
- 3-8A tiny image whose left side is dark and right side is bright, with a few mid-tones.
- 10-11
np.wherewrites 255 where the condition is true and 0 elsewhere. That array is the binary mask. - 13Count the white pixels with a boolean sum.
- 14-15Inverting is just
255 - mask, swapping the roles of foreground and background. - 17-26A simplified Otsu search. For every possible threshold, split the pixels into a dark group and a bright group and measure how far apart their averages are, weighted by group size. The best split is the one with the largest between-class variance.
import cv2
gray = cv2.imread("page.jpg", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
_, inverted = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
t, otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print("Otsu chose", t)
adaptive = cv2.adaptiveThreshold(
gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 10
)
cv2.imwrite("page_clean.png", adaptive)Line by line
- 3Load a photo of a page as grayscale.
- 5-6
thresholdreturns two values: the threshold used and the new image. The inverse mode makes dark things white. - 7-8With
THRESH_OTSUthe threshold you pass (0) is ignored and OpenCV computes one, which it returns ast. - 10-13Adaptive thresholding decides per neighbourhood: a 31 by 31 pixel block, minus a constant of 10. It copes with shadows across a page.
Convolution, blur and Sobel edges on small matrices
A convolution slides a small grid of weights, the kernel, across the image. At each position you multiply the kernel by the pixels underneath, add up the products and write the sum into the output. Choosing different kernels gives you completely different effects from the same machinery: averaging weights blur an image, and weights with opposite signs on two sides detect where brightness changes.
A blur uses a kernel whose weights are all equal and sum to 1, so each output pixel is the average of its neighbours. That smooths out noise, which is why blur is usually the first step before edge detection. An edge is a place where brightness jumps. The Sobel kernel [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] responds strongly to a left-to-right change: it subtracts the left side from the right side, with extra weight on the middle row. A flat area gives 0, and a vertical edge gives a large number.
Strictly, what image libraries call convolution is usually correlation, because they do not flip the kernel; for symmetric kernels such as a blur it makes no difference. In the example I write the sliding window in NumPy and apply a 3 by 3 blur and Sobel to a five-by-five image with a sharp vertical edge. I compute only the interior pixels where the kernel fits fully, and these match the interior values that OpenCV produces for the same input.
import numpy as np
img = np.array([[10, 10, 10, 200, 200]] * 5, dtype=float)
def slide(image, kernel):
kh, kw = kernel.shape
out_h = image.shape[0] - kh + 1
out_w = image.shape[1] - kw + 1
out = np.zeros((out_h, out_w))
for r in range(out_h):
for c in range(out_w):
window = image[r:r + kh, c:c + kw]
out[r, c] = (window * kernel).sum()
return out
blur_kernel = np.ones((3, 3)) / 9
sobel_x = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
print("image row:", img[0].astype(int).tolist())
print("blurred :", np.round(slide(img, blur_kernel)[0], 1).tolist())
print("sobel x :", slide(img, sobel_x)[0].tolist())
print("sobel y :", slide(img, sobel_x.T)[0].tolist())image row: [10, 10, 10, 200, 200] blurred : [10.0, 73.3, 136.7] sobel x : [0.0, 760.0, 760.0] sobel y : [0.0, 0.0, 0.0]
Line by line
- 3Five identical rows, each dark on the left and bright on the right, so there is one sharp vertical edge between columns 2 and 3.
- 5-14A sliding-window function. For each position it takes a window the size of the kernel, multiplies it element by element with the kernel, sums the result and stores it. The output is smaller than the input by
kernel size - 1. - 16-19Two kernels: a 3 by 3 averaging blur whose weights sum to 1, and the Sobel kernel for horizontal change.
- 21-22The blur turns the jump from 10 to 200 into a gradual ramp (10, 73.3, 136.7).
- 23-24Sobel in x gives 0 on flat parts and a strong response, 760, beside the edge. Using the transposed kernel looks for vertical change; every row is the same, so it finds none and returns zeros.
import cv2
gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)
blurred = cv2.GaussianBlur(gray, (5, 5), 0) # kernel size must be odd
sobel_x = cv2.Sobel(blurred, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(blurred, cv2.CV_64F, 0, 1, ksize=3)
edges = cv2.Canny(blurred, 50, 150) # low and high thresholds
cv2.imwrite("edges.png", edges)Line by line
- 3Load the picture in grayscale.
- 5
GaussianBluris a blur that weights nearby pixels more than far ones. The0tells OpenCV to work out the spread from the kernel size. - 6-7Sobel with
CV_64Fkeeps negative values, which auint8output would clip.(1, 0)means horizontal change and(0, 1)vertical. - 9-10
Cannyis a complete edge detector: it computes gradients, thins the edges, and keeps strong edges plus weak edges connected to them. The two numbers are its hysteresis thresholds.
When you ask Sobel for an 8-bit result, negative gradients are clipped to 0 and half your edges vanish. Use a floating-point depth such as cv2.CV_64F, then take np.abs before displaying.
Histograms and contrast
A histogram counts how many pixels have each brightness value. For an 8-bit image there are 256 bins, from 0 to 255. Looking at the histogram tells you about exposure: if all the counts are bunched at the dark end the picture is under-exposed, and if they occupy a narrow band in the middle it has low contrast.
NumPy computes one with np.bincount(img.ravel(), minlength=256). ravel flattens the grid into a single list of values, and bincount counts occurrences of each integer. OpenCV's cv2.calcHist does the same job and can also build histograms for colour channels or with a mask.
Once you have the numbers you can improve contrast. Contrast stretching is the simplest approach: map the darkest pixel to 0 and the brightest to 255 with a straight line. Histogram equalisation, available as cv2.equalizeHist, spreads the values using the cumulative distribution so the output uses the full range more evenly. The example builds a dull, low-contrast picture and stretches it.
import numpy as np
rng = np.random.default_rng(4)
dull = rng.integers(90, 140, size=(50, 50)).astype(np.uint8) # narrow brightness range
counts = np.bincount(dull.ravel(), minlength=256)
print("min/max before:", int(dull.min()), int(dull.max()))
print("most common brightness:", int(counts.argmax()))
print("pixels counted:", int(counts.sum()))
lo, hi = float(dull.min()), float(dull.max())
stretched = ((dull - lo) / (hi - lo) * 255).round().astype(np.uint8)
print("min/max after:", int(stretched.min()), int(stretched.max()))
# group into 4 coarse bins for a readable summary
coarse = np.bincount(stretched.ravel() // 64, minlength=4)
print("pixels per quarter of the range:", coarse.tolist())min/max before: 90 139 most common brightness: 130 pixels counted: 2500 min/max after: 0 255 pixels per quarter of the range: [645, 581, 579, 695]
Line by line
- 3-4Create a 50 by 50 grayscale image whose values only run from 90 to 139, which is a flat-looking, low-contrast picture.
- 6-8Flatten the image and count each brightness.
counts[v]is the number of pixels with brightnessv; the counts must add up to 2500. - 10-12Contrast stretching: subtract the minimum, divide by the range so values lie in 0 to 1, multiply by 255. The darkest pixel is now 0 and the brightest 255.
- 14-16Divide by 64 to group the 256 levels into four coarse bins, which is easy to read as text.
import cv2
gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)
hist = cv2.calcHist([gray], [0], None, [256], [0, 256]) # shape (256, 1)
equalised = cv2.equalizeHist(gray)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
local = clahe.apply(gray) # adaptive, avoids over-amplifying noise
cv2.imwrite("equalised.png", equalised)Line by line
- 5
calcHisttakes a list of images, the channel number, an optional mask, the bin count and the value range, and returns 256 counts. - 6
equalizeHistredistributes brightness over the whole range using the cumulative histogram. - 8-9CLAHE does equalisation separately in small tiles with a limit on contrast boost, which often looks more natural than global equalisation.
Finding regions and bounding boxes
After thresholding, a picture is a mask where white pixels are the objects you care about. The next question is usually 'where are they, and how big?'. A bounding box is the smallest upright rectangle that contains a shape, described by its top-left corner and its width and height: (x, y, w, h). Boxes are what you draw around detected faces, cars or products.
To get a box you first need to know which white pixels belong together. A connected component is a group of white pixels that touch each other. A simple way to find them is a flood fill: start at an unvisited white pixel, spread to its white neighbours until you run out, then record the smallest and largest row and column you visited. That minimum and maximum give the box.
OpenCV does this far faster and more flexibly with cv2.findContours, which traces the outline of each shape, followed by cv2.boundingRect for the box and cv2.contourArea for the size. My runnable version makes the logic visible on a mask you can read. Notice that I convert between (row, column) and (x, y); in image code that conversion is where most bugs hide.
import numpy as np
mask = np.array([
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
], dtype=np.uint8)
def find_boxes(mask):
seen = np.zeros_like(mask, dtype=bool)
boxes = []
for r in range(mask.shape[0]):
for c in range(mask.shape[1]):
if mask[r, c] and not seen[r, c]:
stack, rows, cols = [(r, c)], [], []
seen[r, c] = True
while stack:
y, x = stack.pop()
rows.append(y)
cols.append(x)
for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
ny, nx = y + dy, x + dx
if (0 <= ny < mask.shape[0] and 0 <= nx < mask.shape[1]
and mask[ny, nx] and not seen[ny, nx]):
seen[ny, nx] = True
stack.append((ny, nx))
x0, y0 = min(cols), min(rows)
w, h = max(cols) - x0 + 1, max(rows) - y0 + 1
boxes.append((x0, y0, w, h, len(rows)))
return boxes
for x, y, w, h, area in find_boxes(mask):
print(f"box x={x} y={y} w={w} h={h} area={area}")box x=1 y=1 w=2 h=2 area=4 box x=6 y=2 w=2 h=3 area=5 box x=2 y=4 w=3 h=2 area=4
Line by line
- 3-11A 7 by 9 mask with three separate white blobs: a square, a small bar and an L shape.
- 13-15A function that scans for white pixels not yet visited.
seenremembers which have been assigned to a blob. - 16-18On finding a new white pixel, start a stack-based flood fill.
rowsandcolscollect every pixel in this blob. - 19-27Pop a pixel, record it, and push its four neighbours if they are inside the image, white and unseen.
- 28-30The blob's bounding box starts at its smallest column and row. Width and height are max minus min plus one, because both ends count.
- 33-34Print each box as x, y, width, height and the blob's pixel area.
import cv2
gray = cv2.imread("coins.jpg", cv2.IMREAD_GRAYSCALE)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, mask = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
color = cv2.imread("coins.jpg")
for cnt in contours:
if cv2.contourArea(cnt) < 200: # ignore specks of noise
continue
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(color, (x, y), (x + w, y + h), (0, 255, 0), 2) # BGR green
cv2.imwrite("boxes.png", color)
print("found", len(contours), "outlines")Line by line
- 3-5Load, smooth and threshold. Inverting makes dark objects on a pale background white, because
findContourslooks for white shapes. - 7Find the outer outline of each white shape.
RETR_EXTERNALignores holes inside shapes andCHAIN_APPROX_SIMPLEstores only corner points. - 9-15For each outline larger than 200 pixels, get its bounding rectangle and draw it on the colour image. The colour tuple is BGR, so
(0, 255, 0)is green. - 17-18Save the annotated picture and report how many outlines were found.
Video, Canny and Haar cascades
A video is a sequence of images, called frames. cv2.VideoCapture opens either a file path or a camera index (0 for the default webcam), and each call to read() returns a pair: a boolean saying whether a frame was obtained, and the frame as an ordinary BGR array. Everything you learned above works on a frame, so processing video is a while loop around image code.
Remember to release the capture when finished and to check the boolean. When a file ends or the camera is unplugged, read() returns False and an empty frame; code that ignores this crashes with confusing errors. Pressing a key to quit is done with cv2.waitKey, which also gives the window time to redraw. Without it no window ever appears.
Haar cascades are an older, fast method for detecting objects such as faces. A trained cascade file ships with OpenCV and you load it with cv2.CascadeClassifier. It scans the image at many scales and returns rectangles, so it plugs into the bounding box code we already have. It is easy to use but it finds mostly frontal faces and produces false positives; modern deep learning detectors are more accurate, and I recommend them for serious work. The code below is static because it needs a camera or video file and a window, which a web page does not have.
import cv2
cap = cv2.VideoCapture(0) # 0 = default webcam; or a path like "clip.mp4"
if not cap.isOpened():
raise SystemExit("Cannot open the camera")
face_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
faces = cv2.CascadeClassifier(face_path)
while True:
ok, frame = cap.read()
if not ok: # end of file or camera lost
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
found = faces.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(40, 40))
for (x, y, w, h) in found:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
edges = cv2.Canny(gray, 80, 160)
cv2.imshow("camera", frame)
cv2.imshow("edges", edges)
if cv2.waitKey(1) & 0xFF == ord("q"): # press q to quit
break
cap.release()
cv2.destroyAllWindows()Line by line
- 3-5Open the default camera (or pass a video file name) and stop with a clear message if it failed.
- 7-8Load the bundled face model.
cv2.data.haarcascadesis the folder where OpenCV installs its trained files. - 10-13Read one frame each time round the loop.
okbecomesFalsewhen there are no more frames. - 15-18Detectors work on grayscale.
detectMultiScalereturns a list of(x, y, w, h)boxes.minNeighborsraises or lowers how strict the detector is, andminSizeignores tiny false hits. Each face gets a blue box (BGR). - 20-23Compute Canny edges and show both windows.
- 24-25
waitKey(1)waits one millisecond for a key press and keeps the windows responsive. Pressing q ends the loop. - 27-28Always release the camera and close the windows.
import numpy as np
# Simulated "video": 5 frames of a bright 2x2 square moving to the right
frames = []
for step in range(5):
frame = np.zeros((6, 10), dtype=np.uint8)
frame[2:4, step * 2: step * 2 + 2] = 255
frames.append(frame)
# Frame differencing, the idea behind simple motion detection
for i in range(1, len(frames)):
diff = np.abs(frames[i].astype(int) - frames[i - 1].astype(int))
changed = int((diff > 50).sum())
cols = sorted(set(np.nonzero(diff > 50)[1].tolist()))
print(f"frame {i}: {changed} changed pixels in columns {cols}")frame 1: 8 changed pixels in columns [0, 1, 2, 3] frame 2: 8 changed pixels in columns [2, 3, 4, 5] frame 3: 8 changed pixels in columns [4, 5, 6, 7] frame 4: 8 changed pixels in columns [6, 7, 8, 9]
Line by line
- 3-8Fake a five-frame video as a list of arrays: a 2 by 2 white square that moves two columns per frame.
- 10-14Subtract each frame from the one before. The absolute difference is large only where something changed. Counting those pixels, and noting which columns they are in, is the heart of basic motion detection.
- 13Convert to
intfirst: subtracting twouint8arrays wraps around instead of going negative, which would give nonsense.
Camera and window code usually fails inside notebooks, remote servers and containers because no display or device exists. Run these scripts on a desktop machine, and use cv2.imwrite to save results when you cannot show windows.
Common mistakes
โ Treating BGR as RGB
Colours look wrong, with reds and blues swapped, when you send an OpenCV array to Matplotlib or Pillow. Convert with cv2.cvtColor(img, cv2.COLOR_BGR2RGB) before showing it with those libraries.
โ Not checking that imread succeeded
cv2.imread returns None for a wrong path instead of raising an error, and the failure appears later as a confusing 'NoneType has no attribute shape'. Test for None straight after loading.
โ Mixing up (width, height) and (height, width)
Array shapes are (rows, columns), which is height then width, but functions such as resize and drawing calls take x, y or (width, height). Mistakes here distort or misplace results without any error.
โ Overflowing uint8 arithmetic
uint8 values wrap around: 250 + 10 becomes 4 in NumPy. Convert to int or float before subtracting or adding images, or use OpenCV's saturating functions such as cv2.add.
โ Forgetting to release the camera or call waitKey
Without cap.release() the camera may stay locked, and without cv2.waitKey windows freeze or never appear. Put release and cleanup after the loop and always include a key check.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. What shape does a 480-pixel-high, 640-pixel-wide colour image loaded by OpenCV have?
Q2. In what order does OpenCV store the colour channels of a loaded image?
COLOR_BGR2RGB before handing images to RGB-based libraries.Q3. Why is the grayscale formula a weighted sum rather than a plain average?
Q4. What does a Sobel kernel measure?
Q5. What does cv2.VideoCapture.read() return?
(ok, frame). When ok is False there is no frame, for example at the end of a file.Q6. Why convert to int before subtracting two uint8 images?
Frequently asked questions
How do I install OpenCV for Python?
+Use pip to install opencv-python, ideally inside a virtual environment, then import cv2. Servers without a display often use the opencv-python-headless package, which leaves out the window functions. Check the project's current installation notes for details for your platform.
Why can I not run OpenCV in the browser examples on this page?
+OpenCV is a compiled library that needs files, cameras and windows, and it is not available in the in-browser Python environment. That is why the runnable blocks rebuild the ideas with NumPy, and the real cv2 code is shown as static examples to copy to your computer.
OpenCV or Pillow?
+Pillow is great for simple loading, resizing, cropping and saving. OpenCV adds computer vision tools such as filters, feature detection, contours and video handling. Many projects use Pillow for file work and OpenCV for analysis; the two convert easily through NumPy arrays.
Is Haar cascade face detection still worth using?
+It is fast and simple, which makes it good for learning and for low-power devices. It is less accurate than modern neural detectors and struggles with angles and lighting, so for production accuracy consider a deep-learning-based detector.
Where do I find sample images to practise with?
+Use your own photos, or screenshots, and also try synthetic images made with NumPy as on this page. Check the licence of any image you download before reusing or publishing it.
Key takeaways
- โAn image is a NumPy array:
(height, width)for grayscale and(height, width, 3)for colour, indexed row first. - โOpenCV uses BGR order, so convert to RGB before using Matplotlib or Pillow and check that
imreaddid not returnNone. - โGrayscale is a weighted sum of channels, and thresholding is a comparison that produces a black-and-white mask.
- โBlur and Sobel are convolutions: a small kernel slides over the image, multiplying and summing at each position.
- โHistograms count brightness values and help you stretch or equalise contrast; bounding boxes come from connected regions or
findContours. - โVideo is a loop over frames from
VideoCapture; check theokflag, callwaitKey, and release the camera when done.