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

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