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

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