Basiclly我创建2文件中的第一个电话train.py和第二个faces.py我试图通过火车开发脸部识别和鉴定data.but当我运行它,它fail.I代码附加两个文件。我帮有人能帮助我就在这个问题上。我尝试运行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()
删除此:
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]
您要打印的东西,不以该行被引发错误存在。