def eigen_train_data(): face_dir = 'face_data' imgs = [] tags = [] index = 0 for (subdirs, dirs, files) in os.walk(face_dir): for subdir in dirs: img_path = os.path.join(face_dir, subdir) for fn in os.listdir(img_path): path = img_path + '/' + fn tag = index img = cv2.imread(path, 0) imgs.append(cv2.resize(img, (92, 112))) tags.append(int(tag)) index += 1 (imgs, tags) = [np.array(item) for item in [imgs, tags]] model = cv2.createEigenFaceRecognizer(5) model.train(imgs, tags) model.save('eigen_trained_data_5.yml') # model = cv2.createEigenFaceRecognizer(10) # model.train(imgs, tags) # model.save('eigen_trained_data_10.yml') # # model = cv2.createEigenFaceRecognizer(30) # model.train(imgs, tags) # model.save('eigen_trained_data_30.yml') # # model = cv2.createEigenFaceRecognizer(40) # model.train(imgs, tags) # model.save('eigen_trained_data_40.yml') # # model = cv2.createEigenFaceRecognizer(50) # model.train(imgs, tags) # model.save('eigen_trained_data_50.yml') # # model = cv2.createEigenFaceRecognizer(60) # model.train(imgs, tags) # model.save('eigen_trained_data_60.yml') model = cv2.createEigenFaceRecognizer(70) model.train(imgs, tags) model.save('eigen_trained_data_70.yml') model = cv2.createEigenFaceRecognizer(80) model.train(imgs, tags) model.save('eigen_trained_data_80.yml') print "Training completed successfully" return
def __init__(self,type,database,partition_percentage,num_components=None): if not num_components==None: if type==1: self.model = cv.createEigenFaceRecognizer(num_components) else: self.model = cv.createFisherFaceRecognizer(num_components) else: if type==1: self.model = cv.createEigenFaceRecognizer() else: self.model = cv.createFisherFaceRecognizer() self.manager = External_DB_Manager(partition_percentage) self.database = database
def Eigen_recognizer(model_dir): model_path = os.path.join(model_dir, 'Eigen.yml') face_recognizer = cv2.createEigenFaceRecognizer(5) print 'loading model in {0}'.format(model_path) face_recognizer.load(model_path) print 'load model finished.' return face_recognizer
def get_trained_model_data_cv(trainDir, persistence_folder=pers_folder): """ """ imgs, nameList = ufd.img_batch_read(trainDir) trained_Y = [lib_str.split(e, '__')[-2] for e in nameList] trained_Y, mapping = get_trained_Y_cv(trained_Y) trained_X = get_img_data_cv(imgs) trained_X = lib_np.array(trained_X) trained_Y = lib_np.array(trained_Y) model = lib_cv2.createEigenFaceRecognizer() # model = lib_cv2.createFisherFaceRecognizer() model.train(trained_X, trained_Y) model.save(trainDir + persistence_folder + model_pers_name_cv) data_persistence_encode(None, trained_X, trained_Y, model_pers_name_cv, trainedX_pers_name_cv, trainedY_pers_name_cv, trainDir) data_persistence_encode_neuromapping(mapping, mapping_pers_name_cv, trainDir) return model, mapping, trained_X, trained_Y
def trainAndPredict(csvFile): imagespaths, strlabels = getCSVData(csvFile) model = cv2.createEigenFaceRecognizer() images = [] intlabels = [] for i in range(len(imagespaths)): images.append(cv2.imread(imagespaths[i], 0)) intlabels.append(int(strlabels[i])) model.train(np.asarray(images), np.asarray(intlabels)) model.save('model.xml') # predict face face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') webcam = cv2.VideoCapture(0) while True: ret, frame = webcam.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: img = cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) f = cv2.resize(gray[y:y + h, x:x + w], (200, 200)) prediction = model.predict(f) print type(prediction) print prediction cv2.imshow('camera', frame) if cv2.waitKey(1000 / 12) & 0xff == ord("q"): break webcam.release() cv2.destroyAllWindows()
def refresh_data(): # Get path to all images path = '../rsc/images' image_paths = [os.path.join(path, f) for f in os.listdir(path)] # Initialize empty lists for these images and labels images = [] labels = [] for path in image_paths: images.append(cv2.imread(path, cv2.CV_LOAD_IMAGE_GRAYSCALE)) labels.append(int(os.path.split(path)[1].split("_")[0])) labels = array(labels) # Create recognizers eigen_recognizer = cv2.createEigenFaceRecognizer() fisher_recognizer = cv2.createFisherFaceRecognizer() lbhp_recognizer = cv2.createLBPHFaceRecognizer() # Train recognizers eigen_recognizer.train(images, labels) fisher_recognizer.train(images, labels) lbhp_recognizer.train(images, labels) # Save results eigen_recognizer.save(EIGEN_RECOGNIZER_PATH) fisher_recognizer.save(FISHER_RECOGNIZER_PATH) lbhp_recognizer.save(LBHP_RECOGNIZER_PATH)
def model(algorithm, thresh): # set the choosen algorithm model = None if not is_cv3(): # OpenCV version renamed the face module if algorithm == 1: model = cv2.face.createLBPHFaceRecognizer(threshold=thresh) elif algorithm == 2: model = cv2.face.createFisherFaceRecognizer(threshold=thresh) elif algorithm == 3: model = cv2.face.createEigenFaceRecognizer(threshold=thresh) else: print("WARNING: face algorithm must be in the range 1-3") os._exit(1) else: if algorithm == 1: model = cv2.createLBPHFaceRecognizer(threshold=thresh) elif algorithm == 2: model = cv2.createFisherFaceRecognizer(threshold=thresh) elif algorithm == 3: model = cv2.createEigenFaceRecognizer(threshold=thresh) else: print("WARNING: face algorithm must be in the range 1-3") os._exit(1) return model
def __init__(self): self.node_name = "face_recog_eigen" rospy.init_node(self.node_name) rospy.on_shutdown(self.cleanup) self.bridge = CvBridge() self.face_names = StringArray() self.size = 4 face_haar = 'haarcascade_frontalface_default.xml' self.haar_cascade = cv2.CascadeClassifier(face_haar) self.face_dir = 'face_data_eigen' # self.model = cv2.createFisherFaceRecognizer() self.model = cv2.createEigenFaceRecognizer() (self.im_width, self.im_height) = (112, 92) rospy.loginfo("Loading data...") # self.fisher_train_data() self.load_trained_data() rospy.sleep(3) # self.img_sub = rospy.Subscriber("/asus/rgb/image_raw", Image, self.img_callback) self.img_sub = rospy.Subscriber("/usb_cam/image_raw", Image, self.img_callback) # self.img_pub = rospy.Publisher('face_img', Image, queue_size=10) self.name_pub = rospy.Publisher('face_names', StringArray, queue_size=10) self.all_names_pub = rospy.Publisher('all_face_names', StringArray, queue_size=10) rospy.loginfo("Detecting faces...")
def __init__(self, recognition, modelType=None, threshold=None): """ Create a FaceRecognizer and train it on the given images """ self._recognition = recognition self.config = ConfigParser.ConfigParser() self.config.read("config.ini") if threshold is None: self.threshold = int(self.config.get("Alg Parameters", "threshold")) else: self.threshold = threshold if self._recognition: if modelType is None: modelType = self.config.get("Alg Parameters", "recognitionModel") if modelType == self.EIGEN_MODEL: self.model = cv2.createEigenFaceRecognizer() elif modelType == self.FISHER_MODEL: self.model = cv2.createFisherFaceRecognizer() elif modelType == self.LBPH_MODEL: self.model = cv2.createLBPHFaceRecognizer() print "Inizializing face recognizer model: " + modelType + "..." self.model, self.nameList = self.trainModel(self.model) self._matchCounter = Counter() # captured subjects or unknowns self._bestUsersMatch = Counter() self._totalMatches = 0 self._countMatchElem = 0 self.frameFaceCounter = 0
def main(self): for fold in self.walk_dir(config.POSITIVE_DIR): if not os.path.exists(config.TRAIN_DIR + fold): os.makedirs(config.TRAIN_DIR + fold) print "Reading training images..." faces = [] labels = [] pos_count = 0 neg_count = 0 count = 0 List = UserData.UserData() pose_list = config.LIST_DIR + fold + '.pkl' folder_path = config.POSITIVE_DIR List.WriteList(pose_list, folder_path) List.ReadList(pose_list, folder_path) # Read all positive images for filename in self.walk_files(config.POSITIVE_DIR + fold, '*.pgm'): faces.append(self.prepare_image(filename)) labels.append(config.POSITIVE_LABEL) pos_count += 1 # Read all negative images for filename in self.walk_files(config.NEGATIVE_DIR, '*.pgm'): faces.append(self.prepare_image(filename)) labels.append(config.NEGATIVE_LABEL) neg_count += 1 print 'Read', pos_count, 'positive images and', neg_count, 'negative images.' # Train model print 'Training model...' model = cv2.createEigenFaceRecognizer() model.train(np.asarray(faces), np.asarray(labels)) # Save model results trainfile = os.path.join(config.TRAIN_DIR + fold, config.TRAINING_FILE) model.save(trainfile) print 'Training data saved to', config.TRAIN_DIR + fold, config.TRAINING_FILE # Save mean and eignface images which summarize the face recognition model. meanfile = os.path.join(config.TRAIN_DIR + fold, MEAN_FILE) positivefile = os.path.join(config.TRAIN_DIR + fold, POSITIVE_EIGENFACE_FILE) negativefile = os.path.join(config.TRAIN_DIR + fold, NEGATIVE_EIGENFACE_FILE) mean = model.getMat("mean").reshape(faces[0].shape) cv2.imwrite(meanfile, self.normalize(mean, 0, 255, dtype=np.uint8)) eigenvectors = model.getMat("eigenvectors") pos_eigenvector = eigenvectors[:, 0].reshape(faces[0].shape) cv2.imwrite( positivefile, self.normalize(pos_eigenvector, 0, 255, dtype=np.uint8)) neg_eigenvector = eigenvectors[:, 1].reshape(faces[0].shape) cv2.imwrite( negativefile, self.normalize(neg_eigenvector, 0, 255, dtype=np.uint8)) count += 1 else: execfile('admin.py')
def recognize(image, model_path, confidence): model = cv2.createEigenFaceRecognizer(threshold=THRESHOLD) model.load(model_path) image = cv2.resize(image, (256,256)) [p_label, p_confidence] = model.predict(image) print "Predicted label = %d (confidence=%.2f)" % (p_label, p_confidence) path = os.path.join(os.path.dirname(__file__), 'faces') subject = "UNKNOWN"; # If the model found something, print the file path if p_label > -1: count = 0 for dirname, dirnames, filenames in os.walk(path): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) if (count == p_label): for filename in os.listdir(subject_path): subject = subdirname count = count+1 if (p_confidence < confidence): print "hello %s" %subject else: print "not authorized" p_label = -1 return p_label, p_confidence, subject
def train(): #train the model with EigenFaceRecognizer model = cv2.createEigenFaceRecognizer() X,y,names_of_images = read_images(path) model.train(np.asarray(X), np.asarray(y)) #print("Training Finished") return model,names_of_images
def train_opencv(train_i, img_h, img_w, total_image_num, person_num, datacsv_file): lbphrecognizer = cv2.createLBPHFaceRecognizer() eigenrecognizer = cv2.createEigenFaceRecognizer() fisherrecognizer = cv2.createFisherFaceRecognizer() images, labels = get_images_and_labels(data_csvfile=datacsv_file, img_h=img_h, img_w=img_w, total_image_num=total_image_num) train_data = numpy.empty(((train_i * person_num, img_h, img_w)), dtype=int) train_label = numpy.empty(train_i * person_num, dtype=int) num_set = total_image_num / person_num for s in range(20): train_data[s * train_i:s * train_i + train_i] = images[s * num_set:s * num_set + train_i] train_label[s * train_i:s * train_i + train_i] = labels[s * num_set:s * num_set + train_i] lbphrecognizer.train(train_data, numpy.array(train_label)) lbphrecognizer.save("./LBPH_train_num_%s.xml" % (str(train_i))) fisherrecognizer.train(train_data, numpy.array(train_label)) fisherrecognizer.save("./fisher_train_num_%s.xml" % (str(train_i))) eigenrecognizer.train(train_data, numpy.array(train_label)) eigenrecognizer.save("./eigen_train_num_%s.xml" % (str(train_i)))
def main(): parser = argparse.ArgumentParser() lfwDefault = os.path.expanduser( "~/openface/data/lfw/dlib.affine.sz:96.OuterEyesAndNose") parser.add_argument('--lfwAligned', type=str, default=lfwDefault, help='Location of aligned LFW images') parser.add_argument('--networkModel', type=str, help="Path to Torch network model.", default=os.path.join(openfaceModelDir, 'nn4.small2.v1.t7')) parser.add_argument('--largeFont', action='store_true') parser.add_argument('workDir', type=str, help='The work directory where intermediate files and results are kept.') args = parser.parse_args() # print(args) if args.largeFont: font = {'family': 'normal', 'size': 20} mpl.rc('font', **font) mkdirP(args.workDir) print("Getting lfwPpl") lfwPplCache = os.path.join(args.workDir, 'lfwPpl.pkl') lfwPpl = cacheToFile(lfwPplCache)(getLfwPplSorted)(args.lfwAligned) print("Eigenfaces Experiment") cls = cv2.createEigenFaceRecognizer() cache = os.path.join(args.workDir, 'eigenFacesExp.pkl') eigenFacesDf = cacheToFile(cache)(opencvExp)(lfwPpl, cls) print("Fisherfaces Experiment") cls = cv2.createFisherFaceRecognizer() cache = os.path.join(args.workDir, 'fisherFacesExp.pkl') fishFacesDf = cacheToFile(cache)(opencvExp)(lfwPpl, cls) print("LBPH Experiment") cls = cv2.createLBPHFaceRecognizer() cache = os.path.join(args.workDir, 'lbphExp.pkl') lbphFacesDf = cacheToFile(cache)(opencvExp)(lfwPpl, cls) print("OpenFace CPU/SVM Experiment") net = openface.TorchNeuralNet(args.networkModel, 96, cuda=False) cls = SVC(kernel='linear', C=1) cache = os.path.join(args.workDir, 'openface.cpu.svm.pkl') openfaceCPUsvmDf = cacheToFile(cache)(openfaceExp)(lfwPpl, net, cls) print("OpenFace GPU/SVM Experiment") net = openface.TorchNeuralNet(args.networkModel, 96, cuda=True) cache = os.path.join(args.workDir, 'openface.gpu.svm.pkl') openfaceGPUsvmDf = cacheToFile(cache)(openfaceExp)(lfwPpl, net, cls) plotAccuracy(args.workDir, args.largeFont, eigenFacesDf, fishFacesDf, lbphFacesDf, openfaceCPUsvmDf, openfaceGPUsvmDf) plotTrainingTime(args.workDir, argrs.largeFont, eigenFacesDf, fishFacesDf, lbphFacesDf, openfaceCPUsvmDf, openfaceGPUsvmDf) plotPredictionTime(args.workDir, args.largeFont, eigenFacesDf, fishFacesDf, lbphFacesDf, openfaceCPUsvmDf, openfaceGPUsvmDf)
def learnCollectedFaces(preprocessedFaces, faceLabels, facerecAlgorithm, recognizer): print "Learning the collected faces using the {0} algorithm...".format(facerecAlgorithm) # Make sure the "contrib" module is dynamically loaded at runtime # Requires OpenCV v2.4.1 or later (from June 2012), otherwise the FaceRecognizer will not compile or run # haveContribModule = # if not haveContribModule: # print "contrib module is needed for facerecognizer" # sys.exit() # create recognizer depending on the defined algorithm faceLabels = np.array(faceLabels) if facerecAlgorithm == 'Fisherfaces': recognizer = cv2.createFisherFaceRecognizer() elif facerecAlgorithm == 'Eigenfaces': recognizer = cv2.createEigenFaceRecognizer() else: recognizer = cv2.createLBPHFaceRecognizer() # faceLabels = np.array(faceLabels) print np.unique(faceLabels) recognizer.train(preprocessedFaces, faceLabels) return recognizer
def load_data(): train.train_classifier() train.train_classifier1() #Load training data into model print 'Loading training data...' model = cv2.createEigenFaceRecognizer() #Trianed classifier model.load(config.TRAINING_FILE) model1 = cv2.createEigenFaceRecognizer() model1.load(config.TRAINING_FILE1) print 'Training data loaded!' return model,model1
def __init__(self): self.node_name = "train_faces_eigen" rospy.init_node(self.node_name) rospy.on_shutdown(self.cleanup) self.bridge = CvBridge() self.size = 4 face_haar = 'haarcascade_frontalface_default.xml' self.haar_cascade = cv2.CascadeClassifier(face_haar) self.face_dir = 'face_data_eigen' self.face_name = sys.argv[1] self.path = os.path.join(self.face_dir, self.face_name) # self.model = cv2.createFisherFaceRecognizer() self.model = cv2.createEigenFaceRecognizer() self.cp_rate = 5 if not os.path.isdir(self.path): os.mkdir(self.path) self.count = 0 self.train_img_sub = rospy.Subscriber("/usb_cam/image_raw", Image, self.img_callback) # self.train_img_pub = rospy.Publisher('train_face', Image, queue_size=10) rospy.loginfo("Capturing data...")
def create_eigenmodel(): x, y = [], [] SIZES = (256, 256) image_list = glob.glob(average_image_file_path) image_list.sort() # Read images i = 0 for image_path in image_list: image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) rects = get_faces_rect(image) for (x1, y1, w, h) in rects: cropped = np.copy(image[y1:y1+h, x1:x1+w]) cropped = cv2.resize(cropped, SIZES) x.append(np.asarray(cropped, dtype=np.uint8)) y.append(i) i = i + 1 # Convert labels to np array y = np.asarray(y, dtype=np.int32) # Eigenfaces model model = cv2.createEigenFaceRecognizer() # Train our model model.train(np.asarray(x), np.asarray(y)) model.save(eigenmodel_xml_file_path)
def compareWith(self, eigenModelFile, detectedFilesDir): model = cv2.createEigenFaceRecognizer(threshold=self.threshold) # Load the model model.load(eigenModelFile) # Read the image we're looking for sampleImage = cv2.imread(self.file, cv2.IMREAD_GRAYSCALE) sampleImage = cv2.resize(sampleImage, (256,256)) # Look through the model and find the face it matches model_prediction = model.predict(sampleImage) [p_label, p_confidence] = model_prediction # Print the confidence levels # print "Predicted label = {0} (confidence={1})".format(p_label, p_confidence) # hold all the found images paths result_paths = [] # If the model found something, print the file path if (p_label > -1): count = 0 for dirname, dirnames, filenames in os.walk(detectedFilesDir): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) if (count == p_label): for filename in os.listdir(subject_path): result_paths.append(subject_path) count = count+1 return (result_paths, model_prediction)
def findPerson(path, smaple, threshold="100000.0"): # Create an Eign Face recogniser t = float(threshold) # t = float(sys.argv[3]) model = cv2.createEigenFaceRecognizer(threshold=t) # Load the model model.load("eigenModel.xml") # Read the image we're looking for sampleImage = cv2.imread(smaple, cv2.IMREAD_GRAYSCALE) # sampleImage = cv2.imread(sys.argv[2], cv2.IMREAD_GRAYSCALE) sampleImage = cv2.resize(sampleImage, (256,256)) # Look through the model and find the face it matches [p_label, p_confidence] = model.predict(sampleImage) # Print the confidence levels print "Predicted label = %d (confidence=%.2f)" % (p_label, p_confidence) # If the model found something, print the file path if (p_label > 0): # if (p_label > -1): count = 0 for dirname, dirnames, filenames in os.walk(path): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) if (count == p_label): for filename in os.listdir(subject_path): # print subject_path return subject_path count = count+1
def load_recognizer(file): recognizer = cv2.createEigenFaceRecognizer() t1 = time.time() recognizer.load(file) t2 = time.time() print 'Time for loading recognizer:', t2 - t1 print 'loading complete' return recognizer
def __init__(self, type, database, partition_percentage, num_components=None): if not num_components == None: if type == 1: self.model = cv.createEigenFaceRecognizer(num_components) else: self.model = cv.createFisherFaceRecognizer(num_components) else: if type == 1: self.model = cv.createEigenFaceRecognizer() else: self.model = cv.createFisherFaceRecognizer() self.manager = External_DB_Manager(partition_percentage) self.database = database
def recognize(model, image, threshold): emodel = cv2.createEigenFaceRecognizer(threshold=threshold) emodel.load(model) simg = cv2.imread(image, cv2.IMREAD_GRAYSCALE) simg = cv2.resize(simg, (256,256)) [p_label, p_confidence] = emodel.predict(simg) return (p_label, p_confidence)
def create_and_train_model_from_dict(label_matrix): # Create and train eigenface model model = cv2.createEigenFaceRecognizer() images = label_matrix.values() labels = numpy.array(label_matrix.keys()) #model.train() model.train(images, labels) return model
def useopencv(testcsv_file, train_i): csv_file = open(testcsv_file) data = csv.reader(csv_file) count_incorrect_fisher = 0.0 count_incorrect_eigen = 0.0 count_incorrect_lbph = 0.0 total_num_face = 0 fisherrecognizer = cv2.createFisherFaceRecognizer() lbphrecognizer = cv2.createLBPHFaceRecognizer() eigenrecognizer = cv2.createEigenFaceRecognizer() eigenrecognizer.load("./eigen_train_num_%s.xml" % (str(train_i))) lbphrecognizer.load("./LBPH_train_num_%s.xml" % (str(train_i))) fisherrecognizer.load("./fisher_train_num_%s.xml" % (str(train_i))) for csvdata2, csvlabel2 in data: # print csvdata # print csvlabel total_num_face = total_num_face + 1 f = csvdata2 l = int(csvlabel2) predict_image_pil = Image.open(f).convert('L') predict_image = numpy.array(predict_image_pil, 'uint8') nbr_predicted_fisher, conf2_fisher = fisherrecognizer.predict( predict_image[:]) nbr_predicted_eigen, conf2_eigen = eigenrecognizer.predict( predict_image[:]) nbr_predicted_lbph, conf2_lbph = lbphrecognizer.predict( predict_image[:]) nbr_actual = l if nbr_actual != nbr_predicted_fisher: #print "{} is Correctly Recognized with confidence {}".format(nbr_actual, conf) #else: #print "fisherrecognizer {}is Incorrect Recognized as {}".format(nbr_actual2, nbr_predicted2) count_incorrect_fisher = count_incorrect_fisher + 1.0 if nbr_actual != nbr_predicted_eigen: count_incorrect_eigen = count_incorrect_eigen + 1.0 if nbr_actual != nbr_predicted_lbph: count_incorrect_lbph = count_incorrect_lbph + 1.0 percentage_fisher = 100 - (count_incorrect_fisher / total_num_face) * 100 percentage_lbph = 100 - (count_incorrect_lbph / total_num_face) * 100 percentage_eigen = 100 - (count_incorrect_eigen / total_num_face) * 100 print "correct rate {} % in fisherrecognizer with {} trainning face".format( percentage_fisher, train_i) print "correct rate {} % in lbphrecognizer with {} trainning face".format( percentage_lbph, train_i) print "correct rate {} % in eigenrecognizer with {} trainning face".format( percentage_eigen, train_i)
def comp(): datab = request.form['comp'] #print datab #open image path to save after decode inital = open("limage/attempt.jpg", "wb") inital.write(datab.decode('base64')) inital.close() #open image and convert to pgm format second = Image.open('limage/attempt.jpg') second = second.convert('RGB') second.save('limage/attempt.pgm') print 'Loading training data...' #initalize opencv facerecognizer class model = cv2.createEigenFaceRecognizer() #loads xml training file creaded by train.py model.load(config.TRAINING_FILE) print 'Training data loaded!' print 'Capturing Profile...' #start loop to process users image while True: #read in converted pgm image and change to grayscale third= cv2.imread('limage/attempt.pgm') #print type(third) compare = cv2.cvtColor(third,cv2.COLOR_RGB2GRAY) #run face detect cv process result = face.detect_single(compare) if result is None: print 'Could not detect one face!' #return "User Not Detected" flash("User Not Detected! Please retake image", 'danger') return render_template('facelogin.html') break x, y, w, h = result # Crop and resize image to face. crop = face.resize(face.crop(compare, x, y, w, h)) #write debug image after crop and resize peformed cv2.imwrite('limage/debug.pgm',crop) #read croped image for model to process--prevents wrong shape matrices error final = cv2.imread('limage/debug.pgm',0) # Test user face against model label, confidence = model.predict(final) print 'Predicted face with confidence {1} (lower is more confident).'.format( 'POSITIVE' if label == config.POSITIVE_LABEL else 'NEGATIVE', confidence) #if confidence level is less than set threshold in config.py user is accepted if label == config.POSITIVE_LABEL and confidence < config.POSITIVE_THRESHOLD: #return 'Accepted User' flash("User Accepted", 'success') return render_template('facelogin.html') #user is denied if confidence level is greater than set threshold in config.py else: print 'Did not recognize user!' #return 'User Not Accepted !' flash("User Not Accepted!", 'danger') return render_template('facelogin.html')
def main(): # Load training data into model print 'Loading training data...' model = cv2.createEigenFaceRecognizer() model.load(config.TRAINING_FILE) print 'Training data loaded!' # Initialize camer and box. camera = config.get_camera() door = hardware.Door() # Move box to locked position. door.lock() print 'Running Lock...' print 'Press button to lock (if unlocked), or unlock if the correct face is detected.' print 'Press Ctrl-C to quit.' while True: try: # Check if capture should be made. # TODO: Check if button is pressed. if door.is_button_up() or is_letter_input('l'): if not door.is_locked: # Lock the door if it is unlocked door.lock() print 'Door is now locked.' else: print 'Button pressed, looking for face...' # Check for the positive face and unlock if found. image = camera.read() # Convert image to grayscale. image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # Get coordinates of single face in captured image. result = face.detect_single(image) if result is None: print 'Could not detect single face! Check the image in capture.pgm' \ ' to see what was captured and try again with only one face visible.' soundChannelC.play(soundC) sleep(.01) continue x, y, w, h = result # Crop and resize image to face. crop = face.resize(face.crop(image, x, y, w, h)) # Test face against model. label, confidence = model.predict(crop) print 'Predicted {0} face with confidence {1} (lower is more confident).'.format( 'POSITIVE' if label == config.POSITIVE_LABEL else 'NEGATIVE', confidence) if label == config.POSITIVE_LABEL and confidence < config.POSITIVE_THRESHOLD: print 'Recognized face! Unlocking Door Now...' door.unlock() soundChannelA.play(soundA) sleep(.01) else: print 'Did not recognize face!' soundChannelB.play(soundB) sleep(.01) except KeyboardInterrupt: door.clean() sys.exit()
def load(self, db_file_name): """ Update the face models data structure from a file. :type db_file_name: string :param db_file_name: the name of the file containing the dump of the face models data structure :rtype: boolean :returns: True if loading was successful """ if db_file_name is None: ''' Set the name of database. Algorithm : LBP (Local Binary Pattern) ''' db_file_name = self._db_name + '-' + self._algorithm tags_file_name = db_file_name + '-Tags' algorithm = ce.FACE_MODEL_ALGORITHM if self._params is not None: algorithm = self._params[ce.FACE_MODEL_ALGORITHM_KEY] model = None if algorithm == 'Eigenfaces': model = cv2.createEigenFaceRecognizer() elif algorithm == 'Fisherfaces': model = cv2.createFisherFaceRecognizer() elif algorithm == 'LBP': model = cv2.createLBPHFaceRecognizer() ok = False if os.path.isfile(db_file_name) and (os.path.isfile(tags_file_name)): if(not((ce.USE_TRACKING or ce.SIM_TRACKING or ce.USE_SLIDING_WINDOW) and ce.LOAD_IND_FRAMES_RESULTS)): model.load(db_file_name) if not(model is None): self.model = model self._tags = utils.load_YAML_file(tags_file_name) ok = True print('\n### DB LOADED ###\n') return ok
def __init__(self, algorithm='fisherface'): self.algorithm = algorithm if (algorithm == 'fisherface'): self.model = cv2.createFisherFaceRecognizer() elif (algorithm == 'eigenface'): self.model = cv2.createEigenFaceRecognizer() elif (algorithm == 'lbphf'): self.model = cv2.createLBPHFaceRecognizer() else: raise ValueError('Unknown algorithm: "%s"!' % (algorithm,))
def findFrame(frame, csvFile, haarcascade, scaleFactor=1.2, minNeighbors=8): global lastCSVFile, trained, recognizer, faceCascade, names if (trained == True and lastCSVFile <> csvFile): trained = False if (trained == False): trained = True lastCSVFile = csvFile file = open(csvFile) faceCascade = cv2.CascadeClassifier(haarcascade) images = [] names = [] labels = [] rownum = 0 reader = csv.reader(file, delimiter=';') for row in reader: if rownum == 0: header = row else: idx = row[0] name = row[1] path = row[2] if isfile(path) and path.endswith('.jpg'): img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) img_to_save = cv2.resize(img, (100, 100)) images.append(img_to_save) names.append(name) labels.append(int(idx)) rownum += 1 file.close() print "starting recognizer" #recognizer = cv2.face.createLBPHFaceRecognizer() #recognizer = cv2.face.createEigenFaceRecognizer(10, 10.0) recognizer = cv2.createEigenFaceRecognizer() recognizer.train(images, np.array(labels)) print "done recognizer" gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) faces = faceCascade.detectMultiScale(gray, scaleFactor, minNeighbors) finds = [] for (x, y, w, h) in faces: img_to_check = cv2.resize(gray[y:y + h, x:x + w], (100, 100)) nbr_predicted, conf = recognizer.predict(img_to_check) if nbr_predicted > 0 and conf < 4000: finds.append( '{"name": "%s", "x": "%s", "y": "%s", "w": "%s", "h": "%s"}' % (names[nbr_predicted], x, y, w, h)) return finds
def main(): arg = ([], []) os.path.walk(sys.argv[1], output, arg) print "Training Fisher" r = cv2.createFisherFaceRecognizer() r.train(arg[0], numpy.array(arg[1])) r.save('ricbit.fisher.xml') print "Training Eigen" s = cv2.createEigenFaceRecognizer(num_components=9) s.train(arg[0], numpy.array(arg[1])) s.save('ricbit.eigen.xml')
def __init__(self): cascPath = "haarcascade_frontalface_default.xml" self.face_cascade = cv2.CascadeClassifier(cascPath) self.face_dir = 'face_data' self.face_name = sys.argv[1] self.path = os.path.join(self.face_dir, self.face_name) if not os.path.isdir(self.path): os.mkdir(self.path) self.model = cv2.createEigenFaceRecognizer() self.count_captures = 0 self.count_timer = 0
def __init__(self, images, labels): """ Initialization and training images: training set of images labels: labels for training images """ self.images = images self.labels = labels self.model = cv2.createEigenFaceRecognizer() self.model.train(images, np.array(labels))
def createLearner(path = "../../data/"): db = server.Server() db.connect() tup = db.getMapping() # Reverse the mapping so we can map folder names to their index value mapping = dict(map(reversed,tup)) [X,Y] = extractData(path,mapping) y = np.asarray(Y,dtype=np.int32) learner = cv2.createEigenFaceRecognizer(40,35000.0) learner.train(np.asarray(X),np.asarray(y)) learner.save("../../metadata/learner.xml")
def create_and_train_model_from_dict(label_matrix, type): # Create and train eigenface model if type == 'lbph': model = cv2.createLBPHFaceRecognizer() elif type == 'eigen': model = cv2.createEigenFaceRecognizer() elif type == 'fisher': model = cv2.createFisherFaceRecognizer() images = label_matrix.values() labels = numpy.array(label_matrix.keys()) model.train(images, labels) return model
def create_face_identity(self): image_count = 0 time_limit = time.time() + config.TRAINING_TASK_TIMEOUT training_images = list() self.flag_require_light_on = True # start training task while image_count < config.NUM_SAMPLED_TRAINING_IMAGES and time.time() < time_limit: progress_text = 'training... %d %%' % (image_count * 100 // config.NUM_SAMPLED_TRAINING_IMAGES) _, orig_image = self.camera.read() # get coordinates of single face in captured image gray_image = cv2.cvtColor(orig_image, cv2.COLOR_RGB2GRAY) result = detect_single_face(gray_image) # show captured image if result is None: orig_image = flip_image(orig_image) cv2.putText(orig_image, progress_text, (10, 30), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 240, 240), 1, 8) cv2.putText(orig_image, 'no face detected', (10, 60), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 255), 1, 8) self.gui_service.camera_image = orig_image continue x, y, w, h = result cv2.rectangle(orig_image, (x, y), (x + w, y + h), (0, 255, 0), 2) orig_image = flip_image(orig_image) cv2.putText(orig_image, progress_text, (10, 30), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 240, 240), 1, 8) self.gui_service.camera_image = orig_image cropped_image = resize_image(crop_image(gray_image, x, y, w, h)) training_images.append(cropped_image) image_count += 1 self.flag_require_light_on = False # return None if timeout if image_count == 0: return None # train model labels = [POSITIVE_LABEL] * len(training_images) # create the label array model = cv2.createEigenFaceRecognizer() model.train(numpy.asarray(training_images), numpy.asarray(labels)) # obtain the result with tempfile.NamedTemporaryFile() as tmp_file: model.save(tmp_file.name) model_description = tmp_file.read() return model_description
def __init__(self): #cascPath = "haarcascade_frontalface_default.xml" self.face_cascade = cv2.CascadeClassifier( 'haarcascade_frontalface_alt.xml') self.face_dir = 'face_data' PERSON_NAME = raw_input("Enter Name: ") self.face_name = PERSON_NAME self.path = os.path.join(self.face_dir, self.face_name) if not os.path.isdir(self.path): os.mkdir(self.path) self.model = cv2.createEigenFaceRecognizer() self.count_captures = 0 self.count_timer = 0
def __init__(self): self.imageTable = {} self.learnerList = None self.retVal = None self.learner = cv2.createEigenFaceRecognizer(40,35000.0) db = server.Server() db.connect() tup = db.getMapping() self.imageTable = dict(tup) if(os.path.isfile("../../metadata/learner.xml")): self.learner.load("../../metadata/learner.xml") else: print "Learner not found, please make sure learner.xml is in the appropriate file"
def _recognizer(self): recognizer = None if self.model_name == 'Eigen': recognizer = cv2.createEigenFaceRecognizer() elif self.model_name == 'Fisher': #self.size = 300,300 recognizer = cv2.createFisherFaceRecognizer() elif self.model_name == 'LBPH': recognizer = cv2.createLBPHFaceRecognizer(threshold=200) else: raise Exception('Unknown face recognition model "%s"' % (self.model_name)) return recognizer
def Eigen(data_dir, out_dir): face_recognizer = cv2.createEigenFaceRecognizer(5) print 'start reading images in {0}'.format(data_dir) images, labels, names = read_images(data_dir, resize=True) save_names(names, out_dir) print 'start training face recognizer' face_recognizer.train(images, labels) model_path = os.path.join(out_dir, 'Eigen.yml')# LBPH.yml, Eigen.yml, Fisher.yml print 'save trained model to {0}'.format(model_path) face_recognizer.save(model_path)
def __init__(self, face_type): self._type = ['eigen', 'fisher', 'lbph'] if face_type not in self._type: raise ValueError("you must be chose in ['eigen', 'fisher', 'lbph']") if face_type == 'eigen': self._model = cv2.createEigenFaceRecognizer(threshold=1000) if face_type == 'fisher': self._model = cv2.createFisherFaceRecognizer(threshold=1000) if face_type == 'lbph': self._model = cv2.createLBPHFaceRecognizer(threshold=100)
def main(argv): pid = int(sys.argv[1]) print 'PID is: ', pid # Load training data into model print 'Loading training data...' model = cv2.createEigenFaceRecognizer() print 'Model created' model.load(config.TRAINING_FILE) print 'Training data loaded!' # Initialize camera and box. camera = config.get_camera() print 'Press Ctrl-C to quit.' goodpicture = False; while goodpicture == False: print 'Looking for face...' print 'Check for the positive face and unlock if found.' image = camera.read() print 'Convert image to grayscale.' image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) print 'Get coordinates of single face in captured image.' result = face.detect_single(image) if result is None: print 'Could not detect single face! Check the image in capture.pgm to see what was captured and try again with only one face visible.' #continue else: goodpicture = True; x, y, w, h = result print 'Crop and resize image to face.' crop = face.resize(face.crop(image, x, y, w, h)) print 'Test face against model.' label, confidence = model.predict(crop) print 'Predicted {0} face with confidence {1} (lower is more confident).'.format( 'POSITIVE' if label == config.POSITIVE_LABEL else 'NEGATIVE', confidence) print 'Starting to print in file' fo = open("foo.txt", "wr") if label == config.POSITIVE_LABEL and confidence < config.POSITIVE_THRESHOLD: print 'Recognized face!' fo.write("recognized") else: print 'Did not recognize face!' fo.write("echec") fo.close() os.kill(pid, signal.SIGUSR2)
def load(self): threshold = self.get_threshold(self.algorithm) if self.algorithm == 1: self.model = cv2.createLBPHFaceRecognizer(threshold=threshold) self.training_file = "training_lbp.xml" elif self.algorithm == 2: self.model = cv2.createFisherFaceRecognizer(threshold=threshold) self.training_file = "training_fisher.xml" else: self.model = cv2.createEigenFaceRecognizer(threshold=threshold) self.training_file = "training_eigen.xml" self.model.load( os.path.join(self.training_file_dir, self.training_file))
def create_pokemon_eigenface_model(filenameList, threshold=100.0): imageList = [] labelList = numpy.arange(len(filenameList)) for i, imName in enumerate(filenameList): tmp = cv2.imread(imName, cv2.IMREAD_UNCHANGED) tmp[numpy.where(tmp[:, :, 3] == 0)] = 255 tmpGrey = cv2.cvtColor(tmp, cv2.COLOR_BGR2GRAY) imageList.append(tmpGrey) model = cv2.createEigenFaceRecognizer(threshold) model.train(imageList, labelList) return imageList, model
def __init__(self): self.debug_image = "debug.pgm" self.face_cascade = cv2.CascadeClassifier( 'haarcascade_frontalface_alt.xml') self.face_dir = 'face_data' if not os.path.isdir(self.face_dir): os.mkdir(self.face_dir) person_name = raw_input("Enter name:") self.face_name = person_name self.path = os.path.join(self.face_dir, self.face_name) if not os.path.isdir(self.path): os.mkdir(self.path) self.model = cv2.createEigenFaceRecognizer() self.count_captures = 0
def create_pokemon_eigenface_model(filenameList, threshold=100.0): imageList = [] labelList = numpy.arange(len(filenameList)) for i, imName in enumerate(filenameList): tmp = cv2.imread(imName, cv2.IMREAD_UNCHANGED) tmp[numpy.where(tmp[:,:,3]==0)] = 255 tmpGrey = cv2.cvtColor(tmp, cv2.COLOR_BGR2GRAY) imageList.append(tmpGrey) model = cv2.createEigenFaceRecognizer(threshold) model.train(imageList, labelList) return imageList, model
def recognize_face(self, model_descriptions): # create face recognizers trained_models = list() self.flag_require_light_on = True for description in model_descriptions: with tempfile.NamedTemporaryFile() as tmp_file: tmp_file.file.write(description) tmp_file.flush() model = cv2.createEigenFaceRecognizer() model.load(tmp_file.name) trained_models.append(model) # start face recognition task face_count = 0 time_limit = time.time() + config.RECOGNITION_TASK_TIMEOUT while face_count < config.NUM_SAMPLED_TESTING_IMAGES and time.time() < time_limit: # try to recognize a face _, orig_image = self.camera.read() gray_image = cv2.cvtColor(orig_image, cv2.COLOR_RGB2GRAY) result = detect_single_face(gray_image) # show captured image to screen if result is None: orig_image = flip_image(orig_image) cv2.putText(orig_image, 'Recognizing...', (10, 30), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 240, 240), 1, 8) self.gui_service.camera_image = orig_image continue x, y, w, h = result cv2.rectangle(orig_image, (x, y), (x + w, y + h), (0, 255, 0), 2) orig_image = flip_image(orig_image) cv2.putText(orig_image, 'Recognizing...', (10, 30), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 240, 240), 1, 8) self.gui_service.camera_image = orig_image # calculate confidence and vote face_count += 1 cropped_image = resize_image(crop_image(gray_image, x, y, w, h)) for model in trained_models: label, confidence = model.predict(cropped_image) if label == POSITIVE_LABEL and confidence < config.CONFIDENCE_THRESHOLD: self.flag_require_light_on = False return True self.flag_require_light_on = False return False
def findFrame(frame, csvFile, haarcascade, scaleFactor = 1.2, minNeighbors = 8): global lastCSVFile, trained, recognizer, faceCascade, names if (trained == True and lastCSVFile <> csvFile): trained = False if (trained == False): trained = True lastCSVFile = csvFile file = open(csvFile) faceCascade = cv2.CascadeClassifier(haarcascade) images = [] names = [] labels = [] rownum = 0 reader = csv.reader(file, delimiter=';') for row in reader: if rownum == 0: header = row else: idx = row[0] name = row[1] path = row[2] if isfile(path) and path.endswith('.jpg'): img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) img_to_save = cv2.resize(img, (100, 100)) images.append(img_to_save) names.append(name) labels.append(int(idx)) rownum += 1 file.close() print "starting recognizer" #recognizer = cv2.face.createLBPHFaceRecognizer() #recognizer = cv2.face.createEigenFaceRecognizer(10, 10.0) recognizer = cv2.createEigenFaceRecognizer() recognizer.train(images, np.array(labels)) print "done recognizer" gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) faces = faceCascade.detectMultiScale(gray, scaleFactor, minNeighbors) finds = [] for (x, y, w, h) in faces: img_to_check = cv2.resize(gray[y: y + h, x: x + w], (100, 100)) nbr_predicted, conf = recognizer.predict(img_to_check) if nbr_predicted > 0 and conf < 4000: finds.append('{"name": "%s", "x": "%s", "y": "%s", "w": "%s", "h": "%s"}' % (names[nbr_predicted], x, y, w, h)) return finds
def load_model(self, db_file_name): """ Update the face models data structure for a single person from a file. :type db_file_name: string :param db_file_name: the name of the file containing the dump of the face models data structure :rtype: boolean :returns: True if loading was successful """ ok = False if db_file_name is None: print "No db file was provided" else: algorithm = ce.FACE_MODEL_ALGORITHM if self._params is not None: algorithm = self._params[ce.FACE_MODEL_ALGORITHM_KEY] model = None if algorithm == 'Eigenfaces': model = cv2.createEigenFaceRecognizer() elif algorithm == 'Fisherfaces': model = cv2.createFisherFaceRecognizer() elif algorithm == 'LBP': model = cv2.createLBPHFaceRecognizer() if os.path.isfile(db_file_name): model.load(db_file_name) if not(model is None): self.model = model ok = True return ok
def __init__(self): print "Recognizer instantiated !" self.lbphModel = cv2.createLBPHFaceRecognizer() self.eigenModel = cv2.createEigenFaceRecognizer() self.fisherModel = cv2.createFisherFaceRecognizer() self.model_path = "models" self.lbph_model_path = os.path.join(self.model_path, "lbphModel.xml") self.eigen_model_path = os.path.join(self.model_path, "eigenModel.xml") self.fisher_model_path = os.path.join(self.model_path, "fisherModel.xml") self.load_models() self.new_faces, self.new_labels = [], [] self.db = db.Database()
def __init__(self, dir): # three algorithms for face comparison self.eigen = cv2.createEigenFaceRecognizer(num_components=80) self.fisher = cv2.createFisherFaceRecognizer() self.lbph = cv2.createLBPHFaceRecognizer() # Viola-Jones algorithm for face-detection w/in training and test images cascadePath = "../face_detection/haarcascade_frontalface_alt2.xml" self.face_cascade = cv2.CascadeClassifier(cascadePath) self.int_names = {} # models need numeric labels for training; correlates labels to actual names self.avg_width = 0 # for image resizing self.avg_height = 0 self.thresholds = [7000, 5000, 250]#[8000,5000,240]#[6000, 5300, 220] # train the models self.train(dir)