python - 如何在字典中存储一组图像,并使用python opencv检索它

标签 python opencv dictionary

我有一本字典,其中我已将图像作为值,将索引作为键,我已使用zip函数将其存储,并且在尝试检索它时,它不显示图像。我所做的是:

pth = 'D:\6th sem\Major project\Code'
resizedlist = dict()

for infile in glob.glob(os.path.join(path,'*.jpg')):
  imge = cv2.imread(infile)

  re_img = cv2.resize(imge,(256,256))
  ImEdges = cv2.imwrite('{0:d}.jpg'.format(i),re_img)
  resizelist.append(imge)
  i = i + 1
  resizelist_key = OrderedDict(sorted(enumerate(resizelist),key=lambda x: x[0])).keys()

for i,infle in enumerate(glob.glob(os.path.join(pth,'*.jpg'))):
  img = cv2.imread(infle)
  my_key = str(i)               
  resizedlist[my_key] = img

# Retreival code, result_list contains euclidean distance, and resultlist_key contains numbers

res_lst_srt = {'val': result_list,'key':resultlist_key}
res_lst_srt['val'], res_lst_srt['key'] = zip(*sorted(zip(res_lst_srt['val'], res_lst_srt['key'])))
cv2.imshow('query image',imge)
for key in res_lst_srt:
   if key in resizedlist:
       cv2.imshow("Result " + str(i + 1), resizedlist[i])
cv2.waitKey(0)
cv2.destroyAllWindows()    

path包含系统中一组图像的路径。 resizedlist_key包含从零开始直到n-1的数字。有什么方法可以基于字典键从字典中检索图像吗?
我一直在努力,但是仍然没有得到正确的结果,而且我不知道我的代码是否正确。所以我要问您的建议,我有49个图像的数据集,我需要将所有图像放入字典中,以便可以使用其键值随机检索图像。

提前致谢!

最佳答案

我不太了解您的代码和答案,尤其是我不理解您代码的zip部分。

无论如何,我假设您想要一个以数字作为键的字典,以及一个与键相关联的值的图像。

我认为您对dict在python中的工作方式感到有些困惑,您应该对其进行一些研究。 Google充满了有关python字典的不错的教程。另外,在使用opencv的图像之前,尝试仅使用简单的数字或字符串来进行一些练习,要了解这么好的python数据结构的内幕正在发生的事情要容易得多。

您将'value'用作键,因此您的字典仅包含1个项目,其中字符串'value'作为键。循环播放,您将用'value'中的最后一个图像替换与字符串cv2.imread关联的值。

词典数据结构具有2个属性,对于这种类型的集合中的每个项目,您都有一个键和一个值。使用'value'作为键(在[]运算符中),您假定元素的键具有SAME键:字符串。

尝试print len(resizedlist)print resized list,看看会发生什么。 Python非常擅长和出色的交互式编码,您可以轻松地通过打印进行调试。

这段代码可以正常工作,并将在给定路径中找到的所有图像(作为numpy数组,这是python和opencv2的工作方式)放入字典中,该字典的键是从0到n的数字(由enumerate提供):

import glob, os
import cv2, numpy

path = './'
image_dict = dict()

for i,infile in enumerate(glob.glob(os.path.join(path,'*.jpg'))):
    img = cv2.imread(infile)
    my_key = i                 # or put here whatever you want as a key
    image_dict[my_key] = img

#print image_dict
print len(image_dict)
print image_dict[0] # this is the value associated with the key 0
print image_dict.keys() # this is the list of all keys
print type(image_dict.keys()[0]) # this is <type 'int'>
print type(image_dict.values()[0]) # this is <type 'numpy.ndarray'>

为了更好地理解dict在python中的工作方式,请尝试使用my_key = str(i),并查看打印调试代码的变化。

希望对您有所帮助,希望能理解您的问题!!

关于python - 如何在字典中存储一组图像,并使用python opencv检索它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22556388/

相关文章:

python - 从 Pymongo 结果中删除 _id 元素

c++ - OpenCV内存不足

python - 选择 key :value pairs from a dictionary in Python

python - 如何在 Python 中将列表转换为嵌套字典

python - Julia 中的 Pyplot Labelposition Y 轴

python - 使用 python 正则表达式从文件中提取一行

python - Opencv imshow 是对的,而 imwrite 是错的?

visual-c++ - 从视频中获取帧

python - 在不使用 try except 的情况下填充字典

Python/Django - 表单选择值是对象 ID ...无法获取对象