Skip to content

Instantly share code, notes, and snippets.

@mike-huls
Created August 25, 2022 09:09
Show Gist options
  • Save mike-huls/896ab6bb00c390d1038c0c1220ac0bab to your computer and use it in GitHub Desktop.
Save mike-huls/896ab6bb00c390d1038c0c1220ac0bab to your computer and use it in GitHub Desktop.
def get_most_popular_color(image_path:str) -> tuple:
""" Loads the path to an image and returns most prevalent color as a tuple:
(the image_path, rgb-color, % of pixels with this color)
NOTICE: This is unoptimized code: this is used as an example for demonstrating multiprocessing
"""
# 1. Load the image and pixels
img = Image.open(image_path)
pixels = img.load()
# 2. Image details
img_width, img_height = img.size # Get the width and hight of the image for iterating over
image_pixel_count = img_width * img_height
# 3. Loop over all pixels, round the pixels and count them in a dict)
rgb_count_dict:{tuple, int} = {}
for x in range(img_width):
for y in range(img_height):
r,g,b = pixels[x,y]
r = 10 * round(r/10)
g = 10 * round(g/10)
b = 10 * round(b/10)
rgb = (r, g, b)
if (rgb not in rgb_count_dict.keys()):
rgb_count_dict[rgb] = 0
rgb_count_dict[rgb] += 1
# 4. Sort the rgb_count_dict by the count
sorted_rgb_count_dict = {k: v for k, v in sorted(rgb_count_dict.items(), key=lambda item: item[1], reverse=True)}
most_popular_rgb = next(iter(sorted_rgb_count_dict))
most_popular_rgb_pixelcount = rgb_count_dict.pop(most_popular_rgb)
return image_path, most_popular_rgb, most_popular_rgb_pixelcount / image_pixel_count
@someonehi383
Copy link

someonehi383 commented Sep 3, 2023

I'm confused, what I need is:
#some code
funtionthatneedstoruninthebackground()
#some more code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment