用python对图片进行拼接

pillow库可能有问题

解决“DLL load failed while importing _imaging 找不到指定的模块”错误 - 知乎

python3.7环境

pip uninstall pillow

pip install pillow==8.0.0

import os
filepath=(r"C:\Users\AAA\Documents\电气与自动化\电力电子类(电路分析、模拟电路、交流电、)\电力电子类(电力电子、IGBT)\电力电子技术第五版(王兆安)\电力电子技术第五版(王兆安)课件_全")
ls=os.listdir(filepath)
#排序
ls.sort(key=lambda x: int(x[3:-4]))
ls

#python3.7
#PIL 8.0.0

from PIL import Image
print(Image.__file__)
def merge_images(image_paths, output_path, mode='resize'):
    """
    将多张图片纵向合并为长图,支持调整宽度或填充。

    参数:
        image_paths (list[str]): 图片路径列表
        output_path (str): 合并后的图片保存路径
        mode (str): 处理方式,'resize'调整宽度,'pad'填充两侧(默认为'resize')
    """
    # 读取所有图片
    images = [Image.open(p) for p in image_paths]
    if not images:
        raise ValueError("图片列表不能为空")

    # 计算最大宽度
    max_width = max(img.width for img in images)
    processed_images = []

    for img in images:
        if mode == 'resize':
            # 调整图片宽度至最大宽度,保持比例
            ratio = max_width / img.width
            new_height = int(img.height * ratio)
            processed_img = img.resize((max_width, new_height), Image.LANCZOS)
        elif mode == 'pad':
            # 创建新图片并居中粘贴原图
            processed_img = Image.new('RGB', (max_width, img.height), (255, 255, 255))
            x_offset = (max_width - img.width) // 2
            processed_img.paste(img, (x_offset, 0))
        else:
            raise ValueError("模式参数应为'resize'或'pad'")
        processed_images.append(processed_img)

    # 计算总高度并创建合并后的图片
    total_height = sum(img.height for img in processed_images)
    merged_img = Image.new('RGB', (max_width, total_height), (255, 255, 255))

    # 拼接所有处理后的图片
    y_offset = 0
    for img in processed_images:
        merged_img.paste(img, (0, y_offset))
        y_offset += img.height

    # 保存结果
    merged_img.save(output_path)


# 示例用法
os.chdir(filepath)
image_paths = ['幻灯片104.jpg', '幻灯片104.jpg', '幻灯片105.jpg']
merge_images(image_paths, "concat.jpg", mode='pad')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值