opencv简单人脸识别代码python
时间: 2024-09-13 15:01:08 浏览: 46
python-opencv 简单人脸识别
在Python中使用OpenCV进行简单的人脸识别通常涉及以下几个步骤:
1. **安装库**:首先确保已经安装了OpenCV (`cv2`) 和 `face_recognition` 库。你可以通过pip来安装:
```
pip install opencv-python face_recognition
```
2. **导入所需模块**:
```python
import cv2
from PIL import Image
import face_recognition
```
3. **加载人脸数据库**(如果你想要识别特定人员):
- 下载并保存一些已知人脸的照片作为样本。
- 使用`face_recognition.load_image_file()`加载图片,并获取编码。
4. **加载图像或视频流**:
```python
img_path = "path_to_your_image.jpg" or cap = cv2.VideoCapture("video.mp4")
```
5. **检测人脸**:
```python
if img_path:
image = face_recognition.load_image_file(img_path)
else:
ret, frame = cap.read()
faces = face_recognition.face_locations(image)
```
6. **面部特征提取**:
```python
known_face_encodings = [] # 存储已知人脸编码
for face in faces:
encoding = face_recognition.face_encodings(image, known_face_locations)[0]
known_face_encodings.append(encoding)
```
7. **识别新面孔**:
```python
unknown_face_encoding = face_recognition.face_encodings(image)[0] # 获取当前帧中的面部编码
results = face_recognition.compare_faces(known_face_encodings, unknown_face_encoding)
match_index = None
if True in results:
match_index = results.index(True)
```
8. **显示结果**:
```python
name = "Unknown" if match_index is None else "Known Person"
print(f"Face matched with {name}")
# 在图像上标记匹配的人脸
for (top, right, bottom, left), name in zip(faces, ["Unknown", "John Doe"]):
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
y = top - 15 if top - 15 > 15 else top + 15
cv2.putText(frame, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
```
9. **保存结果或显示视频流**:
如果是视频流,持续循环上述过程;如果是图像,直接展示处理后的图像。
```python
if img_path:
cv2.imshow('Image', image)
cv2.waitKey(0)
else:
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 在这里插入上面的人脸识别代码
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
```
记得关闭窗口:
```python
cap.release()
cv2.destroyAllWindows()
```
阅读全文