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