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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. # less 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. """Evaluation for yolo_v3"""
  16. import os
  17. import argparse
  18. import time
  19. from mindspore import context, Tensor
  20. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  21. from mindspore.model_zoo.yolov3 import yolov3_resnet18, YoloWithEval
  22. from dataset import create_yolo_dataset, data_to_mindrecord_byte_image
  23. from config import ConfigYOLOV3ResNet18
  24. from util import metrics
  25. def yolo_eval(dataset_path, ckpt_path):
  26. """Yolov3 evaluation."""
  27. ds = create_yolo_dataset(dataset_path, is_training=False)
  28. config = ConfigYOLOV3ResNet18()
  29. net = yolov3_resnet18(config)
  30. eval_net = YoloWithEval(net, config)
  31. print("Load Checkpoint!")
  32. param_dict = load_checkpoint(ckpt_path)
  33. load_param_into_net(net, param_dict)
  34. eval_net.set_train(False)
  35. i = 1.
  36. total = ds.get_dataset_size()
  37. start = time.time()
  38. pred_data = []
  39. print("\n========================================\n")
  40. print("total images num: ", total)
  41. print("Processing, please wait a moment.")
  42. for data in ds.create_dict_iterator():
  43. img_np = data['image']
  44. image_shape = data['image_shape']
  45. annotation = data['annotation']
  46. eval_net.set_train(False)
  47. output = eval_net(Tensor(img_np), Tensor(image_shape))
  48. for batch_idx in range(img_np.shape[0]):
  49. pred_data.append({"boxes": output[0].asnumpy()[batch_idx],
  50. "box_scores": output[1].asnumpy()[batch_idx],
  51. "annotation": annotation})
  52. percent = round(i / total * 100, 2)
  53. print(' %s [%d/%d]' % (str(percent) + '%', i, total), end='\r')
  54. i += 1
  55. print(' %s [%d/%d] cost %d ms' % (str(100.0) + '%', total, total, int((time.time() - start) * 1000)), end='\n')
  56. precisions, recalls = metrics(pred_data)
  57. print("\n========================================\n")
  58. for i in range(config.num_classes):
  59. print("class {} precision is {:.2f}%, recall is {:.2f}%".format(i, precisions[i] * 100, recalls[i] * 100))
  60. if __name__ == '__main__':
  61. parser = argparse.ArgumentParser(description='Yolov3 evaluation')
  62. parser.add_argument("--device_id", type=int, default=0, help="Device id, default is 0.")
  63. parser.add_argument("--mindrecord_dir", type=str, default="./Mindrecord_eval",
  64. help="Mindrecord directory. If the mindrecord_dir is empty, it wil generate mindrecord file by"
  65. "image_dir and anno_path. Note if mindrecord_dir isn't empty, it will use mindrecord_dir "
  66. "rather than image_dir and anno_path. Default is ./Mindrecord_eval")
  67. parser.add_argument("--image_dir", type=str, default="", help="Dataset directory, "
  68. "the absolute image path is joined by the image_dir "
  69. "and the relative path in anno_path.")
  70. parser.add_argument("--anno_path", type=str, default="", help="Annotation path.")
  71. parser.add_argument("--ckpt_path", type=str, required=True, help="Checkpoint path.")
  72. args_opt = parser.parse_args()
  73. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=args_opt.device_id)
  74. context.set_context(enable_task_sink=True, enable_loop_sink=True, enable_mem_reuse=True,
  75. enable_auto_mixed_precision=False)
  76. # It will generate mindrecord file in args_opt.mindrecord_dir,
  77. # and the file name is yolo.mindrecord0, 1, ... file_num.
  78. if not os.path.isdir(args_opt.mindrecord_dir):
  79. os.makedirs(args_opt.mindrecord_dir)
  80. prefix = "yolo.mindrecord"
  81. mindrecord_file = os.path.join(args_opt.mindrecord_dir, prefix + "0")
  82. if not os.path.exists(mindrecord_file):
  83. if os.path.isdir(args_opt.image_dir) and os.path.exists(args_opt.anno_path):
  84. print("Create Mindrecord")
  85. data_to_mindrecord_byte_image(args_opt.image_dir,
  86. args_opt.anno_path,
  87. args_opt.mindrecord_dir,
  88. prefix=prefix,
  89. file_num=8)
  90. print("Create Mindrecord Done, at {}".format(args_opt.mindrecord_dir))
  91. else:
  92. print("image_dir or anno_path not exits")
  93. print("Start Eval!")
  94. yolo_eval(mindrecord_file, args_opt.ckpt_path)