model = models.resnet18(pretrained=True)
return_nodes = {
'avgpool': 'embedding'
}
model = create_feature_extractor(model, return_nodes=return_nodes)
model.eval()
model.to(device)tform= transforms.Compose([
transforms.Resize((224,224)),
transforms.ToTensor(),
transforms.Lambda(lambda x: torch.cat([x, x, x], dim=0) if x.shape[0] == 1 else x),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])
def embedding_function(images, model = model, transform = tform, batch_size = 4):
"""Creates a list of embeddings based on a list of image filenames. Images are processed in batches."""
if isinstance(images, str):
images = [images]
#Proceess the embeddings in batches, but return everything as a single list
embeddings = []
for i in range(0, len(images), batch_size):
batch = torch.stack([transform(Image.open(item)) for item in images[i:i+batch_size]])
batch = batch.to(device)
with torch.no_grad():
embeddings+= model(batch)['embedding'][:,:,0,0].cpu().numpy().tolist()
return embeddingsvector_store_path = 'hub://<org_id>/<dataset_name>'
vector_store = VectorStore(
path = vector_store_path,
tensor_params = [{'name': 'image', 'htype': 'image', 'sample_compression': 'jpg'},
{'name': 'embedding', 'htype': 'embedding'},
{'name': 'filename', 'htype': 'text'}],
)image_fns = [os.path.join(images_path, item) for item in os.listdir(images_path) if os.path.splitext(item)[-1]=='.jpg']vector_store.add(image = image_fns,
filename = image_fns,
embedding_function = embedding_function,
embedding_data = image_fns) tensor htype shape dtype compression
------- ------- ------- ------- -------
embedding embedding (5000, 512) float32 None
filename text (5000, 1) str None
id text (5000, 1) str None
image image (5000, 145:640, 200:640, 1:3) uint8 jpeg image_path = '/image_similarity.jpg'
result = vector_store.search(embedding_data = image_path,
embedding_function = embedding_function)result.keys()
# Returns: dict_keys(['filename', 'id', 'image', 'score'])len(result['score'])
# Returns: 4result['image'][0].shape
# Returns: (427, 640, 3)result = vector_store.search(embedding_data = image_path,
embedding_function = embedding_function,
return_tensors = ['id', 'filename'])result.keys()
# Returns: dict_keys(['filename', 'id', 'image', 'score'])view = vector_store.search(embedding_data = image_path,
embedding_function = embedding_function,
return_view = True)view.save_view()


