何谓马赛克拼图,简单来说就是将若干小图片平凑成为一张大图,如下图路飞一样,如果放大看你会发现里面都是一些海贼王里面的图片。
LUFFY
其实整个项目很小,项目总共代码量不过100行左右。
itchat
;numpy
和PIL
库。我这边是用的所有微信好友头像作为的数据源,你们如果有其他的数据源也可以的,可以直接跳过这步。
爬取微信好友头像我使用的是itchat
,里面已经有封装好了的API,直接调用就可以,将所有的好友头像保存到一个文件夹供后期调用。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : AwesomeTang
# @File : Wechat_Icon.py
# @Version : Python 3.7
# @Time : 2019-06-29 23:35
import os
import itchat
itchat.login()
friends = itchat.get_friends(update=True)
base_folder = 'wechat'
if os.path.isdir(base_folder):
pass
else:
os.mkdir(base_folder)
for item in friends:
img = itchat.get_head_img(item['UserName'])
# 使用用户昵称作为文件名
path = os.path.join(base_folder, '{}.jpg'.format(item['NickName'].replace('/', '')))
with open(path, 'wb') as f:
f.write(img)
print('{} 写入完成...'.format(item['NickName']))
说起来好像很简单,但实际操作起来只能......
聪明的你应该知道了,最麻烦的地方其实是怎么找到最相似的图片,什么切割图片,拼接图片都是没啥难度,寻找最相似的图片算法是参考了 阮一峰的博客。
)个像素点,分别去与平均值比较大小,高于平均值的记为1,小于平均值的记为0,这样我们每张图片相当于得到了一个类似[0,1,1,0,1,0....0,1,1]的‘编码’。
np.equal()
计算相同的点了,取相同位数最多的那张头像即为最相似的图片。不过我一步一步的操作完成之后得到的是如下效果:
你们能看出来是什么吗,然后我又......
然后好像就成功了......
放大之后是这个效果:
然后便能去朋友圈愉快的装逼了???
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : AwesomeTang
# @File : Resemble.py
# @Version : Python 3.7
# @Time : 2019-06-23 13:52
from PIL import Image
import os
import numpy as np
class Config:
corp_size = 40
filter_size = 50
def mapping_table(pic_folder='wechat'):
"""
What this function do?
1. transverse every image in PIC_FOLDER;
2. resize every image in (8, 8) and covert into GREY;
3. CODE for every image, CODE like [1, 0, 1, 1, 0....1]
4. build a dict to gather all image and its CODE.
:param pic_folder: path of pictures folder.
:return: a dict
"""
suffix = ['jpg', 'jpeg', 'JPG', 'JPEG', 'gif', 'GIF', 'png', 'PNG']
if not os.path.isdir(pic_folder):
raise OSError('Folder [{}] is not exist, please check.'.format(pic_folder))
pic_list = os.listdir(pic_folder)
results = {}
pic_dic = {}
for idx, pic in enumerate(pic_list):
if pic.split('.')[-1] in suffix:
path = os.path.join(pic_folder, pic)
try:
img = Image.open(path).resize((Config.corp_size, Config.corp_size), Image.ANTIALIAS).convert('L')
results[idx] = pic_code(np.array(img.resize((8, 8), Image.ANTIALIAS)))
pic_dic[idx] = img
except OSError:
pass
return results, pic_dic
def pic_code(image: np.ndarray):
"""
To make a one-hot code for IMAGE.
AVG is mean of the array(IMAGE).
Traverse every pixel of IMAGE, if the pixel value is more then AVG, make it 1, else 0.
:param image: an array of picture
:return: A sparse list with length [picture's width * picture's height].
"""
width, height = image.shape
avg = image.mean()
one_hot = np.array([1 if image[i, j] > avg else 0 for i in range(width) for j in range(height)])
return one_hot
class PicMerge:
def __init__(self, pic_path, corp_size=20):
self.mapping_table, self.pictures = mapping_table(pic_folder='wechat')
self.picture = Image.open(pic_path).convert('L')
self.corp_size = corp_size
def corp(self):
width, height = self.picture.size
width = (width // Config.corp_size) * Config.corp_size
height = (height // Config.corp_size) * Config.corp_size
self.picture.resize((width, height), Image.ANTIALIAS)
picture = np.array(self.picture)
for i in range(width // Config.corp_size):
for j in range(height // Config.corp_size):
slice_mean = picture[i * Config.corp_size:(i + 1) * Config.corp_size,
j * Config.corp_size:(j + 1) * Config.corp_size].mean()
candidate = sorted([(key_, abs(np.array(value_).mean() - slice_mean))
for key_, value_ in self.pictures.items()],
key=lambda item: item[1])[:Config.filter_size]
slice_ = Image.fromarray(picture[i * Config.corp_size:(i + 1) * Config.corp_size,
j * Config.corp_size:(j + 1) * Config.corp_size]).convert('L')
one_hot = pic_code(np.array(slice_.resize((8, 8), Image.ANTIALIAS)))
a = [(key_, np.equal(one_hot, self.mapping_table[key_]).mean()) for key_, _ in candidate]
a = max(a, key=lambda item: item[1])
picture[i * Config.corp_size:(i + 1) * Config.corp_size,
j * Config.corp_size:(j + 1) * Config.corp_size] = self.pictures[a[0]]
picture = Image.fromarray(picture)
picture.show()
picture.save('result.jpg')
if __name__ == "__main__":
p = PicMerge(pic_path='WechatIMG97.jpeg')
p.corp()
代码部分目前只完成灰度图片的,RGB模式下的暂未开整,搞定之后再继续更新。
skr~~ skr~~~