<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samiksha Patil on Medium]]></title>
        <description><![CDATA[Stories by Samiksha Patil on Medium]]></description>
        <link>https://medium.com/@samikshapatil486?source=rss-15716f2acb6e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qZ-Wx_LEZMrG0HtR</url>
            <title>Stories by Samiksha Patil on Medium</title>
            <link>https://medium.com/@samikshapatil486?source=rss-15716f2acb6e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:30:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samikshapatil486/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Can Your Camera Tell if You’re Bored in Class?]]></title>
            <link>https://medium.com/@samikshapatil486/can-your-camera-tell-if-youre-bored-in-class-bfece6871e58?source=rss-15716f2acb6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfece6871e58</guid>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[emotion-recognition]]></category>
            <category><![CDATA[mediapipe]]></category>
            <category><![CDATA[facial-emotion-detection]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Samiksha Patil]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 10:10:51 GMT</pubDate>
            <atom:updated>2025-10-15T21:07:58.883Z</atom:updated>
            <content:encoded><![CDATA[<h3>Can Your Camera Tell if You’re Bored in Class? An Introduction to Facial Emotion Recognition using MediaPipe</h3><p>What if your camera could sense your boredom and instantly slap on a filter that makes you look laser-focused?</p><p>How cool would it be to have a camera that always covers for you?</p><p>Wait, but how can it decipher what’s going on in your mind? How can a machine understand your emotions from your face?</p><p>The answer lies in the incredible world of Computer Vision(CV). It’s a field of AI that allows machines to “see” and “understand” the world as we do. <br>From the Face ID unlocking your phone to the perfectly placed Snapchat filters, CV is everywhere. It’s the reason your camera takes a selfie when you show your palm and the reason you can search for something through images.</p><p>Are you already thinking about the long lines of code and the complicated math involved in building something like this? Or maybe you’re someone with minimal coding experience, daring to step into the world of CV but worried you’ll drown in complexity? Worry not, dear friends, Google’s MediaPipe has come to the rescue!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nu6JsCvcJghI3FJME9CU5g.jpeg" /></figure><p>MediaPipe is an open-source framework that brings machine learning directly to your device. No PhD required, no supercomputers needed, no cloud servers sending your face data to mysterious locations.<br>It’s very lightweight, and it comes with pre-trained models that don’t require you to collect thousands of face images or train for hours. Import the library, write a few lines of code, and you’re tracking faces.</p><p>At the heart of MediaPipe’s emotion detection is Face Mesh, a solution that detects 468 3D facial landmarks in real-time. It’s like a 3D graph capturing all your facial features and plotting them as points. Tracking how these 468 points move relative to each other creates a mathematical representation of your expressions.</p><p>So how exactly does it work?</p><h4>Your Tour Guide: (Index)</h4><p>· <a href="#fac9">Stage 1:</a><br> ∘ <a href="#62ba">Step 1: Cut the nonsense.</a><br> ∘ <a href="#53e1">Step 2: Map the terrain.</a><br>· <a href="#3fe0">Stage 2: Normalization</a><br> ∘ <a href="#264f">Procrustes Analysis </a><br>· <a href="#28bf">Stage 3: Feature Extraction</a><br> ∘ <a href="#db94">Approach 1: Geometric Feature Engineering (The Ruler Method) </a><br> ∘ <a href="#ceaa">Approach 2: Deep Learning on Raw Coordinates (The AI Method)</a><br> ∘ <a href="#b6af">Approach 3: Blendshape Scores (MediaPipe’s built-in cheat codes) </a><br>· <a href="#0635">Stage 4: The Classifier</a><br> ∘ <a href="#d1be">Option #1: Traditional ML (Random Forest or SVM)</a><br> ∘ <a href="#a350">Option #2: Deep Learning (CNN, GNN, MLP)</a><br>· <a href="#a647">Final Pipeline</a><br>· <a href="#663c">Try it Yourself!</a></p><h3>Stage 1:</h3><h4><strong>Step 1: Cut the nonsense.</strong></h4><p>It scans the entire image looking for a face and marks the face. This drastically reduces the unnecessary processing of the background elements.</p><h4><strong>Step 2: Map the terrain.</strong></h4><p>Now that it has a cropped face region, it places 468 precise 3D points across your entire facial surface — nose tip, eyebrow corners, lip edges, everything. Think of it like a cartographer mapping every hill and valley on a small island, but the island is your face and the map is built in milliseconds.</p><p>Each point has three coordinates (x, y, z). The z coordinate denotes the depth. These points are not random, they’re mathematically derived, not pixel-dependent and therefore strategic. But why 468 points? Because emotions are <em>subtle</em>! A real smile vs. a fake smile? That’s a difference of maybe 2–3 millimeters in how your cheek muscles lift. More dots = more precision.</p><h3>Stage 2: Normalization</h3><p><em>Raw coordinates are sensitive to head pose and camera distance.</em></p><p>Imagine taking photos of 100 different people, but:</p><ul><li>Some are selfies (close-up)</li><li>Some are taken from across the room (far away)</li><li>Some people are tilting their heads</li></ul><p>So what do we do in this case?</p><h4><strong>Procrustes Analysis</strong></h4><p>It is the automatic tool that:</p><p>1. Rotates all faces to the same upright angle<br> 2. Scales them to the same size<br> 3. Aligns them to the same center point</p><p>This is done using a transformation matrix (rotation + scale + translation).</p><p>Now every face is in the same “pose” and you can fairly compare the actual facial expressions.<br>By normalizing the position early, the neural network doesn’t have to learn “what if the face is tilted? what if they’re far away? What if…” Instead, it gets a consistently framed face every time and can dedicate all its brain power to precision.</p><p>Here’s the best part: You don’t need to store or transmit the actual image!<br>What gets saved: 468 points × 3 coordinates = 1,404 numbers<br>What gets deleted: The actual photo of your face.</p><h3>Stage 3: Feature Extraction</h3><p>Once you have 468 points, how do you detect emotions?</p><p>First, we extract the features that we want to analyze.</p><blockquote><strong>Without feature extraction:</strong></blockquote><blockquote>Computer<strong>:</strong> “I see coordinates (0.234, 0.567, 0.012)… no idea what that means for emotions ”</blockquote><blockquote><strong>With feature extraction:</strong></blockquote><blockquote>Computer<strong>:</strong> “smile_score = 0.92, which is highly positive, so this is probably happiness!”</blockquote><h4><strong>Approach 1: Geometric Feature Engineering (The Ruler Method) :</strong></h4><p>This is involves manually defining the measurements based on domain knowledge (like FACS — Facial Action Coding System). Instead of saying “she looks sad,” FACS breaks down EVERY facial expression into tiny, individual muscle movements called Action Units (AUs). Emotions aren’t single movements — they’re combinations of AUs!</p><p>Though you cannot calculate random distances (like for instance the distance between your left ear and right nostril) and label it as an emotion. Garbage features that don’t correlate with emotions. You need to choose the right features and hence, domain knowledge is required.</p><p>This method is very tedious and cannot detect texture-based expressions (like forehead wrinkles for brow lowering).</p><h4><strong>Approach 2: Deep Learning on Raw Coordinates (The AI Method):</strong></h4><p>In this method you feed all 468 × 3 = 1,404 coordinates directly into a neural network and let it figure out the patterns.</p><p>This uses calculation of <strong>Difference Vector (Δ)</strong> = <strong>Emotional Face</strong> — <strong>Neutral Face.</strong></p><blockquote>Capture your “neutral resting face” → Coordinates A <br>Capture your “peak emotional face” → Coordinates B<br>Calculate: Δ = B — A (the change)</blockquote><p>Or you can this of it like this:</p><blockquote>Δ = (Identity + Expression) — (Identity + Neutral)<br>Δ = Expression — Neutral<br>Δ = Pure Expression!</blockquote><p>This Δ vector contains ONLY the emotional deformation, removing your unique facial structure.</p><p>By subtracting away the neutral face, you’re essentially saying:</p><p>“I don’t care what you look like normally. I only care about HOW YOUR FACE CHANGED.”<br>And since everyone’s face changes in similar ways when feeling the same emotion (smile → corners go up), the difference vectors capture the universal pattern of emotion while ignoring the unique structure of each face.</p><h4><strong>Approach 3: Blendshape Scores (MediaPipe’s built-in cheat codes):</strong></h4><p>Using MediaPipe’s built-in semantic outputs instead of raw coordinates, we can speed up our processing.<br>Think of blendshapes as MediaPipe saying, “I’ve already done the hard work for you!”<br>Instead of manually measuring distances or training a neural network from scratch, MediaPipe gives you 52 pre-calculated blendshape scores. These are basically emotion coefficients that tell you exactly how much of each facial expression is present.</p><p>Examples:</p><p><em>mouthSmileLeft: 0.0 (not smiling) → 1.0 (full smile)<br>eyeBlinkLeft: 0.0 (wide open) → 1.0 (completely closed)<br>browDownLeft: 0.0 (neutral) → 1.0 (angry furrowing)</em></p><p>Why are they genius?<br>MediaPipe’s pre-trained model has already learned what “raising your eyebrows” looks like across millions of faces. You don’t need to:</p><ol><li>Calculate angles between landmarks</li><li>Build the difference vectors</li><li>Train your own neural network</li></ol><p>You just read the score and interpret it!</p><h3>Stage 4: The Classifier</h3><p>Once you’ve extracted features, you need something to say “these features = happiness!”</p><h4><strong>Option #1: Traditional ML (Random Forest or SVM):</strong></h4><p>What it is: Classic machine learning algorithms that learn decision rules</p><p>How it works:<br>1.<strong> Random Forest</strong>: Learns human-readable rules through repeated yes/no questions (builds decision trees)<br> Asks sequential questions → votes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUk1rkM9fNsWlF494AiUOg.png" /></figure><p>2. <strong>SVM</strong>: Learns mathematical boundaries that separate emotion clusters in space.</p><p>Plots position → finds nearest boundary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FS88wWruvkNnz_3c_3E7Nw.png" /></figure><p>Prediction for X: 😊 HAPPINESS</p><h4><strong>Option #2: Deep Learning (CNN, GNN, MLP):</strong></h4><p>What it is: Neural networks that learn complex patterns automatically.</p><p>Types:</p><ol><li>CNN (Convolutional Neural Network): Good for spatial patterns in coordinate grids.</li><li>GNN (Graph Neural Network): Perfect for facial landmarks (they’re literally a graph of connected points!)</li><li>MLP (Multi-Layer Perceptron): A Simple neural network for vector data.</li></ol><p>Implementation: Use individually or combine based on your needs (e.g., GNN for facial structure + MLP for final classification).</p><h3>Final Pipeline:</h3><p>To sum it all up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zY2bdMSqDz0aroh1UCHnAw.png" /></figure><h3>Try it Yourself!</h3><p>Now that you’ve understood how the architecture works, let’s use it in a program.</p><p>Installation:</p><pre>#for Terminal or Command prompt:<br>pip install mediapipe opencv-python numpy<br>#for Jupyter notebook users, use the command below<br>!pip install mediapipe opencv-python matplotlib numpy</pre><p>Imports:</p><pre>import time<br>import cv2  # OpenCV - the camera/image boss<br>import numpy as np  # NumPy - math wizard for calculations<br>import mediapipe as mp  # MediaPipe - Google&#39;s magical face detector</pre><p>Load your weapons:</p><pre>mp_drawing = mp.solutions.drawing_utils  # Draws pretty landmarks on faces<br>mp_pose = mp.solutions.pose  # Detects body pose (shoulders, arms, etc.)<br>mp_face_mesh = mp.solutions.face_mesh  # The star of the show - detects 468 face points!</pre><h4>The get_landmark_coords function:</h4><p>Converts MediaPipe’s weird 0–1 coordinates into actual pixel positions.</p><pre>def get_landmark_coords(landmarks, landmark_index, img_shape):<br>    h, w, _ = img_shape # Get image height, width (&#39;_&#39; means ignore color channels)<br>    lm = landmarks.landmark[landmark_index]  # Grab the specific landmark point<br>    return (lm.x * w, lm.y * h) # MediaPipe gives fractions, multiply by dimensions to get real pixel coordinates</pre><h4>The detect_emotion function:</h4><p>The emotion detective! Analyzes face geometry to guess what you’re feeling.</p><pre>def detect_emotion(face_landmarks, img_shape):<br>    # STEP 1: Grab the mouth landmarks (we need these for EVERY emotion)<br>    upper_lip = get_landmark_coords(face_landmarks, 13, img_shape)  # Top of mouth<br>    lower_lip = get_landmark_coords(face_landmarks, 14, img_shape)  # Bottom of mouth<br>    left_mouth_corner = get_landmark_coords(face_landmarks, 61, img_shape)  # Left smile corner<br>    right_mouth_corner = get_landmark_coords(face_landmarks, 291, img_shape)  # Right smile corner<br>    <br>    # STEP 2: Calculate inter-ocular distance <br>    # Why? Because everyone&#39;s face is different sizes, but proportions stay similar<br>    left_eye_inner = get_landmark_coords(face_landmarks, 133, img_shape)  # Inner corner of left eye<br>    right_eye_inner = get_landmark_coords(face_landmarks, 362, img_shape)  # Inner corner of right eye<br>    # np.linalg.norm = fancy math speak for &quot;distance between two points&quot;<br>    inter_ocular_distance = np.linalg.norm(np.array(left_eye_inner) - np.array(right_eye_inner))<br>    <br>    # Safety check: if eyes aren&#39;t detected properly, bail out gracefully<br>    if inter_ocular_distance == 0:<br>        return &quot;Neutral&quot;  # Can&#39;t measure without a ruler!<br><br>    # STEP 3: Calculate normalized mouth features<br>    # Dividing by inter_ocular_distance makes it work for all face sizes (tiny baby or giant adult!)<br>    mouth_openness = np.linalg.norm(np.array(upper_lip) - np.array(lower_lip)) / inter_ocular_distance<br>    mouth_width = np.linalg.norm(np.array(left_mouth_corner) - np.array(right_mouth_corner)) / inter_ocular_distance<br>    <br>    # STEP 4: Check for SURPRISE 😲<br>    # Rule: Big open mouth + eyebrows way up = &quot;OMG WHAT?!&quot;<br>    left_eyebrow_top = get_landmark_coords(face_landmarks, 105, img_shape)  # Top of left eyebrow<br>    left_eye_top = get_landmark_coords(face_landmarks, 159, img_shape)  # Top of left eye<br>    eyebrow_raise = (left_eye_top[1] - left_eyebrow_top[1]) / inter_ocular_distance  # How far up are the brows?<br>    if mouth_openness &gt; 0.4 and eyebrow_raise &gt; 0.2:  # Both conditions must be true!<br>        return &quot;Surprise&quot;<br><br>    # STEP 5: Check for FEAR 😨<br>    # Rule: Wide open eyes + moderately open mouth = &quot;RUN AWAY!&quot;<br>    left_eyelid_upper = get_landmark_coords(face_landmarks, 159, img_shape)  # Top eyelid<br>    left_eyelid_lower = get_landmark_coords(face_landmarks, 145, img_shape)  # Bottom eyelid<br>    left_eye_openness = np.linalg.norm(np.array(left_eyelid_upper) - np.array(left_eyelid_lower)) / inter_ocular_distance<br>    if left_eye_openness &gt; 0.2 and mouth_openness &gt; 0.3:  # Eyes wide + mouth open<br>        return &quot;Fear&quot;<br><br>    # STEP 6: Check for DISGUST 🤢<br>    # Rule: Nose wrinkled up toward face + mouth barely open = &quot;Eww, gross!&quot;<br>    upper_lip_y = get_landmark_coords(face_landmarks, 13, img_shape)[1]  # Y-coordinate of upper lip<br>    nose_tip_y = get_landmark_coords(face_landmarks, 4, img_shape)[1]  # Y-coordinate of nose tip<br>    disgust_score = (nose_tip_y - upper_lip_y) / inter_ocular_distance  # Distance between nose and lip<br>    if disgust_score &gt; 0.15 and mouth_openness &lt; 0.1:  # Wrinkled nose + closed mouth<br>        return &quot;Disgust&quot;<br><br>    # STEP 7: Check for ANGER 😠<br>    # Rule: Eyebrows squeezed together (furrow) + mouth corners down = &quot;Grr!&quot;<br>    left_inner_eyebrow = get_landmark_coords(face_landmarks, 55, img_shape)  # Inner part of left brow<br>    right_inner_eyebrow = get_landmark_coords(face_landmarks, 285, img_shape)  # Inner part of right brow<br>    eyebrow_furrow = np.linalg.norm(np.array(left_inner_eyebrow) - np.array(right_inner_eyebrow)) / inter_ocular_distance<br>    <br>    # Calculate if mouth is turning down (frown direction)<br>    mouth_corners_y = (left_mouth_corner[1] + right_mouth_corner[1]) / 2  # Average Y of corners<br>    mouth_center_y = (upper_lip[1] + lower_lip[1]) / 2  # Average Y of lip center<br>    mouth_downturn = (mouth_corners_y - mouth_center_y) / inter_ocular_distance  # Positive = frown<br>    <br>    if eyebrow_furrow &lt; 0.3 and mouth_downturn &gt; 0.05:  # Brows close together + frown<br>        return &quot;Anger&quot;<br><br>    # STEP 8: Check for HAPPINESS 😊 or SADNESS 😢<br>    # The smile test! It&#39;s all about whether mouth corners are higher or lower than center<br>    smile_score = (mouth_center_y - mouth_corners_y) / inter_ocular_distance<br>    # Positive score = corners are UP (smile!), Negative = corners are DOWN (sad!)<br>    <br>    if smile_score &gt; 0.05:  # Mouth corners higher than center = YOU&#39;RE SMILING!<br>        return &quot;Happiness&quot;<br>    if smile_score &lt; -0.05:  # Mouth corners lower than center = big sad :(<br>        return &quot;Sadness&quot;<br><br>    # STEP 9: If nothing else triggered, you&#39;ve got a perfect poker face<br>    return &quot;Neutral&quot;</pre><h4>The main() function:</h4><p>Where execution begins.</p><pre>def main():<br>   <br>    # Tell the program which image to analyze (CHANGE THIS to your actual image!)<br>    image_path = &quot;your_image.jpg&quot;<br>    frame = cv2.imread(image_path)  # cv2.imread = &quot;hey OpenCV, load this image file&quot;<br><br>    # Error handling: Did the image actually load, or did we get nothing?<br>    if frame is None:<br>        print(f&quot;Error: Could not read the image from {image_path}&quot;)<br>        return  # Exit gracefully instead of crashing<br><br>    # Initialize MediaPipe models (these are the AI brains!)<br>    # static_image_mode=True = &quot;this is a photo, not a video&quot;<br>    # min_detection_confidence=0.5 = &quot;only detect if you&#39;re at least 50% sure&quot;<br>    pose = mp_pose.Pose(static_image_mode=True, min_detection_confidence=0.5, min_tracking_confidence=0.5)<br>    face_mesh = mp_face_mesh.FaceMesh(static_image_mode=True, max_num_faces=1, min_detection_confidence=0.5, min_tracking_confidence=0.5)<br><br>    try:<br>        # Convert image from BGR to RGB (OpenCV uses BGR, MediaPipe uses RGB - why? ¯\_(ツ)_/¯)<br>        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>        <br>        # ACTION TIME! Run the AI models - this is where the magic happens<br>        results_pose = pose.process(rgb)  # Detect body: shoulders, elbows, hips, etc.<br>        results_face = face_mesh.process(rgb)  # Detect face: all 468 landmarks!<br><br>        emotion = &quot;Neutral&quot;  # Default emotion if no face is found<br><br>        # If MediaPipe found a face, let&#39;s draw it and detect emotion!<br>        if results_face.multi_face_landmarks:<br>            for face_landmarks in results_face.multi_face_landmarks:  # Loop through all detected faces (usually just 1)<br>                # Draw the face mesh - those fancy interconnected dots and lines<br>                mp_drawing.draw_landmarks(<br>                    image=frame,  # Draw on this image<br>                    landmark_list=face_landmarks,  # These are the 468 points<br>                    connections=mp_face_mesh.FACEMESH_TESSELATION,  # Connect the dots!<br>                    landmark_drawing_spec=None,  # Don&#39;t draw the dots themselves<br>                    connection_drawing_spec=mp_drawing.DrawingSpec(color=(200,200,200), thickness=1, circle_radius=1)  # Gray lines<br>                )<br>                <br>                # Now run our emotion detection magic!<br>                emotion = detect_emotion(face_landmarks, frame.shape)<br><br>        # If MediaPipe found a body pose, draw the skeleton too!<br>        if results_pose.pose_landmarks:<br>            mp_drawing.draw_landmarks(<br>                frame,  # Draw on this image<br>                results_pose.pose_landmarks,  # Body joint positions<br>                mp_pose.POSE_CONNECTIONS,  # Connect shoulders to elbows, etc.<br>                mp_drawing.DrawingSpec(color=(0, 255, 0), thickness=2, circle_radius=3),  # Green dots for joints<br>                mp_drawing.DrawingSpec(color=(0, 128, 255), thickness=2)  # Orange lines connecting joints<br>            )<br><br>        # Add text overlay showing the detected emotion (top-left corner)<br>        # Parameters: image, text, position, font, size, color (BGR!), thickness, anti-aliasing<br>        cv2.putText(frame, f&quot;Emotion: {emotion}&quot;, (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)<br><br>        # Display the final masterpiece in a window<br>        cv2.imshow(&quot;Emotion Detection&quot;, frame)  # Show the image<br>        cv2.waitKey(0)  # Wait forever until you press ANY key (then close)<br>        <br>    finally:<br>        # Clean up properly - close models and windows (like washing dishes after cooking!)<br>        pose.close()  # Release the pose model from memory<br>        face_mesh.close()  # Release the face mesh model from memory<br>        cv2.destroyAllWindows()  # Close all OpenCV windows</pre><p>And lastly, the Python tradition: only run main() if this script is executed directly (not imported)</p><pre>if __name__ == &quot;__main__&quot;:<br>    main()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*3HoO5N9SaCRSykdYPV397w.png" /></figure><p>You can download and run this code for live video capture as well as static images from this <a href="https://github.com/samikshapatil08/CV_mediapipe_blog">GitHub link.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfece6871e58" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>