2017-02-28 53 views
0
“列表”和“INT”

我的代码为28次的迭代随机图像上运行,并且然后得到的错误:类型错误:不支持的操作数类型(个),/:在28次迭代

TypeError: unsupported operand type(s) for /: 'list' and 'int'

我不太确定为什么它会在28次迭代后得到这个错误,当它在1次迭代之后应该中断。

我的代码:

import numpy as np 
import cv2 
import matplotlib.pyplot as plt 
import math 

#import image 
img = cv2.imread('small.jpg') 
height,width = img.shape[:2] 

#create feature vector for RGB values 
#for this image length = 6536 
feature = [] 
for i in range(0, height): 
    for j in range(0, width): 
     val = img[i,j] 
     feature.append(val) 

#find average normal value 
normThreshold = 3 


#function for the gaussian kernal 
def gaussian(x, xi): 
    h = 2 
    const = 1/(np.sqrt(math.pi)) 
    norm_x = np.linalg.norm(x) 
    norm_xi = np.linalg.norm(xi) 
    output = const*(np.exp((-1)*np.square(norm_x-norm_xi)/np.square(2*h))) 
    return output 

#conduct mean shift algorithm 
for i in range(0, len(feature)): 
    print (i) 
    condition = True 
    while(condition): 
     s1 = [0,0,0] 
     s2 = 0 
     m = [0,0,0] 
     for j in range(0, len(feature)): 
      if (i != j): 
       diff = np.linalg.norm(feature[i] - feature[j]) 
       if (diff < normThreshold and diff != 0): 
        # print (feature[j]) 
        top = gaussian(feature[i],feature[j])*feature[j] 
        bottom = gaussian(feature[i],feature[j]) 
        s1 += top 
        s2 += bottom 
     if (gaussian(feature[i],feature[j]) != 0): 
      m = s1/s2 
      # print (s1) 
      # print (s2) 
      # print (m) 
     c1 = np.linalg.norm(m) 
     c2 = np.linalg.norm(feature[i]) 
     if (np.absolute(c1-c2) < 0.001): 
      condition = False 
     feature[i] = m 
print("finished") 
+0

哪一行会抛出错误? – Peter

+0

@Peter我认为我解决了它,问题是“normThreshold”变量,如果我将其设置为更高的值,则会解决此问题 –

+0

@RichardWU如果您将其作为答案发布并标记为正确,则会更好。 –

回答

0

初始化s1m作为数组,而不是名单。

s1 = np.array([0.0, 0.0, 0.0]) 
m = np.array([0.0, 0.0, 0.0]) 
0

不研究整个代码或测试它,这里的东西看起来很可疑的:

s1 = [0,0,0] 
    s2 = 0 
    while .... 
     s1 += top 
     s2 += bottom 

+=的列表(s1)是串连。对于一个整数(s2)它意味着添加。 +=似乎是相似的,但由于2个变量的创建方式而完全不同。

m = s1/s2 

是引发错误的原因之一,因为/没有为列表定义。

这两个操作都在if条款中。

如果要对s1(和m)的所有元素执行数学计算,则应使用np.array而不是列表。但是如果使用阵列,则需要更多注意shape(和dtype)。并且要注意将数组与迭代代码混合在一起。