简体   繁体   中英

UnboundLocalError using Kmeans in scipy

I'm trying to learn more about image processing in Python and, as part of the process, am doing some of the exercises in a book that I am reading. In one exercise I'm trying to do kmeans clustering of average pixel color in an image. The code below is pretty much verbatim from the example, but I keep getting an error (stack as follows).

File "C:/Users/xxx/gitStuff/version-control/image/data/practiceCh6.py", line 31, in centroids,variance = kmeans(features,3)

File "C:\\Users\\xxx\\AppData\\Local\\Continuum\\Anaconda\\Lib\\site-packages\\scipy\\cluster\\vq.py", line 524, in kmeans result = best_book, best_dist

UnboundLocalError: local variable 'best_book' referenced before assignment

Code is below:

from PIL import Image
from scipy.cluster.vq import kmeans,vq
from scipy.misc import imresize
from numpy import *


steps = 50
im = array(Image.open('frontside.jpg'))

dx = im.shape[0]
dy = im.shape[1]

#compute color features for each region
features =[]
for x in range(steps):
    for y in range(steps):
        R = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,0])
        G = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,1])
        B = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,2])
        features.append([R,G,B])

features = array(features,'f') #make into array

#cluster
centroids,variance = kmeans(features,3)
code,distance = vq(features,centroids)

#create image with clulster labels
codeim = code.reshape(steps,steps)
codeim = imresize(codeim,im.shape[:2],interp='nearest')

figure()
imshow(codeim)
show()

Any advice on what might be wrong would be much appreciated.

I'm not familiar with image processing, but by adding a simple print statement to your code, you will see that values in your array are 'nan'.

for x in range(steps):
    for y in range(steps):
        R = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,0])
        G = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,1])
        B = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,2])
        features.append([R,G,B])

features = array(features,'f') #make into array
print features

Returns:

[[ 186.93768311  159.18690491  157.92678833]
 [          nan           nan           nan]
 [          nan           nan           nan]
 ...,
 [          nan           nan           nan]
 [          nan           nan           nan]
 [          nan           nan           nan]]

You can't run K-means on nan's, I'd go back and check how you're assigning R,G,B.

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