Python Mediapipe 调用电脑摄像头

接下来,我们需要调用电脑摄像头并实时处理图像。以下是完整的代码:
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头图像
ret, frame = cap.read()
# 将图像转换为 RGB 格式
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 进行人脸检测
results = face_detection.process(rgb_frame)
if results.detections:
for detection in results.detections:
# 提取人脸框的位置信息
bbox = detection.location_data.relative_bounding_box
height, width, _ = frame.shape
xmin = int(bbox.xmin * width)
ymin = int(bbox.ymin * height)
xmax = int((bbox.xmin + bbox.width) * width)
ymax = int((bbox.ymin + bbox.height) * height)
# 绘制人脸框和关键点
cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2)
for landmark in detection.location_data.relative_keypoints:
x = int(landmark.x * width)
y = int(landmark.y * height)
cv2.circle(frame, (x, y), 5, (0, 255, 0), -1)
# 显示图像
cv2.imshow('Face Detection', frame)
# 退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头资源
cap.release()
cv2.destroyAllWindows()
解析代码
上面的代码首先调用摄像头,然后对每一帧图像进行处理。首先,将图像转换为 RGB 格式,这是因为 Mediapipe 使用的是 RGB 图像格式。然后,我们将图像传递给人脸检测模型,并获取检测结果。
如果检测到了人脸,我们将绘制人脸框和人脸关键点。对于每个人脸,我们提取其相对位置信息,将其转换为图像上的坐标,然后使用 OpenCV 的绘图函数来绘制人脸框和关键点。
最后,我们将处理后的图像显示出来,并通过按下 "q" 键来退出程序。
总结
本文介绍了如何使用 Mediapipe 库来调用电脑摄像头进行图像处理。通过使用 Mediapipe 的人脸检测功能,我们可以轻松地实现实时人脸检测并标记人脸关键点。这只是 Mediapipe 提供的众多功能之一,你可以根据自己的需求探索更多用法。
代码示例中的代码使用了 OpenCV 来调用摄像头和进行图像处理。如果你对 OpenCV 不熟悉,建议先学习一些基本的图像