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
|
| 4 |
+
import pathlib
|
| 5 |
+
import enum
|
| 6 |
+
import logging
|
| 7 |
+
import datetime
|
| 8 |
+
import shutil
|
| 9 |
+
import subprocess
|
| 10 |
+
import argparse
|
| 11 |
+
import tempfile
|
| 12 |
+
from PIL import Image, ImageOps, ImageEnhance, ImageFilter
|
| 13 |
+
|
| 14 |
+
# default variables used in arg-parser
|
| 15 |
+
INPUT_VIDEOS = []
|
| 16 |
+
OUTPUT = ""
|
| 17 |
+
NUM_FRAMES = 10
|
| 18 |
+
ANIMATION = "rotation"
|
| 19 |
+
MAX_ROTATION = 45
|
| 20 |
+
MAX_DISTORTION = 0.7
|
| 21 |
+
MAX_BLUR = 0.2
|
| 22 |
+
MAX_BRIGHTNESS = 1.0
|
| 23 |
+
MAX_ZOOM = 2.0
|
| 24 |
+
DEBUG = False
|
| 25 |
+
ART = True
|
| 26 |
+
REMOVE_ORIGINAL = False
|
| 27 |
+
MERGE_PHASES = False
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# variable that cannot be changed by arg-parser
|
| 31 |
+
_OUTPUT_VIDEO_TYPE = ".mp4"
|
| 32 |
+
_OUTPUT_VIDEO_CODEC = "h264"
|
| 33 |
+
_LIMITS = {"rotation": (5, 90), "brightness": (0.0, 2.0), "blur": (0.005, 1.0),
|
| 34 |
+
"distortion": (0.3, 1.0), "zoom": (1.2, 2.0)}
|
| 35 |
+
_ANIMATION_HELP = f"""
|
| 36 |
+
This program supports multiple types of animation. The arguments 'max_blur', 'max_distortion' and 'max_brightness' \
|
| 37 |
+
affect all these types. Whereas, 'max_rotation' and 'max_zoom' only affect [rotation] and [zoom] animations \
|
| 38 |
+
respectively. Here is the list of supported animations and the number of frames needed for each (assuming that the \
|
| 39 |
+
argument 'num_frames' is kept at {NUM_FRAMES}):
|
| 40 |
+
|
| 41 |
+
* [rotation]: clockwise rotation, has 2 phases and needs {NUM_FRAMES*2} frames.
|
| 42 |
+
* [rotation_inv]: anti-clockwise rotation, has 2 phases and needs {NUM_FRAMES*2} frames.
|
| 43 |
+
* [zoom_in]: zooms inwards, has 2 phases and needs {NUM_FRAMES*2} frames.
|
| 44 |
+
* [zoom_out]: zooms outwards, has 2 phases and needs {NUM_FRAMES*2} frames.
|
| 45 |
+
* [translation]: translation from left to right, has 2 phases and needs {NUM_FRAMES*2} frames.
|
| 46 |
+
* [translation_inv]: translation from right to left, has 2 phases and needs {NUM_FRAMES*2} frames.
|
| 47 |
+
* [long_translation]: translation from left to right, has 3 phases and needs {NUM_FRAMES*3} frames ({NUM_FRAMES} from \
|
| 48 |
+
the first video, and {NUM_FRAMES*2} from the second one).
|
| 49 |
+
* [long_translation_inv]: translation from right to left, has 3 phases and needs {NUM_FRAMES*3} frames.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def log_debug(msg):
|
| 54 |
+
logging.getLogger(__package__).debug(msg)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def log_info(msg):
|
| 58 |
+
logging.getLogger(__package__).info(msg)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def log_warning(msg):
|
| 62 |
+
logging.getLogger(__package__).info("WARNING: " + msg)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def log_error(msg):
|
| 66 |
+
logging.getLogger(__package__).error("ERROR: " + msg + " (use --debug from more info)")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def intro_print(in_art):
|
| 70 |
+
""" Taken from https://patorjk.com/software/taag using 4MAX font"""
|
| 71 |
+
intro = '''
|
| 72 |
+
Yb dP 88 8888b. 888888 88""Yb db 88b 88 .dP"Y8 88 888888
|
| 73 |
+
Yb dP 88 8I Yb 88 88__dP dPYb 88Yb88 `Ybo." 88 88
|
| 74 |
+
YbdP 88 8I dY 88 88"Yb dP__Yb 88 Y88 o.`Y8b 88 88
|
| 75 |
+
YP 88 8888Y" 88 88 Yb dP""""Yb 88 Y8 8bodP' 88 88
|
| 76 |
+
'''
|
| 77 |
+
if in_art:
|
| 78 |
+
log_info(intro)
|
| 79 |
+
log_debug("=" * 80)
|
| 80 |
+
log_info((" starting video transition creation ".center(80, "=")))
|
| 81 |
+
log_debug("=" * 80)
|
| 82 |
+
log_info("")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def end_print(in_art):
|
| 86 |
+
end = """
|
| 87 |
+
,d8PPPP 888 ,d8 88PPP.
|
| 88 |
+
______ d88ooo 888_dPY8 88 8 ______
|
| 89 |
+
XXXXXX ,88' 8888' 88 88 8 XXXXXX
|
| 90 |
+
88bdPPP Y8P Y8 88oop'
|
| 91 |
+
"""
|
| 92 |
+
log_info((" video transition finished ".center(80, "=")))
|
| 93 |
+
if in_art:
|
| 94 |
+
log_info(end)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def progress(count, total, status=''):
|
| 98 |
+
bar_len = 40
|
| 99 |
+
end_char = ''
|
| 100 |
+
filled_len = int(round(bar_len * count / float(total)))
|
| 101 |
+
|
| 102 |
+
percents = round(100.0 * (count + 1) / float(total), 1)
|
| 103 |
+
|
| 104 |
+
bar = '=' * (filled_len - 1) + '>' + ' ' * (bar_len - filled_len)
|
| 105 |
+
if count == total - 1:
|
| 106 |
+
bar = '=' * bar_len
|
| 107 |
+
end_char = '\n'
|
| 108 |
+
msg = '\r[%s] %s%s [%s/%s] ... %s ' % (bar, percents, '%', count + 1, total, status)
|
| 109 |
+
print(msg, end=end_char, flush=True)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def format_list(in_list, format_str=""):
|
| 113 |
+
format_str = "{:" + format_str + "}"
|
| 114 |
+
return "[" + (", ".join([format_str.format(ii) for ii in in_list])) + "]"
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class Animations(enum.IntEnum):
|
| 118 |
+
rotation = 0
|
| 119 |
+
rotation_inv = 1
|
| 120 |
+
zoom_in = 2
|
| 121 |
+
zoom_out = 3
|
| 122 |
+
translation = 4
|
| 123 |
+
translation_inv = 5
|
| 124 |
+
long_translation = 6
|
| 125 |
+
long_translation_inv = 7
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class FramesActions:
|
| 129 |
+
class Type(enum.IntEnum):
|
| 130 |
+
mirror = 0
|
| 131 |
+
zoom = 1
|
| 132 |
+
crop = 2
|
| 133 |
+
rotation = 3
|
| 134 |
+
blur = 4
|
| 135 |
+
distortion = 5
|
| 136 |
+
brightness = 6
|
| 137 |
+
|
| 138 |
+
class Function(enum.IntEnum):
|
| 139 |
+
linear = 0
|
| 140 |
+
polynomial = 1
|
| 141 |
+
polynomial_inv = 2
|
| 142 |
+
|
| 143 |
+
class MirrorDirection(enum.IntEnum):
|
| 144 |
+
all_directions_1 = 0
|
| 145 |
+
left_1 = 1
|
| 146 |
+
right_1 = 2
|
| 147 |
+
left_3 = 3
|
| 148 |
+
right_3 = 4
|
| 149 |
+
|
| 150 |
+
def __init__(self, action_type=Type.mirror):
|
| 151 |
+
self.action_type = action_type
|
| 152 |
+
self.values = []
|
| 153 |
+
self.function = FramesActions.Function.linear
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class AnimationActions:
|
| 157 |
+
def __init__(self, max_zoom, max_brightness, max_rotation, max_blur, max_distortion, half_animation_num_frames):
|
| 158 |
+
self.phase1_actions = []
|
| 159 |
+
self.phase2_actions = []
|
| 160 |
+
self.max_zoom = max_zoom
|
| 161 |
+
self.max_brightness = max_brightness
|
| 162 |
+
self.max_rotation = max_rotation
|
| 163 |
+
self.max_blur = max_blur
|
| 164 |
+
self.max_distortion = max_distortion
|
| 165 |
+
self.half_animation_num_frames = half_animation_num_frames
|
| 166 |
+
|
| 167 |
+
def get_actions_values(self, animation_type):
|
| 168 |
+
if animation_type == Animations.rotation:
|
| 169 |
+
self._get_rotation_actions(clockwise=True)
|
| 170 |
+
elif animation_type == Animations.rotation_inv:
|
| 171 |
+
self._get_rotation_actions(clockwise=False)
|
| 172 |
+
elif animation_type == Animations.translation:
|
| 173 |
+
self._get_translation_actions(left2right=True)
|
| 174 |
+
elif animation_type == Animations.translation_inv:
|
| 175 |
+
self._get_translation_actions(left2right=False)
|
| 176 |
+
elif animation_type == Animations.zoom_in:
|
| 177 |
+
self._get_zoom_actions(inward_direction=True)
|
| 178 |
+
elif animation_type == Animations.zoom_out:
|
| 179 |
+
self._get_zoom_actions(inward_direction=False)
|
| 180 |
+
elif animation_type == Animations.long_translation:
|
| 181 |
+
self._get_long_translation_actions(left2right=True)
|
| 182 |
+
elif animation_type == Animations.long_translation_inv:
|
| 183 |
+
self._get_long_translation_actions(left2right=False)
|
| 184 |
+
|
| 185 |
+
self._print_info(animation_type)
|
| 186 |
+
return self.phase1_actions, self.phase2_actions
|
| 187 |
+
|
| 188 |
+
def _get_long_translation_actions(self, left2right=True):
|
| 189 |
+
num_frames1 = self.half_animation_num_frames
|
| 190 |
+
num_frames1_30p = int(round(num_frames1 * 0.3, 0))
|
| 191 |
+
num_frames1_50p = int(round(num_frames1 * 0.5, 0))
|
| 192 |
+
num_frames2 = 2 * self.half_animation_num_frames
|
| 193 |
+
num_frames2_30p = int(round(num_frames2 * 0.3, 0))
|
| 194 |
+
# --- mirror frames ---
|
| 195 |
+
direction1, direction2 = FramesActions.MirrorDirection.right_1, FramesActions.MirrorDirection.left_3
|
| 196 |
+
if not left2right:
|
| 197 |
+
direction1, direction2 = FramesActions.MirrorDirection.left_1, FramesActions.MirrorDirection.right_3
|
| 198 |
+
fa_mirror1 = FramesActions(FramesActions.Type.mirror)
|
| 199 |
+
[fa_mirror1.values.append(direction1) for _ in range(num_frames1)]
|
| 200 |
+
self.phase1_actions.append(fa_mirror1)
|
| 201 |
+
fa_mirror2 = FramesActions(FramesActions.Type.mirror)
|
| 202 |
+
[fa_mirror2.values.append(direction2) for _ in range(num_frames2)]
|
| 203 |
+
self.phase2_actions.append(fa_mirror2)
|
| 204 |
+
|
| 205 |
+
# --- crop ---
|
| 206 |
+
crop_1_values, crop_2_values = (0, 1), (0, 2, 3)
|
| 207 |
+
if not left2right:
|
| 208 |
+
crop_1_values, crop_2_values = (1, 0), (3, 2, 0)
|
| 209 |
+
fa_crop1 = FramesActions(FramesActions.Type.crop)
|
| 210 |
+
self._polynomial(fa_crop1, crop_1_values[0], crop_1_values[1], num_frames1)
|
| 211 |
+
fa_crop1.values = [(v, 0) for v in fa_crop1.values]
|
| 212 |
+
self.phase1_actions.append(fa_crop1)
|
| 213 |
+
|
| 214 |
+
fa_crop2 = FramesActions(FramesActions.Type.crop)
|
| 215 |
+
# self._linear(fa_crop2, crop_2_values[0], crop_2_values[1], num_frames1)
|
| 216 |
+
self._polynomial_inv(fa_crop2, crop_2_values[0], crop_2_values[2], 2 * num_frames1)
|
| 217 |
+
fa_crop2.values = [(v, 0) for v in fa_crop2.values]
|
| 218 |
+
self.phase2_actions.append(fa_crop2)
|
| 219 |
+
|
| 220 |
+
# --- brightness ---
|
| 221 |
+
if _LIMITS["brightness"][0] <= self.max_brightness <= _LIMITS["brightness"][1] and self.max_brightness != 1:
|
| 222 |
+
fa_br1, fa_br2 = FramesActions(FramesActions.Type.brightness), FramesActions(FramesActions.Type.brightness)
|
| 223 |
+
self._polynomial(fa_br1, 1.0, self.max_brightness, num_frames1)
|
| 224 |
+
fa_br2.values = [self.max_brightness for _ in range(num_frames1)]
|
| 225 |
+
self._polynomial_inv(fa_br2, self.max_brightness, 1.0, num_frames1)
|
| 226 |
+
self.phase1_actions.append(fa_br1)
|
| 227 |
+
self.phase2_actions.append(fa_br2)
|
| 228 |
+
# --- blur ---
|
| 229 |
+
if _LIMITS["blur"][0] < self.max_blur <= _LIMITS["blur"][1]:
|
| 230 |
+
fa_bl1, fa_bl2 = FramesActions(FramesActions.Type.blur), FramesActions(FramesActions.Type.blur)
|
| 231 |
+
fa_bl1.values = [0 for _ in range(num_frames1_30p)]
|
| 232 |
+
self._polynomial(fa_bl1, 0.0, self.max_blur, num_frames1 - num_frames1_30p)
|
| 233 |
+
self._polynomial(fa_bl2, self.max_blur, 0.0, num_frames2)
|
| 234 |
+
self.phase1_actions.append(fa_bl1)
|
| 235 |
+
self.phase2_actions.append(fa_bl2)
|
| 236 |
+
# --- distortion ---
|
| 237 |
+
if _LIMITS["distortion"][0] < self.max_distortion <= _LIMITS["distortion"][1]:
|
| 238 |
+
fa_ds1, fa_ds2 = FramesActions(FramesActions.Type.distortion), FramesActions(FramesActions.Type.distortion)
|
| 239 |
+
self._polynomial(fa_ds1, 0.0, self.max_distortion, num_frames1 - num_frames1_50p)
|
| 240 |
+
fa_ds1.values += [self.max_distortion for _ in range(num_frames1_50p)]
|
| 241 |
+
fa_ds2.values = [self.max_distortion for _ in range(num_frames1 + num_frames1_50p)]
|
| 242 |
+
self._polynomial(fa_ds2, self.max_distortion, 0.0, num_frames1 - num_frames1_50p)
|
| 243 |
+
self.phase1_actions.append(fa_ds1)
|
| 244 |
+
self.phase2_actions.append(fa_ds2)
|
| 245 |
+
|
| 246 |
+
def _get_zoom_actions(self, inward_direction=True):
|
| 247 |
+
num_frames = self.half_animation_num_frames
|
| 248 |
+
num_frames_30p = int(round(num_frames * 0.3, 0))
|
| 249 |
+
num_frames_50p = int(round(num_frames * 0.5, 0))
|
| 250 |
+
# --- mirror frames ---
|
| 251 |
+
for phase_fas in [self.phase1_actions, self.phase2_actions]:
|
| 252 |
+
fa_mirror = FramesActions(FramesActions.Type.mirror)
|
| 253 |
+
for _ in range(num_frames):
|
| 254 |
+
fa_mirror.values.append(FramesActions.MirrorDirection.all_directions_1)
|
| 255 |
+
phase_fas.append(fa_mirror)
|
| 256 |
+
# --- zoom ---
|
| 257 |
+
zoom_1v, zoom_2v = self.max_zoom, 1 / self.max_zoom
|
| 258 |
+
if not inward_direction:
|
| 259 |
+
zoom_1v, zoom_2v = zoom_2v, zoom_1v
|
| 260 |
+
if _LIMITS["zoom"][0] <= self.max_zoom <= _LIMITS["zoom"][1]:
|
| 261 |
+
fa_zoom1, fa_zoom2 = FramesActions(FramesActions.Type.zoom), FramesActions(FramesActions.Type.zoom)
|
| 262 |
+
self._polynomial(fa_zoom1, 1.0, zoom_1v, num_frames)
|
| 263 |
+
self.phase1_actions.append(fa_zoom1)
|
| 264 |
+
self._polynomial_inv(fa_zoom2, zoom_2v, 1.0, num_frames)
|
| 265 |
+
self.phase2_actions.append(fa_zoom2)
|
| 266 |
+
# --- crop ---
|
| 267 |
+
for phase_fas in [self.phase1_actions, self.phase2_actions]:
|
| 268 |
+
fa_crop = FramesActions(FramesActions.Type.crop)
|
| 269 |
+
for _ in range(num_frames):
|
| 270 |
+
fa_crop.values.append((1, 1))
|
| 271 |
+
phase_fas.append(fa_crop)
|
| 272 |
+
# --- brightness ---
|
| 273 |
+
if _LIMITS["brightness"][0] <= self.max_brightness <= _LIMITS["brightness"][1] and self.max_brightness != 1:
|
| 274 |
+
self._symmetric_action_value(self._linear, FramesActions.Type.brightness, 1,
|
| 275 |
+
self.max_brightness, num_frames)
|
| 276 |
+
|
| 277 |
+
# --- blur ---
|
| 278 |
+
if _LIMITS["blur"][0] < self.max_blur <= _LIMITS["blur"][1]:
|
| 279 |
+
self._symmetric_action_value(self._polynomial, FramesActions.Type.blur, 0,
|
| 280 |
+
self.max_blur, num_frames, num_f_a_duplicates=num_frames_30p)
|
| 281 |
+
# --- distortion ---
|
| 282 |
+
if _LIMITS["distortion"][0] < self.max_distortion <= _LIMITS["distortion"][1]:
|
| 283 |
+
self._symmetric_action_value(self._polynomial_inv, FramesActions.Type.distortion, 0,
|
| 284 |
+
self.max_distortion, num_frames, num_f_b_duplicates=num_frames_50p)
|
| 285 |
+
|
| 286 |
+
def _get_translation_actions(self, left2right=True):
|
| 287 |
+
num_frames = self.half_animation_num_frames
|
| 288 |
+
num_frames_30p = int(round(num_frames * 0.3, 0))
|
| 289 |
+
num_frames_50p = int(round(num_frames * 0.5, 0))
|
| 290 |
+
# --- mirror frames ---
|
| 291 |
+
direction1, direction2 = FramesActions.MirrorDirection.right_1, FramesActions.MirrorDirection.left_1
|
| 292 |
+
if not left2right:
|
| 293 |
+
direction1, direction2 = direction2, direction1
|
| 294 |
+
fa_mirror1 = FramesActions(FramesActions.Type.mirror)
|
| 295 |
+
[fa_mirror1.values.append(direction1) for _ in range(num_frames)]
|
| 296 |
+
self.phase1_actions.append(fa_mirror1)
|
| 297 |
+
fa_mirror2 = FramesActions(FramesActions.Type.mirror)
|
| 298 |
+
[fa_mirror2.values.append(direction2) for _ in range(num_frames)]
|
| 299 |
+
self.phase2_actions.append(fa_mirror2)
|
| 300 |
+
|
| 301 |
+
# --- crop ---
|
| 302 |
+
crop_f_a, crop_f_b = 0, 1
|
| 303 |
+
if not left2right:
|
| 304 |
+
crop_f_a, crop_f_b = 1, 0
|
| 305 |
+
fa_crop1 = FramesActions(FramesActions.Type.crop)
|
| 306 |
+
self._polynomial(fa_crop1, crop_f_a, crop_f_b, num_frames)
|
| 307 |
+
fa_crop1.values = [(v, 0) for v in fa_crop1.values]
|
| 308 |
+
self.phase1_actions.append(fa_crop1)
|
| 309 |
+
fa_crop2 = FramesActions(FramesActions.Type.crop)
|
| 310 |
+
self._polynomial_inv(fa_crop2, crop_f_a, crop_f_b, num_frames)
|
| 311 |
+
fa_crop2.values = [(v, 0) for v in fa_crop2.values]
|
| 312 |
+
self.phase2_actions.append(fa_crop2)
|
| 313 |
+
|
| 314 |
+
# --- brightness ---
|
| 315 |
+
if _LIMITS["brightness"][0] <= self.max_brightness <= _LIMITS["brightness"][1] and self.max_brightness != 1:
|
| 316 |
+
self._symmetric_action_value(self._linear, FramesActions.Type.brightness, 1,
|
| 317 |
+
self.max_brightness, num_frames)
|
| 318 |
+
# --- blur ---
|
| 319 |
+
if _LIMITS["blur"][0] < self.max_blur <= _LIMITS["blur"][1]:
|
| 320 |
+
self._symmetric_action_value(self._polynomial, FramesActions.Type.blur, 0,
|
| 321 |
+
self.max_blur, num_frames, num_f_a_duplicates=num_frames_30p)
|
| 322 |
+
# --- distortion ---
|
| 323 |
+
if _LIMITS["distortion"][0] < self.max_distortion <= _LIMITS["distortion"][1]:
|
| 324 |
+
self._symmetric_action_value(self._polynomial_inv, FramesActions.Type.distortion, 0,
|
| 325 |
+
self.max_distortion, num_frames, num_f_b_duplicates=num_frames_50p)
|
| 326 |
+
|
| 327 |
+
def _get_rotation_actions(self, clockwise=True):
|
| 328 |
+
num_frames = self.half_animation_num_frames
|
| 329 |
+
num_frames_30p = int(round(num_frames * 0.3, 0))
|
| 330 |
+
num_frames_50p = int(round(num_frames * 0.5, 0))
|
| 331 |
+
# --- mirror frames ---
|
| 332 |
+
for phase_fas in [self.phase1_actions, self.phase2_actions]:
|
| 333 |
+
fa_mirror = FramesActions(FramesActions.Type.mirror)
|
| 334 |
+
for _ in range(num_frames):
|
| 335 |
+
fa_mirror.values.append(FramesActions.MirrorDirection.all_directions_1)
|
| 336 |
+
phase_fas.append(fa_mirror)
|
| 337 |
+
# --- rotation ---
|
| 338 |
+
if _LIMITS["rotation"][0] < self.max_rotation <= _LIMITS["rotation"][1]:
|
| 339 |
+
mul = 1 if clockwise else -1
|
| 340 |
+
fa1_rot, fa2_rot = FramesActions(FramesActions.Type.rotation), FramesActions(FramesActions.Type.rotation)
|
| 341 |
+
self._polynomial(fa1_rot, 0, - mul * self.max_rotation, num_frames)
|
| 342 |
+
self._polynomial_inv(fa2_rot, mul * self.max_rotation, 0, num_frames)
|
| 343 |
+
self.phase1_actions.append(fa1_rot)
|
| 344 |
+
self.phase2_actions.append(fa2_rot)
|
| 345 |
+
|
| 346 |
+
# --- crop ---
|
| 347 |
+
for phase_fas in [self.phase1_actions, self.phase2_actions]:
|
| 348 |
+
fa_crop = FramesActions(FramesActions.Type.crop)
|
| 349 |
+
for _ in range(num_frames):
|
| 350 |
+
fa_crop.values.append((1, 1))
|
| 351 |
+
phase_fas.append(fa_crop)
|
| 352 |
+
# --- brightness ---
|
| 353 |
+
if _LIMITS["brightness"][0] <= self.max_brightness <= _LIMITS["brightness"][1] and self.max_brightness != 1:
|
| 354 |
+
self._symmetric_action_value(self._linear, FramesActions.Type.brightness, 1,
|
| 355 |
+
self.max_brightness, num_frames)
|
| 356 |
+
# --- blur ---
|
| 357 |
+
if _LIMITS["blur"][0] < self.max_blur <= _LIMITS["blur"][1]:
|
| 358 |
+
self._symmetric_action_value(self._polynomial, FramesActions.Type.blur, 0,
|
| 359 |
+
self.max_blur, num_frames, num_f_a_duplicates=num_frames_30p)
|
| 360 |
+
# --- distortion ---
|
| 361 |
+
if _LIMITS["distortion"][0] < self.max_distortion <= _LIMITS["distortion"][1]:
|
| 362 |
+
self._symmetric_action_value(self._polynomial_inv, FramesActions.Type.distortion, 0,
|
| 363 |
+
self.max_distortion, num_frames, num_f_b_duplicates=num_frames_50p)
|
| 364 |
+
|
| 365 |
+
def _symmetric_action_value(self, func, action_type, f_a, f_b, length,
|
| 366 |
+
num_f_a_duplicates=0, num_f_b_duplicates=0, phase2_multiplier=1):
|
| 367 |
+
p2m = phase2_multiplier
|
| 368 |
+
phase1_fa = FramesActions(action_type)
|
| 369 |
+
phase2_fa = FramesActions(action_type)
|
| 370 |
+
[phase1_fa.values.append(f_a) for _ in range(num_f_a_duplicates)]
|
| 371 |
+
[phase2_fa.values.append(f_b * p2m) for _ in range(num_f_b_duplicates)]
|
| 372 |
+
func(phase1_fa, f_a, f_b, length - num_f_a_duplicates - num_f_b_duplicates)
|
| 373 |
+
if phase1_fa.function == FramesActions.Function.linear:
|
| 374 |
+
self._linear(phase2_fa, f_b * p2m, f_a * p2m, length - num_f_a_duplicates - num_f_b_duplicates)
|
| 375 |
+
elif phase1_fa.function == FramesActions.Function.polynomial:
|
| 376 |
+
self._polynomial_inv(phase2_fa, f_b * p2m, f_a * p2m, length - num_f_a_duplicates - num_f_b_duplicates)
|
| 377 |
+
elif phase1_fa.function == FramesActions.Function.polynomial_inv:
|
| 378 |
+
self._polynomial(phase2_fa, f_b * p2m, f_a * p2m, length - num_f_a_duplicates - num_f_b_duplicates)
|
| 379 |
+
else:
|
| 380 |
+
log_error("this should never happens")
|
| 381 |
+
[phase1_fa.values.append(f_b) for _ in range(num_f_b_duplicates)]
|
| 382 |
+
[phase2_fa.values.append(f_a * p2m) for _ in range(num_f_a_duplicates)]
|
| 383 |
+
self.phase1_actions.append(phase1_fa)
|
| 384 |
+
self.phase2_actions.append(phase2_fa)
|
| 385 |
+
|
| 386 |
+
def _print_info(self, animation_type):
|
| 387 |
+
log_info("")
|
| 388 |
+
log_debug("".center(80, "="))
|
| 389 |
+
log_info(" Transition animation info ".center(80, "="))
|
| 390 |
+
log_debug("".center(80, "="))
|
| 391 |
+
animation_types = {0: "clockwise rotation", 1: "anticlockwise rotation", 2: "zoom in", 3: "zoom out",
|
| 392 |
+
4: "translation (left to right)", 5: "translation (right to left)",
|
| 393 |
+
6: "long translation (left to right)", 7: "inverse long translation(right to left)"}
|
| 394 |
+
log_info(f"transition animation type: [{animation_types[animation_type]}]")
|
| 395 |
+
log_info(f"transition activated effects (in order):")
|
| 396 |
+
|
| 397 |
+
phase1_activated = [action.action_type.name for action in self.phase1_actions]
|
| 398 |
+
phase2_activated = [action.action_type.name for action in self.phase2_actions]
|
| 399 |
+
log_info(f"* phase 1 activated effects: [{', '.join(phase1_activated)}]")
|
| 400 |
+
log_info(f"* phase 2 activated effects: [{', '.join(phase2_activated)}]")
|
| 401 |
+
log_debug("")
|
| 402 |
+
|
| 403 |
+
for phase_idx, actions in enumerate([self.phase1_actions, self.phase2_actions]):
|
| 404 |
+
log_debug(f" transition phase_{phase_idx + 1} ".center(80, "-"))
|
| 405 |
+
for action in actions:
|
| 406 |
+
if action.action_type == FramesActions.Type.mirror:
|
| 407 |
+
log_debug(f"mirroring frames, type: [{action.action_type.name}], "
|
| 408 |
+
f"function: [{action.function.name}]")
|
| 409 |
+
log_debug(f"* values: [{action.values[0].name}] - num frames: [{len(action.values)}]")
|
| 410 |
+
elif action.action_type == FramesActions.Type.zoom:
|
| 411 |
+
log_debug(f"zoom effect, max value: [{self.max_zoom:.1%}], function: [{action.function.name}]")
|
| 412 |
+
log_debug(f"* values: {format_list(action.values, '.1%')}")
|
| 413 |
+
elif action.action_type == FramesActions.Type.crop:
|
| 414 |
+
log_debug(f"crop effect")
|
| 415 |
+
cropped = [f"({v[0]:g}, {v[1]:g})" for v in action.values]
|
| 416 |
+
log_debug(f"* values: {format_list(cropped, 's')}, function: [{action.function.name}]")
|
| 417 |
+
elif action.action_type == FramesActions.Type.rotation:
|
| 418 |
+
log_debug(f"rotation effect, max value (in degrees): [{self.max_rotation:.1f}], "
|
| 419 |
+
f"function: [{action.function.name}]")
|
| 420 |
+
log_debug(f"* values (degree): {format_list(action.values, '.1f')}")
|
| 421 |
+
elif action.action_type == FramesActions.Type.blur:
|
| 422 |
+
log_debug(f"blur effect, max value: [{self.max_blur:.1%}], function: [{action.function.name}]")
|
| 423 |
+
log_debug(f"* values: {format_list(action.values, '.1%')}")
|
| 424 |
+
elif action.action_type == FramesActions.Type.distortion:
|
| 425 |
+
log_debug(f"len pincushion distortion effect, max value: [{self.max_distortion:.1%}], "
|
| 426 |
+
f"function: [{action.function.name}]")
|
| 427 |
+
log_debug(f"* values: {format_list(action.values, '.1%')}")
|
| 428 |
+
elif action.action_type == FramesActions.Type.brightness:
|
| 429 |
+
log_debug(f"brightness effect, max value: [{self.max_brightness:.1%}], "
|
| 430 |
+
f"function: [{action.function.name}]")
|
| 431 |
+
log_debug(f"* values: {format_list(action.values, '.1%')}")
|
| 432 |
+
log_debug("")
|
| 433 |
+
log_debug("")
|
| 434 |
+
|
| 435 |
+
@staticmethod
|
| 436 |
+
def _linear(frame_action, f_a, f_b, length):
|
| 437 |
+
xa, xb = 0, length - 1
|
| 438 |
+
c1 = (f_b - f_a) / (xb - xa)
|
| 439 |
+
c2 = f_a - c1 * xa
|
| 440 |
+
for xi in range(length):
|
| 441 |
+
frame_action.values.append(c1 * xi + c2)
|
| 442 |
+
frame_action.function = FramesActions.Function.linear
|
| 443 |
+
|
| 444 |
+
@staticmethod
|
| 445 |
+
def _polynomial(frame_action, f_a, f_b, length, strength=3.0):
|
| 446 |
+
xa, xb = 0, length - 1
|
| 447 |
+
c1 = (f_b - f_a) / ((xb - xa) ** strength)
|
| 448 |
+
c2 = f_a
|
| 449 |
+
for xi in range(length):
|
| 450 |
+
frame_action.values.append(c1 * ((xi - xa) ** strength) + c2)
|
| 451 |
+
frame_action.function = FramesActions.Function.polynomial
|
| 452 |
+
|
| 453 |
+
@staticmethod
|
| 454 |
+
def _polynomial_inv(frame_action, f_a, f_b, length, strength=3.0):
|
| 455 |
+
AnimationActions._polynomial(frame_action, f_a, f_b, length, 1 / strength)
|
| 456 |
+
frame_action.function = FramesActions.Function.polynomial_inv
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
class AnimationImages:
|
| 460 |
+
class PincushionDeformation:
|
| 461 |
+
def __init__(self, strength=0.2, zoom=1.2, auto_zoom=False):
|
| 462 |
+
self.correction_radius = None
|
| 463 |
+
self.zoom = zoom
|
| 464 |
+
self.strength = strength
|
| 465 |
+
if strength <= 0:
|
| 466 |
+
self.strength = 0.00001
|
| 467 |
+
self.auto_zoom = auto_zoom
|
| 468 |
+
self.half_height = None
|
| 469 |
+
self.half_width = None
|
| 470 |
+
|
| 471 |
+
def transform(self, x, y):
|
| 472 |
+
new_x = x - self.half_width
|
| 473 |
+
new_y = y - self.half_height
|
| 474 |
+
distance = math.sqrt(new_x ** 2 + new_y ** 2)
|
| 475 |
+
r = distance / self.correction_radius
|
| 476 |
+
if r == 0:
|
| 477 |
+
theta = 1
|
| 478 |
+
else:
|
| 479 |
+
theta = math.atan(r) / r
|
| 480 |
+
source_x = self.half_width + theta * new_x * self.zoom
|
| 481 |
+
source_y = self.half_height + theta * new_y * self.zoom
|
| 482 |
+
return source_x, source_y
|
| 483 |
+
|
| 484 |
+
def transform_rectangle(self, x0, y0, x1, y1):
|
| 485 |
+
return (*self.transform(x0, y0),
|
| 486 |
+
*self.transform(x0, y1),
|
| 487 |
+
*self.transform(x1, y1),
|
| 488 |
+
*self.transform(x1, y0))
|
| 489 |
+
|
| 490 |
+
def determine_parameters(self, img):
|
| 491 |
+
width, height = img.size
|
| 492 |
+
self.half_width = width / 2
|
| 493 |
+
self.half_height = height / 2
|
| 494 |
+
self.correction_radius = (min(self.half_width, self.half_height) * 10) * (1 - self.strength) ** 2 + 1
|
| 495 |
+
# print(f"correction radius => {self.correction_radius}")
|
| 496 |
+
if self.auto_zoom:
|
| 497 |
+
r = math.sqrt(min(self.half_height, self.half_width) ** 2) / self.correction_radius
|
| 498 |
+
self.zoom = r / math.atan(r)
|
| 499 |
+
|
| 500 |
+
def get_debug_info(self, img):
|
| 501 |
+
self.determine_parameters(img)
|
| 502 |
+
w, h = img.size
|
| 503 |
+
msg = [" lens distortion debug info ".center(80, '=')]
|
| 504 |
+
msg += [f"input image size: [w:{w}, h:{h}]"]
|
| 505 |
+
if not self.auto_zoom:
|
| 506 |
+
msg += [f"strength: [{self.strength:.0%}] , automatic zoom: [Off] , provided zoom: [{self.zoom:.0%}]"]
|
| 507 |
+
else:
|
| 508 |
+
msg += [f"strength: [{self.strength:.0%}] , automatic zoom: [On] , calculated zoom: [{self.zoom:.0%}]"]
|
| 509 |
+
msg += ["corner points displacement:"]
|
| 510 |
+
points = {"top-left": (0, 0), "top-center": (self.half_width, 0), "top-right": (w, 0),
|
| 511 |
+
"left": (0, self.half_height), "right": (w, self.half_height),
|
| 512 |
+
"bottom-left": (0, h), "bottom-center": (self.half_width, h), "bottom-right": (w, h)}
|
| 513 |
+
for key, value in points.items():
|
| 514 |
+
res = self.transform(value[0], value[1])
|
| 515 |
+
msg += [f"* {key:<13s} [x:{res[0]:<6.1f}, y:{res[1]:<6.1f}] => [{value[0]:<4.0f}, {value[1]:<4.0f}]"]
|
| 516 |
+
msg += [""]
|
| 517 |
+
return msg
|
| 518 |
+
|
| 519 |
+
def getmesh(self, img):
|
| 520 |
+
self.determine_parameters(img)
|
| 521 |
+
width, height = img.size
|
| 522 |
+
|
| 523 |
+
grid_space = 20
|
| 524 |
+
target_grid = []
|
| 525 |
+
for x in range(0, width, grid_space):
|
| 526 |
+
for y in range(0, height, grid_space):
|
| 527 |
+
target_grid.append((x, y, x + grid_space, y + grid_space))
|
| 528 |
+
|
| 529 |
+
source_grid = [self.transform_rectangle(*rect) for rect in target_grid]
|
| 530 |
+
return [t for t in zip(target_grid, source_grid)]
|
| 531 |
+
|
| 532 |
+
@staticmethod
|
| 533 |
+
def make_transition(working_dir, in_images1, in_images2, in_actions1, in_actions2, debug=False):
|
| 534 |
+
log_info("")
|
| 535 |
+
log_debug("".center(80, "="))
|
| 536 |
+
log_info(" Transition image processing ".center(80, "="))
|
| 537 |
+
log_debug("".center(80, "="))
|
| 538 |
+
images_path = [in_images1, in_images2]
|
| 539 |
+
res_folder = [None, None]
|
| 540 |
+
peak_distortion_msg = []
|
| 541 |
+
peak_distortion_value = 0.0
|
| 542 |
+
peak_distortion_img = None
|
| 543 |
+
for phase_idx, actions in enumerate([in_actions1, in_actions2]):
|
| 544 |
+
log_debug("=" * 80)
|
| 545 |
+
log_info(f"processing transition phase_{phase_idx+1} images")
|
| 546 |
+
for img_idx, img_path in enumerate(images_path[phase_idx]):
|
| 547 |
+
if not debug:
|
| 548 |
+
progress(img_idx, len(images_path[phase_idx]), f"phase_{phase_idx+1} images")
|
| 549 |
+
img = Image.open(str(img_path))
|
| 550 |
+
original_size = img.size
|
| 551 |
+
log_debug(f" image [{img_idx+1}/{len(images_path[phase_idx])}] processing ".center(80, "-"))
|
| 552 |
+
log_debug(f"image path {img_path}")
|
| 553 |
+
for action_idx, action in enumerate(actions):
|
| 554 |
+
suffix = action.action_type.name
|
| 555 |
+
if action_idx == len(actions) - 1:
|
| 556 |
+
suffix += "_final"
|
| 557 |
+
img_save_folder = working_dir / f"{action_idx+2}_phase{phase_idx+1}_{suffix}"
|
| 558 |
+
img_save_folder.mkdir(exist_ok=True)
|
| 559 |
+
if action_idx == len(actions) - 1:
|
| 560 |
+
res_folder[phase_idx] = img_save_folder
|
| 561 |
+
value = action.values[img_idx]
|
| 562 |
+
msg = f"phase_{phase_idx+1} - img [{img_idx+1}/{len(images_path[phase_idx])}]"
|
| 563 |
+
if isinstance(value, tuple):
|
| 564 |
+
msg += f" - action [{action.action_type.name} => ({value[0]:.1%}, {value[1]:.1%})]"
|
| 565 |
+
else:
|
| 566 |
+
msg += f" - action [{action.action_type.name} => {value:g}]"
|
| 567 |
+
msg += f" - folder [{img_save_folder.name}]"
|
| 568 |
+
log_debug(msg)
|
| 569 |
+
if action.action_type == FramesActions.Type.mirror:
|
| 570 |
+
img = AnimationImages.mirror_image_effect(img, value)
|
| 571 |
+
elif action.action_type == FramesActions.Type.zoom:
|
| 572 |
+
img = AnimationImages.zoom_effect(img, value)
|
| 573 |
+
elif action.action_type == FramesActions.Type.crop:
|
| 574 |
+
img = AnimationImages.crop_effect(img, value, original_size)
|
| 575 |
+
elif action.action_type == FramesActions.Type.rotation:
|
| 576 |
+
img = AnimationImages.rotation_effect(img, value)
|
| 577 |
+
elif action.action_type == FramesActions.Type.blur:
|
| 578 |
+
img = AnimationImages.blur_effect(img, value)
|
| 579 |
+
elif action.action_type == FramesActions.Type.distortion:
|
| 580 |
+
img = AnimationImages.distortion_effect(img, value)
|
| 581 |
+
if value > peak_distortion_value:
|
| 582 |
+
peak_distortion_msg = AnimationImages.PincushionDeformation(value, 1.0).get_debug_info(img)
|
| 583 |
+
peak_distortion_value = value
|
| 584 |
+
peak_distortion_img = img_path
|
| 585 |
+
elif action.action_type == FramesActions.Type.brightness:
|
| 586 |
+
img = AnimationImages.brightness_effect(img, value)
|
| 587 |
+
if debug or action_idx == len(actions) - 1:
|
| 588 |
+
img.save(str(img_save_folder / img_path.name))
|
| 589 |
+
|
| 590 |
+
log_debug("")
|
| 591 |
+
if peak_distortion_img is not None:
|
| 592 |
+
log_debug(f"peak distortion effect: value [{peak_distortion_value}:.1%], img path: [{peak_distortion_img}]")
|
| 593 |
+
for line in peak_distortion_msg:
|
| 594 |
+
log_debug(line)
|
| 595 |
+
return res_folder
|
| 596 |
+
|
| 597 |
+
@staticmethod
|
| 598 |
+
def mirror_image_effect(in_img, mirror_direction):
|
| 599 |
+
images = [in_img, in_img.transpose(0), in_img.transpose(1),
|
| 600 |
+
in_img.transpose(0).transpose(1)]
|
| 601 |
+
w, h = in_img.width, in_img.height
|
| 602 |
+
if mirror_direction == FramesActions.MirrorDirection.all_directions_1:
|
| 603 |
+
new_size = (3 * w, 3 * h)
|
| 604 |
+
pos_dict = {(0, 0): 3, (1, 0): 2, (2, 0): 3,
|
| 605 |
+
(0, 1): 1, (1, 1): 0, (2, 1): 1,
|
| 606 |
+
(0, 2): 3, (1, 2): 2, (2, 2): 3}
|
| 607 |
+
elif mirror_direction == FramesActions.MirrorDirection.left_1:
|
| 608 |
+
new_size = (2 * w, 1 * h)
|
| 609 |
+
pos_dict = {(0, 0): 1, (1, 0): 0}
|
| 610 |
+
elif mirror_direction == FramesActions.MirrorDirection.right_1:
|
| 611 |
+
new_size = (2 * w, 1 * h)
|
| 612 |
+
pos_dict = {(0, 0): 0, (1, 0): 1}
|
| 613 |
+
elif mirror_direction == FramesActions.MirrorDirection.left_3:
|
| 614 |
+
new_size = (4 * w, 1 * h)
|
| 615 |
+
pos_dict = {(0, 0): 1, (1, 0): 0, (2, 0): 1, (3, 0): 0}
|
| 616 |
+
elif mirror_direction == FramesActions.MirrorDirection.right_3:
|
| 617 |
+
new_size = (4 * w, 1 * h)
|
| 618 |
+
pos_dict = {(0, 0): 0, (1, 0): 1, (2, 0): 0, (3, 0): 1}
|
| 619 |
+
else:
|
| 620 |
+
return in_img
|
| 621 |
+
res = Image.new('RGB', new_size)
|
| 622 |
+
[res.paste(images[idx], (w * xy[0], h * xy[1])) for xy, idx in pos_dict.items()]
|
| 623 |
+
return res
|
| 624 |
+
|
| 625 |
+
@staticmethod
|
| 626 |
+
def zoom_effect(in_img, zoom_value):
|
| 627 |
+
w, h = in_img.size
|
| 628 |
+
zoom2 = zoom_value * 2
|
| 629 |
+
new_img = in_img.crop((w/2 - w / zoom2, h/2 - h / zoom2, w/2 + w / zoom2, h/2 + h / zoom2))
|
| 630 |
+
try:
|
| 631 |
+
return new_img.resize((w, h), Image.Resampling.BICUBIC)
|
| 632 |
+
except AttributeError:
|
| 633 |
+
return new_img.resize((w, h), Image.BICUBIC)
|
| 634 |
+
|
| 635 |
+
@staticmethod
|
| 636 |
+
def crop_effect(in_img, top_left_corner, original_img_size):
|
| 637 |
+
h, w = original_img_size[0], original_img_size[1]
|
| 638 |
+
tfc_x, tfc_y = int(round(top_left_corner[0] * h, 0)), int(round(top_left_corner[1] * w, 0))
|
| 639 |
+
return in_img.crop((tfc_x, tfc_y, tfc_x + h, tfc_y + w))
|
| 640 |
+
|
| 641 |
+
@staticmethod
|
| 642 |
+
def rotation_effect(in_img, rot_angle):
|
| 643 |
+
return in_img.rotate(rot_angle)
|
| 644 |
+
|
| 645 |
+
@staticmethod
|
| 646 |
+
def blur_effect(in_img, blur_value):
|
| 647 |
+
blue_strength = min(in_img.size[0], in_img.size[1]) * blur_value * 0.1
|
| 648 |
+
# print(blue_strength)
|
| 649 |
+
return in_img.filter(ImageFilter.GaussianBlur(blue_strength))
|
| 650 |
+
|
| 651 |
+
@staticmethod
|
| 652 |
+
def distortion_effect(in_img, distortion_strength):
|
| 653 |
+
return ImageOps.deform(in_img, AnimationImages.PincushionDeformation(distortion_strength, 1.0))
|
| 654 |
+
|
| 655 |
+
@staticmethod
|
| 656 |
+
def brightness_effect(in_img, brightness_value):
|
| 657 |
+
enhancer = ImageEnhance.Brightness(in_img)
|
| 658 |
+
return enhancer.enhance(brightness_value)
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
class DataHandler:
|
| 662 |
+
def __init__(self):
|
| 663 |
+
self.start_time = datetime.datetime.now()
|
| 664 |
+
self.tmp_path = None
|
| 665 |
+
self.output = None
|
| 666 |
+
self.input_vid1 = None
|
| 667 |
+
self.input_vid2 = None
|
| 668 |
+
self.phase1_vid = None
|
| 669 |
+
self.phase2_vid = None
|
| 670 |
+
self.merged_vid = None
|
| 671 |
+
self.fps = 30
|
| 672 |
+
self.vid1_raw_images_folder = None
|
| 673 |
+
self.vid2_raw_images_folder = None
|
| 674 |
+
self.phase1_images = []
|
| 675 |
+
self.phase2_images = []
|
| 676 |
+
self.animation = None
|
| 677 |
+
|
| 678 |
+
def verify_arguments(self, in_args, in_tmp_path):
|
| 679 |
+
self.tmp_path = in_tmp_path
|
| 680 |
+
self.output = pathlib.Path(in_args.output)
|
| 681 |
+
if in_args.output == "":
|
| 682 |
+
self._suggest_output(in_args.output)
|
| 683 |
+
if in_args.debug:
|
| 684 |
+
self.tmp_path = self.output.parent / (self.output.stem + "_debug")
|
| 685 |
+
if self.tmp_path.is_dir():
|
| 686 |
+
shutil.rmtree(str(self.tmp_path))
|
| 687 |
+
self.tmp_path.mkdir()
|
| 688 |
+
|
| 689 |
+
self._setup_logging(in_args.debug, self.tmp_path / f"{__package__}.log")
|
| 690 |
+
intro_print(in_args.art)
|
| 691 |
+
if not self._verify_critical_info(in_args):
|
| 692 |
+
return False
|
| 693 |
+
|
| 694 |
+
self.phase1_vid = self.output.parent / (self.output.stem + "_phase1" + _OUTPUT_VIDEO_TYPE)
|
| 695 |
+
self.phase2_vid = self.output.parent / (self.output.stem + "_phase2" + _OUTPUT_VIDEO_TYPE)
|
| 696 |
+
self.merged_vid = self.output.parent / (self.output.stem + "_merged" + _OUTPUT_VIDEO_TYPE)
|
| 697 |
+
log_info(f"first input video: {self.input_vid1}")
|
| 698 |
+
log_info(f"second input video: {self.input_vid2}")
|
| 699 |
+
if in_args.merge:
|
| 700 |
+
log_debug(f"transition phase1 video: {self.phase1_vid}")
|
| 701 |
+
log_debug(f"transition phase2 video: {self.phase2_vid}")
|
| 702 |
+
log_info(f"output transition merged video: {self.merged_vid}")
|
| 703 |
+
else:
|
| 704 |
+
log_info(f"output transition phase1 video: {self.phase1_vid}")
|
| 705 |
+
log_info(f"output transition phase2 video: {self.phase2_vid}")
|
| 706 |
+
self._get_fps_from_video()
|
| 707 |
+
log_info(f"frames per second (FPS): {self.fps}")
|
| 708 |
+
|
| 709 |
+
self.vid1_raw_images_folder = self.tmp_path / "1_phase1_raw"
|
| 710 |
+
self.vid2_raw_images_folder = self.tmp_path / "1_phase2_raw"
|
| 711 |
+
self.vid1_raw_images_folder.mkdir()
|
| 712 |
+
log_debug(f"created vid1_raw_images_folder: {self.vid1_raw_images_folder}")
|
| 713 |
+
self.vid2_raw_images_folder.mkdir()
|
| 714 |
+
log_debug(f"created vid2_raw_images_folder: {self.vid2_raw_images_folder}")
|
| 715 |
+
if not self._extract_phase1_images(in_args.num_frames):
|
| 716 |
+
return False
|
| 717 |
+
num_frames_for_vid2 = in_args.num_frames
|
| 718 |
+
if self.animation == Animations.long_translation or self.animation == Animations.long_translation_inv:
|
| 719 |
+
num_frames_for_vid2 = 2 * in_args.num_frames
|
| 720 |
+
if not self._extract_phase2_images(num_frames_for_vid2):
|
| 721 |
+
return False
|
| 722 |
+
log_info(f"number of frames for phase1: [{len(self.phase1_images)}], for phase2: [{len(self.phase2_images)}]")
|
| 723 |
+
return True
|
| 724 |
+
|
| 725 |
+
def final_images_to_video(self, res_folders):
|
| 726 |
+
output_videos = [self.phase1_vid, self.phase2_vid]
|
| 727 |
+
fps = str(self.fps)
|
| 728 |
+
for idx in range(2):
|
| 729 |
+
log_info(f"merging phase_{idx} images into a video ...")
|
| 730 |
+
img_names = [f.stem for f in res_folders[idx].glob("*.png")]
|
| 731 |
+
img_names.sort()
|
| 732 |
+
start_idx = f"{max(int(img_names[0]) - 1, 0):04d}"
|
| 733 |
+
cmd = ["ffmpeg", "-hide_banner", "-start_number", start_idx, "-framerate", fps, "-y", "-r", fps, "-i",
|
| 734 |
+
str(res_folders[idx] / "%04d.png"), "-r", fps, "-vcodec", _OUTPUT_VIDEO_CODEC,
|
| 735 |
+
str(output_videos[idx])]
|
| 736 |
+
self._exec_command(cmd, f"command used for merging phase_{idx} images into a video ...")
|
| 737 |
+
if not output_videos[idx].is_file():
|
| 738 |
+
log_error(f"ffmpeg failed to convert images to: {output_videos[idx]}")
|
| 739 |
+
return False
|
| 740 |
+
return True
|
| 741 |
+
|
| 742 |
+
def _verify_critical_info(self, in_args):
|
| 743 |
+
if shutil.which("ffmpeg") is None:
|
| 744 |
+
log_error("'ffmpeg' is not installed, please install it before use")
|
| 745 |
+
return False
|
| 746 |
+
if len(in_args.input) < 2 or len(in_args.input) > 2:
|
| 747 |
+
log_error(f"2 input videos needed, [{len(in_args.input)}] provided")
|
| 748 |
+
return False
|
| 749 |
+
self.input_vid1 = pathlib.Path(in_args.input[0])
|
| 750 |
+
if not self.input_vid1.is_file():
|
| 751 |
+
log_error(f"could not find first video under: {self.input_vid1}")
|
| 752 |
+
return False
|
| 753 |
+
self.input_vid2 = pathlib.Path(in_args.input[1])
|
| 754 |
+
if not self.input_vid2.is_file():
|
| 755 |
+
log_error(f"could not find second video under: {self.input_vid2}")
|
| 756 |
+
return False
|
| 757 |
+
if in_args.num_frames < 2 or in_args.num_frames > 100:
|
| 758 |
+
log_error(f"number of frames per phase should be in the range [2, 100] (provided: [{in_args.num_frames}])")
|
| 759 |
+
return False
|
| 760 |
+
for animation_enum in Animations:
|
| 761 |
+
# print(f"{in_args.animation.lower().strip()} <-> {animation_enum.name}")
|
| 762 |
+
if in_args.animation.lower().strip() == animation_enum.name:
|
| 763 |
+
self.animation = animation_enum
|
| 764 |
+
break
|
| 765 |
+
if self.animation is None:
|
| 766 |
+
log_error(f"animation provided [{in_args.animation}] not recognized, please use one of the "
|
| 767 |
+
f"following animations:")
|
| 768 |
+
log_info(_ANIMATION_HELP)
|
| 769 |
+
return False
|
| 770 |
+
return True
|
| 771 |
+
|
| 772 |
+
def _extract_phase1_images(self, in_num_frames):
|
| 773 |
+
duration_ms = int(math.ceil(1000 * (in_num_frames + 2) / self.fps))
|
| 774 |
+
cmd = ["ffmpeg", "-hide_banner", "-sseof", f"-{duration_ms}ms", "-i", str(self.input_vid1),
|
| 775 |
+
str(self.vid1_raw_images_folder / "%04d.png")]
|
| 776 |
+
self._exec_command(cmd, "command used for extracting images from video num 1:")
|
| 777 |
+
for img_f in self.vid1_raw_images_folder.glob("*.png"):
|
| 778 |
+
self.phase1_images.append(img_f)
|
| 779 |
+
self.phase1_images.sort()
|
| 780 |
+
if len(self.phase1_images) < in_num_frames:
|
| 781 |
+
log_error(f"could not extract [{in_num_frames}] images from the first video "
|
| 782 |
+
f"({len(self.phase1_images)} extracted)")
|
| 783 |
+
return False
|
| 784 |
+
if len(self.phase1_images) > in_num_frames:
|
| 785 |
+
self.phase1_images = self.phase1_images[-in_num_frames:]
|
| 786 |
+
return True
|
| 787 |
+
|
| 788 |
+
def _extract_phase2_images(self, in_num_frames):
|
| 789 |
+
duration_ms = int(math.ceil(1000 * (in_num_frames + 2) / self.fps))
|
| 790 |
+
cmd = ["ffmpeg", "-hide_banner", "-to", f"{duration_ms}ms", "-i", str(self.input_vid2),
|
| 791 |
+
str(self.vid2_raw_images_folder / "%04d.png")]
|
| 792 |
+
self._exec_command(cmd, "command used for extracting images from video num 2:")
|
| 793 |
+
for img_f in self.vid2_raw_images_folder.glob("*.png"):
|
| 794 |
+
self.phase2_images.append(img_f)
|
| 795 |
+
self.phase2_images.sort()
|
| 796 |
+
if len(self.phase2_images) < in_num_frames:
|
| 797 |
+
log_error(f"could not extract [{in_num_frames}] images from the second video "
|
| 798 |
+
f"({len(self.phase2_images)} extracted)")
|
| 799 |
+
return False
|
| 800 |
+
if len(self.phase2_images) > in_num_frames:
|
| 801 |
+
self.phase2_images = self.phase2_images[:in_num_frames]
|
| 802 |
+
return True
|
| 803 |
+
|
| 804 |
+
@staticmethod
|
| 805 |
+
def _exec_command(in_cmd, in_presentation):
|
| 806 |
+
log_debug("")
|
| 807 |
+
log_debug(in_presentation)
|
| 808 |
+
log_debug("")
|
| 809 |
+
log_debug(" ".join(in_cmd))
|
| 810 |
+
res = subprocess.run(in_cmd, capture_output=True, text=True)
|
| 811 |
+
log_debug("")
|
| 812 |
+
log_debug("")
|
| 813 |
+
log_debug("stdout:")
|
| 814 |
+
log_debug("")
|
| 815 |
+
log_debug(res.stdout)
|
| 816 |
+
log_debug("")
|
| 817 |
+
log_debug("stderr:")
|
| 818 |
+
log_debug("")
|
| 819 |
+
log_debug(res.stderr)
|
| 820 |
+
log_debug("")
|
| 821 |
+
log_debug("")
|
| 822 |
+
return res.stdout, res.stderr
|
| 823 |
+
|
| 824 |
+
def _get_fps_from_video(self):
|
| 825 |
+
cmd = ["ffmpeg", "-hide_banner", "-i", str(self.input_vid1)]
|
| 826 |
+
stdout, stderr = self._exec_command(cmd, "command used for extracting FPS")
|
| 827 |
+
res = (stdout.lower() + " " + stderr.lower()).split(" ")
|
| 828 |
+
log_debug("searching for FPS value in ffmpeg video information")
|
| 829 |
+
for fps_word in ["fps", "fps,"]:
|
| 830 |
+
for idx, word in enumerate(res):
|
| 831 |
+
if word == fps_word:
|
| 832 |
+
try:
|
| 833 |
+
self.fps = int(res[idx - 1])
|
| 834 |
+
log_debug(f"FPS extracted from video [{self.fps}]")
|
| 835 |
+
return
|
| 836 |
+
except ValueError:
|
| 837 |
+
log_debug(f"failed extract FPS, value [{res[idx - 1]}], error :[{ValueError}]")
|
| 838 |
+
|
| 839 |
+
log_warning(f"cloud not retrieve FPS value from video (using ffmpeg): {self.input_vid1}")
|
| 840 |
+
log_warning("falling back to FPS value of [30]")
|
| 841 |
+
self.fps = 30
|
| 842 |
+
|
| 843 |
+
def get_duration_msg(self):
|
| 844 |
+
end_time = datetime.datetime.now()
|
| 845 |
+
t_delta = end_time - self.start_time
|
| 846 |
+
seconds = int(t_delta.total_seconds())
|
| 847 |
+
days, seconds = divmod(seconds, 86400)
|
| 848 |
+
hours, seconds = divmod(seconds, 3600)
|
| 849 |
+
minutes, seconds = divmod(seconds, 60)
|
| 850 |
+
if days > 0:
|
| 851 |
+
return '%d d %d h %d m %d s' % (days, hours, minutes, seconds)
|
| 852 |
+
elif hours > 0:
|
| 853 |
+
return '%d h %d m %d s' % (hours, minutes, seconds)
|
| 854 |
+
elif minutes > 0:
|
| 855 |
+
return '%d m %d s' % (minutes, seconds)
|
| 856 |
+
else:
|
| 857 |
+
return '%d s' % (seconds,)
|
| 858 |
+
|
| 859 |
+
def _suggest_output(self, in_output):
|
| 860 |
+
# self.output = pathlib.Path().cwd() / "vt_debug"
|
| 861 |
+
# return
|
| 862 |
+
if in_output != "":
|
| 863 |
+
out_path = pathlib.Path(in_output)
|
| 864 |
+
self.output = out_path.parent / out_path.stem
|
| 865 |
+
return
|
| 866 |
+
cur_dir = pathlib.Path().cwd()
|
| 867 |
+
video_files = [f.name for f in cur_dir.glob("*" + _OUTPUT_VIDEO_TYPE)]
|
| 868 |
+
num = 1
|
| 869 |
+
previous_num = 0
|
| 870 |
+
while previous_num != num:
|
| 871 |
+
previous_num = num
|
| 872 |
+
for vn in video_files:
|
| 873 |
+
if vn.startswith(f"vt{num}_"):
|
| 874 |
+
num += 1
|
| 875 |
+
self.output = cur_dir / f"vt{num}"
|
| 876 |
+
|
| 877 |
+
def merge_video_chunks(self): # TODO implement
|
| 878 |
+
log_info("merging the two phases video chunks into one transition video")
|
| 879 |
+
cmd = ["ffmpeg", "-hide_banner", "-i", str(self.phase1_vid), "-i", str(self.phase2_vid),
|
| 880 |
+
"-filter_complex", "[0:v] [1:v] concat=n=2:v=1 [v]", "-map", "[v]", str(self.merged_vid)]
|
| 881 |
+
self._exec_command(cmd, f"command used for merging phase video chunks into the output video ...")
|
| 882 |
+
|
| 883 |
+
if not self.merged_vid.is_file():
|
| 884 |
+
log_error(f"ffmpeg failed to merge video phases into: {self.merged_vid}")
|
| 885 |
+
return False
|
| 886 |
+
|
| 887 |
+
log_debug(f"remove output video phase1: {self.phase1_vid}")
|
| 888 |
+
self.phase1_vid.unlink(missing_ok=True)
|
| 889 |
+
log_debug(f"remove output video phase2: {self.phase2_vid}")
|
| 890 |
+
self.phase2_vid.unlink(missing_ok=True)
|
| 891 |
+
return True
|
| 892 |
+
|
| 893 |
+
@staticmethod
|
| 894 |
+
def _setup_logging(debug, log_file_path):
|
| 895 |
+
init_logger = logging.getLogger(__package__)
|
| 896 |
+
if debug:
|
| 897 |
+
init_logger.setLevel(logging.DEBUG)
|
| 898 |
+
else:
|
| 899 |
+
init_logger.setLevel(logging.INFO)
|
| 900 |
+
i_formatter = logging.Formatter('%(message)s')
|
| 901 |
+
ch = logging.StreamHandler()
|
| 902 |
+
ch.setFormatter(i_formatter)
|
| 903 |
+
init_logger.addHandler(ch)
|
| 904 |
+
if debug:
|
| 905 |
+
handler = logging.FileHandler(str(log_file_path), encoding='utf8')
|
| 906 |
+
n_formatter = logging.Formatter('[%(levelname)s] [%(asctime)s] - %(message)s', "%H:%M:%S")
|
| 907 |
+
handler.setFormatter(n_formatter)
|
| 908 |
+
handler.setLevel(logging.DEBUG)
|
| 909 |
+
init_logger.addHandler(handler)
|
| 910 |
+
|
| 911 |
+
|
| 912 |
+
def str2bool(v):
|
| 913 |
+
if isinstance(v, bool):
|
| 914 |
+
return v
|
| 915 |
+
if v.lower() in ('yes', 'true', 't', 'y', '1'):
|
| 916 |
+
return True
|
| 917 |
+
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
|
| 918 |
+
return False
|
| 919 |
+
else:
|
| 920 |
+
raise argparse.ArgumentTypeError('Boolean value expected, possible values: yes, y, true, 1, no, n, false, 0.')
|
| 921 |
+
|
| 922 |
+
|
| 923 |
+
if __name__ == "__main__":
|
| 924 |
+
all_animation_names = ", ".join([animation_enum.name for animation_enum in Animations])
|
| 925 |
+
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 926 |
+
description='make a transition animation between two videos, using the last part '
|
| 927 |
+
'of the first video, and the first part of the second video')
|
| 928 |
+
parser.add_argument('-i', '--input', help='input videos, must be two', type=str, nargs='+', metavar='\b',
|
| 929 |
+
default=INPUT_VIDEOS)
|
| 930 |
+
parser.add_argument('-n', '--num_frames', help='the number of frames used for each animation phase, '
|
| 931 |
+
'most animations consists of two phases',
|
| 932 |
+
type=int, default=NUM_FRAMES, metavar='\b')
|
| 933 |
+
parser.add_argument('-a', '--animation', help=f'possible animations (use -a help to show more info): '
|
| 934 |
+
f'{all_animation_names} ',
|
| 935 |
+
type=str, default=ANIMATION, metavar='\b')
|
| 936 |
+
parser.add_argument('-o', '--output', help='the name of the output (determined automatically if left empty), '
|
| 937 |
+
'FPS is copied from the first video.',
|
| 938 |
+
type=str, default=OUTPUT, metavar='\b')
|
| 939 |
+
parser.add_argument('-r', '--max_rotation', help=f'rotation (in degree) value at the midpoint of the animation, '
|
| 940 |
+
f'possible range {list(_LIMITS["rotation"])}',
|
| 941 |
+
type=int, default=MAX_ROTATION, metavar='\b')
|
| 942 |
+
parser.add_argument('-d', '--max_distortion', help=f'lens distortion value at the midpoint of the animation'
|
| 943 |
+
f'(in percentage), possible range {list(_LIMITS["distortion"])}',
|
| 944 |
+
type=float, default=MAX_DISTORTION, metavar='\b')
|
| 945 |
+
parser.add_argument('-b', '--max_blur', help=f'gaussian blur value at the midpoint of the animation, '
|
| 946 |
+
f'(in percentage), possible range {list(_LIMITS["blur"])}',
|
| 947 |
+
type=float, default=MAX_BLUR, metavar='\b')
|
| 948 |
+
parser.add_argument('-s', '--max_brightness', help=f'brightness value at the midpoint of the animation, '
|
| 949 |
+
f'(in percentage), possible range {list(_LIMITS["brightness"])}',
|
| 950 |
+
type=float, default=MAX_BRIGHTNESS, metavar='\b')
|
| 951 |
+
parser.add_argument('-z', '--max_zoom', help=f'zoom value at the midpoint of the animation, '
|
| 952 |
+
f'(in percentage), possible range {list(_LIMITS["zoom"])}',
|
| 953 |
+
type=float, default=MAX_ZOOM, metavar='\b')
|
| 954 |
+
parser.add_argument('-g', '--debug', help='this will show more info, will create a logs file, '
|
| 955 |
+
'and will create a folder which contains animation images',
|
| 956 |
+
type=str2bool, default=DEBUG, metavar='\b')
|
| 957 |
+
parser.add_argument('-t', '--art', help='Display ASCII art', type=str2bool, default=ART, metavar='\b')
|
| 958 |
+
parser.add_argument('-e', '--remove', help='delete original videos after a successful animation creation',
|
| 959 |
+
type=str2bool, default=REMOVE_ORIGINAL, metavar='\b')
|
| 960 |
+
parser.add_argument('-m', '--merge', help='merge both phases video chunks into one transition video',
|
| 961 |
+
type=str2bool, default=MERGE_PHASES, metavar='\b')
|
| 962 |
+
args = parser.parse_args()
|
| 963 |
+
|
| 964 |
+
if args.animation.lower() == "help":
|
| 965 |
+
print(_ANIMATION_HELP)
|
| 966 |
+
exit(0)
|
| 967 |
+
|
| 968 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 969 |
+
tmp_path = pathlib.Path(tmp_dir)
|
| 970 |
+
dh = DataHandler()
|
| 971 |
+
if not dh.verify_arguments(args, tmp_path):
|
| 972 |
+
exit(1)
|
| 973 |
+
|
| 974 |
+
actions_determinator = AnimationActions(args.max_zoom, args.max_brightness, args.max_rotation, args.max_blur,
|
| 975 |
+
args.max_distortion, args.num_frames)
|
| 976 |
+
|
| 977 |
+
phase1_actions, phase2_actions = actions_determinator.get_actions_values(dh.animation)
|
| 978 |
+
|
| 979 |
+
final_phase_folder = AnimationImages.make_transition(dh.tmp_path, dh.phase1_images, dh.phase2_images,
|
| 980 |
+
phase1_actions, phase2_actions, args.debug)
|
| 981 |
+
|
| 982 |
+
if not dh.final_images_to_video(final_phase_folder):
|
| 983 |
+
exit(1)
|
| 984 |
+
if args.merge:
|
| 985 |
+
if not dh.merge_video_chunks():
|
| 986 |
+
exit(1)
|
| 987 |
+
log_info(f"output transition video: {dh.merged_vid}")
|
| 988 |
+
else:
|
| 989 |
+
log_info(f"output transition phase1 video: {dh.phase1_vid}")
|
| 990 |
+
log_info(f"output transition phase2 video: {dh.phase2_vid}")
|
| 991 |
+
if args.remove:
|
| 992 |
+
log_debug(f"remove original video1: {dh.input_vid1}")
|
| 993 |
+
dh.input_vid1.unlink()
|
| 994 |
+
log_debug(f"remove original video2: {dh.input_vid2}")
|
| 995 |
+
dh.input_vid2.unlink()
|
| 996 |
+
log_info("")
|
| 997 |
+
log_info((f" Transition finished. Duration = {dh.get_duration_msg()} ".center(80, "=")))
|
| 998 |
+
log_info("")
|
| 999 |
+
end_print(args.art)
|
| 1000 |
+
exit(0)
|