프로그래밍/Python

[Python] OpenCV 사람 표정 검출(라즈베리파이)

Beginner:) 2022. 11. 11.
320x100

테스트환경은 아래와 같다.

라즈베리파이3/4 (둘 다 테스트) buster

OpenCV 4.1.0

Keras 2.4.3

 


이게 얼굴을 검출하고 그 검출된 사진으로 표정을 검출하기 때문에 진짜 겁나 느리다 ... 

 

라즈베리로는 도저히 못돌리겠다 

 

github에 돌아다니는 코드를 클론해서 사용했다. 링크는 아래에

https://github.com/petercunha/Emotion

 

코드를 보면 이전에 작성했던 글에서 얼굴만 가져와서 다시 모델링을 비교하는 방식이다.

얼굴만 가져오는 예시는 아니고 full body를 가져오는 방식인데 모델만 바꾸면 되니 참고하려면 참고하자

2022.11.11 - [프로그래밍/Python] - [Python] OpenCV 사람인식(라즈베리파이)

 

근데  실행이 안되서 코드를 조금 바꿨다. 코드는 아래에

import cv2
import numpy as np
from keras.models import load_model
from utils.datasets import get_labels
from utils.inference import apply_offsets
from utils.preprocessor import preprocess_input

emotion_model_path = './models/emotion_model.hdf5'
emotion_labels = get_labels('fer2013')

face_cascade = cv2.CascadeClassifier('./models/haarcascade_frontalface_default.xml')
emotion_classifier = load_model(emotion_model_path)
emotion_target_size = emotion_classifier.input_shape[1:3]

cap = cv2.VideoCapture(0)
cap.set(3,320)
cap.set(4,240)

while True: # True:
    ret, bgr_image = cap.read()
    gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5,minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
    
    for face_coordinates in faces:
        x1, x2, y1, y2 = apply_offsets(face_coordinates, (20,40))
        gray_face = gray_image[y1:y2, x1:x2]
        try:
            gray_face = cv2.resize(gray_face, (emotion_target_size))
            gray_face = preprocess_input(gray_face, True)
            gray_face = np.expand_dims(gray_face, 0)
            gray_face = np.expand_dims(gray_face, -1)
            
            face_list = emotion_classifier.predict(gray_face)[0]
            face_index = 0;
            face_text=emotion_labels[0]
            
            for i,v in enumerate(face_list):
                if face_list[i] > face_list[face_index]:
                    face_index = i
                    face_text = emotion_labels[i]
            
            cv2.rectangle(gray_image,(x1,y1),(x2,y2), (0,0,255),3)
            cv2.putText(gray_image,face_text,(x1,y1), 0,1,(0,0,255),2)
        except:
            continue

    cv2.imshow('video', gray_image)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

 

결과물은 구글에 표정이라고 쳐서 카메라를 비췄다.

 

 

사람 표정이란게 다양한데 뭐 이정도만해도 그럭저럭 쓸만하다.

 

참고로 표정의 종류는 0번부터 6번까지  angry, disgust, fear, happy, sad, supprise, natural이다. 

 

근데 깃허브 코드에는 disgust와 natural이 빠져있다.

 

 

반응형

댓글