您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

分享一个趣味性十足的Python可视化技巧

2025/11/23 10:27:39发布16次查看
如下图所示:
在示例照片当中有着各种各样的颜色,我们将通过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) = 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可视化技巧的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product