File size: 2,521 Bytes
9945a10
 
9e510e0
9945a10
 
 
 
 
 
 
 
 
 
 
82443bc
 
 
 
 
 
 
 
 
9945a10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0aeb27
 
9945a10
 
 
 
 
 
 
 
 
 
 
 
 
 
82443bc
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# 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)