Below is the Python script that uses SAM (Segment Anything Model) to remove the background from video frames based on the object specified by pixel coordinates in a specific frame. The script uses the click library for argument parsing.
Script: remove_background.py
python
import os
import numpy as np
from PIL import Image
import torch
import click
from sam2.build_sam import build_sam2_video_predictor
# Define the background color
BACKGROUND_COLOR = (0, 0, 0) # Black (R, G, B)
def load_frame(frame_path):
"""Load an image frame."""
return Image.open(frame_path).convert("RGB")
def save_frame(frame_path, frame):
"""Save an image frame."""
frame.save(frame_path)
def apply_mask_to_frame(frame, mask):
"""
Apply a segmentation mask to a frame.
Keep only the object under the mask and replace other pixels with BACKGROUND_COLOR.
"""
frame = np.array(frame)
mask = mask.squeeze() # Ensure the mask is 2D
output = frame.copy()
output[~mask] = BACKGROUND_COLOR # Replace outside mask with background color
return Image.fromarray(output)
@click.command()
@click.argument("frames_dir", type=click.Path(exists=True))
@click.argument("frame_id", type=int)
@click.argument("pixel_x", type=int)
@click.argument("pixel_y", type=int)
@click.option(
"--output_dir",
type=click.Path(),
default="./output_frames",
help="Directory to save processed frames.",
)
@click.option(
"--sam_cfg",
type=click.Path(),
default="configs/sam2.1/sam2.1_hiera_b+.yaml",
help="Path to SAM configuration file.",
)
@click.option(
"--sam_checkpoint",
type=click.Path(),
default="./checkpoints/sam2.1_hiera_base_plus.pt",
help="Path to SAM checkpoint file.",
)
def remove_background(frames_dir, frame_id, pixel_x, pixel_y, output_dir, sam_cfg, sam_checkpoint):
"""
Remove the background from video frames based on an object specified by pixel coordinates.
Arguments:
- FRAMES_DIR: Path to the folder containing image frames.
- FRAME_ID: The ID of the frame where the object is specified.
- PIXEL_X, PIXEL_Y: The pixel coordinates of the object in the frame.
"""
# Load SAM model
print("Loading SAM model...")
predictor = build_sam2_video_predictor(config_file=sam_cfg, ckpt_path=sam_checkpoint)
# Get list of frames
frame_paths = sorted(
[
os.path.join(frames_dir, f)
for f in os.listdir(frames_dir)
if [Redacted Person].lower().endswith((".jpg", ".png"))
]
)
if not frame_paths:
print(f"No image frames found in directory: {frames_dir}")
return
# Ensure the specified frame_id is valid
if frame_id < 0 or frame_id >= len(frame_paths):
print(f"Invalid frame_id: {frame_id}. Must be between 0 and {len(frame_paths) - 1}.")
return
# Initialize SAM inference state
print(f"Initializing SAM with video frames from: {frames_dir}")
inference_state = predictor.init_state(video_path=frames_dir)
# Add the input point (pixel coordinates) as a positive point
input_points = [[pixel_x, pixel_y]]
input_labels = [1] # 1 indicates the point belongs to the object
print(f"Adding input point ({pixel_x}, {pixel_y}) on frame {frame_id}")
predictor.add_new_points_or_box(
inference_state=inference_state,
frame_idx=frame_id,
obj_id=1, # Object ID
points=input_points,
labels=input_labels,
clear_old_points=True,
normalize_coords=False,
)
# Propagate the segmentation mask across all frames
print("Propagating masks across video frames...")
os.makedirs(output_dir, exist_ok=True)
for frame_idx, _, video_res_masks in predictor.propagate_in_video(inference_state):
mask = (video_res_masks > 0).squeeze(0).cpu().numpy() # Get binary mask
frame = load_frame(frame_paths[frame_idx]) # Load the corresponding frame
masked_frame = apply_mask_to_frame(frame, mask) # Apply mask to frame
# Save the masked frame to the output directory
output_path = os.path.join(output_dir, os.path.basename(frame_paths[frame_idx]))
save_frame(output_path, masked_frame)
print(f"Processed frame {frame_idx} saved to {output_path}")
print(f"Processing complete! Masked frames saved to: {output_dir}")
if __name__ == "__main__":
remove_background()
How It Works:
Input Arguments:
frames_dir: Path to the folder containing the video frames as individual image files.
frame_id: The index of the frame where the object is specified.
pixel_x and pixel_y: Pixel coordinates of the object in the specified frame.
output_dir: Path to save the processed frames (default: ./output_frames).
SAM Integration:
The SAM model is initialized using the build_sam2_video_predictor function.
The specified pixel coordinates are added as a positive point for segmentation using add_new_points_or_box.
The segmentation masks are propagated across all frames using propagate_in_video.
Background Removal:
For each frame, the mask is applied to retain only the object, and the rest of the pixels are replaced with the specified background color (BACKGROUND_COLOR).
Output:
The processed frames with the background removed are saved to the output_dir.
This command processes the video frames in the ./frames directory, removes the background based on the object located at (120, 200) in frame 10, and saves the masked frames to the ./masked_frames directory.