Athagi commited on
Commit
5d20d22
·
verified ·
1 Parent(s): 02ad1fc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -42
app.py CHANGED
@@ -1,56 +1,59 @@
1
  import cv2
2
  import numpy as np
3
- import gradio as gr
4
  import onnxruntime as ort
5
- from facenet_pytorch import MTCNN
6
  from PIL import Image
7
 
8
- # Load GFPGAN ONNX
9
- gfp_session = ort.InferenceSession("models/gfpgan_1.4.onnx", providers=["CPUExecutionProvider"])
 
10
 
11
- # Load MTCNN for face detection and alignment
12
- face_detector = MTCNN(keep_all=True, device='cpu')
 
 
 
 
 
13
 
14
- def restore_face_from_crop(crop):
15
- """Run GFPGAN on a single aligned crop"""
16
- crop = crop.resize((512, 512), Image.BICUBIC)
17
- np_crop = np.array(crop).astype(np.float32) / 255.0
18
- np_crop = np_crop.transpose(2, 0, 1)[None, ...]
19
- inputs = {gfp_session.get_inputs()[0].name: np_crop}
20
- output = gfp_session.run(None, inputs)[0]
21
  restored = output.squeeze().transpose(1, 2, 0)
22
  restored = np.clip(restored * 255, 0, 255).astype(np.uint8)
23
- return Image.fromarray(restored)
24
-
25
- def enhance_faces(input_image):
26
- input_pil = input_image.convert("RGB")
27
- boxes, probs = face_detector.detect(input_pil)
28
-
29
- if boxes is None or len(boxes) == 0:
30
- return input_image, "❌ No faces detected."
31
-
32
- restored_faces = []
33
- for box in boxes:
34
- x1, y1, x2, y2 = map(int, box)
35
- face_crop = input_pil.crop((x1, y1, x2, y2))
36
- restored = restore_face_from_crop(face_crop)
37
- restored_faces.append(restored)
38
-
39
- # Show only restored faces separately
40
- if restored_faces:
41
- return input_pil, restored_faces
42
- else:
43
- return input_pil, "❌ Could not restore faces."
44
-
 
 
 
 
 
 
 
45
  iface = gr.Interface(
46
  fn=enhance_faces,
47
- inputs=gr.Image(type="pil", label="Upload Image"),
48
- outputs=[
49
- gr.Image(type="pil", label="Original"),
50
- gr.Gallery(label="Restored Faces").style(grid=3, height=200),
51
- ],
52
- title="🧠 GFPGAN 1.4 Face Restoration (Improved)",
53
- description="Uses MTCNN face detection + GFPGAN ONNX for high-quality restoration.",
54
  )
55
 
56
  if __name__ == "__main__":
 
1
  import cv2
2
  import numpy as np
 
3
  import onnxruntime as ort
4
+ import gradio as gr
5
  from PIL import Image
6
 
7
+ # Load GFPGAN ONNX model
8
+ onnx_path = "models/gfpgan_1.4.onnx"
9
+ session = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])
10
 
11
+ def preprocess_face(img, box, size=512):
12
+ x1, y1, x2, y2 = [int(v) for v in box]
13
+ face = img[y1:y2, x1:x2]
14
+ face = cv2.resize(face, (size, size), interpolation=cv2.INTER_LINEAR)
15
+ face = face.astype(np.float32) / 255.0
16
+ face = face.transpose(2, 0, 1)[np.newaxis, :]
17
+ return face, (x1, y1, x2, y2)
18
 
19
+ def postprocess_face(output, face_box, original_shape):
 
 
 
 
 
 
20
  restored = output.squeeze().transpose(1, 2, 0)
21
  restored = np.clip(restored * 255, 0, 255).astype(np.uint8)
22
+ restored = cv2.resize(restored, (face_box[2] - face_box[0], face_box[3] - face_box[1]))
23
+ return restored
24
+
25
+ def detect_faces(img):
26
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
27
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
28
+ boxes = face_cascade.detectMultiScale(gray, 1.3, 5)
29
+ return [[x, y, x + w, y + h] for (x, y, w, h) in boxes]
30
+
31
+ def enhance_faces(image_pil):
32
+ image = np.array(image_pil.convert("RGB"))
33
+ img = image.copy()
34
+ faces = detect_faces(img)
35
+
36
+ if not faces:
37
+ return image_pil, "No faces detected."
38
+
39
+ for box in faces:
40
+ face_input, face_coords = preprocess_face(img, box)
41
+ output = session.run(None, {session.get_inputs()[0].name: face_input})[0]
42
+ restored = postprocess_face(output, box, img.shape)
43
+
44
+ # Paste restored face back
45
+ x1, y1, x2, y2 = box
46
+ img[y1:y2, x1:x2] = restored
47
+
48
+ return Image.fromarray(img), f"{len(faces)} face(s) enhanced."
49
+
50
+ # Gradio UI
51
  iface = gr.Interface(
52
  fn=enhance_faces,
53
+ inputs=gr.Image(type="pil", label="Input Image"),
54
+ outputs=[gr.Image(type="pil", label="Restored Image"), gr.Textbox(label="Log")],
55
+ title="GFPGAN v1.4 (ONNX) - Face Restoration",
56
+ description="Run GFPGAN face restoration using the ONNX model (no PyTorch dependencies)."
 
 
 
57
  )
58
 
59
  if __name__ == "__main__":