简体   繁体   中英

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

My code runs on a random image for 28 iterations and THEN gets the error:

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

I'm not really sure why it is getting that error after 28 iterations when it should have broken after 1 iteration only.

My code:

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")

Initialize s1 and m as arrays, not lists.

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

Without studying the whole code or testing it, here's something that looks suspicious:

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

+= for a list ( s1 ) is concatenate. For an integer ( s2 ) it mean add. The += appear to be similar, but are totally different because of how the 2 variables are created.

 m = s1/s2

is the one that raises the error, since / is not defined for a list.

Both operations are in if clauses.

If you want to do math on all the elements of s1 (and m ) you should use np.array instead of lists. But if using arrays you need to pay more attention to shape (and dtype ). And be careful about mixing arrays with iterative code like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM