SamBenji commited on
Commit
f1debe0
·
verified ·
1 Parent(s): 1944277

Upload 2 files

Browse files
Emotion-detection_openCV-main/Emotion-detection_openCV-main/README.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Emotion-detection_openCV
2
+ Here’s a professional `README.md` for your **real-time Emotion Detection with CNN and OpenCV** project (`emotion.py`):
3
+
4
+ ---
5
+
6
+ ## 😄 Emotion Detection with CNN & OpenCV
7
+
8
+ This project implements a real-time emotion detection system using a Convolutional Neural Network (CNN) trained on grayscale facial images. It uses OpenCV for face detection and TensorFlow/Keras for emotion classification.
9
+
10
+ ---
11
+
12
+ ### 📸 Live Demo
13
+
14
+ The system uses your webcam to detect faces and classify emotions in real-time, displaying labels like `happy`, `sad`, `angry`, etc., on detected faces.
15
+
16
+ ---
17
+
18
+ ### 🧠 Model Overview
19
+
20
+ * **Model Type:** CNN (Convolutional Neural Network)
21
+ * **Input:** 48x48 grayscale facial images
22
+ * **Output:** Emotion classification (softmax)
23
+ * **Framework:** TensorFlow/Keras
24
+ * **Face Detection:** OpenCV Haar cascades
25
+
26
+ ---
27
+ Recommended Kaggle Dataset:
28
+ FER-2013: Facial Expression Recognition
29
+ 🔗 Link: https://www.kaggle.com/datasets/msambare/fer2013
30
+ ### 🗂 Dataset Format
31
+
32
+ Organize your dataset as follows:
33
+
34
+ ```
35
+ dataset/
36
+ ├── train/
37
+ │ ├── happy/
38
+ │ ├── sad/
39
+ │ └── ...
40
+ ├── test/
41
+ │ ├── happy/
42
+ │ ├── sad/
43
+ │ └── ...
44
+ ```
45
+
46
+ Each emotion class should be in its own folder with grayscale 48x48 facial images.
47
+
48
+ ---
49
+
50
+ ### ⚙️ Installation
51
+
52
+ 1. **Clone the repo**
53
+
54
+ ```bash
55
+ git clone https://github.com/yourusername/Emotion-detection_openCV.git
56
+ cd emotion-detection
57
+ ```
58
+
59
+ 2. **Install dependencies**
60
+
61
+ ```bash
62
+ pip install tensorflow opencv-python numpy
63
+ ```
64
+
65
+ > You may also need:
66
+
67
+ ```bash
68
+ pip install keras
69
+ ```
70
+
71
+ ---
72
+
73
+ ### 🚀 How to Run
74
+
75
+ 1. **Train the model**
76
+
77
+ ```bash
78
+ python emotion.py
79
+ ```
80
+
81
+ This will:
82
+
83
+ * Load and preprocess images
84
+ * Train a CNN model
85
+ * Save the model as `emotion_model.h5`
86
+ * Launch webcam for live prediction
87
+
88
+ 2. **Use webcam for emotion detection**
89
+ The webcam will open automatically after training, or load `emotion_model.h5` if it already exists.
90
+
91
+ Press `q` to exit webcam mode.
92
+
93
+ ---
94
+
95
+ ### 📁 Files
96
+
97
+ | File | Description |
98
+ | ------------------ | ------------------------------------------------ |
99
+ | `emotion.py` | Main script for training and real-time detection |
100
+ | `emotion_model.h5` | Trained CNN model (saved after training) |
101
+ | `dataset/` | Folder containing training and testing images |
102
+
103
+ ---
104
+
105
+ ### 📊 Model Architecture
106
+
107
+ * Conv2D → ReLU → MaxPooling
108
+ * Conv2D → ReLU → MaxPooling
109
+ * Flatten → Dense → Dropout → Softmax
110
+
111
+ ---
112
+
113
+ ### 🔍 Emotion Labels
114
+
115
+ Automatically inferred from folder names in `dataset/train/`. For example:
116
+
117
+ * `happy`, `angry`, `surprised`, `sad`, etc.
118
+
119
+ ---
120
+
121
+ ### 📌 Notes
122
+
123
+ * Ensure your dataset is balanced across emotion classes.
124
+ * Webcam access must be granted for live prediction.
125
+ * Model is trained in grayscale for efficiency.
126
+
127
+ ---
128
+
129
+ ### 📄 License
130
+
131
+ MIT License — free to use, modify, and share.
132
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
133
+ ![Last Commit](https://img.shields.io/github/last-commit/Soham-Banerjee-web/Emotion-detection_openCV)
134
+ ![Issues](https://img.shields.io/github/issues/Soham-Banerjee-web/Emotion-detection_openCV)
135
+
Emotion-detection_openCV-main/Emotion-detection_openCV-main/emotion.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import tensorflow as tf
4
+ from tensorflow.keras.models import Sequential
5
+ from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
6
+ from tensorflow.keras.preprocessing.image import ImageDataGenerator
7
+ import os
8
+
9
+ # Paths to dataset folders
10
+ train_dir = "dataset/train"
11
+ test_dir = "dataset/test"
12
+
13
+ # Define image size & batch size
14
+ IMG_SIZE = (48, 48)
15
+ BATCH_SIZE = 64
16
+
17
+ # Load dataset using ImageDataGenerator
18
+ train_datagen = ImageDataGenerator(rescale=1./255)
19
+ test_datagen = ImageDataGenerator(rescale=1./255)
20
+
21
+ train_generator = train_datagen.flow_from_directory(
22
+ train_dir,
23
+ target_size=IMG_SIZE,
24
+ batch_size=BATCH_SIZE,
25
+ color_mode="grayscale",
26
+ class_mode="categorical"
27
+ )
28
+
29
+ test_generator = test_datagen.flow_from_directory(
30
+ test_dir,
31
+ target_size=IMG_SIZE,
32
+ batch_size=BATCH_SIZE,
33
+ color_mode="grayscale",
34
+ class_mode="categorical"
35
+ )
36
+
37
+ # Get emotion labels from folder names
38
+ emotion_labels = list(train_generator.class_indices.keys())
39
+
40
+ # Build CNN model
41
+ model = Sequential([
42
+ Conv2D(64, (3, 3), activation="relu", input_shape=(48, 48, 1)),
43
+ MaxPooling2D(2, 2),
44
+
45
+ Conv2D(128, (3, 3), activation="relu"),
46
+ MaxPooling2D(2, 2),
47
+
48
+ Flatten(),
49
+ Dense(256, activation="relu"),
50
+ Dropout(0.5),
51
+ Dense(len(emotion_labels), activation="softmax") # Number of emotions
52
+ ])
53
+
54
+ # Compile the model
55
+ model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
56
+
57
+ # Train the model
58
+ model.fit(train_generator, epochs=20, validation_data=test_generator)
59
+
60
+ # Save trained model
61
+ model.save("emotion_model.h5")
62
+
63
+ print("✅ Model training complete and saved as 'emotion_model.h5'")
64
+
65
+ # Load trained model
66
+ model = tf.keras.models.load_model("emotion_model.h5")
67
+
68
+ # OpenCV Face Detection
69
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
70
+
71
+ # Open webcam
72
+ cap = cv2.VideoCapture(0)
73
+
74
+ while True:
75
+ ret, frame = cap.read()
76
+ if not ret:
77
+ break
78
+
79
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
80
+ faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
81
+
82
+ for (x, y, w, h) in faces:
83
+ roi_gray = gray[y:y+h, x:x+w]
84
+ roi_gray = cv2.resize(roi_gray, (48, 48))
85
+ roi_gray = np.expand_dims(roi_gray, axis=0)
86
+ roi_gray = np.expand_dims(roi_gray, axis=-1) / 255.0
87
+
88
+ # Predict emotion
89
+ predictions = model.predict(roi_gray)
90
+ emotion_label = emotion_labels[np.argmax(predictions)]
91
+
92
+ # Draw rectangle and label on face
93
+ cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
94
+ cv2.putText(frame, emotion_label, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2)
95
+
96
+ cv2.imshow("Emotion Detection", frame)
97
+
98
+ if cv2.waitKey(1) & 0xFF == ord('q'):
99
+ break
100
+
101
+ cap.release()
102
+ cv2.destroyAllWindows()