TypeError:“ int”对象不是下标错误

时间:2019-11-30 12:53:47

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

我的代码遇到问题。 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')

1 个答案:

答案 0 :(得分:0)

鉴于"//".*\n acc是在您的代码中定义的,并且具有足够的尺寸来支持对cuplrit的索引,因此必须为kernel。我假设您期望一个一维的长度为3的数组,该数组代表点pixel上的RGB值。这里最明显的可能性是您已经加载了灰度图像-可能是这种情况吗?