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

复制教程Python代码运行报错:TypeError: 'int' object is not subscriptable

问题分析与解决

错误原因

触发TypeError: 'int' object is not subscriptable是因为你的densityMap_fruits.png图像不是RGB模式,导致img.getdata()返回的每个像素元素是单个整数,而非代码预期的RGB三元组(如(R, G, B)),所以p[0]尝试对整数做下标访问时会报错。教程中的原图是RGB模式,因此代码能正常运行。

解决方案

在打开图像后添加一行代码,强制将图像转换为RGB模式,确保每个像素以三元组形式返回:

修改后的完整代码

from PIL import Image


def update_pixel(p):
     channel = p[0] + (256 * p[1])
     state = channel // 32
     index = channel % 32
     new_channel = (state * 64) + index
     return (new_channel % 256, new_channel // 256, 0)


img = Image.open("densityMap_fruits.png")
# 强制转换为RGB模式,适配代码对像素三元组的要求
img = img.convert("RGB")
list_of_pixels = list(img.getdata())
new_list_of_pixels = list(map(update_pixel, list_of_pixels))
img.putdata(new_list_of_pixels)
img.save("densityMap_fruits_new.png")

补充说明

如果你的原图确实是单通道灰度图,也可以针对性修改update_pixel函数,但强制转RGB的方案更通用,能完全匹配教程代码的逻辑,无需调整像素处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 08:49:57