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 5.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. # Copyright 2020-2021 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 FasterRcnn"""
  16. import os
  17. import argparse
  18. import time
  19. import numpy as np
  20. from pycocotools.coco import COCO
  21. from mindspore import context
  22. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  23. from mindspore.common import set_seed, Parameter
  24. from src.FasterRcnn.faster_rcnn_r50 import Faster_Rcnn_Resnet50
  25. from src.config import config
  26. from src.dataset import data_to_mindrecord_byte_image, create_fasterrcnn_dataset
  27. from src.util import coco_eval, bbox2result_1image, results2json
  28. set_seed(1)
  29. parser = argparse.ArgumentParser(description="FasterRcnn evaluation")
  30. parser.add_argument("--dataset", type=str, default="coco", help="Dataset, default is coco.")
  31. parser.add_argument("--ann_file", type=str, default="val.json", help="Ann file, default is val.json.")
  32. parser.add_argument("--checkpoint_path", type=str, required=True, help="Checkpoint file path.")
  33. parser.add_argument("--device_target", type=str, default="Ascend",
  34. help="device where the code will be implemented, default is Ascend")
  35. parser.add_argument("--device_id", type=int, default=0, help="Device id, default is 0.")
  36. args_opt = parser.parse_args()
  37. context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target, device_id=args_opt.device_id)
  38. def FasterRcnn_eval(dataset_path, ckpt_path, ann_file):
  39. """FasterRcnn evaluation."""
  40. ds = create_fasterrcnn_dataset(dataset_path, batch_size=config.test_batch_size, is_training=False)
  41. net = Faster_Rcnn_Resnet50(config)
  42. param_dict = load_checkpoint(ckpt_path)
  43. if args_opt.device_target == "GPU":
  44. for key, value in param_dict.items():
  45. tensor = value.asnumpy().astype(np.float32)
  46. param_dict[key] = Parameter(tensor, key)
  47. load_param_into_net(net, param_dict)
  48. net.set_train(False)
  49. eval_iter = 0
  50. total = ds.get_dataset_size()
  51. outputs = []
  52. dataset_coco = COCO(ann_file)
  53. print("\n========================================\n")
  54. print("total images num: ", total)
  55. print("Processing, please wait a moment.")
  56. max_num = 128
  57. for data in ds.create_dict_iterator(num_epochs=1):
  58. eval_iter = eval_iter + 1
  59. img_data = data['image']
  60. img_metas = data['image_shape']
  61. gt_bboxes = data['box']
  62. gt_labels = data['label']
  63. gt_num = data['valid_num']
  64. start = time.time()
  65. # run net
  66. output = net(img_data, img_metas, gt_bboxes, gt_labels, gt_num)
  67. end = time.time()
  68. print("Iter {} cost time {}".format(eval_iter, end - start))
  69. # output
  70. all_bbox = output[0]
  71. all_label = output[1]
  72. all_mask = output[2]
  73. for j in range(config.test_batch_size):
  74. all_bbox_squee = np.squeeze(all_bbox.asnumpy()[j, :, :])
  75. all_label_squee = np.squeeze(all_label.asnumpy()[j, :, :])
  76. all_mask_squee = np.squeeze(all_mask.asnumpy()[j, :, :])
  77. all_bboxes_tmp_mask = all_bbox_squee[all_mask_squee, :]
  78. all_labels_tmp_mask = all_label_squee[all_mask_squee]
  79. if all_bboxes_tmp_mask.shape[0] > max_num:
  80. inds = np.argsort(-all_bboxes_tmp_mask[:, -1])
  81. inds = inds[:max_num]
  82. all_bboxes_tmp_mask = all_bboxes_tmp_mask[inds]
  83. all_labels_tmp_mask = all_labels_tmp_mask[inds]
  84. outputs_tmp = bbox2result_1image(all_bboxes_tmp_mask, all_labels_tmp_mask, config.num_classes)
  85. outputs.append(outputs_tmp)
  86. eval_types = ["bbox"]
  87. result_files = results2json(dataset_coco, outputs, "./results.pkl")
  88. coco_eval(result_files, eval_types, dataset_coco, single_result=True)
  89. if __name__ == '__main__':
  90. prefix = "FasterRcnn_eval.mindrecord"
  91. mindrecord_dir = config.mindrecord_dir
  92. mindrecord_file = os.path.join(mindrecord_dir, prefix)
  93. print("CHECKING MINDRECORD FILES ...")
  94. if not os.path.exists(mindrecord_file):
  95. if not os.path.isdir(mindrecord_dir):
  96. os.makedirs(mindrecord_dir)
  97. if args_opt.dataset == "coco":
  98. if os.path.isdir(config.coco_root):
  99. print("Create Mindrecord. It may take some time.")
  100. data_to_mindrecord_byte_image("coco", False, prefix, file_num=1)
  101. print("Create Mindrecord Done, at {}".format(mindrecord_dir))
  102. else:
  103. print("coco_root not exits.")
  104. else:
  105. if os.path.isdir(config.IMAGE_DIR) and os.path.exists(config.ANNO_PATH):
  106. print("Create Mindrecord. It may take some time.")
  107. data_to_mindrecord_byte_image("other", False, prefix, file_num=1)
  108. print("Create Mindrecord Done, at {}".format(mindrecord_dir))
  109. else:
  110. print("IMAGE_DIR or ANNO_PATH not exits.")
  111. print("CHECKING MINDRECORD FILES DONE!")
  112. print("Start Eval!")
  113. FasterRcnn_eval(mindrecord_file, args_opt.checkpoint_path, args_opt.ann_file)