Update vtoonify_model.py
Browse files- vtoonify_model.py +105 -77
vtoonify_model.py
CHANGED
@@ -8,7 +8,7 @@ from util import load_psp_standalone, get_video_crop_parameter, tensor2cv2
|
|
8 |
import torch
|
9 |
import torch.nn as nn
|
10 |
import numpy as np
|
11 |
-
import
|
12 |
import cv2
|
13 |
from model.vtoonify import VToonify
|
14 |
from model.bisenet.model import BiSeNet
|
@@ -51,13 +51,13 @@ class Model():
|
|
51 |
'illustration5-d': ['vtoonify_d_illustration/vtoonify_s086_d_c.pt', 86],
|
52 |
}
|
53 |
|
54 |
-
self.
|
55 |
self.parsingpredictor = self._create_parsing_model()
|
56 |
self.pspencoder = self._load_encoder()
|
57 |
self.transform = transforms.Compose([
|
58 |
transforms.ToTensor(),
|
59 |
-
transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5,0.5,0.5]),
|
60 |
-
|
61 |
|
62 |
self.vtoonify, self.exstyle = self._load_default_model()
|
63 |
self.color_transfer = False
|
@@ -65,10 +65,11 @@ class Model():
|
|
65 |
self.video_limit_cpu = 100
|
66 |
self.video_limit_gpu = 300
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
|
|
72 |
|
73 |
def _create_parsing_model(self):
|
74 |
parsingpredictor = BiSeNet(n_classes=19)
|
@@ -78,93 +79,118 @@ class Model():
|
|
78 |
return parsingpredictor
|
79 |
|
80 |
def _load_encoder(self) -> nn.Module:
|
81 |
-
style_encoder_path = huggingface_hub.hf_hub_download(MODEL_REPO,'models/encoder.pt')
|
82 |
return load_psp_standalone(style_encoder_path, self.device)
|
83 |
|
84 |
def _load_default_model(self) -> tuple[torch.Tensor, str]:
|
85 |
-
vtoonify = VToonify(backbone
|
86 |
vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,
|
87 |
'models/vtoonify_d_cartoon/vtoonify_s026_d0.5.pt'),
|
88 |
map_location=lambda storage, loc: storage)['g_ema'])
|
89 |
vtoonify.to(self.device)
|
90 |
-
tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO,'models/vtoonify_d_cartoon/exstyle_code.npy'), allow_pickle=True).item()
|
91 |
exstyle = torch.tensor(tmp[list(tmp.keys())[26]]).to(self.device)
|
92 |
with torch.no_grad():
|
93 |
exstyle = vtoonify.zplus2wplus(exstyle)
|
94 |
return vtoonify, exstyle
|
95 |
|
96 |
-
def load_model(self, style_type: str) -> tuple[torch.Tensor, str]:
|
97 |
-
if 'illustration' in style_type:
|
98 |
-
self.color_transfer = True
|
99 |
-
else:
|
100 |
-
self.color_transfer = False
|
101 |
-
if style_type not in self.style_types.keys():
|
102 |
-
return None, 'Oops, wrong Style Type. Please select a valid model.'
|
103 |
-
self.style_name = style_type
|
104 |
-
model_path, ind = self.style_types[style_type]
|
105 |
-
style_path = os.path.join('models',os.path.dirname(model_path),'exstyle_code.npy')
|
106 |
-
self.vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,'models/'+model_path),
|
107 |
-
map_location=lambda storage, loc: storage)['g_ema'])
|
108 |
-
tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, style_path), allow_pickle=True).item()
|
109 |
-
exstyle = torch.tensor(tmp[list(tmp.keys())[ind]]).to(self.device)
|
110 |
-
with torch.no_grad():
|
111 |
-
exstyle = self.vtoonify.zplus2wplus(exstyle)
|
112 |
-
return exstyle, 'Model of %s loaded.'%(style_type)
|
113 |
-
|
114 |
def detect_and_align(self, frame, top, bottom, left, right, return_para=False):
|
115 |
message = 'Error: no face detected! Please retry or change the photo.'
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
|
|
|
|
|
|
|
|
121 |
H, W = int(bottom-top), int(right-left)
|
122 |
# for HR image, we apply gaussian blur to it to avoid over-sharp stylization results
|
123 |
-
kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
|
124 |
if scale <= 0.75:
|
125 |
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
126 |
if scale <= 0.375:
|
127 |
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
128 |
frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
|
129 |
with torch.no_grad():
|
130 |
-
I = align_face(frame, self.
|
131 |
if I is not None:
|
132 |
I = self.transform(I).unsqueeze(dim=0).to(self.device)
|
133 |
instyle = self.pspencoder(I)
|
134 |
instyle = self.vtoonify.zplus2wplus(instyle)
|
135 |
-
message = 'Successfully rescale the frame to (%d, %d)'%(bottom-top, right-left)
|
136 |
else:
|
137 |
-
frame = np.zeros((256,256,3), np.uint8)
|
138 |
else:
|
139 |
-
frame = np.zeros((256,256,3), np.uint8)
|
140 |
if return_para:
|
141 |
return frame, instyle, message, w, h, top, bottom, left, right, scale
|
142 |
return frame, instyle, message
|
143 |
|
144 |
-
|
145 |
-
def
|
146 |
-
|
147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
148 |
|
149 |
-
|
|
|
|
|
|
|
|
|
150 |
frame_bgr = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2BGR)
|
151 |
-
|
152 |
return self.detect_and_align(frame_bgr, top, bottom, left, right)
|
153 |
|
154 |
-
def detect_and_align_video(self, video: str, top: int, bottom: int, left: int, right: int
|
155 |
-
) -> tuple[np.ndarray, torch.Tensor, str]:
|
156 |
if video is None:
|
157 |
-
return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load empty file.'
|
158 |
video_cap = cv2.VideoCapture(video)
|
159 |
if video_cap.get(7) == 0:
|
160 |
video_cap.release()
|
161 |
-
return np.zeros((256,256,3), np.uint8), torch.zeros(1,18,512).to(self.device), 'Error: fail to load the video.'
|
162 |
success, frame = video_cap.read()
|
163 |
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
164 |
video_cap.release()
|
165 |
return self.detect_and_align(frame, top, bottom, left, right)
|
166 |
-
|
167 |
-
def detect_and_align_full_video(self, video: str, top: int, bottom: int, left: int, right: int) -> tuple
|
168 |
message = 'Error: no face detected! Please retry or change the video.'
|
169 |
instyle = None
|
170 |
if video is None:
|
@@ -172,7 +198,7 @@ class Model():
|
|
172 |
video_cap = cv2.VideoCapture(video)
|
173 |
if video_cap.get(7) == 0:
|
174 |
video_cap.release()
|
175 |
-
return 'default.mp4', instyle, 'Error: fail to load the video.'
|
176 |
num = min(self.video_limit_gpu, int(video_cap.get(7)))
|
177 |
if self.device == 'cpu':
|
178 |
num = min(self.video_limit_cpu, num)
|
@@ -180,14 +206,14 @@ class Model():
|
|
180 |
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
181 |
frame, instyle, message, w, h, top, bottom, left, right, scale = self.detect_and_align(frame, top, bottom, left, right, True)
|
182 |
if instyle is None:
|
183 |
-
return 'default.mp4', instyle, message
|
184 |
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
185 |
videoWriter = cv2.VideoWriter('input.mp4', fourcc, video_cap.get(5), (int(right-left), int(bottom-top)))
|
186 |
videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
187 |
-
kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
|
188 |
for i in range(num-1):
|
189 |
success, frame = video_cap.read()
|
190 |
-
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
191 |
if scale <= 0.75:
|
192 |
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
193 |
if scale <= 0.375:
|
@@ -198,42 +224,40 @@ class Model():
|
|
198 |
videoWriter.release()
|
199 |
video_cap.release()
|
200 |
|
201 |
-
return 'input.mp4', instyle, 'Successfully rescale the video to (%d, %d)'%(bottom-top, right-left)
|
202 |
-
|
203 |
-
def image_toonify(self, aligned_face: np.ndarray, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple
|
204 |
-
#print(style_type + ' ' + self.style_name)
|
205 |
if instyle is None or aligned_face is None:
|
206 |
-
return np.zeros((256,256,3), np.uint8), 'Opps, something wrong with the input. Please go to Step 2 and Rescale Image/First Frame again.'
|
207 |
if self.style_name != style_type:
|
208 |
-
exstyle, _
|
209 |
if exstyle is None:
|
210 |
-
return np.zeros((256,256,3), np.uint8), 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
|
211 |
with torch.no_grad():
|
212 |
if self.color_transfer:
|
213 |
s_w = exstyle
|
214 |
else:
|
215 |
s_w = instyle.clone()
|
216 |
-
s_w[
|
217 |
|
218 |
x = self.transform(aligned_face).unsqueeze(dim=0).to(self.device)
|
219 |
x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
|
220 |
scale_factor=0.5, recompute_scale_factor=False).detach()
|
221 |
inputs = torch.cat((x, x_p/16.), dim=1)
|
222 |
-
y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s
|
223 |
y_tilde = torch.clamp(y_tilde, -1, 1)
|
224 |
-
print('*** Toonify %dx%d image with style of %s'%(y_tilde.shape[2], y_tilde.shape[3], style_type))
|
225 |
-
return ((y_tilde[0].cpu().numpy().transpose(1, 2, 0) + 1.0) * 127.5).astype(np.uint8), 'Successfully toonify the image with style of %s'%(self.style_name)
|
226 |
-
|
227 |
-
def
|
228 |
-
#print(style_type + ' ' + self.style_name)
|
229 |
if aligned_video is None:
|
230 |
-
return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
|
231 |
video_cap = cv2.VideoCapture(aligned_video)
|
232 |
if instyle is None or aligned_video is None or video_cap.get(7) == 0:
|
233 |
video_cap.release()
|
234 |
return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
|
235 |
if self.style_name != style_type:
|
236 |
-
exstyle, _
|
237 |
if exstyle is None:
|
238 |
return 'default.mp4', 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
|
239 |
num = min(self.video_limit_gpu, int(video_cap.get(7)))
|
@@ -247,18 +271,18 @@ class Model():
|
|
247 |
batch_frames = []
|
248 |
if video_cap.get(3) != 0:
|
249 |
if self.device == 'cpu':
|
250 |
-
batch_size = max(1, int(4 * 256* 256/ video_cap.get(3) / video_cap.get(4)))
|
251 |
else:
|
252 |
-
batch_size = min(max(1, int(4 * 400 * 360/ video_cap.get(3) / video_cap.get(4))), 4)
|
253 |
else:
|
254 |
batch_size = 1
|
255 |
-
print('*** Toonify using batch size of %d on %dx%d video of %d frames with style of %s'%(batch_size, int(video_cap.get(3)*4), int(video_cap.get(4)*4), num, style_type))
|
256 |
with torch.no_grad():
|
257 |
if self.color_transfer:
|
258 |
s_w = exstyle
|
259 |
else:
|
260 |
s_w = instyle.clone()
|
261 |
-
s_w[
|
262 |
for i in range(num):
|
263 |
success, frame = video_cap.read()
|
264 |
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
@@ -278,6 +302,10 @@ class Model():
|
|
278 |
|
279 |
videoWriter.release()
|
280 |
video_cap.release()
|
281 |
-
return 'output.mp4', 'Successfully toonify video of %d frames with style of %s'%(num, self.style_name)
|
282 |
-
|
283 |
|
|
|
|
|
|
|
|
|
|
|
|
8 |
import torch
|
9 |
import torch.nn as nn
|
10 |
import numpy as np
|
11 |
+
import insightface
|
12 |
import cv2
|
13 |
from model.vtoonify import VToonify
|
14 |
from model.bisenet.model import BiSeNet
|
|
|
51 |
'illustration5-d': ['vtoonify_d_illustration/vtoonify_s086_d_c.pt', 86],
|
52 |
}
|
53 |
|
54 |
+
self.face_detector = self._create_insightface_detector()
|
55 |
self.parsingpredictor = self._create_parsing_model()
|
56 |
self.pspencoder = self._load_encoder()
|
57 |
self.transform = transforms.Compose([
|
58 |
transforms.ToTensor(),
|
59 |
+
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
60 |
+
])
|
61 |
|
62 |
self.vtoonify, self.exstyle = self._load_default_model()
|
63 |
self.color_transfer = False
|
|
|
65 |
self.video_limit_cpu = 100
|
66 |
self.video_limit_gpu = 300
|
67 |
|
68 |
+
def _create_insightface_detector(self):
|
69 |
+
# Initialize InsightFace
|
70 |
+
app = insightface.app.FaceAnalysis()
|
71 |
+
app.prepare(ctx_id=0, det_size=(640, 640)) # ctx_id=-1 for CPU, 0 for GPU
|
72 |
+
return app
|
73 |
|
74 |
def _create_parsing_model(self):
|
75 |
parsingpredictor = BiSeNet(n_classes=19)
|
|
|
79 |
return parsingpredictor
|
80 |
|
81 |
def _load_encoder(self) -> nn.Module:
|
82 |
+
style_encoder_path = huggingface_hub.hf_hub_download(MODEL_REPO, 'models/encoder.pt')
|
83 |
return load_psp_standalone(style_encoder_path, self.device)
|
84 |
|
85 |
def _load_default_model(self) -> tuple[torch.Tensor, str]:
|
86 |
+
vtoonify = VToonify(backbone='dualstylegan')
|
87 |
vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,
|
88 |
'models/vtoonify_d_cartoon/vtoonify_s026_d0.5.pt'),
|
89 |
map_location=lambda storage, loc: storage)['g_ema'])
|
90 |
vtoonify.to(self.device)
|
91 |
+
tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/vtoonify_d_cartoon/exstyle_code.npy'), allow_pickle=True).item()
|
92 |
exstyle = torch.tensor(tmp[list(tmp.keys())[26]]).to(self.device)
|
93 |
with torch.no_grad():
|
94 |
exstyle = vtoonify.zplus2wplus(exstyle)
|
95 |
return vtoonify, exstyle
|
96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
def detect_and_align(self, frame, top, bottom, left, right, return_para=False):
|
98 |
message = 'Error: no face detected! Please retry or change the photo.'
|
99 |
+
# Use InsightFace for face detection
|
100 |
+
faces = self.face_detector.get(frame)
|
101 |
+
if len(faces) > 0:
|
102 |
+
face = faces[0]
|
103 |
+
bbox = face.bbox.astype(int)
|
104 |
+
x, y, w, h = bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]
|
105 |
+
top, bottom, left, right = y, y + h, x, x + w
|
106 |
+
scale = 1.0 # Adjust scale as needed
|
107 |
+
h, w = frame.shape[:2]
|
108 |
H, W = int(bottom-top), int(right-left)
|
109 |
# for HR image, we apply gaussian blur to it to avoid over-sharp stylization results
|
110 |
+
kernel_1d = np.array([[0.125], [0.375], [0.375], [0.125]])
|
111 |
if scale <= 0.75:
|
112 |
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
113 |
if scale <= 0.375:
|
114 |
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
115 |
frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
|
116 |
with torch.no_grad():
|
117 |
+
I = align_face(frame, self.face_detector)
|
118 |
if I is not None:
|
119 |
I = self.transform(I).unsqueeze(dim=0).to(self.device)
|
120 |
instyle = self.pspencoder(I)
|
121 |
instyle = self.vtoonify.zplus2wplus(instyle)
|
122 |
+
message = 'Successfully rescale the frame to (%d, %d)' % (bottom-top, right-left)
|
123 |
else:
|
124 |
+
frame = np.zeros((256, 256, 3), np.uint8)
|
125 |
else:
|
126 |
+
frame = np.zeros((256, 256, 3), np.uint8)
|
127 |
if return_para:
|
128 |
return frame, instyle, message, w, h, top, bottom, left, right, scale
|
129 |
return frame, instyle, message
|
130 |
|
131 |
+
# Other methods remain unchanged
|
132 |
+
def _create_parsing_model(self):
|
133 |
+
parsingpredictor = BiSeNet(n_classes=19)
|
134 |
+
parsingpredictor.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/faceparsing.pth'),
|
135 |
+
map_location=lambda storage, loc: storage))
|
136 |
+
parsingpredictor.to(self.device).eval()
|
137 |
+
return parsingpredictor
|
138 |
+
|
139 |
+
def _load_encoder(self) -> nn.Module:
|
140 |
+
style_encoder_path = huggingface_hub.hf_hub_download(MODEL_REPO, 'models/encoder.pt')
|
141 |
+
return load_psp_standalone(style_encoder_path, self.device)
|
142 |
+
|
143 |
+
def _load_default_model(self) -> tuple:
|
144 |
+
vtoonify = VToonify(backbone='dualstylegan')
|
145 |
+
vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,
|
146 |
+
'models/vtoonify_d_cartoon/vtoonify_s026_d0.5.pt'),
|
147 |
+
map_location=lambda storage, loc: storage)['g_ema'])
|
148 |
+
vtoonify.to(self.device)
|
149 |
+
tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/vtoonify_d_cartoon/exstyle_code.npy'), allow_pickle=True).item()
|
150 |
+
exstyle = torch.tensor(tmp[list(tmp.keys())[26]]).to(self.device)
|
151 |
+
with torch.no_grad():
|
152 |
+
exstyle = vtoonify.zplus2wplus(exstyle)
|
153 |
+
return vtoonify, exstyle
|
154 |
+
|
155 |
+
def load_model(self, style_type: str) -> tuple:
|
156 |
+
if 'illustration' in style_type:
|
157 |
+
self.color_transfer = True
|
158 |
+
else:
|
159 |
+
self.color_transfer = False
|
160 |
+
if style_type not in self.style_types.keys():
|
161 |
+
return None, 'Oops, wrong Style Type. Please select a valid model.'
|
162 |
+
self.style_name = style_type
|
163 |
+
model_path, ind = self.style_types[style_type]
|
164 |
+
style_path = os.path.join('models', os.path.dirname(model_path), 'exstyle_code.npy')
|
165 |
+
self.vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/' + model_path),
|
166 |
+
map_location=lambda storage, loc: storage)['g_ema'])
|
167 |
+
tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, style_path), allow_pickle=True).item()
|
168 |
+
exstyle = torch.tensor(tmp[list(tmp.keys())[ind]]).to(self.device)
|
169 |
+
with torch.no_grad():
|
170 |
+
exstyle = self.vtoonify.zplus2wplus(exstyle)
|
171 |
+
return exstyle, 'Model of %s loaded.' % (style_type)
|
172 |
|
173 |
+
def detect_and_align_image(self, frame_rgb: np.ndarray, top: int, bottom: int, left: int, right: int) -> tuple:
|
174 |
+
if frame_rgb is None:
|
175 |
+
return np.zeros((256, 256, 3), np.uint8), None, 'Error: fail to load the image.'
|
176 |
+
|
177 |
+
# Convert RGB to BGR
|
178 |
frame_bgr = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2BGR)
|
|
|
179 |
return self.detect_and_align(frame_bgr, top, bottom, left, right)
|
180 |
|
181 |
+
def detect_and_align_video(self, video: str, top: int, bottom: int, left: int, right: int) -> tuple:
|
|
|
182 |
if video is None:
|
183 |
+
return np.zeros((256, 256, 3), np.uint8), None, 'Error: fail to load empty file.'
|
184 |
video_cap = cv2.VideoCapture(video)
|
185 |
if video_cap.get(7) == 0:
|
186 |
video_cap.release()
|
187 |
+
return np.zeros((256, 256, 3), np.uint8), torch.zeros(1, 18, 512).to(self.device), 'Error: fail to load the video.'
|
188 |
success, frame = video_cap.read()
|
189 |
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
190 |
video_cap.release()
|
191 |
return self.detect_and_align(frame, top, bottom, left, right)
|
192 |
+
|
193 |
+
def detect_and_align_full_video(self, video: str, top: int, bottom: int, left: int, right: int) -> tuple:
|
194 |
message = 'Error: no face detected! Please retry or change the video.'
|
195 |
instyle = None
|
196 |
if video is None:
|
|
|
198 |
video_cap = cv2.VideoCapture(video)
|
199 |
if video_cap.get(7) == 0:
|
200 |
video_cap.release()
|
201 |
+
return 'default.mp4', instyle, 'Error: fail to load the video.'
|
202 |
num = min(self.video_limit_gpu, int(video_cap.get(7)))
|
203 |
if self.device == 'cpu':
|
204 |
num = min(self.video_limit_cpu, num)
|
|
|
206 |
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
207 |
frame, instyle, message, w, h, top, bottom, left, right, scale = self.detect_and_align(frame, top, bottom, left, right, True)
|
208 |
if instyle is None:
|
209 |
+
return 'default.mp4', instyle, message
|
210 |
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
211 |
videoWriter = cv2.VideoWriter('input.mp4', fourcc, video_cap.get(5), (int(right-left), int(bottom-top)))
|
212 |
videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
213 |
+
kernel_1d = np.array([[0.125], [0.375], [0.375], [0.125]])
|
214 |
for i in range(num-1):
|
215 |
success, frame = video_cap.read()
|
216 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
217 |
if scale <= 0.75:
|
218 |
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
219 |
if scale <= 0.375:
|
|
|
224 |
videoWriter.release()
|
225 |
video_cap.release()
|
226 |
|
227 |
+
return 'input.mp4', instyle, 'Successfully rescale the video to (%d, %d)' % (bottom-top, right-left)
|
228 |
+
|
229 |
+
def image_toonify(self, aligned_face: np.ndarray, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple:
|
|
|
230 |
if instyle is None or aligned_face is None:
|
231 |
+
return np.zeros((256, 256, 3), np.uint8), 'Opps, something wrong with the input. Please go to Step 2 and Rescale Image/First Frame again.'
|
232 |
if self.style_name != style_type:
|
233 |
+
exstyle, _ = self.load_model(style_type)
|
234 |
if exstyle is None:
|
235 |
+
return np.zeros((256, 256, 3), np.uint8), 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
|
236 |
with torch.no_grad():
|
237 |
if self.color_transfer:
|
238 |
s_w = exstyle
|
239 |
else:
|
240 |
s_w = instyle.clone()
|
241 |
+
s_w[:, :7] = exstyle[:, :7]
|
242 |
|
243 |
x = self.transform(aligned_face).unsqueeze(dim=0).to(self.device)
|
244 |
x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
|
245 |
scale_factor=0.5, recompute_scale_factor=False).detach()
|
246 |
inputs = torch.cat((x, x_p/16.), dim=1)
|
247 |
+
y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s=style_degree)
|
248 |
y_tilde = torch.clamp(y_tilde, -1, 1)
|
249 |
+
print('*** Toonify %dx%d image with style of %s' % (y_tilde.shape[2], y_tilde.shape[3], style_type))
|
250 |
+
return ((y_tilde[0].cpu().numpy().transpose(1, 2, 0) + 1.0) * 127.5).astype(np.uint8), 'Successfully toonify the image with style of %s' % (self.style_name)
|
251 |
+
|
252 |
+
def video_toonify(self, aligned_video: str, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple:
|
|
|
253 |
if aligned_video is None:
|
254 |
+
return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
|
255 |
video_cap = cv2.VideoCapture(aligned_video)
|
256 |
if instyle is None or aligned_video is None or video_cap.get(7) == 0:
|
257 |
video_cap.release()
|
258 |
return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
|
259 |
if self.style_name != style_type:
|
260 |
+
exstyle, _ = self.load_model(style_type)
|
261 |
if exstyle is None:
|
262 |
return 'default.mp4', 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
|
263 |
num = min(self.video_limit_gpu, int(video_cap.get(7)))
|
|
|
271 |
batch_frames = []
|
272 |
if video_cap.get(3) != 0:
|
273 |
if self.device == 'cpu':
|
274 |
+
batch_size = max(1, int(4 * 256 * 256 / video_cap.get(3) / video_cap.get(4)))
|
275 |
else:
|
276 |
+
batch_size = min(max(1, int(4 * 400 * 360 / video_cap.get(3) / video_cap.get(4))), 4)
|
277 |
else:
|
278 |
batch_size = 1
|
279 |
+
print('*** Toonify using batch size of %d on %dx%d video of %d frames with style of %s' % (batch_size, int(video_cap.get(3)*4), int(video_cap.get(4)*4), num, style_type))
|
280 |
with torch.no_grad():
|
281 |
if self.color_transfer:
|
282 |
s_w = exstyle
|
283 |
else:
|
284 |
s_w = instyle.clone()
|
285 |
+
s_w[:, :7] = exstyle[:, :7]
|
286 |
for i in range(num):
|
287 |
success, frame = video_cap.read()
|
288 |
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
|
|
302 |
|
303 |
videoWriter.release()
|
304 |
video_cap.release()
|
305 |
+
return 'output.mp4', 'Successfully toonify video of %d frames with style of %s' % (num, self.style_name)
|
|
|
306 |
|
307 |
+
def tensor2cv2(self, img):
|
308 |
+
"""Convert a tensor image to OpenCV format."""
|
309 |
+
tmp = ((img.cpu().numpy().transpose(1, 2, 0) + 1.0) * 127.5).astype(np.uint8).copy()
|
310 |
+
logging.debug(f"Converted image shape: {tmp.shape}, strides: {tmp.strides}")
|
311 |
+
return cv2.cvtColor(tmp, cv2.COLOR_RGB2BGR)
|