2015-12-04 3 views
3

Я пытаюсь адаптировать некоторый код python 2.4 к 3.5. Я пытаюсь использовать верхний ответ из этой темы: Python - Find dominant/most common color in an image, но это дает мне проблемы. У этого автора также были проблемы, но разные проблемы Error with hex encode in Python 3.3Python 3: Самый распространенный цвет в изображении Тип данных kmeans соответствует

В частности, что-то связанное с переменными типами 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 
>>> 

ответ

8

StackTrace говорит нам, что только поддерживаемые типы данных для 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) 
+1

Спасибо Йохан - Прошел мимо этой части :) Теперь работа над следующей ошибкой. Я попытался преобразовать переменную несколькими другими способами без везения. Я очень ценю подсказку! – Plashkes

+1

Если следующая ошибка связана с печатью шестнадцатеричного значения цвета, кажется, что вам не нужен окончательный 'encode ('hex_codec')'. Также необходимо преобразовать результат в целые числа: 'peak = peak.astype (int)' 'color = '' .join (формат (c, '02x') для c в пике)' 'print («Наиболее часто встречаются% s (#% s)»% (пик, цвет)) ' –