-
Notifications
You must be signed in to change notification settings - Fork 9
/
crop.py
59 lines (44 loc) · 1.76 KB
/
crop.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
from pycocotools.coco import COCO
import cv2
import os
import json
import numpy as np
def crop_imgs():
coco_path = '/home/Hacker_Davinci/Desktop/coco'
crop_path = os.path.join(coco_path,'images/crop')
if not os.path.exists(crop_path):
os.makedirs(crop_path)
coco = COCO(os.path.join(coco_path,'annotations/instances_train2017.json'))
cat_objs = coco.loadCats(coco.getCatIds())
cat_instances = {}
for c in cat_objs:
print(c['name'])
cat_path = os.path.join(crop_path,f'{c["id"]}')
if not os.path.exists(cat_path):
os.makedirs(cat_path)
count = 0
imgIds = coco.getImgIds(catIds = c['id'])
cat_instances[c['id']] = []
for i in imgIds:
img_obj = coco.loadImgs(i)[0]
img = cv2.imread(os.path.join(coco_path,'images/train2017',img_obj['file_name']),cv2.IMREAD_COLOR)
annos = coco.loadAnns(coco.getAnnIds(i,c['id']))
for a in annos:
x,y,w,h = a['bbox']
if w < 64 or h <64:
continue
crop_img = img[int(y):int(y+h),int(x):int(x+w)]
img_size = max(w,h)
h_pad = int((img_size-h) // 2)
w_pad = int((img_size-w) // 2)
crop_img = np.pad(crop_img,((h_pad,h_pad),(w_pad,w_pad),(0,0)))
crop_img = cv2.resize(crop_img,(64,64))
cv2.imwrite(os.path.join(cat_path,f'{a["id"]}.png'),crop_img)
cat_instances[c['id']].append(a["id"])
count += 1
if(count >=500):
break
with open(os.path.join(coco_path,'annotations/crop.json'),'w') as f:
json.dump(cat_instances,f)
if __name__ == "__main__":
crop_imgs()