Traceback (most recent call last):
File "/home/pi/Project/mainf.py", line 145, in <module>
predicted_img1 = predict(test_img1)
File "/home/pi/Project/mainf.py", line 83, in predict
label, confidence = face_recognizer.predict(face)
TypeError: 'int' object is not iterable
我的任务是在运行时使用网络摄像头拍摄一些照片并按当前日期和时间.jpg保存文件。当系统尝试读取面部识别文件时,它会抛出错误。我的目录是一个名为test-data的文件,其中保存了文件。另一个是training-data有一个名为s1和s2的子文件夹,其中包含一个人的图像
import cv2
import sys
import time
import os
import glob
import operator
import numpy as np
subjects = ["", "Sanjeev", "Vijay"]
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
#function to detect face using OpenCV
def detect_face(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('opencv-files/lbpcascade_frontalface.xml')
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);
if (len(faces) == 0):
return None, None
(x, y, w, h) = faces[0]
return gray[y:y+w, x:x+h], faces[0]
#function to prepare a training set.
def prepare_training_data(data_folder_path):
dirs = os.listdir(data_folder_path)
faces = []
labels = []
for dir_name in dirs:
if not dir_name.startswith("s"):
continue;
label = int(dir_name.replace("s", ""))
subject_dir_path = data_folder_path + "/" + dir_name
subject_images_names = os.listdir(subject_dir_path)
for image_name in subject_images_names:
if image_name.startswith("."):
continue;
image_path = subject_dir_path + "/" + image_name
image = cv2.imread(image_path)
face, rect = detect_face(image)
if face is not None:
faces.append(face)
labels.append(label)
cv2.destroyAllWindows()
cv2.waitKey(1)
cv2.destroyAllWindows()
return faces, labels
faces, labels = prepare_training_data("training-data")
#create our LBPH face recognizer
#face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer = cv2.face.createLBPHFaceRecognizer()
#face_recognizer = cv2.face.EigenFaceRecognizer_create()
#face_recognizer = cv2.face.FisherFaceRecognizer_create()
#train our face recognizer of our training faces
face_recognizer.train(faces, np.array(labels))
def draw_rectangle(img, rect):
(x, y, w, h) = rect
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
def draw_text(img, text, x, y):
cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)
def predict(test_img):
img = test_img.copy()
face, rect = detect_face(img)
label, confidence = face_recognizer.predict(face)
print(confidence)
print(label)
label_text = subjects[label]
draw_rectangle(img, rect)
draw_text(img, label_text, rect[0], rect[1]-5)
if confidence <=20:
print(subjects[label]+"is a known face")
return img
else:
print("Unknown face found")
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
if ret is True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
continue
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
#flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
#Save just the rectangle faces in SubRecFaces
sub_face = frame[y:y+h, x:x+w]
timestr = time.strftime("%Y%m%d-%H%M%S")
FaceFileName = "test-data/"+timestr+str(y)+ ".jpg"
#FaceFileName = "test-data/"+"san"+ ".jpg"
cv2.imwrite(FaceFileName, sub_face)
# Display the resulting frame
#cv2.imshow('Video', frame)
#getting latest file names
list_of_files = glob.glob('test-data/*.*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
#index=latest_file.rfind('\\')
#new_file = latest_file[index+1:]
#print('test-data/'+new_file)
#print new_file
#print latest_file
#load test images
test_img1 = cv2.imread(latest_file)
#test_img1 = cv2.imread("test-data/test1.jpg")
#test_img2 = cv2.imread('test-data/'+new_file)
#perform a prediction
predicted_img1 = predict(test_img1)
#predicted_img1 = predict(test_img1)
#predicted_img2 = predict(test_img2)
time.sleep(2.0)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()