def face_Encode(self): name = self.textEdit.toPlainText() title = self.textEdit_2.toPlainText() encodingsBox = [] namesBox = [] titlesBox = [] cap = cv2.VideoCapture(0) time.sleep(1) while True: ret, frame = cap.read() if ret == True: rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) boxes = face_recognition.face_locations(rgb_frame, model="hog") encodings = face_recognition.face_encodings(rgb_frame, boxes) for encoding in encodings: encodingsBox.append(encoding) namesBox.append(name) titlesBox.append(title) cv2.imshow("Frame", frame) if cv2.waitKey(1) == 27 & 0xff: break data = { 'encodings': encodingsBox, 'names': namesBox, 'titles': titlesBox } f = open("Models/encodings.pickle", "wb") f.write(pickle.dumps(data)) f.close() cap.release() cv2.destroyAllWindows()
def get_vector(image_path): # Load the jpg file into a numpy array image = face_recognition.load_image_file(image_path) face_locations = face_recognition.face_locations(image) face_encodings = face_recognition.face_encodings(image, face_locations) return face_encodings
def drawRectangle(image, known_encodings): status = False # Find all the faces and face encodings in the unknown image face_locations = fr.face_locations(image) known_face_names = ["Michael Reeves", "Michael Reeves"] face_encodings = fr.face_encodings(image, face_locations) # Convert the image to a PIL-format image so that we can draw on top of it with the Pillow library # See http://pillow.readthedocs.io/ for more about PIL/Pillow pil_image = Image.fromarray(image) # Create a Pillow ImageDraw Draw instance to draw with draw = ImageDraw.Draw(pil_image) for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): # See if the face is a match for the known face(s) matches = fr.compare_faces(known_encodings, face_encoding) name = "Unknown" # If a match was found in known_face_encodings, just use the first one. # if True in matches: # first_match_index = matches.index(True) # name = known_face_names[first_match_index] # Or instead, use the known face with the smallest distance to the new face face_distances = fr.face_distance(known_encodings, face_encoding) best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = known_face_names[best_match_index] # Draw a label with a name below the face pad = 10 text_width, text_height = draw.textsize(name) draw.rectangle(((left - pad, bottom - text_height - 10), (right + pad, bottom + pad)), fill=(255, 0, 0), outline=(255, 0, 0)) draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255)) # Draw a box around the face using the Pillow module draw.rectangle( ((left - pad, top - pad), (right + pad, bottom + pad)), outline=(255, 0, 0), width=3) status = True del draw buffered = BytesIO() pil_image.save(buffered, format="JPEG") img_str = base64.b64encode(buffered.getvalue()) return [status, img_str]
def recognize_faces(self, msg): # Grab a single frame of video frame = image_to_numpy(msg) if self.process_frame: # Resize frame of video to 1/4 size for faster face recognition processing small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) rgb_small_frame = small_frame[:, :, ::-1] # Find all the faces and face encodings in the current frame of video _face_locations = face_locations(rgb_small_frame) _face_encodings = face_encodings(rgb_small_frame, _face_locations) face_names = [] for face_encoding in _face_encodings: # See if the face is a match for the known face(s) matches = compare_faces(known_face_encodings, face_encoding) name = "Unknown" # If a match was found in known_face_encodings, just use the first one. if True in matches: first_match_index = matches.index(True) name = known_face_names[first_match_index] face_names.append(name) # Display the results for (top, right, bottom, left), name in zip(_face_locations, face_names): # Scale back up face locations since the frame we detected in was scaled to 1/4 size top *= 4 right *= 4 bottom *= 4 left *= 4 # Draw a box around the face cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) # Draw a label with a name below the face cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) # Display the resulting image cv2.imshow('Face recognition', frame) cv2.waitKey(1) self.process_frame = not self.process_frame
def match(clf, filename): # Load the test image with unknown faces into a numpy array test_image = face_recognition.load_image_file(filename) # Find all the faces in the test image using the default HOG-based model face_locations = face_recognition.face_locations(test_image) no = len(face_locations) print("\nNumber of faces detected: ", no) # Predict all the faces in the test image using the trained classifier firstname = None print("\n(☞゚ヮ゚)☞ ☜(゚ヮ゚☜)\n") print("Found:") for i in range(no): test_image_enc = face_recognition.face_encodings(test_image)[i] name = clf.predict([test_image_enc]) probs = clf.predict_proba([test_image_enc]) print(*name) firstname = (str(name[0])) return (firstname, no)
def train(): # Training the SVC classifier # The training data would be all the face encodings from all the known images and the labels are their names encodings = [] names = [] # Training directory train_dir = os.listdir("train_dir/") # Loop through each person in the training directory for person in train_dir: pix = os.listdir("train_dir/" + person) # pix = [item for item in pix if not item.startswith('.') and os.path.isfile(os.path.join(root, item))] # Loop through each training image for the current person for person_img in pix: # Get the face encodings for the face in each image file if person_img == ".DS_Store": continue face = face_recognition.load_image_file( "train_dir/" + person + "/" + person_img ) face_bounding_boxes = face_recognition.face_locations(face) if len(face_bounding_boxes) == 1: face_enc = face_recognition.face_encodings(face)[0] # Add face encoding for current image with corresponding label (name) to the training data encodings.append(face_enc) names.append(person) # Create and train the SVC classifier clf = svm.SVC(gamma="scale", probability=True) clf.fit(encodings, names) dump(clf, 'clf.joblib') return clf
def Face_Recognition_(self, frame): small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) rgb_small_frame = small_frame[:, :, ::-1] face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings( rgb_small_frame, face_locations) face_names = [] face_titles = [] for face_encoding in face_encodings: matches = face_recognition.compare_faces(knownFE, face_encoding) name = "Unknown" title = "Unknown" if True in matches: first_match_index = matches.index(True) name = knownN[first_match_index] title = knownT[first_match_index] face_names.append(name) face_titles.append(title) for (top, right, bottom, left), name, title in zip(face_locations, face_names, face_titles): top *= 4 right *= 4 bottom *= 4 left *= 4 cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name + ": " + title, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) return frame, face_names, face_titles
from face_recognition.face_recognition import load_image_file, face_encodings, face_locations, compare_faces DIR = os.path.dirname(os.path.realpath(__file__)) # This is a demo of running face recognition on live video from your webcam. It's a little more complicated than the # other example, but it includes some basic performance tweaks to make things run a lot faster: # 1. Process each video frame at 1/4 resolution (though still display it at full resolution) # 2. Only detect faces in every other frame of video. # PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam. # OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this # specific demo. If you have trouble installing it, try any of the other demos that don't require it instead. # Load a sample picture and learn how to recognize it. obama_image = load_image_file(os.path.join(DIR, "obama.jpg")) obama_face_encoding = face_encodings(obama_image)[0] # Load a second sample picture and learn how to recognize it. biden_image = load_image_file(os.path.join(DIR, "biden.jpg")) biden_face_encoding = face_encodings(biden_image)[0] # Load a second sample picture and learn how to recognize it. emilka_image = load_image_file(os.path.join(DIR, "emilka.jpg")) emilka_face_encoding = face_encodings(emilka_image)[0] # Load a second sample picture and learn how to recognize it. wagram_image = load_image_file(os.path.join(DIR, "wagram.jpg")) wagram_face_encoding = face_encodings(wagram_image)[0] # Create arrays of known face encodings and their names
name = users.get_name_from_id(user) for imagePath in users.get_pictures_from_id(user): # load the input image and convert it from BGR (OpenCV ordering) # to dlib ordering (RGB) image = cv2.imread(imagePath) rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # detect the (x, y)-coordinates of the bounding boxes # corresponding to each face in the input image boxes = face_recognition.face_locations(rgb, \ model=args["detection_method"]) # compute the facial embedding for the face encodings = face_recognition.face_encodings(rgb, boxes) # loop over the encodings for encoding in encodings: # add each encoding + user(name) to our lists of known users and # encodings knownEncodings.append(encoding) knownUsers.append(user) # knownNames.append(name) # dump the facial encodings + names to disk print("[INFO] serializing encodings...") data = {"encodings": knownEncodings, "users": knownUsers} f = open(args["encodings"], "wb") f.write(pickle.dumps(data)) f.close()