kalpit sharma
adding changes
5b6acdd
import numpy as np
import cv2
import base64
from tensorflow.keras.preprocessing import image
import logging
import joblib
# Load KNN model globally
knn_model = joblib.load('k-nn_model.joblib')
# Emotion classes
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)) # 48x48
norm_img = resized / 255.0
# Feature extraction similar to training: horizontal chunks
chunks = [norm_img[:, i*8:(i+1)*8] for i in range(6)] # 6 chunks of 8px
sequence = np.stack([chunk.flatten() for chunk in chunks]) # (6, 384)
features = sequence.flatten() # (2304,)
features = features[:994] # match training shape
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