SoFunction
Updated on 2024-11-19

Python to get the main color of an image via PIL and compare it with a color library

This article example describes how Python gets the main color of an image and compares it with the color library via PIL. Shared for your reference. Specific analysis is as follows:

This code is mainly used to extract the main color from the image, similar to Goolge and Baidu's image search can be specified in accordance with the color of the search, so we first need to extract the main color of each image, and then the color will be divided into its closest color segments, and then you can search in accordance with the color.

In the use of google or baidu search map will find that there is a picture color options, the feeling is very interesting, some people may think that this must be man-made to divide, oh, there is such a possibility, but it is estimated that people will die of exhaustion, just kidding, of course, is recognized by the machine, the massive number of pictures only machine recognition can be done.

So can this be done in python? The answer is: yes.

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

Copy Code The code is as follows.
import colorsys
def get_dominant_color(image):
# Color mode conversion for outputting rgb color values
    image = ('RGBA')
# Generate thumbnails to reduce computation and cpu pressure
    ((200, 200))
    max_score = None
    dominant_color = None
    for count, (r, g, b, a) in ([0] * [1]):
# Skip the solid 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 highlights
        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((''))

This will return an rgb color, but this value is a very precise range, so how do we achieve the color gamut like Baidu images?

In fact, the method is very simple, r/g/b are 0-255 values, we just divide these three values into equal intervals, and then combinations, take the approximate value. 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 can be.

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

I hope the description of this article will help you in python programming.