Created
January 15, 2016 10:24
-
-
Save lotabout/2d65fd842fa3e278b242 to your computer and use it in GitHub Desktop.
Extract the main color(and usage) used by an image, like color thief but in python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import sys, argparse | |
from PIL import Image | |
from PIL.ImageDraw import Draw | |
import sys | |
def to_hash(color): | |
return ''.join(['{:02x}'.format(x) for x in color]) | |
def show_info(info): | |
number = len(info) | |
per_width = 200 | |
width = per_width + 100 | |
per_height = 50 | |
height = per_height * number | |
im = Image.new('RGB', (width,height), 'white') | |
total_pixels = sum([x[0] for x in info]) | |
draw = Draw(im) | |
for idx, item in enumerate(info): | |
draw.rectangle([0, idx*per_height, per_width, (idx+1)*per_height], fill='#'+to_hash(item[1])) | |
draw.text((per_width+10, (idx*per_height) + 14), '#'+to_hash(item[1]), fill='#333') | |
draw.text((per_width+10, idx*per_height + 30), | |
'{:.2f}%'.format(float(item[0])*100/total_pixels), fill='#333') | |
print('#'+to_hash(item[1]) + '\trgb' + str(item[1]), | |
'\t{:.2f}%'.format(float(item[0])*100/total_pixels)) | |
im.show() | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('filename', help = "specify the input filename") | |
parser.add_argument('-c', '--colors', type=int, | |
help = "Specify how many colors you want to extract") | |
args = parser.parse_args() | |
# open images | |
num_colors = args.colors if args.colors else 10 | |
im = Image.open(args.filename) | |
all_colors = sorted(im.quantize(colors=num_colors, method=2).convert('RGB').getcolors(), | |
reverse=True) | |
show_info(all_colors) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment