安装环境
安装时间2023/11/22
环境为windows cuda11.7
pip install mtcnn
pip install opencv-python-4.3.0.38
pip install tensorflow==2.12.0
裁剪代码
import os
import cv2
import numpy as np
from mtcnn import MTCNN
# 读取图像文件夹路径
input_dir = '/path/to/input/folder'
# 保存截取人脸的图像文件夹路径
output_dir = '/path/to/output/folder'
# 创建保存截取人脸的图像文件夹
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 初始化MTCNN模型
detector = MTCNN()
# 遍历图像文件夹中的所有图像
for filename in os.listdir(input_dir):
# 读取图像
img = cv2.imread(os.path.join(input_dir, filename))
# 检测人脸
faces = detector.detect_faces(img)
# 遍历检测到的人脸
for face in faces:
# 获取人脸坐标
x1, y1, width, height = face['box']
# 截取对齐人脸
cropped = img[y1:y1+height, x1:x1+width]
cv2.imwrite(os.path.join(output_dir, filename), cropped)
效果
原图
裁剪后
如果遇到什么问题欢迎评论区交流
群内交流更多技术
130856474