【问题标题】:Python 3: Most common color in image kmeans data type matchPython 3:图像kmeans数据类型匹配中最常见的颜色
【发布时间】:2016-03-09 03:18:52
【问题描述】:

我正在尝试将一些 python 2.4 代码改编为 3.5。我正在尝试使用该线程的最佳答案:Python - Find dominant/most common color in an image,但这给我带来了麻烦。这个作者也遇到了麻烦,不过不一样的麻烦Error with hex encode in Python 3.3

具体与 scipy 和 kmeans 变量类型有关吗?这是代码和回溯。你的智慧值得赞赏! -S

import struct
from PIL import Image
import scipy
import scipy.misc
import scipy.cluster
import numpy as np

NUM_CLUSTERS = 3

print('reading image')
im = Image.open('image.jpg')
im = im.resize((150, 150))      # optional, to reduce time
ar = scipy.misc.fromimage(im)
shape = ar.shape
ar = ar.reshape(scipy.product(shape[:2]), shape[2])

print ('finding clusters')
print(ar)
print("Variable type:", type(ar))
codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
print('cluster centres:\n', codes)

vecs, dist = scipy.cluster.vq.vq(ar, codes)         # assign codes
counts, bins = scipy.histogram(vecs, len(codes))    # count occurrences
index_max = scipy.argmax(counts)                    # find most frequent
peak = codes[index_max]

colour = ''.join(format(c, '02x') for c in peak).encode('hex_codec')
print ('most frequent is %s (#%s)' % (peak, colour))

回溯是:

=========== RESTART: /Users/splash/Dropbox/PY/image-dom-color.py ============
reading image
finding clusters
[[255 255 255]
 [255 255 255]
 [255 255 255]
 ..., 
 [255 255 255]
 [255 255 255]
 [255 255 255]]
Variable type: <class 'numpy.ndarray'>
Traceback (most recent call last):
  File "/Users/splash/Dropbox/PY/image-dom-color.py", line 20, in <module>
    codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/scipy/cluster/vq.py", line 568, in kmeans
    book, dist = _kmeans(obs, guess, thresh=thresh)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/scipy/cluster/vq.py", line 436, in _kmeans
    code_book, has_members = _vq.update_cluster_means(obs, obs_code, nc)
  File "scipy/cluster/_vq.pyx", line 347, in scipy.cluster._vq.update_cluster_means (scipy/cluster/_vq.c:4695)
TypeError: type other than float or double not supported
>>> 

【问题讨论】:

    标签: python colors python-3.5


    【解决方案1】:

    堆栈跟踪告诉我们,scipy.cluster._vq.update_cluster_means() 唯一支持的数据类型是 float 和 double。查看 scipy 的源代码证实了这一点:

    def update_cluster_means(np.ndarray obs, np.ndarray labels, int nc):
        """
        The update-step of K-means. Calculate the mean of observations in each
        cluster.
        Parameters
        ----------
        obs : ndarray
            The observation matrix. Each row is an observation. Its dtype must be
            float32 or float64.
        ...
    

    来源:_vq.pyx on GitHub

    要解决您的问题,您首先需要使用numpy.ndarray.astype() 将输入转换为支持的数据类型:

    codes, dist = scipy.cluster.vq.kmeans(ar.astype(float), NUM_CLUSTERS)
    # Or:       = scipy.cluster.vq.kmeans(ar.astype('double'), NUM_CLUSTERS)
    

    【讨论】:

    • 谢谢 Johan - 让我超越了那部分 :) 现在正在处理下一个错误。我曾尝试以其他多种方式转换变量,但没有成功。我真的很感激这个小费!
    • 如果下一个错误与打印颜色的十六进制值有关,看来您不需要最终的encode('hex_codec')。还需要将结果转换回整数:peak = peak.astype(int)colour = ''.join(format(c, '02x') for c in peak)print ('most frequent is %s (#%s)' % (peak, colour))
    猜你喜欢
    • 1970-01-01
    • 2011-05-24
    • 2011-03-15
    • 2019-11-17
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 2016-07-17
    相关资源
    最近更新 更多