predict.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. import os
  15. import math
  16. import cv2
  17. import numpy as np
  18. import paddle
  19. from paddlex.paddleseg import utils
  20. from paddlex.paddleseg.core import infer
  21. from paddlex.paddleseg.utils import logger, progbar
  22. def mkdir(path):
  23. sub_dir = os.path.dirname(path)
  24. if not os.path.exists(sub_dir):
  25. os.makedirs(sub_dir)
  26. def partition_list(arr, m):
  27. """split the list 'arr' into m pieces"""
  28. n = int(math.ceil(len(arr) / float(m)))
  29. return [arr[i:i + n] for i in range(0, len(arr), n)]
  30. def predict(model,
  31. model_path,
  32. transforms,
  33. image_list,
  34. image_dir=None,
  35. save_dir='output',
  36. aug_pred=False,
  37. scales=1.0,
  38. flip_horizontal=True,
  39. flip_vertical=False,
  40. is_slide=False,
  41. stride=None,
  42. crop_size=None):
  43. """
  44. predict and visualize the image_list.
  45. Args:
  46. model (nn.Layer): Used to predict for input image.
  47. model_path (str): The path of pretrained model.
  48. transforms (transform.Compose): Preprocess for input image.
  49. image_list (list): A list of image path to be predicted.
  50. image_dir (str, optional): The root directory of the images predicted. Default: None.
  51. save_dir (str, optional): The directory to save the visualized results. Default: 'output'.
  52. aug_pred (bool, optional): Whether to use mulit-scales and flip augment for predition. Default: False.
  53. scales (list|float, optional): Scales for augment. It is valid when `aug_pred` is True. Default: 1.0.
  54. flip_horizontal (bool, optional): Whether to use flip horizontally augment. It is valid when `aug_pred` is True. Default: True.
  55. flip_vertical (bool, optional): Whether to use flip vertically augment. It is valid when `aug_pred` is True. Default: False.
  56. is_slide (bool, optional): Whether to predict by sliding window. Default: False.
  57. stride (tuple|list, optional): The stride of sliding window, the first is width and the second is height.
  58. It should be provided when `is_slide` is True.
  59. crop_size (tuple|list, optional): The crop size of sliding window, the first is width and the second is height.
  60. It should be provided when `is_slide` is True.
  61. """
  62. utils.utils.load_entire_model(model, model_path)
  63. model.eval()
  64. nranks = paddle.distributed.get_world_size()
  65. local_rank = paddle.distributed.get_rank()
  66. if nranks > 1:
  67. img_lists = partition_list(image_list, nranks)
  68. else:
  69. img_lists = [image_list]
  70. added_saved_dir = os.path.join(save_dir, 'added_prediction')
  71. pred_saved_dir = os.path.join(save_dir, 'pseudo_color_prediction')
  72. logger.info("Start to predict...")
  73. progbar_pred = progbar.Progbar(target=len(img_lists[0]), verbose=1)
  74. with paddle.no_grad():
  75. for i, im_path in enumerate(img_lists[local_rank]):
  76. im = cv2.imread(im_path)
  77. ori_shape = im.shape[:2]
  78. im, _ = transforms(im)
  79. im = im[np.newaxis, ...]
  80. im = paddle.to_tensor(im)
  81. if aug_pred:
  82. pred = infer.aug_inference(
  83. model,
  84. im,
  85. ori_shape=ori_shape,
  86. transforms=transforms.transforms,
  87. scales=scales,
  88. flip_horizontal=flip_horizontal,
  89. flip_vertical=flip_vertical,
  90. is_slide=is_slide,
  91. stride=stride,
  92. crop_size=crop_size)
  93. else:
  94. pred = infer.inference(
  95. model,
  96. im,
  97. ori_shape=ori_shape,
  98. transforms=transforms.transforms,
  99. is_slide=is_slide,
  100. stride=stride,
  101. crop_size=crop_size)
  102. pred = paddle.squeeze(pred)
  103. pred = pred.numpy().astype('uint8')
  104. # get the saved name
  105. if image_dir is not None:
  106. im_file = im_path.replace(image_dir, '')
  107. else:
  108. im_file = os.path.basename(im_path)
  109. if im_file[0] == '/':
  110. im_file = im_file[1:]
  111. # save added image
  112. added_image = utils.visualize.visualize(im_path, pred, weight=0.6)
  113. added_image_path = os.path.join(added_saved_dir, im_file)
  114. mkdir(added_image_path)
  115. cv2.imwrite(added_image_path, added_image)
  116. # save pseudo color prediction
  117. pred_mask = utils.visualize.get_pseudo_color_map(pred)
  118. pred_saved_path = os.path.join(pred_saved_dir,
  119. im_file.rsplit(".")[0] + ".png")
  120. mkdir(pred_saved_path)
  121. pred_mask.save(pred_saved_path)
  122. # pred_im = utils.visualize(im_path, pred, weight=0.0)
  123. # pred_saved_path = os.path.join(pred_saved_dir, im_file)
  124. # mkdir(pred_saved_path)
  125. # cv2.imwrite(pred_saved_path, pred_im)
  126. progbar_pred.update(i + 1)