utils.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. import math
  2. import pathlib
  3. import warnings
  4. from types import FunctionType
  5. from typing import Any, BinaryIO, List, Optional, Tuple, Union
  6. import numpy as np
  7. import torch
  8. from PIL import Image, ImageColor, ImageDraw, ImageFont
  9. __all__ = [
  10. "make_grid",
  11. "save_image",
  12. "draw_bounding_boxes",
  13. "draw_segmentation_masks",
  14. "draw_keypoints",
  15. "flow_to_image",
  16. ]
  17. @torch.no_grad()
  18. def make_grid(
  19. tensor: Union[torch.Tensor, List[torch.Tensor]],
  20. nrow: int = 8,
  21. padding: int = 2,
  22. normalize: bool = False,
  23. value_range: Optional[Tuple[int, int]] = None,
  24. scale_each: bool = False,
  25. pad_value: float = 0.0,
  26. **kwargs,
  27. ) -> torch.Tensor:
  28. """
  29. Make a grid of images.
  30. Args:
  31. tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)
  32. or a list of images all of the same size.
  33. nrow (int, optional): Number of images displayed in each row of the grid.
  34. The final grid size is ``(B / nrow, nrow)``. Default: ``8``.
  35. padding (int, optional): amount of padding. Default: ``2``.
  36. normalize (bool, optional): If True, shift the image to the range (0, 1),
  37. by the min and max values specified by ``value_range``. Default: ``False``.
  38. value_range (tuple, optional): tuple (min, max) where min and max are numbers,
  39. then these numbers are used to normalize the image. By default, min and max
  40. are computed from the tensor.
  41. range (tuple. optional):
  42. .. warning::
  43. This parameter was deprecated in ``0.12`` and will be removed in ``0.14``. Please use ``value_range``
  44. instead.
  45. scale_each (bool, optional): If ``True``, scale each image in the batch of
  46. images separately rather than the (min, max) over all images. Default: ``False``.
  47. pad_value (float, optional): Value for the padded pixels. Default: ``0``.
  48. Returns:
  49. grid (Tensor): the tensor containing grid of images.
  50. """
  51. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  52. _log_api_usage_once(make_grid)
  53. if not torch.is_tensor(tensor):
  54. if isinstance(tensor, list):
  55. for t in tensor:
  56. if not torch.is_tensor(t):
  57. raise TypeError(f"tensor or list of tensors expected, got a list containing {type(t)}")
  58. else:
  59. raise TypeError(f"tensor or list of tensors expected, got {type(tensor)}")
  60. if "range" in kwargs.keys():
  61. warnings.warn(
  62. "The parameter 'range' is deprecated since 0.12 and will be removed in 0.14. "
  63. "Please use 'value_range' instead."
  64. )
  65. value_range = kwargs["range"]
  66. # if list of tensors, convert to a 4D mini-batch Tensor
  67. if isinstance(tensor, list):
  68. tensor = torch.stack(tensor, dim=0)
  69. if tensor.dim() == 2: # single image H x W
  70. tensor = tensor.unsqueeze(0)
  71. if tensor.dim() == 3: # single image
  72. if tensor.size(0) == 1: # if single-channel, convert to 3-channel
  73. tensor = torch.cat((tensor, tensor, tensor), 0)
  74. tensor = tensor.unsqueeze(0)
  75. if tensor.dim() == 4 and tensor.size(1) == 1: # single-channel images
  76. tensor = torch.cat((tensor, tensor, tensor), 1)
  77. if normalize is True:
  78. tensor = tensor.clone() # avoid modifying tensor in-place
  79. if value_range is not None and not isinstance(value_range, tuple):
  80. raise TypeError("value_range has to be a tuple (min, max) if specified. min and max are numbers")
  81. def norm_ip(img, low, high):
  82. img.clamp_(min=low, max=high)
  83. img.sub_(low).div_(max(high - low, 1e-5))
  84. def norm_range(t, value_range):
  85. if value_range is not None:
  86. norm_ip(t, value_range[0], value_range[1])
  87. else:
  88. norm_ip(t, float(t.min()), float(t.max()))
  89. if scale_each is True:
  90. for t in tensor: # loop over mini-batch dimension
  91. norm_range(t, value_range)
  92. else:
  93. norm_range(tensor, value_range)
  94. if not isinstance(tensor, torch.Tensor):
  95. raise TypeError("tensor should be of type torch.Tensor")
  96. if tensor.size(0) == 1:
  97. return tensor.squeeze(0)
  98. # make the mini-batch of images into a grid
  99. nmaps = tensor.size(0)
  100. xmaps = min(nrow, nmaps)
  101. ymaps = int(math.ceil(float(nmaps) / xmaps))
  102. height, width = int(tensor.size(2) + padding), int(tensor.size(3) + padding)
  103. num_channels = tensor.size(1)
  104. grid = tensor.new_full((num_channels, height * ymaps + padding, width * xmaps + padding), pad_value)
  105. k = 0
  106. for y in range(ymaps):
  107. for x in range(xmaps):
  108. if k >= nmaps:
  109. break
  110. # Tensor.copy_() is a valid method but seems to be missing from the stubs
  111. # https://pytorch.org/docs/stable/tensors.html#torch.Tensor.copy_
  112. grid.narrow(1, y * height + padding, height - padding).narrow( # type: ignore[attr-defined]
  113. 2, x * width + padding, width - padding
  114. ).copy_(tensor[k])
  115. k = k + 1
  116. return grid
  117. @torch.no_grad()
  118. def save_image(
  119. tensor: Union[torch.Tensor, List[torch.Tensor]],
  120. fp: Union[str, pathlib.Path, BinaryIO],
  121. format: Optional[str] = None,
  122. **kwargs,
  123. ) -> None:
  124. """
  125. Save a given Tensor into an image file.
  126. Args:
  127. tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,
  128. saves the tensor as a grid of images by calling ``make_grid``.
  129. fp (string or file object): A filename or a file object
  130. format(Optional): If omitted, the format to use is determined from the filename extension.
  131. If a file object was used instead of a filename, this parameter should always be used.
  132. **kwargs: Other arguments are documented in ``make_grid``.
  133. """
  134. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  135. _log_api_usage_once(save_image)
  136. grid = make_grid(tensor, **kwargs)
  137. # Add 0.5 after unnormalizing to [0, 255] to round to nearest integer
  138. ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
  139. im = Image.fromarray(ndarr)
  140. im.save(fp, format=format)
  141. @torch.no_grad()
  142. def draw_bounding_boxes(
  143. image: torch.Tensor,
  144. boxes: torch.Tensor,
  145. labels: Optional[List[str]] = None,
  146. colors: Optional[Union[List[Union[str, Tuple[int, int, int]]], str, Tuple[int, int, int]]] = None,
  147. fill: Optional[bool] = False,
  148. width: int = 1,
  149. font: Optional[str] = None,
  150. font_size: Optional[int] = None,
  151. ) -> torch.Tensor:
  152. """
  153. Draws bounding boxes on given image.
  154. The values of the input image should be uint8 between 0 and 255.
  155. If fill is True, Resulting Tensor should be saved as PNG image.
  156. Args:
  157. image (Tensor): Tensor of shape (C x H x W) and dtype uint8.
  158. boxes (Tensor): Tensor of size (N, 4) containing bounding boxes in (xmin, ymin, xmax, ymax) format. Note that
  159. the boxes are absolute coordinates with respect to the image. In other words: `0 <= xmin < xmax < W` and
  160. `0 <= ymin < ymax < H`.
  161. labels (List[str]): List containing the labels of bounding boxes.
  162. colors (color or list of colors, optional): List containing the colors
  163. of the boxes or single color for all boxes. The color can be represented as
  164. PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
  165. By default, random colors are generated for boxes.
  166. fill (bool): If `True` fills the bounding box with specified color.
  167. width (int): Width of bounding box.
  168. font (str): A filename containing a TrueType font. If the file is not found in this filename, the loader may
  169. also search in other directories, such as the `fonts/` directory on Windows or `/Library/Fonts/`,
  170. `/System/Library/Fonts/` and `~/Library/Fonts/` on macOS.
  171. font_size (int): The requested font size in points.
  172. Returns:
  173. img (Tensor[C, H, W]): Image Tensor of dtype uint8 with bounding boxes plotted.
  174. """
  175. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  176. _log_api_usage_once(draw_bounding_boxes)
  177. if not isinstance(image, torch.Tensor):
  178. raise TypeError(f"Tensor expected, got {type(image)}")
  179. elif image.dtype != torch.uint8:
  180. raise ValueError(f"Tensor uint8 expected, got {image.dtype}")
  181. elif image.dim() != 3:
  182. raise ValueError("Pass individual images, not batches")
  183. elif image.size(0) not in {1, 3}:
  184. raise ValueError("Only grayscale and RGB images are supported")
  185. num_boxes = boxes.shape[0]
  186. if num_boxes == 0:
  187. warnings.warn("boxes doesn't contain any box. No box was drawn")
  188. return image
  189. if labels is None:
  190. labels: Union[List[str], List[None]] = [None] * num_boxes # type: ignore[no-redef]
  191. elif len(labels) != num_boxes:
  192. raise ValueError(
  193. f"Number of boxes ({num_boxes}) and labels ({len(labels)}) mismatch. Please specify labels for each box."
  194. )
  195. if colors is None:
  196. colors = _generate_color_palette(num_boxes)
  197. elif isinstance(colors, list):
  198. if len(colors) < num_boxes:
  199. raise ValueError(f"Number of colors ({len(colors)}) is less than number of boxes ({num_boxes}). ")
  200. else: # colors specifies a single color for all boxes
  201. colors = [colors] * num_boxes
  202. colors = [(ImageColor.getrgb(color) if isinstance(color, str) else color) for color in colors]
  203. if font is None:
  204. if font_size is not None:
  205. warnings.warn("Argument 'font_size' will be ignored since 'font' is not set.")
  206. txt_font = ImageFont.load_default()
  207. else:
  208. txt_font = ImageFont.truetype(font=font, size=font_size or 10)
  209. # Handle Grayscale images
  210. if image.size(0) == 1:
  211. image = torch.tile(image, (3, 1, 1))
  212. ndarr = image.permute(1, 2, 0).cpu().numpy()
  213. img_to_draw = Image.fromarray(ndarr)
  214. img_boxes = boxes.to(torch.int64).tolist()
  215. if fill:
  216. draw = ImageDraw.Draw(img_to_draw, "RGBA")
  217. else:
  218. draw = ImageDraw.Draw(img_to_draw)
  219. for bbox, color, label in zip(img_boxes, colors, labels): # type: ignore[arg-type]
  220. if fill:
  221. fill_color = color + (100,)
  222. draw.rectangle(bbox, width=width, outline=color, fill=fill_color)
  223. else:
  224. draw.rectangle(bbox, width=width, outline=color)
  225. if label is not None:
  226. margin = width + 1
  227. draw.text((bbox[0] + margin, bbox[1] + margin), label, fill=color, font=txt_font)
  228. return torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1).to(dtype=torch.uint8)
  229. @torch.no_grad()
  230. def draw_segmentation_masks(
  231. image: torch.Tensor,
  232. masks: torch.Tensor,
  233. alpha: float = 0.8,
  234. colors: Optional[Union[List[Union[str, Tuple[int, int, int]]], str, Tuple[int, int, int]]] = None,
  235. ) -> torch.Tensor:
  236. """
  237. Draws segmentation masks on given RGB image.
  238. The values of the input image should be uint8 between 0 and 255.
  239. Args:
  240. image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
  241. masks (Tensor): Tensor of shape (num_masks, H, W) or (H, W) and dtype bool.
  242. alpha (float): Float number between 0 and 1 denoting the transparency of the masks.
  243. 0 means full transparency, 1 means no transparency.
  244. colors (color or list of colors, optional): List containing the colors
  245. of the masks or single color for all masks. The color can be represented as
  246. PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
  247. By default, random colors are generated for each mask.
  248. Returns:
  249. img (Tensor[C, H, W]): Image Tensor, with segmentation masks drawn on top.
  250. """
  251. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  252. _log_api_usage_once(draw_segmentation_masks)
  253. if not isinstance(image, torch.Tensor):
  254. raise TypeError(f"The image must be a tensor, got {type(image)}")
  255. elif image.dtype != torch.uint8:
  256. raise ValueError(f"The image dtype must be uint8, got {image.dtype}")
  257. elif image.dim() != 3:
  258. raise ValueError("Pass individual images, not batches")
  259. elif image.size()[0] != 3:
  260. raise ValueError("Pass an RGB image. Other Image formats are not supported")
  261. if masks.ndim == 2:
  262. masks = masks[None, :, :]
  263. if masks.ndim != 3:
  264. raise ValueError("masks must be of shape (H, W) or (batch_size, H, W)")
  265. if masks.dtype != torch.bool:
  266. raise ValueError(f"The masks must be of dtype bool. Got {masks.dtype}")
  267. if masks.shape[-2:] != image.shape[-2:]:
  268. raise ValueError("The image and the masks must have the same height and width")
  269. num_masks = masks.size()[0]
  270. if colors is not None and num_masks > len(colors):
  271. raise ValueError(f"There are more masks ({num_masks}) than colors ({len(colors)})")
  272. if num_masks == 0:
  273. warnings.warn("masks doesn't contain any mask. No mask was drawn")
  274. return image
  275. if colors is None:
  276. colors = _generate_color_palette(num_masks)
  277. if not isinstance(colors, list):
  278. colors = [colors]
  279. if not isinstance(colors[0], (tuple, str)):
  280. raise ValueError("colors must be a tuple or a string, or a list thereof")
  281. if isinstance(colors[0], tuple) and len(colors[0]) != 3:
  282. raise ValueError("It seems that you passed a tuple of colors instead of a list of colors")
  283. out_dtype = torch.uint8
  284. colors_ = []
  285. for color in colors:
  286. if isinstance(color, str):
  287. color = ImageColor.getrgb(color)
  288. colors_.append(torch.tensor(color, dtype=out_dtype))
  289. img_to_draw = image.detach().clone()
  290. # TODO: There might be a way to vectorize this
  291. for mask, color in zip(masks, colors_):
  292. img_to_draw[:, mask] = color[:, None]
  293. out = image * (1 - alpha) + img_to_draw * alpha
  294. return out.to(out_dtype)
  295. @torch.no_grad()
  296. def draw_keypoints(
  297. image: torch.Tensor,
  298. keypoints: torch.Tensor,
  299. connectivity: Optional[List[Tuple[int, int]]] = None,
  300. colors: Optional[Union[str, Tuple[int, int, int]]] = None,
  301. radius: int = 2,
  302. width: int = 3,
  303. ) -> torch.Tensor:
  304. """
  305. Draws Keypoints on given RGB image.
  306. The values of the input image should be uint8 between 0 and 255.
  307. Args:
  308. image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
  309. keypoints (Tensor): Tensor of shape (num_instances, K, 2) the K keypoints location for each of the N instances,
  310. in the format [x, y].
  311. connectivity (List[Tuple[int, int]]]): A List of tuple where,
  312. each tuple contains pair of keypoints to be connected.
  313. colors (str, Tuple): The color can be represented as
  314. PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
  315. radius (int): Integer denoting radius of keypoint.
  316. width (int): Integer denoting width of line connecting keypoints.
  317. Returns:
  318. img (Tensor[C, H, W]): Image Tensor of dtype uint8 with keypoints drawn.
  319. """
  320. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  321. _log_api_usage_once(draw_keypoints)
  322. if not isinstance(image, torch.Tensor):
  323. raise TypeError(f"The image must be a tensor, got {type(image)}")
  324. elif image.dtype != torch.uint8:
  325. raise ValueError(f"The image dtype must be uint8, got {image.dtype}")
  326. elif image.dim() != 3:
  327. raise ValueError("Pass individual images, not batches")
  328. elif image.size()[0] != 3:
  329. raise ValueError("Pass an RGB image. Other Image formats are not supported")
  330. if keypoints.ndim != 3:
  331. raise ValueError("keypoints must be of shape (num_instances, K, 2)")
  332. ndarr = image.permute(1, 2, 0).cpu().numpy()
  333. img_to_draw = Image.fromarray(ndarr)
  334. draw = ImageDraw.Draw(img_to_draw)
  335. img_kpts = keypoints.to(torch.int64).tolist()
  336. for kpt_id, kpt_inst in enumerate(img_kpts):
  337. for inst_id, kpt in enumerate(kpt_inst):
  338. x1 = kpt[0] - radius
  339. x2 = kpt[0] + radius
  340. y1 = kpt[1] - radius
  341. y2 = kpt[1] + radius
  342. draw.ellipse([x1, y1, x2, y2], fill=colors, outline=None, width=0)
  343. if connectivity:
  344. for connection in connectivity:
  345. start_pt_x = kpt_inst[connection[0]][0]
  346. start_pt_y = kpt_inst[connection[0]][1]
  347. end_pt_x = kpt_inst[connection[1]][0]
  348. end_pt_y = kpt_inst[connection[1]][1]
  349. draw.line(
  350. ((start_pt_x, start_pt_y), (end_pt_x, end_pt_y)),
  351. width=width,
  352. )
  353. return torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1).to(dtype=torch.uint8)
  354. # Flow visualization code adapted from https://github.com/tomrunia/OpticalFlow_Visualization
  355. @torch.no_grad()
  356. def flow_to_image(flow: torch.Tensor) -> torch.Tensor:
  357. """
  358. Converts a flow to an RGB image.
  359. Args:
  360. flow (Tensor): Flow of shape (N, 2, H, W) or (2, H, W) and dtype torch.float.
  361. Returns:
  362. img (Tensor): Image Tensor of dtype uint8 where each color corresponds
  363. to a given flow direction. Shape is (N, 3, H, W) or (3, H, W) depending on the input.
  364. """
  365. if flow.dtype != torch.float:
  366. raise ValueError(f"Flow should be of dtype torch.float, got {flow.dtype}.")
  367. orig_shape = flow.shape
  368. if flow.ndim == 3:
  369. flow = flow[None] # Add batch dim
  370. if flow.ndim != 4 or flow.shape[1] != 2:
  371. raise ValueError(f"Input flow should have shape (2, H, W) or (N, 2, H, W), got {orig_shape}.")
  372. max_norm = torch.sum(flow ** 2, dim=1).sqrt().max()
  373. epsilon = torch.finfo((flow).dtype).eps
  374. normalized_flow = flow / (max_norm + epsilon)
  375. img = _normalized_flow_to_image(normalized_flow)
  376. if len(orig_shape) == 3:
  377. img = img[0] # Remove batch dim
  378. return img
  379. @torch.no_grad()
  380. def _normalized_flow_to_image(normalized_flow: torch.Tensor) -> torch.Tensor:
  381. """
  382. Converts a batch of normalized flow to an RGB image.
  383. Args:
  384. normalized_flow (torch.Tensor): Normalized flow tensor of shape (N, 2, H, W)
  385. Returns:
  386. img (Tensor(N, 3, H, W)): Flow visualization image of dtype uint8.
  387. """
  388. N, _, H, W = normalized_flow.shape
  389. device = normalized_flow.device
  390. flow_image = torch.zeros((N, 3, H, W), dtype=torch.uint8, device=device)
  391. colorwheel = _make_colorwheel().to(device) # shape [55x3]
  392. num_cols = colorwheel.shape[0]
  393. norm = torch.sum(normalized_flow ** 2, dim=1).sqrt()
  394. a = torch.atan2(-normalized_flow[:, 1, :, :], -normalized_flow[:, 0, :, :]) / torch.pi
  395. fk = (a + 1) / 2 * (num_cols - 1)
  396. k0 = torch.floor(fk).to(torch.long)
  397. k1 = k0 + 1
  398. k1[k1 == num_cols] = 0
  399. f = fk - k0
  400. for c in range(colorwheel.shape[1]):
  401. tmp = colorwheel[:, c]
  402. col0 = tmp[k0] / 255.0
  403. col1 = tmp[k1] / 255.0
  404. col = (1 - f) * col0 + f * col1
  405. col = 1 - norm * (1 - col)
  406. flow_image[:, c, :, :] = torch.floor(255 * col)
  407. return flow_image
  408. def _make_colorwheel() -> torch.Tensor:
  409. """
  410. Generates a color wheel for optical flow visualization as presented in:
  411. Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007)
  412. URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf.
  413. Returns:
  414. colorwheel (Tensor[55, 3]): Colorwheel Tensor.
  415. """
  416. RY = 15
  417. YG = 6
  418. GC = 4
  419. CB = 11
  420. BM = 13
  421. MR = 6
  422. ncols = RY + YG + GC + CB + BM + MR
  423. colorwheel = torch.zeros((ncols, 3))
  424. col = 0
  425. # RY
  426. colorwheel[0:RY, 0] = 255
  427. colorwheel[0:RY, 1] = torch.floor(255 * torch.arange(0, RY) / RY)
  428. col = col + RY
  429. # YG
  430. colorwheel[col : col + YG, 0] = 255 - torch.floor(255 * torch.arange(0, YG) / YG)
  431. colorwheel[col : col + YG, 1] = 255
  432. col = col + YG
  433. # GC
  434. colorwheel[col : col + GC, 1] = 255
  435. colorwheel[col : col + GC, 2] = torch.floor(255 * torch.arange(0, GC) / GC)
  436. col = col + GC
  437. # CB
  438. colorwheel[col : col + CB, 1] = 255 - torch.floor(255 * torch.arange(CB) / CB)
  439. colorwheel[col : col + CB, 2] = 255
  440. col = col + CB
  441. # BM
  442. colorwheel[col : col + BM, 2] = 255
  443. colorwheel[col : col + BM, 0] = torch.floor(255 * torch.arange(0, BM) / BM)
  444. col = col + BM
  445. # MR
  446. colorwheel[col : col + MR, 2] = 255 - torch.floor(255 * torch.arange(MR) / MR)
  447. colorwheel[col : col + MR, 0] = 255
  448. return colorwheel
  449. def _generate_color_palette(num_objects: int):
  450. palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])
  451. return [tuple((i * palette) % 255) for i in range(num_objects)]
  452. def _log_api_usage_once(obj: Any) -> None:
  453. """
  454. Logs API usage(module and name) within an organization.
  455. In a large ecosystem, it's often useful to track the PyTorch and
  456. TorchVision APIs usage. This API provides the similar functionality to the
  457. logging module in the Python stdlib. It can be used for debugging purpose
  458. to log which methods are used and by default it is inactive, unless the user
  459. manually subscribes a logger via the `SetAPIUsageLogger method <https://github.com/pytorch/pytorch/blob/eb3b9fe719b21fae13c7a7cf3253f970290a573e/c10/util/Logging.cpp#L114>`_.
  460. Please note it is triggered only once for the same API call within a process.
  461. It does not collect any data from open-source users since it is no-op by default.
  462. For more information, please refer to
  463. * PyTorch note: https://pytorch.org/docs/stable/notes/large_scale_deployments.html#api-usage-logging;
  464. * Logging policy: https://github.com/pytorch/vision/issues/5052;
  465. Args:
  466. obj (class instance or method): an object to extract info from.
  467. """
  468. if not obj.__module__.startswith("torchvision"):
  469. return
  470. name = obj.__class__.__name__
  471. if isinstance(obj, FunctionType):
  472. name = obj.__name__
  473. torch._C._log_api_usage_once(f"{obj.__module__}.{name}")