-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathinference_video.py
More file actions
192 lines (153 loc) · 5.5 KB
/
inference_video.py
File metadata and controls
192 lines (153 loc) · 5.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
'''
This script works as an inference video recorder.
'''
import os
import numpy as np
import cv2 as cv
from options.options import parse
import argparse
parser = argparse.ArgumentParser(description="Script for video inference")
parser.add_argument('-p', '--config', type=str, default='./options/inference_video/Baseline.yml', help = 'Config file of video inference')
args = parser.parse_args()
path_options = args.config
opt = parse(path_options)
os.environ["CUDA_VISIBLE_DEVICES"]= "0"
# PyTorch library
import torch
import torch.optim
import torch.multiprocessing as mp
from tqdm import tqdm
from torchvision.transforms import Resize
from data.dataset_reader.datapipeline import *
from archs import *
from utils.test_utils import *
from ptflops import get_model_complexity_info
device = torch.device('cuda') if torch.cuda.is_available() else 'cpu'
#define some transforms
pil_to_tensor = transforms.ToTensor()
tensor_to_pil = transforms.ToPILImage()
resize = opt['Resize']
def array_to_tensor(frame):
'''
Transform from numpy array [H,W,C] to torch tensor [B,C,H,W]
'''
frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
tensor_frame = torch.from_numpy(frame).permute(2, 0, 1).unsqueeze(0).float()
return tensor_frame
def tensor_to_array(tensor):
'''
Transform from torch tensor [B,C,H,W] to numpy array [H,W,C].
'''
array = tensor.squeeze(0).permute(1, 2, 0).cpu().numpy()
frame = (array * 255).astype(np.uint8)
frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB) # flip red and blue channels
return frame
def normalize_tensor(tensor):
'''
Normalize tensor to the range [0,1]
'''
max_value = torch.max(tensor)
min_value = torch.min(tensor)
output = (tensor - min_value)/(max_value)
return output
def save_tensor(tensor, path):
'''
Save tensor as PIL image.
'''
tensor = tensor.squeeze(0)
# tensor = normalize_tensor(tensor)
print(tensor.shape, tensor.dtype, torch.max(tensor), torch.min(tensor))
img = tensor_to_pil(tensor)
img.save(path)
def pad_tensor(tensor, multiple = 8):
'''
Pad the tensor to be multiple of some number (its size).
'''
multiple = multiple
_, _, H, W = tensor.shape
pad_h = (multiple - H % multiple) % multiple
pad_w = (multiple - W % multiple) % multiple
tensor = F.pad(tensor, (0, pad_w, 0, pad_h), value = 0)
return tensor
def load_model(model, path_weights):
'''
Load the weights of the model.
'''
map_location = 'cpu'
checkpoints = torch.load(path_weights, map_location=map_location, weights_only=False)
weights = checkpoints['params']
weights = {'module.' + key: value for key, value in weights.items()}
macs, params = get_model_complexity_info(model, (3, 256, 256), print_per_layer_stat=False, verbose=False)
print('Complexity information of the model: ', macs, params)
model.load_state_dict(weights)
print('Loaded weights correctly')
return model
def apply_model(model, tensor, resize = False):
'''
Apply the inference over each specific frame. If resize = True, resizes before inference.
'''
_, _, H, W = tensor.shape
if resize:
new_size = [720, 1080]
downsample = Resize(new_size)
else:
downsample = torch.nn.Identity()
tensor = downsample(tensor)
tensor = pad_tensor(tensor)
with torch.no_grad():
output = model(tensor, side_loss=False)
if resize:
upsample = Resize((H, W))
else: upsample = torch.nn.Identity()
output = upsample(output)
output = torch.clamp(output, 0., 1.)
output = output[:,:, :H, :W]
return output
def inference_video(rank, world_size):
'''
Inferences the video frames and constructs a new video. The result video is a composition of the original and the process ones.
'''
import argparse
parser = argparse.ArgumentParser(description="Video inference script")
parser.add_argument('-i', '--inp_path', type=str, default=None,
help="File path to video")
args = parser.parse_args()
setup(rank, world_size=world_size) # setup the torch.distributor
# Open the video file
cap = cv.VideoCapture(args.inp_path)
# Get video properties
frame_width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
fps = int(cap.get(cv.CAP_PROP_FPS))
fourcc = cv.VideoWriter_fourcc(*'mp4v')
output_path = os.path.join('./videos/results', os.path.basename(args.inp_path))
out = cv.VideoWriter(output_path, fourcc, fps, (int(frame_width * 2), frame_height))
# Instantiate model and load weights
model, _, _ = create_model(opt['network'], rank=rank)
model = load_model(model, path_weights = opt['save']['path'])
model.eval()
if rank==0:
pbar = tqdm(total = int(cap.get(cv.CAP_PROP_FRAME_COUNT)))
while cap.isOpened():
ret, frame = cap.read()
old_frame = np.copy(frame)
if not ret: break
tensor = array_to_tensor(frame)
tensor = normalize_tensor(tensor)
output = apply_model(model, tensor, resize = resize)
frame = tensor_to_array(output)
combined = np.hstack((old_frame, frame))
out.write(combined)
if rank==0: pbar.update(1)
cap.release()
out.release()
print('Finished inference!')
if rank == 0:
pbar.close()
cleanup()
def main():
world_size = 1
print('Used GPUS:', world_size)
mp.spawn(inference_video, args =(world_size,), nprocs=world_size, join=True)
if __name__ == '__main__':
main()