# -*- coding: utf-8 -*-
"""sa.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1HPrK7I6aebmJqlQQi59JiW7AJFD5d_FK
"""

# !python3 -m cirtorch.examples.test --gpu-id '0' --network-path 'retrievalSfM120k-resnet101-gem' --datasets 'oxford5k' --whitening 'retrieval-SfM-120k' --multiscale '[1, 1/2**(1/2), 1/2]'

# from google.colab import drive
# drive.mount('/content/drive')
# %cd /content/drive/My Drive/Image_retrieval/cnnimageretrieval-pytorch

#!git clone https://github.com/filipradenovic/cnnimageretrieval-pytorch.git
import os
import torch
import os
import time
import pickle
import pdb

import numpy as np

import torch
from torch.utils.model_zoo import load_url
from torchvision import transforms

from cirtorch.networks.imageretrievalnet import init_network, extract_vectors
from cirtorch.datasets.datahelpers import cid2filename
from cirtorch.datasets.testdataset import configdataset
from cirtorch.utils.download import download_train, download_test
from cirtorch.utils.whiten import whitenlearn, whitenapply
from cirtorch.utils.evaluate import compute_map_and_print
from cirtorch.utils.general import get_data_root, htime


# os.environ['CUDA_VISIBLE_DEVICES'] = '0'
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
network_path = os.path.join(ROOT_DIR, 'data', 'networks', 'retrievalSfM120k-resnet101-gem-b80fb85.pth')
state = torch.load(network_path)
#
net_params = {}
net_params['architecture'] = state['meta']['architecture']
net_params['pooling'] = state['meta']['pooling']
net_params['local_whitening'] = state['meta'].get('local_whitening', False)
net_params['regional'] = state['meta'].get('regional', False)
net_params['whitening'] = state['meta'].get('whitening', False)
net_params['mean'] = state['meta']['mean']
net_params['std'] = state['meta']['std']
net_params['pretrained'] = False
#
 # load network
net = init_network(net_params)
net.load_state_dict(state['state_dict'])

#config groundtruth
cfg = configdataset('oxford5k', os.path.join(get_data_root(), 'test'))

#parameter
normalize = transforms.Normalize( mean=net.meta['mean'], std=net.meta['std'])
transform = transforms.Compose([transforms.ToTensor(), normalize])

ms = list(eval('[1, 1/2**(1/2), 1/2]'))
if len(ms)>1 and net.meta['pooling'] == 'gem' and not net.meta['regional'] and not net.meta['whitening']:
    msp = net.pool.p.item()
    print(">> Set-up multiscale:")
    print(">>>> ms: {}".format(ms))            
    print(">>>> msp: {}".format(msp))
else:
    msp = 1

#load database vector
vect_path = os.path.join(ROOT_DIR, 'data', 'oxford5k.npy')
vect = np.load(vect_path)

# net.cuda()
net.eval()
temp_path = os.path.join(ROOT_DIR, 'data', 'image_list.npy')
img_list = np.load(temp_path)
def query(query_path, bbx = None):
  global net, tranform, ms, msp, vect
  q = [query_path]

  if bbx is not None:
    bbxs = [bbx]
  else:
    bbxs = None
  q2vecs = extract_vectors(net, q, 1024, transform, bbxs = bbxs, ms=ms, msp=msp)
  scores = np.dot(vect.T, q2vecs)
  ranks = np.argsort(-scores, axis=0)
  ranks = ranks.reshape(5063)
  name = []
  for i in range(10):
      name += [img_list[ranks[i]]]
  return ranks, name
c9b65c4abf80bab9b850bae02e1bdea40041bf6c
<mask token>


def query(query_path, bbx=None):
    global net, tranform, ms, msp, vect
    q = [query_path]
    if bbx is not None:
        bbxs = [bbx]
    else:
        bbxs = None
    q2vecs = extract_vectors(net, q, 1024, transform, bbxs=bbxs, ms=ms, msp=msp
        )
    scores = np.dot(vect.T, q2vecs)
    ranks = np.argsort(-scores, axis=0)
    ranks = ranks.reshape(5063)
    name = []
    for i in range(10):
        name += [img_list[ranks[i]]]
    return ranks, name

<mask token>
net.load_state_dict(state['state_dict'])
<mask token>
if len(ms) > 1 and net.meta['pooling'] == 'gem' and not net.meta['regional'
    ] and not net.meta['whitening']:
    msp = net.pool.p.item()
    print('>> Set-up multiscale:')
    print('>>>> ms: {}'.format(ms))
    print('>>>> msp: {}'.format(msp))
else:
    msp = 1
<mask token>
net.eval()
<mask token>


def query(query_path, bbx=None):
    global net, tranform, ms, msp, vect
    q = [query_path]
    if bbx is not None:
        bbxs = [bbx]
    else:
        bbxs = None
    q2vecs = extract_vectors(net, q, 1024, transform, bbxs=bbxs, ms=ms, msp=msp
        )
    scores = np.dot(vect.T, q2vecs)
    ranks = np.argsort(-scores, axis=0)
    ranks = ranks.reshape(5063)
    name = []
    for i in range(10):
        name += [img_list[ranks[i]]]
    return ranks, name

<mask token>
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
network_path = os.path.join(ROOT_DIR, 'data', 'networks',
    'retrievalSfM120k-resnet101-gem-b80fb85.pth')
state = torch.load(network_path)
net_params = {}
net_params['architecture'] = state['meta']['architecture']
net_params['pooling'] = state['meta']['pooling']
net_params['local_whitening'] = state['meta'].get('local_whitening', False)
net_params['regional'] = state['meta'].get('regional', False)
net_params['whitening'] = state['meta'].get('whitening', False)
net_params['mean'] = state['meta']['mean']
net_params['std'] = state['meta']['std']
net_params['pretrained'] = False
net = init_network(net_params)
net.load_state_dict(state['state_dict'])
cfg = configdataset('oxford5k', os.path.join(get_data_root(), 'test'))
normalize = transforms.Normalize(mean=net.meta['mean'], std=net.meta['std'])
transform = transforms.Compose([transforms.ToTensor(), normalize])
ms = list(eval('[1, 1/2**(1/2), 1/2]'))
if len(ms) > 1 and net.meta['pooling'] == 'gem' and not net.meta['regional'
    ] and not net.meta['whitening']:
    msp = net.pool.p.item()
    print('>> Set-up multiscale:')
    print('>>>> ms: {}'.format(ms))
    print('>>>> msp: {}'.format(msp))
else:
    msp = 1
vect_path = os.path.join(ROOT_DIR, 'data', 'oxford5k.npy')
vect = np.load(vect_path)
net.eval()
temp_path = os.path.join(ROOT_DIR, 'data', 'image_list.npy')
img_list = np.load(temp_path)


def query(query_path, bbx=None):
    global net, tranform, ms, msp, vect
    q = [query_path]
    if bbx is not None:
        bbxs = [bbx]
    else:
        bbxs = None
    q2vecs = extract_vectors(net, q, 1024, transform, bbxs=bbxs, ms=ms, msp=msp
        )
    scores = np.dot(vect.T, q2vecs)
    ranks = np.argsort(-scores, axis=0)
    ranks = ranks.reshape(5063)
    name = []
    for i in range(10):
        name += [img_list[ranks[i]]]
    return ranks, name

<mask token>
import os
import torch
import os
import time
import pickle
import pdb
import numpy as np
import torch
from torch.utils.model_zoo import load_url
from torchvision import transforms
from cirtorch.networks.imageretrievalnet import init_network, extract_vectors
from cirtorch.datasets.datahelpers import cid2filename
from cirtorch.datasets.testdataset import configdataset
from cirtorch.utils.download import download_train, download_test
from cirtorch.utils.whiten import whitenlearn, whitenapply
from cirtorch.utils.evaluate import compute_map_and_print
from cirtorch.utils.general import get_data_root, htime
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
network_path = os.path.join(ROOT_DIR, 'data', 'networks',
    'retrievalSfM120k-resnet101-gem-b80fb85.pth')
state = torch.load(network_path)
net_params = {}
net_params['architecture'] = state['meta']['architecture']
net_params['pooling'] = state['meta']['pooling']
net_params['local_whitening'] = state['meta'].get('local_whitening', False)
net_params['regional'] = state['meta'].get('regional', False)
net_params['whitening'] = state['meta'].get('whitening', False)
net_params['mean'] = state['meta']['mean']
net_params['std'] = state['meta']['std']
net_params['pretrained'] = False
net = init_network(net_params)
net.load_state_dict(state['state_dict'])
cfg = configdataset('oxford5k', os.path.join(get_data_root(), 'test'))
normalize = transforms.Normalize(mean=net.meta['mean'], std=net.meta['std'])
transform = transforms.Compose([transforms.ToTensor(), normalize])
ms = list(eval('[1, 1/2**(1/2), 1/2]'))
if len(ms) > 1 and net.meta['pooling'] == 'gem' and not net.meta['regional'
    ] and not net.meta['whitening']:
    msp = net.pool.p.item()
    print('>> Set-up multiscale:')
    print('>>>> ms: {}'.format(ms))
    print('>>>> msp: {}'.format(msp))
else:
    msp = 1
vect_path = os.path.join(ROOT_DIR, 'data', 'oxford5k.npy')
vect = np.load(vect_path)
net.eval()
temp_path = os.path.join(ROOT_DIR, 'data', 'image_list.npy')
img_list = np.load(temp_path)


def query(query_path, bbx=None):
    global net, tranform, ms, msp, vect
    q = [query_path]
    if bbx is not None:
        bbxs = [bbx]
    else:
        bbxs = None
    q2vecs = extract_vectors(net, q, 1024, transform, bbxs=bbxs, ms=ms, msp=msp
        )
    scores = np.dot(vect.T, q2vecs)
    ranks = np.argsort(-scores, axis=0)
    ranks = ranks.reshape(5063)
    name = []
    for i in range(10):
        name += [img_list[ranks[i]]]
    return ranks, name

# -*- coding: utf-8 -*-
"""sa.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1HPrK7I6aebmJqlQQi59JiW7AJFD5d_FK
"""

# !python3 -m cirtorch.examples.test --gpu-id '0' --network-path 'retrievalSfM120k-resnet101-gem' --datasets 'oxford5k' --whitening 'retrieval-SfM-120k' --multiscale '[1, 1/2**(1/2), 1/2]'

# from google.colab import drive
# drive.mount('/content/drive')
# %cd /content/drive/My Drive/Image_retrieval/cnnimageretrieval-pytorch

#!git clone https://github.com/filipradenovic/cnnimageretrieval-pytorch.git
import os
import torch
import os
import time
import pickle
import pdb

import numpy as np

import torch
from torch.utils.model_zoo import load_url
from torchvision import transforms

from cirtorch.networks.imageretrievalnet import init_network, extract_vectors
from cirtorch.datasets.datahelpers import cid2filename
from cirtorch.datasets.testdataset import configdataset
from cirtorch.utils.download import download_train, download_test
from cirtorch.utils.whiten import whitenlearn, whitenapply
from cirtorch.utils.evaluate import compute_map_and_print
from cirtorch.utils.general import get_data_root, htime


# os.environ['CUDA_VISIBLE_DEVICES'] = '0'
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
network_path = os.path.join(ROOT_DIR, 'data', 'networks', 'retrievalSfM120k-resnet101-gem-b80fb85.pth')
state = torch.load(network_path)
#
net_params = {}
net_params['architecture'] = state['meta']['architecture']
net_params['pooling'] = state['meta']['pooling']
net_params['local_whitening'] = state['meta'].get('local_whitening', False)
net_params['regional'] = state['meta'].get('regional', False)
net_params['whitening'] = state['meta'].get('whitening', False)
net_params['mean'] = state['meta']['mean']
net_params['std'] = state['meta']['std']
net_params['pretrained'] = False
#
 # load network
net = init_network(net_params)
net.load_state_dict(state['state_dict'])

#config groundtruth
cfg = configdataset('oxford5k', os.path.join(get_data_root(), 'test'))

#parameter
normalize = transforms.Normalize( mean=net.meta['mean'], std=net.meta['std'])
transform = transforms.Compose([transforms.ToTensor(), normalize])

ms = list(eval('[1, 1/2**(1/2), 1/2]'))
if len(ms)>1 and net.meta['pooling'] == 'gem' and not net.meta['regional'] and not net.meta['whitening']:
    msp = net.pool.p.item()
    print(">> Set-up multiscale:")
    print(">>>> ms: {}".format(ms))            
    print(">>>> msp: {}".format(msp))
else:
    msp = 1

#load database vector
vect_path = os.path.join(ROOT_DIR, 'data', 'oxford5k.npy')
vect = np.load(vect_path)

# net.cuda()
net.eval()
temp_path = os.path.join(ROOT_DIR, 'data', 'image_list.npy')
img_list = np.load(temp_path)
def query(query_path, bbx = None):
  global net, tranform, ms, msp, vect
  q = [query_path]

  if bbx is not None:
    bbxs = [bbx]
  else:
    bbxs = None
  q2vecs = extract_vectors(net, q, 1024, transform, bbxs = bbxs, ms=ms, msp=msp)
  scores = np.dot(vect.T, q2vecs)
  ranks = np.argsort(-scores, axis=0)
  ranks = ranks.reshape(5063)
  name = []
  for i in range(10):
      name += [img_list[ranks[i]]]
  return ranks, name