-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcoco_eval.py
187 lines (148 loc) · 6.51 KB
/
coco_eval.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
from pycocotools.cocoeval import COCOeval
import numpy as np
import json
from tqdm import tqdm
from torchvision.datasets import CocoDetection
from torchvision import transforms
import cv2
from model.fcos import FCOSDetector
import torch
class COCOGenerator(CocoDetection):
CLASSES_NAME = (
'__back_ground__', 'person', 'bicycle', 'car', 'motorcycle',
'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench',
'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant',
'bear', 'zebra', 'giraffe', 'backpack', 'umbrella',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
'sports ball', 'kite', 'baseball bat', 'baseball glove',
'skateboard', 'surfboard', 'tennis racket', 'bottle',
'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
'banana', 'apple', 'sandwich', 'orange', 'broccoli',
'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair',
'couch', 'potted plant', 'bed', 'dining table', 'toilet',
'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator',
'book', 'clock', 'vase', 'scissors', 'teddy bear',
'hair drier', 'toothbrush')
def __init__(self,imgs_path,anno_path,resize_size=[800,1024]):
super().__init__(imgs_path,anno_path)
print("INFO====>check annos, filtering invalid data......")
ids=[]
for id in self.ids:
ann_id=self.coco.getAnnIds(imgIds=id,iscrowd=None)
ann=self.coco.loadAnns(ann_id)
if self._has_valid_annotation(ann):
ids.append(id)
self.ids=ids
self.category2id = {v: i + 1 for i, v in enumerate(self.coco.getCatIds())}
self.id2category = {v: k for k, v in self.category2id.items()}
self.resize_size=resize_size
self.mean=[0.40789654, 0.44719302, 0.47026115]
self.std=[0.28863828, 0.27408164, 0.27809835]
def __getitem__(self,index):
img,ann=super().__getitem__(index)
ann = [o for o in ann if o['iscrowd'] == 0]
boxes = [o['bbox'] for o in ann]
boxes=np.array(boxes,dtype=np.float32)
#xywh-->xyxy
boxes[...,2:]=boxes[...,2:]+boxes[...,:2]
img=np.array(img)
img,boxes,scale=self.preprocess_img_boxes(img,boxes,self.resize_size)
# img=draw_bboxes(img,boxes)
classes = [o['category_id'] for o in ann]
classes = [self.category2id[c] for c in classes]
img=transforms.ToTensor()(img)
img= transforms.Normalize(self.mean, self.std,inplace=True)(img)
# boxes=torch.from_numpy(boxes)
classes=np.array(classes,dtype=np.int64)
return img,boxes,classes,scale
def preprocess_img_boxes(self,image,boxes,input_ksize):
'''
resize image and bboxes
Returns
image_paded: input_ksize
bboxes: [None,4]
'''
min_side, max_side = input_ksize
h, w, _ = image.shape
smallest_side = min(w,h)
largest_side=max(w,h)
scale=min_side/smallest_side
if largest_side*scale>max_side:
scale=max_side/largest_side
nw, nh = int(scale * w), int(scale * h)
image_resized = cv2.resize(image, (nw, nh))
pad_w=32-nw%32
pad_h=32-nh%32
image_paded = np.zeros(shape=[nh+pad_h, nw+pad_w, 3],dtype=np.float32)
image_paded[:nh, :nw, :] = image_resized
if boxes is None:
return image_paded
else:
boxes[:, [0, 2]] = boxes[:, [0, 2]] * scale
boxes[:, [1, 3]] = boxes[:, [1, 3]] * scale
return image_paded, boxes,scale
def _has_only_empty_bbox(self,annot):
return all(any(o <= 1 for o in obj['bbox'][2:]) for obj in annot)
def _has_valid_annotation(self,annot):
if len(annot) == 0:
return False
if self._has_only_empty_bbox(annot):
return False
return True
def evaluate_coco(generator, model, threshold=0.05):
""" Use the pycocotools to evaluate a COCO model on a dataset.
Args
generator : The generator for generating the evaluation data.
model : The model to evaluate.
threshold : The score threshold to use.
"""
# start collecting results
results = []
image_ids = []
for index in tqdm(range(len(generator))):
img,gt_boxes,gt_labels,scale = generator[index]
# run network
scores, labels,boxes = model(img.unsqueeze(dim=0))
boxes /= scale
# correct boxes for image scale
# change to (x, y, w, h) (MS COCO standard)
boxes[:, :, 2] -= boxes[:, :, 0]
boxes[:, :, 3] -= boxes[:, :, 1]
# compute predicted labels and scores
for box, score, label in zip(boxes[0], scores[0], labels[0]):
# scores are sorted, so we can break
if score < threshold:
break
# append detection for each positively labeled class
image_result = {
'image_id' : generator.ids[index],
'category_id' : generator.id2category(label),
'score' : float(score),
'bbox' : box.tolist(),
}
# append detection to results
results.append(image_result)
# append image to list of processed images
# image_ids.append(generator.ids[index])
if not len(results):
return
# write output
json.dump(results, open('coco_bbox_results.json', 'w'), indent=4)
# json.dump(image_ids, open('{}_processed_image_ids.json'.format(generator.set_name), 'w'), indent=4)
# load results in COCO evaluation tool
coco_true = generator.coco
coco_pred = coco_true.loadRes('coco_bbox_results.json')
# run COCO evaluation
coco_eval = COCOeval(coco_true, coco_pred, 'bbox')
coco_eval.params.imgIds = image_ids
coco_eval.evaluate()
coco_eval.accumulate()
coco_eval.summarize()
return coco_eval.stats
if __name__ == "__main__":
generator=COCOGenerator("/home/data/coco2017/val2017","/home/data/coco2017/instances_val2017.json")
model=FCOSDetector(mode="inference")
model.load_state_dict(torch.load("./logs/1121/coco2017_multigpu_800x1024_epoch4_loss1.2863.pth",map_location=torch.device('cpu')))
evaluate_coco(generator,model)