Python - Find dominant/most common color in an image

80,314

Solution 1

Here's code making use of Pillow and Scipy's cluster package.

For simplicity I've hardcoded the filename as "image.jpg". Resizing the image is for speed: if you don't mind the wait, comment out the resize call. When run on this sample image of blue peppers it usually says the dominant colour is #d8c865, which corresponds roughly to the bright yellowish area to the lower left of the two peppers. I say "usually" because the clustering algorithm used has a degree of randomness to it. There are various ways you could change this, but for your purposes it may suit well. (Check out the options on the kmeans2() variant if you need deterministic results.)

from __future__ import print_function
import binascii
import struct
from PIL import Image
import numpy as np
import scipy
import scipy.misc
import scipy.cluster

NUM_CLUSTERS = 5

print('reading image')
im = Image.open('image.jpg')
im = im.resize((150, 150))      # optional, to reduce time
ar = np.asarray(im)
shape = ar.shape
ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float)

print('finding clusters')
codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
print('cluster centres:\n', codes)

vecs, dist = scipy.cluster.vq.vq(ar, codes)         # assign codes
counts, bins = scipy.histogram(vecs, len(codes))    # count occurrences

index_max = scipy.argmax(counts)                    # find most frequent
peak = codes[index_max]
colour = binascii.hexlify(bytearray(int(c) for c in peak)).decode('ascii')
print('most frequent is %s (#%s)' % (peak, colour))

Note: when I expand the number of clusters to find from 5 to 10 or 15, it frequently gave results that were greenish or bluish. Given the input image, those are reasonable results too... I can't tell which colour is really dominant in that image either, so I don't fault the algorithm!

Also a small bonus: save the reduced-size image with only the N most-frequent colours:

# bonus: save image using only the N most common colours
import imageio
c = ar.copy()
for i, code in enumerate(codes):
    c[scipy.r_[scipy.where(vecs==i)],:] = code
imageio.imwrite('clusters.png', c.reshape(*shape).astype(np.uint8))
print('saved clustered image')

Solution 2

Try Color-thief. It is based on Pillow and works awesome.

Installation

pip install colorthief

Usage

from colorthief import ColorThief
color_thief = ColorThief('/path/to/imagefile')
# get the dominant color
dominant_color = color_thief.get_color(quality=1)

It can also find color pallete

palette = color_thief.get_palette(color_count=6)

Solution 3

Python Imaging Library has method getcolors on Image objects:

im.getcolors() => a list of (count, color) tuples or None

I guess you can still try resizing the image before that and see if it performs any better.

Solution 4

You can do this in many different ways. And you don't really need scipy and k-means since internally Pillow already does that for you when you either resize the image or reduce the image to a certain pallete.

Solution 1: resize image down to 1 pixel.

def get_dominant_color(pil_img):
    img = pil_img.copy()
    img = img.convert("RGBA")
    img = img.resize((1, 1), resample=0)
    dominant_color = img.getpixel((0, 0))
    return dominant_color

Solution 2: reduce image colors to a pallete

def get_dominant_color(pil_img, palette_size=16):
    # Resize image to speed up processing
    img = pil_img.copy()
    img.thumbnail((100, 100))

    # Reduce colors (uses k-means internally)
    paletted = img.convert('P', palette=Image.ADAPTIVE, colors=palette_size)

    # Find the color that occurs most often
    palette = paletted.getpalette()
    color_counts = sorted(paletted.getcolors(), reverse=True)
    palette_index = color_counts[0][1]
    dominant_color = palette[palette_index*3:palette_index*3+3]

    return dominant_color

Both solutions give similar results. The latter solution gives you probably more accuracy since we keep the aspect ratio when resizing the image. Also you get more control since you can tweak the pallete_size.

Solution 5

It's not necessary to use k-means to find the dominant color as Peter suggests. This overcomplicates a simple problem. You're also restricting yourself by the amount of clusters you select so basically you need an idea of what you're looking at.

As you mentioned and as suggested by zvone, a quick solution to find the most common/dominant color is by using the Pillow library. We just need to sort the pixels by their count number.

from PIL import Image

    def find_dominant_color(filename):
        #Resizing parameters
        width, height = 150,150
        image = Image.open(filename)
        image = image.resize((width, height),resample = 0)
        #Get colors from image object
        pixels = image.getcolors(width * height)
        #Sort them by count number(first element of tuple)
        sorted_pixels = sorted(pixels, key=lambda t: t[0])
        #Get the most frequent color
        dominant_color = sorted_pixels[-1][1]
        return dominant_color

The only problem is that the method getcolors() returns None when the amount of colors is more than 256. You can deal with it by resizing the original image.

In all, it might not be the most precise solution but it gets the job done.

Share:
80,314
Blue Peppers
Author by

Blue Peppers

Updated on July 08, 2022

Comments

  • Blue Peppers
    Blue Peppers almost 2 years

    I'm looking for a way to find the most dominant color/tone in an image using python. Either the average shade or the most common out of RGB will do. I've looked at the Python Imaging library, and could not find anything relating to what I was looking for in their manual, and also briefly at VTK.

    I did however find a PHP script which does what I need, here (login required to download). The script seems to resize the image to 150*150, to bring out the dominant colors. However, after that, I am fairly lost. I did consider writing something that would resize the image to a small size then check every other pixel or so for it's image, though I imagine this would be very inefficient (though implementing this idea as a C python module might be an idea).

    However, after all of that, I am still stumped. So I turn to you, SO. Is there an easy, efficient way to find the dominant color in an image.

  • Blue Peppers
    Blue Peppers almost 14 years
    Wow. That's great. Almost exactly what I was looking for. I did look at scipy, and had a feeling the answer was somewhere in there :P Thank you for your answer.
  • frakman1
    frakman1 over 8 years
    Great answer. Worked for me. However, I had a small question. How do I access the second most frequent colour in the case that black is the most frequent and I wish to ignore it?
  • Peter Hansen
    Peter Hansen over 8 years
    @frakman1, argmax() is just a convenience function that gives the first. What you'd need to do is sort the counts array (keeping track of the original indices), then pick the second (or second last) entry rather than the first (which is effectively what argmax does).
  • rossdavidh
    rossdavidh over 7 years
    For png, you need to tweak this slightly to handle the fact that img.getpixel returns r,g,b,a (four values instead of three). Or it did for me anyway.
  • Russell Borogove
    Russell Borogove over 7 years
    This weighs pixels unevenly. The final pixel touched contributes half the total value. The pixel before contributes half of that. Only the last 8 pixels will affect the average at all, in fact.
  • Tim S
    Tim S over 7 years
    You're right - silly mistake. Just edited the answer - let me know if that works.
  • Simon Steinberger
    Simon Steinberger over 6 years
    I'm getting this error: File "_vq.pyx", line 342, in scipy.cluster._vq.update_cluster_means TypeError: type other than float or double not supported. Any idea what this is?
  • Peter Hansen
    Peter Hansen over 6 years
    @SimonSteinberger With the above code or your own variant? It worked when I posted it, but that was years ago, probably using Python 2.7 and whatever scipy/numpy was reasonably current at the time.
  • Simon Steinberger
    Simon Steinberger over 6 years
    With the above code on Py 2.7. I just received an answer here, which I need to test now: stackoverflow.com/questions/47612243/… Possibly something changed in Scipy over the years.
  • Simon Steinberger
    Simon Steinberger over 6 years
    ar = ar.reshape(scipy.product(shape[:2]), shape[2]) needs to be written now as ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float). The chr(x) doesn't work then, because an int is expected, but it's now a float.
  • Simon Steinberger
    Simon Steinberger over 6 years
    I've edited/updated your code. Thanks for this compact and well working solution!
  • Peter Hansen
    Peter Hansen over 6 years
    @SimonSteinberger Thanks for the edit, and I'm happy to hear it's still able to run and help someone 7 years later! It was a fun problem to work on.
  • philshem
    philshem about 5 years
    this has multiple issues with python 3.x. For example, (1) .encode('hex') is no longer valid syntax, and (2) from PIL import Image source
  • Peter Hansen
    Peter Hansen about 5 years
    Thanks @philshem. I believe I've modified it to support 3.x as well now. Some changes done at the same time resolved deprecations and warnings that were reported on either 2.7 or 3.7 (but not necessarily both).
  • Phani Rithvij
    Phani Rithvij almost 5 years
    This is not an answer to this question. Average color is not the dominant color in an image.
  • Black Thunder
    Black Thunder over 4 years
    You know what? You are returning the function itself, though you are assigning a value to it but it isn't a good idea
  • mobiuscreek
    mobiuscreek over 4 years
    You're absolutely right and for that I have edited the name of the function!
  • Trect
    Trect over 4 years
    Fantastic module
  • Bowen Liu
    Bowen Liu over 4 years
    What an amazing answer. Works really well for me. But just 2 simple questions: is there any way to visualize peak and colour, and would you mind explaining the difference between peak and colour please? Thanks.
  • Peter Hansen
    Peter Hansen over 4 years
    @BowenLiu Colour is just the "hex" form of peak, which is a vector of integer values for red, green, and blue. If peak is [175, 40, 102], then colour would be "af2866". You can visualize it by entering the colour code into a tool like this: color-hex.com/color/af2866 (use the text box at top to try others).
  • Bowen Liu
    Bowen Liu over 4 years
    @PeterHansen Thanks. Can I visualize with any Python tool or lib like matplotlib? I tried to use the imshow to do it but to no avail. I am trying to print out the color in the same IPython Notebook.
  • Peter Hansen
    Peter Hansen over 4 years
    @BowenLiu That sounds like something best asked as a new question, since there are many ways to do it, and what works best will depend on details you could provide in your question. Comments here aren't really the best way to do that...
  • Bowen Liu
    Bowen Liu over 4 years
    You are right. I will do that. All the questions on SO are about the other way around, namely getting the color array with a given picture.
  • Pithikos
    Pithikos about 4 years
    This is not very reliable. (1) you should use thumbnail instead of resize to avoid crop or stretch, (2) if you have an image with 2 white pixels and 100 different levels of blackish pixels, you will still get white.
  • whlteXbread
    whlteXbread about 4 years
    This is also leaps and bounds faster than any of the scikit-learn/scipy images above.
  • mobiuscreek
    mobiuscreek almost 4 years
    Agreed but I wanted to avoid the caveat of reducing the granularity when using predefined clusters or a palette. Depending on the use case this might not be desirable.
  • RealA10N
    RealA10N over 3 years
    Works like a charm, and doesn't require any additional modules. Thank you so much!
  • Maicon Mauricio
    Maicon Mauricio almost 3 years
    Can you explain your code a little bit? (What libraries or modules you used if any and why). It would be nice for others to understand your research, the downsides and upsides of your code and alternatives. It's always better to add some explanation in order to provide context to readers.
  • quine9997
    quine9997 almost 3 years
    Look better. This is a complete python script. There are 7-8 IMPORT instructions. And every line of code is commented. This is a script, so the user can copy and paste it. You have just change the name of the input image image001.png
  • Jacob
    Jacob over 2 years
    For anyone who found this fantastic answer helpful I have an adaptation here which is faster and is deterministic
  • Peter Hansen
    Peter Hansen over 2 years
    Thanks for adding to the solution Jacob! It's gratifying to see this fun question still helping people out. :)
  • vangap
    vangap over 2 years
    I am wondering if there is a difference in the correcness of the methods in Top voted, accepeted answer and this? I understand the other answer is old and hence might have more votes.
  • Adithya Raj
    Adithya Raj about 2 years
    Thanks for the piece of code, also could you explain how to know what colour is this (Red, blue...). It would be great if you can provide some piece of code.