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