Python TypeError:列表索引必须是整数或切片,而不是元组

I am trying to extract features from an image img using convolution.

img_copy = np.copy(img)
x = img_copy.shape[0]
y = img_copy.shape[1]

matrix = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]] # convolution matrix
weight = 1

def conv(x, y):
    val = 0.0
    for row,i in enumerate([-1, 0, 1]):
        for col,j in enumerate([-1, 0, 1]):
            val = val + img[x+j, y+i]*matrix[row, col]
    val = val*weight

    return val

for i in range(1, x-1):
    for j in range(1, y-1):
        pixel = conv(i, j)
        if(pixel<0):
            pixel = 0
        if(pixel>255):
            pixel = 255

执行此代码块将引发以下错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-66-84eb09b3a0b7> in <module>
      1 for i in range(1, x-1):
      2     for j in range(1, y-1):
----> 3         pixel = conv(i, j)
      4         if(pixel<0):
      5             pixel = 0

<ipython-input-65-88737f90ffac> in conv(x, y)
      6     for row,i in enumerate([-1, 0, 1]):
      7         for col,j in enumerate([-1, 0, 1]):
----> 8             val = val + img[x+j, y+i]*matrix[row, col]
      9     val = val*weight
     10 

TypeError: list indices must be integers or slices, not tuple

感谢您提供解决此问题的任何帮助。

评论
  • 神经
    神经 回复
    val = val + img[x+j, y+i]*matrix[row, col]
    

    用逗号分隔的两个值通常被解释为元组。试试这个

    val = val + img[x+j][y+i]*matrix[row][col]
    
  • aeius
    aeius 回复

    Your matrix is not a numpy array, but a Python list, thus matrix[row, col] can not be performed.

    因此,您应该将其转换为numpy数组:

    matrix = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])