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

PIL Image.paste报错TypeError:color must be int or tuple问题求助

Python PIL拼接图片切片时出现TypeError: color must be int or tuple

问题描述

我需要编写Python脚本将若干300x200像素的RGB PNG切片拼接成4200x1200像素的完整图片,切片命名格式为LG_Test.i.j.png(i是宽度方向序号,j是高度方向序号)。我写了如下脚本:

import PIL
from PIL import Image
composed_image = Image.new('RGB', (4200, 1200))
i = 0
j = 0
counter_i = 0
counter_j = 0
while j <= 1200-200:
    while i <= 4200-300:
        #Create File Name: name.i.j.png
        filename = "LG_Test." + str(counter_i) + "." + str(counter_j) + ".png"
        image_in = [Image.open(filename)]
        composed_image.paste(image_in, box=(i,j,300,200))
        i = i+300
        counter_i = counter_i+1
    i = 0
    j = j+200
    counter_i = 0
    counter_j = counter_j+1
composed_image.save("Composed_Image.png")

运行时出现错误:

composed_image.paste(image_in, box=(i,j,300,200))
File "/usr/lib/python3.11/site-packages/PIL/Image.py", line 1740, in paste
self.im.paste(im, box)
TypeError: color must be int or tuple

拼接图和切片都是RGB格式,不清楚问题出在哪,求帮助。

解决方案

错误原因

报错的核心问题是你把Image.open()返回的Image对象放到了列表里:

image_in = [Image.open(filename)]

而Image.paste()方法第一个参数需要的是Image对象,不是列表。当你传入列表时,PIL会把它误认为是颜色值(int或tuple类型),因此抛出类型错误。

另外你的box参数也有问题:box=(i,j,300,200)里的后两个值应该是切片右下角的坐标(i+300和j+200),而不是固定的300和200,否则所有切片都会被粘贴到同一个固定区域。

修正后的代码

import PIL
from PIL import Image

composed_image = Image.new('RGB', (4200, 1200))
i = 0
j = 0
counter_i = 0
counter_j = 0

while j <= 1200 - 200:
    while i <= 4200 - 300:
        filename = f"LG_Test.{counter_i}.{counter_j}.png"  # 用f-string简化文件名拼接
        image_in = Image.open(filename)  # 去掉列表包裹,直接赋值Image对象
        # 修正box参数为当前切片的完整坐标范围
        composed_image.paste(image_in, box=(i, j, i+300, j+200))
        i += 300
        counter_i += 1
    i = 0
    j += 200
    counter_i = 0
    counter_j += 1

composed_image.save("Composed_Image.png")

更简洁的优化版本

用for循环代替while循环,无需手动维护计数器,代码可读性更高:

from PIL import Image

# 计算行列数量:总宽度/切片宽度,总高度/切片高度
total_cols = 4200 // 300
total_rows = 1200 // 200

composed_image = Image.new('RGB', (4200, 1200))

for row_idx in range(total_rows):
    for col_idx in range(total_cols):
        filename = f"LG_Test.{col_idx}.{row_idx}.png"
        # 用with语句自动管理图片文件的打开/关闭
        with Image.open(filename) as tile_img:
            # 计算当前切片的左上角坐标,直接传入paste即可(PIL会自动识别切片尺寸)
            x_pos = col_idx * 300
            y_pos = row_idx * 200
            composed_image.paste(tile_img, (x_pos, y_pos))

composed_image.save("Composed_Image.png")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:52:36