我试图在Python中学习更多有关图像处理的知识,作为整个过程的一部分,我正在阅读一本书中的一些练习。在一个练习中,我尝试对图像中的平均像素颜色进行kmeans聚类。下面的代码几乎是从示例中逐字逐句,但我不断收到错误(堆栈如下)。
文件" C:/Users/xxx/gitStuff/version-control/image/data/practiceCh6.py" ;,第31行,在 质心,方差= kmeans(特征,3)
文件" C:\ Users \ xxx \ AppData \ Local \ Continuum \ Anaconda \ Lib \ site-packages \ scipy \ cluster \ vq.py",第524行,在kmeans中 result = best_book,best_dist
UnboundLocalError:本地变量' best_book'在分配前引用
代码如下:
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()
非常感谢任何关于可能出错的建议。
答案 0 :(得分:0)
我不熟悉图像处理,但通过在代码中添加一个简单的print语句,您会发现数组中的值是'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
返回:
[[ 186.93768311 159.18690491 157.92678833]
[ nan nan nan]
[ nan nan nan]
...,
[ nan nan nan]
[ nan nan nan]
[ nan nan nan]]
你不能在nan上运行K-means,我会回去查看你如何分配R,G,B。