val_ml.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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 cv2
  16. import numpy as np
  17. import time
  18. import paddle
  19. import paddle.nn.functional as F
  20. from paddleseg.utils import TimeAverager, calculate_eta, logger, progbar
  21. from ppmatting.metrics import metric
  22. from pymatting.util.util import load_image, save_image, stack_images
  23. from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml
  24. np.set_printoptions(suppress=True)
  25. def save_alpha_pred(alpha, path):
  26. """
  27. The value of alpha is range [0, 1], shape should be [h,w]
  28. """
  29. dirname = os.path.dirname(path)
  30. if not os.path.exists(dirname):
  31. os.makedirs(dirname)
  32. alpha = (alpha).astype('uint8')
  33. cv2.imwrite(path, alpha)
  34. def reverse_transform(alpha, trans_info):
  35. """recover pred to origin shape"""
  36. for item in trans_info[::-1]:
  37. if item[0][0] == 'resize':
  38. h, w = int(item[1][0]), int(item[1][1])
  39. alpha = cv2.resize(alpha, dsize=(w, h))
  40. elif item[0][0] == 'padding':
  41. h, w = int(item[1][0]), int(item[1][1])
  42. alpha = alpha[0:h, 0:w]
  43. else:
  44. raise Exception("Unexpected info '{}' in im_info".format(item[0]))
  45. return alpha
  46. def evaluate_ml(model,
  47. eval_dataset,
  48. num_workers=0,
  49. print_detail=True,
  50. save_dir='output/results',
  51. save_results=True):
  52. loader = paddle.io.DataLoader(
  53. eval_dataset,
  54. batch_size=1,
  55. drop_last=False,
  56. num_workers=num_workers,
  57. return_list=True, )
  58. total_iters = len(loader)
  59. mse_metric = metric.MSE()
  60. sad_metric = metric.SAD()
  61. grad_metric = metric.Grad()
  62. conn_metric = metric.Conn()
  63. if print_detail:
  64. logger.info("Start evaluating (total_samples: {}, total_iters: {})...".
  65. format(len(eval_dataset), total_iters))
  66. progbar_val = progbar.Progbar(target=total_iters, verbose=1)
  67. reader_cost_averager = TimeAverager()
  68. batch_cost_averager = TimeAverager()
  69. batch_start = time.time()
  70. img_name = ''
  71. i = 0
  72. ignore_cnt = 0
  73. for iter, data in enumerate(loader):
  74. reader_cost_averager.record(time.time() - batch_start)
  75. image_rgb_chw = data['img'].numpy()[0]
  76. image_rgb_hwc = np.transpose(image_rgb_chw, (1, 2, 0))
  77. trimap = data['trimap'].numpy().squeeze() / 255.0
  78. image = image_rgb_hwc * 0.5 + 0.5 # reverse normalize (x/255 - mean) / std
  79. is_fg = trimap >= 0.9
  80. is_bg = trimap <= 0.1
  81. if is_fg.sum() == 0 or is_bg.sum() == 0:
  82. ignore_cnt += 1
  83. logger.info(str(iter))
  84. continue
  85. alpha_pred = model(image, trimap)
  86. alpha_pred = reverse_transform(alpha_pred, data['trans_info'])
  87. alpha_gt = data['alpha'].numpy().squeeze() * 255
  88. trimap = data['ori_trimap'].numpy().squeeze()
  89. alpha_pred = np.round(alpha_pred * 255)
  90. mse = mse_metric.update(alpha_pred, alpha_gt, trimap)
  91. sad = sad_metric.update(alpha_pred, alpha_gt, trimap)
  92. grad = grad_metric.update(alpha_pred, alpha_gt, trimap)
  93. conn = conn_metric.update(alpha_pred, alpha_gt, trimap)
  94. if sad > 1000:
  95. print(data['img_name'][0])
  96. if save_results:
  97. alpha_pred_one = alpha_pred
  98. alpha_pred_one[trimap == 255] = 255
  99. alpha_pred_one[trimap == 0] = 0
  100. save_name = data['img_name'][0]
  101. name, ext = os.path.splitext(save_name)
  102. if save_name == img_name:
  103. save_name = name + '_' + str(i) + ext
  104. i += 1
  105. else:
  106. img_name = save_name
  107. save_name = name + '_' + str(0) + ext
  108. i = 1
  109. save_alpha_pred(alpha_pred_one, os.path.join(save_dir, save_name))
  110. batch_cost_averager.record(
  111. time.time() - batch_start, num_samples=len(alpha_gt))
  112. batch_cost = batch_cost_averager.get_average()
  113. reader_cost = reader_cost_averager.get_average()
  114. if print_detail:
  115. progbar_val.update(iter + 1,
  116. [('SAD', sad), ('MSE', mse), ('Grad', grad),
  117. ('Conn', conn), ('batch_cost', batch_cost),
  118. ('reader cost', reader_cost)])
  119. reader_cost_averager.reset()
  120. batch_cost_averager.reset()
  121. batch_start = time.time()
  122. mse = mse_metric.evaluate()
  123. sad = sad_metric.evaluate()
  124. grad = grad_metric.evaluate()
  125. conn = conn_metric.evaluate()
  126. logger.info('[EVAL] SAD: {:.4f}, MSE: {:.4f}, Grad: {:.4f}, Conn: {:.4f}'.
  127. format(sad, mse, grad, conn))
  128. logger.info('{}'.format(ignore_cnt))
  129. return sad, mse, grad, conn