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

报错TypeError: 'Image' object is not subscriptable,numpy图像处理求助

解决TypeError: 'Image' object is not subscriptable错误

错误原因

你的代码存在变量复用问题:

  • 初始时image是shape为(8, 1080, 1920, 3)的numpy数组
  • 第一次循环中,你把image重新赋值为Image.fromarray(...)返回的PIL Image对象
  • 第二次循环执行image[i]时,image已经是PIL Image对象,该类型不支持下标访问,因此抛出TypeError

修复后的代码

def show_img(self, img):
    # 保留原始numpy数组,避免被覆盖
    image_array = img
    print(image_array.shape)
    for i in range(len(image_array)):
        # 用新变量存储转换后的PIL Image
        pil_image = Image.fromarray(image_array[i].astype(np.uint8))
        pil_image.show()

额外优化建议

可以直接遍历numpy数组的元素,无需通过索引,代码更简洁:

def show_img(self, img):
    print(img.shape)
    for frame in img:
        pil_image = Image.fromarray(frame.astype(np.uint8))
        pil_image.show()

内容的提问来源于stack exchange,提问作者윤상흠

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:40:34