0% found this document useful (0 votes)
3 views

app.py

Uploaded by

mi539919
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

app.py

Uploaded by

mi539919
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import streamlit as st

import cv2
from keras.models import model_from_json
import numpy as np
import tensorflow as tf
from PIL import Image

# Load the model


json_file = open("facialemotionmodel.json", "r")
model_json = json_file.read()
json_file.close()
model = model_from_json(model_json)
model.load_weights("facialemotionmodel.h5")

# Load the Haar Cascade for face detection


haar_file = cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
face_cascade = cv2.CascadeClassifier(haar_file)

# Emotion labels
labels = {0: 'angry', 1: 'disgust', 2: 'fear', 3: 'happy', 4: 'neutral', 5: 'sad',
6: 'surprise'}

# Function to extract features from the image


def extract_features(image):
feature = np.array(image)
feature = feature.reshape(1, 48, 48, 1)
return feature / 255.0

# Function to process the webcam feed and make predictions


def process_frame(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(frame, 1.3, 5)

for (p, q, r, s) in faces:


image = gray[q:q + s, p:p + r]
image = cv2.resize(image, (48, 48))
img = extract_features(image)
pred = model.predict(img)
prediction_label = labels[pred.argmax()]

# Draw rectangle and put text on the face


cv2.rectangle(frame, (p, q), (p + r, q + s), (255, 0, 0), 2)
cv2.putText(frame, '% s' % (prediction_label), (p - 10, q - 10),
cv2.FONT_HERSHEY_COMPLEX_SMALL, 2, (0, 0, 255))

return frame

# Streamlit UI elements
st.title("Facial Emotion Recognition")
st.write("Webcam live feed with emotion prediction.")

# Displaying video from webcam


video_stream = st.camera_input("Take a snapshot", key="webcam",
use_column_width=True)

if video_stream:
# Get image from the Streamlit camera input
frame = video_stream.getvalue()
np_frame = np.frombuffer(frame, dtype=np.uint8)
frame = cv2.imdecode(np_frame, 1)

# Process the frame to predict emotion


output_frame = process_frame(frame)

# Convert processed frame to RGB for Streamlit display


output_frame = cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB)
st.image(output_frame, channels="RGB", use_column_width=True)

You might also like