feature.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 
4 import numpy as np
5 from sklearn.cluster import MiniBatchKMeans
6 from sklearn.neighbors import NearestNeighbors
7 
8 
9 class BagOfFeatures(object):
10  def __init__(self, hist_size=500):
11  self.nn = None
12  self.hist_size = hist_size
13 
14  def fit(self, X):
15  """Fit features and extract bag of features"""
16  k = self.hist_size
17  km = MiniBatchKMeans(n_clusters=k, init_size=3*k, max_iter=300)
18  km.fit(X)
19  nn = NearestNeighbors(n_neighbors=1)
20  nn.fit(km.cluster_centers_)
21  self.nn = nn
22 
23  def transform(self, X):
24  return np.vstack([self.make_hist(xi.reshape((-1, 128))) for xi in X])
25 
26  def make_hist(self, descriptors):
27  """Make histogram for one image"""
28  nn = self.nn
29  if nn is None:
30  raise ValueError('must fit features before making histogram')
31  indices = nn.kneighbors(descriptors, return_distance=False)
32  histogram = np.zeros(self.hist_size)
33  for idx in np.unique(indices):
34  mask = indices == idx
35  histogram[idx] = mask.sum() # count the idx
36  indices = indices[mask == False]
37  return histogram
38 
39 
40 def decompose_descriptors_with_label(descriptors, positions, label_img,
41  skip_zero_label=False):
42  descriptors = descriptors.reshape((-1, 128))
43  positions = positions.reshape((-1, 2))
44  assert descriptors.shape[0] == positions.shape[0]
45 
46  decomposed = {}
47  positions = np.round(positions).astype(int)
48  labels = label_img[positions[:, 1], positions[:, 0]]
49  for label in np.unique(labels):
50  if skip_zero_label and (label == 0):
51  continue
52  decomposed[label] = descriptors[labels == label].reshape(-1)
53 
54  return decomposed
def make_hist(self, descriptors)
Definition: feature.py:26
def decompose_descriptors_with_label(descriptors, positions, label_img, skip_zero_label=False)
Definition: feature.py:41
def __init__(self, hist_size=500)
Definition: feature.py:10


jsk_recognition_utils
Author(s):
autogenerated on Mon May 3 2021 03:03:03