Swarm-SLAM  1.0.0
C-SLAM Framework
nns_matching.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 import numpy as np
3 from scipy.spatial import distance
4 
5 
7  """Nearest Neighbor matching of description vectors
8  """
9 
10  def __init__(self, dim=None):
11  """Initialization
12 
13  Args:
14  dim (int, optional): Global descriptor size. Defaults to None.
15  """
16  self.nn = 0
17  self.dimdim = dim
18  self.itemsitems = dict()
19  self.datadata = []
20  if dim is not None:
21  self.datadata = np.zeros((1000, dim), dtype='float32')
22 
23  def add_item(self, vector, item):
24  """Add item to the matching list
25 
26  Args:
27  vector (np.array): descriptor
28  item: identification info (e.g., int)
29  """
30  assert vector.ndim == 1
31  if self.nn >= len(self.datadata):
32  if self.dimdim is None:
33  self.dimdim = len(vector)
34  self.datadata = np.zeros((1000, self.dimdim), dtype='float32')
35  else:
36  self.datadata.resize((2 * len(self.datadata), self.dimdim),
37  refcheck=False)
38  self.itemsitems[self.nn] = item
39  self.datadata[self.nn] = vector
40  self.nn += 1
41 
42  def search(self, query, k): # searching from 100000 items consume 30ms
43  """Search for nearest neighbors
44 
45  Args:
46  query (np.array): descriptor to match
47  k (int): number of best matches to return
48 
49  Returns:
50  list(int, np.array): best matches
51  """
52  if len(self.datadata) == 0:
53  return [], []
54 
55  similarities = np.zeros(self.nn)
56 
57  for i in range(self.nn):
58  similarities[i] = 1 - distance.cosine(query, self.datadata[i,:].squeeze())
59 
60  ns = np.argsort(similarities)[::-1][:k]
61  return [self.itemsitems[n] for n in ns], similarities[ns]
62 
63  def search_best(self, query):
64  """Search for the nearest neighbor
65 
66  Args:
67  query (np.array): descriptor to match
68 
69  Returns:
70  int, np.array: best match
71  """
72  if len(self.datadata) == 0:
73  return None, None
74 
75  items, similarities = self.searchsearch(query, 1)
76  return items[0], similarities[0]