Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 39

Video Inpainting: Filling Masked Regions

Recommended resources

Hello! Welcome back.

In our last lesson, we explored temporal attention, a powerful mechanism for generating coherent video clips by allowing every frame to attend to every other frame. This non-autoregressive approach provides a global understanding of motion, which is crucial for consistency.

Today, we'll apply this foundation to a practical and essential task: video inpainting. The goal is to fill in masked or missing regions within a video sequence. This is far more challenging than image inpainting because the filled content must be consistent not only with the surrounding pixels in a single frame but also with the motion and appearance across time. Your learning outcome for this lesson is to implement video inpainting to fill masked regions across frames.

We will explore two primary strategies for achieving this, both of which you could implement as a machine learning engineer:

  1. A training-free approach that uses optical flow to guide a pre-trained image inpainting model.
  2. An end-to-end approach that adapts the spatio-temporal video models we've been studying.

The Core Challenge: Spatial and Temporal Coherence

Imagine you need to remove a logo from all frames of a video. If you inpaint each frame independently, you'll likely get a "flickering" effect where the texture of the filled region changes randomly from one frame to the next. The core challenge of video inpainting is to generate content that is both spatially plausible within each frame and temporally coherent across the entire sequence.

Video Inpainting Strategies: Pre-propagation vs. Pre-inference
This diagram illustrates two conceptual strategies for maintaining temporal consistency in video inpainting. The 'Pre-propagation' method explicitly uses information from an inpainted frame to guide the filling of subsequent frames, ensuring consistency. We'll explore a powerful version of this idea next.

Strategy 1: Training-Free Inpainting with Optical Flow

One of the most effective and practical methods for video inpainting doesn't require training a new video-specific model. Instead, it cleverly combines a pre-trained image diffusion model with an optical flow estimator. The VipDiff paper proposes an elegant framework for this.

The core idea is to use motion information (optical flow) to "borrow" pixels from nearby frames to fill in the masked region of a target frame. These borrowed pixels then act as a powerful conditioning signal for a standard image inpainting model, ensuring the generated patch aligns with the video's motion.

VipDiff: Towards Coherent and Diverse Video Inpainting via ...

The paper 'VipDiff: Towards Coherent and Diverse Video Inpainting via Training-free Denoising Diffusion Models' provides a comprehensive overview of this technique. It's a great example of an engineering-focused solution that combines existing tools to solve a new problem.

Please read the following sections to understand the VipDiff pipeline: Section 3.1 & Figure 2: Briefly review the preliminaries on DDPMs and look at Figure 2, which shows the overall framework. This will give you a high-level map of the process. Section 3.2 (Optical Flow Guided Pixel Propagation): This is the key mechanism for ensuring temporal consistency. Focus on how optical flow F(·) is used to warp pixels from a reference frame to a target frame. Section 3.3 (Noise Optimized Reverse Diffusion Process): This explains how the propagated pixels are used as a constraint (L_cond) to guide the generation process of a standard latent diffusion model. Section 4.1.3 (Implementation Details): As an engineer, you'll find this section particularly useful. Note the specific models used (LDM, RAFT), the number of steps, and the learning rate for noise optimization. This is a recipe for implementation.

To summarize the VipDiff pipeline:

  1. Select a Target Frame: Choose a frame k from the video that needs to be inpainted.
  2. Estimate Flow: For each nearby reference frame j, compute the optical flow from k to j.
  3. Propagate Pixels: Use the estimated flow to warp valid pixels from reference frames into the masked region of the target frame k. This creates a partially filled frame e_xk_0.
  4. Guided Denoising: Use a pre-trained image diffusion model (like Stable Diffusion) to inpaint the remaining holes in e_xk_0. The crucial step is that the reverse diffusion process is guided by a loss function that ensures the output matches the known pixels (both original and propagated). This is done by optimizing the initial noise z through backpropagation, rather than fine-tuning the model.
  5. Iterate: Once frame k is fully inpainted, it becomes a high-quality reference frame for its neighbors. The process is repeated for the next frame that still has missing regions.

This approach is powerful because it leverages the high-quality generation capabilities of modern image models while enforcing temporal consistency through an external motion model.


Strategy 2: Integrated Inpainting with Spatio-Temporal Models

The second strategy involves adapting a native video diffusion model, like the one we discussed in the previous lesson with temporal attention, to perform inpainting. This approach is more "end-to-end" as the model itself handles both spatial and temporal coherence.

The implementation follows a pattern common in image inpainting, often associated with the RePaint paper, but extended to video.

The Core Algorithm:

During the reverse diffusion (sampling) process, at each denoising step t:

  1. Predict: The video model predicts the "clean" video x_0 based on the current noisy video x_t.
  2. Enforce Consistency: This is the key step. We know what the unmasked parts of the original video look like. We take the original, clean video x_0_orig, apply the mask m, and "noise it up" to the current timestep t-1. This gives us the ground-truth noisy values for the unmasked region.
  3. Combine: We create the next noisy sample x_{t-1} by combining two parts:
    • The known, noised pixels from the step above for the unmasked region.
    • The model's generated pixels for the masked region.
  4. Repeat: This x_{t-1} becomes the input for the next denoising step.

By repeatedly re-injecting the known information at every step of the sampling process, we force the model's generation in the masked region to remain consistent with the unmasked context.

For an implementation-focused perspective, let's see how a library like imagen-pytorch exposes this functionality.

lucidrains/imagen-pytorch

The imagen-pytorch library, which we've referenced before, provides a very clean API for video inpainting that abstracts away the sampling loop details. This shows how you'd use such a model in practice.

Please review the code snippet under the 'Inpainting' section, specifically the second block for video. Notice how the sample function takes inpaint_videos and inpaint_masks as direct arguments. The mask can even be different for each frame.

The code inpainted_videos = trainer.sample(..., inpaint_videos=inpaint_videos, inpaint_masks=inpaint_masks) demonstrates the ideal end-user experience. Under the hood, a sampler implementing the RePaint-style logic would perform the step-by-step consistency enforcement we just described. This approach leverages the temporal attention layers of the Unet3D to ensure the filled patch is coherent across frames.


Practical Workflows with ComfyUI

To see how these concepts are pieced together in a production-style environment, it's helpful to look at workflows in a node-based interface like ComfyUI. These demos often use pre-packaged nodes that encapsulate the logic we've discussed.

ComfyUI: Vid To Vid AnimateDIFF Workflow Part 2 | Inpaint AnimateDiff

This first video demonstrates a common video inpainting task: changing an article of clothing. It uses AnimateDiff, a model built for adding motion to static images, to ensure temporal consistency.

Watch the section from 02:39 to 03:49. Observe the workflow: the user draws a mask on one frame, provides a new text prompt ('girl wearing jeans'), and the system applies this change consistently across the animated sequence.

Shoot ENTIRE MOVIES with this FREE AI WORKFLOW! [ComfyUI Tutorial]

This second video shows a more advanced workflow for removing a person from a video to create a 'clean plate' for visual effects. This is a classic inpainting problem.

Now, watch the segment from 15:18 to 16:35. Pay attention to how the workflow is structured: one node is used to identify the object to remove (creating a mask), and another prompt is used to guide the filling of that empty space.

These practical examples show how the underlying principles of masking and guided generation are operationalized in real-world tools.

Test your understanding!

You are tasked with removing a small, static logo from the corner of a 10-second video. The background behind the logo is a simple, non-moving wall. You have two pre-trained models available: a state-of-the-art image inpainting model and a state-of-the-art video inpainting model.

Considering computational efficiency, which model would you choose and why? Describe the high-level process you would use.

Show answer

For this specific task, the image inpainting model would be the most computationally efficient choice.

Reasoning:
Since the logo and the background are both static, there is no complex temporal motion to model. The content needed to fill the masked region is the same in every frame. Running a full spatio-temporal video model would be overkill, as its expensive temporal attention mechanism would not be providing much value.

Process:

  1. Inpaint a Single Frame: Take one frame from the video and use the image inpainting model to remove the logo. This will generate a clean "patch" of the wall texture.
  2. Create a Static Patch: Crop this newly generated patch.
  3. Overlay the Patch: For every frame in the original video, simply overlay this static patch at the location of the logo.

This "copy-paste" approach avoids running a neural network on every single frame, making it vastly more efficient than processing the entire video through a deep model. It's a great example of choosing the simplest effective tool for the job.


Conclusion

In this lesson, we demystified video inpainting by breaking it down into two main strategies.

Key Takeaways:

  • Video inpainting must maintain both spatial plausibility and temporal coherence to avoid flickering artifacts.
  • Flow-Based Propagation (e.g., VipDiff) is a powerful, training-free method that combines optical flow with pre-trained image models. It's an excellent engineering solution that leverages existing components.
  • Integrated Spatio-Temporal Inpainting (e.g., RePaint for video) adapts a native video model's sampling loop to enforce consistency with known pixels at every denoising step. This is a more end-to-end deep learning approach.
  • The choice of method depends on the problem and available resources. For static fills, simple solutions are often best. For dynamic scenes, a motion-aware approach is necessary.

Next Lesson Preview:

We've now seen how to fill masked regions in a video. The next logical step is to control what we fill them with. In the next lesson, we will tackle instruction-guided video editing. Instead of just filling a hole, we'll learn how to modify objects, change styles, or alter the scene based on a text prompt (e.g., "turn the red car blue"), building directly on the masking and consistency techniques we learned today.