Python TypeError : list indices must be integers or slices, 不是元组

标签 python list numpy convolution

我正在尝试使用卷积从图像 img 中提取特征。

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

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

最佳答案

您的矩阵不是一个numpy数组,而是一个Python列表,因此matrix[row, col]无法执行。

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

matrix = <b>np.array(</b>[[-1, -2, -1], [0, 0, 0], [1, 2, 1]]<b>)</b>

关于Python TypeError : list indices must be integers or slices, 不是元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61109809/

相关文章:

python - 将 Anaconda MKL 链接到 C++/Cython 程序

performance - 创建一维 NumPy 数组的 NoN 填充元素的滑动窗口

python - Numpy 多数组.so : undefined symbol: cblas_sgemm

python - 仅在实际发生错误的情况下,如何仅将python错误(stderr)保存到日志文件?

r - 缩写科学名称的功能

C++ - 静态列表,当满时从头部弹出节点

python - 如何将以下列表转换为字典?

python - Tkinter 颜色名称到颜色对象

Python:拆分混合字符串

python - 当我有一个二维列表时如何生成随机选择?