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