File size: 2,457 Bytes
1d76068 | 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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | {
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "1992223c",
"metadata": {},
"outputs": [],
"source": [
"import cv2\n",
"import numpy as np\n",
"from keras.models import load_model\n",
"\n",
"# Load model\n",
"model = load_model(\"load's path\")\n",
"\n",
"# Emotion labels (adjust if needed)\n",
"emotion_labels = {\n",
" 0: \"Angry\",\n",
" 1: \"Happy\",\n",
" 2: \"Neutral\",\n",
" 3: \"Sad\",\n",
" 4: \"Surprised\"\n",
"}\n",
"\n",
"# Load face detector\n",
"face_cascade = cv2.CascadeClassifier(\"path\")\n",
"\n",
"# Open webcam\n",
"cap = cv2.VideoCapture(0)\n",
"\n",
"while True:\n",
" ret, frame = cap.read()\n",
" if not ret:\n",
" break\n",
"\n",
" gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n",
" faces = face_cascade.detectMultiScale(\n",
" gray, scaleFactor=1.3, minNeighbors=5\n",
" )\n",
"\n",
" for (x, y, w, h) in faces:\n",
" face = gray[y:y+h, x:x+w]\n",
" face = cv2.resize(face, (48, 48))\n",
" face = face / 255.0\n",
" face = face.reshape(1, 48, 48, 1)\n",
"\n",
" prediction = model.predict(face, verbose=0)\n",
" emotion = emotion_labels[np.argmax(prediction)]\n",
"\n",
" # Draw rectangle and label\n",
" cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2)\n",
" cv2.putText(\n",
" frame,\n",
" emotion,\n",
" (x, y-10),\n",
" cv2.FONT_HERSHEY_SIMPLEX,\n",
" 0.9,\n",
" (0,255,0),\n",
" 2\n",
" )\n",
"\n",
" cv2.imshow(\"Real-Time Emotion Detection\", frame)\n",
"\n",
" if cv2.waitKey(1) & 0xFF == ord('q'):\n",
" break\n",
"\n",
"\n",
"cv2.destroyAllWindows()\n",
"cap.release()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|