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

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