コード例 #1
0
ファイル: recognizer.py プロジェクト: tyler-cromwell/Cerebrum
    def recognize(self, frame):
        confidences = []
        labels = []
        objects = self.detect(frame)

        for (x, y, w, h) in objects:
            face = imgproc.preprocess(
                frame,
                self._rwidth,
                self._rheight,
                x, y, w, h
            )

            predicted_label, confidence = self._recognizer.predict(face)

            if predicted_label == self._hash:
                labels.append(self._label)
                confidences.append(round(confidence))
            else:
                labels.append('Unknown')
                confidences.append(-1)

        return (objects, labels, confidences)
コード例 #2
0
def main():
    """
    Main function.
    """
    label = None
    show = False
    classifier = None
    settings = opt.map_settings()
    key = opt.default_settings()

    # Parse command-line arguments
    try:
        short_opts = ['']
        long_opts = ['help', 'classifier=', 'label=', 'settings=', 'show']
        opts, args = getopt.getopt(sys.argv[1:], short_opts, long_opts)
    except getopt.GetoptError as error:
        print('Invalid argument: \'' + str(error) + '\'\n')
        print_usage()

    if len(opts) == 0:
        print_usage()

    for o, a in opts:
        if o == '--help':
            print_usage()
        elif o == '--classifier':
            classifier = opt.validate_file(a)
        elif o == '--label':
            label = opt.validate_raw_dataset(sys.path[1], a)
        elif o == '--settings':
            key = a
        elif o == '--show':
            show = True

    if not label:
        print('\n  Label not specified!\n')
        print_usage()
    elif key not in settings.keys():
        print('\n  Settings not specified!\n')
        print_usage()

    # Initialize variables
    configuration = config.Config(settings[key])
    recognizer = configuration.recognizer()
    width = int(recognizer['width'])
    height = int(recognizer['height'])
    stream = camera.Camera(0, configuration)
    detector_obj = detector.Detector(classifier, configuration)
    raw_path = sys.path[1] + '/data/faces/' + label + '/raw/'
    training_path = sys.path[1] + '/data/faces/' + label + '/training/'
    image_paths = []

    os.makedirs(training_path, exist_ok=True)

    # Get the absolute path of each image
    print('Collecting raw images... ', end='')
    for entry in os.listdir(raw_path):
        image_paths.append(os.path.join(raw_path, entry))
    print('DONE')

    # Preprocess each image
    l = len(image_paths)
    for i, path in enumerate(image_paths):
        print('\rPreprocessing raw images... (' + str(i+1) + '/' + str(l) + ')', end='')
        cont = False
        image_pil = Image.open(path)
        image_org = numpy.array(image_pil)
        image_rgb = cv2.cvtColor(image_org, cv2.COLOR_BGR2RGB)

        (iwidth, iheight) = image_pil.size
        aspect_ratio = iwidth / iheight

        image = cv2.resize(image_rgb, (stream.get_width(), int(stream.get_width() / aspect_ratio)))
        (x, y, w, h) = (0, 0, 0, 0)

        try:
            (x, y, w, h) = detector_obj.detect(image)[0]
        except IndexError:
            print('\nNo faces detected in:', path)
            cont = True

        if show:
            cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 255), 2)
            cv2.imshow('process_raw_images.py', image)
            cv2.waitKey(1)

        if cont:
            continue

        face = imgproc.preprocess(image, width, height, x, y, w, h)

        if i < 10:
            cv2.imwrite(training_path + label + '.0' + str(i) + '.png', face)
        else:
            cv2.imwrite(training_path + label + '.' + str(i) + '.png', face)

    print('\rPreprocessing raw images... DONE    ')
コード例 #3
0
def main():
    """
    Main function.
    """
    classifier = None
    label = None
    settings = opt.map_settings()
    key = opt.default_settings()
    window_name = "Camera %d" % (CAMERA_DEFAULT)

    # Parse command-line arguments
    try:
        short_opts = [""]
        long_opts = ["help", "classifier=", "label=", "settings="]
        opts, args = getopt.getopt(sys.argv[1:], short_opts, long_opts)
    except getopt.GetoptError as error:
        print("Invalid argument: '" + str(error) + "'\n")
        print_usage()

    if len(opts) == 0:
        print_usage()

    for o, a in opts:
        if o == "--help":
            print_usage()
        elif o == "--classifier":
            classifier = opt.validate_file(a)
        elif o == "--label":
            label = a
        elif o == "--settings":
            key = a

    if not label:
        print("\n  Label not specified!\n")
        print_usage()
    elif key not in settings.keys():
        print("\n  Settings not specified!\n")
        print_usage()

    # Setup training set, objects, and window
    configuration = config.Config(settings[key])
    recognizer = configuration.recognizer()
    width = int(recognizer["width"])
    height = int(recognizer["height"])
    training_path = sys.path[1] + "/data/faces/" + label + "/training/"
    os.makedirs(training_path, exist_ok=True)

    dwidth, dheight = misc.get_display_resolution()
    print("Display resolution: %dx%d" % (dwidth, dheight))

    detector_obj = detector.Detector(classifier, configuration)
    stream = camera.Camera(CAMERA_DEFAULT, configuration)
    print("Capture Resolution: %dx%d" % (stream.get_width(), stream.get_height()))

    cv2.namedWindow(window_name, cv2.WINDOW_AUTOSIZE)
    cv2.moveWindow(window_name, (dwidth - stream.get_width()) // 2, 0)

    p = 0

    # Begin using the camera
    if not stream.open():
        print("Failed to open Camera", CAMERA_DEFAULT)
        exit(1)

    while True:
        retval, frame = stream.read()
        faces = detector_obj.detect(frame)

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

        cv2.putText(frame, "Photos taken: {}".format(p), (0, 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))
        cv2.putText(frame, "Press 'w' to take photo", (0, 22), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))

        cv2.imshow(window_name, frame)
        key = cv2.waitKey(1)

        if key == 27:
            cv2.destroyWindow(window_name)
            cv2.waitKey(1)
            cv2.waitKey(1)
            cv2.waitKey(1)
            cv2.waitKey(1)
            stream.release()
            break
        elif key == ord("w") and len(faces) >= 1:
            retval, frame = stream.read()  # Get frame without drawings
            (x, y, w, h) = faces[0]

            image = imgproc.preprocess(frame, width, height, x, y, w, h)

            if p < 10:
                cv2.imwrite(training_path + label + ".0" + str(p) + ".png", image)
            else:
                cv2.imwrite(training_path + label + "." + str(p) + ".png", image)

            p = p + 1

    stream.release()