-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideo_test.py
356 lines (262 loc) · 13.1 KB
/
video_test.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
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import cv2
import tensorflow as tf
import numpy as np
import os, shutil, sys
import subprocess
from enum import Enum
from typing import Any, List, Tuple
class Task(Enum):
CLIPPING = 1
VISUALIZATION_OBJECT = 2
VISUALIZATION_AREA = 3
SEQUENCE_IMAGES_DIR = './temp_seq_images'
DEFAULT_OUTPUT_FILE = './outputs/output_{0}.mp4'.format(len(os.listdir('./outputs'))+1)
ROLLING_WINDOW_SIZE = 25
VERTICAL_FORMAT = (16,9)
TYPE_TASK = Task.VISUALIZATION_AREA
def main():
if len(sys.argv) == 1:
print('Ошибка: пропущен видеофайл')
return
model = get_saved_model()
video_path = sys.argv[1]
if TYPE_TASK == Task.CLIPPING:
run_clipping_video_by_salient_area_task(video_path, model)
elif TYPE_TASK == Task.VISUALIZATION_OBJECT:
run_visualization_salient_object_task(video_path, model)
elif TYPE_TASK == Task.VISUALIZATION_AREA:
run_visualization_salient_area_task(video_path, model)
def run_visualization_salient_object_task(video_path: str, model: Any, need_log: bool = True):
os.makedirs(SEQUENCE_IMAGES_DIR, exist_ok=True)
video_cap = cv2.VideoCapture(video_path)
number_frames = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT))
if (video_cap.isOpened() == False):
print("Ошибка открытия видеофайла")
else:
print("Определение основного объекта по кадрам...")
for i in range(1, number_frames+1):
ret, frame = video_cap.read()
if ret == True:
image_tensor = tf.convert_to_tensor(frame)
salient_mask = model.signatures["serving_default"](image_tensor)['mask'].numpy()
mask = cv2.cvtColor(salient_mask*255, cv2.COLOR_GRAY2RGB)
writefile = '{0:s}/img{1:05d}.jpg'.format(SEQUENCE_IMAGES_DIR, i)
cv2.imwrite(writefile, highlight_by_mask(frame, mask))
if need_log:
print_progress_bar(i, number_frames)
else:
print("Ошибка чтения {0} кадра".format(i))
break
video_cap.release()
create_video_using_ffmpeg()
shutil.rmtree(SEQUENCE_IMAGES_DIR)
def run_visualization_salient_area_task(video_path: str, model: Any):
video_cap = cv2.VideoCapture(video_path)
width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
result_video_shape = vertical_shape_from_horizontal((height, width), VERTICAL_FORMAT)
# Найти левый верхний угол прямоугольника с основным объектом для каждого кадра видео
corners = find_all_corners(video_cap, model, result_video_shape)
video_cap.release()
# Сглаживание
corners = list(zip(
rolling_list(list(map(lambda pair: pair[0], corners)), ROLLING_WINDOW_SIZE),
rolling_list(list(map(lambda pair: pair[1], corners)), ROLLING_WINDOW_SIZE)))
os.makedirs(SEQUENCE_IMAGES_DIR, exist_ok=True)
# Обрезка видео
video_cap = cv2.VideoCapture(video_path)
highlight_and_write_video(video_cap, corners, result_video_shape)
video_cap.release()
create_video_using_ffmpeg()
shutil.rmtree(SEQUENCE_IMAGES_DIR)
def highlight_and_write_video(video_cap: cv2.VideoCapture, corners: List, area_shape: Tuple):
number_frames = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT))
assert number_frames == len(corners), "Количество кадров в видео должно быть равно количеству углов"
if (video_cap.isOpened() == False):
print("Ошибка открытия видеофайла")
else:
print("Обрезка кадров...")
for i in range(1, number_frames+1):
ret, frame = video_cap.read()
if ret == True:
left_up_i, left_up_j = corners[i-1]
mask = np.zeros(frame.shape, dtype = "uint8")
polygon = np.array([[
[left_up_j, left_up_i],
[left_up_j, left_up_i+area_shape[0]-1],
[left_up_j+area_shape[1], left_up_i+area_shape[0]-1],
[left_up_j+area_shape[1], left_up_i]
]], np.int32)
cv2.fillPoly(mask, polygon, (255,255,255))
writefile = '{0:s}/img{1:05d}.jpg'.format(SEQUENCE_IMAGES_DIR, i)
cv2.imwrite(writefile, highlight_by_mask(frame, mask))
else:
print("Ошибка чтения {0} кадра".format(i))
break
def run_clipping_video_by_salient_area_task(video_path: str, model: Any):
video_cap = cv2.VideoCapture(video_path)
width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
result_video_shape = vertical_shape_from_horizontal((height, width), VERTICAL_FORMAT)
# Найти левый верхний угол прямоугольника с основным объектом для каждого кадра видео
corners = find_all_corners(video_cap, model, result_video_shape)
video_cap.release()
# Сглаживание
corners = list(zip(
rolling_list(list(map(lambda pair: pair[0], corners)), ROLLING_WINDOW_SIZE),
rolling_list(list(map(lambda pair: pair[1], corners)), ROLLING_WINDOW_SIZE)))
os.makedirs(SEQUENCE_IMAGES_DIR, exist_ok=True)
# Обрезка видео
video_cap = cv2.VideoCapture(video_path)
crop_and_write_video(video_cap, corners, result_video_shape)
video_cap.release()
create_video_using_ffmpeg()
shutil.rmtree(SEQUENCE_IMAGES_DIR)
def highlight_by_mask(image, mask):
background_image = change_brightness(image, -60)
masked_image = cv2.bitwise_and(image, mask)
mask = cv2.bitwise_not(mask)
background_image = cv2.bitwise_and(background_image, mask)
highlight_image = cv2.bitwise_or(masked_image, background_image)
return highlight_image
def find_all_corners(video_cap: cv2.VideoCapture, model: Any, shape_bounding_box: Tuple, need_log: bool = True) -> List:
corners = []
number_frames = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT))
salient_weights = create_center_gradient_image(shape_bounding_box[0], shape_bounding_box[1], dtype=tf.uint32)
if (video_cap.isOpened() == False):
print("Ошибка открытия видеофайла")
else:
print("Определение основного объекта по кадрам...")
for i in range(1, number_frames+1):
ret, frame = video_cap.read()
if ret == True:
image_tensor = tf.convert_to_tensor(frame)
salient_mask = model.signatures["serving_default"](image_tensor)['mask']
left_up_i, left_up_j = find_salient_area_left_corner(salient_mask, shape_bounding_box, salient_weights)
corners.append([left_up_i, left_up_j])
if need_log:
print_progress_bar(i, number_frames)
else:
print("Ошибка чтения {0} кадра".format(i))
break
return corners
def rolling_list(source: List, rolling_window: int) -> List:
padding_size = rolling_window // 2
assert padding_size < len(source), "Указано слишком большое окно для сглаживания"
assert rolling_window % 2 == 1, "Окно для сглаживания должно быть нечетного размера"
# mirror
list_with_padding = [*reversed(source[:padding_size]), *source, *reversed(source[-padding_size:])]
result = []
for i in range(0, len(list_with_padding)-rolling_window+1):
result.append(sum(list_with_padding[i:i+rolling_window]) // rolling_window)
return result
def crop_and_write_video(video_cap: cv2.VideoCapture, corners: List, shape_bounding_box: Tuple):
number_frames = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT))
assert number_frames == len(corners), "Количество кадров в видео должно быть равно количеству углов"
if (video_cap.isOpened() == False):
print("Ошибка открытия видеофайла")
else:
print("Обрезка кадров...")
for i in range(1, number_frames+1):
ret, frame = video_cap.read()
if ret == True:
image_tensor = tf.convert_to_tensor(frame)
left_up_i, left_up_j = corners[i-1]
cropped_image = tf.slice(image_tensor,
[left_up_i, left_up_j, 0],
[shape_bounding_box[0], shape_bounding_box[1], 3])
writefile = '{0:s}/img{1:05d}.jpg'.format(SEQUENCE_IMAGES_DIR, i)
cv2.imwrite(writefile, cropped_image.numpy())
else:
print("Ошибка чтения {0} кадра".format(i))
break
def get_saved_model():
return tf.saved_model.load('./serving/models/u2net/3')
def find_salient_area_left_corner(salient_mask, area_shape, weights=None):
mask_height = salient_mask.shape[0]
mask_width = salient_mask.shape[1]
area_height = area_shape[0]
area_width = area_shape[1]
if weights == None:
weights = tf.fill([area_height, area_width, 1])
max_saliency = 0
corner = []
salient_mask = tf.cast(salient_mask, tf.uint32)
for i in range(mask_height-area_height + 1):
for j in range(mask_width-area_width + 1):
sum_saliency_area = tf.reduce_sum(
tf.math.multiply(tf.slice(salient_mask, [i, j, 0], [area_height, area_width, 1]), weights)
)
if max_saliency < sum_saliency_area:
max_saliency = sum_saliency_area
corner = [i, j]
return corner
def create_video_using_ffmpeg():
subprocess.call(
'ffmpeg -framerate 25 -i {0}/img%05d.jpg -pix_fmt yuv420p {1}'
.format(SEQUENCE_IMAGES_DIR, DEFAULT_OUTPUT_FILE),
shell=True,
)
def vertical_shape_from_horizontal(source_shape: tuple, proportions_of_sides: tuple):
assert len(source_shape) == 2 and len(proportions_of_sides) == 2
assert proportions_of_sides[0] > proportions_of_sides[1]
part = source_shape[0]//proportions_of_sides[0]
height = (proportions_of_sides[0] * part) - (proportions_of_sides[0] * part % 2)
width = (proportions_of_sides[1] * part) - (proportions_of_sides[1] * part % 2)
return [height, width]
def change_brightness(img, value=30):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
v = cv2.add(v,value)
v[v > 255] = 255
v[v < 0] = 0
final_hsv = cv2.merge((h, s, v))
img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
return img
def print_progress_bar (current_iteration: int, total_iterations: int, length = 50, prefix = 'Progress:'):
percent = "{0:.1f}".format(100 * (current_iteration / float(total_iterations)))
filledLength = int(length * current_iteration // total_iterations)
bar = '█' * filledLength + '-' * (length - filledLength)
print(f'\r{prefix} |{bar}| {percent}%', end = "\r")
# Print New Line on Complete
if current_iteration == total_iterations:
print()
def create_center_gradient_image(height: int, width: int, shift_scale=1, dtype: Any = None) -> tf.Tensor:
matrix = []
for i in range(height):
row = []
if i < (height+1)//2:
shift_i = i + 1
else:
shift_i = height - i
for j in range(width):
if j < (width+1)//2:
shift_j = j + 1
else:
shift_j = width - j
row.append([(shift_i + shift_j)*shift_scale])
matrix.append(row)
return tf.convert_to_tensor(matrix, dtype=dtype)
def show_salient_area_polygon(video_cap: cv2.VideoCapture, model: Any):
width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
shape_bounding_box = vertical_shape_from_horizontal((height, width), (16,9))
print(shape_bounding_box)
ret, frame = video_cap.read()
if ret == True:
image_tensor = tf.convert_to_tensor(frame)
salient_mask = model.signatures["serving_default"](image_tensor)['mask']
salient_weights = create_center_gradient_image(shape_bounding_box[0], shape_bounding_box[1], dtype=tf.uint32)
left_up_row, left_up_col = find_salient_area_left_corner(salient_mask, shape_bounding_box, salient_weights)
polygon = np.array([[
[left_up_col, left_up_row],
[left_up_col, left_up_row+shape_bounding_box[0]-1],
[left_up_col+shape_bounding_box[1], left_up_row+shape_bounding_box[0]-1],
[left_up_col+shape_bounding_box[1], left_up_row]
]], np.int32)
img_mod = cv2.polylines(image_tensor.numpy(), [polygon], True, (0,255,0),3)
cv2.imshow("Frame", img_mod)
cv2.waitKey()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()