用python3.8➕opencv-python(4.10)➕opencv-contrib-python(4.10)环境,写人脸采集可运行的代码
时间: 2024-09-07 10:02:27 浏览: 112
在Python 3.8环境中使用OpenCV (cv2) 和 contrib模块进行人脸采集,你可以使用`cv2.VideoCapture`来获取摄像头流,并结合`face_recognition`库来进行人脸识别。以下是一个简单的代码示例:
```python
# 首先需要安装必要的库
# 安装OpenCV
!pip install opencv-python==4.10.0
# 安装opencv_contrib_python
!pip install opencv-contrib-python==4.10.0
import cv2
from PIL import Image
import face_recognition
def capture_faces_from_webcam():
# 创建VideoCapture对象,这里默认是电脑内置摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取一帧视频
ret, frame = cap.read()
# 如果读取成功
if ret:
# 转换到灰度图像,便于处理
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 使用face_recognition识别人脸
face_locations = face_recognition.face_locations(gray)
for (top, right, bottom, left) in face_locations:
# 绘制矩形框
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
# 将BGR颜色空间转换回RGB,因为PIL需要RGB
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
pil_image = Image.fromarray(rgb_frame)
# 显示图片
pil_image.show()
# 按 'q' 键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
print("无法从摄像头读取数据")
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
capture_faces_from_webcam()
```
这个代码会在摄像头中实时捕获人脸并用绿色矩形框标记出来。当你按下'q'键时,程序会停止运行。
阅读全文
相关推荐

















