Skip to main content
 首页 » 编程设计

python之Scipy Kmeans 以 TypeError 退出

2024年10月01日15itcoder

当运行下面的代码时,我得到一个 TypeError:

“文件“_vq.pyx”,第 342 行,在 scipy.cluster._vq.update_cluster_means TypeError:不支持 float 或 double 以外的类型”

from PIL import Image 
import scipy, scipy.misc, scipy.cluster 
 
NUM_CLUSTERS = 5 
 
im = Image.open('d:/temp/test.jpg') 
ar = scipy.misc.fromimage(im) 
shape = ar.shape 
ar = ar.reshape(scipy.product(shape[:2]), shape[2]) 
codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS) 
vecs, dist = scipy.cluster.vq.vq(ar, codes) 
counts, bins = scipy.histogram(vecs, len(codes)) 
 
peak = codes[scipy.argmax(counts)] 
print 'Most frequent color: %s (#%s)' % (peak, ''.join(chr(c) for c in peak).encode('hex')) 

我不知道如何解决这个问题。

更新:

完整回溯:

Traceback (most recent call last): File "...\temp.py", line 110, in <module> codes, dist = scipy.cluster.vq.kmeans2(ar, NUM_CLUSTERS) File "...\site-packages\scipy\cluster\vq.py", line 642, in kmeans2 new_code_book, has_members = _vq.update_cluster_means(data, label, nc) File "_vq.pyx", line 342, in scipy.cluster._vq.update_cluster_means TypeError: type other than float or double not supported

请您参考如下方法:

正在做:

ar = ar.reshape(scipy.product(shape[:2]), shape[2]) 
print(ar.dtype) 

您会看到,您使用 uint8 类型的数据调用 kmeans。

理论上,kmeans 是在 d 维实向量上定义的,scipy 也不喜欢它(如错误中给出的那样)!

就这样吧:

ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float) 

这样的转换让我的示例运行到打印为止,打印也需要更改以反射(reflect)给定的类型。