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

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