eyad222 commited on
Commit
46f40e7
·
verified ·
1 Parent(s): 4428ffd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -19
app.py CHANGED
@@ -1,57 +1,65 @@
1
  import gradio as gr
2
  import numpy as np
3
  import cv2
 
4
 
5
- # Load model data
 
 
 
6
  mean = np.load("mean.npy")
7
  eigenfaces = np.load("eigenfaces.npy")
8
  projected_faces = np.load("projected_faces.npy")
9
  labels = np.load("labels.npy")
10
 
11
- # Resize and flatten the image
12
  def preprocess(img):
13
  try:
14
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
 
15
  except Exception as e:
16
  raise ValueError(f"Failed to convert to grayscale: {e}")
17
 
18
- resized = cv2.resize(gray, (100, 100))
19
- return resized.flatten()
 
 
20
 
21
- # Predict function with debug
22
- def predict(img):
23
- print("📸 Raw input image:", type(img))
 
 
 
24
 
 
 
25
  if img is None:
26
- return "❌ No image provided"
27
 
28
  try:
29
- # Ensure the input is a NumPy array
30
- if not isinstance(img, np.ndarray):
31
- return f"❌ Unexpected input type: {type(img)}"
32
-
33
- # Preprocess image
34
  img_vector = preprocess(img)
35
  img_centered = img_vector - mean
36
  img_projected = np.dot(eigenfaces.T, img_centered)
37
 
38
- # Compare with dataset
39
  distances = np.linalg.norm(projected_faces - img_projected, axis=1)
40
  min_index = np.argmin(distances)
41
  predicted_label = labels[min_index]
 
42
 
43
- return f"✅ Match found: Person {predicted_label} (distance={distances[min_index]:.2f})"
44
 
45
  except Exception as e:
46
- return f"⚠️ Error during prediction: {str(e)}"
47
 
48
  # Gradio interface
49
  iface = gr.Interface(
50
  fn=predict,
51
- inputs=gr.Image(type="numpy", label="Upload Face Image"),
52
  outputs=gr.Textbox(label="Prediction Result"),
53
- title="Eigenfaces Face Recognition",
54
- description="Upload a face image (JPG/PNG) to identify the most similar person from the dataset."
55
  )
56
 
57
  iface.launch()
 
1
  import gradio as gr
2
  import numpy as np
3
  import cv2
4
+ import os
5
 
6
+ # Load Haar cascade for face detection
7
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
8
+
9
+ # Load precomputed model data
10
  mean = np.load("mean.npy")
11
  eigenfaces = np.load("eigenfaces.npy")
12
  projected_faces = np.load("projected_faces.npy")
13
  labels = np.load("labels.npy")
14
 
15
+ # Preprocess the image: detect face, crop, grayscale, resize, flatten
16
  def preprocess(img):
17
  try:
18
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
19
+ gray = cv2.equalizeHist(gray) # Improve lighting
20
  except Exception as e:
21
  raise ValueError(f"Failed to convert to grayscale: {e}")
22
 
23
+ # Detect face
24
+ faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
25
+ if len(faces) == 0:
26
+ raise ValueError("❌ No face detected in the image.")
27
 
28
+ # Crop the first face found
29
+ x, y, w, h = faces[0]
30
+ face_roi = gray[y:y+h, x:x+w]
31
+ resized_face = cv2.resize(face_roi, (100, 100))
32
+
33
+ return resized_face.flatten()
34
 
35
+ # Predict function
36
+ def predict(img):
37
  if img is None:
38
+ return "❌ No image provided."
39
 
40
  try:
 
 
 
 
 
41
  img_vector = preprocess(img)
42
  img_centered = img_vector - mean
43
  img_projected = np.dot(eigenfaces.T, img_centered)
44
 
45
+ # Calculate Euclidean distances
46
  distances = np.linalg.norm(projected_faces - img_projected, axis=1)
47
  min_index = np.argmin(distances)
48
  predicted_label = labels[min_index]
49
+ confidence = distances[min_index]
50
 
51
+ return f"✅ Match: Person {predicted_label} (distance = {confidence:.2f})"
52
 
53
  except Exception as e:
54
+ return f"⚠️ Error: {str(e)}"
55
 
56
  # Gradio interface
57
  iface = gr.Interface(
58
  fn=predict,
59
+ inputs=gr.Image(type="numpy", label="Upload or Capture a Face"),
60
  outputs=gr.Textbox(label="Prediction Result"),
61
+ title="Enhanced Eigenfaces Face Recognition",
62
+ description="Improved with face detection and lighting normalization. Upload a clear frontal face image."
63
  )
64
 
65
  iface.launch()