detection / app.py
Ahmad140's picture
Create app.py
1535689 verified
Raw History Blame Contribute Delete
2.15 kB
import gradio as gr
import numpy as np
import cv2
import tensorflow as tf
from PIL import Image
# ---------- Load the trained model ----------
smile_model = tf.keras.models.load_model('smile_model.h5')
print("✅ Model loaded")
# Load Haar Cascade for face detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# ---------- Detection function (called on each webcam frame) ----------
def detect_smile(image):
"""
Takes an image (numpy array), detects faces, classifies smile,
draws bounding boxes (green=smile, red=no smile), and returns the image.
"""
# Convert PIL Image or Gradio numpy to OpenCV BGR
if isinstance(image, Image.Image):
image = np.array(image)
img = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
for (x, y, w, h) in faces:
# Extract face ROI
face_roi = rgb[y:y+h, x:x+w]
face_resized = cv2.resize(face_roi, (224, 224))
face_array = np.expand_dims(face_resized / 255.0, axis=0)
# Predict smile
prob = smile_model.predict(face_array, verbose=0)[0][0]
label = 'Smile' if prob > 0.5 else 'No Smile'
color = (0, 255, 0) if label == 'Smile' else (0, 0, 255)
# Draw rectangle and label
cv2.rectangle(img, (x, y), (x+w, y+h), color, 2)
cv2.putText(img, label, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
# Convert back to RGB for Gradio
return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# ---------- Gradio Interface ----------
interface = gr.Interface(
fn=detect_smile,
inputs=gr.Image(sources=["webcam"], streaming=True, type="numpy", label="Live Webcam"),
outputs=gr.Image(type="numpy", label="Detection Result"),
live=True, # Real-time updates
title="😊 Real-Time Smile Detection",
description="Allow camera access and see live smile detection! Green box = Smile, Red box = No Smile."
)
if __name__ == "__main__":
interface.launch()