Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python 图片拼接

作者:我在坚强也需要有人疼   发布日期:2026-03-29   浏览:104

from PIL import Image

def concatenate_images(image_paths, direction='horizontal'):
    """
    将多张图片拼接成一张图片。

    参数:
    image_paths (list): 包含图片路径的列表。
    direction (str): 拼接方向,'horizontal' 或 'vertical'。

    返回:
    Image: 拼接后的图片。
    """
    images = [Image.open(x) for x in image_paths]
    widths, heights = zip(*(i.size for i in images))

    if direction == 'horizontal':
        total_width = sum(widths)
        max_height = max(heights)
        new_image = Image.new('RGB', (total_width, max_height))
        x_offset = 0
        for img in images:
            new_image.paste(img, (x_offset, 0))
            x_offset += img.size[0]
    elif direction == 'vertical':
        max_width = max(widths)
        total_height = sum(heights)
        new_image = Image.new('RGB', (max_width, total_height))
        y_offset = 0
        for img in images:
            new_image.paste(img, (0, y_offset))
            y_offset += img.size[1]
    else:
        raise ValueError("direction must be 'horizontal' or 'vertical'")

    return new_image

# 示例用法
image_paths = ['path/to/image1.jpg', 'path/to/image2.jpg', 'path/to/image3.jpg']
concatenated_image = concatenate_images(image_paths, direction='horizontal')
concatenated_image.save('path/to/output.jpg')

解释说明:

  • PIL库:我们使用了Python Imaging Library (PIL),它是一个处理图像的强大库。from PIL import Image 导入了处理图像所需的模块。
  • 函数 concatenate_images:该函数接受一个包含图片路径的列表,并根据指定的方向(水平或垂直)将这些图片拼接在一起。
    • 参数
      • image_paths:包含图片路径的列表。
      • direction:指定拼接方向,默认为水平拼接。
    • 返回值:返回拼接后的图片对象。
  • 示例用法:通过指定图片路径列表和拼接方向,调用 concatenate_images 函数并将结果保存到指定路径。

如果你有任何问题或需要进一步的帮助,请告诉我!

上一篇:python translate

下一篇:python中列表的概念

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站