示例#1
0
    def compute_dist(self, images, labels, sample_size=None):
        """Compute distances for pairs

        sample_size: None or integer, number of pairs as all pairs can be large number.
                        If None, by default all possible pairs are considered.

        Returns:
        dist_embed:  array of distances
        actual_issame: array of booleans, True if positive pair, False if negative pair
        """
        # Run forward pass to calculate embeddings
        print('Generating pairs and computing embeddings...')

        # Define generator to loop over data
        gen = ImageDataGenerator(
            data_format=K.image_data_format(),
            preprocessing_function=self.backend_class.normalize,
        )
        features_shape = self.model.get_output_shape_at(0)[1:]

        if sample_size is None:
            n_pairs = comb(images.shape[0], 2, exact=True)
        else:
            n_pairs = int(sample_size)

        embeddings = np.zeros(shape=(2, n_pairs) + features_shape)
        actual_issame = np.full(shape=(n_pairs, ),
                                fill_value=True,
                                dtype=np.bool)

        # Create all possible combinations of images (no repeats)
        idx = 0
        for i in range(images.shape[0]):
            for j in range(i):
                img_1 = gen.random_transform(images[i].astype(K.floatx()))
                img_1 = gen.preprocessing_function(img_1)

                img_2 = gen.random_transform(images[j].astype(K.floatx()))
                img_2 = gen.preprocessing_function(img_2)

                embeddings[0, idx] = self.model.predict_on_batch(
                    np.expand_dims(img_1, 0))
                embeddings[1, idx] = self.model.predict_on_batch(
                    np.expand_dims(img_2, 0))

                if labels[i] != labels[j]:
                    actual_issame[idx] = False
                idx += 1

                if idx >= n_pairs:
                    break

            if idx >= n_pairs:
                break

        print('Number of pairs in evaluation {}, number of positive {}'.format(
            len(actual_issame), np.sum(actual_issame)))
        dist_emb = distance(embeddings[0], embeddings[1], distance_metric=0)
        return dist_emb, actual_issame
def getDistances(vectors):
    nSet = len(vectors)
    dists = [[] for k in range(nSet)]
    for i in range(0, nSet):
        for j in range(i + 1, nSet):
            dists[i][j] = distance(vectors[i], vectors[j])
            dists[j][i] = dists[i][j]
    return dists
示例#3
0
    def _calc_dist_between_pts(self):
        distances = []
        points = self.shape_points

        for ind in range(len(points) - 1):
            current_pt = (points[ind][0], points[ind][1])
            next_pt = (points[ind + 1][0], points[ind + 1][1])
            distances.append(metrics.distance(next_pt, current_pt))

        self.dist_between_pts = distances
示例#4
0
def main(img_path='../data/test/017029558.jpg',
         imgs_path='../data/test/',
         csv_path='data.csv',
         metric='0'):
    # ../data/test/000316731.jpg
    repo = Repository(csv_path)
    feats_map = []
    for fpath, _, feats in repo:
        if fpath.split('/')[-1] == img_path.split('/')[-1]:
            source_feats = feats
        else:
            feats_map.append((fpath, feats))

    if metric.startswith('m'):
        dim = int(metric.split('_')[-1])
        all_feats = [feats[:dim] for _, feats in feats_map[:dim]]
        cov = np.cov(np.array(all_feats))
        VI = np.linalg.pinv(cov)
        distance_map = map(
            lambda (fpath, feats):
            (mahalanobis(feats[:dim], source_feats[:dim], VI), fpath),
            feats_map)
    else:
        metric = int(metric)
        distance_map = map(
            lambda (fpath, feats):
            (distance(feats, source_feats, metric), fpath), feats_map)

    distance_map.sort()

    f, axarr = plt.subplots(4, 5, figsize=(20, 16))
    axarr[0, 2].imshow(mpimg.imread(img_path))
    axarr[0, 2].set_title("Source image", fontsize=24)
    axarr[0, 2].xaxis.set_visible(False)
    axarr[0, 2].yaxis.set_visible(False)
    for i in [0, 1, 3, 4]:
        axarr[0, i].axis('off')
    for i in xrange(15):
        axarr[1 + i / 5, i % 5].imshow(
            mpimg.imread(os.path.join(imgs_path, distance_map[i][1])))
        axarr[1 + i / 5, i % 5].set_title("{0:.3f}".format(distance_map[i][0]),
                                          fontsize=20)
        axarr[1 + i / 5, i % 5].xaxis.set_visible(False)
        axarr[1 + i / 5, i % 5].yaxis.set_visible(False)
    plt.tight_layout()
    plt.show()
    plt.close(f)