Update main.py
Browse files
main.py
CHANGED
|
@@ -1,47 +1,6 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import shutil
|
| 3 |
-
import subprocess
|
| 4 |
import os
|
| 5 |
-
from pathlib import Path
|
| 6 |
-
import threading
|
| 7 |
import cv2
|
| 8 |
-
import
|
| 9 |
-
from functools import cached_property
|
| 10 |
-
|
| 11 |
-
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 12 |
-
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 13 |
-
import config
|
| 14 |
-
from backend.tools.common_tools import is_video_or_image, is_image_file
|
| 15 |
-
from backend.scenedetect import scene_detect
|
| 16 |
-
from backend.scenedetect.detectors import ContentDetector
|
| 17 |
-
from backend.inpaint.sttn_inpaint import STTNInpaint, STTNVideoInpaint
|
| 18 |
-
from backend.inpaint.lama_inpaint import LamaInpaint
|
| 19 |
-
from backend.inpaint.video_inpaint import VideoInpaint
|
| 20 |
-
from backend.tools.inpaint_tools import create_mask, batch_generator
|
| 21 |
-
import importlib
|
| 22 |
-
import platform
|
| 23 |
-
import tempfile
|
| 24 |
-
import multiprocessing
|
| 25 |
-
from shapely.geometry import Polygon
|
| 26 |
-
import time
|
| 27 |
-
from tqdm import tqdm
|
| 28 |
-
import os
|
| 29 |
-
import cv2
|
| 30 |
-
import numpy as np
|
| 31 |
-
import urllib.request
|
| 32 |
-
|
| 33 |
-
# 模型路径配置
|
| 34 |
-
LAMA_MODEL_PATH = "./models/big-lama"
|
| 35 |
-
MODEL_FILE = os.path.join(LAMA_MODEL_PATH, "big-lama.pt")
|
| 36 |
-
|
| 37 |
-
# 自动下载模型(如果缺失)
|
| 38 |
-
os.makedirs(LAMA_MODEL_PATH, exist_ok=True)
|
| 39 |
-
if not os.path.exists(MODEL_FILE):
|
| 40 |
-
print("🔄 正在下载 big-lama 模型...")
|
| 41 |
-
urllib.request.urlretrieve(
|
| 42 |
-
"https://huggingface.co/your-username/your-model-repo/resolve/main/big-lama.pt",
|
| 43 |
-
MODEL_FILE
|
| 44 |
-
)
|
| 45 |
|
| 46 |
def process_video(input_video_path, output_video_path):
|
| 47 |
cap = cv2.VideoCapture(input_video_path)
|
|
@@ -55,7 +14,7 @@ def process_video(input_video_path, output_video_path):
|
|
| 55 |
ret, frame = cap.read()
|
| 56 |
if not ret:
|
| 57 |
break
|
| 58 |
-
#
|
| 59 |
y1 = int(h * 0.85)
|
| 60 |
y2 = h
|
| 61 |
frame[y1:y2, :] = cv2.GaussianBlur(frame[y1:y2, :], (21, 21), 0)
|
|
@@ -72,962 +31,3 @@ if __name__ == "__main__":
|
|
| 72 |
parser.add_argument("--output_video", type=str, required=True)
|
| 73 |
args = parser.parse_args()
|
| 74 |
process_video(args.input_video, args.output_video)
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
class SubtitleDetect:
|
| 79 |
-
"""
|
| 80 |
-
文本框检测类,用于检测视频帧中是否存在文本框
|
| 81 |
-
"""
|
| 82 |
-
|
| 83 |
-
def __init__(self, video_path, sub_area=None):
|
| 84 |
-
self.video_path = video_path
|
| 85 |
-
self.sub_area = sub_area
|
| 86 |
-
|
| 87 |
-
@cached_property
|
| 88 |
-
def text_detector(self):
|
| 89 |
-
import paddle
|
| 90 |
-
paddle.disable_signal_handler()
|
| 91 |
-
from paddleocr.tools.infer import utility
|
| 92 |
-
from paddleocr.tools.infer.predict_det import TextDetector
|
| 93 |
-
# 获取参数对象
|
| 94 |
-
importlib.reload(config)
|
| 95 |
-
args = utility.parse_args()
|
| 96 |
-
args.det_algorithm = 'DB'
|
| 97 |
-
args.det_model_dir = self.convertToOnnxModelIfNeeded(config.DET_MODEL_PATH)
|
| 98 |
-
args.use_onnx=len(config.ONNX_PROVIDERS) > 0
|
| 99 |
-
args.onnx_providers=config.ONNX_PROVIDERS
|
| 100 |
-
return TextDetector(args)
|
| 101 |
-
|
| 102 |
-
def detect_subtitle(self, img):
|
| 103 |
-
dt_boxes, elapse = self.text_detector(img)
|
| 104 |
-
return dt_boxes, elapse
|
| 105 |
-
|
| 106 |
-
@staticmethod
|
| 107 |
-
def get_coordinates(dt_box):
|
| 108 |
-
"""
|
| 109 |
-
从返回的检测框中获取坐标
|
| 110 |
-
:param dt_box 检测框返回结果
|
| 111 |
-
:return list 坐标点列表
|
| 112 |
-
"""
|
| 113 |
-
coordinate_list = list()
|
| 114 |
-
if isinstance(dt_box, list):
|
| 115 |
-
for i in dt_box:
|
| 116 |
-
i = list(i)
|
| 117 |
-
(x1, y1) = int(i[0][0]), int(i[0][1])
|
| 118 |
-
(x2, y2) = int(i[1][0]), int(i[1][1])
|
| 119 |
-
(x3, y3) = int(i[2][0]), int(i[2][1])
|
| 120 |
-
(x4, y4) = int(i[3][0]), int(i[3][1])
|
| 121 |
-
xmin = max(x1, x4)
|
| 122 |
-
xmax = min(x2, x3)
|
| 123 |
-
ymin = max(y1, y2)
|
| 124 |
-
ymax = min(y3, y4)
|
| 125 |
-
coordinate_list.append((xmin, xmax, ymin, ymax))
|
| 126 |
-
return coordinate_list
|
| 127 |
-
|
| 128 |
-
def find_subtitle_frame_no(self, sub_remover=None):
|
| 129 |
-
video_cap = cv2.VideoCapture(self.video_path)
|
| 130 |
-
frame_count = video_cap.get(cv2.CAP_PROP_FRAME_COUNT)
|
| 131 |
-
tbar = tqdm(total=int(frame_count), unit='frame', position=0, file=sys.__stdout__, desc='Subtitle Finding')
|
| 132 |
-
current_frame_no = 0
|
| 133 |
-
subtitle_frame_no_box_dict = {}
|
| 134 |
-
print('[Processing] start finding subtitles...')
|
| 135 |
-
while video_cap.isOpened():
|
| 136 |
-
ret, frame = video_cap.read()
|
| 137 |
-
# 如果读取视频帧失败(视频读到最后一帧)
|
| 138 |
-
if not ret:
|
| 139 |
-
break
|
| 140 |
-
# 读取视频帧成功
|
| 141 |
-
current_frame_no += 1
|
| 142 |
-
dt_boxes, elapse = self.detect_subtitle(frame)
|
| 143 |
-
coordinate_list = self.get_coordinates(dt_boxes.tolist())
|
| 144 |
-
if coordinate_list:
|
| 145 |
-
temp_list = []
|
| 146 |
-
for coordinate in coordinate_list:
|
| 147 |
-
xmin, xmax, ymin, ymax = coordinate
|
| 148 |
-
if self.sub_area is not None:
|
| 149 |
-
s_ymin, s_ymax, s_xmin, s_xmax = self.sub_area
|
| 150 |
-
if (s_xmin <= xmin and xmax <= s_xmax
|
| 151 |
-
and s_ymin <= ymin
|
| 152 |
-
and ymax <= s_ymax):
|
| 153 |
-
temp_list.append((xmin, xmax, ymin, ymax))
|
| 154 |
-
else:
|
| 155 |
-
temp_list.append((xmin, xmax, ymin, ymax))
|
| 156 |
-
if len(temp_list) > 0:
|
| 157 |
-
subtitle_frame_no_box_dict[current_frame_no] = temp_list
|
| 158 |
-
tbar.update(1)
|
| 159 |
-
if sub_remover:
|
| 160 |
-
sub_remover.progress_total = (100 * float(current_frame_no) / float(frame_count)) // 2
|
| 161 |
-
subtitle_frame_no_box_dict = self.unify_regions(subtitle_frame_no_box_dict)
|
| 162 |
-
# if config.UNITE_COORDINATES:
|
| 163 |
-
# subtitle_frame_no_box_dict = self.get_subtitle_frame_no_box_dict_with_united_coordinates(subtitle_frame_no_box_dict)
|
| 164 |
-
# if sub_remover is not None:
|
| 165 |
-
# try:
|
| 166 |
-
# # 当帧数大于1时,说明并非图片或单帧
|
| 167 |
-
# if sub_remover.frame_count > 1:
|
| 168 |
-
# subtitle_frame_no_box_dict = self.filter_mistake_sub_area(subtitle_frame_no_box_dict,
|
| 169 |
-
# sub_remover.fps)
|
| 170 |
-
# except Exception:
|
| 171 |
-
# pass
|
| 172 |
-
# subtitle_frame_no_box_dict = self.prevent_missed_detection(subtitle_frame_no_box_dict)
|
| 173 |
-
print('[Finished] Finished finding subtitles...')
|
| 174 |
-
new_subtitle_frame_no_box_dict = dict()
|
| 175 |
-
for key in subtitle_frame_no_box_dict.keys():
|
| 176 |
-
if len(subtitle_frame_no_box_dict[key]) > 0:
|
| 177 |
-
new_subtitle_frame_no_box_dict[key] = subtitle_frame_no_box_dict[key]
|
| 178 |
-
return new_subtitle_frame_no_box_dict
|
| 179 |
-
|
| 180 |
-
def convertToOnnxModelIfNeeded(self, model_dir, model_filename="inference.pdmodel", params_filename="inference.pdiparams", opset_version=14):
|
| 181 |
-
"""Converts a Paddle model to ONNX if ONNX providers are available and the model does not already exist."""
|
| 182 |
-
|
| 183 |
-
if not config.ONNX_PROVIDERS:
|
| 184 |
-
return model_dir
|
| 185 |
-
|
| 186 |
-
onnx_model_path = os.path.join(model_dir, "model.onnx")
|
| 187 |
-
|
| 188 |
-
if os.path.exists(onnx_model_path):
|
| 189 |
-
print(f"ONNX model already exists: {onnx_model_path}. Skipping conversion.")
|
| 190 |
-
return onnx_model_path
|
| 191 |
-
|
| 192 |
-
print(f"Converting Paddle model {model_dir} to ONNX...")
|
| 193 |
-
model_file = os.path.join(model_dir, model_filename)
|
| 194 |
-
params_file = os.path.join(model_dir, params_filename) if params_filename else ""
|
| 195 |
-
|
| 196 |
-
try:
|
| 197 |
-
import paddle2onnx
|
| 198 |
-
# Ensure the target directory exists
|
| 199 |
-
os.makedirs(os.path.dirname(onnx_model_path), exist_ok=True)
|
| 200 |
-
|
| 201 |
-
# Convert and save the model
|
| 202 |
-
onnx_model = paddle2onnx.export(
|
| 203 |
-
model_filename=model_file,
|
| 204 |
-
params_filename=params_file,
|
| 205 |
-
save_file=onnx_model_path,
|
| 206 |
-
opset_version=opset_version,
|
| 207 |
-
auto_upgrade_opset=True,
|
| 208 |
-
verbose=True,
|
| 209 |
-
enable_onnx_checker=True,
|
| 210 |
-
enable_experimental_op=True,
|
| 211 |
-
enable_optimize=True,
|
| 212 |
-
custom_op_info={},
|
| 213 |
-
deploy_backend="onnxruntime",
|
| 214 |
-
calibration_file="calibration.cache",
|
| 215 |
-
external_file=os.path.join(model_dir, "external_data"),
|
| 216 |
-
export_fp16_model=False,
|
| 217 |
-
)
|
| 218 |
-
|
| 219 |
-
print(f"Conversion successful. ONNX model saved to: {onnx_model_path}")
|
| 220 |
-
return onnx_model_path
|
| 221 |
-
except Exception as e:
|
| 222 |
-
print(f"Error during conversion: {e}")
|
| 223 |
-
return model_dir
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
@staticmethod
|
| 227 |
-
def split_range_by_scene(intervals, points):
|
| 228 |
-
# 确保离散值列表是有序的
|
| 229 |
-
points.sort()
|
| 230 |
-
# 用于存储结果区间的列表
|
| 231 |
-
result_intervals = []
|
| 232 |
-
# 遍历区间
|
| 233 |
-
for start, end in intervals:
|
| 234 |
-
# 在当前区间内的点
|
| 235 |
-
current_points = [p for p in points if start <= p <= end]
|
| 236 |
-
|
| 237 |
-
# 遍历当前区间内的离散点
|
| 238 |
-
for p in current_points:
|
| 239 |
-
# 如果当前离散点不是区间的起始点,添加从区间开始到离散点前一个数字的区间
|
| 240 |
-
if start < p:
|
| 241 |
-
result_intervals.append((start, p - 1))
|
| 242 |
-
# 更新区间开始为当前离散点
|
| 243 |
-
start = p
|
| 244 |
-
# 添加从最后一个离散点或区间开始到区间结束的区间
|
| 245 |
-
result_intervals.append((start, end))
|
| 246 |
-
# 输出结果
|
| 247 |
-
return result_intervals
|
| 248 |
-
|
| 249 |
-
@staticmethod
|
| 250 |
-
def get_scene_div_frame_no(v_path):
|
| 251 |
-
"""
|
| 252 |
-
获取发生场景切换的帧号
|
| 253 |
-
"""
|
| 254 |
-
scene_div_frame_no_list = []
|
| 255 |
-
scene_list = scene_detect(v_path, ContentDetector())
|
| 256 |
-
for scene in scene_list:
|
| 257 |
-
start, end = scene
|
| 258 |
-
if start.frame_num == 0:
|
| 259 |
-
pass
|
| 260 |
-
else:
|
| 261 |
-
scene_div_frame_no_list.append(start.frame_num + 1)
|
| 262 |
-
return scene_div_frame_no_list
|
| 263 |
-
|
| 264 |
-
@staticmethod
|
| 265 |
-
def are_similar(region1, region2):
|
| 266 |
-
"""判断两个区域是否相似。"""
|
| 267 |
-
xmin1, xmax1, ymin1, ymax1 = region1
|
| 268 |
-
xmin2, xmax2, ymin2, ymax2 = region2
|
| 269 |
-
|
| 270 |
-
return abs(xmin1 - xmin2) <= config.PIXEL_TOLERANCE_X and abs(xmax1 - xmax2) <= config.PIXEL_TOLERANCE_X and \
|
| 271 |
-
abs(ymin1 - ymin2) <= config.PIXEL_TOLERANCE_Y and abs(ymax1 - ymax2) <= config.PIXEL_TOLERANCE_Y
|
| 272 |
-
|
| 273 |
-
def unify_regions(self, raw_regions):
|
| 274 |
-
"""将连续相似的区域统一,保持列表结构。"""
|
| 275 |
-
if len(raw_regions) > 0:
|
| 276 |
-
keys = sorted(raw_regions.keys()) # 对键进行排序以确保它们是连续的
|
| 277 |
-
unified_regions = {}
|
| 278 |
-
|
| 279 |
-
# 初始化
|
| 280 |
-
last_key = keys[0]
|
| 281 |
-
unify_value_map = {last_key: raw_regions[last_key]}
|
| 282 |
-
|
| 283 |
-
for key in keys[1:]:
|
| 284 |
-
current_regions = raw_regions[key]
|
| 285 |
-
|
| 286 |
-
# 新增一个列表来存放匹配过的标准区间
|
| 287 |
-
new_unify_values = []
|
| 288 |
-
|
| 289 |
-
for idx, region in enumerate(current_regions):
|
| 290 |
-
last_standard_region = unify_value_map[last_key][idx] if idx < len(unify_value_map[last_key]) else None
|
| 291 |
-
|
| 292 |
-
# 如果当前的区间与前一个键的对应区间相似,我们统一它们
|
| 293 |
-
if last_standard_region and self.are_similar(region, last_standard_region):
|
| 294 |
-
new_unify_values.append(last_standard_region)
|
| 295 |
-
else:
|
| 296 |
-
new_unify_values.append(region)
|
| 297 |
-
|
| 298 |
-
# 更新unify_value_map为最新的区间值
|
| 299 |
-
unify_value_map[key] = new_unify_values
|
| 300 |
-
last_key = key
|
| 301 |
-
|
| 302 |
-
# 将最终统一后的结果传递给unified_regions
|
| 303 |
-
for key in keys:
|
| 304 |
-
unified_regions[key] = unify_value_map[key]
|
| 305 |
-
return unified_regions
|
| 306 |
-
else:
|
| 307 |
-
return raw_regions
|
| 308 |
-
|
| 309 |
-
@staticmethod
|
| 310 |
-
def find_continuous_ranges(subtitle_frame_no_box_dict):
|
| 311 |
-
"""
|
| 312 |
-
获取字幕出现的起始帧号与结束帧号
|
| 313 |
-
"""
|
| 314 |
-
numbers = sorted(list(subtitle_frame_no_box_dict.keys()))
|
| 315 |
-
ranges = []
|
| 316 |
-
start = numbers[0] # 初始区间开始值
|
| 317 |
-
|
| 318 |
-
for i in range(1, len(numbers)):
|
| 319 |
-
# 如果当前数字与前一个数字间隔超过1,
|
| 320 |
-
# 则上一个区间结束,记录当前区间的开始与结束
|
| 321 |
-
if numbers[i] - numbers[i - 1] != 1:
|
| 322 |
-
end = numbers[i - 1] # 则该数字是当前连续区间的终点
|
| 323 |
-
ranges.append((start, end))
|
| 324 |
-
start = numbers[i] # 开始下一个连续区间
|
| 325 |
-
# 添加最后一个区间
|
| 326 |
-
ranges.append((start, numbers[-1]))
|
| 327 |
-
return ranges
|
| 328 |
-
|
| 329 |
-
@staticmethod
|
| 330 |
-
def find_continuous_ranges_with_same_mask(subtitle_frame_no_box_dict):
|
| 331 |
-
numbers = sorted(list(subtitle_frame_no_box_dict.keys()))
|
| 332 |
-
ranges = []
|
| 333 |
-
start = numbers[0] # 初始区间开始值
|
| 334 |
-
for i in range(1, len(numbers)):
|
| 335 |
-
# 如果当前帧号与前一个帧号间隔超过1,
|
| 336 |
-
# 则上一个区间结束,记录当前区间的开始与结束
|
| 337 |
-
if numbers[i] - numbers[i - 1] != 1:
|
| 338 |
-
end = numbers[i - 1] # 则该数字是当前连续区间的终点
|
| 339 |
-
ranges.append((start, end))
|
| 340 |
-
start = numbers[i] # 开始下一个连续区间
|
| 341 |
-
# 如果当前帧号与前一个帧号间隔为1,且当前帧号对应的坐标点与上一帧号对应的坐标点不一致
|
| 342 |
-
# 记录当前区间的开始与结束
|
| 343 |
-
if numbers[i] - numbers[i - 1] == 1:
|
| 344 |
-
if subtitle_frame_no_box_dict[numbers[i]] != subtitle_frame_no_box_dict[numbers[i - 1]]:
|
| 345 |
-
end = numbers[i - 1] # 则该数字是当前连续区间的终点
|
| 346 |
-
ranges.append((start, end))
|
| 347 |
-
start = numbers[i] # 开始下一个连续区间
|
| 348 |
-
# 添加最后一个区间
|
| 349 |
-
ranges.append((start, numbers[-1]))
|
| 350 |
-
return ranges
|
| 351 |
-
|
| 352 |
-
@staticmethod
|
| 353 |
-
def sub_area_to_polygon(sub_area):
|
| 354 |
-
"""
|
| 355 |
-
xmin, xmax, ymin, ymax = sub_area
|
| 356 |
-
"""
|
| 357 |
-
s_xmin = sub_area[0]
|
| 358 |
-
s_xmax = sub_area[1]
|
| 359 |
-
s_ymin = sub_area[2]
|
| 360 |
-
s_ymax = sub_area[3]
|
| 361 |
-
return Polygon([[s_xmin, s_ymin], [s_xmax, s_ymin], [s_xmax, s_ymax], [s_xmin, s_ymax]])
|
| 362 |
-
|
| 363 |
-
@staticmethod
|
| 364 |
-
def expand_and_merge_intervals(intervals, expand_size=config.STTN_NEIGHBOR_STRIDE*config.STTN_REFERENCE_LENGTH, max_length=config.STTN_MAX_LOAD_NUM):
|
| 365 |
-
# 初始化输出区间列表
|
| 366 |
-
expanded_intervals = []
|
| 367 |
-
|
| 368 |
-
# 对每个原始区间进行扩展
|
| 369 |
-
for interval in intervals:
|
| 370 |
-
start, end = interval
|
| 371 |
-
|
| 372 |
-
# 扩展至至少 'expand_size' 个单位,但不超过 'max_length' 个单位
|
| 373 |
-
expansion_amount = max(expand_size - (end - start + 1), 0)
|
| 374 |
-
|
| 375 |
-
# 在保证包含原区间的前提下尽可能平分前后扩展量
|
| 376 |
-
expand_start = max(start - expansion_amount // 2, 1) # 确保起始点不小于1
|
| 377 |
-
expand_end = end + expansion_amount // 2
|
| 378 |
-
|
| 379 |
-
# 如果扩展后的区间超出了最大长度,进行调整
|
| 380 |
-
if (expand_end - expand_start + 1) > max_length:
|
| 381 |
-
expand_end = expand_start + max_length - 1
|
| 382 |
-
|
| 383 |
-
# 对于单点的处理,需额外保证有至少 'expand_size' 长度
|
| 384 |
-
if start == end:
|
| 385 |
-
if expand_end - expand_start + 1 < expand_size:
|
| 386 |
-
expand_end = expand_start + expand_size - 1
|
| 387 |
-
|
| 388 |
-
# 检查与前一个区间是否有重叠并进行相应的合并
|
| 389 |
-
if expanded_intervals and expand_start <= expanded_intervals[-1][1]:
|
| 390 |
-
previous_start, previous_end = expanded_intervals.pop()
|
| 391 |
-
expand_start = previous_start
|
| 392 |
-
expand_end = max(expand_end, previous_end)
|
| 393 |
-
|
| 394 |
-
# 添加扩展后的区间至结果列表
|
| 395 |
-
expanded_intervals.append((expand_start, expand_end))
|
| 396 |
-
|
| 397 |
-
return expanded_intervals
|
| 398 |
-
|
| 399 |
-
@staticmethod
|
| 400 |
-
def filter_and_merge_intervals(intervals, target_length=config.STTN_REFERENCE_LENGTH):
|
| 401 |
-
"""
|
| 402 |
-
合并传入的字幕起始区间,确保区间大小最低为STTN_REFERENCE_LENGTH
|
| 403 |
-
"""
|
| 404 |
-
expanded = []
|
| 405 |
-
# 首先单独处理单点区间以扩展它们
|
| 406 |
-
for start, end in intervals:
|
| 407 |
-
if start == end: # 单点区间
|
| 408 |
-
# 扩展到接近的目标长度,但保证前后不重叠
|
| 409 |
-
prev_end = expanded[-1][1] if expanded else float('-inf')
|
| 410 |
-
next_start = float('inf')
|
| 411 |
-
# 查找下一个区间的起始点
|
| 412 |
-
for ns, ne in intervals:
|
| 413 |
-
if ns > end:
|
| 414 |
-
next_start = ns
|
| 415 |
-
break
|
| 416 |
-
# 确定新的扩展起点和终点
|
| 417 |
-
new_start = max(start - (target_length - 1) // 2, prev_end + 1)
|
| 418 |
-
new_end = min(start + (target_length - 1) // 2, next_start - 1)
|
| 419 |
-
# 如果新的扩展终点在起点前面,说明没有足够空间来进行扩展
|
| 420 |
-
if new_end < new_start:
|
| 421 |
-
new_start, new_end = start, start # 保持原样
|
| 422 |
-
expanded.append((new_start, new_end))
|
| 423 |
-
else:
|
| 424 |
-
# 非单点区间直接保留,稍后处理任何可能的重叠
|
| 425 |
-
expanded.append((start, end))
|
| 426 |
-
# 排序以合并那些因扩展导致重叠的区间
|
| 427 |
-
expanded.sort(key=lambda x: x[0])
|
| 428 |
-
# 合并重叠的区间,但仅当它们之间真正重叠且小于目标长度时
|
| 429 |
-
merged = [expanded[0]]
|
| 430 |
-
for start, end in expanded[1:]:
|
| 431 |
-
last_start, last_end = merged[-1]
|
| 432 |
-
# 检查是否重叠
|
| 433 |
-
if start <= last_end and (end - last_start + 1 < target_length or last_end - last_start + 1 < target_length):
|
| 434 |
-
# 需要合并
|
| 435 |
-
merged[-1] = (last_start, max(last_end, end)) # 合并区间
|
| 436 |
-
elif start == last_end + 1 and (end - last_start + 1 < target_length or last_end - last_start + 1 < target_length):
|
| 437 |
-
# 相邻区间也需要合并的场景
|
| 438 |
-
merged[-1] = (last_start, end)
|
| 439 |
-
else:
|
| 440 |
-
# 如果没有重叠且都大于目标长度,则直接保留
|
| 441 |
-
merged.append((start, end))
|
| 442 |
-
return merged
|
| 443 |
-
|
| 444 |
-
def compute_iou(self, box1, box2):
|
| 445 |
-
box1_polygon = self.sub_area_to_polygon(box1)
|
| 446 |
-
box2_polygon = self.sub_area_to_polygon(box2)
|
| 447 |
-
intersection = box1_polygon.intersection(box2_polygon)
|
| 448 |
-
if intersection.is_empty:
|
| 449 |
-
return -1
|
| 450 |
-
else:
|
| 451 |
-
union_area = (box1_polygon.area + box2_polygon.area - intersection.area)
|
| 452 |
-
if union_area > 0:
|
| 453 |
-
intersection_area_rate = intersection.area / union_area
|
| 454 |
-
else:
|
| 455 |
-
intersection_area_rate = 0
|
| 456 |
-
return intersection_area_rate
|
| 457 |
-
|
| 458 |
-
def get_area_max_box_dict(self, sub_frame_no_list_continuous, subtitle_frame_no_box_dict):
|
| 459 |
-
_area_max_box_dict = dict()
|
| 460 |
-
for start_no, end_no in sub_frame_no_list_continuous:
|
| 461 |
-
# 寻找面积最大文本框
|
| 462 |
-
current_no = start_no
|
| 463 |
-
# 查找当前区间矩形框最大面积
|
| 464 |
-
area_max_box_list = []
|
| 465 |
-
while current_no <= end_no:
|
| 466 |
-
for coord in subtitle_frame_no_box_dict[current_no]:
|
| 467 |
-
# 取出每一个文本框坐标
|
| 468 |
-
xmin, xmax, ymin, ymax = coord
|
| 469 |
-
# 计算当前文本框坐标面积
|
| 470 |
-
current_area = abs(xmax - xmin) * abs(ymax - ymin)
|
| 471 |
-
# 如果区间最大框列表为空,则当前面积为区间最大面积
|
| 472 |
-
if len(area_max_box_list) < 1:
|
| 473 |
-
area_max_box_list.append({
|
| 474 |
-
'area': current_area,
|
| 475 |
-
'xmin': xmin,
|
| 476 |
-
'xmax': xmax,
|
| 477 |
-
'ymin': ymin,
|
| 478 |
-
'ymax': ymax
|
| 479 |
-
})
|
| 480 |
-
# 如果列表非空,判断当前文本框是与区间最大文本框在同一区域
|
| 481 |
-
else:
|
| 482 |
-
has_same_position = False
|
| 483 |
-
# 遍历每个区间最大文本框,判断当前文本框位置是否与区间最大文本框列表的某个文本框位于同一行且交叉
|
| 484 |
-
for area_max_box in area_max_box_list:
|
| 485 |
-
if (area_max_box['ymin'] - config.THRESHOLD_HEIGHT_DIFFERENCE <= ymin
|
| 486 |
-
and ymax <= area_max_box['ymax'] + config.THRESHOLD_HEIGHT_DIFFERENCE):
|
| 487 |
-
if self.compute_iou((xmin, xmax, ymin, ymax), (
|
| 488 |
-
area_max_box['xmin'], area_max_box['xmax'], area_max_box['ymin'],
|
| 489 |
-
area_max_box['ymax'])) != -1:
|
| 490 |
-
# 如果高度差异不一样
|
| 491 |
-
if abs(abs(area_max_box['ymax'] - area_max_box['ymin']) - abs(
|
| 492 |
-
ymax - ymin)) < config.THRESHOLD_HEIGHT_DIFFERENCE:
|
| 493 |
-
has_same_position = True
|
| 494 |
-
# 如果在同一行,则计算当前面积是不是最大
|
| 495 |
-
# 判断面积大小,若当前面积更大,则将当前行的最大区域坐标点更新
|
| 496 |
-
if has_same_position and current_area > area_max_box['area']:
|
| 497 |
-
area_max_box['area'] = current_area
|
| 498 |
-
area_max_box['xmin'] = xmin
|
| 499 |
-
area_max_box['xmax'] = xmax
|
| 500 |
-
area_max_box['ymin'] = ymin
|
| 501 |
-
area_max_box['ymax'] = ymax
|
| 502 |
-
# 如果遍历了所有的区间最大文本框列表,发现是新的一行,则直接添加
|
| 503 |
-
if not has_same_position:
|
| 504 |
-
new_large_area = {
|
| 505 |
-
'area': current_area,
|
| 506 |
-
'xmin': xmin,
|
| 507 |
-
'xmax': xmax,
|
| 508 |
-
'ymin': ymin,
|
| 509 |
-
'ymax': ymax
|
| 510 |
-
}
|
| 511 |
-
if new_large_area not in area_max_box_list:
|
| 512 |
-
area_max_box_list.append(new_large_area)
|
| 513 |
-
break
|
| 514 |
-
current_no += 1
|
| 515 |
-
_area_max_box_list = list()
|
| 516 |
-
for area_max_box in area_max_box_list:
|
| 517 |
-
if area_max_box not in _area_max_box_list:
|
| 518 |
-
_area_max_box_list.append(area_max_box)
|
| 519 |
-
_area_max_box_dict[f'{start_no}->{end_no}'] = _area_max_box_list
|
| 520 |
-
return _area_max_box_dict
|
| 521 |
-
|
| 522 |
-
def get_subtitle_frame_no_box_dict_with_united_coordinates(self, subtitle_frame_no_box_dict):
|
| 523 |
-
"""
|
| 524 |
-
将多个视频帧的文本区域坐标统一
|
| 525 |
-
"""
|
| 526 |
-
subtitle_frame_no_box_dict_with_united_coordinates = dict()
|
| 527 |
-
frame_no_list = self.find_continuous_ranges_with_same_mask(subtitle_frame_no_box_dict)
|
| 528 |
-
area_max_box_dict = self.get_area_max_box_dict(frame_no_list, subtitle_frame_no_box_dict)
|
| 529 |
-
for start_no, end_no in frame_no_list:
|
| 530 |
-
current_no = start_no
|
| 531 |
-
while True:
|
| 532 |
-
area_max_box_list = area_max_box_dict[f'{start_no}->{end_no}']
|
| 533 |
-
current_boxes = subtitle_frame_no_box_dict[current_no]
|
| 534 |
-
new_subtitle_frame_no_box_list = []
|
| 535 |
-
for current_box in current_boxes:
|
| 536 |
-
current_xmin, current_xmax, current_ymin, current_ymax = current_box
|
| 537 |
-
for max_box in area_max_box_list:
|
| 538 |
-
large_xmin = max_box['xmin']
|
| 539 |
-
large_xmax = max_box['xmax']
|
| 540 |
-
large_ymin = max_box['ymin']
|
| 541 |
-
large_ymax = max_box['ymax']
|
| 542 |
-
box1 = (current_xmin, current_xmax, current_ymin, current_ymax)
|
| 543 |
-
box2 = (large_xmin, large_xmax, large_ymin, large_ymax)
|
| 544 |
-
res = self.compute_iou(box1, box2)
|
| 545 |
-
if res != -1:
|
| 546 |
-
new_subtitle_frame_no_box = (large_xmin, large_xmax, large_ymin, large_ymax)
|
| 547 |
-
if new_subtitle_frame_no_box not in new_subtitle_frame_no_box_list:
|
| 548 |
-
new_subtitle_frame_no_box_list.append(new_subtitle_frame_no_box)
|
| 549 |
-
subtitle_frame_no_box_dict_with_united_coordinates[current_no] = new_subtitle_frame_no_box_list
|
| 550 |
-
current_no += 1
|
| 551 |
-
if current_no > end_no:
|
| 552 |
-
break
|
| 553 |
-
return subtitle_frame_no_box_dict_with_united_coordinates
|
| 554 |
-
|
| 555 |
-
def prevent_missed_detection(self, subtitle_frame_no_box_dict):
|
| 556 |
-
"""
|
| 557 |
-
添加额外的文本框,防止漏检
|
| 558 |
-
"""
|
| 559 |
-
frame_no_list = self.find_continuous_ranges_with_same_mask(subtitle_frame_no_box_dict)
|
| 560 |
-
for start_no, end_no in frame_no_list:
|
| 561 |
-
current_no = start_no
|
| 562 |
-
while True:
|
| 563 |
-
current_box_list = subtitle_frame_no_box_dict[current_no]
|
| 564 |
-
if current_no + 1 != end_no and (current_no + 1) in subtitle_frame_no_box_dict.keys():
|
| 565 |
-
next_box_list = subtitle_frame_no_box_dict[current_no + 1]
|
| 566 |
-
if set(current_box_list).issubset(set(next_box_list)):
|
| 567 |
-
subtitle_frame_no_box_dict[current_no] = subtitle_frame_no_box_dict[current_no + 1]
|
| 568 |
-
current_no += 1
|
| 569 |
-
if current_no > end_no:
|
| 570 |
-
break
|
| 571 |
-
return subtitle_frame_no_box_dict
|
| 572 |
-
|
| 573 |
-
@staticmethod
|
| 574 |
-
def get_frequency_in_range(sub_frame_no_list_continuous, subtitle_frame_no_box_dict):
|
| 575 |
-
sub_area_with_frequency = {}
|
| 576 |
-
for start_no, end_no in sub_frame_no_list_continuous:
|
| 577 |
-
current_no = start_no
|
| 578 |
-
while True:
|
| 579 |
-
current_box_list = subtitle_frame_no_box_dict[current_no]
|
| 580 |
-
for current_box in current_box_list:
|
| 581 |
-
if str(current_box) not in sub_area_with_frequency.keys():
|
| 582 |
-
sub_area_with_frequency[f'{current_box}'] = 1
|
| 583 |
-
else:
|
| 584 |
-
sub_area_with_frequency[f'{current_box}'] += 1
|
| 585 |
-
current_no += 1
|
| 586 |
-
if current_no > end_no:
|
| 587 |
-
break
|
| 588 |
-
return sub_area_with_frequency
|
| 589 |
-
|
| 590 |
-
def filter_mistake_sub_area(self, subtitle_frame_no_box_dict, fps):
|
| 591 |
-
"""
|
| 592 |
-
过滤错误的字幕区域
|
| 593 |
-
"""
|
| 594 |
-
sub_frame_no_list_continuous = self.find_continuous_ranges_with_same_mask(subtitle_frame_no_box_dict)
|
| 595 |
-
sub_area_with_frequency = self.get_frequency_in_range(sub_frame_no_list_continuous, subtitle_frame_no_box_dict)
|
| 596 |
-
correct_sub_area = []
|
| 597 |
-
for sub_area in sub_area_with_frequency.keys():
|
| 598 |
-
if sub_area_with_frequency[sub_area] >= (fps // 2):
|
| 599 |
-
correct_sub_area.append(sub_area)
|
| 600 |
-
else:
|
| 601 |
-
print(f'drop {sub_area}')
|
| 602 |
-
correct_subtitle_frame_no_box_dict = dict()
|
| 603 |
-
for frame_no in subtitle_frame_no_box_dict.keys():
|
| 604 |
-
current_box_list = subtitle_frame_no_box_dict[frame_no]
|
| 605 |
-
new_box_list = []
|
| 606 |
-
for current_box in current_box_list:
|
| 607 |
-
if str(current_box) in correct_sub_area and current_box not in new_box_list:
|
| 608 |
-
new_box_list.append(current_box)
|
| 609 |
-
correct_subtitle_frame_no_box_dict[frame_no] = new_box_list
|
| 610 |
-
return correct_subtitle_frame_no_box_dict
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
class SubtitleRemover:
|
| 614 |
-
def __init__(self, vd_path, sub_area=None, gui_mode=False):
|
| 615 |
-
importlib.reload(config)
|
| 616 |
-
# 线程锁
|
| 617 |
-
self.lock = threading.RLock()
|
| 618 |
-
# 用户指定的字幕区域位置
|
| 619 |
-
self.sub_area = sub_area
|
| 620 |
-
# 是否为gui运行,gui运行需要显示预览
|
| 621 |
-
self.gui_mode = gui_mode
|
| 622 |
-
# 判断是否为图片
|
| 623 |
-
self.is_picture = False
|
| 624 |
-
if is_image_file(str(vd_path)):
|
| 625 |
-
self.sub_area = None
|
| 626 |
-
self.is_picture = True
|
| 627 |
-
# 视频路径
|
| 628 |
-
self.video_path = vd_path
|
| 629 |
-
self.video_cap = cv2.VideoCapture(vd_path)
|
| 630 |
-
# 通过视频路径获取视频名称
|
| 631 |
-
self.vd_name = Path(self.video_path).stem
|
| 632 |
-
# 视频帧总数
|
| 633 |
-
self.frame_count = int(self.video_cap.get(cv2.CAP_PROP_FRAME_COUNT) + 0.5)
|
| 634 |
-
# 视频帧率
|
| 635 |
-
self.fps = self.video_cap.get(cv2.CAP_PROP_FPS)
|
| 636 |
-
# 视频尺寸
|
| 637 |
-
self.size = (int(self.video_cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(self.video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
|
| 638 |
-
self.mask_size = (int(self.video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(self.video_cap.get(cv2.CAP_PROP_FRAME_WIDTH)))
|
| 639 |
-
self.frame_height = int(self.video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 640 |
-
self.frame_width = int(self.video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 641 |
-
# 创建字幕检测对象
|
| 642 |
-
self.sub_detector = SubtitleDetect(self.video_path, self.sub_area)
|
| 643 |
-
# 创建视频临时对象,windows下delete=True会有permission denied的报错
|
| 644 |
-
self.video_temp_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False)
|
| 645 |
-
# 创建视频写对象
|
| 646 |
-
self.video_writer = cv2.VideoWriter(self.video_temp_file.name, cv2.VideoWriter_fourcc(*'mp4v'), self.fps, self.size)
|
| 647 |
-
self.video_out_name = os.path.join(os.path.dirname(self.video_path), f'{self.vd_name}_no_sub.mp4')
|
| 648 |
-
self.video_inpaint = None
|
| 649 |
-
self.lama_inpaint = None
|
| 650 |
-
self.ext = os.path.splitext(vd_path)[-1]
|
| 651 |
-
if self.is_picture:
|
| 652 |
-
pic_dir = os.path.join(os.path.dirname(self.video_path), 'no_sub')
|
| 653 |
-
if not os.path.exists(pic_dir):
|
| 654 |
-
os.makedirs(pic_dir)
|
| 655 |
-
self.video_out_name = os.path.join(pic_dir, f'{self.vd_name}{self.ext}')
|
| 656 |
-
if torch.cuda.is_available():
|
| 657 |
-
print('use GPU for acceleration')
|
| 658 |
-
if config.USE_DML:
|
| 659 |
-
print('use DirectML for acceleration')
|
| 660 |
-
if config.MODE != config.InpaintMode.STTN:
|
| 661 |
-
print('Warning: DirectML acceleration is only available for STTN model. Falling back to CPU for other models.')
|
| 662 |
-
for provider in config.ONNX_PROVIDERS:
|
| 663 |
-
print(f"Detected execution provider: {provider}")
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
# 总处理进度
|
| 667 |
-
self.progress_total = 0
|
| 668 |
-
self.progress_remover = 0
|
| 669 |
-
self.isFinished = False
|
| 670 |
-
# 预览帧
|
| 671 |
-
self.preview_frame = None
|
| 672 |
-
# 是否将原音频嵌入到去除字幕后的视频
|
| 673 |
-
self.is_successful_merged = False
|
| 674 |
-
|
| 675 |
-
@staticmethod
|
| 676 |
-
def get_coordinates(dt_box):
|
| 677 |
-
"""
|
| 678 |
-
从返回的检测框中获取坐标
|
| 679 |
-
:param dt_box 检测框返回结果
|
| 680 |
-
:return list 坐标点列表
|
| 681 |
-
"""
|
| 682 |
-
coordinate_list = list()
|
| 683 |
-
if isinstance(dt_box, list):
|
| 684 |
-
for i in dt_box:
|
| 685 |
-
i = list(i)
|
| 686 |
-
(x1, y1) = int(i[0][0]), int(i[0][1])
|
| 687 |
-
(x2, y2) = int(i[1][0]), int(i[1][1])
|
| 688 |
-
(x3, y3) = int(i[2][0]), int(i[2][1])
|
| 689 |
-
(x4, y4) = int(i[3][0]), int(i[3][1])
|
| 690 |
-
xmin = max(x1, x4)
|
| 691 |
-
xmax = min(x2, x3)
|
| 692 |
-
ymin = max(y1, y2)
|
| 693 |
-
ymax = min(y3, y4)
|
| 694 |
-
coordinate_list.append((xmin, xmax, ymin, ymax))
|
| 695 |
-
return coordinate_list
|
| 696 |
-
|
| 697 |
-
@staticmethod
|
| 698 |
-
def is_current_frame_no_start(frame_no, continuous_frame_no_list):
|
| 699 |
-
"""
|
| 700 |
-
判断给定的帧号是否为开头,是的话返回结束帧号,不是的话返回-1
|
| 701 |
-
"""
|
| 702 |
-
for start_no, end_no in continuous_frame_no_list:
|
| 703 |
-
if start_no == frame_no:
|
| 704 |
-
return True
|
| 705 |
-
return False
|
| 706 |
-
|
| 707 |
-
@staticmethod
|
| 708 |
-
def find_frame_no_end(frame_no, continuous_frame_no_list):
|
| 709 |
-
"""
|
| 710 |
-
判断给定的帧号是否为开头,是的话返回结束帧号,不是的话返回-1
|
| 711 |
-
"""
|
| 712 |
-
for start_no, end_no in continuous_frame_no_list:
|
| 713 |
-
if start_no <= frame_no <= end_no:
|
| 714 |
-
return end_no
|
| 715 |
-
return -1
|
| 716 |
-
|
| 717 |
-
def update_progress(self, tbar, increment):
|
| 718 |
-
tbar.update(increment)
|
| 719 |
-
current_percentage = (tbar.n / tbar.total) * 100
|
| 720 |
-
self.progress_remover = int(current_percentage) // 2
|
| 721 |
-
self.progress_total = 50 + self.progress_remover
|
| 722 |
-
|
| 723 |
-
def propainter_mode(self, tbar):
|
| 724 |
-
print('use propainter mode')
|
| 725 |
-
sub_list = self.sub_detector.find_subtitle_frame_no(sub_remover=self)
|
| 726 |
-
continuous_frame_no_list = self.sub_detector.find_continuous_ranges_with_same_mask(sub_list)
|
| 727 |
-
scene_div_points = self.sub_detector.get_scene_div_frame_no(self.video_path)
|
| 728 |
-
continuous_frame_no_list = self.sub_detector.split_range_by_scene(continuous_frame_no_list,
|
| 729 |
-
scene_div_points)
|
| 730 |
-
self.video_inpaint = VideoInpaint(config.PROPAINTER_MAX_LOAD_NUM)
|
| 731 |
-
print('[Processing] start removing subtitles...')
|
| 732 |
-
index = 0
|
| 733 |
-
while True:
|
| 734 |
-
ret, frame = self.video_cap.read()
|
| 735 |
-
if not ret:
|
| 736 |
-
break
|
| 737 |
-
index += 1
|
| 738 |
-
# 如果当前帧没有水印/文本则直接写
|
| 739 |
-
if index not in sub_list.keys():
|
| 740 |
-
self.video_writer.write(frame)
|
| 741 |
-
print(f'write frame: {index}')
|
| 742 |
-
self.update_progress(tbar, increment=1)
|
| 743 |
-
continue
|
| 744 |
-
# 如果有水印,判断该帧是不是开头帧
|
| 745 |
-
else:
|
| 746 |
-
# 如果是开头帧,则批推理到尾帧
|
| 747 |
-
if self.is_current_frame_no_start(index, continuous_frame_no_list):
|
| 748 |
-
# print(f'No 1 Current index: {index}')
|
| 749 |
-
start_frame_no = index
|
| 750 |
-
print(f'find start: {start_frame_no}')
|
| 751 |
-
# 找到结束帧
|
| 752 |
-
end_frame_no = self.find_frame_no_end(index, continuous_frame_no_list)
|
| 753 |
-
# 判断当前帧号是不是字幕起始位置
|
| 754 |
-
# 如果获取的结束帧号不为-1则说明
|
| 755 |
-
if end_frame_no != -1:
|
| 756 |
-
print(f'find end: {end_frame_no}')
|
| 757 |
-
# ************ 读取该区间所有帧 start ************
|
| 758 |
-
temp_frames = list()
|
| 759 |
-
# 将头帧加入处理列表
|
| 760 |
-
temp_frames.append(frame)
|
| 761 |
-
inner_index = 0
|
| 762 |
-
# 一直读取到尾帧
|
| 763 |
-
while index < end_frame_no:
|
| 764 |
-
ret, frame = self.video_cap.read()
|
| 765 |
-
if not ret:
|
| 766 |
-
break
|
| 767 |
-
index += 1
|
| 768 |
-
temp_frames.append(frame)
|
| 769 |
-
# ************ 读取该区间所有帧 end ************
|
| 770 |
-
if len(temp_frames) < 1:
|
| 771 |
-
# 没有待处理,直接跳过
|
| 772 |
-
continue
|
| 773 |
-
elif len(temp_frames) == 1:
|
| 774 |
-
inner_index += 1
|
| 775 |
-
single_mask = create_mask(self.mask_size, sub_list[index])
|
| 776 |
-
if self.lama_inpaint is None:
|
| 777 |
-
self.lama_inpaint = LamaInpaint()
|
| 778 |
-
inpainted_frame = self.lama_inpaint(frame, single_mask)
|
| 779 |
-
self.video_writer.write(inpainted_frame)
|
| 780 |
-
print(f'write frame: {start_frame_no + inner_index} with mask {sub_list[start_frame_no]}')
|
| 781 |
-
self.update_progress(tbar, increment=1)
|
| 782 |
-
continue
|
| 783 |
-
else:
|
| 784 |
-
# 将读取的视频帧分批处理
|
| 785 |
-
# 1. 获取当前批次使用的mask
|
| 786 |
-
mask = create_mask(self.mask_size, sub_list[start_frame_no])
|
| 787 |
-
for batch in batch_generator(temp_frames, config.PROPAINTER_MAX_LOAD_NUM):
|
| 788 |
-
# 2. 调用批推理
|
| 789 |
-
if len(batch) == 1:
|
| 790 |
-
single_mask = create_mask(self.mask_size, sub_list[start_frame_no])
|
| 791 |
-
if self.lama_inpaint is None:
|
| 792 |
-
self.lama_inpaint = LamaInpaint()
|
| 793 |
-
inpainted_frame = self.lama_inpaint(frame, single_mask)
|
| 794 |
-
self.video_writer.write(inpainted_frame)
|
| 795 |
-
print(f'write frame: {start_frame_no + inner_index} with mask {sub_list[start_frame_no]}')
|
| 796 |
-
inner_index += 1
|
| 797 |
-
self.update_progress(tbar, increment=1)
|
| 798 |
-
elif len(batch) > 1:
|
| 799 |
-
inpainted_frames = self.video_inpaint.inpaint(batch, mask)
|
| 800 |
-
for i, inpainted_frame in enumerate(inpainted_frames):
|
| 801 |
-
self.video_writer.write(inpainted_frame)
|
| 802 |
-
print(f'write frame: {start_frame_no + inner_index} with mask {sub_list[index]}')
|
| 803 |
-
inner_index += 1
|
| 804 |
-
if self.gui_mode:
|
| 805 |
-
self.preview_frame = cv2.hconcat([batch[i], inpainted_frame])
|
| 806 |
-
self.update_progress(tbar, increment=len(batch))
|
| 807 |
-
|
| 808 |
-
def sttn_mode_with_no_detection(self, tbar):
|
| 809 |
-
"""
|
| 810 |
-
使用sttn对选中区域进行重绘,不进行字幕检测
|
| 811 |
-
"""
|
| 812 |
-
print('use sttn mode with no detection')
|
| 813 |
-
print('[Processing] start removing subtitles...')
|
| 814 |
-
if self.sub_area is not None:
|
| 815 |
-
ymin, ymax, xmin, xmax = self.sub_area
|
| 816 |
-
else:
|
| 817 |
-
print('[Info] No subtitle area has been set. Video will be processed in full screen. As a result, the final outcome might be suboptimal.')
|
| 818 |
-
ymin, ymax, xmin, xmax = 0, self.frame_height, 0, self.frame_width
|
| 819 |
-
mask_area_coordinates = [(xmin, xmax, ymin, ymax)]
|
| 820 |
-
mask = create_mask(self.mask_size, mask_area_coordinates)
|
| 821 |
-
sttn_video_inpaint = STTNVideoInpaint(self.video_path)
|
| 822 |
-
sttn_video_inpaint(input_mask=mask, input_sub_remover=self, tbar=tbar)
|
| 823 |
-
|
| 824 |
-
def sttn_mode(self, tbar):
|
| 825 |
-
# 是否跳过字幕帧寻找
|
| 826 |
-
if config.STTN_SKIP_DETECTION:
|
| 827 |
-
# 若跳过则世界使用sttn模式
|
| 828 |
-
self.sttn_mode_with_no_detection(tbar)
|
| 829 |
-
else:
|
| 830 |
-
print('use sttn mode')
|
| 831 |
-
sttn_inpaint = STTNInpaint()
|
| 832 |
-
sub_list = self.sub_detector.find_subtitle_frame_no(sub_remover=self)
|
| 833 |
-
continuous_frame_no_list = self.sub_detector.find_continuous_ranges_with_same_mask(sub_list)
|
| 834 |
-
print(continuous_frame_no_list)
|
| 835 |
-
continuous_frame_no_list = self.sub_detector.filter_and_merge_intervals(continuous_frame_no_list)
|
| 836 |
-
print(continuous_frame_no_list)
|
| 837 |
-
start_end_map = dict()
|
| 838 |
-
for interval in continuous_frame_no_list:
|
| 839 |
-
start, end = interval
|
| 840 |
-
start_end_map[start] = end
|
| 841 |
-
current_frame_index = 0
|
| 842 |
-
print('[Processing] start removing subtitles...')
|
| 843 |
-
while True:
|
| 844 |
-
ret, frame = self.video_cap.read()
|
| 845 |
-
# 如果读取到为,则结束
|
| 846 |
-
if not ret:
|
| 847 |
-
break
|
| 848 |
-
current_frame_index += 1
|
| 849 |
-
# 判断当前帧号是不是字幕区间开始, 如果不是,则直接写
|
| 850 |
-
if current_frame_index not in start_end_map.keys():
|
| 851 |
-
self.video_writer.write(frame)
|
| 852 |
-
print(f'write frame: {current_frame_index}')
|
| 853 |
-
self.update_progress(tbar, increment=1)
|
| 854 |
-
if self.gui_mode:
|
| 855 |
-
self.preview_frame = cv2.hconcat([frame, frame])
|
| 856 |
-
# 如果是区间开始,则找到尾巴
|
| 857 |
-
else:
|
| 858 |
-
start_frame_index = current_frame_index
|
| 859 |
-
end_frame_index = start_end_map[current_frame_index]
|
| 860 |
-
print(f'processing frame {start_frame_index} to {end_frame_index}')
|
| 861 |
-
# 用于存储需要去字幕的视频帧
|
| 862 |
-
frames_need_inpaint = list()
|
| 863 |
-
frames_need_inpaint.append(frame)
|
| 864 |
-
inner_index = 0
|
| 865 |
-
# 接着往下读,直到读取到尾巴
|
| 866 |
-
for j in range(end_frame_index - start_frame_index):
|
| 867 |
-
ret, frame = self.video_cap.read()
|
| 868 |
-
if not ret:
|
| 869 |
-
break
|
| 870 |
-
current_frame_index += 1
|
| 871 |
-
frames_need_inpaint.append(frame)
|
| 872 |
-
mask_area_coordinates = []
|
| 873 |
-
# 1. 获取当前批次的mask坐标全集
|
| 874 |
-
for mask_index in range(start_frame_index, end_frame_index):
|
| 875 |
-
if mask_index in sub_list.keys():
|
| 876 |
-
for area in sub_list[mask_index]:
|
| 877 |
-
xmin, xmax, ymin, ymax = area
|
| 878 |
-
# 判断是不是非字幕区域(如果宽大于长,则认为是错误检测)
|
| 879 |
-
if (ymax - ymin) - (xmax - xmin) > config.THRESHOLD_HEIGHT_WIDTH_DIFFERENCE:
|
| 880 |
-
continue
|
| 881 |
-
if area not in mask_area_coordinates:
|
| 882 |
-
mask_area_coordinates.append(area)
|
| 883 |
-
# 1. 获取当前批次使用的mask
|
| 884 |
-
mask = create_mask(self.mask_size, mask_area_coordinates)
|
| 885 |
-
print(f'inpaint with mask: {mask_area_coordinates}')
|
| 886 |
-
for batch in batch_generator(frames_need_inpaint, config.STTN_MAX_LOAD_NUM):
|
| 887 |
-
# 2. 调用批推理
|
| 888 |
-
if len(batch) >= 1:
|
| 889 |
-
inpainted_frames = sttn_inpaint(batch, mask)
|
| 890 |
-
for i, inpainted_frame in enumerate(inpainted_frames):
|
| 891 |
-
self.video_writer.write(inpainted_frame)
|
| 892 |
-
print(f'write frame: {start_frame_index + inner_index} with mask')
|
| 893 |
-
inner_index += 1
|
| 894 |
-
if self.gui_mode:
|
| 895 |
-
self.preview_frame = cv2.hconcat([batch[i], inpainted_frame])
|
| 896 |
-
self.update_progress(tbar, increment=len(batch))
|
| 897 |
-
|
| 898 |
-
def lama_mode(self, tbar):
|
| 899 |
-
print('use lama mode')
|
| 900 |
-
sub_list = self.sub_detector.find_subtitle_frame_no(sub_remover=self)
|
| 901 |
-
if self.lama_inpaint is None:
|
| 902 |
-
self.lama_inpaint = LamaInpaint()
|
| 903 |
-
index = 0
|
| 904 |
-
print('[Processing] start removing subtitles...')
|
| 905 |
-
while True:
|
| 906 |
-
ret, frame = self.video_cap.read()
|
| 907 |
-
if not ret:
|
| 908 |
-
break
|
| 909 |
-
original_frame = frame
|
| 910 |
-
index += 1
|
| 911 |
-
if index in sub_list.keys():
|
| 912 |
-
mask = create_mask(self.mask_size, sub_list[index])
|
| 913 |
-
if config.LAMA_SUPER_FAST:
|
| 914 |
-
frame = cv2.inpaint(frame, mask, 3, cv2.INPAINT_TELEA)
|
| 915 |
-
else:
|
| 916 |
-
frame = self.lama_inpaint(frame, mask)
|
| 917 |
-
if self.gui_mode:
|
| 918 |
-
self.preview_frame = cv2.hconcat([original_frame, frame])
|
| 919 |
-
if self.is_picture:
|
| 920 |
-
cv2.imencode(self.ext, frame)[1].tofile(self.video_out_name)
|
| 921 |
-
else:
|
| 922 |
-
self.video_writer.write(frame)
|
| 923 |
-
tbar.update(1)
|
| 924 |
-
self.progress_remover = 100 * float(index) / float(self.frame_count) // 2
|
| 925 |
-
self.progress_total = 50 + self.progress_remover
|
| 926 |
-
|
| 927 |
-
def run(self):
|
| 928 |
-
# 记录开始时间
|
| 929 |
-
start_time = time.time()
|
| 930 |
-
# 重置进度条
|
| 931 |
-
self.progress_total = 0
|
| 932 |
-
tbar = tqdm(total=int(self.frame_count), unit='frame', position=0, file=sys.__stdout__,
|
| 933 |
-
desc='Subtitle Removing')
|
| 934 |
-
if self.is_picture:
|
| 935 |
-
sub_list = self.sub_detector.find_subtitle_frame_no(sub_remover=self)
|
| 936 |
-
self.lama_inpaint = LamaInpaint()
|
| 937 |
-
original_frame = cv2.imread(self.video_path)
|
| 938 |
-
if len(sub_list):
|
| 939 |
-
mask = create_mask(original_frame.shape[0:2], sub_list[1])
|
| 940 |
-
inpainted_frame = self.lama_inpaint(original_frame, mask)
|
| 941 |
-
else:
|
| 942 |
-
inpainted_frame = original_frame
|
| 943 |
-
if self.gui_mode:
|
| 944 |
-
self.preview_frame = cv2.hconcat([original_frame, inpainted_frame])
|
| 945 |
-
cv2.imencode(self.ext, inpainted_frame)[1].tofile(self.video_out_name)
|
| 946 |
-
tbar.update(1)
|
| 947 |
-
self.progress_total = 100
|
| 948 |
-
else:
|
| 949 |
-
# 精准模式下,获取场景分割的帧号,进一步切割
|
| 950 |
-
if config.MODE == config.InpaintMode.PROPAINTER:
|
| 951 |
-
self.propainter_mode(tbar)
|
| 952 |
-
elif config.MODE == config.InpaintMode.STTN:
|
| 953 |
-
self.sttn_mode(tbar)
|
| 954 |
-
else:
|
| 955 |
-
self.lama_mode(tbar)
|
| 956 |
-
self.video_cap.release()
|
| 957 |
-
self.video_writer.release()
|
| 958 |
-
if not self.is_picture:
|
| 959 |
-
# 将原音频合并到新生成的视频文件中
|
| 960 |
-
self.merge_audio_to_video()
|
| 961 |
-
print(f"[Finished]Subtitle successfully removed, video generated at:{self.video_out_name}")
|
| 962 |
-
else:
|
| 963 |
-
print(f"[Finished]Subtitle successfully removed, picture generated at:{self.video_out_name}")
|
| 964 |
-
print(f'time cost: {round(time.time() - start_time, 2)}s')
|
| 965 |
-
self.isFinished = True
|
| 966 |
-
self.progress_total = 100
|
| 967 |
-
if os.path.exists(self.video_temp_file.name):
|
| 968 |
-
try:
|
| 969 |
-
os.remove(self.video_temp_file.name)
|
| 970 |
-
except Exception:
|
| 971 |
-
if platform.system() in ['Windows']:
|
| 972 |
-
pass
|
| 973 |
-
else:
|
| 974 |
-
print(f'failed to delete temp file {self.video_temp_file.name}')
|
| 975 |
-
|
| 976 |
-
def merge_audio_to_video(self):
|
| 977 |
-
# 创建音频临时对象,windows下delete=True会有permission denied的报错
|
| 978 |
-
temp = tempfile.NamedTemporaryFile(suffix='.aac', delete=False)
|
| 979 |
-
audio_extract_command = [config.FFMPEG_PATH,
|
| 980 |
-
"-y", "-i", self.video_path,
|
| 981 |
-
"-acodec", "copy",
|
| 982 |
-
"-vn", "-loglevel", "error", temp.name]
|
| 983 |
-
use_shell = True if os.name == "nt" else False
|
| 984 |
-
try:
|
| 985 |
-
subprocess.check_output(audio_extract_command, stdin=open(os.devnull), shell=use_shell)
|
| 986 |
-
except Exception:
|
| 987 |
-
print('fail to extract audio')
|
| 988 |
-
return
|
| 989 |
-
else:
|
| 990 |
-
if os.path.exists(self.video_temp_file.name):
|
| 991 |
-
audio_merge_command = [config.FFMPEG_PATH,
|
| 992 |
-
"-y", "-i", self.video_temp_file.name,
|
| 993 |
-
"-i", temp.name,
|
| 994 |
-
"-vcodec", "libx264" if config.USE_H264 else "copy",
|
| 995 |
-
"-acodec", "copy",
|
| 996 |
-
"-loglevel", "error", self.video_out_name]
|
| 997 |
-
try:
|
| 998 |
-
subprocess.check_output(audio_merge_command, stdin=open(os.devnull), shell=use_shell)
|
| 999 |
-
except Exception:
|
| 1000 |
-
print('fail to merge audio')
|
| 1001 |
-
return
|
| 1002 |
-
if os.path.exists(temp.name):
|
| 1003 |
-
try:
|
| 1004 |
-
os.remove(temp.name)
|
| 1005 |
-
except Exception:
|
| 1006 |
-
if platform.system() in ['Windows']:
|
| 1007 |
-
pass
|
| 1008 |
-
else:
|
| 1009 |
-
print(f'failed to delete temp file {temp.name}')
|
| 1010 |
-
self.is_successful_merged = True
|
| 1011 |
-
finally:
|
| 1012 |
-
temp.close()
|
| 1013 |
-
if not self.is_successful_merged:
|
| 1014 |
-
try:
|
| 1015 |
-
shutil.copy2(self.video_temp_file.name, self.video_out_name)
|
| 1016 |
-
except IOError as e:
|
| 1017 |
-
print("Unable to copy file. %s" % e)
|
| 1018 |
-
self.video_temp_file.close()
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
if __name__ == '__main__':
|
| 1022 |
-
multiprocessing.set_start_method("spawn")
|
| 1023 |
-
# 1. 提示用户输入视频路径
|
| 1024 |
-
video_path = input(f"Please input video or image file path: ").strip()
|
| 1025 |
-
# 判断视频路径是不是一个目录,是目录的化,批量处理改目录下的所有视频文件
|
| 1026 |
-
# 2. 按以下顺序传入字幕区域
|
| 1027 |
-
# sub_area = (ymin, ymax, xmin, xmax)
|
| 1028 |
-
# 3. 新建字幕提取对象
|
| 1029 |
-
if is_video_or_image(video_path):
|
| 1030 |
-
sd = SubtitleRemover(video_path, sub_area=None)
|
| 1031 |
-
sd.run()
|
| 1032 |
-
else:
|
| 1033 |
-
print(f'Invalid video path: {video_path}')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
import cv2
|
| 3 |
+
from config import LAMA_MODEL_PATH
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
def process_video(input_video_path, output_video_path):
|
| 6 |
cap = cv2.VideoCapture(input_video_path)
|
|
|
|
| 14 |
ret, frame = cap.read()
|
| 15 |
if not ret:
|
| 16 |
break
|
| 17 |
+
# 模拟字幕区域模糊(底部 15%)
|
| 18 |
y1 = int(h * 0.85)
|
| 19 |
y2 = h
|
| 20 |
frame[y1:y2, :] = cv2.GaussianBlur(frame[y1:y2, :], (21, 21), 0)
|
|
|
|
| 31 |
parser.add_argument("--output_video", type=str, required=True)
|
| 32 |
args = parser.parse_args()
|
| 33 |
process_video(args.input_video, args.output_video)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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