编写代码基于python的手势一二三识别opencv
时间: 2023-07-27 13:05:51 浏览: 126
以下是一个基于Python和OpenCV的手势识别代码,可以实现一二三的手势识别。
```python
import cv2
import numpy as np
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 捕获每一帧
ret, frame = cap.read()
# 将帧转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 高斯滤波
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# 阈值处理
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY_INV)
# 轮廓检测
contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 找到轮廓中最大的那个
if len(contours) > 0:
contour = max(contours, key=cv2.contourArea)
# 如果轮廓面积大于一定值,则进行手势识别
if cv2.contourArea(contour) > 10000:
# 手势识别,根据手指数来判断
hull = cv2.convexHull(contour, returnPoints=False)
defects = cv2.convexityDefects(contour, hull)
count_defects = 0
for i in range(defects.shape[0]):
s, e, f, d = defects[i, 0]
start = tuple(contour[s][0])
end = tuple(contour[e][0])
far = tuple(contour[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
# 根据手指数来判断手势
if count_defects == 0:
cv2.putText(frame, "1", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 2)
elif count_defects == 1:
cv2.putText(frame, "2", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 2)
elif count_defects == 2:
cv2.putText(frame, "3", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 2)
# 绘制轮廓
cv2.drawContours(frame, [contour], 0, (0, 255, 0), 3)
# 显示每一帧
cv2.imshow('frame', frame)
# 按下q键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放捕获的摄像头并关闭所有窗口
cap.release()
cv2.destroyAllWindows()
```
这个代码可以通过摄像头捕获图像,并实时进行手势识别。当手势为一时,在图像上显示数字1;当手势为二时,在图像上显示数字2;当手势为三时,在图像上显示数字3。
阅读全文