|
6 | 6 | import scipy.misc
|
7 | 7 | import warnings
|
8 | 8 | import face_recognition.api as face_recognition
|
9 |
| - |
| 9 | +import multiprocessing |
| 10 | +import itertools |
| 11 | +import sys |
10 | 12 |
|
11 | 13 | def scan_known_people(known_people_folder):
|
12 | 14 | known_names = []
|
@@ -54,14 +56,40 @@ def image_files_in_folder(folder):
|
54 | 56 | return [os.path.join(folder, f) for f in os.listdir(folder) if re.match(r'.*\.(jpg|jpeg|png)', f, flags=re.I)]
|
55 | 57 |
|
56 | 58 |
|
| 59 | +def process_images_in_process_pool(images_to_check, known_names, known_face_encodings, number_of_cpus): |
| 60 | + if number_of_cpus == -1: |
| 61 | + processes = None |
| 62 | + else: |
| 63 | + processes = number_of_cpus |
| 64 | + |
| 65 | + # macOS will crash due to a bug in libdispatch if you don't use 'forkserver' |
| 66 | + context = multiprocessing |
| 67 | + if "forkserver" in multiprocessing.get_all_start_methods(): |
| 68 | + context = multiprocessing.get_context("forkserver") |
| 69 | + |
| 70 | + pool = context.Pool(processes=processes) |
| 71 | + function_parameters = zip(images_to_check, itertools.repeat(known_names), itertools.repeat(known_face_encodings)) |
| 72 | + |
| 73 | + pool.starmap(test_image, function_parameters) |
| 74 | + |
| 75 | + |
57 | 76 | @click.command()
|
58 | 77 | @click.argument('known_people_folder')
|
59 | 78 | @click.argument('image_to_check')
|
60 |
| -def main(known_people_folder, image_to_check): |
| 79 | +@click.option('--cpus', default=1, help='number of CPU cores to use in parallel (can speed up processing lots of images). -1 means "use all in system"') |
| 80 | +def main(known_people_folder, image_to_check, cpus): |
61 | 81 | known_names, known_face_encodings = scan_known_people(known_people_folder)
|
62 | 82 |
|
| 83 | + # Multi-core processing only supported on Python 3.4 or greater |
| 84 | + if (sys.version_info < (3, 4)) and cpus != 1: |
| 85 | + click.echo("WARNING: Multi-processing support requires Python 3.4 or greater. Falling back to single-threaded processing!") |
| 86 | + cpus = 1 |
| 87 | + |
63 | 88 | if os.path.isdir(image_to_check):
|
64 |
| - [test_image(image_file, known_names, known_face_encodings) for image_file in image_files_in_folder(image_to_check)] |
| 89 | + if cpus == 1: |
| 90 | + [test_image(image_file, known_names, known_face_encodings) for image_file in image_files_in_folder(image_to_check)] |
| 91 | + else: |
| 92 | + process_images_in_process_pool(image_files_in_folder(image_to_check), known_names, known_face_encodings, cpus) |
65 | 93 | else:
|
66 | 94 | test_image(image_to_check, known_names, known_face_encodings)
|
67 | 95 |
|
|
0 commit comments