将文件夹中的图片拼接成一张大图片(python)

工作中经常使用BeeDICOMVIewer,有时候需要导出图片之后,拼接成为一张大图,网上找的方法基本上太傻,另外结合BeeDICOMVIewer导出图片的特点(每张图片大小一样),写了一个函数来解决这个问题。

from PIL import Image
import os

# 定义一个函数,用于将文件夹中的图片拼接成一张大图片
def stitch_images(folder_path, output_image_path, images_per_row=5, padding=5):
    # 从文件夹中获取所有图片路径
    image_paths = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith(('.png', '.jpg', '.jpeg'))]
    
    # 加载所有图片
    images = [Image.open(path) for path in image_paths]
    
    # 假设所有图片大小相同,计算每张图片的宽度和高度
    image_width, image_height = images[0].size
    
    # 计算最终图片的总宽度和高度
    total_width = (image_width + padding) * images_per_row - padding
    total_rows = len(images) // images_per_row + (1 if len(images) % images_per_row > 0 else 0)
    total_height = (image_height + padding) * total_rows - padding
    
    # 创建一个新的空白图片,背景为白色
    stitched_image = Image.new('RGB', (total_width, total_height), 'white')
    
    # 将图片粘贴到拼接图像中
    for i, image in enumerate(images):
        row_num = i // images_per_row
        col_num = i % images_per_row
        x = col_num * (image_width + padding)
        y = row_num * (image_height + padding)
        stitched_image.paste(image, (x, y))
    
    # 保存拼接后的图片
    stitched_image.save(output_image_path)

# 调用函数,将“images”文件夹中的图片拼接,并保存为“stitched_image.jpg”
source_folder = r'/Users/terry/Desktop/Image_Folder_Path/'
stitch_images(source_folder, source_folder+'/stitched_image.jpg')

上面是一个个图片的样子,一个CT片的dicom文件,通常有几十乃至几百个文件,合并之后,就是下面的样子:

代码亲测能用,有问题欢迎连麦。 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值