如何用opencv调用摄像头后标记人脸
时间: 2024-05-16 20:17:32 浏览: 52
使用OpenCV调用摄像头并标记人脸需要以下步骤:
1. 导入必要的库和模块:
```python
import cv2
import numpy as np
import face_recognition
```
2. 打开摄像头:
```python
cap = cv2.VideoCapture(0)
```
3. 循环读取摄像头中的每一帧:
```python
while True:
ret, frame = cap.read()
```
4. 使用face_recognition模块检测人脸:
```python
face_locations = face_recognition.face_locations(frame)
```
5. 对每个检测到的人脸进行标记:
```python
for (top, right, bottom, left) in face_locations:
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
```
6. 显示标记后的图像:
```python
cv2.imshow('Video', frame)
```
完整代码如下:
```python
import cv2
import numpy as np
import face_recognition
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
face_locations = face_recognition.face_locations(frame)
for (top, right, bottom, left) in face_locations:
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
运行代码后,摄像头会自动打开,即可看到标记后的人脸图像。
阅读全文