forked from WoodsGao/cv_utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coco_offline_aug.py
executable file
·136 lines (126 loc) · 4.81 KB
/
coco_offline_aug.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
#!/usr/bin/python3
import argparse
import json
import os
import os.path as osp
from copy import deepcopy
import cv2
import numpy as np
from imgaug import augmenters as ia
from imgaug.augmentables.polys import Polygon, PolygonsOnImage
from imgaug.augmentables.kps import Keypoint, KeypointsOnImage
from coco_utils import create_coco, find_anns, insert_img_anns, sort_coco
AUGS = ia.Sequential([
ia.SomeOf(
[0, 3],
[
ia.Dropout([0.015, 0.1]), # drop 5% or 20% of all pixels
# ia.Sharpen((0.0, 1.0)), # sharpen the image
# rotate by -45 to 45 degrees (affects heatmaps)
# ia.ElasticTransformation(
# alpha=(0, 10),
# sigma=(0, 10)), # apply water effect (affects heatmaps)
# ia.PiecewiseAffine(scale=(0, 0.03), nb_rows=(2, 6), nb_cols=(2, 6)),
# ia.GaussianBlur((0, 3)),
ia.Fliplr(0.1),
ia.Flipud(0.1),
# ia.LinearContrast((0.5, 1)),
# ia.AdditiveGaussianNoise(loc=(0, 10), scale=(0, 10))
],
random_state=True),
ia.Affine(scale=(0.8, 1.2),
translate_percent=(-0.1, 0.1),
rotate=(-90, 90),
shear=(-0.1, 0.1))
])
def aug_img_anns(img, anns):
augments = AUGS.to_deterministic()
polygons = []
kps = []
for ann in anns:
polygons.append(
Polygon(
np.float32(ann['segmentation'][0]).reshape(-1, 2),
ann['category_id']))
if ann.get('keypoints'):
for ki in range(ann['num_keypoints']):
kps.append(
Polygon([[
ann['keypoints'][ki * 3], ann['keypoints'][ki * 3 + 1]
]],
label=(ki, len(polygons) - 1,
ann['keypoints'][ki * 3 + 2])))
polygons = PolygonsOnImage(polygons, img.shape)
kps = PolygonsOnImage(kps, img.shape)
img = augments.augment_image(img)
polygons = augments.augment_polygons(polygons).polygons
kps = augments.augment_polygons(kps).polygons
kps_on_instance = [[] for i in range(len(polygons))]
for kp in kps:
kps_on_instance[kp.label[1]].append(kp)
map(lambda x: x.sort(key=lambda kp: kp.label[0]), kps_on_instance)
anns = []
for p, kps in zip(polygons, kps_on_instance):
seg = p.exterior.reshape(-1).tolist()
xs = seg[::2]
ys = seg[1::2]
if len([x for x in xs if x >= img.shape[1] - 1 or x <= 0]) > 0:
continue
if len([y for y in ys if y >= img.shape[0] - 1 or y <= 0]) > 0:
continue
x1 = min(xs)
y1 = min(ys)
w = max(xs) - x1
h = max(ys) - y1
anns.append({
'area': w * h,
'bbox': [x1, y1, w, h],
'category_id': p.label,
'iscrowd': 0,
'segmentation': [seg]
})
if len(kps):
anns[-1]['keypoints'] = []
anns[-1]['num_keypoints'] = len(kps)
for kp in kps:
anns[-1]['keypoints'].append(float(kp.exterior[0][0]))
anns[-1]['keypoints'].append(float(kp.exterior[0][1]))
anns[-1]['keypoints'].append(kp.label[2])
return img, anns
def coco_offline_aug(coco_path, img_root, output, repeats=1):
with open(coco_path, 'r') as f:
coco = f.read()
coco = json.loads(coco)
new_coco = create_coco(coco)
save_dir = osp.join(output, 'images')
os.makedirs(save_dir, exist_ok=True)
for img_info in coco['images']:
anns = find_anns(coco, img_info)
img = cv2.imread(osp.join(img_root, img_info['file_name']))
img_name = osp.splitext(osp.basename(img_info['file_name']))[0]
anns = find_anns(coco, img_info)
for ri in range(repeats):
aug_img, aug_anns = aug_img_anns(img.copy(), anns)
iname = img_name + '_%05d.png' % ri
cv2.imwrite(osp.join(save_dir, iname), aug_img)
print(osp.join(save_dir, iname))
img_info = {
'file_name': osp.join('images', iname),
'width': aug_img.shape[1],
'height': aug_img.shape[0],
}
insert_img_anns(new_coco, img_info, aug_anns)
save_path = osp.join(output, 'coco_aug.json')
# print(new_coco)
with open(save_path, 'w') as f:
f.write(json.dumps(new_coco, indent=4))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('coco', type=str)
parser.add_argument('output', type=str)
parser.add_argument('--img-root', type=str)
parser.add_argument('--repeats', type=int, default=1)
opt = parser.parse_args()
if not opt.img_root:
opt.img_root = osp.dirname(opt.coco)
coco_offline_aug(opt.coco, opt.img_root, opt.output, opt.repeats)