Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用图像作为键_Python_Python Imaging Library - Fatal编程技术网

Python 使用图像作为键

Python 使用图像作为键,python,python-imaging-library,Python,Python Imaging Library,在Python中是否可以使用图像作为dict中的键 answer_List = {One : 1, Two : 2, Three :3, Four : 4, Five : 5, Six : 6} 其中1-6是png文件。我是python新手,我一直在读到它非常灵活,任何东西都可以作为任何东西存储在和中。然而,我得到了一个错误 TypeError:不可损坏的类型:“PngImageFile” 谢谢。如果要用作字典键,对象必须是可散列的。也就是说,它必须有(或继承)一个方法 我不确定您想要实现什么

在Python中是否可以使用图像作为dict中的键

answer_List = {One : 1, Two : 2, Three :3, Four : 4, Five : 5, Six : 6}
其中1-6是png文件。我是python新手,我一直在读到它非常灵活,任何东西都可以作为任何东西存储在和中。然而,我得到了一个错误

TypeError:不可损坏的类型:“PngImageFile”


谢谢。

如果要用作字典键,对象必须是可散列的。也就是说,它必须有(或继承)一个方法

我不确定您想要实现什么,但如果您需要与图像关联的值,您可以使用它们的文件名作为键:

{One.filename:1,Two.filename:2,…}

字典键的一般规则是希望它是不可变的。如果对键对象进行更改,dict的内部数据结构将变得混乱

图像是非常多变的,你可以在任何时候改变一个像素。可变对象不需要费心实现
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
方法,因为它是无用的。这就是错误消息告诉您的

最好对图像使用代理。另一个答案中的一个好建议是使用图像的文件名,但前提是每个图像都来自一个文件,并且没有任何具有不同文件名的重复图像。另一种方法是将图像的内容冻结到像bytestring这样的不可变内容中,但由于bytestring很大,因此效率极低。您可以通过使用加密哈希生成每个图像输入唯一的字符串来解决该问题

import hashlib

def ImageID(im):
    return hashlib.md5(im.tobytes()).hexdigest()

这种技术不仅仅适用于
dict
s。我已经将其用于mp3封面图像的数据库键,因为许多文件将共享一个图像。

这应该会有所帮助——在大多数情况下,这不是一个好的设计。但是,通过对PngImageFile进行子分类并使其成为可能。散列可以基于文件内容,但对象不能更改。如果希望剪切/旋转的图像散列为相同的内容,甚至可以使用。它运行正常,但远不是完美的。