predictors.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # Copyright (c) 2020 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 numpy as np
  15. import cv2
  16. import math
  17. import paddle
  18. from arch import style_text_rec
  19. from utils.sys_funcs import check_gpu
  20. from utils.logging import get_logger
  21. class StyleTextRecPredictor(object):
  22. def __init__(self, config):
  23. algorithm = config['Predictor']['algorithm']
  24. assert algorithm in ["StyleTextRec"
  25. ], "Generator {} not supported.".format(algorithm)
  26. use_gpu = config["Global"]['use_gpu']
  27. check_gpu(use_gpu)
  28. paddle.set_device('gpu' if use_gpu else 'cpu')
  29. self.logger = get_logger()
  30. self.generator = getattr(style_text_rec, algorithm)(config)
  31. self.height = config["Global"]["image_height"]
  32. self.width = config["Global"]["image_width"]
  33. self.scale = config["Predictor"]["scale"]
  34. self.mean = config["Predictor"]["mean"]
  35. self.std = config["Predictor"]["std"]
  36. self.expand_result = config["Predictor"]["expand_result"]
  37. def predict(self, style_input, text_input):
  38. style_input = self.rep_style_input(style_input, text_input)
  39. tensor_style_input = self.preprocess(style_input)
  40. tensor_text_input = self.preprocess(text_input)
  41. style_text_result = self.generator.forward(tensor_style_input,
  42. tensor_text_input)
  43. fake_fusion = self.postprocess(style_text_result["fake_fusion"])
  44. fake_text = self.postprocess(style_text_result["fake_text"])
  45. fake_sk = self.postprocess(style_text_result["fake_sk"])
  46. fake_bg = self.postprocess(style_text_result["fake_bg"])
  47. bbox = self.get_text_boundary(fake_text)
  48. if bbox:
  49. left, right, top, bottom = bbox
  50. fake_fusion = fake_fusion[top:bottom, left:right, :]
  51. fake_text = fake_text[top:bottom, left:right, :]
  52. fake_sk = fake_sk[top:bottom, left:right, :]
  53. fake_bg = fake_bg[top:bottom, left:right, :]
  54. # fake_fusion = self.crop_by_text(img_fake_fusion, img_fake_text)
  55. return {
  56. "fake_fusion": fake_fusion,
  57. "fake_text": fake_text,
  58. "fake_sk": fake_sk,
  59. "fake_bg": fake_bg,
  60. }
  61. def preprocess(self, img):
  62. img = (img.astype('float32') * self.scale - self.mean) / self.std
  63. img_height, img_width, channel = img.shape
  64. assert channel == 3, "Please use an rgb image."
  65. ratio = img_width / float(img_height)
  66. if math.ceil(self.height * ratio) > self.width:
  67. resized_w = self.width
  68. else:
  69. resized_w = int(math.ceil(self.height * ratio))
  70. img = cv2.resize(img, (resized_w, self.height))
  71. new_img = np.zeros([self.height, self.width, 3]).astype('float32')
  72. new_img[:, 0:resized_w, :] = img
  73. img = new_img.transpose((2, 0, 1))
  74. img = img[np.newaxis, :, :, :]
  75. return paddle.to_tensor(img)
  76. def postprocess(self, tensor):
  77. img = tensor.numpy()[0]
  78. img = img.transpose((1, 2, 0))
  79. img = (img * self.std + self.mean) / self.scale
  80. img = np.maximum(img, 0.0)
  81. img = np.minimum(img, 255.0)
  82. img = img.astype('uint8')
  83. return img
  84. def rep_style_input(self, style_input, text_input):
  85. rep_num = int(1.2 * (text_input.shape[1] / text_input.shape[0]) /
  86. (style_input.shape[1] / style_input.shape[0])) + 1
  87. style_input = np.tile(style_input, reps=[1, rep_num, 1])
  88. max_width = int(self.width / self.height * style_input.shape[0])
  89. style_input = style_input[:, :max_width, :]
  90. return style_input
  91. def get_text_boundary(self, text_img):
  92. img_height = text_img.shape[0]
  93. img_width = text_img.shape[1]
  94. bounder = 3
  95. text_canny_img = cv2.Canny(text_img, 10, 20)
  96. edge_num_h = text_canny_img.sum(axis=0)
  97. no_zero_list_h = np.where(edge_num_h > 0)[0]
  98. edge_num_w = text_canny_img.sum(axis=1)
  99. no_zero_list_w = np.where(edge_num_w > 0)[0]
  100. if len(no_zero_list_h) == 0 or len(no_zero_list_w) == 0:
  101. return None
  102. left = max(no_zero_list_h[0] - bounder, 0)
  103. right = min(no_zero_list_h[-1] + bounder, img_width)
  104. top = max(no_zero_list_w[0] - bounder, 0)
  105. bottom = min(no_zero_list_w[-1] + bounder, img_height)
  106. return [left, right, top, bottom]