python 多张图片拼接成一张

# coding=utf-8
from PIL import Image, ImageDraw, ImageFont
import cv2
import numpy as np


def jigsaw(imgs, direction="horizontal", gap=0):
    imgs = [Image.fromarray(img) for img in imgs]
    w, h = imgs[0].size
    if direction == "horizontal":
        result = Image.new(imgs[0].mode, ((w+gap)*len(imgs)-gap, h))
        for i, img in enumerate(imgs):
            result.paste(img, box=((w+gap)*i, 0))
    elif direction == "vertical":
        result = Image.new(imgs[0].mode, (w, (h+gap)*len(imgs)-gap))
        for i, img in enumerate(imgs):
            result.paste(img, box=(0, (h+gap)*i))
    else:
        raise ValueError("The direction parameter has only two options: horizontal and vertical")
    return np.array(result)


if __name__ == '__main__':
    img1 = cv2.imread("output/frankfurt_000000_000294_leftImg8bit.png")
    img2 = cv2.imread("output/frankfurt_000000_000576_leftImg8bit.png")
    img3 = cv2.imread("output/frankfurt_000000_001016_leftImg8bit.png")
    img = jigsaw([img1, img2, img3])
    cv2.imwrite("test.png", img)

你可能感兴趣的:(Python,python,开发语言,后端)