Sub topic 2
Choosing an interpolation method
This chapter assumes you can load an image with cv2.imread, index NumPy arrays, and know that an OpenCV image is an array of shape (height, width, channels).
Choosing an interpolation method
Resizing creates new pixels that do not exist in the original, so OpenCV must estimate their values. The interpolation argument of cv2.resize controls that estimate. Use cv2.INTER_AREA when shrinking, because it averages the source pixels and avoids aliasing. Use cv2.INTER_CUBIC or cv2.INTER_LINEAR when enlarging. cv2.INTER_NEAREST is the fastest but produces blocky output.
Resizing without distortion
The dsize argument is (width, height), the reverse of the (height, width) order in img.shape. To keep the aspect ratio, compute the height from the new width.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
h, w = img.shape[:2]
# Shrink by half with INTER_AREA
small = cv2.resize(img, (w // 2, h // 2), interpolation=cv2.INTER_AREA)
# Set the width to 320 and compute the height to keep the ratio
scale = 320 / w
thumb = cv2.resize(img, (320, round(h * scale)), interpolation=cv2.INTER_AREA)> Warning: passing a fixed width and height that do not match the original ratio stretches the image.
Cropping with NumPy slicing
Slicing uses img[y1:y2, x1:x2], with rows first. The result is a view that shares memory with the original. Call .copy() when you need an independent crop.
roi = img[50:200, 100:300].copy()Drawing conventions: coordinates, colors, thickness
Drawing functions take (x, y) points, colors in BGR order, and a thickness in pixels. A thickness of -1 fills the shape. Drawing functions change the array in place, so draw on a copy to keep the original.
canvas = img.copy()
cv2.rectangle(canvas, (50, 50), (250, 200), (0, 255, 0), 2)
cv2.circle(canvas, (150, 125), 40, (0, 0, 255), -1)
cv2.imwrite("annotated.jpg", canvas)Exercise
You need to shrink a 4000-pixel-wide photo to 800 pixels wide without stretching it. Which interpolation flag do you pass, and what height do you compute if the original is 3000 pixels tall?
Show answer
Pass cv2.INTERAREA. Use scale = 800 / 4000 = 0.2, so the height is round(3000 * 0.2) = 600, and call cv2.resize(img, (800, 600), interpolation=cv2.INTERAREA).