AI Object Swapping
Replace, remove, or modify objects in videos using AI-powered segmentation and inpainting.
Local Pipeline
Object swapping uses local SAM2 + GroundingDINO segmentation with SDXL inpainting/compositing.
ObjectSwapper
Main class for object manipulation in videos.
Swap Object with Generated Content
Replace an object with AI-generated content from a text prompt:
from videopython.base import Video
from videopython.ai import ObjectSwapper
video = Video.from_path("street.mp4")
swapper = ObjectSwapper()
# Replace red car with a blue motorcycle
result = swapper.swap(
video=video,
source_object="red car",
target_object="blue motorcycle",
)
# Create video from swapped frames
swapped_video = Video.from_frames(result.swapped_frames, video.fps)
swapped_video.save("swapped.mp4")
Swap Object with Image
Replace an object with a provided image:
result = swapper.swap_with_image(
video=video,
source_object="red car",
replacement_image="motorcycle.png",
)
Remove Object
Remove an object and fill with background:
Segment Only
Get object masks without modifying the video:
track = swapper.segment_only(
video=video,
object_prompt="person",
)
print(f"Tracked {len(track.masks)} frames")
for mask in track.masks:
print(f"Frame {mask.frame_index}: confidence {mask.confidence:.2f}")
Visualize Tracking
Debug visualization of tracked object:
debug_frames = swapper.visualize_track(video, track)
debug_video = Video.from_frames(debug_frames, video.fps)
debug_video.save("debug_tracking.mp4")
Progress Tracking
def on_progress(stage: str, progress: float) -> None:
print(f"[{progress*100:5.1f}%] {stage}")
result = swapper.swap(
video=video,
source_object="red car",
target_object="blue motorcycle",
progress_callback=on_progress,
)
ObjectSwapper
Swaps objects in videos using segmentation, inpainting, and compositing.
The object swapping pipeline: 1. Segment source object using SAM2 (track across frames) 2. Inpaint background where object was removed 3. Composite replacement (generated or provided image) into cleaned background
Example
from videopython.base.video import Video from videopython.ai.swapping import ObjectSwapper
video = Video.from_path("street.mp4") swapper = ObjectSwapper()
Option A: Generate replacement from prompt
result = swapper.swap(video, source_object="red car", target_object="blue motorcycle")
Option B: Use provided image
result = swapper.swap_with_image( ... video, source_object="red car", replacement_image="bike.png" ... )
Get result
swapped_video = Video.from_frames(result.swapped_frames, video.fps)
Source code in src/videopython/ai/swapping/swapper.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 | |
__init__
Initialize the object swapper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
SwapConfig | None
|
Configuration for the swapping pipeline. |
None
|
device
|
str | None
|
Device for local models ('cuda', 'mps', or 'cpu'). |
None
|
Source code in src/videopython/ai/swapping/swapper.py
swap
swap(
video: Video,
source_object: str,
target_object: str,
reference_frame: int | None = None,
progress_callback: Callable[[str, float], None]
| None = None,
) -> SwapResult
Swap an object in video with a generated replacement.
Segments the source object, removes it via inpainting, and composites a generated replacement image based on the target prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video
|
Video
|
Input video to process. |
required |
source_object
|
str
|
Text description of object to replace (e.g., "red car"). |
required |
target_object
|
str
|
Text description of replacement object (e.g., "blue motorcycle"). |
required |
reference_frame
|
int | None
|
Frame index for initial segmentation. Default: config value. |
None
|
progress_callback
|
Callable[[str, float], None] | None
|
Optional callback for progress updates. Called with (stage_name, progress_fraction). |
None
|
Returns:
| Type | Description |
|---|---|
SwapResult
|
SwapResult containing swapped frames and metadata. |
Example
result = swapper.swap(video, "person", "robot") Video.from_frames(result.swapped_frames, video.fps).save("output.mp4")
Source code in src/videopython/ai/swapping/swapper.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
swap_with_image
swap_with_image(
video: Video,
source_object: str,
replacement_image: str | Path,
reference_frame: int | None = None,
progress_callback: Callable[[str, float], None]
| None = None,
) -> SwapResult
Swap an object in video with a provided replacement image.
Segments the source object, removes it via inpainting, and composites the provided replacement image in its place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video
|
Video
|
Input video to process. |
required |
source_object
|
str
|
Text description of object to replace (e.g., "red car"). |
required |
replacement_image
|
str | Path
|
Path to replacement image file. |
required |
reference_frame
|
int | None
|
Frame index for initial segmentation. Default: config value. |
None
|
progress_callback
|
Callable[[str, float], None] | None
|
Optional callback for progress updates. |
None
|
Returns:
| Type | Description |
|---|---|
SwapResult
|
SwapResult containing swapped frames and metadata. |
Example
result = swapper.swap_with_image(video, "logo", "new_logo.png") Video.from_frames(result.swapped_frames, video.fps).save("output.mp4")
Source code in src/videopython/ai/swapping/swapper.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | |
remove_object
remove_object(
video: Video,
source_object: str,
reference_frame: int | None = None,
inpaint_prompt: str = "background, seamless, natural",
progress_callback: Callable[[str, float], None]
| None = None,
) -> SwapResult
Remove an object from video without replacement.
Segments the object and inpaints the background to remove it cleanly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video
|
Video
|
Input video to process. |
required |
source_object
|
str
|
Text description of object to remove. |
required |
reference_frame
|
int | None
|
Frame index for initial segmentation. |
None
|
inpaint_prompt
|
str
|
Prompt to guide background generation. |
'background, seamless, natural'
|
progress_callback
|
Callable[[str, float], None] | None
|
Optional progress callback. |
None
|
Returns:
| Type | Description |
|---|---|
SwapResult
|
SwapResult with inpainted frames (swapped_frames equals inpainted_frames). |
Example
result = swapper.remove_object(video, "watermark") Video.from_frames(result.swapped_frames, video.fps).save("clean.mp4")
Source code in src/videopython/ai/swapping/swapper.py
segment_only
segment_only(
video: Video,
source_object: str,
reference_frame: int | None = None,
progress_callback: Callable[[str, float], None]
| None = None,
) -> SwapResult
Segment an object without swapping or inpainting.
Useful for previewing segmentation results before full processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video
|
Video
|
Input video to process. |
required |
source_object
|
str
|
Text description of object to segment. |
required |
reference_frame
|
int | None
|
Frame index for initial segmentation. |
None
|
progress_callback
|
Callable[[str, float], None] | None
|
Optional progress callback. |
None
|
Returns:
| Type | Description |
|---|---|
SwapResult
|
SwapResult with original frames and object track (no swapping performed). |
Source code in src/videopython/ai/swapping/swapper.py
visualize_track
staticmethod
visualize_track(
frames: ndarray,
track: Any,
color: tuple[int, int, int] = (255, 0, 0),
alpha: float = 0.5,
) -> np.ndarray
Overlay object masks on video frames for visualization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
ndarray
|
Video frames array of shape (N, H, W, C). |
required |
track
|
Any
|
ObjectTrack to visualize. |
required |
color
|
tuple[int, int, int]
|
RGB color for mask overlay. |
(255, 0, 0)
|
alpha
|
float
|
Opacity of mask overlay (0-1). |
0.5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Frames with mask overlay. |
Source code in src/videopython/ai/swapping/swapper.py
SwapResult
Result of a swap or remove operation.
result = swapper.swap(video, "car", "truck")
print(f"Processed {len(result.swapped_frames)} frames")
print(f"Object tracked: {result.source_object}")
print(f"Track confidence: {result.track.masks[0].confidence:.2f}")
SwapResult
dataclass
Result of an object swapping operation.
Attributes:
| Name | Type | Description |
|---|---|---|
swapped_frames |
ndarray
|
Array of frames with object swapped, shape (N, H, W, C). |
object_track |
ObjectTrack
|
The tracked object that was swapped. |
inpainted_frames |
ndarray | None
|
Frames with object removed (background only), shape (N, H, W, C). |
source_prompt |
str
|
Text prompt used to identify source object. |
target_prompt |
str
|
Text prompt for the replacement object (if generated). |
replacement_image |
str | None
|
Path to replacement image (if provided). |
Source code in src/videopython/ai/swapping/models.py
ObjectTrack
Tracked object across multiple frames.
ObjectTrack
dataclass
A tracked object across multiple frames.
Attributes:
| Name | Type | Description |
|---|---|---|
object_id |
str
|
Unique identifier for this tracked object. |
masks |
list[ObjectMask]
|
List of ObjectMask instances for each frame where object appears. |
label |
str
|
Text label describing the object (e.g., "red car"). |
start_frame |
int
|
First frame index where object appears. |
end_frame |
int
|
Last frame index where object appears. |
Source code in src/videopython/ai/swapping/models.py
get_mask_for_frame
Get the mask for a specific frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame_index
|
int
|
The frame index to look up. |
required |
Returns:
| Type | Description |
|---|---|
ObjectMask | None
|
The ObjectMask for that frame, or None if not present. |
Source code in src/videopython/ai/swapping/models.py
get_masks_array
Get all masks as a stacked numpy array.
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of shape (N, H, W) where N is number of frames. |
Source code in src/videopython/ai/swapping/models.py
ObjectMask
Single-frame object mask with confidence and bounding box.
ObjectMask
dataclass
A mask representing an object in a single frame.
Attributes:
| Name | Type | Description |
|---|---|---|
frame_index |
int
|
Index of the frame this mask belongs to. |
mask |
ndarray
|
Binary mask array of shape (H, W) where True indicates object pixels. |
confidence |
float
|
Confidence score of the segmentation (0.0 to 1.0). |
bounding_box |
tuple[float, float, float, float] | None
|
Optional bounding box as (x1, y1, x2, y2) normalized coordinates. |
Source code in src/videopython/ai/swapping/models.py
__post_init__
Validate mask shape and values.
Source code in src/videopython/ai/swapping/models.py
dilate
Return a dilated version of this mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kernel_size
|
int
|
Size of the dilation kernel. |
5
|
Returns:
| Type | Description |
|---|---|
ObjectMask
|
New ObjectMask with dilated mask. |