This is a Computer vision package that makes its easy to run Image processing and AI functions. At the core it uses OpenCV and Mediapipe libraries.

Overview

CVZone

This is a Computer vision package that makes its easy to run Image processing and AI functions. At the core it uses OpenCV and Mediapipe libraries.

Installation

You can simply use pip to install the latest version of cvzone.

pip install cvzone


60 FPS Face Detection


import cvzone
import cv2

cap = cv2.VideoCapture(0)
detector = cvzone.FaceDetector()

while True:
    success, img = cap.read()
    img, bboxs = detector.findFaces(img)
    print(bboxs)
    cv2.imshow("Image", img)
    cv2.waitKey(1)

Hand Tracking


Basic Code Example

import cvzone
import cv2

cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
detector = cvzone.HandDetector(detectionCon=0.5, maxHands=1)

while True:
    # Get image frame
    success, img = cap.read()

    # Find the hand and its landmarks
    img = detector.findHands(img)
    lmList, bbox = detector.findPosition(img)
    
    # Display
    cv2.imshow("Image", img)
    cv2.waitKey(1)

Finding How many finger are up

if lmList:
        # Find how many fingers are up
        fingers = detector.fingersUp()
        totalFingers = fingers.count(1)
        cv2.putText(img, f'Fingers:{totalFingers}', (bbox[0] + 200, bbox[1] - 30),
                    cv2.FONT_HERSHEY_PLAIN, 2, (0, 255, 0), 2)

Finding distace between two fingers

                 
if lmList:
        # Find Distance Between Two Fingers
        distance, img, info = detector.findDistance(8, 12, img)
        cv2.putText(img, f'Dist:{int(distance)}', (bbox[0] + 400, bbox[1] - 30),
                    cv2.FONT_HERSHEY_PLAIN, 2, (0, 255, 0), 2)

Find Hand Type - i.e. Left or Right

if lmList:
        # Find Hand Type
        myHandType = detector.handType()
        cv2.putText(img, f'Hand:{myHandType}', (bbox[0], bbox[1] - 30),
                    cv2.FONT_HERSHEY_PLAIN, 2, (0, 255, 0), 2)


Pose Estimation


import cvzone
import cv2

cap = cv2.VideoCapture(0)
detector = cvzone.PoseDetector()
while True:
    success, img = cap.read()
    img = detector.findPose(img)
    lmList = detector.findPosition(img, draw=False)
    if lmList:
        print(lmList[14])
        cv2.circle(img, (lmList[14][1], lmList[14][2]), 15, (0, 0, 255), cv2.FILLED)

    cv2.imshow("Image", img)
    cv2.waitKey(1)


Face Mesh Detection


import cvzone
import cv2

cap = cv2.VideoCapture(0)
detector = cvzone.FaceMeshDetector(maxFaces=2)
while True:
    success, img = cap.read()
    img, faces = detector.findFaceMesh(img)
    if faces:
        print(faces[0])
    cv2.imshow("Image", img)
    cv2.waitKey(1)

Stack Images


import cvzone
import cv2

cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)

while True:
    success, img = cap.read()
    imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    imgList = [img, img, imgGray, img, imgGray, img,imgGray, img, img]
    stackedImg = cvzone.stackImages(imgList, 3, 0.4)

    cv2.imshow("stackedImg", stackedImg)
    cv2.waitKey(1)


Corner Rectangle



import cvzone
import cv2

cap = cv2.VideoCapture(0)
detector = cvzone.HandDetector()

while True:
    # Get image frame
    success, img = cap.read()

    # Find the hand and its landmarks
    img = detector.findHands(img, draw=False)
    lmList, bbox = detector.findPosition(img, draw=False)
    if bbox:
        # Draw  Corner Rectangle
        cvzone.cornerRect(img, bbox)

    # Display
    cv2.imshow("Image", img)
    cv2.waitKey(1)

FPS


import cvzone
import cv2

fpsReader = cvzone.FPS()
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)

while True:
    success, img = cap.read()
    fps, img = fpsReader.update(img,pos=(50,80),color=(0,255,0),scale=5,thickness=5)
    cv2.imshow("Image", img)
    cv2.waitKey(1)
Comments
  • Problem with

    Problem with "no attribute findPosition"

    All packages are installed.

    pip list

    Package               Version
    --------------------- --------
    absl-py               0.13.0
    attrs                 21.2.0
    cvzone                1.5.0
    cycler                0.10.0
    evdev                 1.4.0
    kiwisolver            1.3.2
    matplotlib            3.4.3
    mediapipe             0.8.7.1
    numpy                 1.21.2
    opencv-contrib-python 4.5.3.56
    opencv-python         4.5.3.56
    Pillow                8.3.2
    pip                   21.2.4
    protobuf              3.17.3
    pynput                1.7.3
    pyparsing             2.4.7
    python-dateutil       2.8.2
    python-xlib           0.31
    setuptools            57.4.0
    six                   1.16.0
    wheel                 0.36.2
    

    I get code from your example.

    Error:

    Traceback (most recent call last):
      File "/var/www/examples/CornerRectangle.py", line 14, in <module>
        lmList, bbox = detector.findPosition(img, draw=False)
    AttributeError: 'HandDetector' object has no attribute 'findPosition'
    

    Then I try to install all this packages globally (without venv), and have the same error.

    Where is an error?

    opened by LeXxyIT 3
  • cvzone facedetector error: AttributeError: module 'mediapipe.python.solutions.face_mesh' has no attribute 'FACE_CONNECTIONS'

    cvzone facedetector error: AttributeError: module 'mediapipe.python.solutions.face_mesh' has no attribute 'FACE_CONNECTIONS'

    mediapipe renamed FACE_CONNECTIONS to FACEMESH_TESSELATION . please fixed it

    links: https://github.com/google/mediapipe/issues/2448 https://github.com/google/mediapipe/blob/master/docs/solutions/face_mesh.md#python-solution-api

    opened by zealotCE 2
  • Errors in all cvzone examples

    Errors in all cvzone examples

    I tried to test the FPS sample code in the documentation and I get the error below. I also tried all of the other examples but then all dont work for me. I am using macOS, python==3.9.5, opencv-python==4.5.2.54 and cvzone==1.5.6

      File "/Users/ UserName/Documents/testing_cvzone/testing.py", line 1, in <module>
        import cvzone
      File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/cvzone/__init__.py", line 1, in <module>
        from cvzone.Utils import stackImages, cornerRect, findContours,\
      File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/cvzone/Utils.py", line 7, in <module>
        import cv2
      File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/cv2/__init__.py", line 181, in <module>
        bootstrap()
      File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/cv2/__init__.py", line 175, in bootstrap
        if __load_extra_py_code_for_module("cv2", submodule, DEBUG):
      File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/cv2/__init__.py", line 28, in __load_extra_py_code_for_module
        py_module = importlib.import_module(module_name)
      File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/cv2/mat_wrapper/__init__.py", line 33, in <module>
        cv._registerMatType(Mat)
    AttributeError: partially initialized module 'cv2' has no attribute '_registerMatType' (most likely due to a circular import)
    

    What should I do to fix this?

    opened by vwallajabad 1
  • Added a flexible stabilizer for the HandTrackingModule -> findHands().

    Added a flexible stabilizer for the HandTrackingModule -> findHands().

    The hands always get some error/micro moves per frame even if the hand is stand still, so I added a method to eliminate it by using numpy's allclose() function and catching, a new parameter is added named "stabilizerVal" which indicates how many pixels should any of the hand points move to count as a hand movement.

    opened by AhmedAhmedEG 0
  • Update HandTrackingModule -> findDistance() to ignore z values automatically rather than raising an error

    Update HandTrackingModule -> findDistance() to ignore z values automatically rather than raising an error

    Every landmark was unpacked in only two variables, so giving a normal 3D landmark as input raises errors, so I just omitted the third input (the z value).

    opened by AhmedAhmedEG 0
  • [BUGFIX] FACE_CONNECTIONS no longer exists in mp

    [BUGFIX] FACE_CONNECTIONS no longer exists in mp

    FACE_CONNECTIONS no longer exists, I recommend using FACEMESH_CONTOURS to get the outlines of the face.

    https://github.com/google/mediapipe/blob/master/mediapipe/python/solutions/face_mesh_connections.py

    opened by erickthered 0
  • Update Utils.py

    Update Utils.py

    Draw text with blur or colour background

    Text Blur background Function

    This function simply calculates the size of input text and add crops the ROI, apply the blur to ROI, and merge with the image, draws text, on that region. It has one, a bug 🐛 since where crop region if text, can't go beyond image bounders, hance crash 😟 , how can I fix this? any suggestion ❤️

    Text Color background with opacity Function

    This function Calculate the size of input text and creates a colour background with transparency, draw a rectangle copy of img, and add the image back with the OpenCV function, addWeighted, to provide transparency.

    The output looks something like that.

    output

    It's my first ever contribution to any project, Sir your kind suggestion will help me a lot.

    opened by Asadullah-Dal17 0
  • AttributeError

    AttributeError

    Hi! I get that error " module 'cvzone' has no attribute 'SerialObject' ". And this is my code:

    import cvzone import cv2 from cvzone.HandTrackingModule import HandDetector

    cap = cv2.VideoCapture(1) #detector= cvzone.HandDetector(maxHands=1, detectionCon=0.7) detector = HandDetector(maxHands=1, detectionCon=0.7) mySerial = cvzone.SerialObject("COM3", 9600, 1)

    opened by MertOzgehan 0
  • Ignore the z value automatically rather than raising an error in PoseModule

    Ignore the z value automatically rather than raising an error in PoseModule

    Unpacking only two values from the points tuple forces the user to recreate a manipulated tuple before passing it to the function, ignoring the 3rd value by default makes the work flow more flexible.

    opened by taku0625 0
  • SerialModule.py - readLine() should be within try block.

    SerialModule.py - readLine() should be within try block.

    In SerialModule.py, in getData() line 67: the block of code containing the readLine() should be within a try block, maybe something like this (although there may be a better way):

        def getData(self):
            """
            :param numOfVals: number of vals to retrieve
            :return: list of data received
            """
            try:
                data = self.ser.readline()
                data = data.decode("utf-8")
                data = data.split('#')
                dataList = []
                [dataList.append(d) for d in data]
                return dataList[:-1]
            except Exception as e:
                print(e)
                self.ser.close
    

    See this question on Stack Exchange, Get data from Arduino in Python.

    opened by greenonline 0
  • Exception has occurred: ModuleNotFoundError

    Exception has occurred: ModuleNotFoundError

    Exception has occurred: ModuleNotFoundError No module named 'cvzone' File "C:\Users\Bella\Desktop\sign language\venv\test'.py", line 1, in from cvzone.HandTrackingModule import HandDetector

    hi! i have already installed cvzone and restarted my laptop, how can I fix this error?

    from cvzone.HandTrackingModule import HandDetector import cv2

    cap = cv2.VideoCapture(0) detector = HandDetector(detectionCon=0.8, maxHands=2) while True: # Get image frame success, img = cap.read() # Find the hand and its landmarks hands, img = detector.findHands(img) # with draw # hands = detector.findHands(img, draw=False) # without draw

    if hands:
        # Hand 1
        hand1 = hands[0]
        lmList1 = hand1["lmList"]  # List of 21 Landmark points
        bbox1 = hand1["bbox"]  # Bounding box info x,y,w,h
        centerPoint1 = hand1['center']  # center of the hand cx,cy
        handType1 = hand1["type"]  # Handtype Left or Right
    
        fingers1 = detector.fingersUp(hand1)
    
        if len(hands) == 2:
            # Hand 2
            hand2 = hands[1]
            lmList2 = hand2["lmList"]  # List of 21 Landmark points
            bbox2 = hand2["bbox"]  # Bounding box info x,y,w,h
            centerPoint2 = hand2['center']  # center of the hand cx,cy
            handType2 = hand2["type"]  # Hand Type "Left" or "Right"
    
            fingers2 = detector.fingersUp(hand2)
    
            # Find Distance between two Landmarks. Could be same hand or different hands
            length, info, img = detector.findDistance(lmList1[8], lmList2[8], img)  # with draw
            # length, info = detector.findDistance(lmList1[8], lmList2[8])  # with draw
    # Display
    cv2.imshow("Image", img)
    cv2.waitKey(1)
    

    cap.release() cv2.destroyAllWindows()

    I got the code from the examples here

    opened by cadytto 0
Owner
CVZone
CVZone
This is a repository to learn and get more computer vision skills, make robotics projects integrating the computer vision as a perception tool and create a lot of awesome advanced controllers for the robots of the future.

This is a repository to learn and get more computer vision skills, make robotics projects integrating the computer vision as a perception tool and create a lot of awesome advanced controllers for the robots of the future.

Elkin Javier Guerra Galeano 17 Nov 3, 2022
Solution for Problem 1 by team codesquad for AIDL 2020. Uses ML Kit for OCR and OpenCV for image processing

CodeSquad PS1 Solution for Problem Statement 1 for AIDL 2020 conducted by @unifynd technologies. Problem Given images of bills/invoices, the task was

Burhanuddin Udaipurwala 111 Nov 27, 2022
Introduction to image processing, most used and popular functions of OpenCV

?? OpenCV 101 Introduction to image processing, most used and popular functions of OpenCV go here.

Vusal Ismayilov 3 Jul 2, 2022
This is a project to detect gestures to zoom in or out, using the real-time distance between the index finger and the thumb. It's based on OpenCV and Mediapipe.

Pinch-zoom This is a python project based on real-time hand-gesture detection, to zoom in or out, using the distance between the index finger and the

Harshit Bhalla 6 Jul 11, 2022
Creating of virtual elements of the graphical interface using opencv and mediapipe.

Virtual GUI Creating of virtual elements of the graphical interface using opencv and mediapipe. Element GUI Output Description Button By default the b

Aleksei 4 Jun 16, 2022
This project is basically to draw lines with your hand, using python, opencv, mediapipe.

Paint Opencv ?? This project is basically to draw lines with your hand, using python, opencv, mediapipe. Screenshoots ?? Tools ⚙️ Python Opencv Mediap

Williams Ismael Bobadilla Torres 3 Nov 17, 2021
Roboflow makes managing, preprocessing, augmenting, and versioning datasets for computer vision seamless.

Roboflow makes managing, preprocessing, augmenting, and versioning datasets for computer vision seamless. This is the official Roboflow python package that interfaces with the Roboflow API.

Roboflow 52 Dec 23, 2022
computer vision, image processing and machine learning on the web browser or node.

Image processing and Machine learning labs   computer vision, image processing and machine learning on the web browser or node note Fast Fourier Trans

ryohei tanaka 487 Nov 11, 2022
Image processing is one of the most common term in computer vision

Image processing is one of the most common term in computer vision. Computer vision is the process by which computers can understand images and videos, and how they are stored, manipulated, and retrieve details from them. OpenCV is an open source computer vision image processing library for machine learning, deep leaning and AI application which plays a major role in real-time operation which is very important in today’s systems.

Happy  N. Monday 3 Feb 15, 2022
Computer vision applications project (Flask and OpenCV)

Computer Vision Applications Project This project is at it's initial phase. This is all about the implementation of different computer vision techniqu

Suryam Thapa 1 Jan 26, 2022
Multi-choice answer sheet correction system using computer vision with opencv & python.

Multi choice answer correction ?? 5 answer sheet samples with a specific solution for detecting answers and sheet correction. ?? By running the soluti

Reza Firouzi 7 Mar 7, 2022
Using Opencv ,based on Augmental Reality(AR) and will show the feature matching of image and then by finding its matching

Using Opencv ,this project is based on Augmental Reality(AR) and will show the feature matching of image and then by finding its matching ,it will just mask that image . This project ,if used in cctv then it will detect black listed people if mentioned properly with their images.

null 1 Feb 13, 2022
Fast image augmentation library and easy to use wrapper around other libraries. Documentation: https://albumentations.ai/docs/ Paper about library: https://www.mdpi.com/2078-2489/11/2/125

Albumentations Albumentations is a Python library for image augmentation. Image augmentation is used in deep learning and computer vision tasks to inc

null 11.4k Jan 2, 2023
Image processing using OpenCv

Image processing using OpenCv Write a program that opens the webcam, and the user selects one of the following on the video: ✅ If the user presses the

M.Najafi 4 Feb 18, 2022
Aloception is a set of package for computer vision: aloscene, alodataset, alonet.

Aloception is a set of package for computer vision: aloscene, alodataset, alonet.

Visual Behavior 86 Dec 28, 2022
This repo contains several opencv projects done while learning opencv in python.

opencv-projects-python This repo contains both several opencv projects done while learning opencv by python and opencv learning resources [Basic conce

Fatin Shadab 2 Nov 3, 2022
Basic functions manipulating images using the OpenCV library

OpenCV Basic functions manipulating images using the OpenCV library. Reading Ima

Shatha Siala 3 Feb 17, 2022
Controlling the computer volume with your hands // OpenCV

HandsControll-AI Controlling the computer volume with your hands // OpenCV Step 1 git clone https://github.com/Hayk-21/HandsControll-AI.git pip instal

Hayk 1 Nov 4, 2021
This is a real life mario project using python and mediapipe

real-life-mario This is a real life mario project using python and mediapipe How to run to run this just run - realMario.py file requirements This req

Programminghut 42 Dec 22, 2022