如何将两张图片合并成一张图片

将两张图片合并成一张图片,可以使用多种方法,具体取决于你想要如何合并它们。以下是几种常见的合并方式:

1. 水平拼接(Side by Side)

将两张图片并排放置,形成一张新的图片。

import cv2
import numpy as np

def horizontal_concat(image1_path, image2_path, output_path):
    # 读取两张图片
    img1 = cv2.imread(image1_path)
    img2 = cv2.imread(image2_path)

    # 确保两张图片的高度相同
    if img1.shape[0] != img2.shape[0]:
        # 如果高度不同,可以选择裁剪或者填充其中一张图片以匹配另一张的高度
        # 这里我们选择裁剪较高的那张图片
        min_height = min(img1.shape[0], img2.shape[0])
        img1 = img1[:min_height, :]
        img2 = img2[:min_height, :]

    # 水平拼接
    stitched_img = np.hstack((img1, img2))

    # 保存结果
    cv2.imwrite(output_path, stitched_img)

# 使用示例
# horizontal_concat('path_to_image1.jpg', 'path_to_image2.jpg', 'output.jpg')

2. 垂直拼接(Top to Bottom)

将两张图片上下堆叠,形成一张新的图片。
 

def vertical_concat(image1_path, image2_path, output_path):
    # 读取两张图片
    img1 = cv2.imread(image1_path)
    img2 = cv2.imread(image2_path)

    # 确保两张图片的宽度相同
    if img1.shape[1] != img2.shape[1]:
        # 如果宽度不同,可以选择裁剪或者填充其中一张图片以匹配另一张的宽度
        # 这里我们选择裁剪较宽的那张图片
        min_width = min(img1.shape[1], img2.shape[1])
        img1 = img1[:, :min_width]
        img2 = img2[:, :min_width]

    # 垂直拼接
    stitched_img = np.vstack((img1, img2))

    # 保存结果
    cv2.imwrite(output_path, stitched_img)

# 使用示例
# vertical_concat('path_to_image1.jpg', 'path_to_image2.jpg', 'output.jpg')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值