module.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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 base64
  16. import json
  17. import cv2
  18. import numpy as np
  19. import paddle.nn as nn
  20. import paddlehub as hub
  21. from paddlehub.module.module import moduleinfo, serving
  22. import solov2_blazeface.processor as P
  23. def cv2_to_base64(image):
  24. data = cv2.imencode('.jpg', image)[1]
  25. return base64.b64encode(data.tostring()).decode('utf8')
  26. def base64_to_cv2(b64str):
  27. data = base64.b64decode(b64str.encode('utf8'))
  28. data = np.fromstring(data, np.uint8)
  29. data = cv2.imdecode(data, cv2.IMREAD_COLOR)
  30. return data
  31. @moduleinfo(
  32. name="solov2_blazeface",
  33. type="CV/image_editing",
  34. author="paddlepaddle",
  35. author_email="",
  36. summary="solov2_blaceface is a segmentation and face detection model based on solov2 and blaceface.",
  37. version="1.0.0")
  38. class SoloV2BlazeFaceModel(nn.Layer):
  39. """
  40. SoloV2BlazeFaceModel
  41. """
  42. def __init__(self, use_gpu=True):
  43. super(SoloV2BlazeFaceModel, self).__init__()
  44. self.solov2 = hub.Module(name='solov2', use_gpu=use_gpu)
  45. self.blaceface = hub.Module(name='blazeface', use_gpu=use_gpu)
  46. def predict(self,
  47. image,
  48. background,
  49. beard_file=None,
  50. glasses_file=None,
  51. hat_file=None,
  52. visualization=False,
  53. threshold=0.5):
  54. # instance segmention
  55. solov2_output = self.solov2.predict(
  56. image=image, threshold=threshold, visualization=visualization)
  57. # Set background pixel to 0
  58. im_segm, x0, x1, y0, y1, _, _, _, _, flag_seg = P.visualize_box_mask(
  59. image, solov2_output, threshold=threshold)
  60. if flag_seg == 0:
  61. return im_segm
  62. h, w = y1 - y0, x1 - x0
  63. back_json = background[:-3] + 'json'
  64. stand_box = json.load(open(back_json))
  65. stand_box = stand_box['outputs']['object'][0]['bndbox']
  66. stand_xmin, stand_xmax, stand_ymin, stand_ymax = stand_box[
  67. 'xmin'], stand_box['xmax'], stand_box['ymin'], stand_box['ymax']
  68. im_path = np.asarray(im_segm)
  69. # face detection
  70. blaceface_output = self.blaceface.predict(
  71. image=im_path, threshold=threshold, visualization=visualization)
  72. im_face_kp, p_left, p_right, p_up, p_bottom, h_xmin, h_ymin, h_xmax, h_ymax, flag_face = P.visualize_box_mask(
  73. im_path,
  74. blaceface_output,
  75. threshold=threshold,
  76. beard_file=beard_file,
  77. glasses_file=glasses_file,
  78. hat_file=hat_file)
  79. if flag_face == 1:
  80. if x0 > h_xmin:
  81. shift_x_ = x0 - h_xmin
  82. else:
  83. shift_x_ = 0
  84. if y0 > h_ymin:
  85. shift_y_ = y0 - h_ymin
  86. else:
  87. shift_y_ = 0
  88. h += p_up + p_bottom + shift_y_
  89. w += p_left + p_right + shift_x_
  90. x0 = min(x0, h_xmin)
  91. y0 = min(y0, h_ymin)
  92. x1 = max(x1, h_xmax) + shift_x_ + p_left + p_right
  93. y1 = max(y1, h_ymax) + shift_y_ + p_up + p_bottom
  94. # Fill the background image
  95. cropped = im_face_kp.crop((x0, y0, x1, y1))
  96. resize_scale = min((stand_xmax - stand_xmin) / (x1 - x0),
  97. (stand_ymax - stand_ymin) / (y1 - y0))
  98. h, w = int(h * resize_scale), int(w * resize_scale)
  99. cropped = cropped.resize((w, h), cv2.INTER_LINEAR)
  100. cropped = cv2.cvtColor(np.asarray(cropped), cv2.COLOR_RGB2BGR)
  101. shift_x = int((stand_xmax - stand_xmin - cropped.shape[1]) / 2)
  102. shift_y = int((stand_ymax - stand_ymin - cropped.shape[0]) / 2)
  103. out_image = cv2.imread(background)
  104. e2gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
  105. ret, mask = cv2.threshold(e2gray, 1, 255, cv2.THRESH_BINARY_INV)
  106. mask_inv = cv2.bitwise_not(mask)
  107. roi = out_image[stand_ymin + shift_y:stand_ymin + cropped.shape[
  108. 0] + shift_y, stand_xmin + shift_x:stand_xmin + cropped.shape[1] +
  109. shift_x]
  110. person_bg = cv2.bitwise_and(roi, roi, mask=mask)
  111. element_fg = cv2.bitwise_and(cropped, cropped, mask=mask_inv)
  112. dst = cv2.add(person_bg, element_fg)
  113. out_image[stand_ymin + shift_y:stand_ymin + cropped.shape[
  114. 0] + shift_y, stand_xmin + shift_x:stand_xmin + cropped.shape[1] +
  115. shift_x] = dst
  116. return out_image
  117. @serving
  118. def serving_method(self, images, background, beard, glasses, hat, **kwargs):
  119. """
  120. Run as a service.
  121. """
  122. final = {}
  123. background_path = os.path.join(
  124. self.directory,
  125. 'element_source/background/{}.png'.format(background))
  126. beard_path = os.path.join(self.directory,
  127. 'element_source/beard/{}.png'.format(beard))
  128. glasses_path = os.path.join(
  129. self.directory, 'element_source/glasses/{}.png'.format(glasses))
  130. hat_path = os.path.join(self.directory,
  131. 'element_source/hat/{}.png'.format(hat))
  132. images_decode = base64_to_cv2(images[0])
  133. output = self.predict(
  134. image=images_decode,
  135. background=background_path,
  136. hat_file=hat_path,
  137. beard_file=beard_path,
  138. glasses_file=glasses_path,
  139. **kwargs)
  140. final['image'] = cv2_to_base64(output)
  141. return final