How do you crop an image by coordinates using OpenCV in Python? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you crop an image by coordinates using OpenCV in Python?

message-square
0

Slice the loaded NumPy image array directly using cropped = img[y1:y2, x1:x2]—placing rows (y, vertical top-to-bottom) first and columns (x, horizontal left-to-right) second—because OpenCV (cv2.imread) represents images as standard 2D/3D NumPy ndarray objects with shape (height, width, channels) and origin (0, 0) at the top-left corner.

Basic Example

import cv2

# Load image as a NumPy array of shape (height, width, 3) in BGR channel order
img = cv2.imread("photo.jpg")
if img is None:
    raise FileNotFoundError("Could not load image 'photo.jpg'")

# Define bounding box in pixels: top-left (x1, y1) to bottom-right (x2, y2)
x1, y1 = 100, 50
x2, y2 = 400, 300

# 1. Recommended: Crop via NumPy slicing [y_start:y_end, x_start:x_end]
cropped = img[y1:y2, x1:x2]

print("Original shape:", img.shape)      # e.g., (720, 1280, 3)
print("Cropped shape: ", cropped.shape)  # (250, 300, 3) -> height=250 (y2-y1), width=300 (x2-x1)

cv2.imwrite("cropped_photo.jpg", cropped)

Key Details & Edge Cases

  • [y1:y2, x1:x2] row-major order vs. (x, y) coordinates (the #1 OpenCV bug):
    • OpenCV drawing functions (cv2.rectangle(img, (x1, y1), (x2, y2), ...)) take (x, y) pairs, whereas NumPy array indexing uses [row, col] $\rightarrow$ [y, x]. Swapping x and y silently crops the wrong region or produces an empty array (shape == (0, 300, 3)).
  • Converting (x, y, width, height) bounding boxes (COCO / Haar cascade format):
    • Object detectors often return (x, y, w, h) instead of (x1, y1, x2, y2). Slice with img[y : y + h, x : x + w].
  • NumPy slicing returns a view, NOT a copy (mutating cropped modifies img):
    • cropped = img[y1:y2, x1:x2] shares underlying memory with img in $O(1)$ time with zero allocation. Drawing on cropped (e.g., cv2.circle(cropped, ...)) mutates the original img in place—append .copy() (img[y1:y2, x1:x2].copy()) whenever you need an independent array.
  • Clamping out-of-bounds or negative coordinates safely:
    • In Python/NumPy, negative coordinates (x1 = -10) wrap around from the right/bottom edge instead of clipping at 0, and x2 <= x1 produces a zero-dimension array that crashes cv2.imwrite (cv2.error: !_img.empty()). Always clamp coordinates to image bounds first:
      h, w = img.shape[:2]
      x1, y1 = max(0, x1), max(0, y1)
      x2, y2 = min(w, x2), min(h, y2)
      if x2 <= x1 or y2 <= y1:
          raise ValueError("Invalid or empty crop box after clamping.")
      cropped = img[y1:y2, x1:x2].copy()
      
  • Works identically for grayscale (H, W), BGR (H, W, 3), and BGRA (H, W, 4) images:
    • Because img[y1:y2, x1:x2] omits the trailing channel axis (...), NumPy preserves all channels automatically regardless of whether img is 2D grayscale or 3D color.

Comparison of Image Cropping Approaches in Python

Method Coordinate Order Returns Copy or View? Out-of-Bounds Behavior Best Used When
img[y1:y2, x1:x2] (OpenCV / NumPy — Recommended) [y_start:y_end, x_start:x_end] ((x, y, w, h) $\rightarrow$ [y:y+h, x:x+w]) View (append .copy() for independent memory) Negative indices wrap around; large end indices clamp silently Computer-vision pipelines, video frame processing, and bounding-box extraction in OpenCV.
pil_img.crop((x1, y1, x2, y2)) (Pillow / PIL) (left, upper, right, lower) ((x1, y1, x2, y2)) Copy (new PIL.Image) Pads out-of-bounds regions with black pixels (0) General image manipulation scripts already using Pillow (PIL.Image).
cv2.getRectSubPix(img, (w, h), (cx, cy)) (OpenCV) Center (cx, cy) + size (w, h) (supports float subpixel centers) Copy (new np.ndarray) Replicates border pixels automatically Subpixel-accurate patch extraction around floating-point keypoints or landmarks.