preface
A picture is made up of numerous pixels, so we will fill these pixels with pictures
Knowledge points:
1. cv2
2. numpy
3. tqdm
4. argparse
Development environment:
Python 3.6
Pycharm
Ideas:
1. Input
2. Calculation and processing
3. Output
4. Display
Add Penguin Group 695185429 and you can get it for free. All the information is in the group file. Materials can be obtained, including but not limited to Python practice, PDF electronic documents, interview brochures, learning materials, etc
step
1, Import tool
import cv2 import glob import argparse import numpy as np from tqdm import tqdm # progress bar from itertools import product # iterator
2, Picture file
def parseArgs(): parser = argparse.ArgumentParser('Mosaic picture') parser.add_argument('--targetpath', type=str, default='examples/1.jpg', help='Target image path') parser.add_argument('--outputpath', type=str, default='output.jpg', help='Output image path') parser.add_argument('--sourcepath', type=str, default='sourceimages', help='All source image folder paths for stitching images') parser.add_argument('--blocksize', type=int, default=15, help='Mosaic block size') args = parser.parse_args() return args
3, Read all source images and calculate the corresponding color average
def readSourceImages(sourcepath,blocksize): print('Start reading image') # List of legal images sourceimages = [] # Average color list 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('End read') return sourceimages,np.array(avgcolors)
4, Call all functions
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('Start production') 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('Production completed')
5, Call
if __name__ == '__main__': # run main(parseArgs())
The operation effect is as follows:
Comparison of final works and drawings