Python Opencv 'numpy.ndarray' 对象没有属性 'iteritems'

Python Opencv 'numpy.ndarray' object has no attribute 'iteritems'

最近我一直在研究对象识别器。下面写的部分代码是抄来的。当我 运行 代码时,我得到了这个奇怪的错误: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))

有人可以帮忙吗?

我刚刚发现如何解决这个令人费解的问题。 @FlyingTeller 说它需要成为一本字典。这对我有帮助,因为我将 Self.data 转换成了字典。谢谢。