Implement processing of images on multiple threads at once

This commit is contained in:
Kristóf Tóth 2018-04-28 21:27:31 +02:00
parent ef37a30e7d
commit 8e69f70cf3

View File

@ -51,9 +51,11 @@ if __name__ == '__main__':
from os import remove from os import remove
from sys import exit from sys import exit
from signal import signal, SIGINT from signal import signal, SIGINT
from multiprocessing import Pool, cpu_count
signal(SIGINT, lambda a, b: exit('\nExiting!')) signal(SIGINT, lambda a, b: exit('\nExiting!'))
def parse_arguments(): def parse_arguments():
ap = ArgumentParser(description='Find the best quality one among similar images.' ap = ArgumentParser(description='Find the best quality one among similar images.'
'Note: image dimensions should match!') 'Note: image dimensions should match!')
@ -65,21 +67,38 @@ if __name__ == '__main__':
def run(args): def run(args):
try: if not hasattr(imgrate, args.method):
ratings = {image: getattr(imgrate(image), args.method) for image in args.images}
except AttributeError:
exit('Invalid --method option!') exit('Invalid --method option!')
ratings = calculate_all_ratings(args.images, args.method)
maximum = max(ratings, key=ratings.get) maximum = max(ratings, key=ratings.get)
for rating in ratings.keys(): fancy_print_ratings(ratings, args.quiet, maximum)
if args.quiet:
print(ratings[rating])
else:
maxmark = '*' if rating == maximum and len(ratings) > 1 else ' '
print('{}imgrate("{}") = {}'.format(maxmark, rating, ratings[rating]))
if args.delete: if args.delete:
[remove(image) for image in ratings if image != maximum] [remove(image) for image in ratings if image != maximum]
def calculate_all_ratings(images, method):
ratings = []
with Pool(processes=cpu_count()) as pool:
for image in images:
ratings.append((image, pool.apply_async(calculate_rating, (image, method))))
return {image: promise.get() for image, promise in ratings}
def calculate_rating(image, method):
return getattr(imgrate(image), method)
def fancy_print_ratings(ratings, quiet, maximum):
for rating in ratings.keys():
if quiet:
print(ratings[rating])
else:
maxmark = '*' if rating == maximum and len(ratings) > 1 else ' '
print('{}imgrate("{}") = {}'.format(maxmark, rating, ratings[rating]))
run(parse_arguments()) run(parse_arguments())