|
| 1 | +import codecs |
| 2 | +import os |
| 3 | +import os.path |
| 4 | +import shutil |
| 5 | +import string |
| 6 | +import sys |
| 7 | +import warnings |
| 8 | +from typing import Any, Callable, Dict, List, Optional, Tuple, Sequence |
| 9 | + |
| 10 | +import numpy as np |
| 11 | +from scipy.spatial import KDTree |
| 12 | +import torch |
| 13 | +from PIL import Image |
| 14 | +import glob |
| 15 | +import cv2 |
| 16 | + |
| 17 | +from snn.utils import detect_device |
| 18 | +from snn.model import SiameseNetwork |
| 19 | + |
| 20 | + |
| 21 | +class ImageSet: |
| 22 | + """ |
| 23 | + Subscriptapble dataset-like class for loading, storing and processing image collections |
| 24 | + |
| 25 | + :param root: Path to project root directory, which contains data/image_corpus/ or data/query catalog |
| 26 | + :param base: Build ImageSet on top of image_corpus if True, else on top of query catalog |
| 27 | + :param build: Build ImageSet from filesystem instead of using saved version |
| 28 | + :param transform: Callable that will be applied to all images when calling __getitem__() method |
| 29 | + :param compatibility_mode: Convert images to PIL.Image before applying transform and returning from __getitime__() method |
| 30 | + :param greyscale: Load images in grayscale if True, else use 3-channel RGB |
| 31 | + :param normalize: If True, images will be normalized image-wise when loaded from disk |
| 32 | + """ |
| 33 | + def __init__(self, |
| 34 | + root: str, |
| 35 | + base: bool = True, |
| 36 | + build: bool = False, |
| 37 | + transform: Callable = None, |
| 38 | + compatibility_mode: bool = False, |
| 39 | + greyscale: bool = False, |
| 40 | + normalize: bool = True) -> None: |
| 41 | + |
| 42 | + self.root = root |
| 43 | + self.compatibility_mode = compatibility_mode |
| 44 | + self.greyscale = greyscale |
| 45 | + self.colormode = 'L' if greyscale else 'RGB' |
| 46 | + self.transform = transform |
| 47 | + self.base = base |
| 48 | + self.normalize = normalize |
| 49 | + |
| 50 | + if build: |
| 51 | + self.embeddings = [] |
| 52 | + self.data, self.names = self._build() |
| 53 | + return |
| 54 | + |
| 55 | + self.data = self._load() |
| 56 | + |
| 57 | + |
| 58 | + def _build(self) -> Tuple[torch.Tensor, str]: |
| 59 | + |
| 60 | + dirpath = f"{self.root}/data/{'image_corpus' if self.base else 'query'}" |
| 61 | + data = [] |
| 62 | + images = [] |
| 63 | + names = [] |
| 64 | + for filename in glob.glob(f"{dirpath}/*png"): |
| 65 | + im = Image.open(filename) |
| 66 | + # resize into common shape |
| 67 | + im = im.convert(self.colormode).resize((118, 143)) |
| 68 | + if self.normalize: |
| 69 | + im = cv2.normalize(np.array(im), None, 0.0, 1.0, cv2.NORM_MINMAX, cv2.CV_32FC1) |
| 70 | + image = np.array(im, dtype=np.float32) |
| 71 | + fname = filename.split('/')[-1] |
| 72 | + data.append(image) |
| 73 | + names.append(fname) |
| 74 | + return torch.from_numpy(np.array(data)), names |
| 75 | + |
| 76 | + def _load(self) -> Tuple[torch.Tensor, str]: |
| 77 | + ... |
| 78 | + |
| 79 | + def save(self) -> None: |
| 80 | + ... |
| 81 | + |
| 82 | + def build_embeddings(self, model: SiameseNetwork, device: torch.cuda.device = None): |
| 83 | + |
| 84 | + if device is None: |
| 85 | + device = detect_device() |
| 86 | + |
| 87 | + with torch.no_grad(): |
| 88 | + model.eval() |
| 89 | + for img, name in self: |
| 90 | + img_input = img.transpose(2,0).transpose(2,1).to(device).unsqueeze(0) |
| 91 | + embedding = model.get_embedding(img_input) |
| 92 | + self.embeddings.append((embedding, name)) |
| 93 | + |
| 94 | + return self |
| 95 | + |
| 96 | + def get_embeddings(self) -> List[Tuple[torch.Tensor, str]]: |
| 97 | + if self.embeddings is None: |
| 98 | + raise RuntimeError('Embedding collection is empty. Run self.build_embeddings() method to build it') |
| 99 | + |
| 100 | + return self.embeddings |
| 101 | + |
| 102 | + def __getitem__(self, index: int) -> Tuple[Any, Any]: |
| 103 | + """ |
| 104 | + Args: |
| 105 | + index (int): Index |
| 106 | +
|
| 107 | + Returns: |
| 108 | + tuple: (image, target) where target is index of the target class. |
| 109 | + """ |
| 110 | + img = self.data[index] |
| 111 | + name = self.names[index] |
| 112 | + # doing this so that it is consistent with all other datasets |
| 113 | + # to return a PIL Image |
| 114 | + if self.compatibility_mode: |
| 115 | + img = Image.fromarray(img.numpy(), mode=self.colormode) |
| 116 | + |
| 117 | + if self.transform is not None: |
| 118 | + img = self.transform(img) |
| 119 | + |
| 120 | + return img, name |
| 121 | + |
| 122 | + |
| 123 | +class SearchTree: |
| 124 | + """ |
| 125 | + Wrapper for k-d tree built on image embeddings |
| 126 | + |
| 127 | + :param query_set: instance of base ImageSet with built embedding representation |
| 128 | + """ |
| 129 | + def __init__(self, query_set: ImageSet) -> None: |
| 130 | + embeddings = query_set.get_embeddings() |
| 131 | + self.embeddings = np.concatenate([x[0].cpu().numpy() for x in embeddings], axis=0) |
| 132 | + self.names = np.array([x[1] for x in embeddings]) |
| 133 | + self.kdtree = self._build_kdtree() |
| 134 | + |
| 135 | + def _build_kdtree(self) -> KDTree: |
| 136 | + print('Building KD-Tree from embeddings') |
| 137 | + return KDTree(self.embeddings) |
| 138 | + |
| 139 | + def query(self, anchors: ImageSet, k: int = 3) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: |
| 140 | + """ |
| 141 | + Search for k nearest neighbors of provided anchor embeddings |
| 142 | + |
| 143 | + :param anchors: instance of query (reference) ImageSet with built embedding representation |
| 144 | + |
| 145 | + :returns: tuple of reference_labels, distances to matched label embeddings, matched label embeddings, matched_labels |
| 146 | + """ |
| 147 | + |
| 148 | + reference = anchors.get_embeddings() |
| 149 | + reference_embeddings = np.concatenate([x[0].cpu().numpy() for x in reference], axis=0) |
| 150 | + reference_labels = np.array([x[1] for x in reference]) |
| 151 | + |
| 152 | + distances, indices = self.kdtree.query(reference_embeddings, k=k, workers=-1) |
| 153 | + return reference_labels, distances, self.embeddings[indices], self.names[indices] |
| 154 | + |
| 155 | + def __call__(self, *args, **kwargs) -> Any: |
| 156 | + return self.query(*args, **kwargs) |
| 157 | + |
0 commit comments