Exemple #1
0
def run(args):
    model = build_model()

    (clf, class_names) = read_classifier(
        os.path.join(args.data_path, 'classifier.pickle'))
    # if classifier is none we only have one face
    if clf is None:
        verified_embedding, only_class = read_only_embedding(args.data_path)

    cap = cv2.VideoCapture(0)

    if (cap.isOpened() == False):
        print("Error opening video stream or file")

    face_detector = FaceDetector()

    while (cap.isOpened()):
        # Capture frame-by-frame
        ret, frame = cap.read()
        if ret == True:

            # Detect image and write it
            faces = face_detector.detect_faces(frame)
            for face in faces:
                x, y, w, h = face
                cropped = frame[y:y + h, x:x + w]
                cropped = cv2.resize(cropped, (96, 96))
                cropped = np.around(convert_image(cropped), decimals=12)
                embedding = model.predict(np.array([cropped]))

                if clf is None:
                    dist = np.linalg.norm(verified_embedding - embedding)
                    match = dist < 0.7
                    label = only_class if match else "Unknown"
                    if args.debug:
                        label += ' (d: {})'.format(round(dist, 2))
                else:
                    predictions = clf.predict_proba(embedding)
                    pred_class = np.argmax(predictions, axis=1)[0]
                    score = round(np.max(predictions) * 100, 2)
                    match = score > 70
                    name = class_names[pred_class]
                    label = '{} ({}%)'.format(name, score)

                color = (0, 255, 0) if match else (0, 0, 255)

                draw_bbox(frame, x, y, x + w, y + h, label=label, color=color)

            cv2.imshow('Frame', frame)

            # Press Q on keyboard to  exit
            if cv2.waitKey(25) & 0xFF == ord('q'):
                break

        else:
            break

    cap.release()
    cv2.destroyAllWindows()
Exemple #2
0
def capture(named_path, data_path, count):
    cap = cv2.VideoCapture(0)

    # Check if camera opened successfully
    if (cap.isOpened() == False):
        print("Error opening video stream or file")

    captured_counter = 0
    face_detector = FaceDetector()
    model = build_model()

    while (cap.isOpened() and captured_counter < count):
        # Capture frame-by-frame
        ret, frame = cap.read()
        if ret == True:

            # Show progress bar
            draw_progressbar(frame, (captured_counter / count))

            # Detect image and write it
            faces = face_detector.detect_faces(frame)
            if len(faces) > 0:

                # Per person path
                file_path = os.path.join(named_path,
                                         str(captured_counter + 1) + '.jpg')
                print('Writing capture: ' + file_path)

                face = faces[0]  # Assume it's the only face
                x, y, w, h = face
                cropped = frame[y:y + h, x:x + w]
                cropped = cv2.resize(cropped, (96, 96))
                cv2.imwrite(file_path, cropped)
                captured_counter += 1
                draw_bbox(frame, x, y, x + w, y + h, label="Face detected")

            cv2.imshow('Frame', frame)

            # Press Q on keyboard to  exit
            if cv2.waitKey(25) & 0xFF == ord('q'):
                break

        # Break the loop
        else:
            break

    # When everything done, release the video capture object
    cap.release()
    cv2.destroyAllWindows()

    # Build and Write the embedding file for this person
    build_embedding(model, named_path)

    # Rebuild the classifier
    build_classifier(data_path)

    print('Done!')
Exemple #3
0
class FaceRecognizer:
    # def __init__(self, config_path = os.path.join(path.rsplit(os.path.sep, 1)[0],'config.yml')):
    def __init__(self,
                 config_path=os.path.join(
                     path.rsplit(os.path.sep, 1)[0], 'config.yml')):
        config = get_config(config_path)
        self.detector = FaceDetector(config)
        self.extractor = FeatureExtractor()
        self.embeddings = np.load(
            os.path.join(
                path.rsplit(os.path.sep, 1)[0], config['embeddings_path']))
        self.df = pd.read_csv(
            os.path.join(
                path.rsplit(os.path.sep, 1)[0], config['classes_path']))
        self.index = faiss.IndexFlatL2(128)
        self.index.add(self.embeddings)
        self.knn = config['k_neighbors']
        self.max_distance = config['max_distance']

    def recognize(self, image):
        """
            Recognize a face in a list of known faces
            Argument:
                - image: np.ndarray and in RGB order
            Return: None if image has no faces or unknown faces. Otherwise, return label
        """
        faces = self.detector.detect_faces(image)
        if not faces:
            return None
        face = faces[0]
        emb = self.extractor.get_embeddings(face)
        distances, indices = self.index.search(emb, self.knn)
        indices = indices[distances < self.max_distance]
        if indices.shape[0] == 0:
            return None
        classes = self.df.loc[indices, 'class']
        return get_class(classes)
import cv2
from video_initializer import VideoInitializer
from face_detector import FaceDetector

if __name__ == '__main__':
    video_initializer = VideoInitializer()
    face_detector = FaceDetector()

    while True:
        frame = video_initializer.get_frame()
        resized_frame = video_initializer.resize_frame(frame, (640, 480))
        face_coords = face_detector.detect_faces(resized_frame)
        # face_detector.plot_coords(resized_frame, face_coords)
        cropped_face = face_detector.get_cropped_face(resized_frame,
                                                      face_coords)
        cv2.imshow('Face', cropped_face)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
from face_detector import FaceDetector
from feature_extractor import FeatureExtractor
from utils import *

if __name__ == '__main__':
    config = get_config()
    detector = FaceDetector(config)
    extractor = FeatureExtractor()

    all_paths = get_all_image_paths()
    faces = []
    class2idx = defaultdict(lambda: 1)
    class_list = defaultdict(list)
    idx = 0
    for i, path in tqdm(enumerate(all_paths)):
        crops = detector.detect_faces(path)
        dirs = path.rsplit(os.path.sep, 2)
        parent_folder = os.path.join('cropped_faces', dirs[1])
        if not os.path.exists(parent_folder):
            os.makedirs(parent_folder)
        for crop in crops:
            cv.imwrite(
                os.path.join(parent_folder, f'{class2idx[dirs[1]]}.jpg'),
                cv.cvtColor(crop, cv.COLOR_RGB2BGR))
            class2idx[dirs[1]] += 1
            class_list[dirs[1]].append(idx)
            idx += 1
        faces.extend(crops)
    faces = np.array(faces)
    embeddings = extractor.get_embeddings(faces)
Exemple #6
0
ap.add_argument("-c ", "--cascade", required=True, help="cascade path")
ap.add_argument("-i", "--image", required=True, help="image path")
ap.add_argument("-s", "--show", help="show result")
args = vars(ap.parse_args())

show = False

img = cv2.imread(args["image"])
face_cascade = cv2.CascadeClassifier(args["cascade"])

if args["show"] is not None:
    if args["show"].lower() in ('yes', 'true', 't', 'y', '1'):
        show = True
    elif args["show"].lower() in ('no', 'false', 'f', 'n', '0'):
        show = False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

face_detector = FaceDetector(face_cascade)
rects = face_detector.detect_faces(img, 1.1, 5)
print(rects)

if show:
    for (x, y, w, h) in rects:
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 3)

    cv2.imshow('img', img)
    cv2.waitKey(0)
Exemple #7
0
scale_percent = 100
if args["scale"] is not None:
    scale_percent = int(args["scale"])

cap = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier(args["cascade"])
face_detector = FaceDetector(face_cascade)

ret, frame = cap.read()
width = int(frame.shape[1] * scale_percent / 100)
height = int(frame.shape[0] * scale_percent / 100)

while True:
    ret, frame = cap.read()
    if ret is None:
        break

    resized = cv2.resize(frame, (width, height))
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    rects = face_detector.detect_faces(gray, 1.1, 5)

    for (x, y, w, h) in rects:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 4)

    cv2.imshow('img', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()