Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Cropping Images
Cropping extracts a rectangular region of interest from an image. It is used to focus on the relevant area and discard irrelevant background.
6 min•By Priygop Team•Updated 2026
Cropping with NumPy Slicing
Cropping with NumPy Slicing
import cv2
image = cv2.imread("photo.jpg")
h, w = image.shape[:2]
# Basic crop: image[start_row:end_row, start_col:end_col]
# Crop the top-left quarter
top_left = image[0:h//2, 0:w//2]
# Crop the centre
margin_h = h // 4
margin_w = w // 4
centre = image[margin_h:h-margin_h, margin_w:w-margin_w]
# Crop around a specific point (e.g. detected object at x=300, y=200)
obj_x, obj_y = 300, 200
crop_size = 100
crop = image[
max(0, obj_y - crop_size):min(h, obj_y + crop_size),
max(0, obj_x - crop_size):min(w, obj_x + crop_size)
]
print(f"Original: {w}x{h}")
print(f"Top-left crop: {top_left.shape[1]}x{top_left.shape[0]}")
print(f"Centre crop: {centre.shape[1]}x{centre.shape[0]}")
# Save crops
cv2.imwrite("crop_topleft.jpg", top_left)
cv2.imwrite("crop_centre.jpg", centre)Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment