2020-11-18 10:44:18 +08:00
|
|
|
import os
|
|
|
|
|
import cv2
|
|
|
|
|
import torch
|
|
|
|
|
import argparse
|
|
|
|
|
import numpy as np
|
|
|
|
|
from tqdm import tqdm
|
|
|
|
|
from torch.nn import functional as F
|
2020-11-20 12:23:56 +08:00
|
|
|
import warnings
|
2020-11-20 19:08:47 +08:00
|
|
|
import _thread
|
2020-11-22 14:41:07 +08:00
|
|
|
import skvideo.io
|
2020-11-22 19:39:03 +08:00
|
|
|
from queue import Queue, Empty
|
2021-01-18 17:40:44 +08:00
|
|
|
from benchmark.pytorch_msssim import ssim_matlab
|
|
|
|
|
|
2020-12-02 17:51:42 +08:00
|
|
|
warnings.filterwarnings("ignore")
|
2020-11-25 02:10:31 -04:00
|
|
|
|
2021-01-18 17:40:44 +08:00
|
|
|
def transferAudio(sourceVideo, targetVideo):
|
2020-12-03 18:59:50 +08:00
|
|
|
import shutil
|
|
|
|
|
import moviepy.editor
|
2020-12-14 17:58:48 +13:00
|
|
|
tempAudioFileName = "./temp/audio.mkv"
|
2020-12-09 17:45:28 -04:00
|
|
|
|
|
|
|
|
# split audio from original video file and store in "temp" directory
|
|
|
|
|
if True:
|
2021-04-23 16:32:04 +09:00
|
|
|
|
2020-12-09 17:45:28 -04:00
|
|
|
# clear old "temp" directory if it exits
|
|
|
|
|
if os.path.isdir("temp"):
|
|
|
|
|
# remove temp directory
|
|
|
|
|
shutil.rmtree("temp")
|
|
|
|
|
# create new "temp" directory
|
|
|
|
|
os.makedirs("temp")
|
2020-12-14 17:58:48 +13:00
|
|
|
# extract audio from video
|
2021-03-14 22:12:11 -07:00
|
|
|
os.system('ffmpeg -y -i "{}" -c:a copy -vn {}'.format(sourceVideo, tempAudioFileName))
|
2021-04-23 16:32:04 +09:00
|
|
|
|
2021-01-17 17:34:48 +01:00
|
|
|
targetNoAudio = os.path.splitext(targetVideo)[0] + "_noaudio" + os.path.splitext(targetVideo)[1]
|
|
|
|
|
os.rename(targetVideo, targetNoAudio)
|
2020-12-09 17:45:28 -04:00
|
|
|
# combine audio file and new video file
|
2021-03-14 22:12:11 -07:00
|
|
|
os.system('ffmpeg -y -i "{}" -i {} -c copy "{}"'.format(targetNoAudio, tempAudioFileName, targetVideo))
|
2021-04-23 16:32:04 +09:00
|
|
|
|
2021-01-11 12:16:24 +01:00
|
|
|
if os.path.getsize(targetVideo) == 0: # if ffmpeg failed to merge the video and audio together try converting the audio to aac
|
|
|
|
|
tempAudioFileName = "./temp/audio.m4a"
|
2021-03-14 22:12:11 -07:00
|
|
|
os.system('ffmpeg -y -i "{}" -c:a aac -b:a 160k -vn {}'.format(sourceVideo, tempAudioFileName))
|
|
|
|
|
os.system('ffmpeg -y -i "{}" -i {} -c copy "{}"'.format(targetNoAudio, tempAudioFileName, targetVideo))
|
2021-01-11 12:16:24 +01:00
|
|
|
if (os.path.getsize(targetVideo) == 0): # if aac is not supported by selected format
|
2021-01-17 17:34:48 +01:00
|
|
|
os.rename(targetNoAudio, targetVideo)
|
2020-12-14 23:06:00 +13:00
|
|
|
print("Audio transfer failed. Interpolated video will have no audio")
|
|
|
|
|
else:
|
2021-01-11 12:16:24 +01:00
|
|
|
print("Lossless audio transfer failed. Audio was transcoded to AAC (M4A) instead.")
|
2021-04-23 16:32:04 +09:00
|
|
|
|
2020-12-14 23:06:00 +13:00
|
|
|
# remove audio-less video
|
2021-01-17 17:34:48 +01:00
|
|
|
os.remove(targetNoAudio)
|
2020-12-14 23:06:00 +13:00
|
|
|
else:
|
2021-01-17 17:34:48 +01:00
|
|
|
os.remove(targetNoAudio)
|
2020-12-09 17:45:28 -04:00
|
|
|
|
2020-11-25 02:10:31 -04:00
|
|
|
# remove temp directory
|
|
|
|
|
shutil.rmtree("temp")
|
|
|
|
|
|
2020-11-18 10:44:18 +08:00
|
|
|
parser = argparse.ArgumentParser(description='Interpolation for a pair of images')
|
2020-12-03 18:04:13 +08:00
|
|
|
parser.add_argument('--video', dest='video', type=str, default=None)
|
2021-01-17 15:24:57 +01:00
|
|
|
parser.add_argument('--output', dest='output', type=str, default=None)
|
2020-12-03 18:04:13 +08:00
|
|
|
parser.add_argument('--img', dest='img', type=str, default=None)
|
2020-11-18 10:44:18 +08:00
|
|
|
parser.add_argument('--montage', dest='montage', action='store_true', help='montage origin video')
|
2021-02-25 08:31:06 +01:00
|
|
|
parser.add_argument('--model', dest='modelDir', type=str, default='train_log', help='directory with trained model files')
|
2021-02-24 20:11:24 +01:00
|
|
|
parser.add_argument('--fp16', dest='fp16', action='store_true', help='fp16 mode for faster and more lightweight inference on cards with Tensor Cores')
|
2020-12-13 23:41:36 +08:00
|
|
|
parser.add_argument('--UHD', dest='UHD', action='store_true', help='support 4k video')
|
2021-02-27 16:57:47 +08:00
|
|
|
parser.add_argument('--scale', dest='scale', type=float, default=1.0, help='Try scale=0.5 for 4k video')
|
2020-11-18 10:44:18 +08:00
|
|
|
parser.add_argument('--skip', dest='skip', action='store_true', help='whether to remove static frames before processing')
|
|
|
|
|
parser.add_argument('--fps', dest='fps', type=int, default=None)
|
2020-11-20 19:08:47 +08:00
|
|
|
parser.add_argument('--png', dest='png', action='store_true', help='whether to vid_out png format vid_outs')
|
|
|
|
|
parser.add_argument('--ext', dest='ext', type=str, default='mp4', help='vid_out video extension')
|
2020-11-19 11:07:37 +08:00
|
|
|
parser.add_argument('--exp', dest='exp', type=int, default=1)
|
2020-11-18 10:44:18 +08:00
|
|
|
args = parser.parse_args()
|
2020-12-03 18:04:13 +08:00
|
|
|
assert (not args.video is None or not args.img is None)
|
2021-02-27 17:34:20 +08:00
|
|
|
if args.UHD and args.scale==1.0:
|
|
|
|
|
args.scale = 0.5
|
2021-02-27 16:57:47 +08:00
|
|
|
assert args.scale in [0.25, 0.5, 1.0, 2.0, 4.0]
|
2020-12-03 18:04:13 +08:00
|
|
|
if not args.img is None:
|
|
|
|
|
args.png = True
|
2021-04-23 16:32:04 +09:00
|
|
|
|
2021-02-24 20:11:24 +01:00
|
|
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
|
|
torch.set_grad_enabled(False)
|
|
|
|
|
if torch.cuda.is_available():
|
|
|
|
|
torch.backends.cudnn.enabled = True
|
|
|
|
|
torch.backends.cudnn.benchmark = True
|
|
|
|
|
if(args.fp16):
|
|
|
|
|
torch.set_default_tensor_type(torch.cuda.HalfTensor)
|
2020-11-18 10:44:18 +08:00
|
|
|
|
2021-02-25 08:31:06 +01:00
|
|
|
try:
|
2021-05-13 16:58:13 +08:00
|
|
|
try:
|
|
|
|
|
from model.RIFE_HDv2 import Model
|
|
|
|
|
model = Model()
|
|
|
|
|
model.load_model(args.modelDir, -1)
|
|
|
|
|
print("Loaded v2.x HD model.")
|
|
|
|
|
except:
|
2021-05-15 16:55:28 +08:00
|
|
|
from train_log.RIFE_HDv3 import Model
|
2021-05-13 16:58:13 +08:00
|
|
|
model = Model()
|
|
|
|
|
model.load_model(args.modelDir, -1)
|
|
|
|
|
print("Loaded v3.x HD model.")
|
2021-02-25 08:31:06 +01:00
|
|
|
except:
|
|
|
|
|
from model.RIFE_HD import Model
|
|
|
|
|
model = Model()
|
2021-02-25 09:03:32 +01:00
|
|
|
model.load_model(args.modelDir, -1)
|
2021-02-25 08:31:06 +01:00
|
|
|
print("Loaded v1.x HD model")
|
2020-11-18 10:44:18 +08:00
|
|
|
model.eval()
|
|
|
|
|
model.device()
|
|
|
|
|
|
2020-12-03 18:04:13 +08:00
|
|
|
if not args.video is None:
|
|
|
|
|
videoCapture = cv2.VideoCapture(args.video)
|
|
|
|
|
fps = videoCapture.get(cv2.CAP_PROP_FPS)
|
|
|
|
|
tot_frame = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)
|
|
|
|
|
videoCapture.release()
|
|
|
|
|
if args.fps is None:
|
|
|
|
|
fpsNotAssigned = True
|
2020-12-03 20:17:20 +08:00
|
|
|
args.fps = fps * (2 ** args.exp)
|
2020-12-03 18:04:13 +08:00
|
|
|
else:
|
|
|
|
|
fpsNotAssigned = False
|
|
|
|
|
videogen = skvideo.io.vreader(args.video)
|
|
|
|
|
lastframe = next(videogen)
|
|
|
|
|
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
|
|
|
|
|
video_path_wo_ext, ext = os.path.splitext(args.video)
|
|
|
|
|
print('{}.{}, {} frames in total, {}FPS to {}FPS'.format(video_path_wo_ext, args.ext, tot_frame, fps, args.fps))
|
2020-12-03 18:59:50 +08:00
|
|
|
if args.png == False and fpsNotAssigned == True and not args.skip:
|
|
|
|
|
print("The audio will be merged after interpolation process")
|
|
|
|
|
else:
|
|
|
|
|
print("Will not merge audio because using png, fps or skip flag!")
|
2020-11-25 02:10:31 -04:00
|
|
|
else:
|
2020-12-03 18:04:13 +08:00
|
|
|
videogen = []
|
|
|
|
|
for f in os.listdir(args.img):
|
|
|
|
|
if 'png' in f:
|
|
|
|
|
videogen.append(f)
|
|
|
|
|
tot_frame = len(videogen)
|
|
|
|
|
videogen.sort(key= lambda x:int(x[:-4]))
|
2021-06-16 11:31:29 +08:00
|
|
|
lastframe = cv2.imread(os.path.join(args.img, videogen[0]), cv2.IMREAD_UNCHANGED)[:, :, ::-1].copy()
|
2021-01-18 17:40:44 +08:00
|
|
|
videogen = videogen[1:]
|
2020-11-22 14:41:07 +08:00
|
|
|
h, w, _ = lastframe.shape
|
2021-01-17 15:24:57 +01:00
|
|
|
vid_out_name = None
|
2020-12-03 18:04:13 +08:00
|
|
|
vid_out = None
|
2020-11-18 10:44:18 +08:00
|
|
|
if args.png:
|
2020-11-20 19:08:47 +08:00
|
|
|
if not os.path.exists('vid_out'):
|
|
|
|
|
os.mkdir('vid_out')
|
2020-11-18 10:44:18 +08:00
|
|
|
else:
|
2021-01-17 15:24:57 +01:00
|
|
|
if args.output is not None:
|
|
|
|
|
vid_out_name = args.output
|
|
|
|
|
else:
|
|
|
|
|
vid_out_name = '{}_{}X_{}fps.{}'.format(video_path_wo_ext, (2 ** args.exp), int(np.round(args.fps)), args.ext)
|
|
|
|
|
vid_out = cv2.VideoWriter(vid_out_name, fourcc, args.fps, (w, h))
|
2021-04-23 16:32:04 +09:00
|
|
|
|
2020-12-05 00:31:33 +08:00
|
|
|
def clear_write_buffer(user_args, write_buffer):
|
2020-11-22 19:39:03 +08:00
|
|
|
cnt = 0
|
2020-11-22 10:32:13 +08:00
|
|
|
while True:
|
2020-12-05 00:31:33 +08:00
|
|
|
item = write_buffer.get()
|
2020-11-23 11:49:08 +08:00
|
|
|
if item is None:
|
|
|
|
|
break
|
2020-11-20 19:08:47 +08:00
|
|
|
if user_args.png:
|
2020-11-22 14:41:07 +08:00
|
|
|
cv2.imwrite('vid_out/{:0>7d}.png'.format(cnt), item[:, :, ::-1])
|
2020-11-20 19:45:08 +08:00
|
|
|
cnt += 1
|
2020-11-20 19:08:47 +08:00
|
|
|
else:
|
2020-11-22 14:41:07 +08:00
|
|
|
vid_out.write(item[:, :, ::-1])
|
2020-12-03 20:17:20 +08:00
|
|
|
|
2020-12-05 00:31:33 +08:00
|
|
|
def build_read_buffer(user_args, read_buffer, videogen):
|
2021-02-12 16:56:53 +08:00
|
|
|
try:
|
|
|
|
|
for frame in videogen:
|
|
|
|
|
if not user_args.img is None:
|
|
|
|
|
frame = cv2.imread(os.path.join(user_args.img, frame))[:, :, ::-1].copy()
|
|
|
|
|
if user_args.montage:
|
|
|
|
|
frame = frame[:, left: left + w]
|
|
|
|
|
read_buffer.put(frame)
|
|
|
|
|
except:
|
|
|
|
|
pass
|
2020-12-05 00:31:33 +08:00
|
|
|
read_buffer.put(None)
|
|
|
|
|
|
2021-04-18 21:39:32 -04:00
|
|
|
def make_inference(I0, I1, n):
|
2020-12-03 20:17:20 +08:00
|
|
|
global model
|
2021-02-27 16:57:47 +08:00
|
|
|
middle = model.inference(I0, I1, args.scale)
|
2021-04-18 21:39:32 -04:00
|
|
|
if n == 1:
|
2020-12-03 20:17:20 +08:00
|
|
|
return [middle]
|
2021-04-18 21:39:32 -04:00
|
|
|
first_half = make_inference(I0, middle, n=n//2)
|
|
|
|
|
second_half = make_inference(middle, I1, n=n//2)
|
|
|
|
|
if n%2:
|
|
|
|
|
return [*first_half, middle, *second_half]
|
|
|
|
|
else:
|
|
|
|
|
return [*first_half, *second_half]
|
2021-04-23 16:32:04 +09:00
|
|
|
|
2021-02-24 20:11:24 +01:00
|
|
|
def pad_image(img):
|
|
|
|
|
if(args.fp16):
|
|
|
|
|
return F.pad(img, padding).half()
|
|
|
|
|
else:
|
|
|
|
|
return F.pad(img, padding)
|
|
|
|
|
|
2020-11-18 10:44:18 +08:00
|
|
|
if args.montage:
|
|
|
|
|
left = w // 4
|
|
|
|
|
w = w // 2
|
2021-02-27 16:57:47 +08:00
|
|
|
tmp = max(32, int(32 / args.scale))
|
|
|
|
|
ph = ((h - 1) // tmp + 1) * tmp
|
|
|
|
|
pw = ((w - 1) // tmp + 1) * tmp
|
2020-11-18 10:44:18 +08:00
|
|
|
padding = (0, pw - w, 0, ph - h)
|
|
|
|
|
pbar = tqdm(total=tot_frame)
|
|
|
|
|
skip_frame = 1
|
|
|
|
|
if args.montage:
|
2020-11-22 14:44:27 +08:00
|
|
|
lastframe = lastframe[:, left: left + w]
|
2020-12-05 00:37:44 +08:00
|
|
|
write_buffer = Queue(maxsize=500)
|
|
|
|
|
read_buffer = Queue(maxsize=500)
|
2020-12-05 00:31:33 +08:00
|
|
|
_thread.start_new_thread(build_read_buffer, (args, read_buffer, videogen))
|
|
|
|
|
_thread.start_new_thread(clear_write_buffer, (args, write_buffer))
|
2020-12-03 18:04:13 +08:00
|
|
|
|
2020-12-05 11:20:58 +08:00
|
|
|
I1 = torch.from_numpy(np.transpose(lastframe, (2,0,1))).to(device, non_blocking=True).unsqueeze(0).float() / 255.
|
2021-02-24 20:11:24 +01:00
|
|
|
I1 = pad_image(I1)
|
2021-04-18 21:39:32 -04:00
|
|
|
|
2020-12-05 00:31:33 +08:00
|
|
|
while True:
|
|
|
|
|
frame = read_buffer.get()
|
|
|
|
|
if frame is None:
|
|
|
|
|
break
|
2020-12-05 11:20:58 +08:00
|
|
|
I0 = I1
|
2020-11-22 14:41:07 +08:00
|
|
|
I1 = torch.from_numpy(np.transpose(frame, (2,0,1))).to(device, non_blocking=True).unsqueeze(0).float() / 255.
|
2021-02-24 20:11:24 +01:00
|
|
|
I1 = pad_image(I1)
|
2021-01-18 17:40:44 +08:00
|
|
|
I0_small = F.interpolate(I0, (32, 32), mode='bilinear', align_corners=False)
|
|
|
|
|
I1_small = F.interpolate(I1, (32, 32), mode='bilinear', align_corners=False)
|
|
|
|
|
ssim = ssim_matlab(I0_small, I1_small)
|
2021-04-18 21:39:32 -04:00
|
|
|
|
|
|
|
|
if ssim > 0.995:
|
2020-11-22 14:41:07 +08:00
|
|
|
if skip_frame % 100 == 0:
|
2021-04-18 21:39:32 -04:00
|
|
|
print("\nWarning: Your video has {} static frames, skipping them may change the duration of the generated video.".format(skip_frame))
|
2020-11-22 14:41:07 +08:00
|
|
|
skip_frame += 1
|
2021-04-23 16:32:04 +09:00
|
|
|
if args.skip:
|
|
|
|
|
pbar.update(1)
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
if ssim < 0.5:
|
|
|
|
|
output = []
|
|
|
|
|
step = 1 / (2 ** args.exp)
|
|
|
|
|
alpha = 0
|
|
|
|
|
for i in range((2 ** args.exp) - 1):
|
|
|
|
|
alpha += step
|
|
|
|
|
beta = 1-alpha
|
|
|
|
|
output.append(torch.from_numpy(np.transpose((cv2.addWeighted(frame[:, :, ::-1], alpha, lastframe[:, :, ::-1], beta, 0)[:, :, ::-1].copy()), (2,0,1))).to(device, non_blocking=True).unsqueeze(0).float() / 255.)
|
2020-11-22 14:41:07 +08:00
|
|
|
else:
|
2021-04-23 16:32:04 +09:00
|
|
|
output = make_inference(I0, I1, 2**args.exp-1) if args.exp else []
|
2021-04-18 21:39:32 -04:00
|
|
|
|
2020-11-22 14:41:07 +08:00
|
|
|
if args.montage:
|
2020-12-05 00:31:33 +08:00
|
|
|
write_buffer.put(np.concatenate((lastframe, lastframe), 1))
|
2020-12-03 20:17:20 +08:00
|
|
|
for mid in output:
|
2020-12-05 11:55:22 +08:00
|
|
|
mid = (((mid[0] * 255.).byte().cpu().numpy().transpose(1, 2, 0)))
|
2020-12-05 00:31:33 +08:00
|
|
|
write_buffer.put(np.concatenate((lastframe, mid[:h, :w]), 1))
|
2020-11-22 14:41:07 +08:00
|
|
|
else:
|
2020-12-05 00:31:33 +08:00
|
|
|
write_buffer.put(lastframe)
|
2020-12-03 20:17:20 +08:00
|
|
|
for mid in output:
|
2020-12-05 11:55:22 +08:00
|
|
|
mid = (((mid[0] * 255.).byte().cpu().numpy().transpose(1, 2, 0)))
|
2020-12-05 00:31:33 +08:00
|
|
|
write_buffer.put(mid[:h, :w])
|
2020-11-22 14:41:07 +08:00
|
|
|
pbar.update(1)
|
|
|
|
|
lastframe = frame
|
2021-04-23 16:32:04 +09:00
|
|
|
|
2020-11-18 10:44:18 +08:00
|
|
|
if args.montage:
|
2020-12-05 00:31:33 +08:00
|
|
|
write_buffer.put(np.concatenate((lastframe, lastframe), 1))
|
2020-11-18 10:44:18 +08:00
|
|
|
else:
|
2020-12-05 00:31:33 +08:00
|
|
|
write_buffer.put(lastframe)
|
2020-11-23 11:54:25 +08:00
|
|
|
import time
|
2020-12-05 00:31:33 +08:00
|
|
|
while(not write_buffer.empty()):
|
2020-11-23 11:54:25 +08:00
|
|
|
time.sleep(0.1)
|
2020-11-18 10:44:18 +08:00
|
|
|
pbar.close()
|
2020-11-20 21:07:26 +08:00
|
|
|
if not vid_out is None:
|
|
|
|
|
vid_out.release()
|
2020-11-25 02:10:31 -04:00
|
|
|
|
|
|
|
|
# move audio to new video file if appropriate
|
2020-12-03 18:59:50 +08:00
|
|
|
if args.png == False and fpsNotAssigned == True and not args.skip and not args.video is None:
|
2020-12-09 17:45:28 -04:00
|
|
|
try:
|
2021-01-17 15:24:57 +01:00
|
|
|
transferAudio(args.video, vid_out_name)
|
2020-12-09 17:45:28 -04:00
|
|
|
except:
|
|
|
|
|
print("Audio transfer failed. Interpolated video will have no audio")
|
2021-01-17 17:34:48 +01:00
|
|
|
targetNoAudio = os.path.splitext(vid_out_name)[0] + "_noaudio" + os.path.splitext(vid_out_name)[1]
|
|
|
|
|
os.rename(targetNoAudio, vid_out_name)
|