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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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. 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 import SSD300, SsdInferWithDecoder, ssd_mobilenet_v2, ssd_mobilenet_v1_fpn
  23. from src.dataset import create_ssd_dataset, create_mindrecord
  24. from src.config import config
  25. from src.eval_utils import metrics
  26. from src.box_utils import default_boxes
  27. def ssd_eval(dataset_path, ckpt_path, anno_json):
  28. """SSD evaluation."""
  29. batch_size = 1
  30. ds = create_ssd_dataset(dataset_path, batch_size=batch_size, repeat_num=1,
  31. is_training=False, use_multiprocessing=False)
  32. if config.model == "ssd300":
  33. net = SSD300(ssd_mobilenet_v2(), config, is_training=False)
  34. else:
  35. net = ssd_mobilenet_v1_fpn(config=config)
  36. net = SsdInferWithDecoder(net, Tensor(default_boxes), config)
  37. print("Load Checkpoint!")
  38. param_dict = load_checkpoint(ckpt_path)
  39. net.init_parameters_data()
  40. load_param_into_net(net, param_dict)
  41. net.set_train(False)
  42. i = batch_size
  43. total = ds.get_dataset_size() * batch_size
  44. start = time.time()
  45. pred_data = []
  46. print("\n========================================\n")
  47. print("total images num: ", total)
  48. print("Processing, please wait a moment.")
  49. for data in ds.create_dict_iterator(output_numpy=True, num_epochs=1):
  50. img_id = data['img_id']
  51. img_np = data['image']
  52. image_shape = data['image_shape']
  53. output = net(Tensor(img_np))
  54. for batch_idx in range(img_np.shape[0]):
  55. pred_data.append({"boxes": output[0].asnumpy()[batch_idx],
  56. "box_scores": output[1].asnumpy()[batch_idx],
  57. "img_id": int(np.squeeze(img_id[batch_idx])),
  58. "image_shape": image_shape[batch_idx]})
  59. percent = round(i / total * 100., 2)
  60. print(f' {str(percent)} [{i}/{total}]', end='\r')
  61. i += batch_size
  62. cost_time = int((time.time() - start) * 1000)
  63. print(f' 100% [{total}/{total}] cost {cost_time} ms')
  64. mAP = metrics(pred_data, anno_json)
  65. print("\n========================================\n")
  66. print(f"mAP: {mAP}")
  67. def get_eval_args():
  68. parser = argparse.ArgumentParser(description='SSD evaluation')
  69. parser.add_argument("--device_id", type=int, default=0, help="Device id, default is 0.")
  70. parser.add_argument("--dataset", type=str, default="coco", help="Dataset, default is coco.")
  71. parser.add_argument("--checkpoint_path", type=str, required=True, help="Checkpoint file path.")
  72. parser.add_argument("--run_platform", type=str, default="Ascend", choices=("Ascend", "GPU", "CPU"),
  73. help="run platform, support Ascend ,GPU and CPU.")
  74. return parser.parse_args()
  75. if __name__ == '__main__':
  76. args_opt = get_eval_args()
  77. if args_opt.dataset == "coco":
  78. json_path = os.path.join(config.coco_root, config.instances_set.format(config.val_data_type))
  79. elif args_opt.dataset == "voc":
  80. json_path = os.path.join(config.voc_root, config.voc_json)
  81. else:
  82. raise ValueError('SSD eval only supprt dataset mode is coco and voc!')
  83. context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.run_platform, device_id=args_opt.device_id)
  84. mindrecord_file = create_mindrecord(args_opt.dataset, "ssd_eval.mindrecord", False)
  85. print("Start Eval!")
  86. ssd_eval(mindrecord_file, args_opt.checkpoint_path, json_path)