-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract_videos.py
156 lines (131 loc) · 5.88 KB
/
extract_videos.py
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
import argparse
import os
from os.path import join
import functools
import imageio
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import torch
from torch.utils.data import Dataset, TensorDataset
from torch import Tensor
from torch.autograd import Variable
import logging
from pdb import set_trace
import pickle
import sys
import tensorflow as tf
sys.path.append('utils/')
from utils import util
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]= "1"
OFFSET = 2
FPS = 30
def main(args):
extract_videos_and_run_rcnn('/media/msieb/1e2e903d-5929-40bd-a22a-a94fd9e5bcce/tcn_data/experiments/' + args.target + '/videos/' + args.mode, \
'/media/msieb/1e2e903d-5929-40bd-a22a-a94fd9e5bcce/tcn_data/experiments/' + args.target + '/depth/' + args.mode, \
frame_size=(480, 640))
# run_rcnn('/media/msieb/1e2e903d-5929-40bd-a22a-a94fd9e5bcce/tcn_data/experiments/ltcn/videos/valid', frame_size=(480, 640))
def extract_videos_and_run_rcnn(rootpath, rootpath_depth, frame_size):
print(rootpath)
rcnn = util.RCNN(plot_mode=True)
for file in os.listdir(rootpath):
# if 'view1' not in file:
# continue
if not file.endswith('.mp4'):
continue
filepath = join(rootpath, file)
filepath_depth = join(rootpath_depth, file)
folderpath = join(rootpath, file.split('.mp4')[0])
folderpath_depth = join(rootpath_depth, file.split('.mp4')[0])
print("save in", folderpath)
debugpath = join(rootpath, 'debug', file.split('.mp4')[0])
if not os.path.exists(folderpath):
os.makedirs(folderpath)
if not os.path.exists(debugpath):
os.makedirs(debugpath)
if not os.path.exists(folderpath_depth):
os.makedirs(folderpath_depth)
imageio_video = imageio.read(filepath)
imageio_video_depth = imageio.read(filepath_depth)
snap_length = len(imageio_video)
frames = np.zeros((snap_length, 3, *frame_size))
frames_depth = np.zeros((snap_length, 3, *frame_size))
i = 0
for frame, frame_depth in zip(imageio_video, imageio_video_depth):
print("Process frame ", i)
r, fig = rcnn.get_raw_rcnn_results(frame)
save_name = '{0:05d}'.format(i)
with open(join(folderpath, save_name + '.pkl'), 'wb') as handle:
pickle.dump(r, handle, protocol=pickle.HIGHEST_PROTOCOL)
plt.imsave(join(folderpath, save_name + '.jpg'), frame)
plt.imsave(join(folderpath_depth, save_name + '.jpg'), frame_depth)
if fig is not None:
canvas = FigureCanvas(fig)
ax = fig.gca()
canvas.draw() # draw the canvas, cache the renderer
output_img = np.array(fig.canvas.renderer._renderer)
plt.imsave(join(debugpath, save_name + '.jpg'), output_img)
plt.close(fig)
i += 1
print("="*20)
# with open('filename.pickle', 'rb') as handle:
# b = pickle.load(handle)
def run_rcnn(rootpath, frame_size):
print(rootpath)
rcnn = util.RCNN(plot_mode=True)
for file in [p for p in os.listdir(rootpath) if not p.endswith('.mp4')]:
if 'debug' in file:
continue
folderpath = join(rootpath, file)
print("save in", folderpath)
debugpath = join(rootpath, 'debug', file)
if not os.path.exists(debugpath):
os.makedirs(debugpath)
img_paths = sorted([p for p in os.listdir(folderpath) if p.endswith('.jpg')], key=lambda x: int(x.split('.')[0]))
for i, img_path in enumerate(img_paths):
save_name = '{0:05d}'.format(i)
# if os.path.exists(join(folderpath, save_name + '.pkl')):
# continue
print("Process frame ", i)
frame = plt.imread(join(folderpath, img_path))
r, fig = rcnn.get_raw_rcnn_results(frame)
with open(join(folderpath, save_name + '.pkl'), 'wb') as handle:
pickle.dump(r, handle, protocol=pickle.HIGHEST_PROTOCOL)
if fig is not None:
canvas = FigureCanvas(fig)
ax = fig.gca()
canvas.draw() # draw the canvas, cache the renderer
output_img = np.array(fig.canvas.renderer._renderer)
plt.imsave(join(debugpath, save_name + '.jpg'), output_img)
plt.close(fig)
print("="*20)
def extract_frames():
INPUT_PATHS = ['videos/' + args.mode, 'depth/' + args.mode]
for path in INPUT_PATHS:
OUTDIR='/media/msieb/1e2e903d-5929-40bd-a22a-a94fd9e5bcce/tcn_data/experiments/mask_rcnn/mask_estimation_' \
+ args.mode + '/' + path.split('/')[0]
print("saving to {}".format(OUTDIR))
print("Extracting {}".format(path))
for file in os.listdir(path):
if not file.endswith('.mp4'): # or 'view1' in file:
continue
reader = imageio.get_reader(join(path, file))
dest_folder = join(OUTDIR, file.split('.mp4')[0])
if not os.path.exists(dest_folder):
os.makedirs(dest_folder)
print("Extract {}".format(file))
print("="*10)
for i, im in enumerate(reader):
if i > 0 and not args.mode == 'test':
break
imageio.imwrite(os.path.join(dest_folder, "{0:05d}.jpg".format(i)), im)
else:
continue
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--mode', type=str, default='train')
parser.add_argument('-t', '--target', type=str, required=True)
args = parser.parse_args()
main(args)