Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple way to get dominant colors from an image in Python
import Image, ImageDraw
def get_colors(infile, outfile, numcolors=10, swatchsize=20, resize=150):
image = Image.open(infile)
image = image.resize((resize, resize))
result = image.convert('P', palette=Image.ADAPTIVE, colors=numcolors)
result.putalpha(0)
colors = result.getcolors(resize*resize)
# Save colors to file
pal = Image.new('RGB', (swatchsize*numcolors, swatchsize))
draw = ImageDraw.Draw(pal)
posx = 0
for count, col in colors:
draw.rectangle([posx, 0, posx+swatchsize, swatchsize], fill=col)
posx = posx + swatchsize
del draw
pal.save(outfile, "PNG")
if __name__ == '__main__':
get_colors('infile.jpg', 'outfile.png')
@joseluisrt

This comment has been minimized.

Copy link

commented Apr 15, 2014

Thank you for the code. I get a segmentation fault error in line:

result = image.convert('P', palette=Image.ADAPTIVE, colors=numcolors)

Did you get this kind of error anytime?

Thanks in advance

@johnpaulhayes

This comment has been minimized.

Copy link

commented Mar 21, 2015

Great gist! Very helpful.
@joseluisrt - no problems running it from here.

@zakittur

This comment has been minimized.

Copy link

commented Feb 25, 2017

Can this code be modified to give dominant colors of image based on percentage of color ?
Refer to the image below for example.

001

@masterdungeon

This comment has been minimized.

Copy link

commented Sep 8, 2017

Sir, i have a different kind of problem in which I have an image in which different-different color.I want to extract hex code or RGB code of these color.How to do this with python?
first

@NafeesAhmedAbbasi

This comment has been minimized.

Copy link

commented Sep 10, 2017

@masterdungeon Did you find the solution?

@santynaren

This comment has been minimized.

Copy link

commented Mar 18, 2018

@masterdungeon @NafeesAhmedAbbasi For your Reference

Just add print(col) to get the hex values of each color

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.