nirnit-13 commited on
Commit
0e892e8
Β·
1 Parent(s): 6a18c8a

Fix: switch to live webcam streaming with gr.Blocks

Browse files
Files changed (1) hide show
  1. app.py +76 -43
app.py CHANGED
@@ -15,29 +15,43 @@ emotion_labels = {
15
  4: "Surprised"
16
  }
17
 
18
- # Load face detector (OpenCV built-in path via cv2.data)
19
- face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- def detect_emotion(image):
22
  """
23
- Takes an image (numpy array from Gradio), detects faces,
24
- predicts emotion for each face, and returns the annotated image.
 
25
  """
26
- if image is None:
27
  return None
28
 
29
- # Gradio sends RGB; convert to BGR for OpenCV
30
- frame = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
31
- gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
32
 
33
  faces = face_cascade.detectMultiScale(
34
- gray, scaleFactor=1.3, minNeighbors=5
 
 
 
35
  )
36
 
37
  if len(faces) == 0:
38
- # No face detected β€” return original image with a message
39
  cv2.putText(
40
- frame,
41
  "No face detected",
42
  (20, 40),
43
  cv2.FONT_HERSHEY_SIMPLEX,
@@ -47,48 +61,67 @@ def detect_emotion(image):
47
  )
48
  else:
49
  for (x, y, w, h) in faces:
50
- face = gray[y:y+h, x:x+w]
51
- face = cv2.resize(face, (48, 48))
52
- face = face / 255.0
53
- face = face.reshape(1, 48, 48, 1)
 
54
 
55
- prediction = model.predict(face, verbose=0)
56
- emotion = emotion_labels[np.argmax(prediction)]
 
57
  confidence = float(np.max(prediction)) * 100
 
58
 
59
  # Draw bounding box
60
- cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
 
 
 
 
 
61
 
62
- # Draw emotion label with confidence
63
- label = f"{emotion} ({confidence:.1f}%)"
64
  cv2.putText(
65
- frame,
66
  label,
67
- (x, y - 10),
68
  cv2.FONT_HERSHEY_SIMPLEX,
69
- 0.9,
70
- (0, 255, 0),
71
  2
72
  )
73
 
74
- # Convert back to RGB for Gradio output
75
- result = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
76
- return result
77
-
78
-
79
- # Gradio Interface
80
- demo = gr.Interface(
81
- fn=detect_emotion,
82
- inputs=gr.Image(type="numpy", label="Upload or Capture Image"),
83
- outputs=gr.Image(type="numpy", label="Detected Emotion"),
84
- title="😊 Real-Time Emotion Detection",
85
- description=(
86
- "Upload a photo or use your webcam to detect facial emotions.\n\n"
87
- "**Detectable Emotions:** Angry 😠 | Happy πŸ˜„ | Neutral 😐 | Sad 😒 | Surprised 😲\n\n"
88
- "The model uses a CNN trained on 48Γ—48 grayscale face images."
89
- ),
90
- flagging_mode="never"
91
- )
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  if __name__ == "__main__":
94
  demo.launch()
 
15
  4: "Surprised"
16
  }
17
 
18
+ # Emotion colors (BGR) β€” each emotion gets a distinct color
19
+ emotion_colors = {
20
+ "Angry": (0, 0, 255), # Red
21
+ "Happy": (0, 255, 0), # Green
22
+ "Neutral": (255, 255, 0), # Cyan
23
+ "Sad": (255, 0, 0), # Blue
24
+ "Surprised": (0, 165, 255) # Orange
25
+ }
26
+
27
+ # Load face detector via OpenCV built-in path
28
+ face_cascade = cv2.CascadeClassifier(
29
+ cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
30
+ )
31
 
32
+ def detect_emotion(frame):
33
  """
34
+ Called on every webcam frame by Gradio's streaming interface.
35
+ Detects faces, predicts emotion, draws bounding box + label.
36
+ Returns the annotated frame (RGB).
37
  """
38
+ if frame is None:
39
  return None
40
 
41
+ # Gradio streams frames as RGB numpy arrays β€” convert to BGR for OpenCV
42
+ frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
43
+ gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
44
 
45
  faces = face_cascade.detectMultiScale(
46
+ gray,
47
+ scaleFactor=1.3,
48
+ minNeighbors=5,
49
+ minSize=(30, 30)
50
  )
51
 
52
  if len(faces) == 0:
 
53
  cv2.putText(
54
+ frame_bgr,
55
  "No face detected",
56
  (20, 40),
57
  cv2.FONT_HERSHEY_SIMPLEX,
 
61
  )
62
  else:
63
  for (x, y, w, h) in faces:
64
+ # Crop and preprocess face
65
+ face_roi = gray[y:y+h, x:x+w]
66
+ face_roi = cv2.resize(face_roi, (48, 48))
67
+ face_roi = face_roi / 255.0
68
+ face_roi = face_roi.reshape(1, 48, 48, 1)
69
 
70
+ # Predict
71
+ prediction = model.predict(face_roi, verbose=0)
72
+ emotion = emotion_labels[np.argmax(prediction)]
73
  confidence = float(np.max(prediction)) * 100
74
+ color = emotion_colors[emotion]
75
 
76
  # Draw bounding box
77
+ cv2.rectangle(frame_bgr, (x, y), (x+w, y+h), color, 2)
78
+
79
+ # Draw filled label background for readability
80
+ label = f"{emotion} {confidence:.1f}%"
81
+ (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2)
82
+ cv2.rectangle(frame_bgr, (x, y - th - 12), (x + tw + 6, y), color, -1)
83
 
84
+ # Draw label text in black over the colored background
 
85
  cv2.putText(
86
+ frame_bgr,
87
  label,
88
+ (x + 3, y - 5),
89
  cv2.FONT_HERSHEY_SIMPLEX,
90
+ 0.8,
91
+ (0, 0, 0),
92
  2
93
  )
94
 
95
+ # Convert back to RGB for Gradio
96
+ return cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
97
+
98
+
99
+ # Gradio Streaming Interface
100
+ with gr.Blocks(title="Real-Time Emotion Detection") as demo:
101
+
102
+ gr.Markdown(
103
+ """
104
+ # 😊 Real-Time Emotion Detection
105
+ Allow camera access and click **Start** to begin live detection.
106
+ Detectable emotions: 😠 Angry  |  πŸ˜„ Happy  |  😐 Neutral  |  😒 Sad  |  😲 Surprised
107
+ """
108
+ )
109
+
110
+ with gr.Row():
111
+ input_cam = gr.Image(sources=["webcam"], streaming=True, label="πŸ“· Live Webcam")
112
+ output_img = gr.Image(label="🎯 Detected Emotion")
113
+
114
+ gr.Markdown(
115
+ """
116
+ ---
117
+ **How it works:** Each webcam frame is processed by a CNN model trained on 48Γ—48 grayscale face images.
118
+ Haar Cascade detects faces, then the model predicts the emotion with confidence score.
119
+ """
120
+ )
121
+
122
+ # Stream every frame from webcam β†’ detect_emotion β†’ output
123
+ input_cam.stream(fn=detect_emotion, inputs=input_cam, outputs=output_img)
124
+
125
 
126
  if __name__ == "__main__":
127
  demo.launch()