Background Removal Concepts
Background removal isolates the foreground subject from its background. Understanding the classical approaches helps you appreciate when to use classical CV vs. modern deep learning methods.
8 min•By Priygop Team•Updated 2026
Classical Background Removal
Classical Background Removal
import cv2
import numpy as np
# METHOD 1: GrabCut — semi-automatic interactive segmentation
# Requires a bounding box around the foreground object
image = cv2.imread("photo.jpg")
h, w = image.shape[:2]
# Define a bounding box around the foreground object
# (x, y, width, height) — adjust for your image
rect = (50, 50, w - 100, h - 100)
# GrabCut initialisation
mask = np.zeros((h, w), np.uint8)
bgd_model = np.zeros((1, 65), np.float64) # Background model
fgd_model = np.zeros((1, 65), np.float64) # Foreground model
# Run GrabCut (5 iterations)
cv2.grabCut(image, mask, rect, bgd_model, fgd_model, 5, cv2.GC_INIT_WITH_RECT)
# Create binary mask: 0=definite background, 2=probable background
grabcut_mask = np.where((mask == 2) | (mask == 0), 0, 1).astype("uint8")
# Apply mask to extract foreground
foreground = image * grabcut_mask[:, :, np.newaxis]
cv2.imwrite("grabcut_foreground.jpg", foreground)
print("GrabCut background removal complete")
# METHOD 2: Difference from a static background (for video)
# Requires a clean background frame
# background = cv2.imread("empty_background.jpg")
# diff = cv2.absdiff(background, image)
# gray_diff = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
# _, fg_mask = cv2.threshold(gray_diff, 30, 255, cv2.THRESH_BINARY)Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment