再利用face_recognition做人臉識別的時候訓練人臉圖片時報錯:
face_recognition IndexError: list index out of range
主要代碼定位到:增加編碼到訓練集的face_recognition.face_encodings(...)
#遍歷訓練集中每個數據集
for class_dir in os.listdir(train_dir):
if not os.path.isdir(os.path.join(train_dir,class_dir)):
continue
print "get:",class_dir
#遍歷每個目錄下的每張照片
for img_path in image_files_in_folder(os.path.join(train_dir,class_dir)):
image = fr.load_image_file(img_path)
boxes = fr.face_locations(image)
#對於當前圖片 增加編碼到訓練集
X.append(fr.face_encodings(image,known_face_locations=boxes)[0])
y.append(class_dir)
分析原因:
在追加數據到X中時,會將識別的圖片編碼,但是前提是能識別出人臉,否則編碼數據則爲空,這也爲什麼會報訪問超出邊界BUG,這裏我們需要添加判斷。
#遍歷訓練集中每個數據集
for class_dir in os.listdir(train_dir):
if not os.path.isdir(os.path.join(train_dir,class_dir)):
continue
print "get:",class_dir
#遍歷每個目錄下的每張照片
for img_path in image_files_in_folder(os.path.join(train_dir,class_dir)):
image = fr.load_image_file(img_path)
boxes = fr.face_locations(image)
#對於當前圖片 增加編碼到訓練集
encodings = fr.face_encodings(image,known_face_locations=boxes)
if len(encodings) > 0:
X.append(encodings[0])
y.append(class_dir)
else:
print("No faces found in the image!")
#X.append(fr.face_encodings(image,known_face_locations=boxes)[0])
#y.append(class_dir)