SoFunction
Updated on 2025-05-16

Python image processing article opencv realizes sitting posture detection

Preface

Sitting position detection isComputer VisionOne application can be analyzedHuman postureTo determine whether to maintainCorrect sitting posture. Below I will introduce the method and complete code to implement sitting posture detection using Python.

1. Method Overview

Using OpenCV and MediaPipe

Using OpenCV and MediaPipe: MediaPipe provides ready-made human pose estimation models

Key point detection

Key point detection: Detect key points of the body (such as shoulders, ears, buttocks, etc.)

Angle calculation

Angle calculation: calculate the angle between key points to judge the sitting posture

Posture Assessment

Pose evaluation: judge whether the sitting posture is correct based on the angle threshold

2. Complete code implementation

import cv2
import mediapipe as mp
import numpy as np
import time

class PostureDetector:
    def __init__(self, mode=False, upBody=False, smooth=True, 
                 detectionCon=0.5, trackCon=0.5):
        """
        Initialize the posture detector
        parameter:
            mode: Whether to static image mode (FalseIndicates video streaming)
            upBody: Is it possible to detect only the upper body?
            smooth: Whether to smooth the process
            detectionCon: Detection confidence threshold
            trackCon: Track confidence threshold
        """
         = mode
         = upBody
         = smooth
         = detectionCon
         = trackCon
        
         = .drawing_utils
         = 
         = (
            static_image_mode=,
            model_complexity=1,
            smooth_landmarks=,
            enable_segmentation=False,
            smooth_segmentation=,
            min_detection_confidence=,
            min_tracking_confidence=
        )
        
        #Sitting posture evaluation parameters        self.good_posture_time = 0
        self.bad_posture_time = 0
        self.posture_status = "Unknown"
        self.last_posture_change = ()
        
    def find_pose(self, img, draw=True):
        """
        Detecting key points of posture in images
        parameter:
            img: Enter an image (BGRFormat)
            draw: Whether to draw key points and connection lines
        return:
            Annotated image and pose key points
        """
        img_rgb = (img, cv2.COLOR_BGR2RGB)
         = (img_rgb)
        
        if .pose_landmarks and draw:
            .draw_landmarks(
                img, .pose_landmarks, 
                .POSE_CONNECTIONS)
        
        return img
    
    def get_landmarks(self, img):
        """
        Get coordinates for all pose key points
        parameter:
            img: Enter an image
        return:
            Key point coordinate list (x,y,z) or None
        """
         = []
        if .pose_landmarks:
            for id, lm in enumerate(.pose_landmarks.landmark):
                h, w, c = 
                cx, cy = int( * w), int( * h)
                ([id, cx, cy, ])
        return 
    
    def calculate_angle(self, a, b, c):
        """
        Calculate the angle between three points
        parameter:
            a, b, c: Coordinates of three points (x,y)
        return:
            angle (degrees)
        """
        a = (a)
        b = (b)
        c = (c)
        
        radians = np.arctan2(c[1]-b[1], c[0]-b[0]) - np.arctan2(a[1]-b[1], a[0]-b[0])
        angle = (radians * 180.0 / )
        
        if angle > 180.0:
            angle = 360 - angle
            
        return angle
    
    def evaluate_posture(self, img, draw=True):
        """
         Assess the correct sitting posture
         parameter:
             img: Enter image
             draw: Whether to draw the evaluation result on the image
         return:
             Image and sitting position evaluation results
         """
        current_time = ()
        posture_changed = False
        
        if not  or len() < 33:
            return img, "No person detected"
        
        # Get the required link        left_shoulder = [11][1:3]  #11: Left shoulder        right_shoulder = [12][1:3]  #12: Right shoulder        left_ear = [7][1:3]  #7: Left ear        right_ear = [8][1:3]  #8: Right ear        left_hip = [23][1:3]  #23: Left Hip        right_hip = [24][1:3]  # 24: Right hip        
        # Calculate the midpoint of the shoulder        shoulder_mid = (
            (left_shoulder[0] + right_shoulder[0]) // 2,
            (left_shoulder[1] + right_shoulder[1]) // 2
        )
        
        # Calculate the midpoint of the ear        ear_mid = (
            (left_ear[0] + right_ear[0]) // 2,
            (left_ear[1] + right_ear[1]) // 2
        )
        
        # Calculate the hip midpoint        hip_mid = (
            (left_hip[0] + right_hip[0]) // 2,
            (left_hip[1] + right_hip[1]) // 2
        )
        
        # Calculate the spine angle (shoulder-hip-vertical line)        spine_angle = self.calculate_angle(
            (shoulder_mid[0], shoulder_mid[1] - 100),  # a little above the shoulder            shoulder_mid,
            hip_mid
        )
        
        # Calculate the neck angle (ears-shoulders-horizontal line)        neck_angle = self.calculate_angle(
            (ear_mid[0] - 100, ear_mid[1]),
            ear_mid,
            shoulder_mid
        )
        
        #Sitting posture evaluation criteria        good_spine = 160 < spine_angle < 200  # The spine should be close to vertical        good_neck = 70 < neck_angle < 110  # The neck should be close to vertical        
        # Judge sitting posture        new_status = "Good" if good_spine and good_neck else "Bad"
        
        # Update posture status time        if new_status != self.posture_status:
            posture_changed = True
            self.last_posture_change = current_time
            self.posture_status = new_status
        else:
            if new_status == "Good":
                self.good_posture_time += 1
            else:
                self.bad_posture_time += 1
        
        # Draw results on images        if draw:
            # Draw key points and connection lines            (img, ear_mid, 8, (255, 0, 0), )
            (img, shoulder_mid, 8, (255, 0, 0), )
            (img, hip_mid, 8, (255, 0, 0), )
            (img, ear_mid, shoulder_mid, (255, 0, 0), 3)
            (img, shoulder_mid, hip_mid, (255, 0, 0), 3)
            
            # Show angle information            (img, f"Spine Angle: {int(spine_angle)}", 
                        (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
            (img, f"Neck Angle: {int(neck_angle)}", 
                        (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
            
            # Show sitting posture            color = (0, 255, 0) if new_status == "Good" else (0, 0, 255)
            (img, f"Posture: {new_status}", 
                        (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2)
            
            # Show time statistics            (img, f"Good Time: {self.good_posture_time//10}s", 
                        (10, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
            (img, f"Bad Time: {self.bad_posture_time//10}s", 
                        (10, 140), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
            
            # If the posture is bad, add a warning            if new_status == "Bad":
                (img, "WARNING: Bad Posture!", 
                            ([1]//2 - 150, 30), 
                            cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        
        return img, new_status

def main():
    cap = (0)  # Use the camera    detector = PostureDetector()
    
    while True:
        success, img = ()
        if not success:
            break
            
        img = detector.find_pose(img)
        landmarks = detector.get_landmarks(img)
        
        if landmarks:
            img, posture = detector.evaluate_posture(img)
        
        ("Posture Detection", img)
        
        if (1) & 0xFF == ord('q'):
            break
    
    ()
    ()

if __name__ == "__main__":
    main()

3. Code description

PostureDetector class

PostureDetector class: core sitting posture detection class

find_pose()

find_pose(): Detect the imageHuman posture

get_landmarks()

get_landmarks(): GetPose key point coordinates

cakculate_angle()

calculate_angle(): CalculateAngle between the three key points

evaluate_posture()

evaluate_posture(): EvaluateIs the sitting posture correct?

Sitting posture evaluation criteria (parameter adjustments can be made):

The spine angle should be160-200 degreesBetween (nearly perpendicular)
The neck angle should be70-110 degreesBetween (nearly perpendicular)
It is judged as "Good" sitting posture if it meets the above conditions, otherwise it is "Bad"

Visualization function:

  • Draw key points and connection lines
  • Display angle value
  • Show sitting posture status and time statistics
  • Bad sitting postureShow warning when

How to use

Install the dependency library:

pip install opencv-python mediapipe numpy

Run the script:

python posture_detection.py

AdjustmentCamera location, make sure you can clearly see the upper body

4. Improvement direction

  • Add more evaluation criteria (such as whether the shoulder leans forward)
  • Realize sitting posture history and statistical analysis
  • Add sound reminder function
  • Optimize performance (such as reducing image resolution)
  • Add calibration function to suit different body types
    This implementation providesBasic sitting posture detection functionYou can furtherExtendedandComplete

Summarize

This is the article about opencv sitting posture detection in Python image processing. For more related content on Python opencv sitting posture detection, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!