To implement a script that uses the Segment Anything Model (SAM) to remove the background from video frames, we need to follow the requirements outlined in your query. The script will accept inputs for a folder containing image frames, a specific frame ID, and pixel coordinates of the object to segment. It will then obtain segmentation masks for all frames and modify each frame to keep only the specified object visible, replacing the background with a specified color.
We'll utilize the classes and methods defined in the SAM2 repository, particularly the SAM2ImagePredictor class for mask prediction. We'll also use the click library for command-line argument parsing.
Here’s a step-by-step implementation of the script:
Script: remove_background.py
python
import os
import click
import numpy as np
import cv2
from PIL import Image
import torch
from sam2.modeling.sam2_base import SAM2Base
from sam2.utils.transforms import SAM2Transforms
from sam2.scripts import SAM2ImagePredictor
# Define a constant for the background color
BACKGROUND_COLOR = (0, 0, 0) # Black background
def load_images_from_folder(folder):
"""Load images from a specified folder."""
images = []
for filename in sorted(os.listdir(folder)):
img_path = os.path.join(folder, filename)
if img_path.endswith(('.png', '.jpg', '.jpeg')):
img = Image.open(img_path).convert("RGB")
images.append(img)
return images
def process_frames(predictor, images, point_coords):
"""Process each frame to segment the object and remove the background."""
processed_images = []
for image in images:
# Set the current image for the predictor
predictor.set_image(image)
# Obtain the segmentation mask using the provided pixel coordinates
masks, _, _ = predictor.predict(point_coords=point_coords)
# Create a mask from the output
mask = masks[0] # Assuming we want the first mask
# Create a new image where only the object is visible
mask_np = mask.astype(np.uint8) # Convert to numpy array
mask_np = cv2.resize(mask_np, (image.width, image.height)) # Resize to original dimensions
# Prepare a new image with the background color
background = np.full((image.height, image.width, 3), BACKGROUND_COLOR, dtype=np.uint8)
# Combine the original image and the background based on the mask
visible_image = np.where(mask_np[..., np.newaxis] == 1, np.array(image), background)
processed_images.append(Image.fromarray(visible_image))
return processed_images
@click.command()
@click.argument('image_folder', type=click.Path(exists=True))
@click.argument('frame_id', type=int)
@click.argument('x_coord', type=int)
@click.argument('y_coord', type=int)
def main(image_folder, frame_id, x_coord, y_coord):
"""Script to remove background from video frames using SAM."""
# Initialize the SAM predictor
model_id = 'path_to_your_model' # Replace with the actual model ID or path
predictor = SAM2ImagePredictor.from_pretrained(model_id)
# Load images from the specified folder
images = load_images_from_folder(image_folder)
if frame_id < 0 or frame_id >= len(images):
click.echo("Frame ID is out of range.")
return
# Get the pixel coordinates as a numpy array
point_coords = np.array([[x_coord, y_coord]])
# Process frames to remove the background
processed_images = process_frames(predictor, images, point_coords)
# Save processed images to a new folder
output_folder = os.path.join(image_folder, 'processed')
os.makedirs(output_folder, exist_ok=True)
for idx, img in enumerate(processed_images):
output_path = os.path.join(output_folder, f'frame_{idx:04d}.png')
img.save(output_path)
click.echo(f'Saved processed frame to {output_path}')
if __name__ == '__main__':
main()
Explanation of the Script
Loading Images: The load_images_from_folder function reads image files from the specified directory and converts them to PIL Image objects.
Processing Frames: The process_frames function:
Sets the image for the predictor.
Uses the SAM model to predict segmentation masks based on the provided pixel coordinates.
Creates a new image where only the object under the mask is visible, replacing the background with a specified color.
Click Command: The main function defines the command-line interface using click, which processes the input arguments:
image_folder: Path to the folder containing image frames.
frame_id: The specific frame to process.
x_coord and y_coord: Pixel coordinates of the object to segment.
Model Initialization: You should replace 'path_to_your_model' with the actual path or ID of your pretrained SAM model.
Output: The processed images are saved in a new folder called processed within the specified image folder.
Usage
To run the script, use the following command in your terminal:
Replace path/to/image_folder with the actual path to your folder containing image frames, frame_id with the specific frame number, and x_coord and y_coord with the pixel coordinates of the object you want to segment.