写一下用opencv-python识别石头剪刀布手势的代码
时间: 2023-12-03 09:46:00 浏览: 125
下面是一个使用OpenCV-Python库识别石头剪刀布手势的示例代码:
```python
import cv2
import numpy as np
import math
# 定义区域的颜色上下限
lower = np.array([0, 20, 70], dtype=np.uint8)
upper = np.array([20, 255, 255], dtype=np.uint8)
# 开启摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取一帧
ret, frame = cap.read()
if not ret:
break
# 镜像翻转
frame = cv2.flip(frame, 1)
# 转换到HSV空间
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# 创建掩膜
mask = cv2.inRange(hsv, lower, upper)
# 进行图像形态学操作
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
mask = cv2.erode(mask, kernel, iterations=2)
mask = cv2.dilate(mask, kernel, iterations=2)
# 找到轮廓
contours, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 如果找到了轮廓
if len(contours) > 0:
# 找到最大的轮廓
contour = max(contours, key=cv2.contourArea)
# 计算轮廓的外接圆
((x, y), radius) = cv2.minEnclosingCircle(contour)
# 计算轮廓的重心
M = cv2.moments(contour)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
# 绘制重心和外接圆
cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)
cv2.circle(frame, center, 5, (0, 0, 255), -1)
# 如果半径大于10
if radius > 10:
# 计算手势方向
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(frame, [box], 0, (0, 255, 0), 2)
x1, y1 = box[0]
x2, y2 = box[1]
angle = math.atan2(y2 - y1, x2 - x1) * 180.0 / math.pi
if angle < 0:
angle += 180
if angle <= 60:
gesture = "scissors"
elif angle <= 120:
gesture = "rock"
else:
gesture = "paper"
# 在屏幕上显示手势
cv2.putText(frame, gesture, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 2)
# 显示结果
cv2.imshow("Frame", frame)
cv2.imshow("Mask", mask)
# 按下q键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头
cap.release()
# 关闭所有窗口
cv2.destroyAllWindows()
```
代码中使用红色的石头剪刀布手势进行演示,可以根据实际情况调整颜色区间。使用此代码时需要安装OpenCV-Python库,可以通过以下命令进行安装:
```
pip install opencv-python
```
阅读全文