modular_owlv2.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import warnings
  15. import numpy as np
  16. import torch
  17. import torchvision.transforms.v2.functional as tvF
  18. from ...image_processing_backends import TorchvisionBackend
  19. from ...image_processing_utils import BatchFeature
  20. from ...image_transforms import (
  21. group_images_by_shape,
  22. pad,
  23. reorder_images,
  24. to_channel_dimension_format,
  25. )
  26. from ...image_utils import (
  27. OPENAI_CLIP_MEAN,
  28. OPENAI_CLIP_STD,
  29. ChannelDimension,
  30. PILImageResampling,
  31. SizeDict,
  32. )
  33. from ...utils import (
  34. TensorType,
  35. auto_docstring,
  36. is_scipy_available,
  37. requires_backends,
  38. )
  39. from ...utils.import_utils import requires
  40. from ..owlvit.image_processing_owlvit import OwlViTImageProcessor
  41. from ..owlvit.image_processing_pil_owlvit import OwlViTImageProcessorPil
  42. if is_scipy_available():
  43. from scipy import ndimage as ndi
  44. def _preprocess_resize_output_shape(image, output_shape):
  45. """Validate resize output shape according to input image.
  46. Args:
  47. image (`np.ndarray`):
  48. Image to be resized.
  49. output_shape (`iterable`):
  50. Size of the generated output image `(rows, cols[, ...][, dim])`. If `dim` is not provided, the number of
  51. channels is preserved.
  52. Returns
  53. image (`np.ndarray`):
  54. The input image, but with additional singleton dimensions appended in the case where `len(output_shape) >
  55. input.ndim`.
  56. output_shape (`Tuple`):
  57. The output shape converted to tuple.
  58. Raises ------ ValueError:
  59. If output_shape length is smaller than the image number of dimensions.
  60. Notes ----- The input image is reshaped if its number of dimensions is not equal to output_shape_length.
  61. """
  62. output_shape = tuple(output_shape)
  63. output_ndim = len(output_shape)
  64. input_shape = image.shape
  65. if output_ndim > image.ndim:
  66. # append dimensions to input_shape
  67. input_shape += (1,) * (output_ndim - image.ndim)
  68. image = np.reshape(image, input_shape)
  69. elif output_ndim == image.ndim - 1:
  70. # multichannel case: append shape of last axis
  71. output_shape = output_shape + (image.shape[-1],)
  72. elif output_ndim < image.ndim:
  73. raise ValueError("output_shape length cannot be smaller than the image number of dimensions")
  74. return image, output_shape
  75. def _clip_warp_output(input_image, output_image):
  76. """Clip output image to range of values of input image.
  77. Note that this function modifies the values of *output_image* in-place.
  78. Taken from:
  79. https://github.com/scikit-image/scikit-image/blob/b4b521d6f0a105aabeaa31699949f78453ca3511/skimage/transform/_warps.py#L640.
  80. Args:
  81. input_image : ndarray
  82. Input image.
  83. output_image : ndarray
  84. Output image, which is modified in-place.
  85. """
  86. min_val = np.min(input_image)
  87. if np.isnan(min_val):
  88. # NaNs detected, use NaN-safe min/max
  89. min_func = np.nanmin
  90. max_func = np.nanmax
  91. min_val = min_func(input_image)
  92. else:
  93. min_func = np.min
  94. max_func = np.max
  95. max_val = max_func(input_image)
  96. output_image = np.clip(output_image, min_val, max_val)
  97. return output_image
  98. def _scale_boxes(boxes, target_sizes):
  99. """
  100. Scale batch of bounding boxes to the target sizes.
  101. Args:
  102. boxes (`torch.Tensor` of shape `(batch_size, num_boxes, 4)`):
  103. Bounding boxes to scale. Each box is expected to be in (x1, y1, x2, y2) format.
  104. target_sizes (`list[tuple[int, int]]` or `torch.Tensor` of shape `(batch_size, 2)`):
  105. Target sizes to scale the boxes to. Each target size is expected to be in (height, width) format.
  106. Returns:
  107. `torch.Tensor` of shape `(batch_size, num_boxes, 4)`: Scaled bounding boxes.
  108. """
  109. if isinstance(target_sizes, (list, tuple)):
  110. image_height = torch.tensor([i[0] for i in target_sizes])
  111. image_width = torch.tensor([i[1] for i in target_sizes])
  112. elif isinstance(target_sizes, torch.Tensor):
  113. image_height, image_width = target_sizes.unbind(1)
  114. else:
  115. raise TypeError("`target_sizes` must be a list, tuple or torch.Tensor")
  116. # for owlv2 image is padded to max size unlike owlvit, that's why we have to scale boxes to max size
  117. max_size = torch.max(image_height, image_width)
  118. scale_factor = torch.stack([max_size, max_size, max_size, max_size], dim=1)
  119. scale_factor = scale_factor.unsqueeze(1).to(boxes.device)
  120. boxes = boxes * scale_factor
  121. return boxes
  122. @auto_docstring
  123. class Owlv2ImageProcessor(OwlViTImageProcessor):
  124. resample = PILImageResampling.BILINEAR
  125. image_mean = OPENAI_CLIP_MEAN
  126. image_std = OPENAI_CLIP_STD
  127. size = {"height": 960, "width": 960}
  128. rescale_factor = 1 / 255
  129. do_resize = True
  130. do_rescale = True
  131. do_normalize = True
  132. do_pad = True
  133. crop_size = None
  134. do_center_crop = None
  135. def _pad_images(self, images: "torch.Tensor", constant_value: float = 0.0) -> "torch.Tensor":
  136. """
  137. Pad an image with zeros to the given size.
  138. """
  139. height, width = images.shape[-2:]
  140. size = max(height, width)
  141. pad_bottom = size - height
  142. pad_right = size - width
  143. padding = (0, 0, pad_right, pad_bottom)
  144. padded_image = tvF.pad(images, padding, fill=constant_value)
  145. return padded_image
  146. def pad(
  147. self,
  148. images: list["torch.Tensor"],
  149. disable_grouping: bool | None,
  150. constant_value: float = 0.0,
  151. **kwargs,
  152. ) -> list["torch.Tensor"]:
  153. """
  154. Unlike the Base class `self.pad` where all images are padded to the maximum image size,
  155. Owlv2 pads an image to square.
  156. """
  157. grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
  158. processed_images_grouped = {}
  159. for shape, stacked_images in grouped_images.items():
  160. stacked_images = self._pad_images(
  161. stacked_images,
  162. constant_value=constant_value,
  163. )
  164. processed_images_grouped[shape] = stacked_images
  165. processed_images = reorder_images(processed_images_grouped, grouped_images_index)
  166. return processed_images
  167. def resize(
  168. self,
  169. image: "torch.Tensor",
  170. size: SizeDict,
  171. anti_aliasing: bool = True,
  172. anti_aliasing_sigma=None,
  173. **kwargs,
  174. ) -> "torch.Tensor":
  175. """
  176. Resize an image as per the original implementation.
  177. Args:
  178. image (`Tensor`):
  179. Image to resize.
  180. size (`dict[str, int]`):
  181. Dictionary containing the height and width to resize the image to.
  182. anti_aliasing (`bool`, *optional*, defaults to `True`):
  183. Whether to apply anti-aliasing when downsampling the image.
  184. anti_aliasing_sigma (`float`, *optional*, defaults to `None`):
  185. Standard deviation for Gaussian kernel when downsampling the image. If `None`, it will be calculated
  186. automatically.
  187. """
  188. output_shape = (size.height, size.width)
  189. input_shape = image.shape
  190. # select height and width from input tensor
  191. factors = torch.tensor(input_shape[2:]).to(image.device) / torch.tensor(output_shape).to(image.device)
  192. if anti_aliasing:
  193. if anti_aliasing_sigma is None:
  194. anti_aliasing_sigma = ((factors - 1) / 2).clamp(min=0)
  195. else:
  196. anti_aliasing_sigma = torch.atleast_1d(anti_aliasing_sigma) * torch.ones_like(factors)
  197. if torch.any(anti_aliasing_sigma < 0):
  198. raise ValueError("Anti-aliasing standard deviation must be greater than or equal to zero")
  199. elif torch.any((anti_aliasing_sigma > 0) & (factors <= 1)):
  200. warnings.warn(
  201. "Anti-aliasing standard deviation greater than zero but not down-sampling along all axes"
  202. )
  203. if torch.any(anti_aliasing_sigma == 0):
  204. filtered = image
  205. else:
  206. kernel_sizes = 2 * torch.ceil(3 * anti_aliasing_sigma).int() + 1
  207. filtered = tvF.gaussian_blur(
  208. image, (kernel_sizes[0], kernel_sizes[1]), sigma=anti_aliasing_sigma.tolist()
  209. )
  210. else:
  211. filtered = image
  212. return TorchvisionBackend.resize(filtered, size=size, antialias=False)
  213. def _preprocess(
  214. self,
  215. images: list["torch.Tensor"],
  216. do_resize: bool,
  217. size: SizeDict,
  218. resample: "PILImageResampling | None",
  219. do_pad: bool,
  220. do_rescale: bool,
  221. rescale_factor: float,
  222. do_normalize: bool,
  223. image_mean: float | list[float] | None,
  224. image_std: float | list[float] | None,
  225. disable_grouping: bool | None,
  226. return_tensors: str | TensorType | None,
  227. **kwargs,
  228. ) -> BatchFeature:
  229. # Group images by size for batched resizing
  230. grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
  231. processed_images_grouped = {}
  232. for shape, stacked_images in grouped_images.items():
  233. # Rescale images before other operations as done in original implementation
  234. stacked_images = self.rescale_and_normalize(
  235. stacked_images, do_rescale, rescale_factor, False, image_mean, image_std
  236. )
  237. processed_images_grouped[shape] = stacked_images
  238. processed_images = reorder_images(processed_images_grouped, grouped_images_index)
  239. if do_pad:
  240. processed_images = self.pad(processed_images, constant_value=0.0, disable_grouping=disable_grouping)
  241. grouped_images, grouped_images_index = group_images_by_shape(
  242. processed_images, disable_grouping=disable_grouping
  243. )
  244. resized_images_grouped = {}
  245. for shape, stacked_images in grouped_images.items():
  246. if do_resize:
  247. resized_stack = self.resize(image=stacked_images, size=size, resample=resample)
  248. resized_images_grouped[shape] = resized_stack
  249. resized_images = reorder_images(resized_images_grouped, grouped_images_index)
  250. # Group images by size for further processing
  251. # Needed in case do_resize is False, or resize returns images with different sizes
  252. grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
  253. processed_images_grouped = {}
  254. for shape, stacked_images in grouped_images.items():
  255. # Fused rescale and normalize
  256. stacked_images = self.rescale_and_normalize(
  257. stacked_images, False, rescale_factor, do_normalize, image_mean, image_std
  258. )
  259. processed_images_grouped[shape] = stacked_images
  260. processed_images = reorder_images(processed_images_grouped, grouped_images_index)
  261. return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
  262. @auto_docstring
  263. @requires(backends=("torch",))
  264. class Owlv2ImageProcessorPil(OwlViTImageProcessorPil):
  265. resample = PILImageResampling.BILINEAR
  266. image_mean = OPENAI_CLIP_MEAN
  267. image_std = OPENAI_CLIP_STD
  268. size = {"height": 960, "width": 960}
  269. rescale_factor = 1 / 255
  270. do_resize = True
  271. do_rescale = True
  272. do_normalize = True
  273. do_pad = True
  274. crop_size = None
  275. do_center_crop = None
  276. def pad(self, image: np.ndarray, constant_value: float = 0.0) -> np.ndarray:
  277. """
  278. Pad an image with zeros to the given size.
  279. """
  280. height, width = image.shape[-2:]
  281. size = max(height, width)
  282. pad_bottom = size - height
  283. pad_right = size - width
  284. image = pad(
  285. image=image,
  286. padding=((0, pad_bottom), (0, pad_right)),
  287. constant_values=constant_value,
  288. )
  289. return image
  290. def resize(
  291. self,
  292. image: np.ndarray,
  293. size: dict[str, int],
  294. anti_aliasing: bool = True,
  295. anti_aliasing_sigma=None,
  296. **kwargs,
  297. ) -> np.ndarray:
  298. """
  299. Resize an image as per the original implementation.
  300. Args:
  301. image (`np.ndarray`):
  302. Image to resize.
  303. size (`dict[str, int]`):
  304. Dictionary containing the height and width to resize the image to.
  305. anti_aliasing (`bool`, *optional*, defaults to `True`):
  306. Whether to apply anti-aliasing when downsampling the image.
  307. anti_aliasing_sigma (`float`, *optional*, defaults to `None`):
  308. Standard deviation for Gaussian kernel when downsampling the image. If `None`, it will be calculated
  309. automatically.
  310. """
  311. requires_backends(self, "scipy")
  312. output_shape = (size["height"], size["width"])
  313. image = to_channel_dimension_format(image, ChannelDimension.LAST)
  314. image, output_shape = _preprocess_resize_output_shape(image, output_shape)
  315. input_shape = image.shape
  316. factors = np.divide(input_shape, output_shape)
  317. # Translate modes used by np.pad to those used by scipy.ndimage
  318. ndi_mode = "mirror"
  319. cval = 0
  320. order = 1
  321. if anti_aliasing:
  322. if anti_aliasing_sigma is None:
  323. anti_aliasing_sigma = np.maximum(0, (factors - 1) / 2)
  324. else:
  325. anti_aliasing_sigma = np.atleast_1d(anti_aliasing_sigma) * np.ones_like(factors)
  326. if np.any(anti_aliasing_sigma < 0):
  327. raise ValueError("Anti-aliasing standard deviation must be greater than or equal to zero")
  328. elif np.any((anti_aliasing_sigma > 0) & (factors <= 1)):
  329. warnings.warn(
  330. "Anti-aliasing standard deviation greater than zero but not down-sampling along all axes"
  331. )
  332. filtered = ndi.gaussian_filter(image, anti_aliasing_sigma, cval=cval, mode=ndi_mode)
  333. else:
  334. filtered = image
  335. zoom_factors = [1 / f for f in factors]
  336. out = ndi.zoom(filtered, zoom_factors, order=order, mode=ndi_mode, cval=cval, grid_mode=True)
  337. image = _clip_warp_output(image, out)
  338. image = to_channel_dimension_format(image, ChannelDimension.FIRST)
  339. return image
  340. def _preprocess(
  341. self,
  342. images: list[np.ndarray],
  343. do_resize: bool,
  344. size: SizeDict,
  345. resample: "PILImageResampling | None",
  346. do_pad: bool,
  347. do_rescale: bool,
  348. rescale_factor: float,
  349. do_normalize: bool,
  350. image_mean: float | list[float] | None,
  351. image_std: float | list[float] | None,
  352. return_tensors: str | TensorType | None,
  353. **kwargs,
  354. ) -> BatchFeature:
  355. processed_images = []
  356. for image in images:
  357. if do_rescale:
  358. image = self.rescale(image, rescale_factor)
  359. if do_pad:
  360. image = self.pad(image)
  361. if do_resize:
  362. image = self.resize(image, size, resample)
  363. if do_normalize:
  364. image = self.normalize(image, image_mean, image_std)
  365. processed_images.append(image)
  366. return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
  367. __all__ = ["Owlv2ImageProcessor", "Owlv2ImageProcessorPil"]