相关文章推荐
小眼睛的热带鱼  ·  Python equivalent of ...·  2 月前    · 
俊逸的火锅  ·  Python 控制台 — Blender ...·  2 月前    · 
健身的抽屉  ·  在 Google Cloud 上使用 ...·  2 月前    · 
直爽的黑框眼镜  ·  Difference between ...·  2 月前    · 
性感的毛豆  ·  通过SWIG实现在Python中调用C++代 ...·  2 月前    · 
时尚的西红柿  ·  Matlab如何查询数组中的最小值的索引 ...·  2 年前    · 
性感的伤疤  ·  教你用Python破解WiFi,流量自由不再 ...·  3 年前    · 
文雅的炒饭  ·  python - Ensure that ...·  3 年前    · 
欢快的电池  ·  尤大推荐的神器unplugin-vue-co ...·  3 年前    · 
儒雅的冲锋衣  ·  腾讯云开发者社区-腾讯云·  3 年前    · 
Code  ›  Python通过PIL获取图片的主要颜色并和颜色库进行对比的代码开发者社区
python
https://cloud.tencent.com/developer/article/1895437
风流倜傥的饭卡
3 年前
作者头像
用户7166745
0 篇文章

Python通过PIL获取图片的主要颜色并和颜色库进行对比的代码

原创
前往专栏
腾讯云
备案 控制台
开发者社区
学习
实践
活动
专区
工具
TVP
文章/答案/技术大牛
写文章
社区首页 > 专栏 > 代码兼容天下 > 正文

Python通过PIL获取图片的主要颜色并和颜色库进行对比的代码

原创
修改 于 2021-11-01 13:51:14
297 0
举报

这段代码主要用来从图片提取其主要颜色,类似Goolge和Baidu的图片搜索时可以指定按照颜色搜索,所以我们先需要将每张图片的主要颜色提取出来,然后将颜色划分到与其最接近的颜色段上,然后就可以按照颜色搜索了。在使用google或者baidu搜图的时候会发现有一个图片颜色选项,感觉非常有意思,有人可能会想这肯定是人为的去划分的,呵呵,有这种可能,但是估计人会累死,开个玩笑,当然是通过机器识别的,海量的图片只有机器识别才能做到。 那用python能不能实现这种功能呢?答案是:能 利用python的PIL模块的强大的 图像处理 功能就可以做到,下面上代码:

import colorsys
def get_dominant_color(image):
颜色模式转换,以便输出rgb颜色值
image = image.convert('RGBA')
生成缩略图,减少计算量,减小cpu压力
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]):
    # 跳过纯黑色
    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)
    # 忽略高亮色
    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
 如何使用:
 
推荐文章
小眼睛的热带鱼  ·  Python equivalent of PHP's file_get_contents on websites (NOT LOCAL FILES) · GitHub
2 月前
俊逸的火锅  ·  Python 控制台 — Blender Manual
2 月前
健身的抽屉  ·  在 Google Cloud 上使用 Machine Learning API:实验室挑战赛 | Google Skills
2 月前
直爽的黑框眼镜  ·  Difference between Auto_now_add and Auto_now in Django - GeeksforGeeks
2 月前
性感的毛豆  ·  通过SWIG实现在Python中调用C++代码 – My Home
2 月前
时尚的西红柿  ·  Matlab如何查询数组中的最小值的索引 - CSDN文库
2 年前
性感的伤疤  ·  教你用Python破解WiFi,流量自由不再是梦!(附完整源码) - 南柯树下 - 博客园
3 年前
文雅的炒饭  ·  python - Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expr
3 年前
欢快的电池  ·  尤大推荐的神器unplugin-vue-components,解放双手!以后再也不用呆呆的手动引入(组件,ui(Element-ui)库,vue hooks等) - 掘金
3 年前
儒雅的冲锋衣  ·  腾讯云开发者社区-腾讯云
3 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号