最近有网友私信我,问如何把多张图片合成一张马赛克图片的样子
说是女儿从出生到现在,所有的照片,大概有上百张,所以想使用这些照片合成一张,当做生日礼物
那我们今天就用上次爬表情包的图片来做一次马赛克图片,2万张合成一张,想想就很激动
图片素材
4K高清原图
import cv2
import glob
import argparse
import numpy as np
from tqdm import tqdm # 进度条
from itertools import product # 迭代器
def parsArgs():
parser = argparse.ArgumentParser('拼接马赛克图片')
parser.add_argument('--targetpath', type=str, default='examples/3.jpg', help='目标图像路径')
parser.add_argument('--outputpath', type=str, default='output.jpg', help='输出图像的路径')
parser.add_argument('--sourcepath', type=str, default='sourceimages', help='用来拼接图像的所有源图像文件路径')
parser.add_argument('--blocksize', type=int, default=15, help='马赛克快的大小')
args = parser.parse_args()
return args
def readSourceImages(sourcepath,blocksize):
print('开始读取图像')
设置一个列表,存放符合要求的颜色图像
sourceimages = []
avgcolors = []
每遍历一次,进度条走一次
for path in tqdm(glob.glob("{}/*.jpg".format(sourcepath))):
image = cv2.imread(path, cv2.IMREAD_COLOR)
if image.shape[-1] != 3:
continue
# 缩放尺寸
image = cv2.resize(image, (blocksize, blocksize))
# 图像颜色平均值
avgcolor = np.sum(np.sum(image, axis=0), axis=0) / (blocksize * blocksize)
sourceimages.append(image)
avgcolors.append(avgcolor)
print('结束读取')
return sourceimages,np.array(avgcolors)
def main(args):
targetimage = cv2.imread(args.targetpath)
outputimage = np.zeros(targetimage.shape,np.uint8) # int8 int16 int32 int64
sourceimages,avgcolors = readSourceImages(args.sourcepath,args.blocksize)
print('开始制作')
for i, j in tqdm(product(range(int(targetimage.shape[1]/args.blocksize)), range(int(targetimage.shape[0]/args.blocksize)))):
block = targetimage[j * args.blocksize: (j + 1) * args.blocksize, i * args.blocksize: (i + 1) * args.blocksize,:]
avgcolor = np.sum(np.sum(block, axis=0), axis=0) / (args.blocksize * args.blocksize)
distances = np.linalg.norm(avgcolor - avgcolors, axis=1)
idx = np.argmin(distances)
outputimage[j * args.blocksize: (j + 1) * args.blocksize, i * args.blocksize: (i + 1) * args.blocksize, :] = \
sourceimages[idx]
cv2.imwrite(args.outputpath, outputimage)
cv2.imshow('result', outputimage)
print('制作完成')
if __name__ == '__main__':
# run
main(parseArgs())