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

在Google Colab运行Stable Diffusion时遇'Image'对象不可调用错误

Stable Diffusion图片网格报错:'Image' object is not callable 解决方法

问题场景

在Google Colab中使用Stable Diffusion生成图片后,调用自定义的image_grid函数拼接图片网格时,触发类型错误,图片可正常生成但无法通过网格形式显示,报错信息为:TypeError: 'Image' object is not callable

报错堆栈

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-30-ec9ce225f081> in <module>
     16   images = pipe(prompt, width=512, height=512, num_inference_steps=10)["sample"]
     17 
---> 18 grid = image_grid(images, rows=2, cols=2)
     19 grid

<ipython-input-28-2e81f9e2985a> in image_grid(imgs, rows, cols)
     10     for i, img in enumerate(imgs):
     11         grid.paste(img, box=(i%cols*w, i//cols*h))
---> 12     return grid()

TypeError: 'Image' object is not callable

问题原因

从报错堆栈可见,实际运行的image_grid函数最后一行写了return grid(),但grid是通过Image.new()创建的Image对象,并非可调用的函数。多余的括号会试图执行该对象,直接触发类型错误。

你提供的函数代码中原本是return grid,但实际运行的代码存在笔误,多添加了一对括号。

修正方案

将image_grid函数的返回语句从return grid()改为return grid,修正后的完整函数代码如下:

def image_grid(imgs, rows, cols):
    assert len(imgs) == rows*cols
    w, h = imgs[0].size
    grid = Image.new('RGB', size=(cols*w, rows*h))
    grid_w, grid_h = grid.size

    for i, img in enumerate(imgs):
        grid.paste(img, box=(i%cols*w, i//cols*h))

    return grid  # 移除多余的括号

验证步骤

  1. 替换为修正后的image_grid函数
  2. 重新运行图片生成与网格拼接代码:
from torch import autocast
num_images = 4
prompt = ["Astronaut riding a horse"] * num_images
with autocast("cuda"):
  images = pipe(prompt, width=512, height=512, num_inference_steps=10)["sample"]
grid = image_grid(images, rows=2, cols=2)
grid  # 在Colab中直接输出Image对象即可显示图片网格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:01:13