Aug-27-2017, 10:48 PM
Hey ! I wrote a simple script to return the color used in an image.
Requirements
Feel free to suggest improvements, and please tell me if it's working with Python 3
Requirements
- Install the PIL module
- Configure Init values
- Beautiful pie chart
- Colored images named with the percentage
- Json file

- Process only colors with a minimum percentage
- Allow transparent pixels process
- Multiple return color format available
Feel free to suggest improvements, and please tell me if it's working with Python 3

#!/usr/bin/env python #-*- coding: utf-8 -*- import os import json from PIL import Image from PIL import ImageDraw # Init file = '/path/to/your/file.png' results_dir = '/path/to/results/dir' min_percentage = 0.5 # min percentage of color in the file to be added alpha_pixels = True # use transparent pixels circle_size = 500 # circle file size (pixels) color_files = True # get results with image files results_file = True # get json results results_color_format = 'hex' # hex / rgb / rgba results_ext = '.json' PIL_file = Image.open(file) all_pixels = PIL_file.size[0] * PIL_file.size[1] colors_hm = {} sorted_colors = [] if not os.path.isdir(results_dir): os.makedirs(results_dir) for rgba_pixel in PIL_file.getdata(): if rgba_pixel[3] == 0: if alpha_pixels == True: rgba_pixel = (0, 0, 0, 0) else: all_pixels -= 1 continue try: nb = colors_hm[rgba_pixel]['nb'] colors_hm[rgba_pixel] = {'nb':nb + 1} except: colors_hm[rgba_pixel] = {'nb':1} for color in colors_hm: color_percentage = colors_hm[color]['nb'] * 100 / float(all_pixels) if color_percentage >= min_percentage: rgba_pixel = eval(str(color)) if color_files == True: img = Image.new('RGBA', (100, 100), (rgba_pixel[0],rgba_pixel[1],rgba_pixel[2],rgba_pixel[3])) file_name = '%03.4f %%.png' % color_percentage img.save(os.path.join(results_dir,file_name),format="png") sorted_colors.append({'color':rgba_pixel,'num':color_percentage}) sorted_colors.sort(key=lambda k: k['num'],reverse=True) circle = Image.new('RGBA', (circle_size,circle_size), (0,0,0,0)) current_deg = 0 for x in sorted_colors: rgba_pixel = eval(str(x['color'])) pieslice_deg = x['num'] * 3.6 ImageDraw.Draw(circle).pieslice([10, 10, circle_size-10, circle_size-10], current_deg, current_deg + pieslice_deg, fill=(rgba_pixel[0],rgba_pixel[1],rgba_pixel[2],rgba_pixel[3])) current_deg += pieslice_deg if results_file == True: if results_color_format == 'hex': x['color'] = '#%02x%02x%02x' % (rgba_pixel[0],rgba_pixel[1],rgba_pixel[2]) elif results_color_format == 'rgb': x['color'] = (rgba_pixel[0],rgba_pixel[1],rgba_pixel[2]) circle.save(os.path.join(results_dir,"circle.png"),format="png") if results_file == True: with open(os.path.join(results_dir,"results"+results_ext), 'w') as outfile: json.dump(sorted_colors, outfile) print "Done."