-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_model.py
More file actions
65 lines (50 loc) · 1.87 KB
/
Copy pathtest_model.py
File metadata and controls
65 lines (50 loc) · 1.87 KB
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
# FILEPATH: c:/Users/Acer/MockPitch/Emotion/test_model.py
import pickle
import cv2
import numpy as np
import os
import mediapipe as mp
from utils import get_face_landmarks
import csv
import time
# Get the absolute path to the directory of the current script
script_dir = os.path.dirname(os.path.abspath(__file__))
model_file = os.path.join(script_dir, 'model')
# Load the model
with open(model_file, 'rb') as f:
model = pickle.load(f)
emotions = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']
# Initialize MediaPipe FaceMesh
face_mesh = mp.solutions.face_mesh.FaceMesh(static_image_mode=False, max_num_faces=1)
cap = cv2.VideoCapture(0)
# Check if the webcam is opened correctly
if not cap.isOpened():
print("Error: Could not open video stream.")
print("Please make sure your webcam is not in use by another application.")
print("If the issue persists, try changing cv2.VideoCapture(0) to cv2.VideoCapture(1).")
exit()
# Open CSV file for writing
csv_file = open('emotion_output.csv', mode='w', newline='')
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['timestamp', 'emotion']) # header
while True:
ret, frame = cap.read()
if not ret:
print("Error: Can't receive frame (stream end?). Exiting ...")
break
landmarks = get_face_landmarks(frame, face_mesh, draw=False) # disable drawing landmarks
if landmarks:
landmarks = np.array(landmarks).reshape(1, -1)
emotion_idx = model.predict(landmarks)[0]
emotion = emotions[int(emotion_idx)]
# Write timestamp and emotion to CSV and flush immediately
csv_writer.writerow([time.time(), emotion])
csv_file.flush()
# Show clean frame (no text or dots)
cv2.imshow('Emotion Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
csv_file.close()
cap.release()
face_mesh.close()
cv2.destroyAllWindows()