我有一个按顺序排列的图像目录。通常,我的代码将使用图像的连续子集(例如图像 5-10)中的数据,访问这些图像的简单选项是:
使用在需要时加载图像并读取我的数据(例如像素值)的方法创建一个包装对象。这几乎没有内存开销,但速度会很慢,因为每次都需要加载每个图像。
将所有图像存储在内存中。这会很快,但显然我们可以存储的图像数量是有限的。
我想找到:
- 我可以定义如何读取与索引或路径相对应的图像的某种方法,然后允许我访问,例如
magic_image_collection[index]
我不必担心它是否会返回内存中的对象或重新读取它。理想情况下,这将保留适当的图像或n
内存中最近访问的图像。
您可以扩展默认字典并使用__missing__
如果密钥丢失则调用加载函数的方法:
class ImageDict(dict):
def __missing__(self, key):
self[key] = img = self.load(key)
return img
def load(self, key):
# create a queue if not exist (could be moved to __init__)
if not hasattr(self, '_queue'):
self._queue = []
# pop the oldest entry in the list and the dict
if len(self._queue) >= 100:
self.pop(self._queue.pop(0))
# append this key as a newest entry in the queue
self._queue.append(key)
# implement image loading here and return the image instance
print 'loading', key
return 'Image for %s' % key
和输出(仅当密钥尚不存在时才会加载。)
>>> d = ImageDict()
>>> d[3]
loading 3
'Image for 3'
>>> d[3]
'Image for 3'
>>> d['bleh']
loading bleh
'Image for bleh'
>>> d['bleh']
'Image for bleh'
一种演变是仅存储字典中的最后 N 个元素,并清除最旧的条目。您可以通过保留用于排序的键列表来实现它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)