Last modified: Nov 11, 2023 By Alexander Williams
Python OpenCV: Crop Image by Coordinates - Examples
Example 1: Basic Image Cropping
import cv2
# Read the image
image = cv2.imread('path/to/your/image.jpg')
# Define coordinates (x, y, width, height)
x, y, w, h = 100, 50, 200, 150
# Crop the image
cropped_image = image[y:y+h, x:x+w]
Output:
# Display the cropped image
Example 2: Cropping with ROI Selection
import cv2
# Read the image
image = cv2.imread('path/to/your/image.jpg')
# Display the image and select ROI
roi = cv2.selectROI(image)
# Crop the image based on the selected ROI
cropped_image = image[int(roi[1]):int(roi[1]+roi[3]), int(roi[0]):int(roi[0]+roi[2])]
Output:
# Display the cropped image
Example 3: Batch Cropping from a List of Coordinates
import cv2
# Read the image
image = cv2.imread('path/to/your/image.jpg')
# List of coordinates [x, y, width, height]
coordinates_list = [(100, 50, 200, 150), (300, 100, 150, 120), (50, 30, 180, 200)]
# Crop images based on the coordinates list
cropped_images = [image[y:y+h, x:x+w] for x, y, w, h in coordinates_list]
Output:
# Display the cropped images