This article mainly introduces how Python obtains the main color of the image through PIL and compares it with the color Library. The example shows how Python operates the image through the PIL module, which has some reference value, for more information about how to obtain the main color of an image through PIL and compare it with the color Library, see the example in this article. Share it with you for your reference. The specific analysis is as follows:
This code is mainly used to extract the main color of an image. for images similar to Goolge and Baidu, you can specify the color to search. Therefore, we need to extract the main color of each image first, divide the color into the nearest color segment, and then you can search by color.
When using google or baidu to search for images, you will find that there is an image color option, which is very interesting. some people may think that it must be artificially divided, however, it is estimated that people will be exhausted and joking. of course, they are identified by machines. massive images can only be identified by machines.
Can python implement this function? The answer is: yes
You can use the powerful image processing function of python's PIL module. the code below is as follows:
The code is as follows:
Import colorsys
Def get_dominant_color (image ):
# Color mode conversion to output rgb color values
Image = image. convert ('rgba ')
# Generating thumbnails to reduce computing workload and 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 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 highlighted colors
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 Imageprint get_dominant_color(Image.open('logo.jpg'))
In this way, an rgb color is returned, but this value is very accurate. how can we implement the color gamut like Baidu images ??
In fact, the method is very simple, r/g/B are all 0-values, we just need to divide these three values into equal intervals, and then combine them to take an approximate value. For example, divide it into 0-127 and 128-255, and then combine them freely. you can see eight combinations and pick out representative colors.
Of course, I will just give you an example. you can also divide it into more details so that the displayed color will be more accurate ~~ Try it now.
I hope this article will help you with python programming.