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

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