Contour-Based Extraction
Contour-based extraction finds objects by their outlines and extracts each one individually. This allows you to isolate specific objects from a complex scene.
10 min•By Priygop Team•Updated 2026
Extracting Individual Objects
Extracting Individual Objects
import cv2
import numpy as np
import os
def extract_objects(image_path, output_dir="objects", min_area=1000):
"""Extract all significant objects from an image as individual files."""
os.makedirs(output_dir, exist_ok=True)
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
_, binary = cv2.threshold(blurred, 0, 255,
cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
contours, _ = cv2.findContours(
binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
print(f"Found {len(contours)} contours")
extracted = 0
for i, contour in enumerate(contours):
area = cv2.contourArea(contour)
if area < min_area:
continue
# Get bounding rectangle
x, y, w, h = cv2.boundingRect(contour)
# Create object mask from contour
mask = np.zeros_like(gray)
cv2.drawContours(mask, [contour], -1, 255, -1) # Filled contour
# Extract with transparent background (BGRA)
object_bgra = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA)
object_bgra[:, :, 3] = mask # Alpha channel = mask
# Crop to bounding rect
crop = object_bgra[y:y+h, x:x+w]
cv2.imwrite(f"{output_dir}/object_{extracted:03d}.png", crop)
print(f" Object {extracted}: area={area:.0f}, size={w}x{h}px")
extracted += 1
print(f"Extracted {extracted} objects to '{output_dir}/'")
extract_objects("photo.jpg")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment