Python 3.3中的十六进制编码出错

时间:2014-05-23 23:30:08

标签: image python-3.x numpy colors hex

我正在尝试修改this question中的代码以在Python 3.3中使用(我安装了Pillow,scipy和NumPy):

import struct
from PIL import Image
import scipy
import scipy.misc
import scipy.cluster

NUM_CLUSTERS = 5
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')
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(chr(c) for c in peak).encode('hex')
print ('most frequent is %s (#%s)') % (peak, colour)

但是我收到了这个错误:

Traceback (most recent call last):   File
"C:/Users/User/Desktop/pyt33_pic.py", line 24, in <module>
  colour = ''.join(chr(c) for c in peak).encode('hex') LookupError: unknown encoding: hex

我做错了什么?

1 个答案:

答案 0 :(得分:0)

2.x编解码器&#34; hex_codec&#34;别名为&#34; hex&#34;。此别名在3.4中恢复。更大的变化是bytes编码的缓冲区需要在Python 3中使用codecs.encode。此外,对于字符串格式化,您需要解码结果。例如:

>>> peak
array([131, 128, 124], dtype=uint8)

>>> codecs.encode(peak, 'hex_codec').decode('ascii')
'83807c'

或者,您可以使用format函数将数字单独转换为十六进制:

>>> ''.join(format(c, '02x') for c in peak)
'83807c'