我创建了2个文件,第一个调用train.py,第二个faces.py我尝试通过训练数据来开发人脸识别和识别。但是当我运行它时失败了。我为两个文件都附加了代码。我帮助某人可以就此事为我提供帮助。我尝试运行faces.py,但是失败了。当我尝试打印(roi_gray)时也显示错误。
import os
import cv2
import numpy as np
from PIL import Image
import pickle
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
image_dir = os.path.join(BASE_DIR, "images22")
face_cascade =
cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
current_id = 0
label_ids = {}
y_labels = []
x_train = []
recognizer = cv2.face.LBPHFaceRecognizer_create()
for root, dirs, files in os.walk(image_dir):
for file in files:
if file.endswith("png") or file.endswith("jpg"):
path = os.path.join(root, file)
label = os.path.basename(os.path.dirname(path)).replace("","-").lower()
#print(path)
#print(label, path)
if not label in label_ids:
label_ids[label] = current_id
current_id += 1
id_ = label_ids[label]
#print(label_ids)
#y_labels.append(label)
#x_train.append(path)
pil_image = Image.open(path).convert("L")
image_array = np.array(pil_image, "uint8")
#print(image_array)
faces = face_cascade.detectMultiScale(image_array, scaleFactor=1.5,
minNeighbors=5)
for(x,y,w,h) in faces:
roi = image_array[y:y+h, x:x+w]
x_train.append(roi)
y_labels.append(id_)
#print(y_labels)
#print(x_train)
with open("labels.pickle",'wb') as f:
pickle.dump(label_ids, f)
recognizer.train(x_train,np.array(y_labels))
recognizer.save("trainner.yml")
这是faces.py的代码
import numpy as np
import cv2
face_cascade =
cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("trainner.yml")
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5,
minNeighbors=5)
for (x, y, w, h) in faces:
#print(x,y,w,h)
roi_gray = gray[y:y+h, x:x+w] #(ycord_start, ycord_end)
roi_color = frame[y:y+h, x:x+w]
id_, conf = recognizer.predict(roi_gray)
if conf>=4 and conf <=85:
img_item = "my-image.png"
cv2.imwrite(img_item, roi_gray)
color = (255,0,0) #BGR 0-255
stroke = 2
end_cord_x = x + w
end_cord_y = y + h
cv2.rectangle(frame,(x,y),(end_cord_x,end_cord_y),color,stroke)
cv2.imshow('frame',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
答案 0 :(得分:1)
删除此:
print(roi_gray)
或将其移动到此for
循环之后:
for (x, y, w, h) in faces:
#print(x,y,w,h)
roi_gray = gray[y:y+h, x:x+w] #(ycord_start, ycord_end)
roi_color = frame[y:y+h, x:x+w]
您正在尝试打印该行上不存在的某些东西,从而引发错误。