2017-06-27 29 views
0

我有打印出3x3矩阵的2×2矩阵卷积功能:类型错误在Python函数(int对象未标化)

image = [[1,0,1],  # Original image 
     [0,1,0], 
     [1,0,1]] 

在哪里我的功能应该打印出来:

[1,0] 
[0,1] 
[0,1] 
[1,0] 
[0,1] 
[1,0] 
[1,0] 
[0,1] 

的功能如下

def convolution(image,result): 
    # Image being 2d matrix 
    # Result being return stacked 2d matrices 
    # DECLARE LOCAL VARIABLES 
    a = 0 # Slice [a:b] 
    b = 2 
    r = 0 
    # For row in image: 
    for row in image: 
     # While b < row length: 
     while b < len(row): 
      print(row[r][a:b]) # HERE IS THE ERROR 
      print(row[r+1][a:b]) 
      a += 1 
      b += 1 
     a = 0 # Slice [a:b] 
     b = 2 
     matrix2d.clear() 

我得到以下错误:

Traceback (most recent call last): 
    File "conv.py", line 49, in <module> 
    convolution(image,result3d) 
    File "conv.py", line 24, in convolution 
    print(row[r][a:b]) 
TypeError: 'int' object is not subscriptable 

这个错误信息对我来说比较模糊。可以做些什么来纠正这个错误?

回答

1

在您的代码中row是图像的一行,例如[1,0,1]表示第一行。然后在你的while循环中,row[r]是一个整数,而不是一个数组。

错误消息为您提供了错误的路线,并说,你不能把一个整数的下标,这意味着你不能做a[1]如果aint。有了这些信息,你就有了一个很好的线索来发现row[r]确实是一个整数。

相关问题