You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用imutils FaceAligner.align触发TypeError:无法解析'center'

解决人脸归一化时的TypeError: Can't parse 'center'错误

错误原因分析

代码存在两处明显的变量名不匹配问题,这是触发错误的直接原因:

  • 定义的人脸检测器变量为det,但调用时误用了未定义的detector
  • 定义的人脸对齐器变量为alg,但调用时误用了未定义的aligner

这种变量名错误会导致后续人脸检测或关键点提取异常,最终使cv2.getRotationMatrix2D函数接收到不符合要求的center参数(非数值类型),从而抛出TypeError: Can't parse 'center'。

修正后的代码

import cv2
import dlib
from imutils.face_utils import FaceAligner
import matplotlib.pyplot as plt

# 初始化检测器与关键点预测器
det = dlib.get_frontal_face_detector()
# 替换为shape_predictor_68_face_landmarks.dat的实际本地路径
pred = dlib.shape_predictor(r'...\shape_predictor_68_face_landmarks.dat')

# 初始化人脸对齐器
alg = FaceAligner(pred, desiredFaceWidth=256)

# 读取图片并转为灰度图
frame = cv2.imread('img.jpg')
if frame is None:
    raise ValueError("无法读取图片,请检查文件路径是否正确")
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# 检测人脸
rects = det(gray, 1)
if len(rects) == 0:
    raise ValueError("图片中未检测到人脸,请更换图片或调整检测参数")
rect = rects[0]

# 执行人脸对齐
faceAligned = alg.align(frame, gray, rect)

# 可选:显示对齐后的人脸
plt.imshow(cv2.cvtColor(faceAligned, cv2.COLOR_BGR2RGB))
plt.show()

额外注意事项

  • 确保已正确下载dlib的68点人脸关键点模型文件,并填写正确的本地路径
  • 输入图片img.jpg需存在于当前工作目录,或填写完整的文件路径
  • 代码中增加了图片读取和人脸检测的异常判断,提前拦截无效输入避免后续崩溃

内容的提问来源于stack exchange,提问作者user20003920

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:55:20