Image Annotation

Learn to annotate images by adding rectangles, circles, and text.

In a typical computer vision task, we process images in a chained manner: an original image gets transformed into another image, which is processed into another image by a second step, and so on. We might want to annotate our intermediary images to help us understand the effect of each processing step.

The OpenCV library offers various drawing functions that we can use to annotate our images. Let’s examine a few of them.

Direct pixel value access

The most basic way to modify an image is to access its values directly, just like any NumPy array.

Press + to interact
import cv2
import os
image = cv2.imread('./images/hens/paprika_cayenne1.jpg')
# Crop a small patch from the loaded image
roi = (80, 90, 300, 300) # (x_left, y_top, width, height)
# A slice from a NumPy array is defined by arr[y_start: y_end, x_start: x_end, : (i.e. all_channels)]
cropped_img = image[roi[1]: roi[1] + roi[3], roi[0]: roi[0] + roi[2], :]
# Save the cropped image
cv2.imwrite(os.path.join('./output', "cropped.png"), cropped_img)
# Overwrite the color over a rectangle
modified_rect = (30, 10, 60, 45)
# Change the color in the modified rectangle defined above
# Colors are encoded by default as (B, G, R) in OpenCV
cropped_img[modified_rect[1]: modified_rect[1] + modified_rect[3], \
modified_rect[0]: modified_rect[0] + modified_rect[2], :] = (255, 0, 0)
# Save the modified image
cv2.imwrite(os.path.join('./output', "modified.png"), cropped_img)

Click the “>” symbol in the window above to see both the original cropped ...