import os
from PIL import Image
import numpy as np
class thousandMapImaging:
def __init__(self):
self.picture_path = 'assets/picture.jpeg'
self.thousand_picture_path = 'assets/images/'
def compute_mean(self, imgPath):
'''
获取图像平均颜色值
:param imgPath: 缩略图路径
:return: (r,g,b)整个缩略图的rgb平均值
'''
im = Image.open(imgPath)
im = im.convert('RGB')
'''如:
[[ 60 33 24]
[ 58 34 24]
...
[188 152 136]
[ 99 96 113]]
[[ 60 33 24]
[ 58 34 24]
...
[188 152 136]
[ 99 96 113]]
'''
imArray = np.array(im)
R = np.mean(imArray[:, :, 0])
G = np.mean(imArray[:, :, 1])
B = np.mean(imArray[:, :, 2])
return (R, G, B)
def getImgList(self):
"""
获取缩略图的路径及平均色彩
:return: list,存储了图片路径、平均色彩值。
"""
imgList = []
for pic in os.listdir(self.thousand_picture_path):
imgPath = self.thousand_picture_path + pic
imgRGB = self.compute_mean(imgPath)
imgList.append({
"imgPath": imgPath,
"imgRGB": imgRGB
})
return imgList
def computeDis(self, color1, color2):
'''
计算两张图的颜色差,计算机的是色彩空间距离。
dis = (R**2 + G**2 + B**2)**0.5
参数:color1,color2 是色彩数据 (r,g,b)
'''
dis = 0
for i in range(len(color1)):
dis += (color1[i] - color2[i]) ** 2
dis = dis ** 0.5
return dis
def create_image(self, bgImg, imgDir, N=10, M=50):
'''
根据背景图,用头像填充出新图
bgImg:背景图地址
imgDir:头像目录
N:背景图缩放的倍率
M:头像的大小(MxM)
'''
imgList = self.getImgList()
bg = Image.open(bgImg)
bgArray = np.array(bg)
width = bg.size[0] * M
height = bg.size[1] * M
newImg = Image.new('RGB', (width, height))
for x in range(bgArray.shape[0]):
for y in range(bgArray.shape[1]):
minDis = 10000
index = 0
for img in imgList:
dis = self.computeDis(img['imgRGB'], bgArray[x][y])
if dis < minDis:
index = img['imgPath']
minDis = dis
tempImg = Image.open(index)
tempImg = tempImg.resize((M, M))
newImg.paste(tempImg, (y * M, x * M))
print('(%d, %d)' % (x, y))
newImg.save('final.jpg')
def hello(self):
'''
This is a welcome speech
:return: self
'''
print('*' * 50)
print(' ' * 20 + '千图成像')
print(' ' * 5 + 'Author: autofelix Date: 2022-01-14 13:14')
print('*' * 50)
return self
def run(self):
'''
The program entry
'''
self.create_image(self.picture_path, self.thousand_picture_path)
if __name__ == '__main__':
thousandMapImaging().hello().run()