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

如何使用Python对图像切片后拼接生成带间隔的窗格效果

Python图像处理(瓦片切分+窗格效果拼接)实现方案

依赖安装

首先安装Pillow图像处理库:

pip install pillow

实现代码

from PIL import Image

def process_image(input_path, output_path):
    # 加载原始图像,自动转为灰度模式(适配黑白输入图像需求)
    img = Image.open(input_path).convert('L')
    width, height = img.size
    
    # ---------------------- 第一步:按规则切分瓦片 ----------------------
    tile_w, tile_h = 8, 9  # 单个瓦片尺寸
    row_step = tile_h + 1  # 垂直方向每行瓦片起始位置的步长(切完一行跳1px)
    tiles = []
    
    # 计算总共有多少行、多少列瓦片
    col_count = width // tile_w
    row_count = height // row_step
    
    # 逐行逐列切瓦片
    for row_idx in range(row_count):
        row_tiles = []
        y_start = row_idx * row_step
        for col_idx in range(col_count):
            x_start = col_idx * tile_w
            # 切取对应区域的瓦片 坐标格式:(左, 上, 右, 下)
            tile = img.crop((x_start, y_start, x_start + tile_w, y_start + tile_h))
            row_tiles.append(tile)
        tiles.append(row_tiles)
    
    # ---------------------- 第二步:生成带窗格效果的新图像 ----------------------
    padding = 1  # 每个瓦片四周的内边距
    # 计算新画布尺寸
    new_w = col_count * (tile_w + 2 * padding)
    new_h = row_count * (tile_h + 2 * padding)
    # 新建白色背景画布(灰度模式下255对应白色)
    new_img = Image.new('L', (new_w, new_h), 255)
    
    # 把瓦片逐个贴到新画布对应位置
    for row_idx in range(row_count):
        for col_idx in range(col_count):
            # 计算瓦片在新画布的左上角坐标,预留1px内边距
            paste_x = col_idx * (tile_w + 2 * padding) + padding
            paste_y = row_idx * (tile_h + 2 * padding) + padding
            new_img.paste(tiles[row_idx][col_idx], (paste_x, paste_y))
    
    # 保存输出图像
    new_img.save(output_path)

# 调用示例
if __name__ == "__main__":
    process_image("输入图像路径.png", "输出图像路径.png")

代码说明

  • 切分瓦片时垂直方向按9px瓦片+1px跳过的规则计算起始位置,完全符合需求的行间距跳过要求
  • 拼接时直接用白色画布作为底色,每个瓦片粘贴时偏移1px,自动形成四周1px的白色窗格间隔,无需额外绘制分隔线
  • 代码默认将输入图像转为灰度模式,适配黑白图像处理需求,如果需要处理彩色图像,把convert('L')删除,新建画布时把模式改为RGB、底色改为(255,255,255)即可

内容的提问来源于stack exchange,提问作者77two4seven4

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:06:07