face_recognition报错:operands could not be broadcast together with shapes求助
问题描述
按教程实现人脸识别,期望返回True/False结果,却触发ValueError,报错信息:operands could not be broadcast together with shapes (1,4) (1,128)。尝试移除np.array、方括号及dtype=object参数后问题仍未解决。
代码
import cv2 import numpy as np import face_recognition import os path = 'ImageAttendance' # 创建文件列表 myList = os.listdir(path) images = [] classNames = [] print(myList) # 依次提取每个文件的名称 for cl in myList: curImg = cv2.imread(f'{path}/{cl}') images.append(curImg) classNames.append(os.path.splitext(cl)[0]) print(classNames) # 计算所有图片的人脸编码并生成列表 def findEncodings(images): encodeList = [] for img in images: img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) encode = face_recognition.face_encodings(img) encodeList.append(encode) return encodeList # 生成数据库中所有已知人员的编码列表 encodeListKnown = findEncodings(images) print(len(encodeListKnown)) print('Encoding complete') cap = cv2.VideoCapture(0) while True: success, img = cap.read() imgS = cv2.resize(img,(0,0), None, 0.25, 0.25) imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB) facesCurFrame = face_recognition.face_locations(imgS) encodesCurFrame = face_recognition.face_encodings(imgS, facesCurFrame) for encodeFace,faceLoc in zip(encodesCurFrame, facesCurFrame): print('encoding') matches = face_recognition.compare_faces(np.array([encodeListKnown], dtype=object),np.array([encodeFace],dtype=object)) faceDis = face_recognition.face_distance([encodeListKnown], encodeFace) print(faceDis)
完整报错信息
['face.jpg', 'original.jpg', 'Verc.png', 'test.jpg'] ['face', 'original', 'Verc', 'test'] 4 Encoding complete encoding Traceback (most recent call last): File "/home/verc/Документы/Python/FaceRecognition/AttendanceProject.py", line 46, in <module> matches = face_recognition.compare_faces(np.array([encodeListKnown], dtype=object),np.array([encodeFace],dtype=object)) File "/home/verc/.local/lib/python3.10/site-packages/face_recognition/api.py", line 226, in compare_faces return list(face_distance(known_face_encodings, face_encoding_to_check) <= tolerance) File "/home/verc/.local/lib/python3.10/site-packages/face_recognition/api.py", line 75, in face_distance return np.linalg.norm(face_encodings - face_to_compare, axis=1) ValueError: operands could not be broadcast together with shapes (1,4) (1,128) [Finished in 10.8s with exit code 1] [cmd: ['python3', '-u', '/home/verc/Документы/Python/FaceRecognition/AttendanceProject.py']] [dir: /home/verc/Документы/Python/FaceRecognition] [path: /home/verc/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin]
解决方法
问题核心在于findEncodings函数的实现:face_recognition.face_encodings(img)返回的是包含人脸编码的列表(每张图可能有多个人脸,编码为128维数组),你直接将这个列表追加到encodeList中,导致encodeListKnown变成了嵌套列表(4个元素,每个元素是包含128维数组的列表),而非直接存储128维编码数组的列表。
修改步骤:
- 修正
findEncodings函数,提取每张图的第一个人脸编码(假设每张图只有一个人脸),同时处理无检测到人脸的情况:
def findEncodings(images): encodeList = [] for img in images: img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) encodes = face_recognition.face_encodings(img) if encodes: # 确保检测到人脸 encodeList.append(encodes[0]) return encodeList
- 修改
compare_faces和face_distance的调用,不需要手动转成np.array,直接传入处理后的encodeListKnown和encodeFace:
for encodeFace,faceLoc in zip(encodesCurFrame, facesCurFrame): print('encoding') matches = face_recognition.compare_faces(encodeListKnown, encodeFace) faceDis = face_recognition.face_distance(encodeListKnown, encodeFace) print(faceDis)
这样修改后,encodeListKnown是由128维编码数组组成的列表,和encodeFace(单个128维数组)的形状匹配,就能正常计算人脸距离和匹配结果了。
内容的提问来源于stack exchange,提问作者blizzadr
相关产品推荐
相关产品推荐

