You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

eval.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """YoloV3 eval."""
  16. import os
  17. import argparse
  18. import datetime
  19. import time
  20. import sys
  21. from collections import defaultdict
  22. import numpy as np
  23. from pycocotools.coco import COCO
  24. from pycocotools.cocoeval import COCOeval
  25. from mindspore import Tensor
  26. from mindspore.train import ParallelMode
  27. from mindspore import context
  28. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  29. import mindspore as ms
  30. from src.yolo import YOLOV3DarkNet53
  31. from src.logger import get_logger
  32. from src.yolo_dataset import create_yolo_dataset
  33. from src.config import ConfigYOLOV3DarkNet53
  34. devid = int(os.getenv('DEVICE_ID'))
  35. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=True, device_id=devid)
  36. class Redirct:
  37. def __init__(self):
  38. self.content = ""
  39. def write(self, content):
  40. self.content += content
  41. def flush(self):
  42. self.content = ""
  43. class DetectionEngine:
  44. """Detection engine."""
  45. def __init__(self, args):
  46. self.ignore_threshold = args.ignore_threshold
  47. self.labels = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat',
  48. 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat',
  49. 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack',
  50. 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
  51. 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
  52. 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
  53. 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair',
  54. 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
  55. 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book',
  56. 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush']
  57. self.num_classes = len(self.labels)
  58. self.results = {}
  59. self.file_path = ''
  60. self.save_prefix = args.outputs_dir
  61. self.annFile = args.annFile
  62. self._coco = COCO(self.annFile)
  63. self._img_ids = list(sorted(self._coco.imgs.keys()))
  64. self.det_boxes = []
  65. self.nms_thresh = args.nms_thresh
  66. self.coco_catIds = self._coco.getCatIds()
  67. def do_nms_for_results(self):
  68. """Get result boxes."""
  69. for img_id in self.results:
  70. for clsi in self.results[img_id]:
  71. dets = self.results[img_id][clsi]
  72. dets = np.array(dets)
  73. keep_index = self._nms(dets, self.nms_thresh)
  74. keep_box = [{'image_id': int(img_id),
  75. 'category_id': int(clsi),
  76. 'bbox': list(dets[i][:4].astype(float)),
  77. 'score': dets[i][4].astype(float)}
  78. for i in keep_index]
  79. self.det_boxes.extend(keep_box)
  80. def _nms(self, dets, thresh):
  81. """Calculate NMS."""
  82. # conver xywh -> xmin ymin xmax ymax
  83. x1 = dets[:, 0]
  84. y1 = dets[:, 1]
  85. x2 = x1 + dets[:, 2]
  86. y2 = y1 + dets[:, 3]
  87. scores = dets[:, 4]
  88. areas = (x2 - x1 + 1) * (y2 - y1 + 1)
  89. order = scores.argsort()[::-1]
  90. keep = []
  91. while order.size > 0:
  92. i = order[0]
  93. keep.append(i)
  94. xx1 = np.maximum(x1[i], x1[order[1:]])
  95. yy1 = np.maximum(y1[i], y1[order[1:]])
  96. xx2 = np.minimum(x2[i], x2[order[1:]])
  97. yy2 = np.minimum(y2[i], y2[order[1:]])
  98. w = np.maximum(0.0, xx2 - xx1 + 1)
  99. h = np.maximum(0.0, yy2 - yy1 + 1)
  100. inter = w * h
  101. ovr = inter / (areas[i] + areas[order[1:]] - inter)
  102. inds = np.where(ovr <= thresh)[0]
  103. order = order[inds + 1]
  104. return keep
  105. def write_result(self):
  106. """Save result to file."""
  107. import json
  108. t = datetime.datetime.now().strftime('_%Y_%m_%d_%H_%M_%S')
  109. try:
  110. self.file_path = self.save_prefix + '/predict' + t + '.json'
  111. f = open(self.file_path, 'w')
  112. json.dump(self.det_boxes, f)
  113. except IOError as e:
  114. raise RuntimeError("Unable to open json file to dump. What(): {}".format(str(e)))
  115. else:
  116. f.close()
  117. return self.file_path
  118. def get_eval_result(self):
  119. """Get eval result."""
  120. cocoGt = COCO(self.annFile)
  121. cocoDt = cocoGt.loadRes(self.file_path)
  122. cocoEval = COCOeval(cocoGt, cocoDt, 'bbox')
  123. cocoEval.evaluate()
  124. cocoEval.accumulate()
  125. rdct = Redirct()
  126. stdout = sys.stdout
  127. sys.stdout = rdct
  128. cocoEval.summarize()
  129. sys.stdout = stdout
  130. return rdct.content
  131. def detect(self, outputs, batch, image_shape, image_id):
  132. """Detect boxes."""
  133. outputs_num = len(outputs)
  134. # output [|32, 52, 52, 3, 85| ]
  135. for batch_id in range(batch):
  136. for out_id in range(outputs_num):
  137. # 32, 52, 52, 3, 85
  138. out_item = outputs[out_id]
  139. # 52, 52, 3, 85
  140. out_item_single = out_item[batch_id, :]
  141. # get number of items in one head, [B, gx, gy, anchors, 5+80]
  142. dimensions = out_item_single.shape[:-1]
  143. out_num = 1
  144. for d in dimensions:
  145. out_num *= d
  146. ori_w, ori_h = image_shape[batch_id]
  147. img_id = int(image_id[batch_id])
  148. x = out_item_single[..., 0] * ori_w
  149. y = out_item_single[..., 1] * ori_h
  150. w = out_item_single[..., 2] * ori_w
  151. h = out_item_single[..., 3] * ori_h
  152. conf = out_item_single[..., 4:5]
  153. cls_emb = out_item_single[..., 5:]
  154. cls_argmax = np.expand_dims(np.argmax(cls_emb, axis=-1), axis=-1)
  155. x = x.reshape(-1)
  156. y = y.reshape(-1)
  157. w = w.reshape(-1)
  158. h = h.reshape(-1)
  159. cls_emb = cls_emb.reshape(-1, 80)
  160. conf = conf.reshape(-1)
  161. cls_argmax = cls_argmax.reshape(-1)
  162. x_top_left = x - w / 2.
  163. y_top_left = y - h / 2.
  164. # creat all False
  165. flag = np.random.random(cls_emb.shape) > sys.maxsize
  166. for i in range(flag.shape[0]):
  167. c = cls_argmax[i]
  168. flag[i, c] = True
  169. confidence = cls_emb[flag] * conf
  170. for x_lefti, y_lefti, wi, hi, confi, clsi in zip(x_top_left, y_top_left, w, h, confidence, cls_argmax):
  171. if confi < self.ignore_threshold:
  172. continue
  173. if img_id not in self.results:
  174. self.results[img_id] = defaultdict(list)
  175. x_lefti = max(0, x_lefti)
  176. y_lefti = max(0, y_lefti)
  177. wi = min(wi, ori_w)
  178. hi = min(hi, ori_h)
  179. # transform catId to match coco
  180. coco_clsi = self.coco_catIds[clsi]
  181. self.results[img_id][coco_clsi].append([x_lefti, y_lefti, wi, hi, confi])
  182. def parse_args():
  183. """Parse arguments."""
  184. parser = argparse.ArgumentParser('mindspore coco testing')
  185. # dataset related
  186. parser.add_argument('--data_dir', type=str, default='', help='train data dir')
  187. parser.add_argument('--per_batch_size', default=1, type=int, help='batch size for per gpu')
  188. # network related
  189. parser.add_argument('--pretrained', default='', type=str, help='model_path, local pretrained model to load')
  190. # logging related
  191. parser.add_argument('--log_path', type=str, default='outputs/', help='checkpoint save location')
  192. # detect_related
  193. parser.add_argument('--nms_thresh', type=float, default=0.5, help='threshold for NMS')
  194. parser.add_argument('--annFile', type=str, default='', help='path to annotation')
  195. parser.add_argument('--testing_shape', type=str, default='', help='shape for test ')
  196. parser.add_argument('--ignore_threshold', type=float, default=0.001, help='threshold to throw low quality boxes')
  197. args, _ = parser.parse_known_args()
  198. args.data_root = os.path.join(args.data_dir, 'val2014')
  199. args.annFile = os.path.join(args.data_dir, 'annotations/instances_val2014.json')
  200. return args
  201. def conver_testing_shape(args):
  202. """Convert testing shape to list."""
  203. testing_shape = [int(args.testing_shape), int(args.testing_shape)]
  204. return testing_shape
  205. def test():
  206. """The function of eval."""
  207. start_time = time.time()
  208. args = parse_args()
  209. # logger
  210. args.outputs_dir = os.path.join(args.log_path,
  211. datetime.datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S'))
  212. rank_id = int(os.environ.get('RANK_ID'))
  213. args.logger = get_logger(args.outputs_dir, rank_id)
  214. context.reset_auto_parallel_context()
  215. parallel_mode = ParallelMode.STAND_ALONE
  216. context.set_auto_parallel_context(parallel_mode=parallel_mode, mirror_mean=True, device_num=1)
  217. args.logger.info('Creating Network....')
  218. network = YOLOV3DarkNet53(is_training=False)
  219. args.logger.info(args.pretrained)
  220. if os.path.isfile(args.pretrained):
  221. param_dict = load_checkpoint(args.pretrained)
  222. param_dict_new = {}
  223. for key, values in param_dict.items():
  224. if key.startswith('moments.'):
  225. continue
  226. elif key.startswith('yolo_network.'):
  227. param_dict_new[key[13:]] = values
  228. else:
  229. param_dict_new[key] = values
  230. load_param_into_net(network, param_dict_new)
  231. args.logger.info('load_model {} success'.format(args.pretrained))
  232. else:
  233. args.logger.info('{} not exists or not a pre-trained file'.format(args.pretrained))
  234. assert FileNotFoundError('{} not exists or not a pre-trained file'.format(args.pretrained))
  235. exit(1)
  236. data_root = args.data_root
  237. ann_file = args.annFile
  238. config = ConfigYOLOV3DarkNet53()
  239. if args.testing_shape:
  240. config.test_img_shape = conver_testing_shape(args)
  241. ds, data_size = create_yolo_dataset(data_root, ann_file, is_training=False, batch_size=args.per_batch_size,
  242. max_epoch=1, device_num=1, rank=rank_id, shuffle=False,
  243. config=config)
  244. args.logger.info('testing shape : {}'.format(config.test_img_shape))
  245. args.logger.info('totol {} images to eval'.format(data_size))
  246. network.set_train(False)
  247. # init detection engine
  248. detection = DetectionEngine(args)
  249. input_shape = Tensor(tuple(config.test_img_shape), ms.float32)
  250. args.logger.info('Start inference....')
  251. for i, data in enumerate(ds.create_dict_iterator()):
  252. image = Tensor(data["image"])
  253. image_shape = Tensor(data["image_shape"])
  254. image_id = Tensor(data["img_id"])
  255. prediction = network(image, input_shape)
  256. output_big, output_me, output_small = prediction
  257. output_big = output_big.asnumpy()
  258. output_me = output_me.asnumpy()
  259. output_small = output_small.asnumpy()
  260. image_id = image_id.asnumpy()
  261. image_shape = image_shape.asnumpy()
  262. detection.detect([output_small, output_me, output_big], args.per_batch_size, image_shape, image_id)
  263. if i % 1000 == 0:
  264. args.logger.info('Processing... {:.2f}% '.format(i * args.per_batch_size / data_size * 100))
  265. args.logger.info('Calculating mAP...')
  266. detection.do_nms_for_results()
  267. result_file_path = detection.write_result()
  268. args.logger.info('result file path: {}'.format(result_file_path))
  269. eval_result = detection.get_eval_result()
  270. cost_time = time.time() - start_time
  271. args.logger.info('\n=============coco eval reulst=========\n' + eval_result)
  272. args.logger.info('testing cost time {:.2f}h'.format(cost_time / 3600.))
  273. if __name__ == "__main__":
  274. test()