报错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,提问作者윤상흠
相关产品推荐
相关产品推荐

