File size: 32,445 Bytes
8fcb663 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 | from __future__ import annotations
import subprocess
from contextlib import nullcontext
from pathlib import Path
from typing import List, Optional, Sequence, Tuple, Union
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image, ImageOps
from transformers import DINOv3ViTConfig, DINOv3ViTModel
import math
import os
torch.set_float32_matmul_precision("highest")
class BaseDPTSegmentation(nn.Module):
def __init__(self, num_classes=1, num_outputs: int=3, encoder_name: str='facebook/dinov3-vitb16-pretrain-lvd1689m', features: int=256, out_channels: Optional[List[int]]=None, use_bn: bool=True, use_clstoken: bool=False):
super().__init__()
self.patch_size = 16
self.encoder_name = encoder_name
if encoder_name != 'facebook/dinov3-vitb16-pretrain-lvd1689m':
raise ValueError(
'This BEN3 checkpoint is built for facebook/dinov3-vitb16-pretrain-lvd1689m.'
)
encoder_config = DINOv3ViTConfig(
patch_size=16,
hidden_size=768,
intermediate_size=3072,
num_hidden_layers=12,
num_attention_heads=12,
hidden_act='gelu',
attention_dropout=0.0,
initializer_range=0.02,
layer_norm_eps=1e-5,
rope_theta=100.0,
image_size=224,
num_channels=3,
query_bias=True,
key_bias=False,
value_bias=True,
proj_bias=True,
mlp_bias=True,
layerscale_value=1.0,
drop_path_rate=0.0,
use_gated_mlp=False,
num_register_tokens=4,
pos_embed_shift=None,
pos_embed_jitter=None,
pos_embed_rescale=2.0,
)
self.encoder = DINOv3ViTModel(encoder_config)
self.intermediate_layer_idx = {
'facebook/dinov3-vitb16-pretrain-lvd1689m': [2, 5, 8, 11]
}
dim = self.encoder.config.hidden_size
self.n_register_tokens = getattr(self.encoder.config, 'num_register_tokens', 4)
out_channels = out_channels or [256, 512, 1024, 1024]
self.seg_head = self._create_segmentation_head(
nclass=num_classes,
num_outputs=num_outputs,
in_channels=dim,
features=features,
use_bn=use_bn,
out_channels=out_channels,
use_clstoken=use_clstoken,
patch_size=self.patch_size,
)
def _create_segmentation_head(self, **kwargs):
raise NotImplementedError
def extract_intermediate_features(self, x):
layer_indices = self.intermediate_layer_idx.get(self.encoder_name, [2, 5, 8, 11])
outputs = self.encoder(pixel_values=x, output_hidden_states=True, return_dict=True)
hidden_states = outputs.hidden_states
features = []
for layer_idx in layer_indices:
hidden_state = hidden_states[layer_idx]
if self.seg_head.use_clstoken:
cls_token = hidden_state[:, 0]
patch_tokens = hidden_state[:, 1 + self.n_register_tokens:]
features.append((patch_tokens, cls_token))
else:
patch_tokens = hidden_state[:, 1 + self.n_register_tokens:]
features.append((patch_tokens,))
return features
class DPTSegmentation(BaseDPTSegmentation):
def _create_segmentation_head(self, **kwargs):
return DPTSegmentationHead(**kwargs)
def forward(self, x):
h, w = x.shape[-2:]
features = self.extract_intermediate_features(x)
patch_h, patch_w = (h // 16, w // 16)
outputs = self.seg_head(features, patch_h, patch_w)
return outputs
class BaseDPTSegmentationHead(nn.Module):
def __init__(self, nclass, in_channels, num_outputs: int=3, features=256, use_bn=False, out_channels=[256, 512, 1024, 1024], use_clstoken=False, patch_size=16):
super().__init__()
self.nclass = nclass
self.patch_size = patch_size
self.use_clstoken = use_clstoken
self._init_projections(in_channels, out_channels)
self._init_resize_layers(out_channels)
self._init_readout_projections(in_channels, use_clstoken)
self._init_dpt_components(out_channels, features, use_bn)
self._init_output_heads(features, num_outputs)
def _init_projections(self, in_channels, out_channels):
self.projects = nn.ModuleList([nn.Conv2d(in_channels, out_channel, kernel_size=1, stride=1, padding=0) for out_channel in out_channels])
def _init_resize_layers(self, out_channels):
self.resize_layers = nn.ModuleList([nn.ConvTranspose2d(out_channels[0], out_channels[0], kernel_size=4, stride=4, padding=0), nn.ConvTranspose2d(out_channels[1], out_channels[1], kernel_size=2, stride=2, padding=0), nn.Identity(), nn.Conv2d(out_channels[3], out_channels[3], kernel_size=3, stride=2, padding=1)])
def _init_readout_projections(self, in_channels, use_clstoken):
if use_clstoken:
self.readout_projects = nn.ModuleList([nn.Sequential(nn.Linear(2 * in_channels, in_channels), nn.GELU()) for _ in range(4)])
else:
self.readout_projects = None
def _init_dpt_components(self, out_channels, features, use_bn):
self.scratch = _make_scratch(out_channels, features, groups=1, expand=False)
self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
def _init_output_heads(self, features, num_outputs):
self.mask_head = MultiMaskHead(features, num_outputs, inter_features=32)
self.classifier_head = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(features, 64), nn.ReLU(True), nn.Linear(64, num_outputs))
def process_encoder_features(self, out_features, patch_h, patch_w):
processed_features = []
for i, feature_tuple in enumerate(out_features):
if self.use_clstoken:
patch_tokens, cls_token = (feature_tuple[0], feature_tuple[1])
readout = cls_token.unsqueeze(1).expand_as(patch_tokens)
x = self.readout_projects[i](torch.cat((patch_tokens, readout), -1))
else:
patch_tokens = feature_tuple[0]
x = patch_tokens
x = x.permute(0, 2, 1).reshape(x.shape[0], x.shape[-1], patch_h, patch_w)
x = self.projects[i](x)
x = self.resize_layers[i](x)
processed_features.append(x)
return processed_features
class DPTSegmentationHead(BaseDPTSegmentationHead):
def forward(self, out_features, patch_h, patch_w):
processed_features = self.process_encoder_features(out_features, patch_h, patch_w)
layer_1_rn = self.scratch.layer1_rn(processed_features[0])
layer_2_rn = self.scratch.layer2_rn(processed_features[1])
layer_3_rn = self.scratch.layer3_rn(processed_features[2])
layer_4_rn = self.scratch.layer4_rn(processed_features[3])
path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
aux_out = self.classifier_head(path_1)
pred_masks = self.mask_head(path_1, (int(patch_h * self.patch_size), int(patch_w * self.patch_size)))
return (pred_masks, aux_out)
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
out_shape4 = out_shape if len(in_shape) >= 4 else None
if expand:
out_shape1 = out_shape
out_shape2 = out_shape * 2
out_shape3 = out_shape * 4
out_shape4 = out_shape * 8 if len(in_shape) >= 4 else None
scratch.layer1_rn = nn.Conv2d(in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
scratch.layer2_rn = nn.Conv2d(in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
scratch.layer3_rn = nn.Conv2d(in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
if len(in_shape) >= 4:
scratch.layer4_rn = nn.Conv2d(in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
return scratch
class ResidualConvUnit(nn.Module):
def __init__(self, features, activation, bn):
super().__init__()
self.bn = bn
self.groups = 1
self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
if self.bn:
self.bn1 = nn.BatchNorm2d(features)
self.bn2 = nn.BatchNorm2d(features)
self.activation = activation
def forward(self, x):
out = self.activation(x)
out = self.conv1(out)
if self.bn:
out = self.bn1(out)
out = self.activation(out)
out = self.conv2(out)
if self.bn:
out = self.bn2(out)
return out + x
class FeatureFusionBlock(nn.Module):
def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=False, size=None):
super().__init__()
self.deconv = deconv
self.align_corners = align_corners
self.groups = 1
self.expand = expand
self.size = size
out_features = features // 2 if expand else features
self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
self.resConfUnit1 = ResidualConvUnit(features, activation, bn)
self.resConfUnit2 = ResidualConvUnit(features, activation, bn)
def forward(self, *xs, size=None):
output = xs[0]
if len(xs) == 2:
res = self.resConfUnit1(xs[1])
output = output + res
output = self.resConfUnit2(output)
if size is not None:
modifier = {'size': size}
elif self.size is not None:
modifier = {'size': self.size}
else:
modifier = {'scale_factor': 2}
output = F.interpolate(output, **modifier, mode='bilinear', align_corners=self.align_corners)
output = self.out_conv(output)
return output
def _make_fusion_block(features, use_bn, size=None):
return FeatureFusionBlock(features, nn.ReLU(False), deconv=False, bn=use_bn, expand=False, align_corners=False, size=size)
class MultiMaskHead(nn.Module):
def __init__(self, in_features: int, n_masks: int, inter_features: int=32):
super().__init__()
self.output_conv1 = nn.Conv2d(in_features, in_features // 2, kernel_size=3, stride=1, padding=1)
self.upsample_2x = nn.Sequential(nn.ConvTranspose2d(in_features // 2, inter_features * 2, kernel_size=4, stride=2, padding=1), nn.ReLU(inplace=True), nn.Conv2d(inter_features * 2, inter_features * 2, kernel_size=3, padding=1), nn.ReLU(inplace=True))
self.mask_heads = nn.ModuleList([nn.Sequential(nn.Conv2d(inter_features * 2, inter_features, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(inter_features, 1, kernel_size=1, stride=1, padding=0)) for _ in range(n_masks)])
def forward(self, x, target_size):
feat = self.output_conv1(x)
feat = self.upsample_2x(feat)
feat = F.interpolate(feat, size=target_size, mode='bilinear', align_corners=False, antialias=False)
masks = []
for head in self.mask_heads:
mask = head(feat)
masks.append(mask)
return torch.cat(masks, dim=1)
PILInput = Union[Image.Image, Sequence[Image.Image]]
class BEN3:
def __init__(
self,
checkpoint_path: str,
image_size: int = 1024,
device: str = "cuda" if torch.cuda.is_available() else "cpu",
use_fp16: bool = True,
compile_model: bool = False,
compile_mode: str = "reduce-overhead",
):
self.image_size = int(image_size)
if self.image_size <= 0:
raise ValueError("image_size must be > 0")
self._requested_fp16 = bool(use_fp16)
self.device = torch.device(device)
self.use_fp16 = self._requested_fp16 and self.device.type == "cuda"
self.fp = torch.float16 if self.use_fp16 else torch.float32
self.amp_dtype = torch.float16
self.model = DPTSegmentation().to(
device=self.device,
dtype=self.fp,
).eval()
model_checkpoint = torch.load(
checkpoint_path,
map_location="cpu",
weights_only=True,
)
self.model.load_state_dict(model_checkpoint, strict=True)
self._imagenet_mean = torch.tensor(
[0.485, 0.456, 0.406],
dtype=torch.float32,
device=self.device,
).view(1, 3, 1, 1)
self._imagenet_std = torch.tensor(
[0.229, 0.224, 0.225],
dtype=torch.float32,
device=self.device,
).view(1, 3, 1, 1)
self._compiled = False
self._compile_mode = compile_mode
if compile_model:
self.compile(mode=compile_mode)
def eval(self):
self.model.eval()
return self
def train(self, mode: bool = True):
self.model.train(mode)
return self
def to(self, device: Union[str, torch.device]):
self.device = torch.device(device)
self.use_fp16 = self._requested_fp16 and self.device.type == "cuda"
self.fp = torch.float16 if self.use_fp16 else torch.float32
self.model = self.model.to(
device=self.device,
dtype=self.fp,
)
self._imagenet_mean = self._imagenet_mean.to(self.device)
self._imagenet_std = self._imagenet_std.to(self.device)
return self
def cuda(self, device: Optional[Union[int, str, torch.device]] = None):
if device is None:
target = torch.device("cuda")
elif isinstance(device, int):
target = torch.device(f"cuda:{device}")
else:
target = torch.device(device)
return self.to(target)
def cpu(self):
return self.to("cpu")
def compile(self, mode: str = "reduce-overhead"):
if not hasattr(torch, "compile"):
raise RuntimeError("torch.compile requires a supported PyTorch 2.x build")
if self._compiled:
return self
self.model = torch.compile(self.model, mode=mode)
self._compiled = True
self._compile_mode = mode
return self
def _autocast_context(self):
if self.use_fp16:
return torch.autocast(
device_type="cuda",
dtype=self.amp_dtype,
)
return nullcontext()
@torch.inference_mode()
def forward(self, image_batch: torch.Tensor) -> torch.Tensor:
if image_batch.ndim != 4:
raise ValueError(
f"Expected image_batch [B,3,H,W], got {tuple(image_batch.shape)}"
)
if image_batch.shape[1] != 3:
raise ValueError(
f"Expected 3 input channels, got {image_batch.shape[1]}"
)
image_batch = image_batch.to(
device=self.device,
dtype=torch.float32,
non_blocking=True,
)
base_batch = (
image_batch - self._imagenet_mean
) / self._imagenet_std
with self._autocast_context():
pred_masks, aux_out = self.model(base_batch)
pred_masks = torch.sigmoid(pred_masks)
best_idx = aux_out.argmax(dim=1)
batch_idx = torch.arange(
pred_masks.shape[0],
device=pred_masks.device,
)
best_mask = pred_masks[batch_idx, best_idx]
return best_mask
def _rgb_arrays_to_tensor(
self,
images_rgb: Sequence[np.ndarray],
) -> torch.Tensor:
if not images_rgb:
raise ValueError("images_rgb cannot be empty")
resized = []
for image in images_rgb:
if not isinstance(image, np.ndarray):
raise TypeError("Each RGB image must be a numpy.ndarray")
if image.ndim != 3 or image.shape[2] != 3:
raise ValueError(
f"Expected RGB image [H,W,3], got {image.shape}"
)
resized.append(
cv2.resize(
image,
(self.image_size, self.image_size),
interpolation=cv2.INTER_LANCZOS4,
)
)
batch_np = np.stack(resized, axis=0)
return (
torch.from_numpy(batch_np)
.permute(0, 3, 1, 2)
.contiguous()
.float()
.div_(255.0)
)
def _pil_to_tensor(
self,
image: Image.Image,
) -> Tuple[torch.Tensor, Image.Image, Tuple[int, int]]:
if not isinstance(image, Image.Image):
raise TypeError("image must be a PIL.Image.Image")
original = ImageOps.exif_transpose(image).copy()
width, height = original.size
rgb = np.asarray(original.convert("RGB"), dtype=np.uint8)
tensor = self._rgb_arrays_to_tensor([rgb])[0]
return tensor, original, (width, height)
def _rgb_batch_to_tensor(
self,
frames_rgb: Sequence[np.ndarray],
) -> torch.Tensor:
return self._rgb_arrays_to_tensor(frames_rgb)
@staticmethod
def _postprocess_batch_same_size(
refined: torch.Tensor,
output_hw: Tuple[int, int],
) -> np.ndarray:
if refined.ndim == 3:
refined = refined.unsqueeze(1)
if refined.ndim != 4 or refined.shape[1] != 1:
raise ValueError(
f"Expected refined [B,1,H,W], got {tuple(refined.shape)}"
)
refined = F.interpolate(
refined.float(),
size=output_hw,
mode="bilinear",
align_corners=False,
)
return (
refined[:, 0]
.clamp_(0.0, 1.0)
.mul_(255.0)
.round_()
.byte()
.cpu()
.numpy()
)
@staticmethod
def _postprocess_one(
refined_one: torch.Tensor,
output_hw: Tuple[int, int],
) -> np.ndarray:
return BEN3._postprocess_batch_same_size(
refined_one,
output_hw,
)[0]
def predict_masks(
self,
images: Sequence[Image.Image],
) -> List[np.ndarray]:
images = list(images)
if not images:
return []
tensors: List[torch.Tensor] = []
sizes_wh: List[Tuple[int, int]] = []
for image in images:
tensor, _, size_wh = self._pil_to_tensor(image)
tensors.append(tensor)
sizes_wh.append(size_wh)
batch_tensor = torch.stack(tensors, dim=0)
refined = self.forward(batch_tensor)
if all(size == sizes_wh[0] for size in sizes_wh):
out_w, out_h = sizes_wh[0]
masks = self._postprocess_batch_same_size(
refined,
output_hw=(out_h, out_w),
)
return [masks[i] for i in range(masks.shape[0])]
masks: List[np.ndarray] = []
for i, (out_w, out_h) in enumerate(sizes_wh):
masks.append(
self._postprocess_one(
refined[i:i + 1],
output_hw=(out_h, out_w),
)
)
return masks
def inference(self, images: PILInput):
single_input = isinstance(images, Image.Image)
image_list = [images] if single_input else list(images)
if not image_list:
return []
masks = self.predict_masks(image_list)
foregrounds: List[Image.Image] = []
mask_images: List[Image.Image] = []
for image, mask in zip(image_list, masks):
original = ImageOps.exif_transpose(image).convert("RGBA")
mask_pil = Image.fromarray(mask, mode="L")
original.putalpha(mask_pil)
foregrounds.append(original)
mask_images.append(mask_pil)
if single_input:
return foregrounds[0], mask_images[0]
return foregrounds, mask_images
def _predict_video_batch(
self,
frames_rgb: Sequence[np.ndarray],
output_hw: Tuple[int, int],
) -> np.ndarray:
batch_tensor = self._rgb_batch_to_tensor(frames_rgb)
refined = self.forward(batch_tensor)
return self._postprocess_batch_same_size(
refined,
output_hw=output_hw,
)
@staticmethod
def _resolve_video_output_path(
video_path: Union[str, os.PathLike],
output_path: Optional[Union[str, os.PathLike]],
webm: bool,
) -> Path:
suffix = ".webm" if webm else ".mp4"
video_path = Path(video_path)
if output_path is None:
return video_path.with_name(
f"{video_path.stem}_foreground{suffix}"
)
output_path = Path(output_path)
if output_path.exists() and output_path.is_dir():
return output_path / f"foreground{suffix}"
if output_path.suffix:
return output_path.with_suffix(suffix)
return output_path / f"foreground{suffix}"
def segment_video(
self,
video_path: Union[str, os.PathLike],
output_path: Optional[Union[str, os.PathLike]] = None,
fps: Optional[float] = None,
batch: int = 1,
print_frames_processed: bool = True,
webm: bool = False,
rgb_value: Tuple[int, int, int] = (0, 255, 0),
max_frames: Optional[int] = None,
add_audio: bool = True,
) -> str:
if batch < 1:
raise ValueError("batch must be >= 1")
if len(rgb_value) != 3 or any(
not 0 <= int(value) <= 255
for value in rgb_value
):
raise ValueError("rgb_value must contain three values in [0,255]")
video_path = Path(video_path)
final_output = self._resolve_video_output_path(
video_path,
output_path,
webm,
)
final_output.parent.mkdir(parents=True, exist_ok=True)
cap = cv2.VideoCapture(str(video_path))
if not cap.isOpened():
raise IOError(f"Cannot open video: {video_path}")
source_fps = float(cap.get(cv2.CAP_PROP_FPS))
if not math.isfinite(source_fps) or source_fps <= 0:
source_fps = 30.0
if fps in (None, 0):
output_fps = source_fps
else:
output_fps = float(fps)
if not math.isfinite(output_fps) or output_fps <= 0:
cap.release()
raise ValueError("fps must be > 0, None, or 0")
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if width <= 0 or height <= 0:
cap.release()
raise ValueError("Could not determine input video dimensions")
if max_frames is not None:
max_frames = int(max_frames)
if max_frames < 0:
cap.release()
raise ValueError("max_frames must be >= 0 or None")
if add_audio:
raw_output = final_output.with_name(
f"{final_output.stem}.video_only{final_output.suffix}"
)
else:
raw_output = final_output
if webm:
writer = _RGBAWebMWriter(
str(raw_output),
width=width,
height=height,
fps=output_fps,
)
else:
writer = _MP4Writer(
str(raw_output),
width=width,
height=height,
fps=output_fps,
)
frame_batch: List[np.ndarray] = []
repeat_batch: List[int] = []
source_frames_read = 0
output_frames_written = 0
if total_frames > 0:
expected_source_frames = total_frames
if max_frames is not None:
expected_source_frames = min(
expected_source_frames,
max_frames,
)
else:
expected_source_frames = max_frames
def flush_batch():
nonlocal frame_batch
nonlocal repeat_batch
nonlocal output_frames_written
if not frame_batch:
return
masks = self._predict_video_batch(
frame_batch,
output_hw=(height, width),
)
if webm:
for rgb, alpha, repeats in zip(
frame_batch,
masks,
repeat_batch,
):
rgba = np.dstack((rgb, alpha))
for _ in range(repeats):
writer.write(rgba)
output_frames_written += 1
else:
rgb_batch = np.stack(frame_batch, axis=0).astype(
np.float32
)
alpha_batch = (
masks.astype(np.float32)[..., None] / 255.0
)
background = np.asarray(
rgb_value,
dtype=np.float32,
).reshape(1, 1, 1, 3)
composite_batch = (
rgb_batch * alpha_batch
+ background * (1.0 - alpha_batch)
).round().clip(0, 255).astype(np.uint8)
for frame_rgb, repeats in zip(
composite_batch,
repeat_batch,
):
for _ in range(repeats):
writer.write(frame_rgb)
output_frames_written += 1
frame_batch = []
repeat_batch = []
try:
while True:
if (
max_frames is not None
and source_frames_read >= max_frames
):
break
ret, frame_bgr = cap.read()
if not ret:
break
source_index = source_frames_read
source_frames_read += 1
output_before = math.floor(
source_index * output_fps / source_fps
)
output_after = math.floor(
(source_index + 1) * output_fps / source_fps
)
repeats = output_after - output_before
if repeats > 0:
frame_rgb = cv2.cvtColor(
frame_bgr,
cv2.COLOR_BGR2RGB,
)
frame_batch.append(frame_rgb)
repeat_batch.append(repeats)
if len(frame_batch) >= batch:
flush_batch()
if print_frames_processed:
if (
expected_source_frames is None
or expected_source_frames <= 0
):
total_text = "?"
else:
total_text = str(expected_source_frames)
print(
f"Processed {source_frames_read}/{total_text} "
f"source frames; wrote {output_frames_written} "
f"output frames",
end="\r",
flush=True,
)
flush_batch()
finally:
cap.release()
writer.close()
if print_frames_processed:
print()
if not add_audio:
return str(final_output)
audio_added = add_audio_to_video(
video_without_audio_path=str(raw_output),
original_video_path=str(video_path),
output_path=str(final_output),
)
if audio_added:
try:
raw_output.unlink()
except OSError:
pass
return str(final_output)
if raw_output != final_output:
raw_output.replace(final_output)
return str(final_output)
class _MP4Writer:
def __init__(
self,
path: str,
width: int,
height: int,
fps: float,
):
self.writer = cv2.VideoWriter(
path,
cv2.VideoWriter_fourcc(*"mp4v"),
fps,
(width, height),
)
if not self.writer.isOpened():
raise IOError(f"Could not open MP4 writer: {path}")
def write(self, frame_rgb: np.ndarray):
if frame_rgb.ndim != 3 or frame_rgb.shape[2] != 3:
raise ValueError(
f"Expected RGB [H,W,3], got {frame_rgb.shape}"
)
self.writer.write(
cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2BGR)
)
def close(self):
self.writer.release()
class _RGBAWebMWriter:
def __init__(
self,
path: str,
width: int,
height: int,
fps: float,
):
command = [
"ffmpeg",
"-y",
"-loglevel",
"error",
"-f",
"rawvideo",
"-pix_fmt",
"rgba",
"-s:v",
f"{width}x{height}",
"-r",
str(fps),
"-i",
"-",
"-an",
"-c:v",
"libvpx-vp9",
"-pix_fmt",
"yuva420p",
"-auto-alt-ref",
"0",
path,
]
self.process = subprocess.Popen(
command,
stdin=subprocess.PIPE,
)
def write(self, frame_rgba: np.ndarray):
if frame_rgba.ndim != 3 or frame_rgba.shape[2] != 4:
raise ValueError(
f"Expected RGBA [H,W,4], got {frame_rgba.shape}"
)
if self.process.stdin is None:
raise RuntimeError("ffmpeg stdin is closed")
frame_rgba = np.ascontiguousarray(
frame_rgba,
dtype=np.uint8,
)
self.process.stdin.write(frame_rgba.tobytes())
def close(self):
if self.process.stdin is not None:
self.process.stdin.close()
return_code = self.process.wait()
if return_code != 0:
raise subprocess.CalledProcessError(
return_code,
self.process.args,
)
def add_audio_to_video(
video_without_audio_path: str,
original_video_path: str,
output_path: str,
) -> bool:
probe_command = [
"ffprobe",
"-v",
"error",
"-select_streams",
"a:0",
"-show_entries",
"stream=index",
"-of",
"csv=p=0",
original_video_path,
]
result = subprocess.run(
probe_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False,
)
if not result.stdout.strip():
return False
output_suffix = Path(output_path).suffix.lower()
audio_codec = "libopus" if output_suffix == ".webm" else "aac"
command = [
"ffmpeg",
"-y",
"-loglevel",
"error",
"-i",
video_without_audio_path,
"-i",
original_video_path,
"-map",
"0:v:0",
"-map",
"1:a:0",
"-c:v",
"copy",
"-c:a",
audio_codec,
"-shortest",
output_path,
]
subprocess.run(command, check=True)
return True
|