Trusted Video Inpainting Localization via Deep Attentive Noise Learning
An official implementation code for paper "
Trusted Video Inpainting Localization via Deep Attentive Noise Learning ". This repo provides code and trained weights.
Framework
Dependency
Datasets
DAVIS2016
DAVIS2017
MOSE
VOS2k5-800 (in this paper we use 800 videos from VOS2k5)
The
MOSE100 dataset in this paper can be found in
this
Video inpainting algorithms
VI
OP
CP
E2FGVI
FuseFormer
STTN
FGT
FGVC
ISVI
云 GPU 完整操作手册
Python 3.7 + PyTorch 1.7.0 · 从零到推理 · 100% 可复现
目录
环境配置
数据准备
权重下载与加载验证
推理
测试评估
训练
常见问题
1. 环境配置
1.1 创建 Conda 环境
1 # 有 GPU(推荐):conda 自动匹配 CUDA 版本
2 conda create -n truvil python = 3.7 pytorch == 1.7 .0 torchvision == 0.8 .0 cudatoolkit = 10.2 -c pytorch -y
3
4 # 无 GPU / CPU only:
5 conda create -n truvil python = 3.7 pytorch == 1.7 .0 torchvision == 0.8 .0 cpuonly -c pytorch -y
6
7 # 激活环境
8 conda activate truvil
9
10 # 验证
11 python -c "import torch; print('PyTorch:', torch.__version__, '| CUDA:', torch.cuda.is_available())"
12 # 期望输出: PyTorch: 1.7.0 | CUDA: True
1.2 安装依赖
1 # 国内云 GPU 建议用清华镜像加速
2 pip install timm == 0.9 .16 tqdm opencv-python Pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
3
4 # 国外直接用默认源
5 pip install timm == 0.9 .16 tqdm opencv-python Pillow
不需要 安装 mmengine——项目已改用原生 PyTorch(nn.Module / nn.ModuleList),零额外依赖。
1.3 上传项目代码
1 # === 在本地执行 ===
2 cd TruVIL
3 tar -czf truvil.tar.gz \
4 --exclude = 'checkpoints' \
5 --exclude = '__pycache__' \
6 --exclude = '.git' \
7 --exclude = '.results' \
8 --exclude = 'inputs' \
9 --exclude = 'TruVILStudio' \
10 *.py requirements.txt
11
12 scp truvil.tar.gz user@your-gpu-ip:/data/
13
14 # === 上传权重文件(397MB,单独传,避免重复打包)===
15 scp checkpoints/TruVIL_train_VI_OP.pth user@your-gpu-ip:/data/checkpoints/
16
17 # === 在云 GPU 上执行 ===
18 ssh user@your-gpu-ip
19 cd /data && tar -xzf truvil.tar.gz
20 ls *.py # 应看到约 14 个 .py 文件
21 ls checkpoints/ # 应看到 TruVIL_train_VI_OP.pth
2. 数据准备
2.1 目录结构
/data/dataset/
├── train/ # 训练集
│ ├── frame/ # 帧文件夹(每个视频一个子文件夹)
│ │ ├── video_001/
│ │ │ ├── frame_01.png
│ │ │ ├── frame_02.png
│ │ │ ├── frame_03.png
│ │ │ ├── frame_04.png
│ │ │ └── frame_05.png
│ │ ├── video_002/
│ │ └── ...
│ └── groundtruth/ # 标签掩膜(每个视频一张)
│ ├── video_001.png
│ ├── video_002.png
│ └── ...
│
├── val_VI/ # 验证集 1:VI 算法修复
│ ├── frame/
│ └── groundtruth/
├── val_OP/ # 验证集 2:OP 算法修复
│ ├── frame/
│ └── groundtruth/
└── val_CP/ # 验证集 3:CP 算法修复
├── frame/
└── groundtruth/
2.2 数据规格
参数 要求 每视频帧数 ≥ 5 帧(取前 5 帧) 帧分辨率 任意(代码自动 resize 到 240×432) 帧格式 PNG / JPG / BMP 帧命名 自然排序(frame_1 < frame_2 < ... < frame_10) 标签格式 单通道 PNG,修复区域=255,原图区域=0
3. 权重下载与加载验证
3.1 下载预训练权重
从 Google Drive 下载并放到
checkpoints/ 目录:
TruVIL_train_VI_OP.pth (397 MB)
3.2 验证权重加载
1 conda activate truvil
2
3 python -c "
4 from model import TruVIL
5 from load_checkpoint_fix import load_model_safe
6 import torch
7
8 model = TruVIL()
9 model, stats = load_model_safe(model, './checkpoints/TruVIL_train_VI_OP.pth')
10
11 # 预期输出:
12 # Remapped keys : 96
13 # Matched keys : 1534
14 # Missing keys : 3 ← encoder.srm_layer*.weight(HP3D buffer,已在 __init__ 正确初始化)
15 # Unexpected keys : 0
16 # Weight params : 100.0%
17
18 # 前向传播测试
19 model.eval()
20 x = torch.randn(1, 3, 5, 240, 432)
21 with torch.no_grad():
22 y = model(x)
23 print(f'Input : {list(x.shape)}')
24 print(f'Output: {list(y.shape)}') # [1, 1, 240, 432]
25 print('[OK] Model loaded and working!')
26 "
3.3 键名映射说明
预训练权重使用旧版命名,load_checkpoint_fix.py 自动处理映射:
旧名称 新名称 键数 encoder.tacf.*encoder.CAF.*69 rgd.*AND.*27
其余 1438 个键名完全一致,直接匹配。3 个 encoder.srm_layer*.weight(HP3D 高通滤波核)不需要从权重加载——HP3D.__init__ 已用预定义的高通卷积核正确初始化。
4. 推理
4.1 命令行
1 conda activate truvil
2
3 python inference.py \
4 --checkpoint ./checkpoints/TruVIL_train_VI_OP.pth \
5 --input_dir ./demo \
6 --output_dir ./output
输入 : ./demo/video_001/ 下有 5 帧 PNG
输出 : ./output/video_001.png(二值修复掩膜)
4.2 Python API 调用
1 import torch
2 from inference import load_model , preprocess_frames , run_inference
3 from PIL import Image
4
5 # 加载模型(自动检测 GPU)
6 model , device = load_model ( './checkpoints/TruVIL_train_VI_OP.pth' )
7
8 # 预处理 5 帧
9 frames = [
10 '/data/demo/vid_001/frame_01.png' ,
11 '/data/demo/vid_001/frame_02.png' ,
12 '/data/demo/vid_001/frame_03.png' ,
13 '/data/demo/vid_001/frame_04.png' ,
14 '/data/demo/vid_001/frame_05.png' ,
15 ]
16 tensor = preprocess_frames ( frames , device = device ) # → [1, 3, 5, 240, 432]
17
18 # 推理得到二值掩膜
19 mask = run_inference ( model , tensor , threshold = 0.5 ) # → [240, 432] numpy array
20
21 # 保存
22 Image . fromarray ( ( mask * 255 ) . astype ( 'uint8' ) ) . save ( 'output.png' )
4.3 推理函数速查
函数 签名 说明 load_model(checkpoint_path, device=None) → (model, device)加载模型和权重 preprocess_frames(frame_paths, resize_size=(240,432), device=None) → tensor [1,3,5,H,W]读取+resize+堆叠帧 run_inference(model, input_tensor, threshold=0.5) → numpy [H,W]推理→sigmoid→二值化 run_inference_on_tensor(model, input_tensor) → tensor [1,1,H,W]推理返回原始 logits
5. 测试评估
5.1 命令行
1 conda activate truvil
2
3 python test.py \
4 --checkpoint ./checkpoints/TruVIL_train_VI_OP.pth \
5 --val_roots /data/dataset/val_VI /data/dataset/val_OP /data/dataset/val_CP \
6 --batch_size 16
5.2 参数说明
参数 必填 默认值 说明 --checkpoint✓ - 权重文件路径 --val_roots✓ - 验证集根目录(可多个,空格分隔) --batch_size16 批次大小 --num_workers2 DataLoader 进程数 --device自动 cuda / cuda:0 / cpu
5.3 预期输出
============================================================
Checkpoint keys : 1534
Remapped keys : 96
Matched keys : 1534
Missing keys : 3
Unexpected keys : 0
[OK] Loaded: 1534/1537 keys
Evaluating: /data/dataset/val_VI
Val Set 1: F1: 0.xxxx, IoU: 0.xxxx
Evaluating: /data/dataset/val_OP
Val Set 2: F1: 0.xxxx, IoU: 0.xxxx
Evaluating: /data/dataset/val_CP
Val Set 3: F1: 0.xxxx, IoU: 0.xxxx
6. 训练
6.1 从头训练
1 conda activate truvil
2
3 python train.py \
4 --train_root /data/dataset/train \
5 --val_roots /data/dataset/val_VI /data/dataset/val_OP /data/dataset/val_CP \
6 --epochs 200 \
7 --batch_size 8 \
8 --lr 0.0005 \
9 --num_workers 4 \
10 --save_dir ./weights
6.2 断点续训
1 # 自动从 ./weights/latest.pth 恢复
2 python train.py \
3 --train_root /data/dataset/train \
4 --val_roots /data/dataset/val_VI /data/dataset/val_OP /data/dataset/val_CP \
5 --save_dir ./weights
6
7 # 或指定具体 checkpoint 恢复
8 python train.py \
9 --train_root /data/dataset/train \
10 --val_roots /data/dataset/val_VI /data/dataset/val_OP /data/dataset/val_CP \
11 --resume ./weights/epoch_050.pth
6.3 训练参数
参数 必填 默认值 说明 --train_root✓ - 训练集根目录 --val_roots✓ - 验证集根目录(可多个) --epochs200 训练轮数 --batch_size8 批次大小(显存不足时改 4) --lr0.0005 AdamW 学习率 --num_workers2 DataLoader 子进程数 --save_dir./weights 权重保存目录 --resumeNone 指定断点续训的 checkpoint --device自动 cuda / cuda:0 / cpu
6.4 训练输出
weights/
├── epoch_000.pth # 每 epoch 保存的模型权重
├── epoch_001.pth
├── ...
├── epoch_199.pth
└── latest.pth # 最新检查点(含 optimizer/scheduler 状态,用于续训)
6.5 多 GPU 训练
1 # 在 train.py main() 中 model = TruVIL().to(device) 之后添加:
2 if torch . cuda . device_count ( ) > 1 :
3 print ( f"Using { torch . cuda . device_count ( ) } GPUs" )
4 model = torch . nn . DataParallel ( model )
7. 常见问题
Q1: No module named 'mmengine'
不需要 mmengine。如果遇到此错误,说明使用的是旧版 uniformer.py。确认 uniformer.py 顶部是:
1 BaseModule = nn . Module
2 ModuleList = nn . ModuleList
而非:
from mmengine.model import BaseModule, ModuleList # 旧版,不要用
Q2: 权重加载有 3 个 Missing keys
正常现象 。Missing 的是 encoder.srm_layer1.weight、encoder.srm_layer2.weight、encoder.srm_layer3.weight——HP3D 高通滤波核。这些值在 HP3D.__init__ 中已用预定义的高通卷积核(拉普拉斯类算子)正确初始化,不需要 从 checkpoint 加载。不影响模型精度。
Q3: CUDA Out of Memory
减小 batch size 并增大 num_workers:
python train.py --batch_size 4 --num_workers 2 ...
Q4: 推理输出全黑或全白
检查:
是否传入了 恰好 5 帧 连续帧
帧路径是否按时间顺序排列(不是随机)
preprocess_frames 接收的列表顺序 = 帧的时间顺序
Q5: FileNotFoundError: Frame directory not found
数据集目录结构错误。确认存在 root_dir/frame/ 和 root_dir/groundtruth/ 两个子目录。
Q6: 如何验证环境配置是否成功
1 conda activate truvil
2 python -c "
3 import torch; import numpy; import timm; import cv2; import tqdm
4 from PIL import Image
5 from model import TruVIL
6 from HP3D import HP3D
7 from uniformer import Encoder
8 from segformer_head import Decoder_3d
9 from AttentionModule import CAF, AND
10 from base_dataset import FramesDataset
11 from loss import Focal_IoU_LOSS
12 from metric import F1, IoU
13 from load_checkpoint_fix import load_model_safe
14 print('[OK] All modules imported successfully')
15 print(f'PyTorch {torch.__version__} | CUDA {torch.cuda.is_available()}')
16 print(f'NumPy {numpy.__version__}')
17
18 # 模型前向传播
19 model = TruVIL()
20 model, _ = load_model_safe(model, './checkpoints/TruVIL_train_VI_OP.pth')
21 model.eval()
22 x = torch.randn(1, 3, 5, 240, 432)
23 with torch.no_grad():
24 y = model(x)
25 print(f'Input {list(x.shape)} -> Output {list(y.shape)}')
26 print('[OK] Full pipeline verified!')
27 "
附录 A: 完整文件清单
文件 用途 model.pyTruVIL 顶层模型 uniformer.py双流 UniFormer 编码器 segformer_head.py3D SegFormer 解码器 AttentionModule.py注意力模块(CAF / AND / PAM / CAM / TAM) HP3D.py高通 3D 滤波器(buffer 注册,性能优化) base_model.py模型抽象基类 base_dataset.py数据集加载器(自然排序,错误检查) loss.pyFocal + IoU 组合损失 metric.pyF1 / IoU 评估指标 wrappers.py上采样工具 train.py训练脚本(argparse CLI) test.py测试脚本(argparse CLI) inference.py推理脚本 + 可复用 Python API load_checkpoint_fix.py权重键名自动映射 requirements.txtPython 依赖清单
附录 B: 模型架构速览
输入 [B, 3, 5, H, W]
│
├─ HP3D 高通滤波 ──→ Res 残差流
│ │
├─ RGB 流 │
│ │
Stage 1: CBlock×5 CBlock×5 ──→ + HP3D ──→ outs[0]
Stage 2: CBlock×8 CBlock×8 ──→ + HP3D ──→ outs[1]
Stage 3: SABlock×20 SABlock×20 ──→ CAF交叉融合 ──→ outs[2]
Stage 4: SABlock×7 SABlock×7 ──→ outs[3], outs[4]
│ │
└──── outs[0~4] ──→ Decoder_3d ──→ AND门控解码 ──→ 输出 [B, 1, H, W]
总参数 : 103,753,616 | 输入 : 5 帧 240×432 | 输出 : 单通道修复掩膜
Citation
If you use this code for your research, please cite our paper
@article{lou2025trusted,
title={Trusted Video Inpainting Localization via Deep Attentive Noise Learning},
author={Lou, Zijie and Cao, Gang and Lin, Man and Yu, Lifang and Weng, Shaowei},
journal={IEEE Transactions on Dependable and Secure Computing},
year={2025},
publisher={IEEE}
}
License
Licensed under a
Creative Commons Attribution-NonCommercial 4.0 International for Non-commercial use only.
Any commercial use should get formal permission first.