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.0 kB

4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. # Copyright 2021 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. """Evaluation for retinanet"""
  16. import os
  17. import argparse
  18. import time
  19. import numpy as np
  20. from mindspore import context, Tensor
  21. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  22. from src.retinanet import retinanet50, resnet50, retinanetInferWithDecoder
  23. from src.dataset import create_retinanet_dataset, data_to_mindrecord_byte_image, voc_data_to_mindrecord
  24. from src.config import config
  25. from src.coco_eval import metrics
  26. from src.box_utils import default_boxes
  27. def retinanet_eval(dataset_path, ckpt_path):
  28. """retinanet evaluation."""
  29. batch_size = 1
  30. ds = create_retinanet_dataset(dataset_path, batch_size=batch_size, repeat_num=1, is_training=False)
  31. backbone = resnet50(config.num_classes)
  32. net = retinanet50(backbone, config)
  33. net = retinanetInferWithDecoder(net, Tensor(default_boxes), config)
  34. print("Load Checkpoint!")
  35. param_dict = load_checkpoint(ckpt_path)
  36. net.init_parameters_data()
  37. load_param_into_net(net, param_dict)
  38. net.set_train(False)
  39. i = batch_size
  40. total = ds.get_dataset_size() * batch_size
  41. start = time.time()
  42. pred_data = []
  43. print("\n========================================\n")
  44. print("total images num: ", total)
  45. print("Processing, please wait a moment.")
  46. for data in ds.create_dict_iterator(output_numpy=True):
  47. img_id = data['img_id']
  48. img_np = data['image']
  49. image_shape = data['image_shape']
  50. output = net(Tensor(img_np))
  51. for batch_idx in range(img_np.shape[0]):
  52. pred_data.append({"boxes": output[0].asnumpy()[batch_idx],
  53. "box_scores": output[1].asnumpy()[batch_idx],
  54. "img_id": int(np.squeeze(img_id[batch_idx])),
  55. "image_shape": image_shape[batch_idx]})
  56. percent = round(i / total * 100., 2)
  57. print(f' {str(percent)} [{i}/{total}]', end='\r')
  58. i += batch_size
  59. cost_time = int((time.time() - start) * 1000)
  60. print(f' 100% [{total}/{total}] cost {cost_time} ms')
  61. mAP = metrics(pred_data)
  62. print("\n========================================\n")
  63. print(f"mAP: {mAP}")
  64. if __name__ == '__main__':
  65. parser = argparse.ArgumentParser(description='retinanet evaluation')
  66. parser.add_argument("--device_id", type=int, default=0, help="Device id, default is 0.")
  67. parser.add_argument("--dataset", type=str, default="coco", help="Dataset, default is coco.")
  68. parser.add_argument("--run_platform", type=str, default="Ascend", choices=("Ascend"),
  69. help="run platform, only support Ascend.")
  70. args_opt = parser.parse_args()
  71. context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.run_platform, device_id=args_opt.device_id)
  72. prefix = "retinanet_eval.mindrecord"
  73. mindrecord_dir = config.mindrecord_dir
  74. mindrecord_file = os.path.join(mindrecord_dir, prefix + "0")
  75. if args_opt.dataset == "voc":
  76. config.coco_root = config.voc_root
  77. if not os.path.exists(mindrecord_file):
  78. if not os.path.isdir(mindrecord_dir):
  79. os.makedirs(mindrecord_dir)
  80. if args_opt.dataset == "coco":
  81. if os.path.isdir(config.coco_root):
  82. print("Create Mindrecord.")
  83. data_to_mindrecord_byte_image("coco", False, prefix)
  84. print("Create Mindrecord Done, at {}".format(mindrecord_dir))
  85. else:
  86. print("coco_root not exits.")
  87. elif args_opt.dataset == "voc":
  88. if os.path.isdir(config.voc_dir) and os.path.isdir(config.voc_root):
  89. print("Create Mindrecord.")
  90. voc_data_to_mindrecord(mindrecord_dir, False, prefix)
  91. print("Create Mindrecord Done, at {}".format(mindrecord_dir))
  92. else:
  93. print("voc_root or voc_dir not exits.")
  94. else:
  95. if os.path.isdir(config.image_dir) and os.path.exists(config.anno_path):
  96. print("Create Mindrecord.")
  97. data_to_mindrecord_byte_image("other", False, prefix)
  98. print("Create Mindrecord Done, at {}".format(mindrecord_dir))
  99. else:
  100. print("IMAGE_DIR or ANNO_PATH not exits.")
  101. print("Start Eval!")
  102. retinanet_eval(mindrecord_file, config.checkpoint_path)