File size: 6,343 Bytes
e5a1544
 
 
 
 
d4ac8c5
e5a1544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ac8c5
 
 
e5a1544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ac8c5
e5a1544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ac8c5
e5a1544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ac8c5
e5a1544
4d52ef2
d4ac8c5
 
 
e5a1544
d4ac8c5
 
 
 
 
 
 
 
 
e5a1544
d4ac8c5
4d52ef2
e5a1544
d4ac8c5
e5a1544
 
 
 
 
d4ac8c5
e5a1544
 
 
 
 
 
 
d4ac8c5
 
e5a1544
 
 
 
 
 
d4ac8c5
e5a1544
 
 
 
 
 
4d52ef2
 
e5a1544
 
4d52ef2
e5a1544
 
 
 
 
 
 
 
 
 
 
 
 
 
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import gradio as gr
import cv2
import numpy as np
import torch
from torchvision import models, transforms
from torchvision.models.detection import FasterRCNN_ResNet50_FPN_Weights
from PIL import Image
import mediapipe as mp
from fer import FER  # Facial emotion recognition

# -----------------------------
# Initialize Models and Helpers
# -----------------------------

# MediaPipe Pose for posture analysis
mp_pose = mp.solutions.pose
pose = mp_pose.Pose()
mp_drawing = mp.solutions.drawing_utils

# MediaPipe Face Detection for face detection
mp_face_detection = mp.solutions.face_detection
face_detection = mp_face_detection.FaceDetection(min_detection_confidence=0.5)

# Object Detection Model: Faster R-CNN (pretrained on COCO)
object_detection_model = models.detection.fasterrcnn_resnet50_fpn(
    weights=FasterRCNN_ResNet50_FPN_Weights.DEFAULT
)
object_detection_model.eval()
obj_transform = transforms.Compose([transforms.ToTensor()])

# Facial Emotion Detection using FER (this model will detect emotions from a face)
emotion_detector = FER(mtcnn=True)

# -----------------------------
# Define Analysis Functions
# -----------------------------

def analyze_posture(frame_rgb, output_frame):
    """Runs pose estimation and draws landmarks on the frame."""
    pose_results = pose.process(frame_rgb)
    posture_text = "No posture detected"
    if pose_results.pose_landmarks:
        posture_text = "Posture detected"
        # Draw the pose landmarks on the output image
        mp_drawing.draw_landmarks(
            output_frame, pose_results.pose_landmarks, mp_pose.POSE_CONNECTIONS,
            mp_drawing.DrawingSpec(color=(0, 255, 0), thickness=2, circle_radius=2),
            mp_drawing.DrawingSpec(color=(0, 0, 255), thickness=2)
        )
    return posture_text

def analyze_emotion(frame):
    """Detects emotion from faces using FER. Returns the dominant emotion."""
    # FER expects RGB images
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    emotions = emotion_detector.detect_emotions(frame_rgb)
    if emotions:
        # Use the first detected face and its top emotion
        top_emotion, score = max(emotions[0]["emotions"].items(), key=lambda x: x[1])
        emotion_text = f"{top_emotion} ({score:.2f})"
    else:
        emotion_text = "No face detected for emotion analysis"
    return emotion_text

def analyze_objects(frame_rgb, output_frame):
    """Performs object detection and draws bounding boxes for detections above a threshold."""
    image_pil = Image.fromarray(frame_rgb)
    img_tensor = obj_transform(image_pil)
    with torch.no_grad():
        detections = object_detection_model([img_tensor])[0]
    
    threshold = 0.8
    detected_boxes = detections["boxes"][detections["scores"] > threshold]
    for box in detected_boxes:
        box = box.int().cpu().numpy()
        cv2.rectangle(output_frame, (box[0], box[1]), (box[2], box[3]), (255, 255, 0), 2)
    object_text = f"Detected {len(detected_boxes)} object(s)" if len(detected_boxes) else "No objects detected"
    return object_text

def analyze_faces(frame_rgb, output_frame):
    """Detects faces using MediaPipe and draws bounding boxes."""
    face_results = face_detection.process(frame_rgb)
    face_text = "No faces detected"
    if face_results.detections:
        face_text = f"Detected {len(face_results.detections)} face(s)"
        h, w, _ = output_frame.shape
        for detection in face_results.detections:
            bbox = detection.location_data.relative_bounding_box
            x = int(bbox.xmin * w)
            y = int(bbox.ymin * h)
            box_w = int(bbox.width * w)
            box_h = int(bbox.height * h)
            cv2.rectangle(output_frame, (x, y), (x + box_w, y + box_h), (0, 0, 255), 2)
    return face_text

# -----------------------------
# Main Analysis Function
# -----------------------------

def analyze_webcam(video_path):
    """
    Receives a video file (captured from the webcam), extracts one frame,
    then runs posture analysis, facial emotion detection, object detection,
    and face detection on that frame.
    Returns an annotated image and a textual summary.
    """
    # Open the video file (the webcam stream is saved as a temporary file)
    cap = cv2.VideoCapture(video_path)
    success, frame = cap.read()
    cap.release()
    
    if not success:
        return None, "Could not read a frame from the video."
    
    # Create a copy for drawing annotations
    output_frame = frame.copy()
    
    # Convert frame to RGB for some analyses
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    
    # Run analyses
    posture_result = analyze_posture(frame_rgb, output_frame)
    emotion_result = analyze_emotion(frame)
    object_result = analyze_objects(frame_rgb, output_frame)
    face_result = analyze_faces(frame_rgb, output_frame)
    
    # Compose the result summary text
    summary = (
        f"Posture Analysis: {posture_result}\n"
        f"Emotion Analysis: {emotion_result}\n"
        f"Object Detection: {object_result}\n"
        f"Face Detection: {face_result}"
    )
    
    # Optionally, overlay some summary text on the image
    cv2.putText(output_frame, f"Emotion: {emotion_result}", (10, 30),
                cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
    cv2.putText(output_frame, f"Objects: {object_result}", (10, 70),
                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
    cv2.putText(output_frame, f"Faces: {face_result}", (10, 110),
                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
    
    return output_frame, summary

# -----------------------------
# Gradio Interface Setup
# -----------------------------

# Note: In the current version of Gradio, the Video component does not accept a 'source' argument.
# Remove the 'source' parameter. Streaming is still enabled.
interface = gr.Interface(
    fn=analyze_webcam,
    inputs=gr.Video(streaming=True, label="Webcam Feed"),
    outputs=[
        gr.Image(type="numpy", label="Annotated Output"),
        gr.Textbox(label="Analysis Summary")
    ],
    title="Real-Time Multi-Analysis App",
    description=(
        "This app performs real-time posture analysis, facial emotion detection, "
        "object detection, and face detection using your webcam."
    ),
    live=True
)

if __name__ == "__main__":
    interface.launch()