如何忽略未检测到人脸的帧并保存含有人脸的对齐帧?
解决dlib人脸对齐时无检测人脸帧的报错问题
问题场景
使用dlib对视频提取的帧做人脸对齐时,部分帧因未检测到人脸,调用dlib.get_face_chips()时触发RuntimeError: No face were specified in the faces array错误,需要忽略这些无脸帧,只保存成功对齐的结果。
解决方案
在生成人脸对齐图像前,先判断faces数组是否为空:
- 若为空(无检测到人脸),直接跳过当前帧
- 若不为空,执行人脸对齐并将结果保存到目标文件夹
修改后的完整代码
import cv2 as cv import dlib import glob import os import numpy as np # 初始化检测器和特征点预测器 detector = dlib.get_frontal_face_detector() sp = dlib.shape_predictor("shape_predictor_5_face_landmarks.dat") # 配置路径 input_dir = "./frames_copy" # 原始帧文件夹 output_dir = "./aligned_faces" # 对齐后人脸保存文件夹 # 创建输出文件夹(不存在则创建) if not os.path.exists(output_dir): os.makedirs(output_dir) # 遍历文件夹内所有jpg帧 for img_path in glob.glob(f"{input_dir}/*.jpg"): # 读取图像 img = cv.imread(img_path) if img is None: print(f"无法读取图像: {img_path}") continue # 检测人脸 dets = detector(img, 1) # 生成人脸特征点集合 faces = dlib.full_object_detections() for detection in dets: faces.append(sp(img, detection)) # 检查是否检测到人脸,无则跳过 if len(faces) == 0: print(f"未检测到人脸,跳过帧: {img_path}") continue # 执行人脸对齐 aligned_images = dlib.get_face_chips(img, faces, size=180) # 保存对齐后的人脸图像 img_name = os.path.basename(img_path) for idx, aligned_img in enumerate(aligned_images): # 将dlib图像转为opencv格式(BGR) aligned_img_cv = cv.cvtColor(np.array(aligned_img), cv.COLOR_RGB2BGR) # 保存,若一帧多脸则加索引区分 save_path = os.path.join(output_dir, f"{os.path.splitext(img_name)[0]}_face{idx}.jpg") cv.imwrite(save_path, aligned_img_cv) print("人脸对齐处理完成")
关键修改点
- 添加批量帧遍历逻辑,替代原单帧测试代码
- 增加
len(faces) == 0的判断,无检测人脸时直接跳过当前帧 - 新增输出文件夹自动创建逻辑,避免路径不存在报错
- 加入图像读取失败的判断,增强鲁棒性
- 实现对齐后图像的保存逻辑,支持一帧多脸的情况
内容的提问来源于stack exchange,提问作者Umar Usman
相关产品推荐
相关产品推荐

