You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义图像切片拼接函数及多图像批量处理方案求助

自定义图像切片拼接函数及批量处理方案

单张图像切片拼接实现

咱们先搞定单张图像的拼接逻辑。既然要自己实现image_slicer.join()的功能,核心就是要根据切片的行列位置,把它们准确放回原图的对应位置。这里用PIL库来操作就很方便,具体步骤和代码如下:

  1. 读取目录下所有切片文件,解析每个切片的行列索引(image_slicer默认保存的文件名格式是slice_{行号}_{列号}.xxx)
  2. 确定单个切片的尺寸,再推算出原图的总尺寸(行数×切片高度,列数×切片宽度)
  3. 创建和原图尺寸一致的空白画布,把每个切片按行列坐标粘贴进去
from PIL import Image
import os
import re

def stitch_slices(slice_dir, output_path):
    # 获取目录下符合命名规则的切片文件
    slice_files = [f for f in os.listdir(slice_dir) 
                   if f.startswith('slice_') and f.lower().endswith(('.png', '.jpg', '.jpeg'))]
    if not slice_files:
        raise ValueError("目录中没有找到符合格式的切片文件")
    
    # 解析每个切片的行列信息并读取图像
    slice_info = []
    slice_pattern = re.compile(r'slice_(\d+)_(\d+)\.\w+')
    for file in slice_files:
        match = slice_pattern.match(file)
        if match:
            row = int(match.group(1))
            col = int(match.group(2))
            img = Image.open(os.path.join(slice_dir, file))
            slice_info.append((row, col, img))
    
    # 计算原图的尺寸
    slice_width, slice_height = slice_info[0][2].size
    max_row = max(s[0] for s in slice_info) + 1
    max_col = max(s[1] for s in slice_info) + 1
    original_size = (max_col * slice_width, max_row * slice_height)
    
    # 创建空白画布并粘贴切片
    original_img = Image.new('RGB', original_size)
    for row, col, img in slice_info:
        paste_x = col * slice_width
        paste_y = row * slice_height
        original_img.paste(img, (paste_x, paste_y))
    
    # 保存拼接后的图像
    original_img.save(output_path)
    print(f"拼接完成,已保存至: {output_path}")

扩展为批量处理多张图像

如果要处理文件夹里的多张图像对应的切片,建议把每个图像的切片放在单独的子目录里(比如image1_slices、image2_slices),然后遍历所有子目录,对每个子目录调用上面的拼接函数。

假设你的根目录结构是这样的:

slices_root/
├── image1_slices/
│   ├── slice_0_0.jpg
│   ├── slice_0_1.jpg
│   └── ...(共9个切片)
├── image2_slices/
│   ├── slice_0_0.jpg
│   └── ...
└── ...

对应的批量处理代码如下:

def batch_stitch_slices(root_dir, output_root):
    # 创建输出根目录(不存在则自动创建)
    os.makedirs(output_root, exist_ok=True)
    
    # 遍历所有切片子目录
    for subdir in os.listdir(root_dir):
        subdir_path = os.path.join(root_dir, subdir)
        if not os.path.isdir(subdir_path):
            continue
        
        # 生成对应的输出文件名
        output_filename = f"{subdir.replace('_slices', '')}.jpg"
        output_path = os.path.join(output_root, output_filename)
        
        try:
            stitch_slices(subdir_path, output_path)
        except Exception as e:
            print(f"处理目录 {subdir} 时出错: {str(e)}")

使用示例

如果你的切片根目录是./slices,想把拼接后的图像保存到./stitched_images,直接调用即可:

batch_stitch_slices(root_dir="./slices", output_root="./stitched_images")

注意事项

  • 如果你的切片命名规则和默认不同,只需调整正则表达式slice_pattern即可适配
  • 若处理带透明通道的PNG图像,把Image.new('RGB', original_size)改为Image.new('RGBA', original_size)即可
  • 批量处理时,子目录命名建议和原图名称对应,方便生成直观的输出文件名

内容的提问来源于stack exchange,提问作者Virinchi Ande

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:05:13