utils.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import collections.abc as collections
  2. from pathlib import Path
  3. from types import SimpleNamespace
  4. from typing import Callable, List, Optional, Tuple, Union
  5. import cv2
  6. import kornia
  7. import numpy as np
  8. import torch
  9. class ImagePreprocessor:
  10. default_conf = {
  11. "resize": None, # target edge length, None for no resizing
  12. "side": "long",
  13. "interpolation": "bilinear",
  14. "align_corners": None,
  15. "antialias": True,
  16. }
  17. def __init__(self, **conf) -> None:
  18. super().__init__()
  19. self.conf = {**self.default_conf, **conf}
  20. self.conf = SimpleNamespace(**self.conf)
  21. def __call__(self, img: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
  22. """Resize and preprocess an image, return image and resize scale"""
  23. h, w = img.shape[-2:]
  24. if self.conf.resize is not None:
  25. img = kornia.geometry.transform.resize(
  26. img,
  27. self.conf.resize,
  28. side=self.conf.side,
  29. antialias=self.conf.antialias,
  30. align_corners=self.conf.align_corners,
  31. )
  32. scale = torch.Tensor([img.shape[-1] / w, img.shape[-2] / h]).to(img)
  33. return img, scale
  34. def map_tensor(input_, func: Callable):
  35. string_classes = (str, bytes)
  36. if isinstance(input_, string_classes):
  37. return input_
  38. elif isinstance(input_, collections.Mapping):
  39. return {k: map_tensor(sample, func) for k, sample in input_.items()}
  40. elif isinstance(input_, collections.Sequence):
  41. return [map_tensor(sample, func) for sample in input_]
  42. elif isinstance(input_, torch.Tensor):
  43. return func(input_)
  44. else:
  45. return input_
  46. def batch_to_device(batch: dict, device: str = "cpu", non_blocking: bool = True):
  47. """Move batch (dict) to device"""
  48. def _func(tensor):
  49. return tensor.to(device=device, non_blocking=non_blocking).detach()
  50. return map_tensor(batch, _func)
  51. def rbd(data: dict) -> dict:
  52. """Remove batch dimension from elements in data"""
  53. return {
  54. k: v[0] if isinstance(v, (torch.Tensor, np.ndarray, list)) else v
  55. for k, v in data.items()
  56. }
  57. def read_image(path: Path, grayscale: bool = False) -> np.ndarray:
  58. """Read an image from path as RGB or grayscale"""
  59. if not Path(path).exists():
  60. raise FileNotFoundError(f"No image at path {path}.")
  61. mode = cv2.IMREAD_GRAYSCALE if grayscale else cv2.IMREAD_COLOR
  62. image = cv2.imread(str(path), mode)
  63. if image is None:
  64. raise IOError(f"Could not read image at {path}.")
  65. if not grayscale:
  66. image = image[..., ::-1]
  67. return image
  68. def numpy_image_to_torch(image: np.ndarray) -> torch.Tensor:
  69. """Normalize the image tensor and reorder the dimensions."""
  70. if image.ndim == 3:
  71. image = image.transpose((2, 0, 1)) # HxWxC to CxHxW
  72. elif image.ndim == 2:
  73. image = image[None] # add channel axis
  74. else:
  75. raise ValueError(f"Not an image: {image.shape}")
  76. return torch.tensor(image / 255.0, dtype=torch.float)
  77. def resize_image(
  78. image: np.ndarray,
  79. size: Union[List[int], int],
  80. fn: str = "max",
  81. interp: Optional[str] = "area",
  82. ) -> np.ndarray:
  83. """Resize an image to a fixed size, or according to max or min edge."""
  84. h, w = image.shape[:2]
  85. fn = {"max": max, "min": min}[fn]
  86. if isinstance(size, int):
  87. scale = size / fn(h, w)
  88. h_new, w_new = int(round(h * scale)), int(round(w * scale))
  89. scale = (w_new / w, h_new / h)
  90. elif isinstance(size, (tuple, list)):
  91. h_new, w_new = size
  92. scale = (w_new / w, h_new / h)
  93. else:
  94. raise ValueError(f"Incorrect new size: {size}")
  95. mode = {
  96. "linear": cv2.INTER_LINEAR,
  97. "cubic": cv2.INTER_CUBIC,
  98. "nearest": cv2.INTER_NEAREST,
  99. "area": cv2.INTER_AREA,
  100. }[interp]
  101. return cv2.resize(image, (w_new, h_new), interpolation=mode), scale
  102. def load_image(path: Path, resize: int = None, **kwargs) -> torch.Tensor:
  103. image = read_image(path)
  104. if resize is not None:
  105. image, _ = resize_image(image, resize, **kwargs)
  106. return numpy_image_to_torch(image)
  107. class Extractor(torch.nn.Module):
  108. def __init__(self, **conf):
  109. super().__init__()
  110. self.conf = SimpleNamespace(**{**self.default_conf, **conf})
  111. @torch.no_grad()
  112. def extract(self, img: torch.Tensor, **conf) -> dict:
  113. """Perform extraction with online resizing"""
  114. if img.dim() == 3:
  115. img = img[None] # add batch dim
  116. assert img.dim() == 4 and img.shape[0] == 1
  117. shape = img.shape[-2:][::-1]
  118. img, scales = ImagePreprocessor(**{**self.preprocess_conf, **conf})(img)
  119. feats = self.forward({"image": img})
  120. feats["image_size"] = torch.tensor(shape)[None].to(img).float()
  121. feats["keypoints"] = (feats["keypoints"] + 0.5) / scales[None] - 0.5
  122. return feats
  123. def match_pair(
  124. extractor,
  125. matcher,
  126. image0: torch.Tensor,
  127. image1: torch.Tensor,
  128. device: str = "cpu",
  129. **preprocess,
  130. ):
  131. """Match a pair of images (image0, image1) with an extractor and matcher"""
  132. feats0 = extractor.extract(image0, **preprocess)
  133. feats1 = extractor.extract(image1, **preprocess)
  134. matches01 = matcher({"image0": feats0, "image1": feats1})
  135. data = [feats0, feats1, matches01]
  136. # remove batch dim and move to target device
  137. feats0, feats1, matches01 = [batch_to_device(rbd(x), device) for x in data]
  138. return feats0, feats1, matches01