Python拼接微信好友头像大图的实现方法

yipeiwu_com4年前Python基础

基于 itchat 库来获取微信好友头像并执行拼接操作,对微信上文字化好友列表数据进行可视化展示。

获取好友头像

def save_avatar(folder):
 """
 保存微信好友头像
 :param folder: 保存的文件夹
 """
 itchat.auto_login(hotReload=True)
 users = itchat.get_friends() or []
 print('%d friends found.' % len(users))
 if not os.path.exists(folder):
  os.makedirs(folder)
 index = 1
 for i, user in enumerate(users):
  nickname = user.RemarkName
  username = user.UserName
  file_path = os.path.join(folder, '%03d_%s.png' % (i, nickname))
  if not os.path.isfile(file_path): # 不重复下载
   avatar = itchat.get_head_img(username)
   with open(file_path, 'w') as f:
    f.write(avatar)
    print('Download %d: %s' % (index, file_path))
    index += 1

这里只需要传入一个保存头像的文件夹即可,运行 itchat.auto_login(hotReload=True) 后会弹出微信扫码界面让你授权微信登录,以便接下来的好友数据获取。

在图片下载时,我添加了一个防止重复下载的判断,以免多次运行时每次都要重新进行头像的下载。

取出待拼接头像

def get_image_files(folder, filters=None):
 """
 取出待拼接头像
 :param folder: 目标文件夹
 :param filters: 需要过滤的图片
 :return: 头像路径
 """
 filters = filters or []
 filenames = [os.path.join(folder, sub) for sub in os.listdir(folder)
     if sub.endswith('.png') and not filters.__contains__(sub)]
 return filenames

这里单独写个方法是为了把过滤的逻辑封装进来,以便于去掉指定的微信好友的头像(比如纯色的头像在拼接之后的大图看上去很明显,非强迫症可忽略)。

计算拼接的排列

def calculate_align_way(image_num, force_align=False):
 """
 计算图片排版对齐方式
 :param image_num: 图片数量
 :return: (rowls, columns)
 """
 actual_value = image_num ** 0.5
 suggest_value = int(actual_value)
 if actual_value == suggest_value or force_align:
  return suggest_value, suggest_value
 else:
  return suggest_value, suggest_value + 1

因为需要知道最终拼接图片的行列数,所有这里单独定义一个计算方法。算法就是直接对图片总数开根号,取出的结果如果正好是整数,就直接返回该结果。如果不是整数(大多数情况都如此),则根据参数 force_align 来决定是否强制进行正好全部铺满的显示。如果设为 True ,能强制铺满,但会有部分好友未显示完全;反之则是相对的情况。 后面发现拼接图片最后一行有很多黑色空位时,只需要更改该参数为True即可。

拼接

def join_images(image_files, rows, cols, width, height, save_file=None):
 """
 拼接操作
 :param image_files: 待拼接的图片
 :param rows: 行数
 :param cols: 列数
 :param width: 每张小头像的宽度
 :param height: 每张小头像的高度
 :param save_file: 拼接好图片的保存路径
 """
 canvas = np.ones((height * rows, width * cols, 3), np.uint8)
 for row in range(rows):
  for col in range(cols):
   index = row * cols + col
   if index >= len(image_files):
    break
   file_path = image_files[index]
   im = Image.open(file_path)
   im = im.resize((width, height))
   im_data = np.array(im)
   if len(im_data.shape) == 2:
    im_data = np.expand_dims(im_data, -1)
   x = col * width
   y = row * height
   canvas[y: y + height, x: x + width, :] = im_data
 image = Image.fromarray(canvas)
 image.show()
 if save_file:
  image.save(save_file)

拼接图片调用的是科学计算包 numpy 和图片库 PIL ,主要就是对 ndarray 进行操作。

最终将上面的步骤全部串联起来,执行如下主函数,便得到上面的拼接图片。

FOLDER = 'avatars'

if __name__ == '__main__':
 # 保存所有好友头像
 save_avatar(FOLDER)

 # 取到准备拼接的头像
 image_files = get_image_files(FOLDER)

 # 计算拼接的行列
 rows, columns = calculate_align_way(len(image_files), force_align=True)

 # 执行拼接操作
 join_images(image_files, rows, columns, 64, 64, 'result.png')

Github源码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

梯度下降法介绍及利用Python实现的方法示例

梯度下降法介绍及利用Python实现的方法示例

本文主要给大家介绍了梯度下降法及利用Python实现的相关内容,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍吧。 梯度下降法介绍 梯度下降法(gradient descen...

Python3实现定时任务的四种方式

最近做一个小程序开发任务,主要负责后台部分开发;根据项目需求,需要实现三个定时任务: 1>定时更新微信token,需要2小时更新一次; 2>商品定时上线; 3>定时检测...

在Python中关于中文编码问题的处理建议

字符串是Python中最常用的数据类型,而且很多时候你会用到一些不属于标准ASCII字符集的字符,这时候代码就很可能抛出UnicodeDecodeError: 'ascii' codec...

对Python信号处理模块signal详解

Python中对信号处理的模块主要是使用signal模块,但signal主要是针对Unix系统,所以在Windows平台上Python不能很好的发挥信号处理的功能。 要查看Python中...

opencv导入头文件时报错#include的解决方法

opencv导入头文件时报错#include的解决方法

一、首先要确保你的电脑上opencv的环境和visual studio上的环境都配置好了,测试的时候通过了没有问题。 二、那么只要在你项目里面的属性设置里面配置一下包含目录就OK了,具体...