import cv2 import mediapipe as mp import time cap = cv2.VideoCapture(0) mpHands = mp.solutions.hands hands = mpHands.Hands() mpDraw = mp.solutions.drawing_utils pTime = 0 cTime = 0 while True: success, img = cap.read() imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) results = hands.process(imgRGB) #print(results.multi_hand_landmarks) if results.multi_hand_landmarks: for handLms in results.multi_hand_landmarks: for id, lm in enumerate(handLms.landmark): #print(id,lm) h, w, c = img.shape cx, cy = int(lm.x *w), int(lm.y*h) #if id ==0: cv2.circle(img, (cx,cy), 7, (255,0,255), cv2.FILLED) mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS) cTime = time.time() fps = 1/(cTime-pTime) pTime = cTime cv2.putText(img,str(int(fps)), (10,70), cv2.FONT_HERSHEY_PLAIN, 3, (255,0,255), 3) cv2.imshow("Image", img) cv2.waitKey(1)
时间: 2024-01-07 20:04:46 浏览: 157
这段代码使用OpenCV和MediaPipe库实现了手部姿势检测,并在视频流中绘制了手部关键点和连接线。具体实现如下:
1. 导入必要的库和模块:
```
import cv2
import mediapipe as mp
import time
```
2. 初始化摄像头并创建MediaPipe Hands模型:
```
cap = cv2.VideoCapture(0) # 初始化摄像头
mpHands = mp.solutions.hands # 创建MediaPipe Hands模型
hands = mpHands.Hands() # 实例化模型
mpDraw = mp.solutions.drawing_utils # 创建绘图工具
```
3. 循环读取视频帧并进行手部姿势检测:
```
while True:
success, img = cap.read() # 读取视频帧
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 将BGR图像转换为RGB图像
results = hands.process(imgRGB) # 进行手部姿势检测
```
4. 绘制手部关键点和连接线:
```
if results.multi_hand_landmarks:
for handLms in results.multi_hand_landmarks:
for id, lm in enumerate(handLms.landmark):
h, w, c = img.shape
cx, cy = int(lm.x *w), int(lm.y*h)
cv2.circle(img, (cx,cy), 7, (255,0,255), cv2.FILLED)
mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)
```
5. 计算并显示帧率:
```
cTime = time.time()
fps = 1/(cTime-pTime)
pTime = cTime
cv2.putText(img,str(int(fps)), (10,70), cv2.FONT_HERSHEY_PLAIN, 3, (255,0,255), 3)
```
6. 显示处理后的帧:
```
cv2.imshow("Image", img)
cv2.waitKey(1)
```
阅读全文