opencv数字手势识别
时间: 2023-12-10 20:36:18 浏览: 161
数字手势识别是计算机视觉中的一个重要应用,而OpenCV正是一个强大的计算机视觉库,可以用于数字手势识别。下面是一个简单的数字手势识别的例子:
```python
import cv2
import numpy as np
# 定义一些常量
cap_region_x_begin = 0.5 # 起始x坐标
cap_region_y_end = 0.8 # 结束y坐标
threshold = 60 # 二值化阈值
blurValue = 41 # 高斯模糊参数
bgSubThreshold = 50
learningRate = 0
# 定义ROI区域
def nothing(x):
pass
cv2.namedWindow('trackbar')
cv2.createTrackbar('x', 'trackbar', 0, 100, nothing)
cv2.createTrackbar('y', 'trackbar', 0, 100, nothing)
# 读取摄像头
camera = cv2.VideoCapture(0)
camera.set(10, 200)
# 背景减除器
fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows=True)
while camera.isOpened():
ret, frame = camera.read()
frame = cv2.bilateralFilter(frame, 5, 50, 100) # 双边滤波
frame = cv2.flip(frame, 1) # 翻转图像
# 获取ROI区域
x = cv2.getTrackbarPos('x', 'trackbar')
y = cv2.getTrackbarPos('y', 'trackbar')
roi = frame[int(cap_region_y_end * frame.shape[0]):frame.shape[0], x:frame.shape[1]]
# 背景减除
fgmask = fgbg.apply(roi, learningRate=learningRate)
kernel = np.ones((3, 3), np.uint8)
fgmask = cv2.erode(fgmask, kernel, iterations=1)
res = cv2.bitwise_and(roi, roi, mask=fgmask)
# 灰度化和二值化
gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (blurValue, blurValue), 0)
ret, thresh = cv2.threshold(blur, threshold, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 找到最大轮廓
max_area = 0
ci = 0
if contours:
for i in range(len(contours)):
cnt = contours[i]
area = cv2.contourArea(cnt)
if area > max_area:
max_area = area
ci = i
cnt = contours[ci]
# 手势识别
hull = cv2.convexHull(cnt)
drawing = np.zeros(roi.shape, np.uint8)
cv2.drawContours(drawing, [cnt], 0, (0, 255, 0), 2)
cv2.drawContours(drawing, [hull], 0, (0, 0, 255), 3)
# 计算凸包和凸缺陷
hull = cv2.convexHull(cnt, returnPoints=False)
defects = cv2.convexityDefects(cnt, hull)
# 绘制凸缺陷
count_defects = 0
if defects is not None:
for i in range(defects.shape[0]):
s, e, f, d = defects[i, 0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
a = np.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2)
b = np.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2)
c = np.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2)
angle = np.arccos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) * 180 / np.pi
if angle <= 90:
count_defects += 1
cv2.circle(drawing, far, 8, [211, 84, 0], -1)
# 显示结果
cv2.imshow('output', drawing)
cv2.imshow('input', roi)
# 按下q键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
camera.release()
cv2.destroyAllWindows()
```
阅读全文