最近我一直在研究对象识别器。下面编写的某些代码已被复制。运行代码时,出现了这个无法修复的奇怪错误:AttributeError: 'numpy.ndarray' object has no attribute 'iteritems'
。我看了一下互联网,但没有找到可以使用的相关答案。预先感谢。
错误:
Traceback (most recent call last):
File "/Users/arkumar/TestProj./ObjDetect.py", line 67, in <module>
ma = Matcher('features.pck')
File "/Users/arkumar/TestProj./ObjDetect.py", line 40, in __init__
for k, v in self.data.iteritems():
AttributeError: 'numpy.ndarray' object has no attribute 'iteritems'
代码:
import cv2
import pickle
import numpy as np
import scipy
import os
class ExtractFeatures():
def __init__(self, img = 'NULL', vectorSize = 32, out = 'features.pck'):
self.img = img
self.out = out
self.vectorSize = vectorSize
self.surf = cv2.xfeatures2d.SURF_create(400)
self.img = cv2.imread(img)
self.kp, self.des = self.surf.detectAndCompute(self.img, None)
self.vectorSize = 32
self.kp = sorted(self.kp, key=lambda x: -x.response)[:self.vectorSize]
print self.des
self.des = self.des.flatten()
needed_size = (self.vectorSize * 64)
if self.des.size < needed_size:
dsc = np.concatenate([self.des, np.zeros(needed_size - self.des.size)])
print(self.des)
with open(self.out, 'w') as fp:
pickle.dump(self.des, fp)
class Matcher(object):
def __init__(self, path = 'NULL'):
with open('features.pck') as fp:
self.data = pickle.load(fp)
self.names = []
self.matrix = []
for k, v in self.data.iteritems():
self.names.append(k)
self.matrix.append(v)
self.matrix = np.array(self.matrix)
self.names = np.array(self.names)
def cos_cdist(self, vector):
v = vector.reshape(1, -1)
return scipy.spatial.distance.cdist(self.matrix, v, 'cosine').reshape(-1)
def match(self, image_path, topn=5):
features = ExtractFeatures(image_path)
img_distances = self.cos_cdist(features)
nearest_ids = np.argsort(img_distances)[:topn].tolist()
nearest_img_paths = self.names[nearest_ids].tolist()
return nearest_img_paths, img_distances[nearest_ids].tolist()
def show_img(path):
img = cv2.imread(path, mode="RGB")
img.imshow()
cv2.waitkey(0)
imagePath = 'flute.jpg'
ExtractFeatures(imagePath)
ma = Matcher('features.pck')
print 'Query:'
show_img(imagePath)
names, match = ma.match(imagePath, topn=3)
print 'Result:'
print 'Match : '
show_img(os.path.join(imagePath))
有人可以帮忙吗?
答案 0 :(得分:0)
我刚刚发现了如何解决这个令人困惑的问题。 @FlyingTeller说它需要是一本字典。这对我有所帮助,因为我将Self.data
转换成字典。谢谢。