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    ')
Example #2
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)))