百度图片中有一个按照颜色搜图片的功能,其核心算法是提取图片主体颜色法,本文将使用python实现提取图片主体颜色算法。

百度将图片主体颜色归类到如下11中颜色:

颜色代码:

label_colors = [[50, 50, 50],[250, 250, 250],[215, 68, 186],[0, 101, 254],[222, 32, 32],[254, 191, 0],[137, 43, 207],[89, 167, 37],[6, 183, 200],[254, 108, 0],[115, 52, 19],]

因为cv2和PIL在读取gif图片时候会出现问题,所以我们使用imageio读取gif:

    try:tmp = imageio.mimread(img_path)if tmp is not None:imt = np.array(tmp)imt = imt[0]img = imt[:, :, 0:3]img = Image.fromarray(img)imageio_success = Trueexcept:imageio_success = Falseif not imageio_success:img = Image.open(img_path)

可以设置成截取图片中心部分:

input_size = 100
crop_size = 100img = img[int((input_size - crop_size) / 2):int((input_size + crop_size) / 2), int((input_size - crop_size) / 2):int((input_size + crop_size) / 2), :]

颜色值量化,将256种颜色量化到8:

def quantization(img):img = np.right_shift(img, quantization_factor)img = np.left_shift(img, quantization_factor)return img

提取主体颜色并排序:

def sort_color(img):img_str = np.asarray(img, np.str)img_str = img_str.reshape((-1, 3))r_g_b = np.char.array(img_str[..., 0]) + '-' + np.char.array(img_str[..., 1]) + '-' + np.char.array(img_str[..., 2])r_g_b = r_g_b.tolist()r_g_b_count = Counter(r_g_b)r_g_b_count = sorted(r_g_b_count.items(), key=lambda x: x[1], reverse=True)max_count_color = r_g_b_count[0][0].split('-')max_count_color = np.asarray(max_count_color, np.int)return max_count_color, r_g_b_count[0][1]

从11种颜色中选取图片代表颜色:

def get_nearest_color(max_count_color):nearest_index_euc = -1nearest_distance_euc = 99999nearest_index_abs = -1nearest_distance_abs = 99999for i, label_color in enumerate(label_colors):euc = get_euc_distance(label_color, np.asarray(max_count_color))if euc < nearest_distance_euc:nearest_distance_euc = eucnearest_index_euc = iabs = get_abs_distance(label_color, np.asarray(max_count_color))if abs < nearest_distance_abs:nearest_distance_abs = absnearest_index_abs = ireturn nearest_distance_euc, nearest_index_euc, nearest_distance_abs, nearest_index_absdef get_euc_distance(color1, color2):return np.linalg.norm(color1 - color2)def get_abs_distance(color1, color2):return np.sum(np.abs(color1 - color2))

返回值说明:

max_count_color         图片主体颜色
        max_count_color_ratio   主题颜色占图片面积的比例
        nearest_distance_euc    使用欧式距离,计算图片代表颜色,返回具体距离数值
        nearest_index_euc       使用欧式距离计算出的图片代表颜色
        nearest_distance_abs    使用L1距离,计算图片代表颜色,返回具体距离数值
        nearest_index_abs       使用L1距离计算出的图片代表颜色

全部代码:

# coding=utf-8
# ================================================================
#
#   File name   : color_service.py
#   Author      : Faye
#   E-mail      : xiansheng14@sina.com
#   Created date: 2022/12/10 22:45
#   Description :
#
# ================================================================
import numpy as np
from collections import Counter
from PIL import Image
import imageiolabel_colors = [[50, 50, 50],[250, 250, 250],[215, 68, 186],[0, 101, 254],[222, 32, 32],[254, 191, 0],[137, 43, 207],[89, 167, 37],[6, 183, 200],[254, 108, 0],[115, 52, 19],]input_size = 100
crop_size = 100
quantization_factor = 5def get_img_main_color(img):"""提取图片主体颜色:param img: PIL格式的图片:return:max_count_color         图片主体颜色max_count_color_ratio   主题颜色占图片面积的比例nearest_distance_euc    使用欧式距离,计算图片代表颜色,返回具体距离数值nearest_index_euc       使用欧式距离计算出的图片代表颜色nearest_distance_abs    使用L1距离,计算图片代表颜色,返回具体距离数值nearest_index_abs       使用L1距离计算出的图片代表颜色"""img = img.resize((input_size, input_size), Image.ANTIALIAS)img = np.asarray(img)if len(img.shape) == 2:img = np.repeat(img[..., np.newaxis], 3, axis=-1)if img.shape[-1] == 4:img = img[..., 0:3]img = img[int((input_size - crop_size) / 2):int((input_size + crop_size) / 2), int((input_size - crop_size) / 2):int((input_size + crop_size) / 2), :]# is_gray = check_gray(img)h, w, _ = img.shapeimg = quantization(img)max_count_color, max_count_color_ratio = sort_color(img)nearest_color = get_nearest_color(max_count_color)res = []res.append(max_count_color)res.append(max_count_color_ratio)for n in nearest_color:res.append(n)return resdef quantization(img):"""颜色值量化:param img::return:"""img = np.right_shift(img, quantization_factor)img = np.left_shift(img, quantization_factor)return imgdef sort_color(img):"""提取主体颜色并排序:param img::return:"""img_str = np.asarray(img, np.str)img_str = img_str.reshape((-1, 3))r_g_b = np.char.array(img_str[..., 0]) + '-' + np.char.array(img_str[..., 1]) + '-' + np.char.array(img_str[..., 2])r_g_b = r_g_b.tolist()r_g_b_count = Counter(r_g_b)r_g_b_count = sorted(r_g_b_count.items(), key=lambda x: x[1], reverse=True)max_count_color = r_g_b_count[0][0].split('-')max_count_color = np.asarray(max_count_color, np.int)return max_count_color, r_g_b_count[0][1]def get_nearest_color(max_count_color):"""从11种颜色中选取图片代表颜色:param max_count_color::return:"""nearest_index_euc = -1nearest_distance_euc = 99999nearest_index_abs = -1nearest_distance_abs = 99999for i, label_color in enumerate(label_colors):euc = get_euc_distance(label_color, np.asarray(max_count_color))if euc < nearest_distance_euc:nearest_distance_euc = eucnearest_index_euc = iabs = get_abs_distance(label_color, np.asarray(max_count_color))if abs < nearest_distance_abs:nearest_distance_abs = absnearest_index_abs = ireturn nearest_distance_euc, nearest_index_euc, nearest_distance_abs, nearest_index_absdef get_euc_distance(color1, color2):return np.linalg.norm(color1 - color2)def get_abs_distance(color1, color2):return np.sum(np.abs(color1 - color2))def check_gray(img):if len(img.shape) == 2:return Trueif img.shape[-1] == 4:img = img[..., 0:3]avg = np.mean(img, axis=-1)r_diff = np.abs(img[..., 0] - avg)g_diff = np.abs(img[..., 1] - avg)b_diff = np.abs(img[..., 2] - avg)diff_count = r_diff + g_diff + b_diffdiff_count_gt = np.where(diff_count > 10)[0]if len(diff_count_gt) == 0:return Truegray_per = len(diff_count_gt) / input_size**2return gray_per > 0.03if __name__ == '__main__':img_path = r'1.jpg'imageio_success = Falsetry:tmp = imageio.mimread(img_path)if tmp is not None:imt = np.array(tmp)imt = imt[0]img = imt[:, :, 0:3]img = Image.fromarray(img)imageio_success = Trueexcept:imageio_success = Falseif not imageio_success:img = Image.open(img_path)max_count_color, max_count_color_ratio, nearest_distance_euc, nearest_index_euc, nearest_distance_abs, nearest_index_abs = get_img_main_color(img)print(max_count_color, max_count_color_ratio, nearest_distance_euc, nearest_index_euc, nearest_distance_abs, nearest_index_abs)

百度图片源码流出~按照颜色搜图片~提取图片主体颜色相关推荐

  1. python爬取图片源码_python抓取百度图片源码

    #!/usr/bin/python # -*- coding:utf-8 -*- import httplib2 import urllib.request import json #import u ...

  2. python爬取图片源码_半次元图片爬取-python爬取半次元图片源码下载-西西软件下载...

    python爬取半次元图片源码,由大神自制的python爬取工具,本源码针对半次元图片平台,可以爬取最新的网站图片资源,支持自定义保存目录,非常方便,需要requests库的支持,想要相关源码资源的朋 ...

  3. 分享66个ASP贺卡图片源码,总有一款适合您

    分享66个ASP贺卡图片源码,总有一款适合您 66个ASP贺卡图片源码下载链接:https://pan.baidu.com/s/1kkCBziEePMdsXsMb1Ytbaw?pwd=lswt  提取 ...

  4. 【老生谈算法】MATLAB生成雪花图片源码——生成雪花图片

    MATLAB生成雪花图片源码 1.文档下载: 本算法已经整理成文档如下,有需要的朋友可以点击进行下载 序号 文档(点击下载) 本项目文档 [老生谈算法]MATLAB生成雪花图片源码.doc 2.算法详 ...

  5. 分享107个ASP贺卡图片源码,总有一款适合您

    分享107个ASP贺卡图片源码,总有一款适合您 107个ASP贺卡图片源码下载链接:https://pan.baidu.com/s/15zaUiNl-PifQY0SSWMjgow?pwd=a1b8  ...

  6. 分享88个ASP贺卡图片源码,总有一款适合您

    分享88个ASP贺卡图片源码,总有一款适合您 88个ASP贺卡图片源码下载链接:https://pan.baidu.com/s/1OilB4S8FjYVi3f3q08OdUA?pwd=07dy  提取 ...

  7. 利用几种颜色量化方法提取图片颜色色调

    利用几种颜色量化方法提取图片颜色色调 利用几种颜色量化方法提取图片颜色色调 1 k-means方法(在RGB空间) 2 k-means方法(Lab颜色空间) 3 最小方差量化方法rgb2ind() 4 ...

  8. 颜色量化 matlab,利用几种颜色量化方法提取图片颜色色调

    利用几种颜色量化方法提取图片颜色色调 这里主要用3种方法:包含两种k-means方法和一种matlab自带的最小方差量化方法. 为了方便对比,文中选用梵高的星空(The Starry Night)作为 ...

  9. html5canvas绘制图片源码,HTML5 CANVAS:绘制图片

    HTML5 CANVAS:绘制图片 通过前面的学习,我们现在已经可以在HTML5 canvas中绘制图形和文字,并给它们设置一些样式.我们还可以在中绘制图片.用于在作为绘制源的图片可以是下面的几种元素 ...

最新文章

  1. 模型可视化_20210208
  2. How to Rate a Software Developer
  3. python安装docx库_linux 环境下的python 安装 docx 的过程
  4. 在Win8中创建热点,共享网络
  5. 技术干货 | 基于 Qt Quick Plugin 快速构建桌面端跨平台组件
  6. 与孩子一起学编程python_与的解释|与的意思|汉典“与”字的基本解释
  7. 深入理解计算机系统(4.2)---硬件的魅力
  8. php scandir遍历,php使用scandir()函数扫描指定目录下所有文件示例
  9. Java获取接口所有实现类的方式
  10. element下拉框回显问题
  11. 初探Bootstrap
  12. 简单几步把Spring Boot 项目部署到 K8S,步骤来了!
  13. js 为对象添加和删除属性
  14. include包含文件查找的顺序 .
  15. 性能优化:缓存使用的秘密
  16. 地理探测器 GD包下载及应用(R语言,基于Rstudio)
  17. 暗黑破坏神(DIABLOII 1.11B)BOT 及源代码公开下载
  18. c语言malloc(c语言malloc头文件)
  19. matlab系统辨识工具箱的使用
  20. 真格量化的回测交易撮合机制简介

热门文章

  1. 云原生热门话题|什么是可观测性-Observability
  2. 装饰者模式——NWU_LK
  3. 卸载驱动模块:已经在/lib目录下建立相应文件夹仍无法实现
  4. Adobe.* 绿色版
  5. 身份证号码校验位生成代码
  6. JAVA学到什么程度可以(实习)找工作?
  7. MATLAB怎么绘制根号x的图像,这样的函数图像用什么软件画呢?
  8. 档案丢失社保难办是谁的错?
  9. 梦幻桌面wmv_【系统萌化】pjdex制作的梦幻桌面8wmv动态背景
  10. 雪亮工程之出租屋视频管理方案