Python 3.3中的十六进制编码错误 [英] Error with hex encode in Python 3.3

查看:224
本文介绍了Python 3.3中的十六进制编码错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从此问题修改代码在Python 3.3中使用(我安装了Pillow,scipy和NumPy):

I am trying modify code from this question to use in Python 3.3 (I installed Pillow, scipy and 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)

/ p>

But I get this error:

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

我做错了什么?

推荐答案

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

In 2.x the codec "hex_codec" is aliased to "hex". This alias is restored in 3.4. A bigger change is that a buffer to bytes encoding requires using codecs.encode in Python 3. Additionally, for string formatting you'll need to decode the result. For example:

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

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

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

Alternatively you can use the format function to individually convert the numbers to hex:

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

这篇关于Python 3.3中的十六进制编码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆