import glob
import argparse
import cv2
import numpy
from tqdm import tqdm
from itertools import product
def parsArgs():
parser = argparse.ArgumentParser('拼接马赛克图片')
parser.add_argument('--targetpath',type=str,default='3.jpg',help='目标图像路径')
parser.add_argument('--outputpath',type=str,default='output.jpg',help='输出图像的路径')
parser.add_argument('--sourcepath',type=str,default='picture2',help='拼接图片所在路径')
parser.add_argument('--blocksize',type=int,default=15,help='马赛克块大小')
args = parser.parse_args()
return args
def readSourceImages(sourcepath,blocksize):
print('开始读取图像数据')
sourceimages = []
avgclolrs = []
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 = numpy.sum(numpy.sum(image,axis=0),axis=0) / (blocksize * blocksize)
sourceimages.append(image)
avgclolrs.append(avgcolor)
print('读取结束')
return sourceimages,numpy.array(avgclolrs)
def main(args):
targetimage = cv2.imread(args.targetpath)
outputimage = numpy.zeros(targetimage.shape,numpy.uint8)
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 = numpy.sum(numpy.sum(block,axis=0),axis=0) / (args.blocksize *args.blocksize)
distances = numpy.linalg.norm(avgcolor - avgcolors,axis=1)
idx = numpy.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__':
main(parsArgs())
跟着写完了,明天看视频学习下,程序运行成功,中间遇到的问题,图片一开始是中文,运行失败了,之后名称批量修改成数字,运行成功类似下面的效果:
明天继续学习看看把这个优化下,图片能更加清晰,放大后的小的图片像素也能比较清楚。