MTCNN截取人脸 代码
时间: 2023-11-12 08:08:46 浏览: 39
MTCNN是一种用于人脸检测的深度学习模型,它能够检测出一张图片中的所有人脸,并给出它们的位置、大小和姿态。下面是使用MTCNN截取人脸的Python代码示例:
```python
import cv2
import numpy as np
from mtcnn import MTCNN
# 加载MTCNN模型
detector = MTCNN()
# 加载图片
img = cv2.imread('test.jpg')
# 检测人脸
results = detector.detect_faces(img)
# 遍历每张人脸,截取并保存
for i, result in enumerate(results):
x, y, w, h = result['box']
face = img[y:y+h, x:x+w]
cv2.imwrite(f'face_{i}.jpg', face)
```
在这个代码中,我们使用了MTCNN库来加载模型并检测人脸。然后,我们遍历检测结果中的每一张人脸,从原始图片中截取出人脸区域,并保存到本地文件中。你可以将`'test.jpg'`替换为你自己的图片路径,运行代码后就能得到每张人脸的截图了。
相关问题
MTCNN截取人脸 python代码
以下是使用MTCNN库在Python中截取人脸的示例代码:
```python
import cv2
from mtcnn import MTCNN
# 创建MTCNN检测器
detector = MTCNN()
# 加载图像
image = cv2.imread('path/to/image.jpg')
# 检测人脸
results = detector.detect_faces(image)
# 遍历每个检测结果
for result in results:
# 获取人脸框位置
x, y, width, height = result['box']
# 截取人脸
face = image[y:y+height, x:x+width]
# 显示截取结果
cv2.imshow('Face', face)
cv2.waitKey(0)
# 释放窗口
cv2.destroyAllWindows()
```
需要注意的是,MTCNN库需要安装才能使用。可以通过以下命令进行安装:
```
pip install mtcnn
```
使用OpenFace截取人脸 python代码
使用OpenFace截取人脸的Python代码如下:
```python
import cv2
import os
# 加载OpenCV的人脸检测器
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 加载OpenFace的人脸识别模型
face_aligner = openface.AlignDlib('shape_predictor_68_face_landmarks.dat')
# 读取图片
img = cv2.imread('test.jpg')
# 将图片转为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_detector.detectMultiScale(gray, 1.3, 5)
# 遍历每张人脸
for (x,y,w,h) in faces:
# 截取人脸区域
face_img = img[y:y+h, x:x+w]
# 将人脸图像对齐
aligned_face = face_aligner.align(96, face_img, face_aligner.getLargestFaceBoundingBox(face_img), landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)
# 保存人脸图像
cv2.imwrite(os.path.join('output', 'face_{}.jpg'.format(i)), aligned_face)
```
其中,`haarcascade_frontalface_default.xml` 是OpenCV的人脸检测器模型,`shape_predictor_68_face_landmarks.dat` 是OpenFace的人脸识别模型。代码中使用了OpenFace的人脸对齐功能,可以将检测到的人脸图像对齐并保存在指定文件夹中。