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.

test.py 5.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. # Unless 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. import os
  16. import math
  17. import operator
  18. from functools import reduce
  19. import argparse
  20. import time
  21. import numpy as np
  22. import cv2
  23. from mindspore import Tensor, context
  24. import mindspore.common.dtype as mstype
  25. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  26. from src.config import config
  27. from src.dataset import test_dataset_creator
  28. from src.ETSNET.etsnet import ETSNet
  29. from src.ETSNET.pse import pse
  30. parser = argparse.ArgumentParser(description='Hyperparams')
  31. parser.add_argument("--ckpt", type=str, default=0, help='trained model path.')
  32. args = parser.parse_args()
  33. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=False,
  34. save_graphs_path=".")
  35. class AverageMeter():
  36. """Computes and stores the average and current value"""
  37. def __init__(self):
  38. self.reset()
  39. def reset(self):
  40. self.val = 0
  41. self.avg = 0
  42. self.sum = 0
  43. self.count = 0
  44. def update(self, val, n=1):
  45. self.val = val
  46. self.sum += val * n
  47. self.count += n
  48. self.avg = self.sum / self.count
  49. def sort_to_clockwise(points):
  50. center = tuple(map(operator.truediv, reduce(lambda x, y: map(operator.add, x, y), points), [len(points)] * 2))
  51. clockwise_points = sorted(points, key=lambda coord: (-135 - math.degrees(
  52. math.atan2(*tuple(map(operator.sub, coord, center))[::-1]))) % 360, reverse=True)
  53. return clockwise_points
  54. def write_result_as_txt(img_name, bboxes, path):
  55. if not os.path.isdir(path):
  56. os.makedirs(path)
  57. filename = os.path.join(path, 'res_{}.txt'.format(os.path.splitext(img_name)[0]))
  58. lines = []
  59. for _, bbox in enumerate(bboxes):
  60. bbox = bbox.reshape(-1, 2)
  61. bbox = np.array(list(sort_to_clockwise(bbox)))[[3, 0, 1, 2]].copy().reshape(-1)
  62. values = [int(v) for v in bbox]
  63. line = "%d,%d,%d,%d,%d,%d,%d,%d\n" % tuple(values)
  64. lines.append(line)
  65. with open(filename, 'w') as f:
  66. for line in lines:
  67. f.write(line)
  68. def test():
  69. if not os.path.isdir('./res/submit_ic15/'):
  70. os.makedirs('./res/submit_ic15/')
  71. if not os.path.isdir('./res/vis_ic15/'):
  72. os.makedirs('./res/vis_ic15/')
  73. ds = test_dataset_creator()
  74. config.INFERENCE = True
  75. net = ETSNet(config)
  76. print(args.ckpt)
  77. param_dict = load_checkpoint(args.ckpt)
  78. load_param_into_net(net, param_dict)
  79. print('parameters loaded!')
  80. get_data_time = AverageMeter()
  81. model_run_time = AverageMeter()
  82. post_process_time = AverageMeter()
  83. end_pts = time.time()
  84. iters = ds.create_tuple_iterator(output_numpy=True)
  85. count = 0
  86. for data in iters:
  87. count += 1
  88. # get data
  89. img, img_resized, img_name = data
  90. img = img[0].astype(np.uint8).copy()
  91. img_name = img_name[0].decode('utf-8')
  92. get_data_pts = time.time()
  93. get_data_time.update(get_data_pts - end_pts)
  94. # model run
  95. img_tensor = Tensor(img_resized, mstype.float32)
  96. score, kernels = net(img_tensor)
  97. score = np.squeeze(score.asnumpy())
  98. kernels = np.squeeze(kernels.asnumpy())
  99. model_run_pts = time.time()
  100. model_run_time.update(model_run_pts - get_data_pts)
  101. # post-process
  102. pred = pse(kernels, 5.0)
  103. scale = max(img.shape[:2]) * 1.0 / config.INFER_LONG_SIZE
  104. label = pred
  105. label_num = np.max(label) + 1
  106. bboxes = []
  107. for i in range(1, label_num):
  108. points = np.array(np.where(label == i)).transpose((1, 0))[:, ::-1]
  109. if points.shape[0] < 600:
  110. continue
  111. score_i = np.mean(score[label == i])
  112. if score_i < 0.93:
  113. continue
  114. rect = cv2.minAreaRect(points)
  115. bbox = cv2.boxPoints(rect) * scale
  116. bbox = bbox.astype('int32')
  117. cv2.drawContours(img, [bbox], 0, (0, 255, 0), 3)
  118. bboxes.append(bbox)
  119. post_process_pts = time.time()
  120. post_process_time.update(post_process_pts - model_run_pts)
  121. if count == 1:
  122. get_data_time.reset()
  123. model_run_time.reset()
  124. post_process_time.reset()
  125. end_pts = time.time()
  126. # save res
  127. cv2.imwrite('./res/vis_ic15/{}'.format(img_name), img[:, :, [2, 1, 0]].copy())
  128. write_result_as_txt(img_name, bboxes, './res/submit_ic15/')
  129. if __name__ == "__main__":
  130. test()