【发布时间】: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)语句后会得到什么输出? -
只需打印
pixel、kernel和acc,您就会找到答案。int is not subscriptable表示您正在下标一个整数,例如5[4]或其他东西。错误消息中说明了解决此问题所需的所有内容。
标签: python python-3.x int python-imaging-library