-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_attack.py
More file actions
141 lines (139 loc) · 6.59 KB
/
example_attack.py
File metadata and controls
141 lines (139 loc) · 6.59 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
import dlib
import random
import os
import re
import sys
import csv
import matplotlib as plt
import numpy as np
from skimage import io
from skimage.metrics import structural_similarity as ssim
from hideface import tools, imagelabels, attacks, utils
from PIL import Image
if __name__ == "__main__":
truth_file = 'data/wider_face_split/wider_face_train_bbx_gt.txt'
detector_dict = {'hog':dlib.get_frontal_face_detector()}
num_imgs = 25
img_input_dir = 'data/WIDER_train/images/51--Dresses'
img_paths = utils.get_img_paths(img_input_dir, num_imgs)
output_dir = 'data/attack_example'
attack_record_filename = 'performance_list.csv'
result_counter_filename = 'tunnel.csv'
use_mult_noise = False #use multiplicative noise, where large pixel value means more noise
n_attack_tests = 1
attack_success_freq_threshold = 0.8
epsilon_start_value = 16
max_epsilon_value = 240
epsilon_delta = 16
iou_cutoff_value = 0.2
performance_list = []
#a dictionary for storing the counts of how often each type of image error/result occurs
tunnel_dict = {
'total_img_count':0,
'bad_image':0,
'multiple_faces_count':0,
'zero_faces_count':0,
'bad_quality_count':0,
'no_found_faces_count':0,
'fail_count':0,
'successful_attack':0}
utils.test_paths(attack_record_filename, result_counter_filename, output_dir)
for detector_name, _ in detector_dict.items():
count = 0
for img_path in img_paths:
img_num = re.findall(r'[0-9]+_[0-9]+\.jpg', str(img_path))[0][:-4]
tunnel_dict['total_img_count'] += 1
count += 1
if (count > num_imgs): break
print('Testing Image: ' + img_num + '\t(' + str(count) + '/' + str(num_imgs) + ')')
try:
image_labels, truth_iou_no_noise = utils.test_image(
img_path,
truth_file,
detector_dict,
detector_name,
iou_cutoff_value,
tunnel_dict,
output_dir)
except ValueError as e:
print(e)
continue
box_height = image_labels.true_box_list[0].height
box_width = image_labels.true_box_list[0].width
performance_dict = {
'img_num':img_num,
'epsilon':-1,
'img_size':image_labels.img_shape[0]*image_labels.img_shape[1],
'true_box_size':box_height * box_width,
'truth_iou_no_noise':truth_iou_no_noise,
'truth_iou_noise_avg':-1,
'ssim_avg':-1}
epsilon = epsilon_start_value
while (epsilon < max_epsilon_value):
try:
image_noise_pairs = attacks.create_noisy_face(
image_labels.found_box_dict[detector_name][0],
img_path,
epsilon,
n_attack_tests,
output_dir,
use_mult_noise=use_mult_noise)
except ValueError as e:
print(e)
continue
attack_success_count = 0
attack_fail_count = 0
truth_iou_noise_avg = 0
for img_pair in image_noise_pairs:
attacked_img = img_pair.img
noise_img = img_pair.noise
found_boxes = tools.get_found_boxes(attacked_img, detector_dict[detector_name])
if (len(found_boxes) == 0):
truth_iou_noise = 0
else:
true_box = image_labels.true_box_list[0]
found_box = found_boxes[0]
truth_iou_noise = true_box.iou(found_box)
truth_iou_noise_avg += truth_iou_noise / n_attack_tests
#if you find no faces or the truth-found face IoU is small, the test attack succeeded
if (len(found_boxes) == 0
or (len(found_boxes) == 1 and truth_iou_noise < iou_cutoff_value)):
attack_success_count += 1
attack_fail_count += 1
#if attack succeed in enough tests, write files as output and report success
if (attack_fail_count == 0
or attack_success_count / attack_fail_count >= attack_success_freq_threshold):
print('Attack succeeded at least ' + str(100*attack_success_freq_threshold)
+ '% of the time with epsilon: ' + str(epsilon))
tunnel_dict['successful_attack'] += 1
performance_dict['epsilon'] = epsilon
performance_dict['truth_iou_noise_avg'] = truth_iou_noise_avg
img = Image.open(image_labels.img_path)
img = np.array(img)
utils.draw_img_noise_pair_arrays(image_noise_pairs, epsilon, img_num, output_dir)
ssim_avg = 0
for test_num, img_pair in enumerate(image_noise_pairs):
attacked_img = img_pair.img
ssim_avg += ssim(img,
attacked_img,
data_range = attacked_img.max() - attacked_img.min(),
multichannel=True)
performance_dict['ssim_avg'] = ssim_avg / n_attack_tests
break
#if attack failed with given epsilon value, increase epsilon
if (attack_success_count / attack_fail_count < attack_success_freq_threshold):
print(str(attack_success_count) + '/' + str(attack_fail_count)
+ ' attacks succeeded with epsilon=' + str(epsilon)
+ '. This is below threshold (' + str(attack_success_freq_threshold)
+ '). Continuing...')
epsilon += epsilon_delta
#if epsilon is larger than max_epsilon_value, the attack has failed
else:
print('Noise attack failed')
performance_dict['epsilon'] = -1
performance_dict['truth_iou_noise_avg'] = -1
performance_dict['ssim_avg'] = -1
tunnel_dict['fail_count'] += 1
performance_list.append(performance_dict)
utils.write_csv(performance_list, attack_record_filename, output_dir)
utils.write_csv(tunnel_dict, result_counter_filename, output_dir)