import cv2
from cvzone.HandTrackingModule import HandDetector

cap = cv2.VideoCapture(0)
detector = HandDetector(detectionCon=0.8,maxHands=2)#maxHands 显示的手掌最大数,现在设置为最多2个手掌,现在想追踪多个手掌可以修改
while True:
    success,img = cap.read()#这一条跟下面两条CV2,用来打开摄像头
    hands,img = detector.findHands(img) # 显示手掌各手指线条,参数 flipType=False 翻转左右手,左手显示为右手,右手显示为左手
    #hands = detector.findHands(img,draw=False) #不显示手掌线条
    #print(len(hands))#打印显示的手掌数量
    #hands是一个字典,里面有一个lmList列表的信息,bbox边界信息框的信息,center 中心的信息,type 类型信息
    #每个手都hand - dict(lmList,bbox,center,type)
    if hands:
        hand1 = hands[0]
        lmList1 = hand1["lmList"] #获取手掌的全部数据 ,一共21个,
        bbox1 = hand1["bbox"] #获取手掌的边框4个点的数据位置
        centerPoint1 = hand1["center"] #获取中心
        handType1 = hand1["type"] #类型,显示是左手还是右手
        #print(len(lmList1),lmList1) #打印手掌的全部数据
        #print(bbox1) #打印手掌边框位置数据
        #print(centerPoint1) #打印手掌中心点位置,可以使用cv2 circle 在它周围创建一个圆圈??
        #print(handType1) #打印手掌类型,左手还是右手,一行只显示一个,
        fingers1 = detector.fingersUp(hand1) #显示手掌有几个手指向上,获得的数据是[1,1,1,1,1],1代表向上,0代表没有向上(张开)
        #length,info,img = detector.findDistance(lmList1[8],lmList1[12],img) # 给手指画圈,8是食指,12是中指,加img是显示圆圈
        #length, info, img = detector.findDistance(lmList1[8], lmList1[12])  # 不加img,不会显示圆圈
        #print(fingers1)
   #如果要两手一行显示,可以以下代码
    if len(hands) == 2:
        hand2 = hands[1]
        lmList2 = hand2["lmList"] #获取手掌的全部数据 ,一共21个,
        bbox2 = hand2["bbox"] #获取手掌的边框4个点的数据位置
        centerPoint2 = hand2["center"] #获取中心
        handType2 = hand2["type"] #类型,显示是左手还是右手

        #print(handType1,handType2) #两只手同时显示时,才打印手掌类型
        fingers2 = detector.fingersUp(hand2)
        #length, info, img = detector.findDistance(lmList1[8], lmList2[8], img) #两个食指画圈, length两个手指的距离
        length, info, img = detector.findDistance(centerPoint1,centerPoint2, img) #两个手掌中心画圈,数据也是两个中心之间
        print(info)
    cv2.imshow("Image",img)
    cv2.waitKey(1)

非常有用,正好结合我正在打印的人体机械人手掌,检测到数据后,通过串口以G代码发送给arduino,控制舵机转动,显示相同手指

最后修改:2021 年 09 月 03 日
如果觉得我的文章对你有用,请随意赞赏