def face_gen(image_path, face_output): # Load the jpg file into a numpy array image = face_recognition_api.load_image_file(image_path) # Find all the faces in the image using a pre-trained convolutional neural network. # This method is more accurate than the default HOG model, but it's slower # unless you have an nvidia GPU and dlib compiled with CUDA extensions. But if you do, # this will use GPU acceleration and perform well. # See also: find_faces_in_picture.py face_locations = face_recognition_api.face_locations( image ) #face_recognition.face_locations(image, number_of_times_to_upsample=0, model="cnn") print("I found {} face(s) in this photograph.".format(len(face_locations))) if len(face_locations) < 1: outname = face_output.split('/')[-1] shutil.copy(image_path, 'trainData2face/zero_face/' + outname) for face_location in face_locations: # Print the location of each face in this image top, right, bottom, left = face_location print( "A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}" .format(top, left, bottom, right)) # You can access the actual face itself like this: face_image = image[top:bottom, left:right] pil_image = Image.fromarray(face_image) pil_image.save(face_output)
def create_store(fileName, name, fname, age, mob): try: img = face_recognition_api.load_image_file(fileName) imgEncoding = face_recognition_api.face_encodings(img) if len(imgEncoding) > 1: print('More than one face found in the image') if len(imgEncoding) == 0: print('No Face found in the Image') else: print('Encoded successfully.') encoded = convert_encoding(imgEncoding) name = name.replace(' ', '*') fname = fname.replace(' ', '*') print(name) print(fname) uniqueKey = str(name) + '@' + str(age) + '@' + str(fname) + '@' + str( mob) print(uniqueKey) root = db.reference('stationID') new_user = root.child('ABC123').child('pending').child(uniqueKey).set( {'encoded': encoded}) print('Done') return "YES" except: return "NO"
def scan_known_people(known_people_folder): known_names = [] known_face_encodings = [] for file in image_files_in_folder(known_people_folder): basename = os.path.splitext(os.path.basename(file))[0] img = face_recognition_api.load_image_file(file) encodings = face_recognition_api.face_encodings(img) if len(encodings) == 0: print("No faces") else: print("Found") known_names.append(basename) known_face_encodings.append(encodings[0]) return known_names, known_face_encodings
def create_dataset(training_dir_path, labels): X = [] for i in _zipped_folders_labels_images(training_dir_path, labels): for fileName in i[2]: file_path = os.path.join(i[0], fileName) img = face_recognition_api.load_image_file(file_path) imgEncoding = face_recognition_api.face_encodings(img) if len(imgEncoding) > 1: print('\x1b[0;37;43m' + 'More than one face found in {}. Only considering the first face.'.format(file_path) + '\x1b[0m') if len(imgEncoding) == 0: print('\x1b[0;37;41m' + 'No face found in {}. Ignoring file.'.format(file_path) + '\x1b[0m') else: print('Encoded {} successfully.'.format(file_path)) X.append(np.append(imgEncoding[0], i[1])) return X
def find_key_pts(): key_pts = [] os.chdir('../') with open('images/locations.txt', 'r') as f: locations = f.read() locations = locations.split('\n') for l in locations: l = l.replace(' ', ',') l = l.split(',') image = l[0] loc = l[1] path = os.path.join('images', image) img = face_recognition_api.load_image_file(path) faces_encodings = face_recognition_api.face_encodings(img) if faces_encodings: key_pts.append([faces_encodings, image, loc]) return key_pts
def load_all(self): results = self.db.select( 'SELECT faces.id, faces.user_id, faces.filename, faces.created FROM faces' ) self.layer_size = 0 count = 0 for row in results: user_id = row[1] filename = row[2] face = { "id": row[0], "user_id": user_id, "filename": filename, "created": row[3] } self.faces.append(face) face_image = face_recognition_api.load_image_file( self.load_train_file_by_name(filename)) face_image_encoding = face_recognition_api.face_encodings( face_image)[0] index_key = len(self.known_encoding_faces) self.known_encoding_faces.append(face_image_encoding) index_key_string = str(index_key) self.face_user_keys['{0}'.format(index_key_string)] = user_id print('user_id', user_id) if count == 0: self.layer_size = len(face_image_encoding) self.tree = AnnoyIndex(self.layer_size, metric) # prepare index self.tree.add_item(user_id, face_image_encoding) count += 1 print 'building index...\n' if self.layer_size > 0: print 'layer_size=', self.layer_size self.tree.build(ntrees) self.tree.save('index.ann')
def recognize(self, unknown_filename): tree = loadannoy() (unfile, unfile_face) = self.load_unknown_file_by_name(unknown_filename) unknown_image = face_recognition_api.load_image_file(unfile) unknown_encoding_image = face_recognition_api.face_encodings( unknown_image)[0] #results = face_recognition.compare_faces(self.known_encoding_faces, unknown_encoding_image); results2 = find_matching_id(unknown_encoding_image, tree) guess_age = age_predict.predict([unfile_face]) guess_gender = gender_predict.predict([unfile_face]) #print("results", results) print("results2", results2) if results2: matching_id, min_dist = results2 user_id = matching_id #self.load_user_by_index_key(matching_id) return (user_id, guess_age, guess_gender) return ('unknown', guess_age, guess_gender) '''
y = np.array(full_data[:, -1:]) if os.path.isfile(fname): with open(fname, 'rb') as f: (le, clf) = pickle.load(f) else: print('\x1b[0;37;43m' + "Classifier '{}' does not exist".format(fname) + '\x1b[0m') quit() for image_path in get_prediction_images(prediction_dir): # print colorful text with image name print('\x1b[6;30;42m' + "=====Predicting faces in '{}'=====".format(image_path) + '\x1b[0m') img = face_recognition_api.load_image_file(image_path) X_faces_loc = face_recognition_api.face_locations(img) faces_encodings = face_recognition_api.face_encodings( img, known_face_locations=X_faces_loc) print("Found {} faces in the image".format(len(faces_encodings))) closest_distances = clf.kneighbors(faces_encodings, n_neighbors=1) is_recognized = [ closest_distances[0][i][0] <= 0.5 for i in range(len(X_faces_loc)) ] # predict classes and cull classifications that are not with high confidence predictions = [(le.inverse_transform(int(pred)).title(), loc) if rec else ("Unknown", loc)
def main(): fname = 'classifier.pkl' prediction_dir = './test-images' encoding_file_path = './encoded-images-data.csv' df = pd.read_csv(encoding_file_path) full_data = np.array(df.astype(float).values.tolist()) # Extract features and labels # remove id column (0th column) X = np.array(full_data[:, 1:-1]) y = np.array(full_data[:, -1:]) if os.path.isfile(fname): with open(fname, 'rb') as f: (le, clf) = pickle.load(f) else: print('\x1b[0;37;43m' + "Classifier '{}' does not exist".format(fname) + '\x1b[0m') quit() for image_path in get_prediction_images(prediction_dir): # print colorful text with image name print('\x1b[6;30;42m' + "=====Predicting faces in '{}'=====".format(image_path) + '\x1b[0m') img = face_recognition_api.load_image_file(image_path) X_faces_loc = face_recognition_api.face_locations(img) faces_encodings = face_recognition_api.face_encodings( img, known_face_locations=X_faces_loc) print("Found {} faces in the image".format(len(faces_encodings))) closest_distances = clf.kneighbors(faces_encodings, n_neighbors=1) is_recognized = [ closest_distances[0][i][0] <= 0.5 for i in range(len(X_faces_loc)) ] # store=[] # # for pred, loc, rec in zip(clf.predict(faces_encodings), X_faces_loc, is_recognized): # a=le.inverse_transform(int(pred)).title() # b=loc # # if rec: # store.append([a,b]) # else: # store.append("unknown", loc) # predict classes and cull classifications that are not with high confidence predictions = [(le.inverse_transform([int(pred)])[0], loc) if rec else ("Unknown", loc) for pred, loc, rec in zip(clf.predict(faces_encodings), X_faces_loc, is_recognized)] print(predictions) # for face_encoding in faces_encodings: # face_encoding = face_encoding.reshape(1, -1) # # predictions = clf.predict_proba(face_encoding).ravel() # maxI = np.argmax(predictions) # person = le.inverse_transform(maxI) # confidence = predictions[maxI] # print("Predict {} with {:.2f} confidence.".format(person, confidence)) print()