ShamsKhan404 commited on
Commit
b6f7fb9
·
verified ·
1 Parent(s): bffe004

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -94
app.py CHANGED
@@ -1,94 +1,74 @@
1
- import base64
2
- from io import BytesIO
3
- import numpy as np
4
- import cv2
5
- from flask import Flask, render_template, request, Response, url_for
6
- import tensorflow
7
- from PIL import Image
8
- from mtcnn import MTCNN
9
- import time
10
-
11
- app = Flask(__name__)
12
- app.secret_key = 'shamstabrez'
13
-
14
- # Load Model
15
- model = tensorflow.keras.models.load_model('model/RAFDB_Custom.h5')
16
- class_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad', 'Surprise']
17
- IMG_SIZE = (48, 48)
18
- detector = MTCNN()
19
-
20
- streaming = False
21
-
22
- def detect_and_classify(frame):
23
- faces = detector.detect_faces(frame)
24
- top_emotions = []
25
- if faces:
26
- for face in faces:
27
- x, y, w, h = face['box']
28
- x, y = max(0, x), max(0, y) # Prevent negative values
29
- cropped_face = frame[y:y+h, x:x+w]
30
-
31
- if cropped_face.shape[0] > 0 and cropped_face.shape[1] > 0:
32
- face_rgb = cv2.resize(cropped_face, (IMG_SIZE[1], IMG_SIZE[0]))
33
- face_array = tensorflow.keras.preprocessing.image.img_to_array(face_rgb) / 255.0 # Normalize
34
- face_array = np.expand_dims(face_array, axis=0)
35
-
36
- predictions = model.predict(face_array)[0]
37
- top_indices = np.argsort(predictions)[-3:][::-1] # Get top 3 emotions sorted
38
- top_emotions = [(class_labels[i], round(predictions[i] * 100, 2)) for i in top_indices]
39
-
40
- # bounding box & text for highest emotion
41
- cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
42
- top_text = f"{top_emotions[0][1]}% {top_emotions[0][0]}"
43
- cv2.putText(frame, top_text, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
44
- return frame, top_emotions
45
-
46
- @app.route('/')
47
- def index():
48
- return render_template('index.html', top_emotions=None, img_base64=None, show_upload=True, show_camera=False, initial_image=True)
49
-
50
- @app.route('/classify', methods=['POST'])
51
- def classify_image():
52
- image = request.files['image']
53
- img = Image.open(image)
54
- img = np.array(img)
55
- img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
56
- processed_frame, top_emotions = detect_and_classify(img)
57
- _, buffer = cv2.imencode('.png', processed_frame)
58
- img_base64 = base64.b64encode(buffer).decode('utf-8')
59
- return render_template('index.html', top_emotions=top_emotions, img_base64=img_base64, show_upload=True, show_camera=False, initial_image=False)
60
-
61
- def video_stream():
62
- global streaming
63
- cap = cv2.VideoCapture(0)
64
- while streaming and cap.isOpened():
65
- ret, frame = cap.read()
66
- if not ret:
67
- break
68
- frame, top_emotions = detect_and_classify(frame)
69
- _, buffer = cv2.imencode('.jpg', frame)
70
- frame_bytes = buffer.tobytes()
71
- yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')
72
- cap.release()
73
-
74
- @app.route('/start_video')
75
- def start_video():
76
- global streaming
77
- streaming = True
78
- return '', 204
79
-
80
- @app.route('/video_feed')
81
- def video_feed():
82
- if streaming:
83
- return Response(video_stream(), mimetype='multipart/x-mixed-replace; boundary=frame')
84
- else:
85
- return '', 204
86
-
87
- @app.route('/stop_video')
88
- def stop_video():
89
- global streaming
90
- streaming = False
91
- return '', 204
92
-
93
- if __name__ == '__main__':
94
- app.run(debug=True)
 
1
+ import base64
2
+ import numpy as np
3
+ import cv2
4
+ from flask import Flask, render_template, request, jsonify
5
+ import tensorflow
6
+ from PIL import Image
7
+ from io import BytesIO
8
+ from mtcnn import MTCNN
9
+
10
+ app = Flask(__name__)
11
+ app.secret_key = 'shamstabrez'
12
+
13
+ model = tensorflow.keras.models.load_model('model/RAFDB_Custom.h5')
14
+ class_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad', 'Surprise']
15
+ IMG_SIZE = (48, 48)
16
+ detector = MTCNN()
17
+
18
+ def detect_and_classify(frame):
19
+ faces = detector.detect_faces(frame)
20
+ top_emotions = [("No Face Detected", 0)] if not faces else []
21
+
22
+ for face in faces:
23
+ x, y, w, h = face['box']
24
+ x, y = max(0, x), max(0, y)
25
+ cropped_face = frame[y:y+h, x:x+w]
26
+
27
+ if cropped_face.shape[0] > 0 and cropped_face.shape[1] > 0:
28
+ face_rgb = cv2.resize(cropped_face, IMG_SIZE)
29
+ face_array = tensorflow.keras.preprocessing.image.img_to_array(face_rgb) / 255.0
30
+ face_array = np.expand_dims(face_array, axis=0)
31
+
32
+ predictions = model.predict(face_array)[0]
33
+ top_indices = np.argsort(predictions)[-3:][::-1]
34
+ top_emotions = [(class_labels[i], round(predictions[i] * 100, 2)) for i in top_indices]
35
+
36
+ return top_emotions
37
+
38
+ @app.route('/')
39
+ def index():
40
+ return render_template('index.html', top_emotions=None, img_base64=None, initial_image=True)
41
+
42
+ @app.route('/classify', methods=['POST'])
43
+ def classify_image():
44
+ image = request.files['image']
45
+ img = Image.open(image)
46
+ img = np.array(img)
47
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
48
+ top_emotions = detect_and_classify(img)
49
+
50
+ _, buffer = cv2.imencode('.png', img)
51
+ img_base64 = base64.b64encode(buffer).decode('utf-8')
52
+
53
+ return render_template('index.html', top_emotions=top_emotions, img_base64=img_base64, initial_image=False)
54
+
55
+ @app.route('/process_frame', methods=['POST'])
56
+ def process_frame():
57
+ """Receives base64-encoded video frame, processes it, and returns emotions."""
58
+ data = request.json
59
+ frame_data = data.get('frame', '')
60
+
61
+ if not frame_data:
62
+ return jsonify({"error": "No frame received"}), 400
63
+
64
+ # Convert base64 to image
65
+ img_data = base64.b64decode(frame_data.split(',')[1])
66
+ img = Image.open(BytesIO(img_data))
67
+ img = np.array(img)
68
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
69
+
70
+ top_emotions = detect_and_classify(img)
71
+ return jsonify({"emotions": top_emotions})
72
+
73
+ if __name__ == '__main__':
74
+ app.run(debug=True)