InsightWhispersAI commited on
Commit
38a6fc5
·
verified ·
1 Parent(s): 06e2a75

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -22
app.py CHANGED
@@ -7,7 +7,7 @@ import onnxruntime
7
  import os
8
 
9
  app = FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider'])
10
- app.prepare(ctx_id=0, det_size=(640, 640))
11
 
12
  inswapper_path = "checkpoints/inswapper_128.onnx"
13
  if not os.path.exists(inswapper_path):
@@ -15,28 +15,36 @@ if not os.path.exists(inswapper_path):
15
  swapper = insightface.model_zoo.get_model(inswapper_path, providers=['CPUExecutionProvider'])
16
 
17
  def preprocess_image(img):
18
- # Adjust brightness and contrast to improve quality
19
- alpha = 1.2 # Contrast control
20
- beta = 10 # Brightness control
21
  adjusted = cv2.convertScaleAbs(img, alpha=alpha, beta=beta)
22
  return adjusted
23
 
24
- def sharpen_image(img):
25
- kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
26
- sharpened = cv2.filter2D(img, -1, kernel)
27
- return np.clip(sharpened, 0, 255).astype(np.uint8)
28
-
29
- def swap_faces(src_img, dst_img, blur_strength=3, sharpen=False):
 
 
 
 
 
 
 
 
 
 
 
 
30
  try:
31
- # Preprocess while preserving color
32
  src = preprocess_image(src_img)
33
  dst = preprocess_image(dst_img)
34
 
35
- # Convert to RGB for face detection
36
  src_rgb = cv2.cvtColor(src, cv2.COLOR_BGR2RGB)
37
  dst_rgb = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)
38
 
39
- # Detect faces
40
  src_faces = app.get(src_rgb)
41
  dst_faces = app.get(dst_rgb)
42
 
@@ -46,19 +54,26 @@ def swap_faces(src_img, dst_img, blur_strength=3, sharpen=False):
46
  src_face = src_faces[0]
47
  dst_face = dst_faces[0]
48
 
49
- # Perform face swap using inswapper
50
- swapped_img = swapper.get(dst_rgb, dst_face, src_face, paste_back=True)
 
 
 
 
 
 
 
51
 
52
- # Post-processing: Apply slight blur for smoother blending
53
  if blur_strength > 0:
54
- swapped_img = cv2.GaussianBlur(swapped_img, (blur_strength, blur_strength), 0)
55
 
56
- # Optional: Apply lightweight sharpening
57
  if sharpen:
58
- swapped_img = sharpen_image(swapped_img)
 
 
59
 
60
- # Convert back to BGR for output
61
- result = cv2.cvtColor(swapped_img, cv2.COLOR_RGB2BGR)
62
  return result
63
  except Exception as e:
64
  print(f"Error: {str(e)}")
@@ -75,7 +90,7 @@ demo = gr.Interface(
75
  inputs=[
76
  gr.Image(label="Source Face", type="numpy"),
77
  gr.Image(label="Target Image", type="numpy"),
78
- gr.Slider(label="Blur Strength", minimum=0, maximum=5, step=1, value=3),
79
  gr.Checkbox(label="Enable Sharpening", value=False)
80
  ],
81
  outputs=gr.Image(label="Face Swapped Output"),
 
7
  import os
8
 
9
  app = FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider'])
10
+ app.prepare(ctx_id=0, det_size=(640, 640), det_thresh=0.3)
11
 
12
  inswapper_path = "checkpoints/inswapper_128.onnx"
13
  if not os.path.exists(inswapper_path):
 
15
  swapper = insightface.model_zoo.get_model(inswapper_path, providers=['CPUExecutionProvider'])
16
 
17
  def preprocess_image(img):
18
+ alpha = 1.3
19
+ beta = 15
 
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:
 
42
  src = preprocess_image(src_img)
43
  dst = preprocess_image(dst_img)
44
 
 
45
  src_rgb = cv2.cvtColor(src, cv2.COLOR_BGR2RGB)
46
  dst_rgb = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)
47
 
 
48
  src_faces = app.get(src_rgb)
49
  dst_faces = app.get(dst_rgb)
50
 
 
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)}")
 
90
  inputs=[
91
  gr.Image(label="Source Face", type="numpy"),
92
  gr.Image(label="Target Image", type="numpy"),
93
+ gr.Slider(label="Blur Strength", minimum=0, maximum=7, step=1, value=5),
94
  gr.Checkbox(label="Enable Sharpening", value=False)
95
  ],
96
  outputs=gr.Image(label="Face Swapped Output"),