Last modified: Nov 11, 2023 By Alexander Williams

OpenCV: Crop Image by Contour - A Comprehensive Guide

Example 1: Finding Contours


import cv2

# Read the image
image = cv2.imread('path/to/your/image.jpg', cv2.IMREAD_COLOR)

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply thresholding
_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# Find contours
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

Output:


# Display the image with detected contours

Example 2: Crop Image by Contour


import cv2

# Read the image
image = cv2.imread('path/to/your/image.jpg', cv2.IMREAD_COLOR)

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply thresholding
_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# Find contours
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Crop image by the first contour
x, y, w, h = cv2.boundingRect(contours[0])
cropped_image = image[y:y+h, x:x+w]

Output:


# Display the cropped image

Example 3: Crop Multiple Regions by Contours


import cv2

# Read the image
image = cv2.imread('path/to/your/image.jpg', cv2.IMREAD_COLOR)

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply thresholding
_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# Find contours
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Crop multiple regions by contours
cropped_images = []
for contour in contours:
    x, y, w, h = cv2.boundingRect(contour)
    cropped_images.append(image[y:y+h, x:x+w])

Output:


# Display the cropped images