2、合并两张图像

目录

CV实现

PIL实现


使用一个函数实现两张图像合并,通过参数指定合并方式(水平或垂直或加权)。

CV实现

import cv2
import numpy as np

def merge_images_cv(image_path1, image_path2, method='horizontal', alpha=0.5):
    # 读取图像
    img1 = cv2.imread(image_path1)
    img2 = cv2.imread(image_path2)

    # 确保 alpha 在 0 和 1 之间
    alpha = max(0, min(alpha, 1))

    if method == 'horizontal':
        # 调整 img2 到 img1 的高度
        img2 = cv2.resize(img2, (img2.shape[1], img1.shape[0]))
        # 水平合并
        merged_img = np.hstack((img1, img2))
        # merged_img = np.concatenate((image1, image2), axis=1)
    elif method == 'vertical':
        # 调整 img2 到 img1 的宽度
        img2 = cv2.resize(img2, (img1.shape[1], img2.shape[0]))
        # 垂直合并
        merged_img = np.vstack((img1, img2))
        # merged_img = np.concatenate((image1, image2), axis=0)
    elif method == 'weighted':
        # 加权合并,确保两张图像大小相同
        img2 = cv2.resize(img2, (img1.shape[1], img1.shape[0]))
        # 加权合并
        merged_img = cv2.addWeighted(img1, alpha, img2, 1 - alpha, 0)
    else:
        raise ValueError("Method must be 'horizontal', 'vertical', or 'weighted'")

    return merged_img

# 使用示例
merged_image = merge_images_cv('path_to_first_image.jpg', 'path_to_second_image.jpg', method='horizontal')
cv2.imwrite('merged_image.jpg', merged_image)

PIL实现

from PIL import Image

def merge_images_pil(image_path1, image_path2, method='horizontal', alpha=0.5):
    # 打开图像
    img1 = Image.open(image_path1)
    img2 = Image.open(image_path2)

    # 确保 alpha 在 0 和 1 之间
    alpha = max(0, min(alpha, 1))

    if method == 'horizontal':
        # 调整 img2 到 img1 的高度
        img2 = img2.resize((img2.width, img1.height))
        # 水平合并
        merged_img = Image.new('RGB', (img1.width + img2.width, img1.height))
        merged_img.paste(img1, (0, 0))
        merged_img.paste(img2, (img1.width, 0))
    elif method == 'vertical':
        # 调整 img2 到 img1 的宽度
        img2 = img2.resize((img1.width, img2.height))
        # 垂直合并
        merged_img = Image.new('RGB', (img1.width, img1.height + img2.height))
        merged_img.paste(img1, (0, 0))
        merged_img.paste(img2, (0, img1.height))
    elif method == 'weighted':
        # 加权合并,确保两张图像大小相同
        img2 = img2.resize((img1.width, img1.height))
        # 加权合并
        merged_img = Image.blend(img1, img2, alpha)
    else:
        raise ValueError("Method must be 'horizontal', 'vertical', or 'weighted'")

    return merged_img

# 使用示例
merged_image = merge_images_pil('path_to_first_image.jpg', 'path_to_second_image.jpg', method='horizontal')
merged_image.save('merged_image.jpg')

你可能感兴趣的:(小知识,图像处理,opencv,计算机视觉,人工智能)