Advertisement
dan-masek

Untitled

Feb 10th, 2017
709
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. #!/usr/bin/python
  2. import numpy as np
  3. import cv2
  4.  
  5. def blend_transparent(face_img, overlay_t_img):
  6.     # Split out the transparency mask from the colour info
  7.     overlay_img = overlay_t_img[:,:,:3] # Grab the BRG planes
  8.     overlay_mask = overlay_t_img[:,:,3:]  # And the alpha plane
  9.  
  10.     # Again calculate the inverse mask
  11.     background_mask = 255 - overlay_mask
  12.  
  13.     # Turn the masks into three channel, so we can use them as weights
  14.     overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR)
  15.     background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR)
  16.  
  17.     # Create a masked out face image, and masked out overlay
  18.     # We convert the images to floating point in range 0.0 - 1.0
  19.     face_part = (face_img * (1 / 255.0)) * (background_mask * (1 / 255.0))
  20.     overlay_part = (overlay_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0))
  21.  
  22.     # And finally just add them together, and rescale it back to an 8bit integer image
  23.     return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0))
  24.  
  25. glasses = cv2.imread('fake_glasses.png', -1)
  26. face    = cv2.imread('cage.png', -1)
  27.  
  28. pts1 = np.float32([[  0,  0], [599,  0],
  29.                    [  0,208], [599,208]])
  30. pts2 = np.float32([[ 94,231], [354,181],
  31.                    [115,316], [375,281]])
  32.  
  33. M = cv2.getPerspectiveTransform(pts1,pts2)
  34.  
  35. rotated = cv2.warpPerspective(glasses, M, (face.shape[1], face.shape[0]))
  36. cv2.imwrite("rotated_glasses.png", rotated)
  37.  
  38. result_2 = blend_transparent(face, rotated)
  39. cv2.imwrite("merged_transparent.png", result_2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement