【Python OpenCV】使用OpenCV实现两张图片拼接

问题引入:

如何使用Python OpenCV实现两张图片的水平拼接和垂直拼接

代码实现:

import cv2
import numpy as np

def image_hstack(image_path_1, image_path_2):
    """两张图片左右拼接
    """
    img1 = cv2.imread(image_path_1)
    img2 = cv2.imread(image_path_2)

    img1_shape = img1.shape
    img2_shape = img2.shape

    if img1_shape[0] != img2_shape[0]:
        if img1_shape[0] > img2_shape[0]:
            # 如果img1高度大于img2,在img2的上下添加边框
            img2 = cv2.copyMakeBorder(img2, 0, img1_shape[0] - img2_shape[0], 0, 0, cv2.BORDER_CONSTANT, value=[0, 0, 0])
        else:
            # 如果img2高度大于img1,在img1的上下添加边框
            img1 = cv2.copyMakeBorder(img1, 0, img2_shape[0] - img1_shape[0], 0, 0, cv2.BORDER_CONSTANT, value=[0, 0, 0])

    new_image = np.hstack((img1, img2))
    
    return new_image


def image_vstack(image_path_1, image_path_2):
    """两张图片上下拼接
    """
    img1 = cv2.imread(image_path_1)
    img2 = cv2.imread(image_path_2)

    img1_shape = img1.shape
    img2_shape = img2.shape

    if img1_shape[1] != img2_shape[1]:
        if img1_shape[1] > img2_shape[1]:
            # 如果img1宽度大于img2,在img2的左右添加边框
            img2 = cv2.copyMakeBorder(img2, 0, 0, 0, img1_shape[1] - img2_shape[1], cv2.BORDER_CONSTANT, value=[0, 0, 0])
        else:
            # 如果img2宽度大于img1,在img1的左右添加边框
            img1 = cv2.copyMakeBorder(img1, 0, 0, 0, img2_shape[1] - img1_shape[1], cv2.BORDER_CONSTANT, value=[0, 0, 0])

    new_image = np.vstack((img1, img2))
    return new_image


if __name__ == "__main__":
    image_path_1 = r"F:\400026.jpg"
    image_path_2 = r"F:\2.jpg"

    # new_image = image_hstack(image_path_1, image_path_2)
    new_image = image_vstack(image_path_1, image_path_2)
    # cv2.imshow("res", new_image)
    # cv2.waitKey(0)

    cv2.imwrite("image_concate.jpg",new_image)

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