将两张图片合并成一张图片,可以使用多种方法,具体取决于你想要如何合并它们。以下是几种常见的合并方式:
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')