【问题标题】:TypeError: 'int' object is not subscriptable errorTypeError: 'int' object is not subscriptable 错误
【发布时间】:2019-11-30 12:53:47
【问题描述】:

我的代码遇到问题。 Pycharm 告诉我我有错误:"TypeError: 'int' object is not subscriptable" 在线:acc[0] = acc[0] + (pixel[0] * kernel[a][b])。谁知道怎么解决?

from PIL import Image, ImageDraw
from numpy import asarray
# Load image:
input_image = Image.open("Cameraman.tif")
input_pixels = input_image.load()

# Box Blur kernel
box_kernel = ([[-1, -1, -1],
                   [-1, 8, -1],
                   [-1, -1, -1]])


# Select kernel here:
kernel = box_kernel

# Middle of the kernel
offset = len(kernel) // 2

# Create output image
output_image = Image.new("RGB", input_image.size)
draw = ImageDraw.Draw(output_image)

# Compute convolution between intensity and kernels
output_image = Image.new("RGB", input_image.size)
draw = ImageDraw.Draw(output_image)

# Compute convolution with kernel
for x in range(offset, input_image.width - offset):
    for y in range(offset, input_image.height - offset):
        acc = [0, 0, 0]
        for a in range(len(kernel)):
            for b in range(len(kernel)):
                xn = x + a - offset
                yn = y + b - offset
                pixel = input_pixels[xn, yn]
                acc[0] = acc[0] + (pixel[0] * kernel[a][b])
                acc[1] = acc[1] + (pixel[1] * kernel[a][b])
                acc[2] = acc[2] + (pixel[2] * kernel[a][b])

        draw.point((x, y), (int(acc[0]), int(acc[1]), int(acc[2])))

output_image.save("Filtered.png")

img1arr = asarray(input_image)
img2arr = asarray(output_image)
im1arrF = img1arr.astype('float')
im2arrF = img2arr.astype('float')
additionF = (im1arrF+im2arrF)/2
addition = additionF.astype('uint8')
resultImage = Image.fromarray(addition)
resultImage.save('Sharpened.jpg')

【问题讨论】:

  • 添加print(pixel) 语句后会得到什么输出?
  • 只需打印pixelkernelacc,您就会找到答案。 int is not subscriptable 表示您正在下标一个整数,例如 5[4] 或其他东西。错误消息中说明了解决此问题所需的所有内容。

标签: python python-3.x int python-imaging-library


【解决方案1】:

鉴于acckernel 在您的代码中定义并且有足够的维度来支持索引cuplrit 必须是pixel。我假设您期望一个一维长度为 3 的数组表示点 [xn,yn] 的 RGB 值。这里最明显的可能性是您加载了灰度图像 - 可能是这种情况吗?

【讨论】:

    猜你喜欢
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2020-08-05
    相关资源
    最近更新 更多