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