当前位置: 首页 > 科技观察

分享一个有趣的Python可视化技巧

时间:2023-03-21 10:11:33 科技观察

如下图:示例照片中有各种颜色,我们将使用Python中的可视化模块和opencv模块识别图片中的所有颜色元素,并添加到视觉图表的颜色匹配。导入模块并加载图片。按照惯例,第一步是导入模块。用于可视化的模块是matplotlib模块。我们从图片中提取颜色后,会保存在颜色映射表中,所以我们需要用到colormap模块,同样需要导入。importnumpyasnpiimportpandasaspdimportmatplotlib.pyplotasptimportmatplotlib.patchesaspatchesimportmatplotlib.imageasmpimgfromPILimportImagefrommatplotlib.offsetboximportOffsetImage,AnnotationBboximportcv2importextcolorsfromcolormapimport然后加载图像如下:rgb2hex'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_xoutput([((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)我们将整合e将以上结果转化为DataFrame数据集,代码如下:defcolor_to_df(input_color):colors_pre_list=str(input_color).replace('([(','').split(',(')[0:-1]df_rgb=[i.split('),')[0]+')'foriincolors_pre_list]df_percent=[i.split('),')[1].replace(')','')foriincolors_pre_list]#将RGB转换为十六进制颜色df_color_up=[rgb2hex(int(i.split(",")[0].replace("(","")),int(i.split(",")[1]),int(i.split(",")[2].replace(")","")))foriindf_rgb]df=pd.DataFrame(zip(df_color_up,df_percent),columns=['c_code','occurence'])returndf我们尝试调用上面的自定义函数,并将结果输出到DataFrame数据集df_color=color_to_df(colors_x)df_coloroutput绘制图表接下来是绘制图表阶段,使用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()输出输出的饼图显示了每种不同颜色的比例,我们进一步将原始图像放在圆圈中。imagebox=OffsetImage(img,zoom=2.3)ab=AnnotationBbox(imagebox,(0,0))ax1.add_artist(ab)output最后做一个调色板,列出原图的所有不同颜色,代码如下如下:##palettex_posi,y_posi,y_posi2=160,-170,-170forcinlist_color:iflist_color.index(c)<=5:y_posi+=180rect=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+=180rect=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()输出实战环节,我们将以上代码全部封装成一个完整的函数。defexact_color(input_image,resize,tolerance,zoom):output_width=resizeimg=Image.open(input_image)如果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_imageimg.save(resize_name)else:resize_name=input_imagefig.set_facecolor('white')ax2.axis('off')bg=plt.imread('bg.png')plt.imshow(bg)plt.tight_layout()returnplt.show()exact_color('test_2.png',900,12,2.5)输出