Пример #1
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    ')
Пример #2
0
def main():
    """
    Main function.
    """
    classifier = None
    flags = 0
    img = 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=', 'image=', '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 == '--image':
            img = opt.validate_file(a)
        elif o == '--label':
            label = opt.validate_recognizer(sys.path[0], 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 objects and window
    configuration = config.Config(settings[key])
    dwidth, dheight = misc.get_display_resolution()
    recognizer_obj = recognizer.Recognizer(classifier, label, configuration)
    stream = camera.Camera(CAMERA_DEFAULT, configuration)
    print('Capture resolution: %dx%d' % (stream.get_width(), stream.get_height()))

    # Recognize in a still image
    if img:
        image, objects, labels, confidences = recognizer_obj.recognize_from_file(img)
        draw_face_info(image, objects, labels, confidences)
        cv2.imshow(img, image)
        cv2.waitKey(0)
        return

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

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

    while True:
        start = time.time()
        retval, frame = stream.read()

        # Check flags
        if flags & 1:
            objects, labels, confidences = recognizer_obj.recognize(frame)
            draw_face_info(frame, objects, labels, confidences)

        end = time.time()
        fps = 1 // (end - start)

        cv2.putText(frame, 'FPS: [%d]' % (fps), (0, 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))
        cv2.imshow(window_name, frame)

        key = cv2.waitKey(1)

        if key >= (1024 * 1024):
            key = key - (1024 * 1024)

        # Determine action
        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('f'):
            flags = flags ^ 1
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()
Пример #4
0
def main():
    """
    Main function.
    """
    label1 = None
    label2 = None
    classifier = None
    settings = opt.map_settings()
    key = opt.default_settings()

    # Parse command-line arguments
    try:
        short_opts = ['']
        long_opts = [
            'help',
            'classifier=',
            'label1=',
            'label2=',
            '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 == '--label1':
            label1 = opt.validate_raw_dataset(sys.path[1], a)
        elif o == '--label2':
            label2 = opt.validate_raw_dataset(sys.path[1], a)
        elif o == '--settings':
            key = a

    if not label1 or not label2:
        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_obj = recognizer.Recognizer(classifier, label1, configuration)
    raw_path = sys.path[1] + '/data/faces/' + label2 + '/raw/'
    image_paths = []
    all_confidences = []
    all_widths = []
    all_heights = []
    percent = 0

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

    # Preprocess each image
    for i, path in enumerate(image_paths):
        percent = ((i+1) / len(image_paths)) * 100
        print("\rCalculating confidence statistics... {:.1f}%".format(percent), end='')
        sys.stdout.flush()
        skip = False

        image, objects, labels, confidences = recognizer_obj.recognize_from_file(path)

        try:
            if len(confidences) > 1:
                all_confidences.append(confidences[1])
                all_widths.append(objects[1][2])
                all_heights.append(objects[1][3])
            else:
                all_confidences.append(confidences[0])
                all_widths.append(objects[0][2])
                all_heights.append(objects[0][3])
        except IndexError:
            skip = True

        if skip:
            continue

    print('\rCalculating confidence statistics... DONE  ')
    print('Five Number Summary:')
    print('  Max:\t   {}'.format(numpy.max(all_confidences)))
    print('  Min:\t   {}'.format(numpy.min(all_confidences)))
    print('  Median:  {}'.format(numpy.median(all_confidences)))
    print('  Mean:\t   {}'.format(numpy.mean(all_confidences)))
    print('  StdDev:  {}'.format(numpy.std(all_confidences)))
    print('Mean face size: %dx%d' % (numpy.mean(all_widths), numpy.mean(all_heights)))