OpenCV EigenFace/FisherFace训练人脸识别模型遇尺寸不匹配错误求助
Hey there! Let's break down why you're hitting that error with EigenFace and FisherFace, even though LBPH works perfectly fine.
问题核心原因
The error message spells it out clearly: EigenFace and FisherFace require all training samples (the cropped face ROIs) to be exactly the same size, but LBPHFace has no such restriction.
You mentioned your original iPhone photos are the same size, but here's the catch: when you use detectMultiScale to locate faces, the cropped region (roi = image_array[y:y+h, x:x+w]) will have different widths and heights for each photo. That's because the face's position and apparent size varies slightly across your shots—even if the original photos share the same resolution, the detected face bounding boxes aren't identical. This leads to ROIs with different pixel counts, which breaks the training process for Eigen/Fisher models.
排查与修复步骤
1. 验证ROI尺寸差异
First, confirm this is the root issue by adding a print statement right after you crop the ROI:
for (x,y,w,h) in faces: roi = image_array[y:y+h, x:x+w] # Add this line to check ROI dimensions print(f"ROI size: {roi.shape}") x_train.append(roi) y_labels.append(id_)
When you run the code, you'll see that each ROI has different (height, width) values—this is exactly what's causing the error.
2. 统一所有ROI的尺寸
Fix this by resizing every cropped face to a fixed target size before adding it to x_train. Update your code like this:
# Define a fixed size for all training samples (adjust to your preference) TARGET_SIZE = (200, 200) for (x,y,w,h) in faces: roi = image_array[y:y+h, x:x+w] # Resize the ROI to the fixed target size roi = cv2.resize(roi, TARGET_SIZE, interpolation=cv2.INTER_AREA) x_train.append(roi) y_labels.append(id_)
- Use
cv2.INTER_AREAfor resizing down (ideal if your detected faces are larger than the target size) - Use
cv2.INTER_CUBICorcv2.INTER_LINEARif you need to resize up
3. 重新训练模型
Once all your ROIs are the same size, both EigenFaceRecognizer_create() and FisherFaceRecognizer_create() should train without throwing that size mismatch error.
为什么LBPH能正常工作?
Quick side note: LBPHFace is designed to handle variable-sized input because it extracts local texture features from small regions of the face. EigenFace and FisherFace, on the other hand, rely on PCA/LDA which requires all input samples to be converted into identical-length vectors—hence the strict size requirement.
内容的提问来源于stack exchange,提问作者bbartling

