手势检测 |Part 1 数据集收集 |cvzone Hand Detector

感谢up我导[微笑]
我刚刚跑完,在我电脑上有两个小问题:
1.offset那里不能直接设置成20像素,因为x-20或者y-20他俩有可能会小于零,当小于零的时候会直接报错退出imshow的展示窗口
2.我用0.08*y和0.08*x分别代替x和y方向的offset,但是生成图片会出现一个问题,crop会直接把红色的边界框一起切下来
下面是代码:
import math
import os.path
import CV2
import numpy as np
from cvzone.HandTrackingModule import HandDetector
# 调用摄像头,并展示窗口
cap = CV2.VideoCapture(0)
detector = HandDetector(maxHands=1)
folder6 = "./images/six"
imgsize = 300
counter = 0
while True:
success, img = cap.read()
hands, img = detector.findHands(img)
if hands:
hand = hands[0]
x, y, w, h = hand['bbox']
img_white = np.ones((imgsize, imgsize, 3), np.uint8) * 255
a_y = 0.08*y
a_x = 0.08*x
imgcrop = img[y - int(a_y):y + h + int(a_y), x - int(a_x):x + w + int(a_x)]
aspectRatio = h / w
if aspectRatio > 1:
k = imgsize / h
wcal = math.ceil(k * w)
resized_img = CV2.resize(imgcrop, (wcal, imgsize))
w_offset = math.ceil((imgsize - wcal) / 2)
img_white[:, w_offset:wcal + w_offset] = resized_img
else:
k = imgsize/w
hcal = math.ceil(k*h)
resized_img = CV2.resize(imgcrop, (imgsize, hcal))
h_offset = math.ceil((imgsize - hcal) / 2)
img_white[h_offset:hcal+h_offset, :] =resized_img
CV2.imshow('imgcrop', img_white)
CV2.imshow('image', img)
key = CV2.waitKey(1)
if key == ord("s"):
counter += 1
CV2.imwrite(os.path.join(folder6,f'{counter}.jpg'),img_white)
print(counter)