自动拼图(同尺寸图片) gaunthan Posted on Mar 22 2021 ? Tool ? ? Python ? > 将多张尺寸相同的图片拼接成一张大图。 > > - 自动决定行数和列数,可以使用 --ncol 选项指定列数。 > - 最后一行如果缺图,会使用全白图片填补。 ## Usage ```sh $ ../concat.py images --out='overview.png' --ncol=4 ``` ```sh $ ./concat.py -h usage: concat.py [-h] [--out OUT] [--verbose VERBOSE] [--ncol NCOL] path concatenate images to one picture positional arguments: path path to images optional arguments: -h, --help show this help message and exit --out OUT path to output --verbose VERBOSE show details --ncol NCOL number of columns ``` ## Example ```sh $ ls test 0.png 100.png 200.png $ ./concat.py test --out=test.png --ncol=2 path: test files: test/0.png test/100.png test/200.png output path: test.png output format: 2 x 2, 3 images Concatenating... done ``` Before:  After:  ## Code ```python3 #!/usr/bin/env python3 # concat.py import glob import cv2 as cv import argparse import math import sys OUTPUT = 'out.png' parser = argparse.ArgumentParser(description='concatenate images to one picture') parser.add_argument('path', type=str, default='.', help='path to images') parser.add_argument('--out', type=str, default=OUTPUT, help='path to output') parser.add_argument('--verbose', type=bool, default=False, help='show details') parser.add_argument('--ncol', type=int, default=0, help='number of columns') args = parser.parse_args() print('path:', args.path) files = glob.glob(args.path + '/*.png') print('files:') for f in files: print('\t', f) print('output path:', args.out) if len(files) <= 1: print('files to concatenate should be at least 2') sys.exit(0) num = len(files) ncol = args.ncol if ncol is None or ncol == 0: ncol = math.ceil(math.sqrt(num)) nrow = math.ceil(num / ncol) print('output format: {} x {}, {} images' .format(nrow, ncol, num)) print('Concatenating...') images = [cv.imread(f) for f in files] row_images = [] for i in range(nrow): begin_index = i * ncol end_index = i*ncol + ncol if args.verbose: print('row {}: [{}, {})' .format(i, begin_index, end_index)) row_image = cv.hconcat(images[begin_index: min(end_index, num)]) if args.verbose: print('row shape:', row_image.shape) # pad white image to tail if end_index > num: num_to_pad = end_index - num if args.verbose: print('need to pad {} white image(s)' .format(num_to_pad)) white_image = images[begin_index] * 0 + 255 padding = cv.hconcat([white_image for _ in range(num_to_pad)]) if args.verbose: print('pad shape:', padding.shape) row_image = cv.hconcat([row_image, padding]) if args.verbose: print('after padded:', row_image.shape) row_images.append(row_image) out = cv.vconcat(row_images) cv.imwrite(args.out, out) print('done') ``` 赏 Wechat Pay Alipay Windows 10, WSL2 显示 GUI 窗口