def test_resize_crop(self):
        vertical_cropped = images.resize_crop(vertical, height, width)
        self.assertEqual(vertical_cropped.shape, (height, height, 3))

        horizontal_cropped = images.resize_crop(horizontal, height, width)
        self.assertEqual(horizontal_cropped.shape, (height, height, 3))

        square_cropped = images.resize_crop(square, height, width)
        self.assertEqual(square_cropped.shape, (height, height, 3))
def results():
    '''
    Add image to database, calculates features and finds nearest neighbors.
    :return: rendered template from html file
    '''

    # get data from form
    search_file = request.files['search_file']
    search_url = request.form['search_url']
    k = int(request.form['count'])

    # path to temporary image file
    filename = 'img'
    path = os.path.join(app.config['UPLOAD_FOLDER'], filename)

    # list of images to be passed to render_template
    filenames = []

    with lock:
        if not search_url and not search_file:
            msg = 'Please provide URL or file.'
            return render_template('results.html', msg=msg, data=[])

        if search_url:
            msg = 'Searching using URL (filename: %s).' % search_url.split('/')[-1]
            # temporarily save image in full resolution
            urllib.urlretrieve(search_url, path)
        else:
            msg = 'Searching using file (filename: %s).' % search_file.filename
            # temporarily save image in full resolution
            search_file.save(path)

        # open image using opencv, resize it and crop it (BGR, float32)
        img = cv2.imread(path)
        if img is None:
            msg = 'We apologize for the inconvenience but the image could not be saved.'
            return render_template('results.html', msg=msg, filenames=filenames)

        img_cropped = images.resize_crop(img, height, width)
        img_cropped = img_cropped.astype(np.float32)

        # delete temporary image
        os.remove(path)

        # calculate features (or choose random for local testing)
        if caffe_toggle:
            print 'Calculating features...'
            score = net.predict([img_cropped]).flatten()
            print 'Calculated.'
        else:
            with h5py.File(h5_fts_fn, 'r') as fr_features:
                score = fr_features['score'][randint(0, 9999)]

        # convert image to RGB uint8
        img_rgb = cv2.cvtColor(img_cropped, cv2.COLOR_BGR2RGB)
        img_rgb = img_rgb.astype(np.uint8)

        # add image and save thumbnail
        kdt.add_images([img_rgb], [score])

        # find k nearest neighbors
        last = len(kdt.features) - 1
        indexes, distances = kdt.find_k_nearest_by_index(last, k+1)

        # check for duplicate image
        if (distances[1] - distances[0]) < 1e-10:
            # remove duplicate image
            kdt.remove_last_image()

            # do not print duplicate image (recently added)
            if indexes[0] > indexes[1]:
                indexes = indexes[1:]
                distances = distances[1:]
            else:
                del indexes[1]
                del distances[1]
        else:
            indexes = indexes[:k]
            distances = distances[:k]
            kdt.save()

        # prepare list of files which will be printed
        for index in indexes:
            filenames.append(str(index) + '.jpg')

        zipped = zip(filenames, distances)

    return render_template('results.html', msg=msg, data=zipped)
kdt = kdtree_flann.ImageSearchKDTreeFlann(storage_dir, 1000000000, (150, 150, 3))

i = 0

for path in imgs_paths:
    if i % 50 == 0:
        print '\r', i, path,

    try:
        # open image using opencv
        img = cv2.imread(path)

        # color channels
        if len(img.shape) == 3:
            # resize image and crop it (BGR, float32)
            img_cropped = images.resize_crop(img, height, width)
            img_cropped = img_cropped.astype(np.float32)

            # calculate features
            score = net.predict([img_cropped]).flatten()

            # convert image to RGB uint8
            img_rgb = cv2.cvtColor(img_cropped, cv2.COLOR_BGR2RGB)
            img_rgb = img_rgb.astype(np.uint8)

            # add image and save thumbnail
            kdt.add_images([img_rgb], [score], build_tree=False)

            i += 1
    except:
        print '\nNot an image'