-
Notifications
You must be signed in to change notification settings - Fork 0
/
valid_crf_twice.py
617 lines (495 loc) · 22.4 KB
/
valid_crf_twice.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# string input
# twice compression (same crf), same interval, (7,4) lcb
# logger, calculate precision + recall
import os
from loguru import logger
from datetime import datetime
from torch.utils.data import DataLoader
from utils import *
from network.Network import *
from utils.linear_block_code import *
from utils.save_images import save_per_frame
from utils.fix_seed import set_random_seed
from utils.video_attacks import video_compression_attack, video_compression_attack2
from sklearn.metrics import recall_score
def validation_twice_crf(network, save_path, valid_path='results/combine5_valid_continous'):
# valid_cfg
batch_size = 1
strength_factor = 1
message_length = 8040
H = 1920
W = 1072
# codec args
crf = str(28)
resize_ratio = str(1.0)
fps = 30
compress_type = 'h264'
# linear block coding args, (robust_length, information_length)
information_length = 4
robust_length = 7
interval = 10
total_length = 500
# watermark
s = 'bilibili@copyright'
# IO args
cover_folder = valid_path # original Image folder
encode_folder = os.path.join(save_path, 'encode') # watermarked image folder
compress_folder = os.path.join(save_path, 'compress') # compressed image folder
logger.info("target message is: " + s)
set_random_seed(0)
# torch.backends.cudnn.benchmark = False
# torch.backends.cudnn.deterministic = True
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
test_dataset = MBRSTestDataset(cover_folder, H, W)
test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=0, pin_memory=True)
logger.info("Start Encoding...")
test_result = {
"psnr": 0.0,
"ssim": 0.0
}
message_used = torch.tensor(stringToBitArray(s, 8)).to(device)
message_unit_length = len(message_used) // information_length * robust_length # start of tail clip in message
message_tail_position = message_length // message_unit_length * message_unit_length # repeat until the end
repeat_time = message_length // message_unit_length
G = np.array([[1, 1, 1, 1, 0, 0, 0],
[1, 1, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 1, 0],
[0, 1, 1, 0, 0, 0, 1]])
lbc = LinearBlockCode()
lbc.setG(G)
num = 0
for i, images in enumerate(test_dataloader):
image = images.to(device)
message_root = torch.Tensor(np.random.choice([0, 1], (image.shape[0], message_length))).to(device)
message = torch.zeros_like(message_root)
message[:, message_tail_position:] = message_root[:, message_tail_position:]
message_used_np = message_used.view(1, -1, information_length).repeat(batch_size, 1, 1).cpu().numpy()
robust_message_list = []
for b_i in range(batch_size):
robust_message_list.append(torch.Tensor(lbc.c(message_used_np[b_i])).view(1, -1))
robust_message = torch.cat(robust_message_list, 0)
robust_message = torch.tile(robust_message, (1, repeat_time))
message[:, :message_tail_position] = robust_message
'''
test
'''
network.encoder_decoder.eval()
network.discriminator.eval()
with torch.no_grad():
# use device to compute
images, messages = images.to(network.device), message.to(network.device)
if i % interval == 0:
encoded_images = network.encoder_decoder.module.encoder(images, messages)
encoded_images = images + (encoded_images - image) * strength_factor
for j in range(batch_size):
frame = i * batch_size + j
if i % interval == 0:
# logger.info("save encoded frame {}", i)
save_per_frame(encoded_images[j], frame, encode_folder)
else:
save_per_frame(images[j], frame, encode_folder)
# psnr
psnr = kornia.losses.psnr_loss(encoded_images.detach(), images, 2).item()
# ssim
ssim = 1 - 2 * kornia.losses.ssim_loss(encoded_images.detach(), images, window_size=5, reduction="mean").item()
result = {
"psnr": psnr,
"ssim": ssim,
}
if i % interval == 0:
for key in result:
test_result[key] += float(result[key])
num += 1
if num == total_length:
break
print(num)
'''
test results
'''
content = "Average :"
for key in test_result:
content += key + "=" + str(test_result[key] / (num // interval)) + ","
logger.info(content)
return_psnr = - test_result["psnr"] / (num // interval)
return_ssim = test_result["ssim"] / (num // interval)
# compress
intermediate_compress_folder = os.path.join(save_path, 'compress_intermediate')
video_compression_attack(encode_folder, intermediate_compress_folder, crf, resize_ratio, fps, compress_type, logger, interval)
video_compression_attack(intermediate_compress_folder, compress_folder, crf, resize_ratio, fps, compress_type, logger, interval)
# decode
set_random_seed(0)
test_dataset = MBRSTestDataset(compress_folder, H, W)
test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=0, pin_memory=True)
logger.info("Start Decoding :")
num = 0
result_list = []
for i, compress_images in enumerate(test_dataloader):
compress_images = compress_images.to(device)
compress_images = F.interpolate(compress_images, size=(image.shape[2],image.shape[3]), mode='bicubic')
# message = torch.Tensor(np.random.choice([0, 1], (compress_images.shape[0], message_length))).to(device)
message_root = torch.Tensor(np.random.choice([0, 1], (image.shape[0], message_length))).to(device)
message = torch.zeros_like(message_root)
message[:, message_tail_position:] = message_root[:, message_tail_position:]
message_used_np = message_used.view(1, -1, information_length).repeat(batch_size, 1, 1).cpu().numpy()
robust_message_list = []
for b_i in range(batch_size):
robust_message_list.append(torch.Tensor(lbc.c(message_used_np[b_i])).view(1, -1))
robust_message = torch.cat(robust_message_list, 0)
robust_message = torch.tile(robust_message, (1, repeat_time))
message[:, :message_tail_position] = robust_message
'''
test
'''
network.encoder_decoder.eval()
network.discriminator.eval()
with torch.no_grad():
# use device to compute
compress_images, messages = compress_images.to(network.device), message.to(network.device)
if i % interval == 0:
decoded_messages = network.encoder_decoder.module.decoder(compress_images)
else:
continue
useful_messages = decoded_messages[:, :message_tail_position]
useful_messages = useful_messages.view(batch_size, repeat_time, message_unit_length)
voted_messages = torch.mean(useful_messages, dim=1)
# voted_messages = useful_messages[:, 0, :]
'''
decoded message error rate
'''
voted_messages = voted_messages.gt(0.5).int()
# lbc error correction
for b in range(batch_size):
rs = voted_messages
rs = rs.reshape(-1, lbc.n()).cpu().numpy()
cs = np.zeros_like(rs)
for j in range(len(rs)):
cs[j] = lbc.syndromeDecode(rs[j])
rm = cs[:, -lbc.k():].reshape(-1)
res = bitArrayToString(rm)
try:
logger.info("message after decoding frame-{}: " + res, i * batch_size + b)
result_list.append(res == s)
except Exception as e:
result_list.append(False)
logger.info(e)
num += 1
y_true = [True for i in range(len(result_list))]
recall = recall_score(y_true, result_list, average='binary')
logger.info("recall: {}", recall)
return return_psnr, return_ssim, recall
def validation_twice_crf_shift(network, save_path, valid_path='results/combine5_valid_continous'):
# valid_cfg
batch_size = 1
strength_factor = 1
message_length = 8040
H = 1920
W = 1072
# codec args
crf = str(27)
resize_ratio = str(1.0)
fps = 30
compress_type = 'h264'
# linear block coding args, (robust_length, information_length)
information_length = 4
robust_length = 7
interval = 10
total_length = 500
# watermark
s = 'bilibili@copyright'
# IO args
cover_folder = valid_path # original Image folder
encode_folder = os.path.join(save_path, 'encode') # watermarked image folder
compress_folder = os.path.join(save_path, 'compress') # compressed image folder
logger.info("target message is: " + s)
set_random_seed(0)
# torch.backends.cudnn.benchmark = False
# torch.backends.cudnn.deterministic = True
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
test_dataset = MBRSTestDataset(cover_folder, H, W)
test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=0, pin_memory=True)
logger.info("Start Encoding...")
test_result = {
"psnr": 0.0,
"ssim": 0.0
}
message_used = torch.tensor(stringToBitArray(s, 8)).to(device)
message_unit_length = len(message_used) // information_length * robust_length # start of tail clip in message
message_tail_position = message_length // message_unit_length * message_unit_length # repeat until the end
repeat_time = message_length // message_unit_length
G = np.array([[1, 1, 1, 1, 0, 0, 0],
[1, 1, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 1, 0],
[0, 1, 1, 0, 0, 0, 1]])
lbc = LinearBlockCode()
lbc.setG(G)
num = 0
for i, images in enumerate(test_dataloader):
image = images.to(device)
message_root = torch.Tensor(np.random.choice([0, 1], (image.shape[0], message_length))).to(device)
message = torch.zeros_like(message_root)
message[:, message_tail_position:] = message_root[:, message_tail_position:]
message_used_np = message_used.view(1, -1, information_length).repeat(batch_size, 1, 1).cpu().numpy()
robust_message_list = []
for b_i in range(batch_size):
robust_message_list.append(torch.Tensor(lbc.c(message_used_np[b_i])).view(1, -1))
robust_message = torch.cat(robust_message_list, 0)
robust_message = torch.tile(robust_message, (1, repeat_time))
message[:, :message_tail_position] = robust_message
'''
test
'''
network.encoder_decoder.eval()
network.discriminator.eval()
with torch.no_grad():
# use device to compute
images, messages = images.to(network.device), message.to(network.device)
if i % interval == 0:
encoded_images = network.encoder_decoder.module.encoder(images, messages)
encoded_images = images + (encoded_images - image) * strength_factor
for j in range(batch_size):
frame = i * batch_size + j
if i % interval == 0:
# logger.info("save encoded frame {}", i)
save_per_frame(encoded_images[j], frame, encode_folder)
else:
save_per_frame(images[j], frame, encode_folder)
# psnr
psnr = kornia.losses.psnr_loss(encoded_images.detach(), images, 2).item()
# ssim
ssim = 1 - 2 * kornia.losses.ssim_loss(encoded_images.detach(), images, window_size=5, reduction="mean").item()
result = {
"psnr": psnr,
"ssim": ssim,
}
if i % interval == 0:
for key in result:
test_result[key] += float(result[key])
num += 1
if num == total_length:
break
print(num)
'''
test results
'''
content = "Average :"
for key in test_result:
content += key + "=" + str(test_result[key] / (num // interval)) + ","
logger.info(content)
return_psnr = - test_result["psnr"] / (num // interval)
return_ssim = test_result["ssim"] / (num // interval)
# compress
intermediate_compress_folder = os.path.join(save_path, 'compress_intermediate')
video_compression_attack(encode_folder, intermediate_compress_folder, crf, resize_ratio, fps, compress_type, logger, interval)
video_compression_attack2(intermediate_compress_folder, compress_folder, crf, resize_ratio, fps, compress_type, logger, shift=interval // 2)
# decode
set_random_seed(0)
test_dataset = MBRSTestDataset(compress_folder, H, W)
test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=0, pin_memory=True)
logger.info("Start Decoding :")
num = 0
result_list = []
for i, compress_images in enumerate(test_dataloader):
compress_images = compress_images.to(device)
compress_images = F.interpolate(compress_images, size=(image.shape[2],image.shape[3]), mode='bicubic')
# message = torch.Tensor(np.random.choice([0, 1], (compress_images.shape[0], message_length))).to(device)
message_root = torch.Tensor(np.random.choice([0, 1], (image.shape[0], message_length))).to(device)
message = torch.zeros_like(message_root)
message[:, message_tail_position:] = message_root[:, message_tail_position:]
message_used_np = message_used.view(1, -1, information_length).repeat(batch_size, 1, 1).cpu().numpy()
robust_message_list = []
for b_i in range(batch_size):
robust_message_list.append(torch.Tensor(lbc.c(message_used_np[b_i])).view(1, -1))
robust_message = torch.cat(robust_message_list, 0)
robust_message = torch.tile(robust_message, (1, repeat_time))
message[:, :message_tail_position] = robust_message
'''
test
'''
network.encoder_decoder.eval()
network.discriminator.eval()
with torch.no_grad():
# use device to compute
compress_images, messages = compress_images.to(network.device), message.to(network.device)
if i % interval == (interval - interval // 2):
decoded_messages = network.encoder_decoder.module.decoder(compress_images)
else:
continue
useful_messages = decoded_messages[:, :message_tail_position]
useful_messages = useful_messages.view(batch_size, repeat_time, message_unit_length)
voted_messages = torch.mean(useful_messages, dim=1)
# voted_messages = useful_messages[:, 0, :]
'''
decoded message error rate
'''
voted_messages = voted_messages.gt(0.5).int()
# lbc error correction
for b in range(batch_size):
rs = voted_messages
rs = rs.reshape(-1, lbc.n()).cpu().numpy()
cs = np.zeros_like(rs)
for j in range(len(rs)):
cs[j] = lbc.syndromeDecode(rs[j])
rm = cs[:, -lbc.k():].reshape(-1)
res = bitArrayToString(rm)
try:
logger.info("message after decoding frame-{}: " + res, i * batch_size + b)
result_list.append(res == s)
except Exception as e:
result_list.append(False)
logger.info(e)
num += 1
y_true = [True for i in range(len(result_list))]
recall = recall_score(y_true, result_list, average='binary')
logger.info("recall: {}", recall)
return return_psnr, return_ssim, recall
def validation_twice_crf_repeat(network, save_path, valid_path='results/combine5_valid_continous', opt={}):
# valid_cfg
batch_size = 1
strength_factor = 1
message_length = opt.get('crf_val_msg_length', 256)
H = 1920
W = 1072
# codec args
crf = str(opt.get('crf', 32))
resize_ratio = str(1.0)
fps = 30
compress_type = 'h264'
interval = 10
total_length = 500
# watermark
s = opt.get('wtm', 'bilibili@copyright')
shift_crf_valid = opt.get('shift_crf_valid', False)
if shift_crf_valid:
decode_frame = (interval - interval // 2)
else:
decode_frame = 0
# IO args
cover_folder = valid_path # original Image folder
encode_folder = os.path.join(save_path, 'encode') # watermarked image folder
compress_folder = os.path.join(save_path, 'compress') # compressed image folder
logger.info("target message is: " + s)
set_random_seed(0)
# torch.backends.cudnn.benchmark = False
# torch.backends.cudnn.deterministic = True
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
test_dataset = MBRSTestDataset(cover_folder, H, W)
test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=0, pin_memory=True)
logger.info("Start Encoding...")
test_result = {
"psnr": 0.0,
"ssim": 0.0
}
message_used = torch.tensor(stringToBitArray(s, 8)).to(device)
message_unit_length = len(message_used) # start of tail clip in message
message_tail_position = message_length // message_unit_length * message_unit_length # repeat until the end
repeat_time = message_length // message_unit_length
num = 0
for i, images in enumerate(test_dataloader):
image = images.to(device)
message_root = torch.Tensor(np.random.choice([0, 1], (image.shape[0], message_length))).to(device)
message = torch.zeros_like(message_root)
message[:, message_tail_position:] = message_root[:, message_tail_position:]
robust_message = message_used.unsqueeze(0).expand(batch_size, -1)
robust_message = torch.tile(robust_message, (1, repeat_time))
message[:, :message_tail_position] = robust_message
'''
test
'''
network.encoder_decoder.eval()
network.discriminator.eval()
with torch.no_grad():
# use device to compute
images, messages = images.to(network.device), message.to(network.device)
if i % interval == 0:
encoded_images = network.encoder_decoder.module.encoder(images, messages)
encoded_images = images + (encoded_images - image) * strength_factor
for j in range(batch_size):
frame = i * batch_size + j
if i % interval == 0:
# logger.info("save encoded frame {}", i)
save_per_frame(encoded_images[j], frame, encode_folder)
else:
save_per_frame(images[j], frame, encode_folder)
# psnr
psnr = kornia.losses.psnr_loss(encoded_images.detach(), images, 2).item()
# ssim
ssim = 1 - 2 * kornia.losses.ssim_loss(encoded_images.detach(), images, window_size=5, reduction="mean").item()
result = {
"psnr": psnr,
"ssim": ssim,
}
if i % interval == 0:
for key in result:
test_result[key] += float(result[key])
num += 1
if num == total_length:
break
print(num)
'''
test results
'''
content = "Average :"
for key in test_result:
content += key + "=" + str(test_result[key] / (num // interval)) + ","
logger.info(content)
return_psnr = - test_result["psnr"] / (num // interval)
return_ssim = test_result["ssim"] / (num // interval)
# compress
intermediate_compress_folder = os.path.join(save_path, 'compress_intermediate')
video_compression_attack(encode_folder, intermediate_compress_folder, crf, resize_ratio, fps, compress_type, logger, interval)
if shift_crf_valid:
video_compression_attack2(intermediate_compress_folder, compress_folder, crf, resize_ratio, fps, compress_type, logger, shift=interval // 2)
else:
video_compression_attack(intermediate_compress_folder, compress_folder, crf, resize_ratio, fps, compress_type, logger, interval)
# decode
set_random_seed(0)
test_dataset = MBRSTestDataset(compress_folder, H, W)
test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=0, pin_memory=True)
logger.info("Start Decoding :")
num = 0
result_list = []
for i, compress_images in enumerate(test_dataloader):
compress_images = compress_images.to(device)
compress_images = F.interpolate(compress_images, size=(image.shape[2],image.shape[3]), mode='bicubic')
# message = torch.Tensor(np.random.choice([0, 1], (compress_images.shape[0], message_length))).to(device)
message_root = torch.Tensor(np.random.choice([0, 1], (image.shape[0], message_length))).to(device)
message = torch.zeros_like(message_root)
message[:, message_tail_position:] = message_root[:, message_tail_position:]
robust_message = message_used.unsqueeze(0).expand(batch_size, -1)
robust_message = torch.tile(robust_message, (1, repeat_time))
message[:, :message_tail_position] = robust_message
'''
test
'''
network.encoder_decoder.eval()
network.discriminator.eval()
with torch.no_grad():
# use device to compute
compress_images, messages = compress_images.to(network.device), message.to(network.device)
if i % interval == decode_frame:
decoded_messages = network.encoder_decoder.module.decoder(compress_images)
else:
continue
useful_messages = decoded_messages[:, :message_tail_position]
useful_messages = useful_messages.view(batch_size, repeat_time, message_unit_length)
voted_messages = torch.mean(useful_messages, dim=1)
# voted_messages = useful_messages[:, 0, :]
'''
decoded message error rate
'''
voted_messages = voted_messages.gt(0.5).int()
# lbc error correction
for b in range(batch_size):
rs = voted_messages[b].cpu().numpy()
res = bitArrayToString(rs)
try:
logger.info("message after decoding frame-{}: " + res, i * batch_size + b)
result_list.append(res == s)
except Exception as e:
result_list.append(False)
logger.info(e)
num += 1
y_true = [True for i in range(len(result_list))]
recall = recall_score(y_true, result_list, average='binary')
logger.info("recall: {}", recall)
return return_psnr, return_ssim, recall