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

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