InsightWhispersAI commited on
Commit
8d77bc1
·
verified ·
1 Parent(s): 38a6fc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +8 -31
app.py CHANGED
@@ -20,22 +20,10 @@ def preprocess_image(img):
20
  adjusted = cv2.convertScaleAbs(img, alpha=alpha, beta=beta)
21
  return adjusted
22
 
23
- def smooth_blend(img, swapped_img, face_mask):
24
- # Dilate the mask for better blending
25
- kernel = np.ones((5, 5), np.uint8)
26
- mask = cv2.dilate(face_mask, kernel, iterations=2)
27
- mask = cv2.GaussianBlur(mask, (15, 15), 0)
28
- mask = mask / 255.0
29
- mask = np.repeat(mask[:, :, np.newaxis], 3, axis=2)
30
- result = (swapped_img * mask + img * (1 - mask)).astype(np.uint8)
31
- return result
32
-
33
- def create_face_mask(img, keypoints):
34
- # Create a convex hull mask around the face using keypoints
35
- hull = cv2.convexHull(keypoints.astype(np.int32))
36
- mask = np.zeros(img.shape[:2], dtype=np.uint8)
37
- cv2.fillConvexPoly(mask, hull, 255)
38
- return mask
39
 
40
  def swap_faces(src_img, dst_img, blur_strength=5, sharpen=False):
41
  try:
@@ -54,26 +42,15 @@ def swap_faces(src_img, dst_img, blur_strength=5, sharpen=False):
54
  src_face = src_faces[0]
55
  dst_face = dst_faces[0]
56
 
57
- # Create a mask for smoother blending
58
- dst_kps = dst_face.kps
59
- face_mask = create_face_mask(dst_rgb, dst_kps)
60
 
61
- # Perform face swap
62
- swapped_img = swapper.get(dst_rgb, dst_face, src_face, paste_back=False)
63
-
64
- # Blend the swapped face with the original image
65
- blended_img = smooth_blend(dst_rgb, swapped_img, face_mask)
66
-
67
- # Post-processing
68
  if blur_strength > 0:
69
- blended_img = cv2.GaussianBlur(blended_img, (blur_strength, blur_strength), 0)
70
 
71
  if sharpen:
72
- kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
73
- blended_img = cv2.filter2D(blended_img, -1, kernel)
74
- blended_img = np.clip(blended_img, 0, 255).astype(np.uint8)
75
 
76
- result = cv2.cvtColor(blended_img, cv2.COLOR_RGB2BGR)
77
  return result
78
  except Exception as e:
79
  print(f"Error: {str(e)}")
 
20
  adjusted = cv2.convertScaleAbs(img, alpha=alpha, beta=beta)
21
  return adjusted
22
 
23
+ def sharpen_image(img):
24
+ kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
25
+ sharpened = cv2.filter2D(img, -1, kernel)
26
+ return np.clip(sharpened, 0, 255).astype(np.uint8)
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  def swap_faces(src_img, dst_img, blur_strength=5, sharpen=False):
29
  try:
 
42
  src_face = src_faces[0]
43
  dst_face = dst_faces[0]
44
 
45
+ swapped_img = swapper.get(dst_rgb, dst_face, src_face, paste_back=True)
 
 
46
 
 
 
 
 
 
 
 
47
  if blur_strength > 0:
48
+ swapped_img = cv2.GaussianBlur(swapped_img, (blur_strength, blur_strength), 0)
49
 
50
  if sharpen:
51
+ swapped_img = sharpen_image(swapped_img)
 
 
52
 
53
+ result = cv2.cvtColor(swapped_img, cv2.COLOR_RGB2BGR)
54
  return result
55
  except Exception as e:
56
  print(f"Error: {str(e)}")