The Wayback Machine - https://web.archive.org/web/20240615005440/https://www.geeksforgeeks.org/right-and-left-hand-detection-using-python/
Open In App

Right and Left Hand Detection Using Python

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to Detect Hands using Python.

We will use mediapipe and OpenCV libraries in python to detect the Right Hand and Left Hand. We will be using the Hands model from mediapipe solutions to detect hands, it is a palm detection model that operates on the full image and returns an oriented hand bounding box.

Required Libraries

  • Mediapipe is Google’s open-source framework, used for media processing. It is cross-platform or we can say it is platform friendly. It can run on Android, iOS, and the web that’s what Cross-platform means, to run everywhere.
  • OpenCV is a Python library that is designed to solve computer vision problems. OpenCV supports a wide variety of programming languages such as C++, Python, Java etc. Support for multiple platforms including Windows, Linux, and MacOS.

Installing required libraries

pip install mediapipe  
pip install opencv-python

Stepwise Implementation

Step 1: Import all required libraries

Python3




# Importing Libraries
import cv2
import mediapipe as mp
  
# Used to convert protobuf message 
# to a dictionary.
from google.protobuf.json_format import MessageToDict


Step 2: Initializing Hands model

Python3




# Initializing the Model
mpHands = mp.solutions.hands
hands = mpHands.Hands(
    static_image_mode=False,
    model_complexity=1,
    min_detection_confidence=0.75,
    min_tracking_confidence=0.75,
    max_num_hands=2)


Let us look into the parameters for the Hands Model:

Hands( static_image_mode=False, model_complexity=1 min_detection_confidence=0.75, min_tracking_confidence=0.75, max_num_hands=2 )

Where:

  • static_image_mode: It is used to specify whether the input image must be static images or as a video stream. The default value is False.
  • model_complexity: Complexity of the hand landmark model: 0 or 1. Landmark accuracy, as well as inference latency, generally go up with the model complexity. Default to 1.
  • min_detection_confidence: It is used to specify the minimum confidence value with which the detection from the person-detection model needs to be considered as successful. Can specify a value in [0.0,1.0]. The default value is 0.5.
  • min_tracking_confidence: It is used to specify the minimum confidence value with which the detection from the landmark-tracking model must be considered as successful. Can specify a value in [0.0,1.0]. The default value is 0.5.
  • max_num_hands: Maximum number of hands to detect. Default it is 2.

Step 3: Hands model process the image and detect hands

Capture the frames continuously from the camera using OpenCV and then Flip the image around y-axis i.e cv2.flip(image, flip code) and Convert BGR image to an RGB image and make predictions using initialized hands model.

Prediction made by the model is saved in the results variable from which we can access landmarks using results.multi_hand_landmarks, results.multi_handedness  respectively and If hands are present in the frame, check for both hands, if yes then put text “Both Hands” on the image else for a single hand, store MessageToDict() function on label variable. If the label is “Left” put text “Left  Hand”  on the image and if label is “Right” put text “Right Hand”  on the image.

Python3




# Start capturing video from webcam
cap = cv2.VideoCapture(0)
  
while True:
    
    # Read video frame by frame
    success, img = cap.read()
  
    # Flip the image(frame)
    img = cv2.flip(img, 1)
  
    # Convert BGR image to RGB image
    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  
    # Process the RGB image
    results = hands.process(imgRGB)
  
    # If hands are present in image(frame)
    if results.multi_hand_landmarks:
  
        # Both Hands are present in image(frame)
        if len(results.multi_handedness) == 2:
                # Display 'Both Hands' on the image
            cv2.putText(img, 'Both Hands', (250, 50),
                        cv2.FONT_HERSHEY_COMPLEX, 0.9,
                        (0, 255, 0), 2)
  
        # If any hand present
        else:
            for i in results.multi_handedness:
                
                # Return whether it is Right or Left Hand
                label = MessageToDict(i)[
                    'classification'][0]['label']
  
                if label == 'Left':
                    
                    # Display 'Left Hand' on left side of window
                    cv2.putText(img, label+' Hand', (20, 50),
                                cv2.FONT_HERSHEY_COMPLEX, 0.9,
                                (0, 255, 0), 2)
  
                if label == 'Right':
                    
                    # Display 'Left Hand' on left side of window
                    cv2.putText(img, label+' Hand', (460, 50),
                                cv2.FONT_HERSHEY_COMPLEX,
                                0.9, (0, 255, 0), 2)
  
    # Display Video and when 'q' is entered, destroy the window
    cv2.imshow('Image', img)
    if cv2.waitKey(1) & 0xff == ord('q'):
        break


Below is the complete implementation:

Python3




# Importing Libraries
import cv2
import mediapipe as mp
  
# Used to convert protobuf message to a dictionary.
from google.protobuf.json_format import MessageToDict
  
# Initializing the Model
mpHands = mp.solutions.hands
hands = mpHands.Hands(
    static_image_mode=False,
    model_complexity=1,
    min_detection_confidence=0.75,
    min_tracking_confidence=0.75,
    max_num_hands=2)
  
# Start capturing video from webcam
cap = cv2.VideoCapture(0)
  
while True:
    # Read video frame by frame
    success, img = cap.read()
  
    # Flip the image(frame)
    img = cv2.flip(img, 1)
  
    # Convert BGR image to RGB image
    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  
    # Process the RGB image
    results = hands.process(imgRGB)
  
    # If hands are present in image(frame)
    if results.multi_hand_landmarks:
  
        # Both Hands are present in image(frame)
        if len(results.multi_handedness) == 2:
                # Display 'Both Hands' on the image
            cv2.putText(img, 'Both Hands', (250, 50),
                        cv2.FONT_HERSHEY_COMPLEX,
                        0.9, (0, 255, 0), 2)
  
        # If any hand present
        else:
            for i in results.multi_handedness:
                
                # Return whether it is Right or Left Hand
                label = MessageToDict(i)
                ['classification'][0]['label']
  
                if label == 'Left':
                    
                    # Display 'Left Hand' on
                    # left side of window
                    cv2.putText(img, label+' Hand',
                                (20, 50),
                                cv2.FONT_HERSHEY_COMPLEX, 
                                0.9, (0, 255, 0), 2)
  
                if label == 'Right':
                      
                    # Display 'Left Hand'
                    # on left side of window
                    cv2.putText(img, label+' Hand', (460, 50),
                                cv2.FONT_HERSHEY_COMPLEX,
                                0.9, (0, 255, 0), 2)
  
    # Display Video and when 'q'
    # is entered, destroy the window
    cv2.imshow('Image', img)
    if cv2.waitKey(1) & 0xff == ord('q'):
        break


Output:

OUTPUT



Previous Article
Next Article

Similar Reads

Car driving using hand detection in Python
In this project, we are going to demonstrate how one can drive a car by just detecting hand gestures on the steering wheel. Let's say the requirement is something like this - If driver wants to start the car then put both of your hands on the steering wheel. If someone having no hands on a steering wheel that means brakes of car will be applied slo
3 min read
Brightness Control With Hand Detection using OpenCV in Python
In this article, we are going to make a Python project that uses OpenCV and Mediapipe to see hand gesture and accordingly set the brightness of the system from a range of 0-100. We have used a HandTracking module that tracks all points on the hand and detects hand landmarks, calculate the distance between thumb tip and index fingertip and maps the
6 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | Corner detection with Harris Corner Detection method using OpenCV
Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with fea
2 min read
Python | Corner Detection with Shi-Tomasi Corner Detection Method using OpenCV
What is a Corner? A corner can be interpreted as the junction of two edges (where an edge is a sudden change in image brightness). Shi-Tomasi Corner Detection - Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper 'Good Features to Track'. Here the basic intuition is that corners can be detected by looking for significant
3 min read
Convert Text Image to Hand Written Text Image using Python
In this article, we are going to see how to convert text images to handwritten text images using PyWhatkit, Pillow, and Tesseract in Python. Module needed: Pytesseract: Sometimes known as Python-tesseract, is a Python-based optical character recognition (OCR) program. It can read and recognize text in photos, license plates, and other documents. To
2 min read
Python - Right and Left Shift characters in String
Sometimes, while working with Python Strings, we can have problem in which we have both right and left rotate count of characters in String and would like to know the resultant condition of String. This type of problem occurs in competitive programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using String multipli
6 min read
Python Program to check if elements to the left and right of the pivot are smaller or greater respectively
Given a list and an index, the task is to write a Python program to first select the element at that index as the pivot element and then test if elements are greater to its right and smaller to its left or not. Examples: Input : test_list = [4, 3, 5, 6, 9, 16, 11, 10, 12], K = 4 Output : True Explanation : Elements at Kth index is 9, elements befor
3 min read
Python Pandas - Check if the interval is open on the left and right side
In pandas Interval.closed_left and Interval.closed_right attributes are used to check if the interval is open on left and right side. Intervals: Closed interval : closed ='both' represents closed interval. The closed interval contains its endpoints. it is of the form [a,b] and it has the condition a<=x<=b.Open interval: closed =' neither' rep
2 min read
Use different y-axes on the left and right of a Matplotlib plot
In this article, we are going to discuss how to create y-axes of both sides of a Matplotlib plot. Sometimes for quick data analysis, it is required to create a single graph having two data variables with different scales. For this purpose twin axes methods are used i.e. dual X or Y-axes. The matplotlib.axes.Axes.twinx() function in axes module of m
2 min read
Article Tags :
Practice Tags :