bg_replace.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
  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 argparse
  15. import os
  16. import sys
  17. import cv2
  18. import numpy as np
  19. import paddle
  20. import paddleseg
  21. from paddleseg.cvlibs import manager
  22. from paddleseg.utils import get_sys_env, logger
  23. LOCAL_PATH = os.path.dirname(os.path.abspath(__file__))
  24. sys.path.append(os.path.join(LOCAL_PATH, '..'))
  25. manager.BACKBONES._components_dict.clear()
  26. manager.TRANSFORMS._components_dict.clear()
  27. import ppmatting
  28. from ppmatting.core import predict
  29. from ppmatting.utils import get_image_list, estimate_foreground_ml, Config, MatBuilder
  30. def parse_args():
  31. parser = argparse.ArgumentParser(
  32. description='PP-HumanSeg inference for video')
  33. parser.add_argument(
  34. "--config",
  35. dest="cfg",
  36. help="The config file.",
  37. default=None,
  38. type=str,
  39. required=True)
  40. parser.add_argument(
  41. '--model_path',
  42. dest='model_path',
  43. help='The path of model for prediction',
  44. type=str,
  45. default=None)
  46. parser.add_argument(
  47. '--image_path',
  48. dest='image_path',
  49. help='Image including human',
  50. type=str,
  51. default=None)
  52. parser.add_argument(
  53. '--trimap_path',
  54. dest='trimap_path',
  55. help='The path of trimap',
  56. type=str,
  57. default=None)
  58. parser.add_argument(
  59. '--background',
  60. dest='background',
  61. help='Background for replacing. It is a string which specifies the background color (r,g,b,w) or a path to background image. If not specified, a green background is used.',
  62. type=str,
  63. default=None)
  64. parser.add_argument(
  65. '--save_dir',
  66. dest='save_dir',
  67. help='The directory for saving the inference results',
  68. type=str,
  69. default='./output')
  70. parser.add_argument(
  71. '--fg_estimate',
  72. default=True,
  73. type=eval,
  74. choices=[True, False],
  75. help='Whether to estimate foreground when predicting.')
  76. parser.add_argument(
  77. '--device',
  78. dest='device',
  79. help='Set the device type, which may be GPU, CPU or XPU.',
  80. default='gpu',
  81. type=str)
  82. return parser.parse_args()
  83. def main(args):
  84. assert args.cfg is not None, \
  85. 'No configuration file specified, please set --config'
  86. cfg = Config(args.cfg)
  87. builder = MatBuilder(cfg)
  88. paddleseg.utils.show_env_info()
  89. paddleseg.utils.show_cfg_info(cfg)
  90. paddleseg.utils.set_device(args.device)
  91. model = builder.model
  92. transforms = ppmatting.transforms.Compose(builder.val_transforms)
  93. alpha, fg = predict(
  94. model,
  95. model_path=args.model_path,
  96. transforms=transforms,
  97. image_list=[args.image_path],
  98. trimap_list=[args.trimap_path],
  99. save_dir=args.save_dir,
  100. fg_estimate=args.fg_estimate)
  101. img_ori = cv2.imread(args.image_path)
  102. bg = get_bg(args.background, img_ori.shape)
  103. alpha = alpha / 255.0
  104. alpha = alpha[:, :, np.newaxis]
  105. com = alpha * fg + (1 - alpha) * bg
  106. com = com.astype('uint8')
  107. com_save_path = os.path.join(args.save_dir,
  108. os.path.basename(args.image_path))
  109. cv2.imwrite(com_save_path, com)
  110. def get_bg(background, img_shape):
  111. bg = np.zeros(img_shape)
  112. if background == 'r':
  113. bg[:, :, 2] = 255
  114. elif background is None or background == 'g':
  115. bg[:, :, 1] = 255
  116. elif background == 'b':
  117. bg[:, :, 0] = 255
  118. elif background == 'w':
  119. bg[:, :, :] = 255
  120. elif not os.path.exists(background):
  121. raise Exception('The --background is not existed: {}'.format(
  122. background))
  123. else:
  124. bg = cv2.imread(background)
  125. bg = cv2.resize(bg, (img_shape[1], img_shape[0]))
  126. return bg
  127. if __name__ == "__main__":
  128. args = parse_args()
  129. main(args)