Sub topic 8
Cropping with NumPy Slicing
Assume you know basic Python functions, NumPy indexing, and the difference between an image's width and height. This chapter uses OpenCV images loaded as NumPy arrays.
How a crop is indexed
OpenCV stores a color image with shape (height, width, channels). NumPy slices arrays in row-first order:
crop = image[y1:y2, x1:x2]The vertical coordinate, y, selects rows first. The horizontal coordinate, x, selects columns second. The ending indexes are exclusive, so y2 and x2 are not included.
OpenCV drawing functions use points as (x, y), but NumPy slicing uses [y, x]. Switching these conventions is a common source of incorrect crops.
| Operation | Coordinate order | Example |
|---|---|---|
| NumPy crop | `[y, x]` | `image[50:200, 100:300]` |
| OpenCV point | `(x, y)` | `cv2.rectangle(image, (100, 50), (300, 200), ...)` |
A crop keeps all channels unless you select the third dimension too. For example, image[50:200, 100:300] keeps the BGR channels, while image[50:200, 100:300, 0] selects only the blue channel.
Crop an image safely
The following program loads an image, checks that loading succeeded, verifies the requested coordinates, and writes the crop to a new file.
import cv2
image = cv2.imread("photo.jpg")
if image is None:
raise FileNotFoundError("Could not read photo.jpg")
height, width = image.shape[:2]
x1, y1 = 100, 50
x2, y2 = 300, 200
if not (0 <= x1 < x2 <= width and 0 <= y1 < y2 <= height):
raise ValueError("Crop coordinates are outside the image")
crop = image[y1:y2, x1:x2]
cv2.imwrite("crop.png", crop)
print("Original shape:", image.shape)
print("Crop shape:", crop.shape)NumPy normally clips a slice that extends beyond an array's bounds instead of raising an error. That behavior can hide a mistake. Explicit validation is useful when crop coordinates come from user input, a detection model, or a file.
Views and independent copies
A basic slice returns a view, which is another array object that refers to the same underlying pixel data. Modifying the view can therefore modify the original image.
Use .copy() when the crop must be independent:
crop = image[y1:y2, x1:x2].copy()
crop[:, :] = (0, 255, 0) # BGR green
cv2.imwrite("green_crop.png", crop)The original image remains unchanged because crop owns its own data. This is especially important before drawing, filtering, or passing a crop to code that may modify its input.
Crop from a center point
Many computer vision tasks describe a region by its center and size rather than by two corners. Convert that description to slice boundaries before indexing:
def crop_center(image, center_x, center_y, crop_width, crop_height):
height, width = image.shape[:2]
x1 = max(0, center_x - crop_width // 2)
y1 = max(0, center_y - crop_height // 2)
x2 = min(width, x1 + crop_width)
y2 = min(height, y1 + crop_height)
return image[y1:y2, x1:x2].copy()This function keeps the crop inside the image and returns an independent array. If the requested region touches an edge, the returned crop may be smaller than the requested dimensions.
Exercise
What does image[20:80, 100:180] select, and what is its shape for a three-channel image?
Show answer
It selects rows 20 through 79 and columns 100 through 179. Its shape is (60, 80, 3).