-
Notifications
You must be signed in to change notification settings - Fork 2
/
test_proper_patch_yolov2.py
175 lines (148 loc) · 7.1 KB
/
test_proper_patch_yolov2.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
import sys
import time
import os
import warnings
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
from torchvision import transforms
from PIL import Image, ImageDraw
from utils import *
from darknet import *
from load_data import PatchTransformer, PatchApplier, InriaDataset, PatchTransformer_A3
import json
warnings.filterwarnings("ignore")
# os.environ["CUDA_VISIBLE_DEVICES"] = '2'
if __name__ == '__main__':
print("Setting everything up")
imgdir = "datasets/RSOD-Dataset/aircraft/Annotation/JPEGImages"
cfgfile = "cfg/yolo-dota.cfg"
weightfile = "weights/yolo-dota.cfg_450000.weights"
#############################################################
patch_generated_by = 'swin'
patchfile = "patches/Patch_A3/" + patch_generated_by + ".png"
savedir = "testing/" + patch_generated_by + "_A3_yolov2"
#############################################################
darknet_model = Darknet(cfgfile)
darknet_model.load_weights(weightfile)
darknet_model = darknet_model.eval().cuda()
patch_applier = PatchApplier().cuda()
patch_transformer = PatchTransformer_A3().cuda()
batch_size = 1
img_size = darknet_model.height # 1024*1024
# patch_size = 300
patch_size = 50
patch_img = Image.open(patchfile).convert('RGB')
tf = transforms.Resize((patch_size, patch_size))
patch_img = tf(patch_img)
tf = transforms.ToTensor()
adv_patch_cpu = tf(patch_img)
adv_patch = adv_patch_cpu.cuda()
clean_results = []
noise_results = []
patch_results = []
print("Done")
# Load orginal image
n = 1
for imgfile in os.listdir(imgdir):
print(imgfile, ' ', n)
n += 1
if imgfile.endswith('.jpg') or imgfile.endswith('.png'):
name = os.path.splitext(imgfile)[0] # image name w/o extension
txtname = name + '.txt'
txtpath = os.path.join(savedir, 'clean/', 'labels-yolo/')
if not os.path.exists(txtpath):
os.makedirs(txtpath)
txtpath = os.path.abspath(os.path.join(txtpath, txtname))
imgfile = os.path.abspath(os.path.join(imgdir, imgfile))
img = Image.open(imgfile).convert('RGB')
w, h = img.size
if w == h:
padded_img = img
else:
dim_to_pad = 1 if w < h else 2
if dim_to_pad == 1:
padding = (h - w) / 2
padded_img = Image.new('RGB', (h, h), color=(127, 127, 127))
padded_img.paste(img, (int(padding), 0))
else:
padding = (w - h) / 2
padded_img = Image.new('RGB', (w, w), color=(127, 127, 127))
padded_img.paste(img, (0, int(padding)))
resize = transforms.Resize((img_size, img_size)) # 1024*1024
padded_img = resize(padded_img)
cleanname = name + ".jpg"
padded_img_save_path = os.path.join(savedir, 'clean/')
if not os.path.exists(padded_img_save_path):
os.makedirs(padded_img_save_path)
# padded_img.save(os.path.join(padded_img_save_path, cleanname))
boxes = do_detect(darknet_model, padded_img, 0.4, 0.4, True)
boxes = nms(boxes, 0.4)
# Save clean labels-yolo
textfile = open(txtpath, 'w+')
for box in boxes:
cls_id = box[6]
if cls_id == 0: # if plane
x_center = box[0]
y_center = box[1]
width = box[2]
height = box[3]
textfile.write(f'{cls_id} {x_center} {y_center} {width} {height}\n')
clean_results.append({'image_id': name, 'bbox': [x_center.item() - width.item() / 2,
y_center.item() - height.item() / 2,
width.item(),
height.item()],
'score': box[4].item(),
'category_id': 1})
textfile.close()
# lees deze labelfile terug in als tensor
if os.path.getsize(txtpath): # check to see if label file contains data.
label = np.loadtxt(txtpath)
else:
label = np.ones([5])
label = torch.from_numpy(label).float()
if label.dim() == 1:
label = label.unsqueeze(0)
transform = transforms.ToTensor()
padded_img = transform(padded_img).cuda()
img_fake_batch = padded_img.unsqueeze(0)
lab_fake_batch = label.unsqueeze(0).cuda()
# transformeer patch en voeg hem toe aan beeld
adv_batch_t = patch_transformer(adv_patch, lab_fake_batch, img_size, do_rotate=True, rand_loc=False)
p_img_batch = patch_applier(img_fake_batch, adv_batch_t)
p_img = p_img_batch.squeeze(0)
p_img_pil = transforms.ToPILImage('RGB')(p_img.cpu())
properpatchedname = name + "_p.png"
proper_patched_img_save_path = os.path.join(savedir, 'proper_patched/')
if not os.path.exists(proper_patched_img_save_path):
os.makedirs(proper_patched_img_save_path)
p_img_pil.save(os.path.join(proper_patched_img_save_path, properpatchedname))
# p_img_pil.save(os.path.join(savedir, 'proper_patched/', properpatchedname))
# genereer een label file voor het beeld met sticker
txtname = properpatchedname.replace('.png', '.txt')
txtpath = os.path.join(savedir, 'proper_patched/', 'labels-yolo/')
if not os.path.exists(txtpath):
os.makedirs(txtpath)
txtpath = os.path.abspath(os.path.join(txtpath, txtname))
# txtpath = os.path.abspath(os.path.join(savedir, 'proper_patched/', 'labels-yolo/', txtname))
boxes = do_detect(darknet_model, p_img_pil, 0.01, 0.4, True)
boxes = nms(boxes, 0.4)
textfile = open(txtpath, 'w+')
for box in boxes:
cls_id = box[6]
if cls_id == 0: # if person
x_center = box[0]
y_center = box[1]
width = box[2]
height = box[3]
textfile.write(f'{cls_id} {x_center} {y_center} {width} {height}\n')
patch_results.append({'image_id': name, 'bbox': [x_center.item() - width.item() / 2,
y_center.item() - height.item() / 2, width.item(),
height.item()], 'score': box[4].item(),
'category_id': 1})
textfile.close()
with open(os.path.join(savedir, 'patch_results.json'), 'w') as fp:
json.dump(patch_results, fp)
# CUDA_VISIBLE_DEVICES=2 python test_proper_patch_yolov2.py