没有报错 不知道哪里有问题 程序是github上找的
import cv2
import numpy as np
import pickle as pk
import random
import os
import matplotlib.pyplot as plt
from imageio import imread
def extract_features(image_path, vector_size=32):
image = imread(image_path, mode="RGB")
try:
alg = cv2.SIFT_create()
kps = alg.detect(image)
kps = sorted(kps, key=lambda x: -x.response)[:vector_size]
kps, dsc = alg.compute(image, kps)
dsc = dsc.flatten()
needed_size = (vector_size * 64)
if dsc.size < needed_size:
dsc = np.concatenate([dsc, np.zeros(needed_size - dsc.size)])
except cv2.error as e:
print('Error: ', e)
return None
return dsc
def batch_extractor(images_path, pickled_db_path):
files = [os.path.join(images_path, p) for p in sorted(os.listdir(images_path))]
result = {}
for f in files:
print('Extracting features from image %s' % f)
name = f.split('/')[-1].lower()
result[name] = extract_features(f)
# saving all our feature vectors in pickled file
with open(pickled_db_path, 'w') as fp:
pickle.dump(result, fp)
class Matcher(object):
def __init__(self, pickled_db_path="features.pck"):
with open(pickled_db_path) 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):
# getting cosine distance between search image and images database
v = vector.reshape(1, -1)
return scipy.spatial.distance.cdist(self.matrix, v, 'cosine').reshape(-1)
def match(self, image_path, topn=5):
features = extract_features(image_path)
img_distances = self.cos_cdist(features)
# getting top 5 records
nearest_ids = np.argsort(img_distances)[:topn].tolist()
nearest_img_paths = self.names[nearest_ids].tolis