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

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