mirror of
https://github.com/hzwer/Practical-RIFE.git
synced 2026-11-29 12:15:38 -05:00
Add code
This commit is contained in:
+14
@@ -0,0 +1,14 @@
|
||||
*.pyc
|
||||
*.py~
|
||||
*.py#
|
||||
|
||||
*.pkl
|
||||
output/*
|
||||
train_log/*
|
||||
*.mp4
|
||||
|
||||
test/
|
||||
.idea/
|
||||
*.npz
|
||||
|
||||
*.zip
|
||||
@@ -0,0 +1,268 @@
|
||||
import os
|
||||
import cv2
|
||||
import torch
|
||||
import argparse
|
||||
import numpy as np
|
||||
from tqdm import tqdm
|
||||
from torch.nn import functional as F
|
||||
import warnings
|
||||
import _thread
|
||||
import skvideo.io
|
||||
from queue import Queue, Empty
|
||||
from benchmark.pytorch_msssim import ssim_matlab
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
def transferAudio(sourceVideo, targetVideo):
|
||||
import shutil
|
||||
import moviepy.editor
|
||||
tempAudioFileName = "./temp/audio.mkv"
|
||||
|
||||
# split audio from original video file and store in "temp" directory
|
||||
if True:
|
||||
|
||||
# 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")
|
||||
# extract audio from video
|
||||
os.system('ffmpeg -y -i "{}" -c:a copy -vn {}'.format(sourceVideo, tempAudioFileName))
|
||||
|
||||
targetNoAudio = os.path.splitext(targetVideo)[0] + "_noaudio" + os.path.splitext(targetVideo)[1]
|
||||
os.rename(targetVideo, targetNoAudio)
|
||||
# combine audio file and new video file
|
||||
os.system('ffmpeg -y -i "{}" -i {} -c copy "{}"'.format(targetNoAudio, tempAudioFileName, targetVideo))
|
||||
|
||||
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"
|
||||
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))
|
||||
if (os.path.getsize(targetVideo) == 0): # if aac is not supported by selected format
|
||||
os.rename(targetNoAudio, targetVideo)
|
||||
print("Audio transfer failed. Interpolated video will have no audio")
|
||||
else:
|
||||
print("Lossless audio transfer failed. Audio was transcoded to AAC (M4A) instead.")
|
||||
|
||||
# remove audio-less video
|
||||
os.remove(targetNoAudio)
|
||||
else:
|
||||
os.remove(targetNoAudio)
|
||||
|
||||
# remove temp directory
|
||||
shutil.rmtree("temp")
|
||||
|
||||
parser = argparse.ArgumentParser(description='Interpolation for a pair of images')
|
||||
parser.add_argument('--video', dest='video', type=str, default=None)
|
||||
parser.add_argument('--output', dest='output', type=str, default=None)
|
||||
parser.add_argument('--img', dest='img', type=str, default=None)
|
||||
parser.add_argument('--montage', dest='montage', action='store_true', help='montage origin video')
|
||||
parser.add_argument('--model', dest='modelDir', type=str, default='train_log', help='directory with trained model files')
|
||||
parser.add_argument('--fp16', dest='fp16', action='store_true', help='fp16 mode for faster and more lightweight inference on cards with Tensor Cores')
|
||||
parser.add_argument('--UHD', dest='UHD', action='store_true', help='support 4k video')
|
||||
parser.add_argument('--scale', dest='scale', type=float, default=1.0, help='Try scale=0.5 for 4k video')
|
||||
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)
|
||||
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')
|
||||
parser.add_argument('--exp', dest='exp', type=int, default=1)
|
||||
args = parser.parse_args()
|
||||
assert (not args.video is None or not args.img is None)
|
||||
if args.UHD and args.scale==1.0:
|
||||
args.scale = 0.5
|
||||
assert args.scale in [0.25, 0.5, 1.0, 2.0, 4.0]
|
||||
if not args.img is None:
|
||||
args.png = True
|
||||
|
||||
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)
|
||||
|
||||
try:
|
||||
try:
|
||||
from model.RIFE_HDv2 import Model
|
||||
model = Model()
|
||||
model.load_model(args.modelDir, -1)
|
||||
print("Loaded v2.x HD model.")
|
||||
except:
|
||||
from train_log.RIFE_HDv3 import Model
|
||||
model = Model()
|
||||
model.load_model(args.modelDir, -1)
|
||||
print("Loaded v3.x HD model.")
|
||||
except:
|
||||
from model.RIFE_HD import Model
|
||||
model = Model()
|
||||
model.load_model(args.modelDir, -1)
|
||||
print("Loaded v1.x HD model")
|
||||
model.eval()
|
||||
model.device()
|
||||
|
||||
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
|
||||
args.fps = fps * (2 ** args.exp)
|
||||
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))
|
||||
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!")
|
||||
else:
|
||||
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]))
|
||||
lastframe = cv2.imread(os.path.join(args.img, videogen[0]))[:, :, ::-1].copy()
|
||||
videogen = videogen[1:]
|
||||
h, w, _ = lastframe.shape
|
||||
vid_out_name = None
|
||||
vid_out = None
|
||||
if args.png:
|
||||
if not os.path.exists('vid_out'):
|
||||
os.mkdir('vid_out')
|
||||
else:
|
||||
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))
|
||||
|
||||
def clear_write_buffer(user_args, write_buffer):
|
||||
cnt = 0
|
||||
while True:
|
||||
item = write_buffer.get()
|
||||
if item is None:
|
||||
break
|
||||
if user_args.png:
|
||||
cv2.imwrite('vid_out/{:0>7d}.png'.format(cnt), item[:, :, ::-1])
|
||||
cnt += 1
|
||||
else:
|
||||
vid_out.write(item[:, :, ::-1])
|
||||
|
||||
def build_read_buffer(user_args, read_buffer, videogen):
|
||||
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
|
||||
read_buffer.put(None)
|
||||
|
||||
def make_inference(I0, I1, n):
|
||||
global model
|
||||
middle = model.inference(I0, I1, args.scale)
|
||||
if n == 1:
|
||||
return [middle]
|
||||
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]
|
||||
|
||||
def pad_image(img):
|
||||
if(args.fp16):
|
||||
return F.pad(img, padding).half()
|
||||
else:
|
||||
return F.pad(img, padding)
|
||||
|
||||
if args.montage:
|
||||
left = w // 4
|
||||
w = w // 2
|
||||
tmp = max(32, int(32 / args.scale))
|
||||
ph = ((h - 1) // tmp + 1) * tmp
|
||||
pw = ((w - 1) // tmp + 1) * tmp
|
||||
padding = (0, pw - w, 0, ph - h)
|
||||
pbar = tqdm(total=tot_frame)
|
||||
skip_frame = 1
|
||||
if args.montage:
|
||||
lastframe = lastframe[:, left: left + w]
|
||||
write_buffer = Queue(maxsize=500)
|
||||
read_buffer = Queue(maxsize=500)
|
||||
_thread.start_new_thread(build_read_buffer, (args, read_buffer, videogen))
|
||||
_thread.start_new_thread(clear_write_buffer, (args, write_buffer))
|
||||
|
||||
I1 = torch.from_numpy(np.transpose(lastframe, (2,0,1))).to(device, non_blocking=True).unsqueeze(0).float() / 255.
|
||||
I1 = pad_image(I1)
|
||||
|
||||
while True:
|
||||
frame = read_buffer.get()
|
||||
if frame is None:
|
||||
break
|
||||
I0 = I1
|
||||
I1 = torch.from_numpy(np.transpose(frame, (2,0,1))).to(device, non_blocking=True).unsqueeze(0).float() / 255.
|
||||
I1 = pad_image(I1)
|
||||
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)
|
||||
|
||||
if ssim > 0.995:
|
||||
if skip_frame % 100 == 0:
|
||||
print("\nWarning: Your video has {} static frames, skipping them may change the duration of the generated video.".format(skip_frame))
|
||||
skip_frame += 1
|
||||
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.)
|
||||
else:
|
||||
output = make_inference(I0, I1, 2**args.exp-1) if args.exp else []
|
||||
|
||||
if args.montage:
|
||||
write_buffer.put(np.concatenate((lastframe, lastframe), 1))
|
||||
for mid in output:
|
||||
mid = (((mid[0] * 255.).byte().cpu().numpy().transpose(1, 2, 0)))
|
||||
write_buffer.put(np.concatenate((lastframe, mid[:h, :w]), 1))
|
||||
else:
|
||||
write_buffer.put(lastframe)
|
||||
for mid in output:
|
||||
mid = (((mid[0] * 255.).byte().cpu().numpy().transpose(1, 2, 0)))
|
||||
write_buffer.put(mid[:h, :w])
|
||||
pbar.update(1)
|
||||
lastframe = frame
|
||||
|
||||
if args.montage:
|
||||
write_buffer.put(np.concatenate((lastframe, lastframe), 1))
|
||||
else:
|
||||
write_buffer.put(lastframe)
|
||||
import time
|
||||
while(not write_buffer.empty()):
|
||||
time.sleep(0.1)
|
||||
pbar.close()
|
||||
if not vid_out is None:
|
||||
vid_out.release()
|
||||
|
||||
# move audio to new video file if appropriate
|
||||
if args.png == False and fpsNotAssigned == True and not args.skip and not args.video is None:
|
||||
try:
|
||||
transferAudio(args.video, vid_out_name)
|
||||
except:
|
||||
print("Audio transfer failed. Interpolated video will have no audio")
|
||||
targetNoAudio = os.path.splitext(vid_out_name)[0] + "_noaudio" + os.path.splitext(vid_out_name)[1]
|
||||
os.rename(targetNoAudio, vid_out_name)
|
||||
@@ -0,0 +1,116 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from model.warplayer import warp
|
||||
from train_log.refine import *
|
||||
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
||||
return nn.Sequential(
|
||||
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
|
||||
padding=padding, dilation=dilation, bias=True),
|
||||
nn.PReLU(out_planes)
|
||||
)
|
||||
|
||||
def conv_bn(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
||||
return nn.Sequential(
|
||||
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
|
||||
padding=padding, dilation=dilation, bias=False),
|
||||
nn.BatchNorm2d(out_planes),
|
||||
nn.PReLU(out_planes)
|
||||
)
|
||||
|
||||
class IFBlock(nn.Module):
|
||||
def __init__(self, in_planes, c=64):
|
||||
super(IFBlock, self).__init__()
|
||||
self.conv0 = nn.Sequential(
|
||||
conv(in_planes, c//2, 3, 2, 1),
|
||||
conv(c//2, c, 3, 2, 1),
|
||||
)
|
||||
self.convblock0 = nn.Sequential(
|
||||
conv(c, c),
|
||||
conv(c, c)
|
||||
)
|
||||
self.convblock1 = nn.Sequential(
|
||||
conv(c, c),
|
||||
conv(c, c)
|
||||
)
|
||||
self.convblock2 = nn.Sequential(
|
||||
conv(c, c),
|
||||
conv(c, c)
|
||||
)
|
||||
self.convblock3 = nn.Sequential(
|
||||
conv(c, c),
|
||||
conv(c, c)
|
||||
)
|
||||
self.conv1 = nn.Sequential(
|
||||
nn.ConvTranspose2d(c, 4, 4, 2, 1),
|
||||
)
|
||||
self.conv2 = nn.ConvTranspose2d(c, 1, 4, 2, 1)
|
||||
|
||||
def forward(self, x, flow, scale=1):
|
||||
x = F.interpolate(x, scale_factor= 1. / scale, mode="bilinear", align_corners=False, recompute_scale_factor=False)
|
||||
flow = F.interpolate(flow, scale_factor= 1. / scale, mode="bilinear", align_corners=False, recompute_scale_factor=False) * 1. / scale
|
||||
feat = self.conv0(torch.cat((x, flow), 1))
|
||||
feat = self.convblock0(feat) + feat
|
||||
feat = self.convblock1(feat) + feat
|
||||
feat = self.convblock2(feat) + feat
|
||||
feat = self.convblock3(feat) + feat
|
||||
flow = self.conv1(feat)
|
||||
mask = self.conv2(feat)
|
||||
flow = F.interpolate(flow, scale_factor=scale*2, mode="bilinear", align_corners=False, recompute_scale_factor=False) * scale*2
|
||||
mask = F.interpolate(mask, scale_factor=scale*2, mode="bilinear", align_corners=False, recompute_scale_factor=False)
|
||||
return flow, mask
|
||||
|
||||
class IFNet(nn.Module):
|
||||
def __init__(self):
|
||||
super(IFNet, self).__init__()
|
||||
self.block0 = IFBlock(7+4, c=90)
|
||||
self.block1 = IFBlock(7+4, c=90)
|
||||
self.block2 = IFBlock(7+4, c=90)
|
||||
self.block_tea = IFBlock(10+4, c=90)
|
||||
# self.contextnet = Contextnet()
|
||||
# self.unet = Unet()
|
||||
|
||||
def forward(self, x, scale_list=[4, 2, 1], scale=1.0, training=False):
|
||||
x = F.interpolate(x, scale_factor=scale, mode="bilinear", align_corners=False)
|
||||
img0 = x[:, :3]
|
||||
img1 = x[:, 3:6]
|
||||
gt = x[:, 6:]
|
||||
flow_list = []
|
||||
merged = []
|
||||
mask_list = []
|
||||
warped_img0 = img0
|
||||
warped_img1 = img1
|
||||
flow = torch.zeros_like(x[:, :4]).to(device)
|
||||
mask = torch.zeros_like(x[:, :1]).to(device)
|
||||
loss_cons = 0
|
||||
block = [self.block0, self.block1, self.block2]
|
||||
for i in range(3):
|
||||
f0, m0 = block[i](torch.cat((warped_img0, warped_img1, mask), 1), flow, scale=scale_list[i])
|
||||
f1, m1 = block[i](torch.cat((warped_img1, warped_img0, -mask), 1), torch.cat((flow[:, 2:4], flow[:, :2]), 1), scale=scale_list[i])
|
||||
flow = flow + (f0 + torch.cat((f1[:, 2:4], f1[:, :2]), 1)) / 2
|
||||
mask = mask + (m0 + (-m1)) / 2
|
||||
mask_list.append(mask)
|
||||
flow_list.append(flow)
|
||||
warped_img0 = warp(img0, flow[:, :2])
|
||||
warped_img1 = warp(img1, flow[:, 2:4])
|
||||
merged.append((warped_img0, warped_img1))
|
||||
if scale != 1.0:
|
||||
flow = F.interpolate(flow, scale_factor=1 / scale, mode="bilinear", align_corners=False) / scale
|
||||
mask_list[2] = F.interpolate(mask_list[2], scale_factor=1 / scale, mode="bilinear", align_corners=False)
|
||||
warped_img0 = warp(img0, flow[:, :2])
|
||||
warped_img1 = warp(img1, flow[:, 2:4])
|
||||
merged[2] = (warped_img0, warped_img1)
|
||||
'''
|
||||
c0 = self.contextnet(img0, flow[:, :2])
|
||||
c1 = self.contextnet(img1, flow[:, 2:4])
|
||||
tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1)
|
||||
res = tmp[:, 1:4] * 2 - 1
|
||||
'''
|
||||
for i in range(3):
|
||||
mask_list[i] = torch.sigmoid(mask_list[i])
|
||||
merged[i] = merged[i][0] * mask_list[i] + merged[i][1] * (1 - mask_list[i])
|
||||
# merged[i] = torch.clamp(merged[i] + res, 0, 1)
|
||||
return flow_list, mask_list[2], merged
|
||||
@@ -0,0 +1,88 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
from torch.optim import AdamW
|
||||
import torch.optim as optim
|
||||
import itertools
|
||||
from model.warplayer import warp
|
||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||
from train_log.IFNet_HDv3 import *
|
||||
import torch.nn.functional as F
|
||||
from model.loss import *
|
||||
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
class Model:
|
||||
def __init__(self, local_rank=-1):
|
||||
self.flownet = IFNet()
|
||||
self.device()
|
||||
self.optimG = AdamW(self.flownet.parameters(), lr=1e-6, weight_decay=1e-4)
|
||||
self.epe = EPE()
|
||||
# self.vgg = VGGPerceptualLoss().to(device)
|
||||
self.sobel = SOBEL()
|
||||
if local_rank != -1:
|
||||
self.flownet = DDP(self.flownet, device_ids=[local_rank], output_device=local_rank)
|
||||
|
||||
def train(self):
|
||||
self.flownet.train()
|
||||
|
||||
def eval(self):
|
||||
self.flownet.eval()
|
||||
|
||||
def device(self):
|
||||
self.flownet.to(device)
|
||||
|
||||
def load_model(self, path, rank=0):
|
||||
def convert(param):
|
||||
if rank == -1:
|
||||
return {
|
||||
k.replace("module.", ""): v
|
||||
for k, v in param.items()
|
||||
if "module." in k
|
||||
}
|
||||
else:
|
||||
return param
|
||||
if rank <= 0:
|
||||
if torch.cuda.is_available():
|
||||
self.flownet.load_state_dict(convert(torch.load('{}/flownet.pkl'.format(path))))
|
||||
else:
|
||||
self.flownet.load_state_dict(convert(torch.load('{}/flownet.pkl'.format(path), map_location ='cpu')))
|
||||
|
||||
def save_model(self, path, rank=0):
|
||||
if rank == 0:
|
||||
torch.save(self.flownet.state_dict(),'{}/flownet.pkl'.format(path))
|
||||
|
||||
def inference(self, img0, img1, scale=1.0):
|
||||
imgs = torch.cat((img0, img1), 1)
|
||||
scale_list = [4, 2, 1]
|
||||
flow, mask, merged = self.flownet(imgs, scale_list, scale=scale)
|
||||
return merged[2]
|
||||
|
||||
def update(self, imgs, gt, learning_rate=0, mul=1, training=True, flow_gt=None):
|
||||
for param_group in self.optimG.param_groups:
|
||||
param_group['lr'] = learning_rate
|
||||
img0 = imgs[:, :3]
|
||||
img1 = imgs[:, 3:]
|
||||
if training:
|
||||
self.train()
|
||||
else:
|
||||
self.eval()
|
||||
scale = [4, 2, 1]
|
||||
flow, mask, merged = self.flownet(torch.cat((imgs, gt), 1), scale=scale, training=training)
|
||||
loss_l1 = (merged[2] - gt).abs().mean()
|
||||
loss_smooth = self.sobel(flow[2], flow[2]*0).mean()
|
||||
# loss_vgg = self.vgg(merged[2], gt)
|
||||
if training:
|
||||
self.optimG.zero_grad()
|
||||
loss_G = loss_cons + loss_smooth * 0.1
|
||||
loss_G.backward()
|
||||
self.optimG.step()
|
||||
else:
|
||||
flow_teacher = flow[2]
|
||||
return merged[2], {
|
||||
'mask': mask,
|
||||
'flow': flow[2][:, :2],
|
||||
'loss_l1': loss_l1,
|
||||
'loss_cons': loss_cons,
|
||||
'loss_smooth': loss_smooth,
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
from torch.optim import AdamW
|
||||
import torch.optim as optim
|
||||
import itertools
|
||||
from model.warplayer import warp
|
||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||
import torch.nn.functional as F
|
||||
from model.loss import *
|
||||
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
||||
return nn.Sequential(
|
||||
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
|
||||
padding=padding, dilation=dilation, bias=True),
|
||||
nn.PReLU(out_planes)
|
||||
)
|
||||
|
||||
def conv_woact(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
||||
return nn.Sequential(
|
||||
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
|
||||
padding=padding, dilation=dilation, bias=True),
|
||||
)
|
||||
|
||||
def deconv(in_planes, out_planes, kernel_size=4, stride=2, padding=1):
|
||||
return nn.Sequential(
|
||||
torch.nn.ConvTranspose2d(in_channels=in_planes, out_channels=out_planes, kernel_size=4, stride=2, padding=1, bias=True),
|
||||
nn.PReLU(out_planes)
|
||||
)
|
||||
|
||||
class Conv2(nn.Module):
|
||||
def __init__(self, in_planes, out_planes, stride=2):
|
||||
super(Conv2, self).__init__()
|
||||
self.conv1 = conv(in_planes, out_planes, 3, stride, 1)
|
||||
self.conv2 = conv(out_planes, out_planes, 3, 1, 1)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv1(x)
|
||||
x = self.conv2(x)
|
||||
return x
|
||||
|
||||
c = 16
|
||||
class Contextnet(nn.Module):
|
||||
def __init__(self):
|
||||
super(Contextnet, self).__init__()
|
||||
self.conv1 = Conv2(3, c)
|
||||
self.conv2 = Conv2(c, 2*c)
|
||||
self.conv3 = Conv2(2*c, 4*c)
|
||||
self.conv4 = Conv2(4*c, 8*c)
|
||||
|
||||
def forward(self, x, flow):
|
||||
x = self.conv1(x)
|
||||
flow = F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False) * 0.5
|
||||
f1 = warp(x, flow)
|
||||
x = self.conv2(x)
|
||||
flow = F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False) * 0.5
|
||||
f2 = warp(x, flow)
|
||||
x = self.conv3(x)
|
||||
flow = F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False) * 0.5
|
||||
f3 = warp(x, flow)
|
||||
x = self.conv4(x)
|
||||
flow = F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False) * 0.5
|
||||
f4 = warp(x, flow)
|
||||
return [f1, f2, f3, f4]
|
||||
|
||||
class Unet(nn.Module):
|
||||
def __init__(self):
|
||||
super(Unet, self).__init__()
|
||||
self.down0 = Conv2(17, 2*c)
|
||||
self.down1 = Conv2(4*c, 4*c)
|
||||
self.down2 = Conv2(8*c, 8*c)
|
||||
self.down3 = Conv2(16*c, 16*c)
|
||||
self.up0 = deconv(32*c, 8*c)
|
||||
self.up1 = deconv(16*c, 4*c)
|
||||
self.up2 = deconv(8*c, 2*c)
|
||||
self.up3 = deconv(4*c, c)
|
||||
self.conv = nn.Conv2d(c, 4, 3, 1, 1)
|
||||
|
||||
def forward(self, img0, img1, warped_img0, warped_img1, mask, flow, c0, c1):
|
||||
s0 = self.down0(torch.cat((img0, img1, warped_img0, warped_img1, mask, flow), 1))
|
||||
s1 = self.down1(torch.cat((s0, c0[0], c1[0]), 1))
|
||||
s2 = self.down2(torch.cat((s1, c0[1], c1[1]), 1))
|
||||
s3 = self.down3(torch.cat((s2, c0[2], c1[2]), 1))
|
||||
x = self.up0(torch.cat((s3, c0[3], c1[3]), 1))
|
||||
x = self.up1(torch.cat((x, s2), 1))
|
||||
x = self.up2(torch.cat((x, s1), 1))
|
||||
x = self.up3(torch.cat((x, s0), 1))
|
||||
x = self.conv(x)
|
||||
return torch.sigmoid(x)
|
||||
@@ -0,0 +1,6 @@
|
||||
numpy>=1.16
|
||||
tqdm>=4.35.0
|
||||
sk-video>=1.1.10
|
||||
torch>=1.3.0
|
||||
opencv-python>=4.1.2
|
||||
moviepy>=1.0.3
|
||||
Reference in New Issue
Block a user