addinng file
Browse files- transparent_background/InSPyReNet.py +152 -0
- transparent_background/Remover.py +419 -0
- transparent_background/__init__.py +2 -0
- transparent_background/backbones/SwinTransformer.py +652 -0
- transparent_background/config.yaml +21 -0
- transparent_background/gui.py +344 -0
- transparent_background/modules/attention_module.py +103 -0
- transparent_background/modules/context_module.py +54 -0
- transparent_background/modules/decoder_module.py +44 -0
- transparent_background/modules/layers.py +171 -0
- transparent_background/utils.py +261 -0
transparent_background/InSPyReNet.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
import torch.nn.functional as F
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
filepath = os.path.abspath(__file__)
|
9 |
+
repopath = os.path.split(filepath)[0]
|
10 |
+
sys.path.append(repopath)
|
11 |
+
|
12 |
+
from transparent_background.modules.layers import *
|
13 |
+
from transparent_background.modules.context_module import *
|
14 |
+
from transparent_background.modules.attention_module import *
|
15 |
+
from transparent_background.modules.decoder_module import *
|
16 |
+
|
17 |
+
from transparent_background.backbones.SwinTransformer import SwinB
|
18 |
+
|
19 |
+
class InSPyReNet(nn.Module):
|
20 |
+
def __init__(self, backbone, in_channels, depth=64, base_size=[384, 384], threshold=512, **kwargs):
|
21 |
+
super(InSPyReNet, self).__init__()
|
22 |
+
self.backbone = backbone
|
23 |
+
self.in_channels = in_channels
|
24 |
+
self.depth = depth
|
25 |
+
self.base_size = base_size
|
26 |
+
self.threshold = threshold
|
27 |
+
|
28 |
+
self.context1 = PAA_e(self.in_channels[0], self.depth, base_size=self.base_size, stage=0)
|
29 |
+
self.context2 = PAA_e(self.in_channels[1], self.depth, base_size=self.base_size, stage=1)
|
30 |
+
self.context3 = PAA_e(self.in_channels[2], self.depth, base_size=self.base_size, stage=2)
|
31 |
+
self.context4 = PAA_e(self.in_channels[3], self.depth, base_size=self.base_size, stage=3)
|
32 |
+
self.context5 = PAA_e(self.in_channels[4], self.depth, base_size=self.base_size, stage=4)
|
33 |
+
|
34 |
+
self.decoder = PAA_d(self.depth * 3, depth=self.depth, base_size=base_size, stage=2)
|
35 |
+
|
36 |
+
self.attention0 = SICA(self.depth , depth=self.depth, base_size=self.base_size, stage=0, lmap_in=True)
|
37 |
+
self.attention1 = SICA(self.depth * 2, depth=self.depth, base_size=self.base_size, stage=1, lmap_in=True)
|
38 |
+
self.attention2 = SICA(self.depth * 2, depth=self.depth, base_size=self.base_size, stage=2 )
|
39 |
+
|
40 |
+
self.ret = lambda x, target: F.interpolate(x, size=target.shape[-2:], mode='bilinear', align_corners=False)
|
41 |
+
self.res = lambda x, size: F.interpolate(x, size=size, mode='bilinear', align_corners=False)
|
42 |
+
self.des = lambda x, size: F.interpolate(x, size=size, mode='nearest')
|
43 |
+
|
44 |
+
self.image_pyramid = ImagePyramid(7, 1)
|
45 |
+
|
46 |
+
self.transition0 = Transition(17)
|
47 |
+
self.transition1 = Transition(9)
|
48 |
+
self.transition2 = Transition(5)
|
49 |
+
|
50 |
+
self.forward = self.forward_inference
|
51 |
+
|
52 |
+
def to(self, device):
|
53 |
+
self.image_pyramid.to(device)
|
54 |
+
self.transition0.to(device)
|
55 |
+
self.transition1.to(device)
|
56 |
+
self.transition2.to(device)
|
57 |
+
super(InSPyReNet, self).to(device)
|
58 |
+
return self
|
59 |
+
|
60 |
+
def cuda(self, idx=None):
|
61 |
+
if idx is None:
|
62 |
+
idx = torch.cuda.current_device()
|
63 |
+
|
64 |
+
self.to(device="cuda:{}".format(idx))
|
65 |
+
return self
|
66 |
+
|
67 |
+
def eval(self):
|
68 |
+
super(InSPyReNet, self).train(False)
|
69 |
+
self.forward = self.forward_inference
|
70 |
+
return self
|
71 |
+
|
72 |
+
def forward_inspyre(self, x):
|
73 |
+
B, _, H, W = x.shape
|
74 |
+
|
75 |
+
x1, x2, x3, x4, x5 = self.backbone(x)
|
76 |
+
|
77 |
+
x1 = self.context1(x1) #4
|
78 |
+
x2 = self.context2(x2) #4
|
79 |
+
x3 = self.context3(x3) #8
|
80 |
+
x4 = self.context4(x4) #16
|
81 |
+
x5 = self.context5(x5) #32
|
82 |
+
|
83 |
+
f3, d3 = self.decoder([x3, x4, x5]) #16
|
84 |
+
|
85 |
+
f3 = self.res(f3, (H // 4, W // 4 ))
|
86 |
+
f2, p2 = self.attention2(torch.cat([x2, f3], dim=1), d3.detach())
|
87 |
+
d2 = self.image_pyramid.reconstruct(d3.detach(), p2) #4
|
88 |
+
|
89 |
+
x1 = self.res(x1, (H // 2, W // 2))
|
90 |
+
f2 = self.res(f2, (H // 2, W // 2))
|
91 |
+
f1, p1 = self.attention1(torch.cat([x1, f2], dim=1), d2.detach(), p2.detach()) #2
|
92 |
+
d1 = self.image_pyramid.reconstruct(d2.detach(), p1) #2
|
93 |
+
|
94 |
+
f1 = self.res(f1, (H, W))
|
95 |
+
_, p0 = self.attention0(f1, d1.detach(), p1.detach()) #2
|
96 |
+
d0 = self.image_pyramid.reconstruct(d1.detach(), p0) #2
|
97 |
+
|
98 |
+
out = dict()
|
99 |
+
out['saliency'] = [d3, d2, d1, d0]
|
100 |
+
out['laplacian'] = [p2, p1, p0]
|
101 |
+
|
102 |
+
return out
|
103 |
+
|
104 |
+
def forward_inference(self, img, img_lr=None):
|
105 |
+
B, _, H, W = img.shape
|
106 |
+
|
107 |
+
if self.threshold is None:
|
108 |
+
out = self.forward_inspyre(img)
|
109 |
+
d3, d2, d1, d0 = out['saliency']
|
110 |
+
p2, p1, p0 = out['laplacian']
|
111 |
+
|
112 |
+
elif (H <= self.threshold or W <= self.threshold):
|
113 |
+
if img_lr is not None:
|
114 |
+
out = self.forward_inspyre(img_lr)
|
115 |
+
else:
|
116 |
+
out = self.forward_inspyre(img)
|
117 |
+
d3, d2, d1, d0 = out['saliency']
|
118 |
+
p2, p1, p0 = out['laplacian']
|
119 |
+
|
120 |
+
else:
|
121 |
+
# LR Saliency Pyramid
|
122 |
+
lr_out = self.forward_inspyre(img_lr)
|
123 |
+
lr_d3, lr_d2, lr_d1, lr_d0 = lr_out['saliency']
|
124 |
+
lr_p2, lr_p1, lr_p0 = lr_out['laplacian']
|
125 |
+
|
126 |
+
# HR Saliency Pyramid
|
127 |
+
hr_out = self.forward_inspyre(img)
|
128 |
+
hr_d3, hr_d2, hr_d1, hr_d0 = hr_out['saliency']
|
129 |
+
hr_p2, hr_p1, hr_p0 = hr_out['laplacian']
|
130 |
+
|
131 |
+
# Pyramid Blending
|
132 |
+
d3 = self.ret(lr_d0, hr_d3)
|
133 |
+
|
134 |
+
t2 = self.ret(self.transition2(d3), hr_p2)
|
135 |
+
p2 = t2 * hr_p2
|
136 |
+
d2 = self.image_pyramid.reconstruct(d3, p2)
|
137 |
+
|
138 |
+
t1 = self.ret(self.transition1(d2), hr_p1)
|
139 |
+
p1 = t1 * hr_p1
|
140 |
+
d1 = self.image_pyramid.reconstruct(d2, p1)
|
141 |
+
|
142 |
+
t0 = self.ret(self.transition0(d1), hr_p0)
|
143 |
+
p0 = t0 * hr_p0
|
144 |
+
d0 = self.image_pyramid.reconstruct(d1, p0)
|
145 |
+
|
146 |
+
pred = torch.sigmoid(d0)
|
147 |
+
pred = (pred - pred.min()) / (pred.max() - pred.min() + 1e-8)
|
148 |
+
|
149 |
+
return pred
|
150 |
+
|
151 |
+
def InSPyReNet_SwinB(depth, pretrained, base_size, **kwargs):
|
152 |
+
return InSPyReNet(SwinB(pretrained=pretrained), [128, 128, 256, 512, 1024], depth, base_size, **kwargs)
|
transparent_background/Remover.py
ADDED
@@ -0,0 +1,419 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import tqdm
|
4 |
+
import wget
|
5 |
+
import gdown
|
6 |
+
import torch
|
7 |
+
import shutil
|
8 |
+
import base64
|
9 |
+
import warnings
|
10 |
+
import importlib
|
11 |
+
|
12 |
+
import numpy as np
|
13 |
+
import torch.nn.functional as F
|
14 |
+
import torchvision.transforms as transforms
|
15 |
+
import albumentations as A
|
16 |
+
import albumentations.pytorch as AP
|
17 |
+
|
18 |
+
from PIL import Image
|
19 |
+
from io import BytesIO
|
20 |
+
from packaging import version
|
21 |
+
|
22 |
+
filepath = os.path.abspath(__file__)
|
23 |
+
repopath = os.path.split(filepath)[0]
|
24 |
+
sys.path.append(repopath)
|
25 |
+
|
26 |
+
from transparent_background.InSPyReNet import InSPyReNet_SwinB
|
27 |
+
from transparent_background.utils import *
|
28 |
+
|
29 |
+
class Remover:
|
30 |
+
def __init__(self, mode="base", jit=False, device=None, ckpt=None, resize='static'):
|
31 |
+
"""
|
32 |
+
Args:
|
33 |
+
mode (str): Choose among below options
|
34 |
+
base -> slow & large gpu memory required, high quality results
|
35 |
+
fast -> resize input into small size for fast computation
|
36 |
+
base-nightly -> nightly release for base mode
|
37 |
+
jit (bool): use TorchScript for fast computation
|
38 |
+
device (str, optional): specifying device for computation. find available GPU resource if not specified.
|
39 |
+
ckpt (str, optional): specifying model checkpoint. find downloaded checkpoint or try download if not specified.
|
40 |
+
fast (bool, optional, DEPRECATED): replaced by mode argument. use fast mode if True.
|
41 |
+
"""
|
42 |
+
cfg_path = os.environ.get('TRANSPARENT_BACKGROUND_FILE_PATH', os.path.abspath(os.path.expanduser('~')))
|
43 |
+
home_dir = os.path.join(cfg_path, ".transparent-background")
|
44 |
+
os.makedirs(home_dir, exist_ok=True)
|
45 |
+
|
46 |
+
if not os.path.isfile(os.path.join(home_dir, "config.yaml")):
|
47 |
+
shutil.copy(os.path.join(repopath, "config.yaml"), os.path.join(home_dir, "config.yaml"))
|
48 |
+
self.meta = load_config(os.path.join(home_dir, "config.yaml"))[mode]
|
49 |
+
|
50 |
+
if device is not None:
|
51 |
+
self.device = device
|
52 |
+
else:
|
53 |
+
self.device = "cpu"
|
54 |
+
if torch.cuda.is_available():
|
55 |
+
self.device = "cuda:0"
|
56 |
+
elif (
|
57 |
+
version.parse(torch.__version__) >= version.parse("1.13")
|
58 |
+
and torch.backends.mps.is_available()
|
59 |
+
):
|
60 |
+
self.device = "mps:0"
|
61 |
+
|
62 |
+
download = False
|
63 |
+
if ckpt is None:
|
64 |
+
ckpt_dir = home_dir
|
65 |
+
ckpt_name = self.meta.ckpt_name
|
66 |
+
|
67 |
+
if not os.path.isfile(os.path.join(ckpt_dir, ckpt_name)):
|
68 |
+
download = True
|
69 |
+
elif (
|
70 |
+
self.meta.md5
|
71 |
+
!= hashlib.md5(
|
72 |
+
open(os.path.join(ckpt_dir, ckpt_name), "rb").read()
|
73 |
+
).hexdigest()
|
74 |
+
):
|
75 |
+
if self.meta.md5 is not None:
|
76 |
+
download = True
|
77 |
+
|
78 |
+
if download:
|
79 |
+
if 'drive.google.com' in self.meta.url:
|
80 |
+
gdown.download(self.meta.url, os.path.join(ckpt_dir, ckpt_name), fuzzy=True, proxy=self.meta.http_proxy)
|
81 |
+
elif 'github.com' in self.meta.url:
|
82 |
+
wget.download(self.meta.url, os.path.join(ckpt_dir, ckpt_name))
|
83 |
+
else:
|
84 |
+
raise NotImplementedError('Please use valid URL')
|
85 |
+
else:
|
86 |
+
ckpt_dir, ckpt_name = os.path.split(os.path.abspath(ckpt))
|
87 |
+
|
88 |
+
self.model = InSPyReNet_SwinB(depth=64, pretrained=False, threshold=None, **self.meta)
|
89 |
+
self.model.eval()
|
90 |
+
self.model.load_state_dict(
|
91 |
+
torch.load(os.path.join(ckpt_dir, ckpt_name), map_location="cpu", weights_only=True),
|
92 |
+
strict=True,
|
93 |
+
)
|
94 |
+
self.model = self.model.to(self.device)
|
95 |
+
|
96 |
+
if jit:
|
97 |
+
ckpt_name = self.meta.ckpt_name.replace(
|
98 |
+
".pth", "_{}.pt".format(self.device)
|
99 |
+
)
|
100 |
+
try:
|
101 |
+
traced_model = torch.jit.load(
|
102 |
+
os.path.join(ckpt_dir, ckpt_name), map_location=self.device
|
103 |
+
)
|
104 |
+
del self.model
|
105 |
+
self.model = traced_model
|
106 |
+
except:
|
107 |
+
traced_model = torch.jit.trace(
|
108 |
+
self.model,
|
109 |
+
torch.rand(1, 3, *self.meta.base_size).to(self.device),
|
110 |
+
strict=True,
|
111 |
+
)
|
112 |
+
del self.model
|
113 |
+
self.model = traced_model
|
114 |
+
torch.jit.save(self.model, os.path.join(ckpt_dir, ckpt_name))
|
115 |
+
if resize != 'static':
|
116 |
+
warnings.warn('Resizing method for TorchScript mode only supports static resize. Fallback to static.')
|
117 |
+
resize = 'static'
|
118 |
+
|
119 |
+
resize_tf = None
|
120 |
+
resize_fn = None
|
121 |
+
if resize == 'static':
|
122 |
+
resize_tf = static_resize(self.meta.base_size)
|
123 |
+
resize_fn = A.Resize(*self.meta.base_size)
|
124 |
+
elif resize == 'dynamic':
|
125 |
+
if 'base' not in mode:
|
126 |
+
warnings.warn('Dynamic resizing only supports base and base-nightly mode. It will cause severe performance degradation with fast mode.')
|
127 |
+
resize_tf = dynamic_resize(L=1280)
|
128 |
+
resize_fn = dynamic_resize_a(L=1280)
|
129 |
+
else:
|
130 |
+
raise AttributeError(f'Unsupported resizing method {resize}')
|
131 |
+
|
132 |
+
self.transform = transforms.Compose(
|
133 |
+
[
|
134 |
+
resize_tf,
|
135 |
+
tonumpy(),
|
136 |
+
normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
137 |
+
totensor(),
|
138 |
+
]
|
139 |
+
)
|
140 |
+
|
141 |
+
self.cv2_transform = A.Compose(
|
142 |
+
[
|
143 |
+
resize_fn,
|
144 |
+
A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
145 |
+
AP.ToTensorV2(),
|
146 |
+
]
|
147 |
+
)
|
148 |
+
|
149 |
+
self.background = {'img': None, 'name': None, 'shape': None}
|
150 |
+
desc = "Mode={}, Device={}, Torchscript={}".format(
|
151 |
+
mode, self.device, "enabled" if jit else "disabled"
|
152 |
+
)
|
153 |
+
print("Settings -> {}".format(desc))
|
154 |
+
|
155 |
+
def process(self, img, type="rgba", threshold=None, reverse=False):
|
156 |
+
"""
|
157 |
+
Args:
|
158 |
+
img (PIL.Image or np.ndarray): input image as PIL.Image or np.ndarray type
|
159 |
+
type (str): output type option as below.
|
160 |
+
'rgba' will generate RGBA output regarding saliency score as an alpha map.
|
161 |
+
'green' will change the background with green screen.
|
162 |
+
'white' will change the background with white color.
|
163 |
+
'[255, 0, 0]' will change the background with color code [255, 0, 0].
|
164 |
+
'blur' will blur the background.
|
165 |
+
'overlay' will cover the salient object with translucent green color, and highlight the edges.
|
166 |
+
Another image file (e.g., 'samples/backgroud.png') will be used as a background, and the object will be overlapped on it.
|
167 |
+
threshold (float or str, optional): produce hard prediction w.r.t specified threshold value (0.0 ~ 1.0)
|
168 |
+
Returns:
|
169 |
+
PIL.Image: output image
|
170 |
+
|
171 |
+
"""
|
172 |
+
|
173 |
+
if isinstance(img, np.ndarray):
|
174 |
+
is_numpy = True
|
175 |
+
shape = img.shape[:2]
|
176 |
+
x = self.cv2_transform(image=img)["image"]
|
177 |
+
else:
|
178 |
+
is_numpy = False
|
179 |
+
shape = img.size[::-1]
|
180 |
+
x = self.transform(img)
|
181 |
+
|
182 |
+
x = x.unsqueeze(0)
|
183 |
+
x = x.to(self.device)
|
184 |
+
|
185 |
+
with torch.no_grad():
|
186 |
+
pred = self.model(x)
|
187 |
+
|
188 |
+
pred = F.interpolate(pred, shape, mode="bilinear", align_corners=True)
|
189 |
+
pred = pred.data.cpu()
|
190 |
+
pred = pred.numpy().squeeze()
|
191 |
+
|
192 |
+
if threshold is not None:
|
193 |
+
pred = (pred > float(threshold)).astype(np.float64)
|
194 |
+
if reverse:
|
195 |
+
pred = 1 - pred
|
196 |
+
|
197 |
+
img = np.array(img)
|
198 |
+
|
199 |
+
if type.startswith("["):
|
200 |
+
type = [int(i) for i in type[1:-1].split(",")]
|
201 |
+
|
202 |
+
if type == "map":
|
203 |
+
img = (np.stack([pred] * 3, axis=-1) * 255).astype(np.uint8)
|
204 |
+
|
205 |
+
elif type == "rgba":
|
206 |
+
if threshold is None:
|
207 |
+
# pymatting is imported here to avoid the overhead in other cases.
|
208 |
+
try:
|
209 |
+
from pymatting.foreground.estimate_foreground_ml_cupy import estimate_foreground_ml_cupy as estimate_foreground_ml
|
210 |
+
except ImportError:
|
211 |
+
try:
|
212 |
+
from pymatting.foreground.estimate_foreground_ml_pyopencl import estimate_foreground_ml_pyopencl as estimate_foreground_ml
|
213 |
+
except ImportError:
|
214 |
+
from pymatting import estimate_foreground_ml
|
215 |
+
img = estimate_foreground_ml(img / 255.0, pred)
|
216 |
+
img = 255 * np.clip(img, 0., 1.) + 0.5
|
217 |
+
img = img.astype(np.uint8)
|
218 |
+
|
219 |
+
r, g, b = cv2.split(img)
|
220 |
+
pred = (pred * 255).astype(np.uint8)
|
221 |
+
img = cv2.merge([r, g, b, pred])
|
222 |
+
|
223 |
+
elif type == "green":
|
224 |
+
bg = np.stack([np.ones_like(pred)] * 3, axis=-1) * [120, 255, 155]
|
225 |
+
img = img * pred[..., np.newaxis] + bg * (1 - pred[..., np.newaxis])
|
226 |
+
|
227 |
+
elif type == "white":
|
228 |
+
bg = np.stack([np.ones_like(pred)] * 3, axis=-1) * [255, 255, 255]
|
229 |
+
img = img * pred[..., np.newaxis] + bg * (1 - pred[..., np.newaxis])
|
230 |
+
|
231 |
+
elif len(type) == 3:
|
232 |
+
print(type)
|
233 |
+
bg = np.stack([np.ones_like(pred)] * 3, axis=-1) * type
|
234 |
+
img = img * pred[..., np.newaxis] + bg * (1 - pred[..., np.newaxis])
|
235 |
+
|
236 |
+
elif type == "blur":
|
237 |
+
img = img * pred[..., np.newaxis] + cv2.GaussianBlur(img, (0, 0), 15) * (
|
238 |
+
1 - pred[..., np.newaxis]
|
239 |
+
)
|
240 |
+
|
241 |
+
elif type == "overlay":
|
242 |
+
bg = (
|
243 |
+
np.stack([np.ones_like(pred)] * 3, axis=-1) * [120, 255, 155] + img
|
244 |
+
) // 2
|
245 |
+
img = bg * pred[..., np.newaxis] + img * (1 - pred[..., np.newaxis])
|
246 |
+
border = cv2.Canny(((pred > 0.5) * 255).astype(np.uint8), 50, 100)
|
247 |
+
img[border != 0] = [120, 255, 155]
|
248 |
+
|
249 |
+
elif type.lower().endswith(IMG_EXTS):
|
250 |
+
if self.background['name'] != type:
|
251 |
+
background_img = cv2.cvtColor(cv2.imread(type), cv2.COLOR_BGR2RGB)
|
252 |
+
background_img = cv2.resize(background_img, img.shape[:2][::-1])
|
253 |
+
|
254 |
+
self.background['img'] = background_img
|
255 |
+
self.background['shape'] = img.shape[:2][::-1]
|
256 |
+
self.background['name'] = type
|
257 |
+
|
258 |
+
elif self.background['shape'] != img.shape[:2][::-1]:
|
259 |
+
self.background['img'] = cv2.resize(self.background['img'], img.shape[:2][::-1])
|
260 |
+
self.background['shape'] = img.shape[:2][::-1]
|
261 |
+
|
262 |
+
img = img * pred[..., np.newaxis] + self.background['img'] * (
|
263 |
+
1 - pred[..., np.newaxis]
|
264 |
+
)
|
265 |
+
|
266 |
+
if is_numpy:
|
267 |
+
return img.astype(np.uint8)
|
268 |
+
else:
|
269 |
+
return Image.fromarray(img.astype(np.uint8))
|
270 |
+
|
271 |
+
def to_base64(image):
|
272 |
+
buffered = BytesIO()
|
273 |
+
image.save(buffered, format="JPEG")
|
274 |
+
base64_img = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
275 |
+
return base64_img
|
276 |
+
|
277 |
+
def entry_point(out_type, mode, device, ckpt, source, dest, jit, threshold, resize, save_format=None, reverse=False, flet_progress=None, flet_page=None, preview=None, preview_out=None, options=None):
|
278 |
+
warnings.filterwarnings("ignore")
|
279 |
+
|
280 |
+
remover = Remover(mode=mode, jit=jit, device=device, ckpt=ckpt, resize=resize)
|
281 |
+
|
282 |
+
if source.isnumeric() is True:
|
283 |
+
save_dir = None
|
284 |
+
_format = "Webcam"
|
285 |
+
if importlib.util.find_spec('pyvirtualcam') is not None:
|
286 |
+
try:
|
287 |
+
import pyvirtualcam
|
288 |
+
vcam = pyvirtualcam.Camera(width=640, height=480, fps=30)
|
289 |
+
except:
|
290 |
+
vcam = None
|
291 |
+
else:
|
292 |
+
raise ImportError("pyvirtualcam not found. Install with \"pip install transparent-background[webcam]\"")
|
293 |
+
|
294 |
+
elif os.path.isdir(source):
|
295 |
+
save_dir = os.path.join(os.getcwd(), source.split(os.sep)[-1])
|
296 |
+
_format = get_format(os.listdir(source))
|
297 |
+
|
298 |
+
elif os.path.isfile(source):
|
299 |
+
save_dir = os.getcwd()
|
300 |
+
_format = get_format([source])
|
301 |
+
|
302 |
+
else:
|
303 |
+
raise FileNotFoundError("File or directory {} is invalid.".format(source))
|
304 |
+
|
305 |
+
if out_type == "rgba" and _format == "Video":
|
306 |
+
raise AttributeError("type 'rgba' cannot be applied to video input.")
|
307 |
+
|
308 |
+
if dest is not None:
|
309 |
+
save_dir = dest
|
310 |
+
|
311 |
+
if save_dir is not None:
|
312 |
+
os.makedirs(save_dir, exist_ok=True)
|
313 |
+
|
314 |
+
loader = eval(_format + "Loader")(source)
|
315 |
+
frame_progress = tqdm.tqdm(
|
316 |
+
total=len(loader),
|
317 |
+
position=1 if (_format == "Video" and len(loader) > 1) else 0,
|
318 |
+
leave=False,
|
319 |
+
bar_format="{desc:<15}{percentage:3.0f}%|{bar:50}{r_bar}",
|
320 |
+
)
|
321 |
+
sample_progress = (
|
322 |
+
tqdm.tqdm(
|
323 |
+
total=len(loader),
|
324 |
+
desc="Total:",
|
325 |
+
position=0,
|
326 |
+
bar_format="{desc:<15}{percentage:3.0f}%|{bar:50}{r_bar}",
|
327 |
+
)
|
328 |
+
if (_format == "Video" and len(loader) > 1)
|
329 |
+
else None
|
330 |
+
)
|
331 |
+
if flet_progress is not None:
|
332 |
+
assert flet_page is not None
|
333 |
+
flet_progress.value = 0
|
334 |
+
flet_step = 1 / frame_progress.total
|
335 |
+
|
336 |
+
writer = None
|
337 |
+
|
338 |
+
for img, name in loader:
|
339 |
+
filename, ext = os.path.splitext(name)
|
340 |
+
ext = ext[1:]
|
341 |
+
ext = save_format if save_format is not None else ext
|
342 |
+
frame_progress.set_description("{}".format(name))
|
343 |
+
if out_type.lower().endswith(IMG_EXTS):
|
344 |
+
outname = "{}_{}".format(
|
345 |
+
filename,
|
346 |
+
os.path.splitext(os.path.split(out_type)[-1])[0],
|
347 |
+
)
|
348 |
+
else:
|
349 |
+
outname = "{}_{}".format(filename, out_type)
|
350 |
+
|
351 |
+
if reverse:
|
352 |
+
outname += '_reverse'
|
353 |
+
|
354 |
+
if _format == "Video" and writer is None:
|
355 |
+
writer = cv2.VideoWriter(
|
356 |
+
os.path.join(save_dir, f"{outname}.{ext}"),
|
357 |
+
cv2.VideoWriter_fourcc(*"mp4v"),
|
358 |
+
loader.fps,
|
359 |
+
img.size,
|
360 |
+
)
|
361 |
+
writer.set(cv2.VIDEOWRITER_PROP_QUALITY, 100)
|
362 |
+
frame_progress.refresh()
|
363 |
+
frame_progress.reset()
|
364 |
+
frame_progress.total = int(loader.cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
365 |
+
if sample_progress is not None:
|
366 |
+
sample_progress.update()
|
367 |
+
|
368 |
+
if flet_progress is not None:
|
369 |
+
assert flet_page is not None
|
370 |
+
flet_progress.value = 0
|
371 |
+
flet_step = 1 / frame_progress.total
|
372 |
+
flet_progress.update()
|
373 |
+
|
374 |
+
if _format == "Video" and img is None:
|
375 |
+
if writer is not None:
|
376 |
+
writer.release()
|
377 |
+
writer = None
|
378 |
+
continue
|
379 |
+
|
380 |
+
out = remover.process(img, type=out_type, threshold=threshold, reverse=reverse)
|
381 |
+
|
382 |
+
if _format == "Image":
|
383 |
+
if out_type == "rgba" and ext.lower() != 'png':
|
384 |
+
warnings.warn('Output format for rgba mode only supports png format. Fallback to png output.')
|
385 |
+
ext = 'png'
|
386 |
+
out.save(os.path.join(save_dir, f"{outname}.{ext}"))
|
387 |
+
elif _format == "Video" and writer is not None:
|
388 |
+
writer.write(cv2.cvtColor(np.array(out), cv2.COLOR_BGR2RGB))
|
389 |
+
elif _format == "Webcam":
|
390 |
+
if vcam is not None:
|
391 |
+
vcam.send(np.array(out))
|
392 |
+
vcam.sleep_until_next_frame()
|
393 |
+
else:
|
394 |
+
cv2.imshow(
|
395 |
+
"transparent-background", cv2.cvtColor(np.array(out), cv2.COLOR_BGR2RGB)
|
396 |
+
)
|
397 |
+
frame_progress.update()
|
398 |
+
if flet_progress is not None:
|
399 |
+
flet_progress.value += flet_step
|
400 |
+
flet_progress.update()
|
401 |
+
|
402 |
+
if out_type == 'rgba':
|
403 |
+
o = np.array(out).astype(np.float64)
|
404 |
+
o[:, :, :3] *= (o[:, :, -1:] / 255)
|
405 |
+
out = Image.fromarray(o[:, :, :3].astype(np.uint8))
|
406 |
+
|
407 |
+
preview.src_base64 = to_base64(img.resize((480, 300)).convert('RGB'))
|
408 |
+
preview_out.src_base64 = to_base64(out.resize((480, 300)).convert('RGB'))
|
409 |
+
preview.update()
|
410 |
+
preview_out.update()
|
411 |
+
|
412 |
+
if options is not None and options['abort']:
|
413 |
+
break
|
414 |
+
|
415 |
+
print("\nDone. Results are saved in {}".format(os.path.abspath(save_dir)))
|
416 |
+
|
417 |
+
def console():
|
418 |
+
args = parse_args()
|
419 |
+
entry_point(args.type, args.mode, args.device, args.ckpt, args.source, args.dest, args.jit, args.threshold, args.resize, args.format, args.reverse)
|
transparent_background/__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
from transparent_background.Remover import Remover, console
|
2 |
+
from transparent_background.gui import gui
|
transparent_background/backbones/SwinTransformer.py
ADDED
@@ -0,0 +1,652 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# --------------------------------------------------------
|
2 |
+
# Swin Transformer
|
3 |
+
# Copyright (c) 2021 Microsoft
|
4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
5 |
+
# Written by Ze Liu, Yutong Lin, Yixuan Wei
|
6 |
+
# --------------------------------------------------------
|
7 |
+
|
8 |
+
import torch
|
9 |
+
import torch.nn as nn
|
10 |
+
import torch.nn.functional as F
|
11 |
+
import torch.utils.checkpoint as checkpoint
|
12 |
+
import numpy as np
|
13 |
+
from timm.layers import DropPath, to_2tuple, trunc_normal_
|
14 |
+
|
15 |
+
class Mlp(nn.Module):
|
16 |
+
""" Multilayer perceptron."""
|
17 |
+
|
18 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
|
19 |
+
super().__init__()
|
20 |
+
out_features = out_features or in_features
|
21 |
+
hidden_features = hidden_features or in_features
|
22 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
23 |
+
self.act = act_layer()
|
24 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
25 |
+
self.drop = nn.Dropout(drop)
|
26 |
+
|
27 |
+
def forward(self, x):
|
28 |
+
x = self.fc1(x)
|
29 |
+
x = self.act(x)
|
30 |
+
x = self.drop(x)
|
31 |
+
x = self.fc2(x)
|
32 |
+
x = self.drop(x)
|
33 |
+
return x
|
34 |
+
|
35 |
+
|
36 |
+
def window_partition(x, window_size):
|
37 |
+
"""
|
38 |
+
Args:
|
39 |
+
x: (B, H, W, C)
|
40 |
+
window_size (int): window size
|
41 |
+
|
42 |
+
Returns:
|
43 |
+
windows: (num_windows*B, window_size, window_size, C)
|
44 |
+
"""
|
45 |
+
B, H, W, C = x.shape
|
46 |
+
x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
|
47 |
+
windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
|
48 |
+
return windows
|
49 |
+
|
50 |
+
|
51 |
+
def window_reverse(windows, window_size, H, W):
|
52 |
+
"""
|
53 |
+
Args:
|
54 |
+
windows: (num_windows*B, window_size, window_size, C)
|
55 |
+
window_size (int): Window size
|
56 |
+
H (int): Height of image
|
57 |
+
W (int): Width of image
|
58 |
+
|
59 |
+
Returns:
|
60 |
+
x: (B, H, W, C)
|
61 |
+
"""
|
62 |
+
B = int(windows.shape[0] / (H * W / window_size / window_size))
|
63 |
+
x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
|
64 |
+
x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
|
65 |
+
return x
|
66 |
+
|
67 |
+
|
68 |
+
class WindowAttention(nn.Module):
|
69 |
+
""" Window based multi-head self attention (W-MSA) module with relative position bias.
|
70 |
+
It supports both of shifted and non-shifted window.
|
71 |
+
|
72 |
+
Args:
|
73 |
+
dim (int): Number of input channels.
|
74 |
+
window_size (tuple[int]): The height and width of the window.
|
75 |
+
num_heads (int): Number of attention heads.
|
76 |
+
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
77 |
+
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
|
78 |
+
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
|
79 |
+
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
|
80 |
+
"""
|
81 |
+
|
82 |
+
def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
|
83 |
+
|
84 |
+
super().__init__()
|
85 |
+
self.dim = dim
|
86 |
+
self.window_size = window_size # Wh, Ww
|
87 |
+
self.num_heads = num_heads
|
88 |
+
head_dim = dim // num_heads
|
89 |
+
self.scale = qk_scale or head_dim ** -0.5
|
90 |
+
|
91 |
+
# define a parameter table of relative position bias
|
92 |
+
self.relative_position_bias_table = nn.Parameter(
|
93 |
+
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
|
94 |
+
|
95 |
+
# get pair-wise relative position index for each token inside the window
|
96 |
+
coords_h = torch.arange(self.window_size[0])
|
97 |
+
coords_w = torch.arange(self.window_size[1])
|
98 |
+
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
|
99 |
+
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
|
100 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
|
101 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
102 |
+
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
|
103 |
+
relative_coords[:, :, 1] += self.window_size[1] - 1
|
104 |
+
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
|
105 |
+
relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
106 |
+
self.register_buffer("relative_position_index", relative_position_index)
|
107 |
+
|
108 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
109 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
110 |
+
self.proj = nn.Linear(dim, dim)
|
111 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
112 |
+
|
113 |
+
trunc_normal_(self.relative_position_bias_table, std=.02)
|
114 |
+
self.softmax = nn.Softmax(dim=-1)
|
115 |
+
|
116 |
+
def forward(self, x, mask=None):
|
117 |
+
""" Forward function.
|
118 |
+
|
119 |
+
Args:
|
120 |
+
x: input features with shape of (num_windows*B, N, C)
|
121 |
+
mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
|
122 |
+
"""
|
123 |
+
B_, N, C = x.shape
|
124 |
+
qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
125 |
+
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
|
126 |
+
|
127 |
+
q = q * self.scale
|
128 |
+
attn = (q @ k.transpose(-2, -1))
|
129 |
+
|
130 |
+
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
|
131 |
+
self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
|
132 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
|
133 |
+
attn = attn + relative_position_bias.unsqueeze(0)
|
134 |
+
|
135 |
+
if mask is not None:
|
136 |
+
nW = mask.shape[0]
|
137 |
+
attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
|
138 |
+
attn = attn.view(-1, self.num_heads, N, N)
|
139 |
+
attn = self.softmax(attn)
|
140 |
+
else:
|
141 |
+
attn = self.softmax(attn)
|
142 |
+
|
143 |
+
attn = self.attn_drop(attn)
|
144 |
+
|
145 |
+
x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
|
146 |
+
x = self.proj(x)
|
147 |
+
x = self.proj_drop(x)
|
148 |
+
return x
|
149 |
+
|
150 |
+
|
151 |
+
class SwinTransformerBlock(nn.Module):
|
152 |
+
""" Swin Transformer Block.
|
153 |
+
|
154 |
+
Args:
|
155 |
+
dim (int): Number of input channels.
|
156 |
+
num_heads (int): Number of attention heads.
|
157 |
+
window_size (int): Window size.
|
158 |
+
shift_size (int): Shift size for SW-MSA.
|
159 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
160 |
+
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
161 |
+
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
162 |
+
drop (float, optional): Dropout rate. Default: 0.0
|
163 |
+
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
164 |
+
drop_path (float, optional): Stochastic depth rate. Default: 0.0
|
165 |
+
act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
|
166 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
167 |
+
"""
|
168 |
+
|
169 |
+
def __init__(self, dim, num_heads, window_size=7, shift_size=0,
|
170 |
+
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
|
171 |
+
act_layer=nn.GELU, norm_layer=nn.LayerNorm):
|
172 |
+
super().__init__()
|
173 |
+
self.dim = dim
|
174 |
+
self.num_heads = num_heads
|
175 |
+
self.window_size = window_size
|
176 |
+
self.shift_size = shift_size
|
177 |
+
self.mlp_ratio = mlp_ratio
|
178 |
+
assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
|
179 |
+
|
180 |
+
self.norm1 = norm_layer(dim)
|
181 |
+
self.attn = WindowAttention(
|
182 |
+
dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
|
183 |
+
qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
|
184 |
+
|
185 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
186 |
+
self.norm2 = norm_layer(dim)
|
187 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
188 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
189 |
+
|
190 |
+
self.H = None
|
191 |
+
self.W = None
|
192 |
+
|
193 |
+
def forward(self, x, mask_matrix):
|
194 |
+
""" Forward function.
|
195 |
+
|
196 |
+
Args:
|
197 |
+
x: Input feature, tensor size (B, H*W, C).
|
198 |
+
H, W: Spatial resolution of the input feature.
|
199 |
+
mask_matrix: Attention mask for cyclic shift.
|
200 |
+
"""
|
201 |
+
B, L, C = x.shape
|
202 |
+
H, W = self.H, self.W
|
203 |
+
assert L == H * W, "input feature has wrong size"
|
204 |
+
|
205 |
+
shortcut = x
|
206 |
+
x = self.norm1(x)
|
207 |
+
x = x.view(B, H, W, C)
|
208 |
+
|
209 |
+
# pad feature maps to multiples of window size
|
210 |
+
pad_l = pad_t = 0
|
211 |
+
pad_r = (self.window_size - W % self.window_size) % self.window_size
|
212 |
+
pad_b = (self.window_size - H % self.window_size) % self.window_size
|
213 |
+
x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
|
214 |
+
_, Hp, Wp, _ = x.shape
|
215 |
+
|
216 |
+
# cyclic shift
|
217 |
+
if self.shift_size > 0:
|
218 |
+
shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
|
219 |
+
attn_mask = mask_matrix
|
220 |
+
else:
|
221 |
+
shifted_x = x
|
222 |
+
attn_mask = None
|
223 |
+
|
224 |
+
# partition windows
|
225 |
+
x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
|
226 |
+
x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
|
227 |
+
|
228 |
+
# W-MSA/SW-MSA
|
229 |
+
attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
|
230 |
+
|
231 |
+
# merge windows
|
232 |
+
attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
|
233 |
+
shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
|
234 |
+
|
235 |
+
# reverse cyclic shift
|
236 |
+
if self.shift_size > 0:
|
237 |
+
x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
|
238 |
+
else:
|
239 |
+
x = shifted_x
|
240 |
+
|
241 |
+
if pad_r > 0 or pad_b > 0:
|
242 |
+
x = x[:, :H, :W, :].contiguous()
|
243 |
+
|
244 |
+
x = x.view(B, H * W, C)
|
245 |
+
|
246 |
+
# FFN
|
247 |
+
x = shortcut + self.drop_path(x)
|
248 |
+
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
249 |
+
|
250 |
+
return x
|
251 |
+
|
252 |
+
|
253 |
+
class PatchMerging(nn.Module):
|
254 |
+
""" Patch Merging Layer
|
255 |
+
|
256 |
+
Args:
|
257 |
+
dim (int): Number of input channels.
|
258 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
259 |
+
"""
|
260 |
+
def __init__(self, dim, norm_layer=nn.LayerNorm):
|
261 |
+
super().__init__()
|
262 |
+
self.dim = dim
|
263 |
+
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
|
264 |
+
self.norm = norm_layer(4 * dim)
|
265 |
+
|
266 |
+
def forward(self, x, H, W):
|
267 |
+
""" Forward function.
|
268 |
+
|
269 |
+
Args:
|
270 |
+
x: Input feature, tensor size (B, H*W, C).
|
271 |
+
H, W: Spatial resolution of the input feature.
|
272 |
+
"""
|
273 |
+
B, L, C = x.shape
|
274 |
+
assert L == H * W, "input feature has wrong size"
|
275 |
+
|
276 |
+
x = x.view(B, H, W, C)
|
277 |
+
|
278 |
+
# padding
|
279 |
+
pad_input = (H % 2 == 1) or (W % 2 == 1)
|
280 |
+
if pad_input:
|
281 |
+
x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
|
282 |
+
|
283 |
+
x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
|
284 |
+
x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
|
285 |
+
x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
|
286 |
+
x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
|
287 |
+
x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
|
288 |
+
x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
|
289 |
+
|
290 |
+
x = self.norm(x)
|
291 |
+
x = self.reduction(x)
|
292 |
+
|
293 |
+
return x
|
294 |
+
|
295 |
+
|
296 |
+
class BasicLayer(nn.Module):
|
297 |
+
""" A basic Swin Transformer layer for one stage.
|
298 |
+
|
299 |
+
Args:
|
300 |
+
dim (int): Number of feature channels
|
301 |
+
depth (int): Depths of this stage.
|
302 |
+
num_heads (int): Number of attention head.
|
303 |
+
window_size (int): Local window size. Default: 7.
|
304 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
|
305 |
+
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
306 |
+
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
307 |
+
drop (float, optional): Dropout rate. Default: 0.0
|
308 |
+
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
309 |
+
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
|
310 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
311 |
+
downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
|
312 |
+
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
|
313 |
+
"""
|
314 |
+
|
315 |
+
def __init__(self,
|
316 |
+
dim,
|
317 |
+
depth,
|
318 |
+
num_heads,
|
319 |
+
window_size=7,
|
320 |
+
mlp_ratio=4.,
|
321 |
+
qkv_bias=True,
|
322 |
+
qk_scale=None,
|
323 |
+
drop=0.,
|
324 |
+
attn_drop=0.,
|
325 |
+
drop_path=0.,
|
326 |
+
norm_layer=nn.LayerNorm,
|
327 |
+
downsample=None,
|
328 |
+
use_checkpoint=False):
|
329 |
+
super().__init__()
|
330 |
+
self.window_size = window_size
|
331 |
+
self.shift_size = window_size // 2
|
332 |
+
self.depth = depth
|
333 |
+
self.use_checkpoint = use_checkpoint
|
334 |
+
|
335 |
+
# build blocks
|
336 |
+
self.blocks = nn.ModuleList([
|
337 |
+
SwinTransformerBlock(
|
338 |
+
dim=dim,
|
339 |
+
num_heads=num_heads,
|
340 |
+
window_size=window_size,
|
341 |
+
shift_size=0 if (i % 2 == 0) else window_size // 2,
|
342 |
+
mlp_ratio=mlp_ratio,
|
343 |
+
qkv_bias=qkv_bias,
|
344 |
+
qk_scale=qk_scale,
|
345 |
+
drop=drop,
|
346 |
+
attn_drop=attn_drop,
|
347 |
+
drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
|
348 |
+
norm_layer=norm_layer)
|
349 |
+
for i in range(depth)])
|
350 |
+
|
351 |
+
# patch merging layer
|
352 |
+
if downsample is not None:
|
353 |
+
self.downsample = downsample(dim=dim, norm_layer=norm_layer)
|
354 |
+
else:
|
355 |
+
self.downsample = None
|
356 |
+
|
357 |
+
def forward(self, x, H, W):
|
358 |
+
""" Forward function.
|
359 |
+
|
360 |
+
Args:
|
361 |
+
x: Input feature, tensor size (B, H*W, C).
|
362 |
+
H, W: Spatial resolution of the input feature.
|
363 |
+
"""
|
364 |
+
|
365 |
+
# calculate attention mask for SW-MSA
|
366 |
+
Hp = int(np.ceil(H / self.window_size)) * self.window_size
|
367 |
+
Wp = int(np.ceil(W / self.window_size)) * self.window_size
|
368 |
+
img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
|
369 |
+
h_slices = (slice(0, -self.window_size),
|
370 |
+
slice(-self.window_size, -self.shift_size),
|
371 |
+
slice(-self.shift_size, None))
|
372 |
+
w_slices = (slice(0, -self.window_size),
|
373 |
+
slice(-self.window_size, -self.shift_size),
|
374 |
+
slice(-self.shift_size, None))
|
375 |
+
cnt = 0
|
376 |
+
for h in h_slices:
|
377 |
+
for w in w_slices:
|
378 |
+
img_mask[:, h, w, :] = cnt
|
379 |
+
cnt += 1
|
380 |
+
|
381 |
+
mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
|
382 |
+
mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
|
383 |
+
attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
|
384 |
+
attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
|
385 |
+
|
386 |
+
for blk in self.blocks:
|
387 |
+
blk.H, blk.W = H, W
|
388 |
+
if self.use_checkpoint:
|
389 |
+
x = checkpoint.checkpoint(blk, x, attn_mask)
|
390 |
+
else:
|
391 |
+
x = blk(x, attn_mask)
|
392 |
+
if self.downsample is not None:
|
393 |
+
x_down = self.downsample(x, H, W)
|
394 |
+
Wh, Ww = (H + 1) // 2, (W + 1) // 2
|
395 |
+
return x, H, W, x_down, Wh, Ww
|
396 |
+
else:
|
397 |
+
return x, H, W, x, H, W
|
398 |
+
|
399 |
+
|
400 |
+
class PatchEmbed(nn.Module):
|
401 |
+
""" Image to Patch Embedding
|
402 |
+
|
403 |
+
Args:
|
404 |
+
patch_size (int): Patch token size. Default: 4.
|
405 |
+
in_chans (int): Number of input image channels. Default: 3.
|
406 |
+
embed_dim (int): Number of linear projection output channels. Default: 96.
|
407 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: None
|
408 |
+
"""
|
409 |
+
|
410 |
+
def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
|
411 |
+
super().__init__()
|
412 |
+
patch_size = to_2tuple(patch_size)
|
413 |
+
self.patch_size = patch_size
|
414 |
+
|
415 |
+
self.in_chans = in_chans
|
416 |
+
self.embed_dim = embed_dim
|
417 |
+
|
418 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
|
419 |
+
if norm_layer is not None:
|
420 |
+
self.norm = norm_layer(embed_dim)
|
421 |
+
else:
|
422 |
+
self.norm = None
|
423 |
+
|
424 |
+
def forward(self, x):
|
425 |
+
"""Forward function."""
|
426 |
+
# padding
|
427 |
+
_, _, H, W = x.size()
|
428 |
+
if W % self.patch_size[1] != 0:
|
429 |
+
x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
|
430 |
+
if H % self.patch_size[0] != 0:
|
431 |
+
x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
|
432 |
+
|
433 |
+
x = self.proj(x) # B C Wh Ww
|
434 |
+
if self.norm is not None:
|
435 |
+
Wh, Ww = x.size(2), x.size(3)
|
436 |
+
x = x.flatten(2).transpose(1, 2)
|
437 |
+
x = self.norm(x)
|
438 |
+
x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
|
439 |
+
|
440 |
+
return x
|
441 |
+
|
442 |
+
|
443 |
+
class SwinTransformer(nn.Module):
|
444 |
+
""" Swin Transformer backbone.
|
445 |
+
A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
|
446 |
+
https://arxiv.org/pdf/2103.14030
|
447 |
+
|
448 |
+
Args:
|
449 |
+
pretrain_img_size (int): Input image size for training the pretrained model,
|
450 |
+
used in absolute postion embedding. Default 224.
|
451 |
+
patch_size (int | tuple(int)): Patch size. Default: 4.
|
452 |
+
in_chans (int): Number of input image channels. Default: 3.
|
453 |
+
embed_dim (int): Number of linear projection output channels. Default: 96.
|
454 |
+
depths (tuple[int]): Depths of each Swin Transformer stage.
|
455 |
+
num_heads (tuple[int]): Number of attention head of each stage.
|
456 |
+
window_size (int): Window size. Default: 7.
|
457 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
|
458 |
+
qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
|
459 |
+
qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
|
460 |
+
drop_rate (float): Dropout rate.
|
461 |
+
attn_drop_rate (float): Attention dropout rate. Default: 0.
|
462 |
+
drop_path_rate (float): Stochastic depth rate. Default: 0.2.
|
463 |
+
norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
|
464 |
+
ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
|
465 |
+
patch_norm (bool): If True, add normalization after patch embedding. Default: True.
|
466 |
+
out_indices (Sequence[int]): Output from which stages.
|
467 |
+
frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
|
468 |
+
-1 means not freezing any parameters.
|
469 |
+
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
|
470 |
+
"""
|
471 |
+
|
472 |
+
def __init__(self,
|
473 |
+
pretrain_img_size=224,
|
474 |
+
patch_size=4,
|
475 |
+
in_chans=3,
|
476 |
+
embed_dim=96,
|
477 |
+
depths=[2, 2, 6, 2],
|
478 |
+
num_heads=[3, 6, 12, 24],
|
479 |
+
window_size=7,
|
480 |
+
mlp_ratio=4.,
|
481 |
+
qkv_bias=True,
|
482 |
+
qk_scale=None,
|
483 |
+
drop_rate=0.,
|
484 |
+
attn_drop_rate=0.,
|
485 |
+
drop_path_rate=0.2,
|
486 |
+
norm_layer=nn.LayerNorm,
|
487 |
+
ape=False,
|
488 |
+
patch_norm=True,
|
489 |
+
out_indices=(0, 1, 2, 3),
|
490 |
+
frozen_stages=-1,
|
491 |
+
use_checkpoint=False):
|
492 |
+
super().__init__()
|
493 |
+
|
494 |
+
self.pretrain_img_size = pretrain_img_size
|
495 |
+
self.num_layers = len(depths)
|
496 |
+
self.embed_dim = embed_dim
|
497 |
+
self.ape = ape
|
498 |
+
self.patch_norm = patch_norm
|
499 |
+
self.out_indices = out_indices
|
500 |
+
self.frozen_stages = frozen_stages
|
501 |
+
|
502 |
+
# split image into non-overlapping patches
|
503 |
+
self.patch_embed = PatchEmbed(
|
504 |
+
patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
|
505 |
+
norm_layer=norm_layer if self.patch_norm else None)
|
506 |
+
|
507 |
+
# absolute position embedding
|
508 |
+
if self.ape:
|
509 |
+
pretrain_img_size = to_2tuple(pretrain_img_size)
|
510 |
+
patch_size = to_2tuple(patch_size)
|
511 |
+
patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
|
512 |
+
|
513 |
+
self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
|
514 |
+
trunc_normal_(self.absolute_pos_embed, std=.02)
|
515 |
+
|
516 |
+
self.pos_drop = nn.Dropout(p=drop_rate)
|
517 |
+
|
518 |
+
# stochastic depth
|
519 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
|
520 |
+
|
521 |
+
# build layers
|
522 |
+
self.layers = nn.ModuleList()
|
523 |
+
for i_layer in range(self.num_layers):
|
524 |
+
layer = BasicLayer(
|
525 |
+
dim=int(embed_dim * 2 ** i_layer),
|
526 |
+
depth=depths[i_layer],
|
527 |
+
num_heads=num_heads[i_layer],
|
528 |
+
window_size=window_size,
|
529 |
+
mlp_ratio=mlp_ratio,
|
530 |
+
qkv_bias=qkv_bias,
|
531 |
+
qk_scale=qk_scale,
|
532 |
+
drop=drop_rate,
|
533 |
+
attn_drop=attn_drop_rate,
|
534 |
+
drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
|
535 |
+
norm_layer=norm_layer,
|
536 |
+
downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
|
537 |
+
use_checkpoint=use_checkpoint)
|
538 |
+
self.layers.append(layer)
|
539 |
+
|
540 |
+
num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
|
541 |
+
self.num_features = num_features
|
542 |
+
|
543 |
+
# add a norm layer for each output
|
544 |
+
for i_layer in out_indices:
|
545 |
+
layer = norm_layer(num_features[i_layer])
|
546 |
+
layer_name = f'norm{i_layer}'
|
547 |
+
self.add_module(layer_name, layer)
|
548 |
+
|
549 |
+
self._freeze_stages()
|
550 |
+
|
551 |
+
def _freeze_stages(self):
|
552 |
+
if self.frozen_stages >= 0:
|
553 |
+
self.patch_embed.eval()
|
554 |
+
for param in self.patch_embed.parameters():
|
555 |
+
param.requires_grad = False
|
556 |
+
|
557 |
+
if self.frozen_stages >= 1 and self.ape:
|
558 |
+
self.absolute_pos_embed.requires_grad = False
|
559 |
+
|
560 |
+
if self.frozen_stages >= 2:
|
561 |
+
self.pos_drop.eval()
|
562 |
+
for i in range(0, self.frozen_stages - 1):
|
563 |
+
m = self.layers[i]
|
564 |
+
m.eval()
|
565 |
+
for param in m.parameters():
|
566 |
+
param.requires_grad = False
|
567 |
+
|
568 |
+
def init_weights(self, pretrained=None):
|
569 |
+
"""Initialize the weights in backbone.
|
570 |
+
|
571 |
+
Args:
|
572 |
+
pretrained (str, optional): Path to pre-trained weights.
|
573 |
+
Defaults to None.
|
574 |
+
"""
|
575 |
+
|
576 |
+
def _init_weights(m):
|
577 |
+
if isinstance(m, nn.Linear):
|
578 |
+
trunc_normal_(m.weight, std=.02)
|
579 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
580 |
+
nn.init.constant_(m.bias, 0)
|
581 |
+
elif isinstance(m, nn.LayerNorm):
|
582 |
+
nn.init.constant_(m.bias, 0)
|
583 |
+
nn.init.constant_(m.weight, 1.0)
|
584 |
+
|
585 |
+
if isinstance(pretrained, str):
|
586 |
+
self.apply(_init_weights)
|
587 |
+
logger = get_root_logger()
|
588 |
+
load_checkpoint(self, pretrained, strict=False, logger=logger)
|
589 |
+
elif pretrained is None:
|
590 |
+
self.apply(_init_weights)
|
591 |
+
else:
|
592 |
+
raise TypeError('pretrained must be a str or None')
|
593 |
+
|
594 |
+
def forward(self, x):
|
595 |
+
"""Forward function."""
|
596 |
+
x = self.patch_embed(x)
|
597 |
+
|
598 |
+
Wh, Ww = x.size(2), x.size(3)
|
599 |
+
if self.ape:
|
600 |
+
# interpolate the position embedding to the corresponding size
|
601 |
+
absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
|
602 |
+
x = (x + absolute_pos_embed) # B Wh*Ww C
|
603 |
+
|
604 |
+
outs = [x.contiguous()]
|
605 |
+
x = x.flatten(2).transpose(1, 2)
|
606 |
+
x = self.pos_drop(x)
|
607 |
+
for i in range(self.num_layers):
|
608 |
+
layer = self.layers[i]
|
609 |
+
x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
|
610 |
+
|
611 |
+
if i in self.out_indices:
|
612 |
+
norm_layer = getattr(self, f'norm{i}')
|
613 |
+
x_out = norm_layer(x_out)
|
614 |
+
|
615 |
+
out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
|
616 |
+
outs.append(out)
|
617 |
+
|
618 |
+
return tuple(outs)
|
619 |
+
|
620 |
+
def train(self, mode=True):
|
621 |
+
"""Convert the model into training mode while keep layers freezed."""
|
622 |
+
super(SwinTransformer, self).train(mode)
|
623 |
+
self._freeze_stages()
|
624 |
+
|
625 |
+
def SwinT(pretrained=True):
|
626 |
+
model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7)
|
627 |
+
if pretrained is True:
|
628 |
+
model.load_state_dict(torch.load('data/backbone_ckpt/swin_tiny_patch4_window7_224.pth', map_location='cpu')['model'], strict=False)
|
629 |
+
|
630 |
+
return model
|
631 |
+
|
632 |
+
def SwinS(pretrained=True):
|
633 |
+
model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7)
|
634 |
+
if pretrained is True:
|
635 |
+
model.load_state_dict(torch.load('data/backbone_ckpt/swin_small_patch4_window7_224.pth', map_location='cpu')['model'], strict=False)
|
636 |
+
|
637 |
+
return model
|
638 |
+
|
639 |
+
def SwinB(pretrained=True):
|
640 |
+
model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
|
641 |
+
if pretrained is True:
|
642 |
+
model.load_state_dict(torch.load('data/backbone_ckpt/swin_base_patch4_window12_384_22kto1k.pth', map_location='cpu')['model'], strict=False)
|
643 |
+
|
644 |
+
return model
|
645 |
+
|
646 |
+
def SwinL(pretrained=True):
|
647 |
+
model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)
|
648 |
+
if pretrained is True:
|
649 |
+
model.load_state_dict(torch.load('data/backbone_ckpt/swin_large_patch4_window12_384_22kto1k.pth', map_location='cpu')['model'], strict=False)
|
650 |
+
|
651 |
+
return model
|
652 |
+
|
transparent_background/config.yaml
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
base:
|
2 |
+
url: "https://github.com/plemeri/transparent-background/releases/download/1.2.12/ckpt_base.pth"
|
3 |
+
md5: "d692e3dd5fa1b9658949d452bebf1cda"
|
4 |
+
ckpt_name: "ckpt_base.pth"
|
5 |
+
http_proxy: NULL
|
6 |
+
base_size: [1024, 1024]
|
7 |
+
|
8 |
+
|
9 |
+
fast:
|
10 |
+
url: "https://github.com/plemeri/transparent-background/releases/download/1.2.12/ckpt_fast.pth"
|
11 |
+
md5: "9efdbfbcc49b79ef0f7891c83d2fd52f"
|
12 |
+
ckpt_name: "ckpt_fast.pth"
|
13 |
+
http_proxy: NULL
|
14 |
+
base_size: [384, 384]
|
15 |
+
|
16 |
+
base-nightly:
|
17 |
+
url: "https://github.com/plemeri/transparent-background/releases/download/1.2.12/ckpt_base_nightly.pth"
|
18 |
+
md5: NULL
|
19 |
+
ckpt_name: "ckpt_base_nightly.pth"
|
20 |
+
http_proxy: NULL
|
21 |
+
base_size: [1024, 1024]
|
transparent_background/gui.py
ADDED
@@ -0,0 +1,344 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import flet as ft
|
2 |
+
from flet import (
|
3 |
+
ElevatedButton,
|
4 |
+
FilePicker,
|
5 |
+
FilePickerResultEvent,
|
6 |
+
Page,
|
7 |
+
Row,
|
8 |
+
Text,
|
9 |
+
icons,
|
10 |
+
)
|
11 |
+
import os
|
12 |
+
import torch
|
13 |
+
import logging
|
14 |
+
|
15 |
+
from transparent_background.utils import *
|
16 |
+
from transparent_background.Remover import *
|
17 |
+
|
18 |
+
logging.basicConfig(level=logging.WARN)
|
19 |
+
logging.getLogger("flet_runtime").setLevel(logging.WARN)
|
20 |
+
|
21 |
+
options = {
|
22 |
+
'output_type':'rgba',
|
23 |
+
'mode':'base',
|
24 |
+
'device':get_backend(),
|
25 |
+
'r' : 0,
|
26 |
+
'g' : 0,
|
27 |
+
'b' : 0,
|
28 |
+
'color' : "[0, 0, 0]",
|
29 |
+
'ckpt':None,
|
30 |
+
'threshold':None,
|
31 |
+
'reverse': False,
|
32 |
+
'resize': 'static',
|
33 |
+
'format': None,
|
34 |
+
'source':None,
|
35 |
+
'dest':None,
|
36 |
+
'use_custom':False,
|
37 |
+
'jit':False,
|
38 |
+
'abort':False,
|
39 |
+
}
|
40 |
+
|
41 |
+
def is_float(str):
|
42 |
+
if str is None:
|
43 |
+
return False
|
44 |
+
try:
|
45 |
+
tmp = float(str)
|
46 |
+
return True
|
47 |
+
except ValueError:
|
48 |
+
return False
|
49 |
+
|
50 |
+
def main(page):
|
51 |
+
def theme_changed(e):
|
52 |
+
page.theme_mode = (
|
53 |
+
ft.ThemeMode.DARK
|
54 |
+
if page.theme_mode == ft.ThemeMode.LIGHT
|
55 |
+
else ft.ThemeMode.LIGHT
|
56 |
+
)
|
57 |
+
page.update()
|
58 |
+
|
59 |
+
def checkbox_changed(e):
|
60 |
+
options['jit'] = jit_check.value
|
61 |
+
options['reverse'] = reverse_check.value
|
62 |
+
page.update()
|
63 |
+
|
64 |
+
def dropdown_changed(e):
|
65 |
+
options['output_type'] = type_dropdown.value
|
66 |
+
options['mode'] = mode_dropdown.value
|
67 |
+
options['device'] = device_dropdown.value
|
68 |
+
options['resize'] = resize_dropdown.value
|
69 |
+
# options['format'] = format_dropdown.value
|
70 |
+
|
71 |
+
if options['output_type'] == 'custom' and not options['use_custom']:
|
72 |
+
page.insert(1, ft.Row([r_field, g_field, b_field]))
|
73 |
+
options['use_custom']=True
|
74 |
+
|
75 |
+
elif options['output_type'] != 'custom' and options['use_custom']:
|
76 |
+
options['use_custom']=False
|
77 |
+
page.remove_at(1)
|
78 |
+
|
79 |
+
output_text.value = 'Type: {}, Mode: {}, Device: {}, Threshold: {}, Resize: {}, Format: {}'.format(options['output_type'], options['mode'], options['device'], options['threshold'], options['resize'], options['format'])
|
80 |
+
page.update()
|
81 |
+
|
82 |
+
def color_changed(e):
|
83 |
+
options['r'] = int(r_field.value) if len(r_field.value) > 0 and r_field.value.isdigit() else 0
|
84 |
+
options['g'] = int(g_field.value) if len(g_field.value) > 0 and g_field.value.isdigit() else 0
|
85 |
+
options['b'] = int(b_field.value) if len(b_field.value) > 0 and b_field.value.isdigit() else 0
|
86 |
+
options['color'] = str([options['r'], options['g'], options['b']])
|
87 |
+
output_text.value = 'Type: {}, Mode: {}, Device: {}, Threshold: {}, Resize: {}, Format: {}'.format(options['output_type'], options['color'], options['device'], options['threshold'], options['resize'], options['format'])
|
88 |
+
page.update()
|
89 |
+
|
90 |
+
def threshold_changed(e):
|
91 |
+
options['threshold'] = float(threshold_field.value) if len(threshold_field.value) > 0 and is_float(threshold_field.value) else None
|
92 |
+
options['threshold'] = None if is_float(options['threshold']) and (options['threshold'] < 0 or options['threshold'] > 1) else options['threshold']
|
93 |
+
output_text.value = 'Type: {}, Mode: {}, Device: {}, Threshold: {}, Resize: {}, Format: {}'.format(options['output_type'], options['mode'], options['device'], options['threshold'], options['resize'], options['format'])
|
94 |
+
page.update()
|
95 |
+
|
96 |
+
def format_changed(e):
|
97 |
+
options['format'] = format_field.value if format_field.value.endswith(IMG_EXTS) or format_field.value.endswith(VID_EXTS) else None
|
98 |
+
output_text.value = 'Type: {}, Mode: {}, Device: {}, Threshold: {}, Resize: {}, Format: {}'.format(options['output_type'], options['mode'], options['device'], options['threshold'], options['resize'], options['format'])
|
99 |
+
page.update()
|
100 |
+
|
101 |
+
def pick_files_result(e: FilePickerResultEvent):
|
102 |
+
file_path.update()
|
103 |
+
options['source'] = e.files[0].path if e.files else 'Not Selected'
|
104 |
+
file_path.value = options['source']
|
105 |
+
file_path.update()
|
106 |
+
if options['dest'] is None:
|
107 |
+
options['dest'] = os.path.split(options['source'])[0]
|
108 |
+
dest_path.value = options['dest']
|
109 |
+
dest_path.update()
|
110 |
+
|
111 |
+
# Open directory dialog
|
112 |
+
def get_directory_result(e: FilePickerResultEvent):
|
113 |
+
options['source'] = e.path if e.path else 'Not Selected'
|
114 |
+
file_path.value = options['source']
|
115 |
+
file_path.update()
|
116 |
+
if options['dest'] is None:
|
117 |
+
options['dest'] = os.path.split(options['source'])[0]
|
118 |
+
dest_path.value = options['dest']
|
119 |
+
dest_path.update()
|
120 |
+
|
121 |
+
def get_dest_result(e: FilePickerResultEvent):
|
122 |
+
options['dest'] = e.path if e.path else 'Not Selected'
|
123 |
+
dest_path.value = options['dest']
|
124 |
+
dest_path.update()
|
125 |
+
|
126 |
+
def process(e):
|
127 |
+
output_type = options['output_type']
|
128 |
+
output_type = options['color'] if output_type == 'custom' else output_type
|
129 |
+
options['abort'] = False
|
130 |
+
entry_point(output_type, options['mode'], options['device'], options['ckpt'], options['source'], options['dest'], options['jit'], options['threshold'], options['resize'], options['format'], options['reverse'], progress_ring, page, preview, preview_out, options)
|
131 |
+
|
132 |
+
def click_abort(e):
|
133 |
+
options['abort'] = True
|
134 |
+
page.update()
|
135 |
+
|
136 |
+
page.window_width = 1000
|
137 |
+
page.window_height = 650
|
138 |
+
page.window_resizable = False
|
139 |
+
|
140 |
+
page.theme_mode = ft.ThemeMode.LIGHT
|
141 |
+
c = ft.Switch(label="Dark mode", on_change=theme_changed)
|
142 |
+
|
143 |
+
output_text = ft.Text(color=ft.colors.BLACK)
|
144 |
+
output_text.value = 'Type: {}, Mode: {}, Device: {}, Threshold: {}, Resize: {}, Format: {}'.format(options['output_type'], options['mode'], options['device'], options['threshold'], options['resize'], options['format'])
|
145 |
+
output_text_container = ft.Container(
|
146 |
+
content=output_text,
|
147 |
+
margin=10,
|
148 |
+
padding=10,
|
149 |
+
bgcolor=ft.colors.GREEN_100,
|
150 |
+
border_radius=10,
|
151 |
+
)
|
152 |
+
|
153 |
+
jit_check = ft.Checkbox(label="use torchscript", value=False, on_change=checkbox_changed)
|
154 |
+
reverse_check = ft.Checkbox(label="reverse", value=False, on_change=checkbox_changed)
|
155 |
+
|
156 |
+
type_dropdown = ft.Dropdown(
|
157 |
+
label='type',
|
158 |
+
width=200,
|
159 |
+
hint_text='output type',
|
160 |
+
on_change=dropdown_changed,
|
161 |
+
options=[
|
162 |
+
ft.dropdown.Option("rgba"),
|
163 |
+
ft.dropdown.Option("map"),
|
164 |
+
ft.dropdown.Option("green"),
|
165 |
+
ft.dropdown.Option("white"),
|
166 |
+
ft.dropdown.Option("blur"),
|
167 |
+
ft.dropdown.Option("overlay"),
|
168 |
+
ft.dropdown.Option("custom"),
|
169 |
+
],
|
170 |
+
)
|
171 |
+
type_dropdown.value = options['output_type']
|
172 |
+
|
173 |
+
resize_dropdown = ft.Dropdown(
|
174 |
+
label='resize',
|
175 |
+
width=200,
|
176 |
+
hint_text='resize method',
|
177 |
+
on_change=dropdown_changed,
|
178 |
+
options=[
|
179 |
+
ft.dropdown.Option("static"),
|
180 |
+
ft.dropdown.Option("dynamic"),
|
181 |
+
],
|
182 |
+
)
|
183 |
+
resize_dropdown.value = options['resize']
|
184 |
+
|
185 |
+
Remover() # init once
|
186 |
+
|
187 |
+
cfg_path = os.environ.get('TRANSPARENT_BACKGROUND_FILE_PATH', os.path.abspath(os.path.expanduser('~')))
|
188 |
+
home_dir = os.path.join(cfg_path, ".transparent-background")
|
189 |
+
configs = load_config(os.path.join(home_dir, "config.yaml"))
|
190 |
+
|
191 |
+
mode_dropdown = ft.Dropdown(
|
192 |
+
label='mode',
|
193 |
+
width=150,
|
194 |
+
hint_text='mode',
|
195 |
+
on_change=dropdown_changed,
|
196 |
+
options=[ft.dropdown.Option(key) for key in configs.keys()],
|
197 |
+
)
|
198 |
+
mode_dropdown.value = options['mode']
|
199 |
+
|
200 |
+
device_options = [ft.dropdown.Option("cpu")]
|
201 |
+
device_options += [ft.dropdown.Option("cuda:{}".format(i)) for i in range(torch.cuda.device_count())]
|
202 |
+
device_options += ['mps:0'] if torch.backends.mps.is_available() else []
|
203 |
+
|
204 |
+
device_dropdown = ft.Dropdown(
|
205 |
+
label='device',
|
206 |
+
width=150,
|
207 |
+
hint_text='device',
|
208 |
+
on_change=dropdown_changed,
|
209 |
+
options=device_options
|
210 |
+
)
|
211 |
+
device_dropdown.value=options['device']
|
212 |
+
|
213 |
+
r_field = ft.TextField(width=60, label='R', on_change=color_changed)
|
214 |
+
g_field = ft.TextField(width=60, label='G', on_change=color_changed)
|
215 |
+
b_field = ft.TextField(width=60, label='B', on_change=color_changed)
|
216 |
+
|
217 |
+
r_field.value=str(options['r'])
|
218 |
+
g_field.value=str(options['g'])
|
219 |
+
b_field.value=str(options['b'])
|
220 |
+
|
221 |
+
threshold_field = ft.TextField(width=150, label='threshold', on_change=threshold_changed)
|
222 |
+
threshold_field.value = None
|
223 |
+
|
224 |
+
format_field = ft.TextField(width=100, label='format', on_change=format_changed)
|
225 |
+
format_field.value = None
|
226 |
+
|
227 |
+
page.add(
|
228 |
+
ft.Row(
|
229 |
+
[
|
230 |
+
ft.Image(src='https://raw.githubusercontent.com/plemeri/transparent-background/main/figures/logo.png', width=100, height=100),
|
231 |
+
ft.Column(
|
232 |
+
[
|
233 |
+
ft.Row([c, jit_check, reverse_check, output_text_container]),
|
234 |
+
ft.Row([type_dropdown, mode_dropdown, device_dropdown, resize_dropdown, threshold_field, format_field])
|
235 |
+
]
|
236 |
+
)
|
237 |
+
]
|
238 |
+
)
|
239 |
+
)
|
240 |
+
|
241 |
+
pick_files_dialog = FilePicker(on_result=pick_files_result)
|
242 |
+
|
243 |
+
get_directory_dialog = FilePicker(on_result=get_directory_result)
|
244 |
+
file_path = Text(color=ft.colors.BLACK)
|
245 |
+
file_path.value = 'Input file or directory will be displayed'
|
246 |
+
file_path_container = ft.Container(
|
247 |
+
content=file_path,
|
248 |
+
margin=10,
|
249 |
+
padding=10,
|
250 |
+
bgcolor=ft.colors.AMBER,
|
251 |
+
border_radius=10,
|
252 |
+
)
|
253 |
+
|
254 |
+
get_dest_dialog = FilePicker(on_result=get_dest_result)
|
255 |
+
dest_path = Text(color=ft.colors.BLACK)
|
256 |
+
dest_path.value = 'Output file or directory will be displayed'
|
257 |
+
dest_path_container = ft.Container(
|
258 |
+
content=dest_path,
|
259 |
+
margin=10,
|
260 |
+
padding=10,
|
261 |
+
bgcolor=ft.colors.CYAN_200,
|
262 |
+
border_radius=10,
|
263 |
+
)
|
264 |
+
|
265 |
+
# hide all dialogs in overlay
|
266 |
+
page.overlay.extend([pick_files_dialog, get_directory_dialog, get_dest_dialog])
|
267 |
+
#progress_ring = ft.ProgressRing(width=16, height=16, stroke_width = 2)
|
268 |
+
progress_ring = ft.ProgressBar(width=200, color='amber', bgcolor='#eeeeee')
|
269 |
+
progress_ring.value = 0
|
270 |
+
|
271 |
+
preview = ft.Image(src=".preview.png", )
|
272 |
+
preview_out = ft.Image(src=".preview_out.png")
|
273 |
+
|
274 |
+
page.add(
|
275 |
+
Row(
|
276 |
+
[
|
277 |
+
ElevatedButton(
|
278 |
+
"Open File",
|
279 |
+
icon=icons.UPLOAD_FILE,
|
280 |
+
on_click=lambda _: pick_files_dialog.pick_files(
|
281 |
+
allow_multiple=False
|
282 |
+
),
|
283 |
+
),
|
284 |
+
ElevatedButton(
|
285 |
+
"Open Directory",
|
286 |
+
icon=icons.FOLDER_OPEN,
|
287 |
+
on_click=lambda _: get_directory_dialog.get_directory_path(),
|
288 |
+
disabled=page.web,
|
289 |
+
),
|
290 |
+
file_path_container,
|
291 |
+
]
|
292 |
+
),
|
293 |
+
Row(
|
294 |
+
[
|
295 |
+
ElevatedButton(
|
296 |
+
"Open Destination",
|
297 |
+
icon=icons.FOLDER_OPEN,
|
298 |
+
on_click=lambda _: get_dest_dialog.get_directory_path(),
|
299 |
+
disabled=page.web,
|
300 |
+
),
|
301 |
+
dest_path_container
|
302 |
+
]
|
303 |
+
),
|
304 |
+
Row(
|
305 |
+
[
|
306 |
+
ElevatedButton(
|
307 |
+
"Process",
|
308 |
+
icon=icons.SEND,
|
309 |
+
on_click=process,
|
310 |
+
disabled=page.web,
|
311 |
+
),
|
312 |
+
ElevatedButton(
|
313 |
+
"Stop",
|
314 |
+
icon=icons.STOP,
|
315 |
+
on_click=click_abort,
|
316 |
+
disabled=page.web,
|
317 |
+
),
|
318 |
+
progress_ring
|
319 |
+
]
|
320 |
+
),
|
321 |
+
)
|
322 |
+
|
323 |
+
page.add(
|
324 |
+
Row(
|
325 |
+
[
|
326 |
+
preview,
|
327 |
+
preview_out
|
328 |
+
]
|
329 |
+
)
|
330 |
+
)
|
331 |
+
|
332 |
+
|
333 |
+
def gui():
|
334 |
+
ft.app(target=main)
|
335 |
+
|
336 |
+
if os.path.isfile('.preview.png'):
|
337 |
+
os.remove('.preview.png')
|
338 |
+
|
339 |
+
if os.path.isfile('.preview_out.png'):
|
340 |
+
os.remove('.preview_out.png')
|
341 |
+
|
342 |
+
|
343 |
+
if __name__ == "__main__":
|
344 |
+
gui()
|
transparent_background/modules/attention_module.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
from torch.nn.parameter import Parameter
|
6 |
+
from operator import xor
|
7 |
+
from typing import Optional
|
8 |
+
|
9 |
+
from transparent_background.modules.layers import *
|
10 |
+
|
11 |
+
class SICA(nn.Module):
|
12 |
+
def __init__(self, in_channel, out_channel=1, depth=64, base_size=None, stage=None, lmap_in=False):
|
13 |
+
super(SICA, self).__init__()
|
14 |
+
self.in_channel = in_channel
|
15 |
+
self.depth = depth
|
16 |
+
self.lmap_in = lmap_in
|
17 |
+
if base_size is not None and stage is not None:
|
18 |
+
self.stage_size = (base_size[0] // (2 ** stage), base_size[1] // (2 ** stage))
|
19 |
+
else:
|
20 |
+
self.stage_size = None
|
21 |
+
|
22 |
+
self.conv_query = nn.Sequential(Conv2d(in_channel, depth, 3, relu=True),
|
23 |
+
Conv2d(depth, depth, 3, relu=True))
|
24 |
+
self.conv_key = nn.Sequential(Conv2d(in_channel, depth, 1, relu=True),
|
25 |
+
Conv2d(depth, depth, 1, relu=True))
|
26 |
+
self.conv_value = nn.Sequential(Conv2d(in_channel, depth, 1, relu=True),
|
27 |
+
Conv2d(depth, depth, 1, relu=True))
|
28 |
+
|
29 |
+
if self.lmap_in is True:
|
30 |
+
self.ctx = 5
|
31 |
+
else:
|
32 |
+
self.ctx = 3
|
33 |
+
|
34 |
+
self.conv_out1 = Conv2d(depth, depth, 3, relu=True)
|
35 |
+
self.conv_out2 = Conv2d(in_channel + depth, depth, 3, relu=True)
|
36 |
+
self.conv_out3 = Conv2d(depth, depth, 3, relu=True)
|
37 |
+
self.conv_out4 = Conv2d(depth, out_channel, 1)
|
38 |
+
|
39 |
+
self.threshold = Parameter(torch.tensor([0.5]))
|
40 |
+
|
41 |
+
if self.lmap_in is True:
|
42 |
+
self.lthreshold = Parameter(torch.tensor([0.5]))
|
43 |
+
|
44 |
+
def forward(self, x, smap, lmap: Optional[torch.Tensor]=None):
|
45 |
+
assert not xor(self.lmap_in is True, lmap is not None)
|
46 |
+
b, c, h, w = x.shape
|
47 |
+
|
48 |
+
# compute class probability
|
49 |
+
smap = F.interpolate(smap, size=x.shape[-2:], mode='bilinear', align_corners=False)
|
50 |
+
smap = torch.sigmoid(smap)
|
51 |
+
p = smap - self.threshold
|
52 |
+
|
53 |
+
fg = torch.clip(p, 0, 1) # foreground
|
54 |
+
bg = torch.clip(-p, 0, 1) # background
|
55 |
+
cg = self.threshold - torch.abs(p) # confusion area
|
56 |
+
|
57 |
+
if self.lmap_in is True and lmap is not None:
|
58 |
+
lmap = F.interpolate(lmap, size=x.shape[-2:], mode='bilinear', align_corners=False)
|
59 |
+
lmap = torch.sigmoid(lmap)
|
60 |
+
lp = lmap - self.lthreshold
|
61 |
+
fp = torch.clip(lp, 0, 1) # foreground
|
62 |
+
bp = torch.clip(-lp, 0, 1) # background
|
63 |
+
|
64 |
+
prob = [fg, bg, cg, fp, bp]
|
65 |
+
else:
|
66 |
+
prob = [fg, bg, cg]
|
67 |
+
|
68 |
+
prob = torch.cat(prob, dim=1)
|
69 |
+
|
70 |
+
# reshape feature & prob
|
71 |
+
if self.stage_size is not None:
|
72 |
+
shape = self.stage_size
|
73 |
+
shape_mul = self.stage_size[0] * self.stage_size[1]
|
74 |
+
else:
|
75 |
+
shape = (h, w)
|
76 |
+
shape_mul = h * w
|
77 |
+
|
78 |
+
f = F.interpolate(x, size=shape, mode='bilinear', align_corners=False).view(b, shape_mul, -1)
|
79 |
+
prob = F.interpolate(prob, size=shape, mode='bilinear', align_corners=False).view(b, self.ctx, shape_mul)
|
80 |
+
|
81 |
+
# compute context vector
|
82 |
+
context = torch.bmm(prob, f).permute(0, 2, 1).unsqueeze(3) # b, 3, c
|
83 |
+
|
84 |
+
# k q v compute
|
85 |
+
query = self.conv_query(x).view(b, self.depth, -1).permute(0, 2, 1)
|
86 |
+
key = self.conv_key(context).view(b, self.depth, -1)
|
87 |
+
value = self.conv_value(context).view(b, self.depth, -1).permute(0, 2, 1)
|
88 |
+
|
89 |
+
# compute similarity map
|
90 |
+
sim = torch.bmm(query, key) # b, hw, c x b, c, 2
|
91 |
+
sim = (self.depth ** -.5) * sim
|
92 |
+
sim = F.softmax(sim, dim=-1)
|
93 |
+
|
94 |
+
# compute refined feature
|
95 |
+
context = torch.bmm(sim, value).permute(0, 2, 1).contiguous().view(b, -1, h, w)
|
96 |
+
context = self.conv_out1(context)
|
97 |
+
|
98 |
+
x = torch.cat([x, context], dim=1)
|
99 |
+
x = self.conv_out2(x)
|
100 |
+
x = self.conv_out3(x)
|
101 |
+
out = self.conv_out4(x)
|
102 |
+
|
103 |
+
return x, out
|
transparent_background/modules/context_module.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
from .layers import *
|
6 |
+
|
7 |
+
class PAA_kernel(nn.Module):
|
8 |
+
def __init__(self, in_channel, out_channel, receptive_size, stage_size=None):
|
9 |
+
super(PAA_kernel, self).__init__()
|
10 |
+
self.conv0 = Conv2d(in_channel, out_channel, 1)
|
11 |
+
self.conv1 = Conv2d(out_channel, out_channel, kernel_size=(1, receptive_size))
|
12 |
+
self.conv2 = Conv2d(out_channel, out_channel, kernel_size=(receptive_size, 1))
|
13 |
+
self.conv3 = Conv2d(out_channel, out_channel, 3, dilation=receptive_size)
|
14 |
+
self.Hattn = SelfAttention(out_channel, 'h', stage_size[0] if stage_size is not None else None)
|
15 |
+
self.Wattn = SelfAttention(out_channel, 'w', stage_size[1] if stage_size is not None else None)
|
16 |
+
|
17 |
+
def forward(self, x):
|
18 |
+
x = self.conv0(x)
|
19 |
+
x = self.conv1(x)
|
20 |
+
x = self.conv2(x)
|
21 |
+
|
22 |
+
Hx = self.Hattn(x)
|
23 |
+
Wx = self.Wattn(x)
|
24 |
+
|
25 |
+
x = self.conv3(Hx + Wx)
|
26 |
+
return x
|
27 |
+
|
28 |
+
class PAA_e(nn.Module):
|
29 |
+
def __init__(self, in_channel, out_channel, base_size=None, stage=None):
|
30 |
+
super(PAA_e, self).__init__()
|
31 |
+
self.relu = nn.ReLU(True)
|
32 |
+
if base_size is not None and stage is not None:
|
33 |
+
self.stage_size = (base_size[0] // (2 ** stage), base_size[1] // (2 ** stage))
|
34 |
+
else:
|
35 |
+
self.stage_size = None
|
36 |
+
|
37 |
+
self.branch0 = Conv2d(in_channel, out_channel, 1)
|
38 |
+
self.branch1 = PAA_kernel(in_channel, out_channel, 3, self.stage_size)
|
39 |
+
self.branch2 = PAA_kernel(in_channel, out_channel, 5, self.stage_size)
|
40 |
+
self.branch3 = PAA_kernel(in_channel, out_channel, 7, self.stage_size)
|
41 |
+
|
42 |
+
self.conv_cat = Conv2d(4 * out_channel, out_channel, 3)
|
43 |
+
self.conv_res = Conv2d(in_channel, out_channel, 1)
|
44 |
+
|
45 |
+
def forward(self, x):
|
46 |
+
x0 = self.branch0(x)
|
47 |
+
x1 = self.branch1(x)
|
48 |
+
x2 = self.branch2(x)
|
49 |
+
x3 = self.branch3(x)
|
50 |
+
|
51 |
+
x_cat = self.conv_cat(torch.cat((x0, x1, x2, x3), 1))
|
52 |
+
x = self.relu(x_cat + self.conv_res(x))
|
53 |
+
|
54 |
+
return x
|
transparent_background/modules/decoder_module.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
from .layers import *
|
6 |
+
class PAA_d(nn.Module):
|
7 |
+
def __init__(self, in_channel, out_channel=1, depth=64, base_size=None, stage=None):
|
8 |
+
super(PAA_d, self).__init__()
|
9 |
+
self.conv1 = Conv2d(in_channel ,depth, 3)
|
10 |
+
self.conv2 = Conv2d(depth, depth, 3)
|
11 |
+
self.conv3 = Conv2d(depth, depth, 3)
|
12 |
+
self.conv4 = Conv2d(depth, depth, 3)
|
13 |
+
self.conv5 = Conv2d(depth, out_channel, 3, bn=False)
|
14 |
+
|
15 |
+
self.base_size = base_size
|
16 |
+
self.stage = stage
|
17 |
+
|
18 |
+
if base_size is not None and stage is not None:
|
19 |
+
self.stage_size = (base_size[0] // (2 ** stage), base_size[1] // (2 ** stage))
|
20 |
+
else:
|
21 |
+
self.stage_size = [None, None]
|
22 |
+
|
23 |
+
self.Hattn = SelfAttention(depth, 'h', self.stage_size[0])
|
24 |
+
self.Wattn = SelfAttention(depth, 'w', self.stage_size[1])
|
25 |
+
|
26 |
+
self.upsample = lambda img, size: F.interpolate(img, size=size, mode='bilinear', align_corners=True)
|
27 |
+
|
28 |
+
def forward(self, fs): #f3 f4 f5 -> f3 f2 f1
|
29 |
+
fx = fs[0]
|
30 |
+
for i in range(1, len(fs)):
|
31 |
+
fs[i] = self.upsample(fs[i], fx.shape[-2:])
|
32 |
+
fx = torch.cat(fs[::-1], dim=1)
|
33 |
+
|
34 |
+
fx = self.conv1(fx)
|
35 |
+
|
36 |
+
Hfx = self.Hattn(fx)
|
37 |
+
Wfx = self.Wattn(fx)
|
38 |
+
|
39 |
+
fx = self.conv2(Hfx + Wfx)
|
40 |
+
fx = self.conv3(fx)
|
41 |
+
fx = self.conv4(fx)
|
42 |
+
out = self.conv5(fx)
|
43 |
+
|
44 |
+
return fx, out
|
transparent_background/modules/layers.py
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
import cv2
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
from kornia.morphology import dilation, erosion
|
9 |
+
from torch.nn.parameter import Parameter
|
10 |
+
|
11 |
+
class ImagePyramid:
|
12 |
+
def __init__(self, ksize=7, sigma=1, channels=1):
|
13 |
+
self.ksize = ksize
|
14 |
+
self.sigma = sigma
|
15 |
+
self.channels = channels
|
16 |
+
|
17 |
+
k = cv2.getGaussianKernel(ksize, sigma)
|
18 |
+
k = np.outer(k, k)
|
19 |
+
k = torch.tensor(k).float()
|
20 |
+
self.kernel = k.repeat(channels, 1, 1, 1)
|
21 |
+
|
22 |
+
def to(self, device):
|
23 |
+
self.kernel = self.kernel.to(device)
|
24 |
+
return self
|
25 |
+
|
26 |
+
def cuda(self, idx=None):
|
27 |
+
if idx is None:
|
28 |
+
idx = torch.cuda.current_device()
|
29 |
+
|
30 |
+
self.to(device="cuda:{}".format(idx))
|
31 |
+
return self
|
32 |
+
|
33 |
+
def expand(self, x):
|
34 |
+
z = torch.zeros_like(x)
|
35 |
+
x = torch.cat([x, z, z, z], dim=1)
|
36 |
+
x = F.pixel_shuffle(x, 2)
|
37 |
+
x = F.pad(x, (self.ksize // 2, ) * 4, mode='reflect')
|
38 |
+
x = F.conv2d(x, self.kernel * 4, groups=self.channels)
|
39 |
+
return x
|
40 |
+
|
41 |
+
def reduce(self, x):
|
42 |
+
x = F.pad(x, (self.ksize // 2, ) * 4, mode='reflect')
|
43 |
+
x = F.conv2d(x, self.kernel, groups=self.channels)
|
44 |
+
x = x[:, :, ::2, ::2]
|
45 |
+
return x
|
46 |
+
|
47 |
+
def deconstruct(self, x):
|
48 |
+
reduced_x = self.reduce(x)
|
49 |
+
expanded_reduced_x = self.expand(reduced_x)
|
50 |
+
|
51 |
+
if x.shape != expanded_reduced_x.shape:
|
52 |
+
expanded_reduced_x = F.interpolate(expanded_reduced_x, x.shape[-2:])
|
53 |
+
|
54 |
+
laplacian_x = x - expanded_reduced_x
|
55 |
+
return reduced_x, laplacian_x
|
56 |
+
|
57 |
+
def reconstruct(self, x, laplacian_x):
|
58 |
+
expanded_x = self.expand(x)
|
59 |
+
if laplacian_x.shape != expanded_x:
|
60 |
+
laplacian_x = F.interpolate(laplacian_x, expanded_x.shape[-2:], mode='bilinear', align_corners=True)
|
61 |
+
return expanded_x + laplacian_x
|
62 |
+
|
63 |
+
class Transition:
|
64 |
+
def __init__(self, k=3):
|
65 |
+
self.kernel = torch.tensor(cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k))).float()
|
66 |
+
|
67 |
+
def to(self, device):
|
68 |
+
self.kernel = self.kernel.to(device)
|
69 |
+
return self
|
70 |
+
|
71 |
+
def cuda(self, idx=0):
|
72 |
+
self.to(device="cuda:{}".format(idx))
|
73 |
+
return self
|
74 |
+
|
75 |
+
def __call__(self, x):
|
76 |
+
x = torch.sigmoid(x)
|
77 |
+
dx = dilation(x, self.kernel)
|
78 |
+
ex = erosion(x, self.kernel)
|
79 |
+
|
80 |
+
return ((dx - ex) > .5).float()
|
81 |
+
|
82 |
+
class Conv2d(nn.Module):
|
83 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1, padding='same', bias=False, bn=True, relu=False):
|
84 |
+
super(Conv2d, self).__init__()
|
85 |
+
if '__iter__' not in dir(kernel_size):
|
86 |
+
kernel_size = (kernel_size, kernel_size)
|
87 |
+
if '__iter__' not in dir(stride):
|
88 |
+
stride = (stride, stride)
|
89 |
+
if '__iter__' not in dir(dilation):
|
90 |
+
dilation = (dilation, dilation)
|
91 |
+
|
92 |
+
if padding == 'same':
|
93 |
+
width_pad_size = kernel_size[0] + (kernel_size[0] - 1) * (dilation[0] - 1)
|
94 |
+
height_pad_size = kernel_size[1] + (kernel_size[1] - 1) * (dilation[1] - 1)
|
95 |
+
elif padding == 'valid':
|
96 |
+
width_pad_size = 0
|
97 |
+
height_pad_size = 0
|
98 |
+
else:
|
99 |
+
if '__iter__' in dir(padding):
|
100 |
+
width_pad_size = padding[0] * 2
|
101 |
+
height_pad_size = padding[1] * 2
|
102 |
+
else:
|
103 |
+
width_pad_size = padding * 2
|
104 |
+
height_pad_size = padding * 2
|
105 |
+
|
106 |
+
width_pad_size = width_pad_size // 2 + (width_pad_size % 2 - 1)
|
107 |
+
height_pad_size = height_pad_size // 2 + (height_pad_size % 2 - 1)
|
108 |
+
pad_size = (width_pad_size, height_pad_size)
|
109 |
+
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, pad_size, dilation, groups, bias=bias)
|
110 |
+
self.reset_parameters()
|
111 |
+
|
112 |
+
if bn is True:
|
113 |
+
self.bn = nn.BatchNorm2d(out_channels)
|
114 |
+
else:
|
115 |
+
self.bn = None
|
116 |
+
|
117 |
+
if relu is True:
|
118 |
+
self.relu = nn.ReLU(inplace=True)
|
119 |
+
else:
|
120 |
+
self.relu = None
|
121 |
+
|
122 |
+
def forward(self, x):
|
123 |
+
x = self.conv(x)
|
124 |
+
if self.bn is not None:
|
125 |
+
x = self.bn(x)
|
126 |
+
if self.relu is not None:
|
127 |
+
x = self.relu(x)
|
128 |
+
return x
|
129 |
+
|
130 |
+
def reset_parameters(self):
|
131 |
+
nn.init.kaiming_normal_(self.conv.weight)
|
132 |
+
|
133 |
+
|
134 |
+
class SelfAttention(nn.Module):
|
135 |
+
def __init__(self, in_channels, mode='hw', stage_size=None):
|
136 |
+
super(SelfAttention, self).__init__()
|
137 |
+
|
138 |
+
self.mode = mode
|
139 |
+
|
140 |
+
self.query_conv = Conv2d(in_channels, in_channels // 8, kernel_size=(1, 1))
|
141 |
+
self.key_conv = Conv2d(in_channels, in_channels // 8, kernel_size=(1, 1))
|
142 |
+
self.value_conv = Conv2d(in_channels, in_channels, kernel_size=(1, 1))
|
143 |
+
|
144 |
+
self.gamma = Parameter(torch.zeros(1))
|
145 |
+
self.softmax = nn.Softmax(dim=-1)
|
146 |
+
|
147 |
+
self.stage_size = stage_size
|
148 |
+
|
149 |
+
def forward(self, x):
|
150 |
+
batch_size, channel, height, width = x.size()
|
151 |
+
|
152 |
+
axis = 1
|
153 |
+
if 'h' in self.mode:
|
154 |
+
axis *= height
|
155 |
+
if 'w' in self.mode:
|
156 |
+
axis *= width
|
157 |
+
|
158 |
+
view = (batch_size, -1, axis)
|
159 |
+
|
160 |
+
projected_query = self.query_conv(x).view(*view).permute(0, 2, 1)
|
161 |
+
projected_key = self.key_conv(x).view(*view)
|
162 |
+
|
163 |
+
attention_map = torch.bmm(projected_query, projected_key)
|
164 |
+
attention = self.softmax(attention_map)
|
165 |
+
projected_value = self.value_conv(x).view(*view)
|
166 |
+
|
167 |
+
out = torch.bmm(projected_value, attention.permute(0, 2, 1))
|
168 |
+
out = out.view(batch_size, channel, height, width)
|
169 |
+
|
170 |
+
out = self.gamma * out + x
|
171 |
+
return out
|
transparent_background/utils.py
ADDED
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import cv2
|
4 |
+
import yaml
|
5 |
+
import torch
|
6 |
+
import hashlib
|
7 |
+
import argparse
|
8 |
+
|
9 |
+
import albumentations as A
|
10 |
+
from albumentations.core.transforms_interface import ImageOnlyTransform
|
11 |
+
|
12 |
+
import numpy as np
|
13 |
+
|
14 |
+
from PIL import Image
|
15 |
+
from threading import Thread
|
16 |
+
from easydict import EasyDict
|
17 |
+
|
18 |
+
VID_EXTS = ('mp4', 'avi', 'h264', 'mkv', 'mov', 'flv', 'wmv', 'webm', 'ts', 'm4v', 'vob', '3gp', '3g2', 'rm', 'rmvb', 'ogv', 'ogg', 'drc', 'gif', 'gifv', 'mng', 'avi', 'mov', 'qt', 'wmv', 'yuv', 'rm', 'rmvb', 'asf', 'amv', 'mp4', 'm4p', 'm4v', 'mpg', 'mp2', 'mpeg', 'mpe', 'mpv', 'mpg', 'mpeg', 'm2v', 'm4v', 'svi', '3gp', '3g2', 'mxf', 'roq', 'nsv', 'flv', 'f4v', 'f4p', 'f4a', 'f4b')
|
19 |
+
IMG_EXTS = ('jpg', 'jpeg', 'bmp', 'png', 'ppm', 'pgm', 'pbm', 'pnm', 'webp', 'sr', 'ras', 'tiff', 'tif', 'exr', 'hdr', 'pic', 'dib', 'jpe', 'jp2', 'j2k', 'jpf', 'jpx', 'jpm', 'mj2', 'jxr', 'hdp', 'wdp', 'cur', 'ico', 'ani', 'icns', 'bpg', 'jp2', 'j2k', 'jpf', 'jpx', 'jpm', 'mj2', 'jxr', 'hdp', 'wdp', 'cur', 'ico', 'ani', 'icns', 'bpg')
|
20 |
+
|
21 |
+
def parse_args():
|
22 |
+
parser = argparse.ArgumentParser()
|
23 |
+
parser.add_argument('--source', '-s', type=str, help="Path to the source. Single image, video, directory of images, directory of videos is supported.")
|
24 |
+
parser.add_argument('--dest', '-d', type=str, default=None, help="Path to destination. Results will be stored in current directory if not specified.")
|
25 |
+
parser.add_argument('--type', '-t', type=str, default='rgba', help="Specify output type. If not specified, output results will make the background transparent. Please refer to the documentation for other types.")
|
26 |
+
parser.add_argument('--reverse', '-R', action='store_true', help="Output will be reverse and foreground will be removed instead of background if specified.")
|
27 |
+
parser.add_argument('--format', '-f', type=str, default=None, help="Specify output format. If not specified, it will be saved with the format of input.")
|
28 |
+
parser.add_argument('--resize', '-r', type=str, default='static', help="Specify resizing method. If not specified, static resize will be used. Choose from (static|dynamic).")
|
29 |
+
parser.add_argument('--jit', '-j', action='store_true', help="Speed up inference speed by using torchscript, but decreases output quality.")
|
30 |
+
parser.add_argument('--device', '-D', type=str, default=None, help="Designate device. If not specified, it will find available device.")
|
31 |
+
parser.add_argument('--mode', '-m', type=str, default='base', help="choose between base and fast mode. Also, use base-nightly for nightly release checkpoint.")
|
32 |
+
parser.add_argument('--ckpt', '-c', type=str, default=None, help="Designate checkpoint. If not specified, it will download or load pre-downloaded default checkpoint.")
|
33 |
+
parser.add_argument('--threshold', '-th', type=str, default=None, help="Designate threshold. If specified, it will output hard prediction above threshold. If not specified, it will output soft prediction.")
|
34 |
+
return parser.parse_args()
|
35 |
+
|
36 |
+
def get_backend():
|
37 |
+
if torch.cuda.is_available():
|
38 |
+
return "cuda:0"
|
39 |
+
elif torch.backends.mps.is_available():
|
40 |
+
return "mps:0"
|
41 |
+
else:
|
42 |
+
return "cpu"
|
43 |
+
|
44 |
+
def load_config(config_dir, easy=True):
|
45 |
+
cfg = yaml.load(open(config_dir), yaml.FullLoader)
|
46 |
+
if easy is True:
|
47 |
+
cfg = EasyDict(cfg)
|
48 |
+
return cfg
|
49 |
+
|
50 |
+
def get_format(source):
|
51 |
+
img_count = len([i for i in source if i.lower().endswith(IMG_EXTS)])
|
52 |
+
vid_count = len([i for i in source if i.lower().endswith(VID_EXTS)])
|
53 |
+
|
54 |
+
if img_count * vid_count != 0:
|
55 |
+
return ''
|
56 |
+
elif img_count != 0:
|
57 |
+
return 'Image'
|
58 |
+
elif vid_count != 0:
|
59 |
+
return 'Video'
|
60 |
+
else:
|
61 |
+
return ''
|
62 |
+
|
63 |
+
def sort(x):
|
64 |
+
convert = lambda text: int(text) if text.isdigit() else text.lower()
|
65 |
+
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
|
66 |
+
return sorted(x, key=alphanum_key)
|
67 |
+
|
68 |
+
def download_and_unzip(filename, url, dest, unzip=True, **kwargs):
|
69 |
+
if not os.path.isdir(dest):
|
70 |
+
os.makedirs(dest, exist_ok=True)
|
71 |
+
|
72 |
+
if os.path.isfile(os.path.join(dest, filename)) is False:
|
73 |
+
os.system("wget -O {} {}".format(os.path.join(dest, filename), url))
|
74 |
+
elif 'md5' in kwargs.keys() and kwargs['md5'] != hashlib.md5(open(os.path.join(dest, filename), 'rb').read()).hexdigest():
|
75 |
+
os.system("wget -O {} {}".format(os.path.join(dest, filename), url))
|
76 |
+
|
77 |
+
if unzip:
|
78 |
+
os.system("unzip -o {} -d {}".format(os.path.join(dest, filename), dest))
|
79 |
+
os.system("rm {}".format(os.path.join(dest, filename)))
|
80 |
+
|
81 |
+
class dynamic_resize:
|
82 |
+
def __init__(self, L=1280):
|
83 |
+
self.L = L
|
84 |
+
|
85 |
+
def __call__(self, img):
|
86 |
+
size = list(img.size)
|
87 |
+
if (size[0] >= size[1]) and size[1] > self.L:
|
88 |
+
size[0] = size[0] / (size[1] / self.L)
|
89 |
+
size[1] = self.L
|
90 |
+
elif (size[1] > size[0]) and size[0] > self.L:
|
91 |
+
size[1] = size[1] / (size[0] / self.L)
|
92 |
+
size[0] = self.L
|
93 |
+
size = (int(round(size[0] / 32)) * 32, int(round(size[1] / 32)) * 32)
|
94 |
+
|
95 |
+
return img.resize(size, Image.BILINEAR)
|
96 |
+
|
97 |
+
class dynamic_resize_a(ImageOnlyTransform):
|
98 |
+
def __init__(self, L=1280, always_apply=False, p=1.0):
|
99 |
+
super(dynamic_resize_a, self).__init__(always_apply, p)
|
100 |
+
self.L = L
|
101 |
+
|
102 |
+
def apply(self, img, **params):
|
103 |
+
size = list(img.shape[:2])
|
104 |
+
if (size[0] >= size[1]) and size[1] > self.L:
|
105 |
+
size[0] = size[0] / (size[1] / self.L)
|
106 |
+
size[1] = self.L
|
107 |
+
elif (size[1] > size[0]) and size[0] > self.L:
|
108 |
+
size[1] = size[1] / (size[0] / self.L)
|
109 |
+
size[0] = self.L
|
110 |
+
size = (int(round(size[0] / 32)) * 32, int(round(size[1] / 32)) * 32)
|
111 |
+
|
112 |
+
return A.resize(img, height=size[0], width=size[1])
|
113 |
+
|
114 |
+
def get_transform_init_args_names(self):
|
115 |
+
return ("L",)
|
116 |
+
|
117 |
+
class static_resize:
|
118 |
+
def __init__(self, size=[1024, 1024]):
|
119 |
+
self.size = size
|
120 |
+
|
121 |
+
def __call__(self, img):
|
122 |
+
return img.resize(self.size, Image.BILINEAR)
|
123 |
+
|
124 |
+
class normalize:
|
125 |
+
def __init__(self, mean=None, std=None, div=255):
|
126 |
+
self.mean = mean if mean is not None else 0.0
|
127 |
+
self.std = std if std is not None else 1.0
|
128 |
+
self.div = div
|
129 |
+
|
130 |
+
def __call__(self, img):
|
131 |
+
img /= self.div
|
132 |
+
img -= self.mean
|
133 |
+
img /= self.std
|
134 |
+
|
135 |
+
return img
|
136 |
+
|
137 |
+
class tonumpy:
|
138 |
+
def __init__(self):
|
139 |
+
pass
|
140 |
+
|
141 |
+
def __call__(self, img):
|
142 |
+
img = np.array(img, dtype=np.float32)
|
143 |
+
return img
|
144 |
+
|
145 |
+
class totensor:
|
146 |
+
def __init__(self):
|
147 |
+
pass
|
148 |
+
|
149 |
+
def __call__(self, img):
|
150 |
+
img = img.transpose((2, 0, 1))
|
151 |
+
img = torch.from_numpy(img).float()
|
152 |
+
|
153 |
+
return img
|
154 |
+
|
155 |
+
class ImageLoader:
|
156 |
+
def __init__(self, root):
|
157 |
+
if os.path.isdir(root):
|
158 |
+
self.images = [os.path.join(root, f) for f in os.listdir(root) if f.lower().endswith(('.jpg', '.png', '.jpeg'))]
|
159 |
+
self.images = sort(self.images)
|
160 |
+
elif os.path.isfile(root):
|
161 |
+
self.images = [root]
|
162 |
+
self.size = len(self.images)
|
163 |
+
|
164 |
+
def __iter__(self):
|
165 |
+
self.index = 0
|
166 |
+
return self
|
167 |
+
|
168 |
+
def __next__(self):
|
169 |
+
if self.index == self.size:
|
170 |
+
raise StopIteration
|
171 |
+
|
172 |
+
img = Image.open(self.images[self.index]).convert('RGB')
|
173 |
+
name = os.path.split(self.images[self.index])[-1]
|
174 |
+
# name = os.path.splitext(name)[0]
|
175 |
+
|
176 |
+
self.index += 1
|
177 |
+
return img, name
|
178 |
+
|
179 |
+
def __len__(self):
|
180 |
+
return self.size
|
181 |
+
|
182 |
+
class VideoLoader:
|
183 |
+
def __init__(self, root):
|
184 |
+
if os.path.isdir(root):
|
185 |
+
self.videos = [os.path.join(root, f) for f in os.listdir(root) if f.lower().endswith(('.mp4', '.avi', 'mov'))]
|
186 |
+
elif os.path.isfile(root):
|
187 |
+
self.videos = [root]
|
188 |
+
self.size = len(self.videos)
|
189 |
+
|
190 |
+
def __iter__(self):
|
191 |
+
self.index = 0
|
192 |
+
self.cap = None
|
193 |
+
self.fps = None
|
194 |
+
return self
|
195 |
+
|
196 |
+
def __next__(self):
|
197 |
+
if self.index == self.size:
|
198 |
+
raise StopIteration
|
199 |
+
|
200 |
+
if self.cap is None:
|
201 |
+
self.cap = cv2.VideoCapture(self.videos[self.index])
|
202 |
+
self.fps = self.cap.get(cv2.CAP_PROP_FPS)
|
203 |
+
ret, frame = self.cap.read()
|
204 |
+
name = os.path.split(self.videos[self.index])[-1]
|
205 |
+
# name = os.path.splitext(name)[0]
|
206 |
+
if ret is False:
|
207 |
+
self.cap.release()
|
208 |
+
self.cap = None
|
209 |
+
img = None
|
210 |
+
self.index += 1
|
211 |
+
|
212 |
+
else:
|
213 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
214 |
+
img = Image.fromarray(frame).convert('RGB')
|
215 |
+
|
216 |
+
return img, name
|
217 |
+
|
218 |
+
def __len__(self):
|
219 |
+
return self.size
|
220 |
+
|
221 |
+
class WebcamLoader:
|
222 |
+
def __init__(self, ID):
|
223 |
+
self.ID = int(ID)
|
224 |
+
self.cap = cv2.VideoCapture(self.ID)
|
225 |
+
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
|
226 |
+
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
|
227 |
+
self.imgs = []
|
228 |
+
self.imgs.append(self.cap.read()[1])
|
229 |
+
self.thread = Thread(target=self.update, daemon=True)
|
230 |
+
self.thread.start()
|
231 |
+
|
232 |
+
def update(self):
|
233 |
+
while self.cap.isOpened():
|
234 |
+
ret, frame = self.cap.read()
|
235 |
+
if ret is True:
|
236 |
+
self.imgs.append(frame)
|
237 |
+
else:
|
238 |
+
break
|
239 |
+
|
240 |
+
def __iter__(self):
|
241 |
+
return self
|
242 |
+
|
243 |
+
def __next__(self):
|
244 |
+
if len(self.imgs) > 0:
|
245 |
+
frame = self.imgs[-1]
|
246 |
+
else:
|
247 |
+
frame = Image.fromarray(np.zeros((480, 640, 3)).astype(np.uint8))
|
248 |
+
|
249 |
+
if self.thread.is_alive() is False or cv2.waitKey(1) == ord('q'):
|
250 |
+
cv2.destroyAllWindows()
|
251 |
+
raise StopIteration
|
252 |
+
|
253 |
+
else:
|
254 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
255 |
+
frame = Image.fromarray(frame).convert('RGB')
|
256 |
+
|
257 |
+
del self.imgs[:-1]
|
258 |
+
return frame, None
|
259 |
+
|
260 |
+
def __len__(self):
|
261 |
+
return 0
|