| import numpy as np |
| import cv2 |
| import base64 |
| from tensorflow.keras.preprocessing import image |
| import logging |
| import joblib |
|
|
| |
| knn_model = joblib.load('k-nn_model.joblib') |
|
|
| |
| class_labels = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise'] |
|
|
| def detect_knn(image_path): |
| frame = cv2.imread(image_path) |
| gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) |
| resized = cv2.resize(gray, (48, 48)) |
| norm_img = resized / 255.0 |
|
|
| |
| chunks = [norm_img[:, i*8:(i+1)*8] for i in range(6)] |
| sequence = np.stack([chunk.flatten() for chunk in chunks]) |
| features = sequence.flatten() |
| features = features[:994] |
|
|
| features = features.reshape(1, -1) |
|
|
| prediction = knn_model.predict(features)[0] |
| class_labels = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise'] |
| emotion = class_labels[prediction] |
|
|
| _, buffer = cv2.imencode('.jpg', frame) |
| frame_base64 = base64.b64encode(buffer).decode('utf-8') |
|
|
| return emotion, frame_base64 |
|
|