Python实现提取图片中颜色并绘制成可视化图表

 更新时间:2022年07月01日 09:32:41   作者:俊欣  
今天小编来为大家分享一个有趣的可视化技巧,就是如何利用Python语言实现从图片中提取颜色然后绘制成可视化图表,感兴趣的可以尝试一下

今天小编来为大家分享一个有趣的可视化技巧,如何从图片中提取颜色然后绘制成可视化图表,如下图所示

在示例照片当中有着各种各样的颜色,我们将通过Python中的可视化模块以及opencv模块来识别出图片当中所有的颜色要素,并且将其添加到可视化图表的配色当中

导入模块并加载图片

那么按照惯例,第一步一般都是导入模块,可视化用到的模块是matplotlib模块,我们将图片中的颜色抽取出来之后会保存在颜色映射表中,所以要使用到colormap模块,同样也需要导入进来

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.image as mpimg

from PIL import Image
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

import cv2
import extcolors
from colormap import rgb2hex

然后我们先来加载一下图片,代码如下

input_name = 'test_1.png'
img = plt.imread(input_name)
plt.imshow(img)
plt.axis('off')
plt.show()

output

提取颜色并整合成表格

我们调用的是extcolors模块来从图片中提取颜色,输出的结果是RGB形式呈现出来的颜色,代码如下

colors_x = extcolors.extract_from_path(img_url, tolerance=12, limit = 12)
colors_x

output

([((3, 107, 144), 180316),
  ((17, 129, 140), 139930),
  ((89, 126, 118), 134080),
  ((125, 148, 154), 20636),
  ((63, 112, 126), 18728),
  ((207, 220, 226), 11037),
  ((255, 255, 255), 7496),
  ((28, 80, 117), 4972),
  ((166, 191, 198), 4327),
  ((60, 150, 140), 4197),
  ((90, 94, 59), 3313),
  ((56, 66, 39), 1669)],
 538200)

我们将上述的结果整合成一个DataFrame数据集,代码如下

def color_to_df(input_color):
    colors_pre_list = str(input_color).replace('([(', '').split(', (')[0:-1]
    df_rgb = [i.split('), ')[0] + ')' for i in colors_pre_list]
    df_percent = [i.split('), ')[1].replace(')', '') for i in colors_pre_list]

    # 将RGB转换成十六进制的颜色
    df_color_up = [rgb2hex(int(i.split(", ")[0].replace("(", "")),
                           int(i.split(", ")[1]),
                           int(i.split(", ")[2].replace(")", ""))) for i in df_rgb]

    df = pd.DataFrame(zip(df_color_up, df_percent), columns=['c_code', 'occurence'])
    return df

我们尝试调用上面我们自定义的函数,输出的结果至DataFrame数据集当中

df_color = color_to_df(colors_x)
df_color

output

绘制图表

接下来便是绘制图表的阶段了,用到的是matplotlib模块,代码如下

fig, ax = plt.subplots(figsize=(90,90),dpi=10)
wedges, text = ax.pie(list_precent,
                      labels= text_c,
                      labeldistance= 1.05,
                      colors = list_color,
                      textprops={'fontsize': 120, 'color':'black'}
                     )
plt.setp(wedges, width=0.3)
ax.set_aspect("equal")
fig.set_facecolor('white')
plt.show()

output

从出来的饼图中显示了每种不同颜色的占比,我们更进一步将原图放置在圆环当中,

imagebox = OffsetImage(img, zoom=2.3)
ab = AnnotationBbox(imagebox, (0, 0))
ax1.add_artist(ab)

output

最后制作一张调色盘,将原图中的各种不同颜色都罗列开来,代码如下

## 调色盘
x_posi, y_posi, y_posi2 = 160, -170, -170
for c in list_color:
    if list_color.index(c) <= 5:
        y_posi += 180
        rect = patches.Rectangle((x_posi, y_posi), 360, 160, facecolor = c)
        ax2.add_patch(rect)
        ax2.text(x = x_posi+400, y = y_posi+100, s = c, fontdict={'fontsize': 190})
    else:
        y_posi2 += 180
        rect = patches.Rectangle((x_posi + 1000, y_posi2), 360, 160, facecolor = c)
        ax2.add_artist(rect)
        ax2.text(x = x_posi+1400, y = y_posi2+100, s = c, fontdict={'fontsize': 190})

ax2.axis('off')
fig.set_facecolor('white')
plt.imshow(bg)       
plt.tight_layout()

output

实战环节

这一块儿是实战环节,我们将上述所有的代码封装成一个完整的函数

def exact_color(input_image, resize, tolerance, zoom):
    
    output_width = resize
    img = Image.open(input_image)
    if img.size[0] >= resize:
        wpercent = (output_width/float(img.size[0]))
        hsize = int((float(img.size[1])*float(wpercent)))
        img = img.resize((output_width,hsize), Image.ANTIALIAS)
        resize_name = 'resize_'+ input_image
        img.save(resize_name)
    else:
        resize_name = input_image
    
    fig.set_facecolor('white')
    ax2.axis('off')
    bg = plt.imread('bg.png')
    plt.imshow(bg)       
    plt.tight_layout()
    return plt.show()
    
exact_color('test_2.png', 900, 12, 2.5)

output

以上就是Python实现提取图片中颜色并绘制成可视化图表的详细内容,更多关于Python提取图片颜色的资料请关注脚本之家其它相关文章!

相关文章

  • django用户登录和注销的实现方法

    django用户登录和注销的实现方法

    这篇文章主要介绍了django用户登录和注销的实现方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • 能让Python提速超40倍的神器Cython详解

    能让Python提速超40倍的神器Cython详解

    今天带大家了解一下能让Python提速超40倍的神器,文章围绕着神器Cython展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下
    2021-06-06
  • 对网站内嵌gradio应用的输入输出做审核实现详解

    对网站内嵌gradio应用的输入输出做审核实现详解

    这篇文章主要为大家介绍了对网站内嵌gradio应用的输入输出做审核实现详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-04-04
  • Django缓存系统实现过程解析

    Django缓存系统实现过程解析

    这篇文章主要介绍了Django缓存系统实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • python re.match()用法相关示例

    python re.match()用法相关示例

    这篇文章主要介绍了python re.match()用法相关示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • 基于高德地图API在Python中实现地图功能的方法示例详解

    基于高德地图API在Python中实现地图功能的方法示例详解

    本文介绍在高德开放平台中,申请、获取地图API的Key的方法,同时通过简单的Python代码,调取API信息,对所得Key的可用性加以验证,感兴趣的朋友一起看看吧
    2025-01-01
  • 详解Anaconda安装tensorflow报错问题解决方法

    详解Anaconda安装tensorflow报错问题解决方法

    这篇文章主要介绍了Anaconda安装tensorflow报错问题解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • Python加速程序运行的方法

    Python加速程序运行的方法

    这篇文章主要介绍了Python加速程序运行的方法,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-07-07
  • python+matplotlib演示电偶极子实例代码

    python+matplotlib演示电偶极子实例代码

    这篇文章主要介绍了python+matplotlib演示电偶极子实例代码,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • 使用Rasterio读取栅格数据的实例讲解

    使用Rasterio读取栅格数据的实例讲解

    今天小编就为大家分享一篇使用Rasterio读取栅格数据的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11

最新评论