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 6.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. """
  16. CenterNet evaluation script.
  17. """
  18. import os
  19. import time
  20. import copy
  21. import json
  22. import argparse
  23. import cv2
  24. from pycocotools.coco import COCO
  25. from pycocotools.cocoeval import COCOeval
  26. from mindspore import context
  27. from mindspore.common.tensor import Tensor
  28. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  29. import mindspore.log as logger
  30. from src import COCOHP, CenterNetMultiPoseEval
  31. from src import convert_eval_format, post_process, merge_outputs
  32. from src import visual_image
  33. from src.config import dataset_config, net_config, eval_config
  34. _current_dir = os.path.dirname(os.path.realpath(__file__))
  35. parser = argparse.ArgumentParser(description='CenterNet evaluation')
  36. parser.add_argument('--device_target', type=str, default='Ascend', choices=['Ascend', 'CPU'],
  37. help='device where the code will be implemented. (Default: Ascend)')
  38. parser.add_argument("--device_id", type=int, default=0, help="Device id, default is 0.")
  39. parser.add_argument("--load_checkpoint_path", type=str, default="", help="Load checkpoint file path")
  40. parser.add_argument("--data_dir", type=str, default="", help="Dataset directory, "
  41. "the absolute image path is joined by the data_dir "
  42. "and the relative path in anno_path")
  43. parser.add_argument("--run_mode", type=str, default="test", help="test or validation, default is test.")
  44. parser.add_argument("--visual_image", type=str, default="false", help="Visulize the ground truth and predicted image")
  45. parser.add_argument("--enable_eval", type=str, default="true", help="Whether evaluate accuracy after prediction")
  46. parser.add_argument("--save_result_dir", type=str, default="", help="The path to save the predict results")
  47. args_opt = parser.parse_args()
  48. def predict():
  49. '''
  50. Predict function
  51. '''
  52. context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target)
  53. if args_opt.device_target == "Ascend":
  54. context.set_context(device_id=args_opt.device_id)
  55. enable_nms_fp16 = True
  56. else:
  57. enable_nms_fp16 = False
  58. logger.info("Begin creating {} dataset".format(args_opt.run_mode))
  59. coco = COCOHP(dataset_config, run_mode=args_opt.run_mode, net_opt=net_config,
  60. enable_visual_image=(args_opt.visual_image == "true"), save_path=args_opt.save_result_dir,)
  61. coco.init(args_opt.data_dir, keep_res=eval_config.keep_res)
  62. dataset = coco.create_eval_dataset()
  63. net_for_eval = CenterNetMultiPoseEval(net_config, eval_config.K, enable_nms_fp16)
  64. net_for_eval.set_train(False)
  65. param_dict = load_checkpoint(args_opt.load_checkpoint_path)
  66. load_param_into_net(net_for_eval, param_dict)
  67. # save results
  68. save_path = os.path.join(args_opt.save_result_dir, args_opt.run_mode)
  69. if not os.path.exists(save_path):
  70. os.makedirs(save_path)
  71. if args_opt.visual_image == "true":
  72. save_pred_image_path = os.path.join(save_path, "pred_image")
  73. if not os.path.exists(save_pred_image_path):
  74. os.makedirs(save_pred_image_path)
  75. save_gt_image_path = os.path.join(save_path, "gt_image")
  76. if not os.path.exists(save_gt_image_path):
  77. os.makedirs(save_gt_image_path)
  78. total_nums = dataset.get_dataset_size()
  79. print("\n========================================\n")
  80. print("Total images num: ", total_nums)
  81. print("Processing, please wait a moment.")
  82. pred_annos = {"images": [], "annotations": []}
  83. index = 0
  84. for data in dataset.create_dict_iterator(num_epochs=1):
  85. index += 1
  86. image = data['image']
  87. image_id = data['image_id'].asnumpy().reshape((-1))[0]
  88. # run prediction
  89. start = time.time()
  90. detections = []
  91. for scale in eval_config.multi_scales:
  92. images, meta = coco.pre_process_for_test(image.asnumpy(), image_id, scale)
  93. detection = net_for_eval(Tensor(images))
  94. dets = post_process(detection.asnumpy(), meta, scale)
  95. detections.append(dets)
  96. end = time.time()
  97. print("Image {}/{} id: {} cost time {} ms".format(index, total_nums, image_id, (end - start) * 1000.))
  98. # post-process
  99. detections = merge_outputs(detections, eval_config.soft_nms)
  100. # get prediction result
  101. pred_json = convert_eval_format(detections, image_id)
  102. gt_image_info = coco.coco.loadImgs([image_id])
  103. for image_info in pred_json["images"]:
  104. pred_annos["images"].append(image_info)
  105. for image_anno in pred_json["annotations"]:
  106. pred_annos["annotations"].append(image_anno)
  107. if args_opt.visual_image == "true":
  108. img_file = os.path.join(coco.image_path, gt_image_info[0]['file_name'])
  109. gt_image = cv2.imread(img_file)
  110. if args_opt.run_mode != "test":
  111. annos = coco.coco.loadAnns(coco.anns[image_id])
  112. visual_image(copy.deepcopy(gt_image), annos, save_gt_image_path)
  113. anno = copy.deepcopy(pred_json["annotations"])
  114. visual_image(gt_image, anno, save_pred_image_path, score_threshold=eval_config.score_thresh)
  115. # save results
  116. save_path = os.path.join(args_opt.save_result_dir, args_opt.run_mode)
  117. if not os.path.exists(save_path):
  118. os.makedirs(save_path)
  119. pred_anno_file = os.path.join(save_path, '{}_pred_result.json').format(args_opt.run_mode)
  120. json.dump(pred_annos, open(pred_anno_file, 'w'))
  121. pred_res_file = os.path.join(save_path, '{}_pred_eval.json').format(args_opt.run_mode)
  122. json.dump(pred_annos["annotations"], open(pred_res_file, 'w'))
  123. if args_opt.run_mode != "test" and args_opt.enable_eval:
  124. run_eval(coco.annot_path, pred_res_file)
  125. def run_eval(gt_anno, pred_anno):
  126. """evaluation by coco api"""
  127. coco = COCO(gt_anno)
  128. coco_dets = coco.loadRes(pred_anno)
  129. coco_eval = COCOeval(coco, coco_dets, "keypoints")
  130. coco_eval.evaluate()
  131. coco_eval.accumulate()
  132. coco_eval.summarize()
  133. coco_eval = COCOeval(coco, coco_dets, "bbox")
  134. coco_eval.evaluate()
  135. coco_eval.accumulate()
  136. coco_eval.summarize()
  137. if __name__ == "__main__":
  138. predict()