Python's way of getting the main color of an image through PIL and comparing it with the color library

  • 2020-04-02 14:44:01
  • OfStack

This example shows how Python USES PIL to get the main colors of an image and compare them with a color library. Share with you for your reference. Specific analysis is as follows:

This code is mainly used to extract the main color from the image. Google and Baidu can specify the search by color when searching images, so we first need to extract the main color of each image, and then divide the color into the closest color segment, and then we can search by color.

When in use Google or baidu SouTu will find a picture color options, feel very interesting, one might think it must be to divide the people, ha ha, the possibility, but estimates people fail, a joke, of course is through the identification of the machine, huge amounts of image can only be done machine recognition.

Is it possible to do this in python? The answer is: yes

Using python's PIL module's powerful image processing function can be done, the following code:

import colorsys
def get_dominant_color(image):
# Color mode conversion for output rgb Color value
    image = image.convert('RGBA')
# Generate thumbnails, reduce computation, reduce cpu pressure
    image.thumbnail((200, 200))
    max_score = None
    dominant_color = None
    for count, (r, g, b, a) in image.getcolors(image.size[0] * image.size[1]):
        # Skip plain black
        if a == 0:
            continue
        saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]
        y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)
        y = (y - 16.0) / (235 - 16)
        # Ignore the high lights
        if y > 0.9:
            continue
        # Calculate the score, preferring highly saturated colors.
        # Add 0.1 to the saturation so we don't completely ignore grayscale
        # colors by multiplying the count by zero, but still give them a low
        # weight.
        score = (saturation + 0.1) * count
        if score > max_score:
            max_score = score
            dominant_color = (r, g, b)
    return dominant_color

Usage:


from PIL import Image
print get_dominant_color(Image.open('logo.jpg'))

This will return a RGB color, but this value is very accurate range, then how do we achieve the color gamut like baidu pictures??

Well, it's pretty simple, r over g over b is 0 minus 255, so we're just going to divide the three values into equal intervals, and then we're going to combine them, and we're going to approximate them. For example: divided into 0-127, and 128-255, and then free combination, can appear eight combinations, and then pick out the more representative color.

Of course, I'm just giving you an example, you can also divide it more finely, so that the color will be more accurate

I hope this article has helped you with your python programming.


Related articles: