Tartan-Ishan/Expression_Classifier
1
1#|export2 3from fastai.vision.all import *4import gradio as gr5'''6Modules for face_location and image manipulation7'''8from PIL import Image9import numpy as np10import cv211 12# import pathlib13# temp = pathlib.PosixPath14# pathlib.PosixPath = pathlib.WindowsPath15import pathlib16plt = platform.system()17if plt == 'Linux': pathlib.WindowsPath = pathlib.PosixPath18 19 20learn = load_learner('resnet18_emotion_detection1.pkl')21 22 23categories = ('Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad', 'Surprise')24 25def classify_image(img_in):26 img_in.thumbnail((192,192))27 img_in_arr = np.array(img_in)28 gray = cv2.cvtColor(img_in_arr, cv2.COLOR_BGR2GRAY)29 30 face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')31 32 # Detect faces33 f = 1.0534 faces =()35 36 # Detect faces37 while len(faces)<1 and f>1.01:38 f*= 0.9739 if f<1:40 f = 1.0141 faces = face_cascade.detectMultiScale(gray, f, 1)42 43 # Draw rectangle around the faces and crop the faces44 for (x, y, w, h) in faces:45 # cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)46 faces = gray[y+10:y + h+10 , x:x +w]47 48 # Convert cv2 image, which is an array to a PIL image format for ease of use 49 if len(faces) > 0:50 img_pil = Image.fromarray(faces)51 else:52 img_pil = Image.fromarray(gray)53 54 # img_pil.thumbnail((48,48))55 img_pil = img_pil.resize((48,48))56 img_arr = np.array(img_pil) 57 58 pred, idx, probs = learn.predict(PILImage.create(img_arr))59 return dict(zip(categories, map(float, probs)))60 61image_in = gr.inputs.Image(type='pil')62label = gr.outputs.Label()63examples = ['angry.jpg','disgust.jpg', 'fear.jpg', 'happy.jpg', 'neutral.jpg', 'sad.jpg', 'surprise.jpg']64 65intf = gr.Interface(fn=classify_image, inputs=image_in, outputs=label, examples=examples)66intf.launch()