-
Notifications
You must be signed in to change notification settings - Fork 0
/
my_per_frame_saliency_figure_4.py
324 lines (264 loc) · 16.8 KB
/
my_per_frame_saliency_figure_4.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
"""
Compress the video through gradient-based optimization.
"""
import argparse
import gc
import logging
import time
from pathlib import Path
import pickle
import shutil
import coloredlogs
import enlighten
import matplotlib.pyplot as plt
import seaborn as sns
import torch
import torch.nn.functional as F
import torchvision.transforms as T
from detectron2.structures.boxes import pairwise_iou
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import io
from dnn.dnn_factory import DNN_Factory
from utils.bbox_utils import center_size
from utils.loss_utils import focal_loss as get_loss
from utils.mask_utils import *
from utils.results_utils import read_ground_truth, read_results
from utils.timer import Timer
from utils.video_utils import get_qp_from_name, read_videos, write_video
from utils.visualize_utils import visualize_heat_by_summarywriter
from detectron2.structures.instances import Instances
from detectron2.structures.boxes import Boxes
from my_utils import *
# construct applications
dnn = "FasterRCNN_ResNet50_FPN"
# dnn = "COCO-Detection/faster_rcnn_R_101_FPN_3x.yaml"
app = DNN_Factory().get_model(dnn)
app.cuda()
# working_dir_path = "/tank/qizheng/codec_project/accmpeg/"
# working_dir_path = "/datamirror/qizhengz/codec_project/"
working_dir_path = "/tank/qizheng/codec_project/"
def compress_saliency(video_input, high_quality_qp, low_quality_qp, img_w = 1280, img_h = 720):
# initialize
if img_h % 16 == 0 and img_w % 16 == 0:
tile_size = 16
else:
tile_size = 8
# tile_size = 16
logger = logging.getLogger("saliency")
logger.addHandler(logging.FileHandler("saliency.log"))
percent = 0.1
# read the video frames (will use the largest video as ground truth)
print(f"Reading in video {video_input} for compression (saliency-based)")
if not os.path.exists(working_dir_path + f"{video_input}_qp{low_quality_qp}_local_codec/"):
encode_video(working_dir_path + f"{video_input}", \
working_dir_path + f"{video_input}_qp{low_quality_qp}_local_codec.mp4", \
low_quality_qp)
decode_video(working_dir_path + f"{video_input}_qp{low_quality_qp}_local_codec.mp4", \
working_dir_path + f"{video_input}_qp{low_quality_qp}_local_codec/")
video_slice_gt = get_image(working_dir_path + f"{video_input}/").unsqueeze(0)
video_slice_lq = get_image(working_dir_path + f"{video_input}_qp{low_quality_qp}_local_codec/").unsqueeze(0)
# saliency_original_frames = Video_Dataset(working_dir_path + f"{video_input}/")
# saliency_lq_frames = Video_Dataset(working_dir_path + f"{video_input}_qp{low_quality_qp}_local_codec/")
# if fid % 100 == 0:
# print(f"Processing frame {fid}")
# video_slice_gt = saliency_original_frames[fid]['image'].unsqueeze(0)
# video_slice_lq = saliency_lq_frames[fid]['image'].unsqueeze(0)
# smap, _ = generate_saliency_map(video_slice_gt, app) # saliency computation
smap, _ = generate_saliency_map(video_slice_lq, app) # saliency computation
emap = abs(video_slice_lq - video_slice_gt)
saliency_sum = abs(smap * emap)
# compute mb-level saliency mask
saliency_sum_mb = F.conv2d(
saliency_sum.sum(dim=1, keepdim=True),
torch.ones([1, 1, tile_size, tile_size]),
stride=tile_size
)
threshold_mb = compute_saliency_threshold_percent(saliency_sum_mb, percent, sum_flag = False)
saliency_mask_mb = (saliency_sum_mb > threshold_mb).float()
saliency_mask_mb_tiled = tile_mask(saliency_mask_mb, tile_size)[0][0].unsqueeze(0).unsqueeze(0)
# save mask
with open(f"masks/{video_input}_saliency_per_frame_{high_quality_qp}_{low_quality_qp}.pt", "wb") as f:
pickle.dump(saliency_mask_mb_tiled, f)
# encode high-quality regions
saliency_high_quality_region = video_slice_gt.cpu() * saliency_mask_mb_tiled.cpu()
save_and_encode(saliency_high_quality_region[0], working_dir_path + video_input, f"saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}", high_quality_qp)
# encode low-quality background
# saliency_low_quality_region = video_slice_gt.cpu() * (torch.ones_like(saliency_mask_mb_tiled) - saliency_mask_mb_tiled).cpu()
save_and_encode(video_slice_lq[0], working_dir_path + video_input, f"saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}", low_quality_qp)
# encoding for smoothing (no need now)
# mask_tiled_reuse = None
# with open(f"masks/videos/trafficcam_2_{int((frame_idx - 1) // 10 * 10 + 1)}_saliency_per_frame_{high_quality_qp}_{low_quality_qp}.pt", "rb") as f:
# mask_tiled_reuse = pickle.load(f)
# saliency_high_quality_region_smooth = video_slice_gt.cpu() * mask_tiled_reuse.cpu()
# save_and_encode(saliency_high_quality_region_smooth[0], video_input, f"saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}_smooth", high_quality_qp)
# saliency_low_quality_region_smooth = video_slice_gt.cpu() * (torch.ones_like(mask_tiled_reuse) - mask_tiled_reuse).cpu()
# save_and_encode(video_slice_lq[0], video_input, f"saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}_smooth", low_quality_qp)
def my_inference(video_input, high_quality_qp, low_quality_qp, stats_file_name):
# read in the encoded video as Dataset objects
print(f"Reading in video {video_input} for inference")
# gt_frames = Video_Dataset(working_dir_path + f"{video_input}/")
video_slice_gt = get_image(working_dir_path + f"{video_input}/").unsqueeze(0)
# non-smoothing
decode_video(working_dir_path + f"{video_input}_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}.mp4",
working_dir_path + f"{video_input}_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}_decoded",)
# saliency_high_quality_frames = Video_Dataset(working_dir_path + f"{video_input}_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}_decoded/")
saliency_high_quality_frame = get_image(working_dir_path + f"{video_input}_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}_decoded/").unsqueeze(0)
decode_video(working_dir_path + f"{video_input}_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}.mp4",
working_dir_path + f"{video_input}_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}_decoded",)
# saliency_low_quality_frames = Video_Dataset(working_dir_path + f"{video_input}_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}_decoded/")
saliency_low_quality_frame = get_image(working_dir_path + f"{video_input}_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}_decoded/").unsqueeze(0)
with open(f"masks/{video_input}_saliency_per_frame_{high_quality_qp}_{low_quality_qp}.pt", "rb") as f:
mask = pickle.load(f)
# smoothing (no need now)
# decode_video(video_input + f"_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}_smooth.mp4",
# video_input + f"_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}_smooth_decoded",)
# saliency_high_quality_frames_smooth = Video_Dataset(f"{video_input}" + f"_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}_smooth_decoded/")
# decode_video(video_input + f"_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}_smooth.mp4",
# video_input + f"_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}_smooth_decoded",)
# saliency_low_quality_frames_smooth = Video_Dataset(f"{video_input}" + f"_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}_smooth_decoded/")
# with open(f"masks/videos/trafficcam_2_{int((frame_idx - 1) // 10 * 10 + 1)}_saliency_per_frame_{high_quality_qp}_{low_quality_qp}.pt", "rb") as f:
# mask_reuse = pickle.load(f)
loss_saliency, loss_saliency_smooth = 0, 0
# process the video frame by frame
# if fid % 100 == 0:
# print(f"Processing frame {fid}")
# compute gt result and qp 40 result for this frame
# video_slice_gt = gt_frames[fid]['image'].unsqueeze(0)
gt_result = infer(video_slice_gt, app)
# non-smoothing
# saliency_high_quality_frame = saliency_high_quality_frames[fid]['image'].unsqueeze(0)
# saliency_low_quality_frame = saliency_low_quality_frames[fid]['image'].unsqueeze(0)
saliency_hybrid_frame = saliency_high_quality_frame.cpu() * mask.cpu() + \
saliency_low_quality_frame.cpu() * (torch.ones_like(mask) - mask).cpu()
saliency_hybrid_frame.require_grad = True
result_saliency_hybrid_frame = app.inference(saliency_hybrid_frame.cuda(), nograd=False)
result_saliency_hybrid_frame = detach_result(result_saliency_hybrid_frame)
loss_saliency_hybrid_frame, _ = compute_loss(result_saliency_hybrid_frame, gt_result)
loss_saliency += abs(loss_saliency_hybrid_frame)
# smoothing (no need now)
# saliency_high_quality_frame_smooth = saliency_high_quality_frames_smooth[fid]['image'].unsqueeze(0)
# saliency_low_quality_frame_smooth = saliency_low_quality_frames_smooth[fid]['image'].unsqueeze(0)
# saliency_hybrid_frame_smooth = saliency_high_quality_frame_smooth.cpu() * mask_reuse.cpu() + \
# saliency_low_quality_frame_smooth.cpu() * (torch.ones_like(mask_reuse) - mask_reuse).cpu()
# saliency_hybrid_frame_smooth.require_grad = True
# result_saliency_hybrid_frame_smooth = app.inference(saliency_hybrid_frame_smooth.cuda(), nograd=False)
# result_saliency_hybrid_frame_smooth = detach_result(result_saliency_hybrid_frame_smooth)
# loss_saliency_hybrid_frame_smooth, _ = compute_loss(result_saliency_hybrid_frame_smooth, gt_result)
# loss_saliency_smooth += abs(loss_saliency_hybrid_frame_smooth)
# compute average loss per frame
# loss_saliency /= len(gt_frames)
# loss_saliency_smooth /= len(gt_frames)
# get file sizes
saliency_high_quality_frames_fs = os.path.getsize(working_dir_path + f"{video_input}_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}.mp4")
saliency_low_quality_frames_fs = os.path.getsize(working_dir_path + f"{video_input}_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}.mp4")
saliency_fs = saliency_high_quality_frames_fs + saliency_low_quality_frames_fs
# saliency_high_quality_frames_fs_smooth = os.path.getsize(f"{video_input}" + f"_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}_smooth.mp4")
# saliency_low_quality_frames_fs_smooth = os.path.getsize(f"{video_input}" + f"_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}_smooth.mp4")
# saliency_fs_smooth = saliency_high_quality_frames_fs_smooth + saliency_low_quality_frames_fs_smooth
# with open(f"stats_files/tradeoff_files/tf2_1800_frames_tmp_4", "a+") as f:
# if not isinstance(loss_saliency, float) and not isinstance(loss_saliency_smooth, float):
# f.write(f"{video_input},{fid},{high_quality_qp},{low_quality_qp},{abs(loss_saliency).item()},{saliency_fs},{abs(loss_saliency_smooth).item()},{saliency_fs_smooth}\n")
# elif not isinstance(loss_saliency_smooth, float):
# f.write(f"{video_input},{fid},{high_quality_qp},{low_quality_qp},{abs(loss_saliency)},{saliency_fs},{abs(loss_saliency_smooth).item()},{saliency_fs_smooth}\n")
# else:
# f.write(f"{video_input},{fid},{high_quality_qp},{low_quality_qp},{abs(loss_saliency)},{saliency_fs},{abs(loss_saliency_smooth)},{saliency_fs_smooth}\n")
# with open(f"stats_files/tradeoff_files/tf2_1800_frames_downsampled_saliency_per_frame_figure_3_1101", "a+") as f:
with open(stats_file_name, "a+") as f:
if not isinstance(loss_saliency, float):
f.write(f"{video_input},0,{high_quality_qp},{low_quality_qp},{abs(loss_saliency).item()},{saliency_fs}\n")
else:
f.write(f"{video_input},0,{high_quality_qp},{low_quality_qp},{abs(loss_saliency)},{saliency_fs}\n")
# cleaning for saving disk space (optional)
if os.path.exists(working_dir_path + f"{video_input}_qp{low_quality_qp}_local_codec.mp4"):
os.remove(working_dir_path + f"{video_input}_qp{low_quality_qp}_local_codec.mp4")
# shutil.rmtree(working_dir_path + f"{video_input}_qp{low_quality_qp}_local_codec/")
os.remove(f"masks/{video_input}_saliency_per_frame_{high_quality_qp}_{low_quality_qp}.pt")
os.remove(working_dir_path + f"{video_input}_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}.mp4")
os.remove(working_dir_path + f"{video_input}_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}.mp4")
shutil.rmtree(working_dir_path + f"{video_input}_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}_decoded/", ignore_errors=True)
shutil.rmtree(working_dir_path + f"{video_input}_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}_decoded/", ignore_errors=True)
shutil.rmtree(working_dir_path + f"{video_input}_saliency_per_frame_hq_{high_quality_qp}_{low_quality_qp}/")
shutil.rmtree(working_dir_path + f"{video_input}_saliency_per_frame_lq_{high_quality_qp}_{low_quality_qp}/")
##### main function
# video_list = [f"videos/trafficcam_2_{i}" for i in range(1,1801,10)]
# vid_names = ["videos/tf1"] * 300 + ["videos/tf2"] * 300 + ["videos/tf3"] * 300 + ["videos/tf4"] * 300 + ["videos/tf5"] * 300
# video_list = [f"videos/trafficcam_1_{i}" for i in range(1,301,1)] + \
# [f"videos/trafficcam_2_{i}" for i in range(1,301,1)] + \
# [f"videos/trafficcam_3_{i}" for i in range(1,301,1)] + \
# [f"videos/trafficcam_4_{i}" for i in range(1,301,1)] + \
# [f"videos/trafficcam_5_{i}" for i in range(1,301,1)]
# HotMobile submiited experiments
# vid_names = ["videos/tf5"] * 300
# video_list = [f"videos/trafficcam_5_{i}" for i in range(1,301,1)]
# Camera-ready experiments (diverse scenes)
# resolutions = [(1280, 720)] * 300
# vid_names = ["videos/cityscape_5"] * 300
# video_list = [f"videos/cityscape_5_{i}" for i in range(1,301,1)]
# resolutions = [(1920, 1080)] * 300 + \
# [(1280, 720)] * 600 + \
# [(1920, 1080)] * 600
# vid_names = ["videos/cityscape_2"] * 300 + \
# ["videos/cityscape_5"] * 300 + \
# ["videos/cityscape_6"] * 300 + \
# ["videos/cityscape_7"] * 300 + \
# ["videos/cityscape_8"] * 300
# video_list = [f"videos/cityscape_2_{i}" for i in range(1,301,1)] + \
# [f"videos/cityscape_5_{i}" for i in range(1,301,1)] + \
# [f"videos/cityscape_6_{i}" for i in range(1,301,1)] + \
# [f"videos/cityscape_7_{i}" for i in range(1,301,1)] + \
# [f"videos/cityscape_8_{i}" for i in range(1,301,1)]
# resolutions = [(1920, 1080)] * 1200
# vid_names = ["videos/cityscape_2"] * 300 + \
# ["videos/cityscape_4"] * 300 + \
# ["videos/cityscape_7"] * 300 + \
# ["videos/cityscape_8"] * 300
# video_list = [f"videos/cityscape_2_{i}" for i in range(1,301,1)] + \
# [f"videos/cityscape_4_{i}" for i in range(1,301,1)] + \
# [f"videos/cityscape_7_{i}" for i in range(1,301,1)] + \
# [f"videos/cityscape_8_{i}" for i in range(1,301,1)]
resolutions = [(1920, 1080)] * 1500
vid_names = ["videos/cityscape_1"] * 300 + \
["videos/cityscape_2"] * 300 + \
["videos/cityscape_4"] * 300 + \
["videos/cityscape_7"] * 300 + \
["videos/cityscape_8"] * 300
video_list = [f"videos/cityscape_1_{i}" for i in range(1,301,1)] + \
[f"videos/cityscape_2_{i}" for i in range(1,301,1)] + \
[f"videos/cityscape_4_{i}" for i in range(1,301,1)] + \
[f"videos/cityscape_7_{i}" for i in range(1,301,1)] + \
[f"videos/cityscape_8_{i}" for i in range(1,301,1)]
# hq_qps = [0, 10, 20]
# lq_qps = [40, 40, 40]
# hq_qps = [2] * 6 + [6] * 6 + [10] * 6 + [14] * 6
# lq_qps = [28, 30, 32, 34, 36, 38]
hq_qps = [2] * 4
lq_qps = [28, 36, 40, 44]
# smooth = 10
time_compression, time_inference = 0.0, 0.0
# compress saliency
for frame_index in range(len(video_list)):
video = video_list[frame_index]
vid_name = vid_names[frame_index]
resolution = resolutions[frame_index]
# file creation
if not os.path.exists(working_dir_path + video):
os.mkdir(working_dir_path + video)
subprocess.run(["cp", f"{working_dir_path}{vid_name}/{str(frame_index).zfill(10)}.png", \
f"{working_dir_path}{video}/0000000000.png"])
# import pdb; pdb.set_trace()
for i in range(len(hq_qps)):
hq_qp, lq_qp = hq_qps[i], lq_qps[i]
stats_file_name = f"stats_files_cr/{vid_name}_300_frames_saliency_figure_3_{hq_qp}_{lq_qp}_cr"
# compression
start_compress = time.time()
compress_saliency(video, hq_qp, lq_qp, resolution[0], resolution[1])
end_compress = time.time()
time_compression += (end_compress - start_compress)
# inference
start_infer = time.time()
my_inference(video, hq_qp, lq_qp, stats_file_name)
end_infer = time.time()
time_inference += (end_infer - start_infer)
print(time_compression)
print(time_inference)