# import libraries import streamlit as st from streamlit_image_select import image_select import tensorflow as tf import numpy as np import cv2 from PIL import Image # Project title st.title('Emotion Detector App') # display banner image st.image("banner_emotions.jpg") img = image_select( label = "Select an image to run model", images = ["test_images/angry1.jpg", "test_images/angry2.jpg", "test_images/happy1.jpg", "test_images/happy2.jpg", "test_images/sad1.jpg", "test_images/sad2.jpg"] ) uploaded_img = st.file_uploader("Upload an image file", type = ["png", "jpg", "jpeg"]) # load model @st.cache_resource def cache_model(model_add): model = tf.keras.models.load_model(model_add) return model model = cache_model("emotion_detector") # creating predict button predict = st.button("Predict") # defining harcascade classifier and class_names face_detector=cv2.CascadeClassifier("haarcascade_frontalface_default.xml") class_names = ["Angry", "Happy", "Sad"] def model_pred(model, image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) results = face_detector.detectMultiScale(gray,scaleFactor=1.05, minNeighbors=10, minSize=(100, 100)) if len(results) != 0: for x,y,w,h in results: img_crp = image[y:y+h, x:x+w] img_crp = cv2.resize(img_crp,(350,350)) y_pred_prob = model.predict(tf.expand_dims(img_crp, axis = 0)) y_pred = np.argmax(y_pred_prob, axis = -1) # print(y_pred_prob) label = class_names[int(y_pred)] cv2.rectangle(image, (x,y), (x+w, y+h), color=(0, 255, 0), thickness = 10) cv2.putText(image,f"{label},{np.round(np.max(y_pred_prob),2)}%", (x,y-20),cv2.FONT_HERSHEY_COMPLEX,2, (0,255,255),2) return image if predict: if uploaded_img: # img_array = np.array(uploaded_img) img_array = np.array(Image.open(uploaded_img)) result_img = model_pred(model,img_array) st.image(result_img) else: st.write("Please upload a valid image") else: image_array = np.array(Image.open(img)) result_img = model_pred(model, image_array) st.image(result_img)