Basiclly i create 2 file the first one call train.py and second one faces.py i try to develop the face recognition and identification by train the data.but when i run it it fail.I attach code for both file. I help someone can help me regarding on this matter. I try to run faces.py but it's fail. When i try to print(roi_gray) also the show the error.
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")
This is code for 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()
Remove this:
print(roi_gray)
Or move it until after this for
loop:
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]
You are trying to print something that doesn't exist at that line which is throwing the error.