PENCV手势识别抓取图片
一位油管的小哥做的项目非常棒,照着写了一个。
代码:
注意:看好cvzone的版本,太新的版本中有个函数没有,如果找不到这个函数的时候请更换一下库的版本。
import cv2
from cvzone.HandTrackingModule import HandDetector
import cvzone
import numpy as np
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
detector = HandDetector(detectionCon=0.8)
colorR = (255, 0, 255)
cx, cy, w, h = 100, 100, 200, 200
class DragRect():
def __init__(self, posCenter, size=[200, 200]):
self.posCenter = posCenter
self.size = size
def update(self, cursor):
cx, cy = self.posCenter
w, h = self.size
# 指尖在矩形内
if cx - w // 2 < curosor[0] < cx + w // 2 and \
cy - h // 2 < curosor[1] < cy + h // 2:
self.posCenter = cursor
rectList = []
for x in range(5):
rectList.append(DragRect([x * 250 + 150, 150]))
while True:
success, img = cap.read()
img = cv2.flip(img, 1)
img = detector.findHands(img)
lmList, _ = detector.findPosition(img)
if lmList:
l, _, _ = detector.findDistance(8, 12, img, draw=False)
print(l)
if l < 30:
curosor = lmList[8] # finger
# 调用更新
for rect in rectList:
rect.update(curosor)
# draw 实体填充
# for rect in rectList:
# cx, cy = rect.posCenter
# w, h = rect.size
# cv2.rectangle(img, (cx - w // 2, cy - h // 2), (cx + w // 2, cy + h // 2), colorR, cv2.FILLED)
# cvzone.cornerRect(img, (cx - w // 2, cy - h // 2, w, h), 20, rt=0)
# 虚化
imgNew = np.zeros_like(img)
for rect in rectList:
cx, cy = rect.posCenter
w, h = rect.size
cv2.rectangle(imgNew, (cx - w // 2, cy - h // 2), (cx + w // 2, cy + h // 2), colorR, cv2.FILLED)
cvzone.cornerRect(imgNew, (cx - w // 2, cy - h // 2, w, h), 20)
out = img.copy()
alpja = 0.5
mask = imgNew.astype(bool)
#print(mask.shape)
out[mask] = cv2.addWeighted(img, alpja, imgNew, 1, -alpja, 0)[mask]
cv2.imshow("Image", out)
cv2.waitKey(1)