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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. # Copyright 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 CTPN"""
  16. import os
  17. import argparse
  18. import time
  19. import numpy as np
  20. from mindspore import context
  21. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  22. from mindspore.common import set_seed
  23. from src.ctpn import CTPN
  24. from src.config import config
  25. from src.dataset import create_ctpn_dataset
  26. from src.text_connector.detector import detect
  27. set_seed(1)
  28. parser = argparse.ArgumentParser(description="CTPN evaluation")
  29. parser.add_argument("--dataset_path", type=str, default="", help="Dataset path.")
  30. parser.add_argument("--image_path", type=str, default="", help="Image path.")
  31. parser.add_argument("--checkpoint_path", type=str, default="", help="Checkpoint file path.")
  32. parser.add_argument("--device_id", type=int, default=0, help="Device id, default is 0.")
  33. args_opt = parser.parse_args()
  34. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=args_opt.device_id)
  35. def ctpn_infer_test(dataset_path='', ckpt_path='', img_dir=''):
  36. """ctpn infer."""
  37. print("ckpt path is {}".format(ckpt_path))
  38. ds = create_ctpn_dataset(dataset_path, batch_size=config.test_batch_size, repeat_num=1, is_training=False)
  39. config.batch_size = config.test_batch_size
  40. total = ds.get_dataset_size()
  41. print("*************total dataset size is {}".format(total))
  42. net = CTPN(config, is_training=False)
  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. print("\n========================================\n")
  48. print("Processing, please wait a moment.")
  49. img_basenames = []
  50. output_dir = os.path.join(os.getcwd(), "submit")
  51. if not os.path.exists(output_dir):
  52. os.mkdir(output_dir)
  53. for file in os.listdir(img_dir):
  54. img_basenames.append(os.path.basename(file))
  55. for data in ds.create_dict_iterator():
  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. start = time.time()
  62. # run net
  63. output = net(img_data, img_metas, gt_bboxes, gt_labels, gt_num)
  64. gt_bboxes = gt_bboxes.asnumpy()
  65. gt_labels = gt_labels.asnumpy()
  66. gt_num = gt_num.asnumpy().astype(bool)
  67. end = time.time()
  68. proposal = output[0]
  69. proposal_mask = output[1]
  70. print("start to draw pic")
  71. for j in range(config.test_batch_size):
  72. img = img_basenames[config.test_batch_size * eval_iter + j]
  73. all_box_tmp = proposal[j].asnumpy()
  74. all_mask_tmp = np.expand_dims(proposal_mask[j].asnumpy(), axis=1)
  75. using_boxes_mask = all_box_tmp * all_mask_tmp
  76. textsegs = using_boxes_mask[:, 0:4].astype(np.float32)
  77. scores = using_boxes_mask[:, 4].astype(np.float32)
  78. shape = img_metas.asnumpy()[0][:2].astype(np.int32)
  79. bboxes = detect(textsegs, scores[:, np.newaxis], shape)
  80. from PIL import Image, ImageDraw
  81. im = Image.open(img_dir + '/' + img)
  82. draw = ImageDraw.Draw(im)
  83. image_h = img_metas.asnumpy()[j][2]
  84. image_w = img_metas.asnumpy()[j][3]
  85. gt_boxs = gt_bboxes[j][gt_num[j], :]
  86. for gt_box in gt_boxs:
  87. gt_x1 = gt_box[0] / image_w
  88. gt_y1 = gt_box[1] / image_h
  89. gt_x2 = gt_box[2] / image_w
  90. gt_y2 = gt_box[3] / image_h
  91. draw.line([(gt_x1, gt_y1), (gt_x1, gt_y2), (gt_x2, gt_y2), (gt_x2, gt_y1), (gt_x1, gt_y1)],\
  92. fill='green', width=2)
  93. file_name = "res_" + img.replace("jpg", "txt")
  94. output_file = os.path.join(output_dir, file_name)
  95. f = open(output_file, 'w')
  96. for bbox in bboxes:
  97. x1 = bbox[0] / image_w
  98. y1 = bbox[1] / image_h
  99. x2 = bbox[2] / image_w
  100. y2 = bbox[3] / image_h
  101. draw.line([(x1, y1), (x1, y2), (x2, y2), (x2, y1), (x1, y1)], fill='red', width=2)
  102. str_tmp = str(int(x1)) + "," + str(int(y1)) + "," + str(int(x2)) + "," + str(int(y2))
  103. f.write(str_tmp)
  104. f.write("\n")
  105. f.close()
  106. im.save(img)
  107. percent = round(eval_iter / total * 100, 2)
  108. eval_iter = eval_iter + 1
  109. print("Iter {} cost time {}".format(eval_iter, end - start))
  110. print(' %s [%d/%d]' % (str(percent) + '%', eval_iter, total), end='\r')
  111. if __name__ == '__main__':
  112. ctpn_infer_test(args_opt.dataset_path, args_opt.checkpoint_path, img_dir=args_opt.image_path)