functional.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  1. import math
  2. import numbers
  3. import sys
  4. import warnings
  5. from enum import Enum
  6. from typing import Any, List, Optional, Tuple, Union
  7. import numpy as np
  8. import torch
  9. from PIL import Image
  10. from torch import Tensor
  11. try:
  12. import accimage
  13. except ImportError:
  14. accimage = None
  15. from ..utils import _log_api_usage_once
  16. from . import _functional_pil as F_pil, _functional_tensor as F_t
  17. class InterpolationMode(Enum):
  18. """Interpolation modes
  19. Available interpolation methods are ``nearest``, ``nearest-exact``, ``bilinear``, ``bicubic``, ``box``, ``hamming``,
  20. and ``lanczos``.
  21. """
  22. NEAREST = "nearest"
  23. NEAREST_EXACT = "nearest-exact"
  24. BILINEAR = "bilinear"
  25. BICUBIC = "bicubic"
  26. # For PIL compatibility
  27. BOX = "box"
  28. HAMMING = "hamming"
  29. LANCZOS = "lanczos"
  30. # TODO: Once torchscript supports Enums with staticmethod
  31. # this can be put into InterpolationMode as staticmethod
  32. def _interpolation_modes_from_int(i: int) -> InterpolationMode:
  33. inverse_modes_mapping = {
  34. 0: InterpolationMode.NEAREST,
  35. 2: InterpolationMode.BILINEAR,
  36. 3: InterpolationMode.BICUBIC,
  37. 4: InterpolationMode.BOX,
  38. 5: InterpolationMode.HAMMING,
  39. 1: InterpolationMode.LANCZOS,
  40. }
  41. return inverse_modes_mapping[i]
  42. pil_modes_mapping = {
  43. InterpolationMode.NEAREST: 0,
  44. InterpolationMode.BILINEAR: 2,
  45. InterpolationMode.BICUBIC: 3,
  46. InterpolationMode.NEAREST_EXACT: 0,
  47. InterpolationMode.BOX: 4,
  48. InterpolationMode.HAMMING: 5,
  49. InterpolationMode.LANCZOS: 1,
  50. }
  51. _is_pil_image = F_pil._is_pil_image
  52. def get_dimensions(img: Tensor) -> List[int]:
  53. """Returns the dimensions of an image as [channels, height, width].
  54. Args:
  55. img (PIL Image or Tensor): The image to be checked.
  56. Returns:
  57. List[int]: The image dimensions.
  58. """
  59. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  60. _log_api_usage_once(get_dimensions)
  61. if isinstance(img, torch.Tensor):
  62. return F_t.get_dimensions(img)
  63. return F_pil.get_dimensions(img)
  64. def get_image_size(img: Tensor) -> List[int]:
  65. """Returns the size of an image as [width, height].
  66. Args:
  67. img (PIL Image or Tensor): The image to be checked.
  68. Returns:
  69. List[int]: The image size.
  70. """
  71. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  72. _log_api_usage_once(get_image_size)
  73. if isinstance(img, torch.Tensor):
  74. return F_t.get_image_size(img)
  75. return F_pil.get_image_size(img)
  76. def get_image_num_channels(img: Tensor) -> int:
  77. """Returns the number of channels of an image.
  78. Args:
  79. img (PIL Image or Tensor): The image to be checked.
  80. Returns:
  81. int: The number of channels.
  82. """
  83. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  84. _log_api_usage_once(get_image_num_channels)
  85. if isinstance(img, torch.Tensor):
  86. return F_t.get_image_num_channels(img)
  87. return F_pil.get_image_num_channels(img)
  88. @torch.jit.unused
  89. def _is_numpy(img: Any) -> bool:
  90. return isinstance(img, np.ndarray)
  91. @torch.jit.unused
  92. def _is_numpy_image(img: Any) -> bool:
  93. return img.ndim in {2, 3}
  94. def to_tensor(pic) -> Tensor:
  95. """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
  96. This function does not support torchscript.
  97. See :class:`~torchvision.transforms.ToTensor` for more details.
  98. Args:
  99. pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
  100. Returns:
  101. Tensor: Converted image.
  102. """
  103. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  104. _log_api_usage_once(to_tensor)
  105. if not (F_pil._is_pil_image(pic) or _is_numpy(pic)):
  106. raise TypeError(f"pic should be PIL Image or ndarray. Got {type(pic)}")
  107. if _is_numpy(pic) and not _is_numpy_image(pic):
  108. raise ValueError(f"pic should be 2/3 dimensional. Got {pic.ndim} dimensions.")
  109. default_float_dtype = torch.get_default_dtype()
  110. if isinstance(pic, np.ndarray):
  111. # handle numpy array
  112. if pic.ndim == 2:
  113. pic = pic[:, :, None]
  114. img = torch.from_numpy(pic.transpose((2, 0, 1))).contiguous()
  115. # backward compatibility
  116. if isinstance(img, torch.ByteTensor):
  117. return img.to(dtype=default_float_dtype).div(255)
  118. else:
  119. return img
  120. if accimage is not None and isinstance(pic, accimage.Image):
  121. nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32)
  122. pic.copyto(nppic)
  123. return torch.from_numpy(nppic).to(dtype=default_float_dtype)
  124. # handle PIL Image
  125. mode_to_nptype = {"I": np.int32, "I;16" if sys.byteorder == "little" else "I;16B": np.int16, "F": np.float32}
  126. img = torch.from_numpy(np.array(pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True))
  127. if pic.mode == "1":
  128. img = 255 * img
  129. img = img.view(pic.size[1], pic.size[0], F_pil.get_image_num_channels(pic))
  130. # put it from HWC to CHW format
  131. img = img.permute((2, 0, 1)).contiguous()
  132. if isinstance(img, torch.ByteTensor):
  133. return img.to(dtype=default_float_dtype).div(255)
  134. else:
  135. return img
  136. def pil_to_tensor(pic: Any) -> Tensor:
  137. """Convert a ``PIL Image`` to a tensor of the same type.
  138. This function does not support torchscript.
  139. See :class:`~torchvision.transforms.PILToTensor` for more details.
  140. .. note::
  141. A deep copy of the underlying array is performed.
  142. Args:
  143. pic (PIL Image): Image to be converted to tensor.
  144. Returns:
  145. Tensor: Converted image.
  146. """
  147. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  148. _log_api_usage_once(pil_to_tensor)
  149. if not F_pil._is_pil_image(pic):
  150. raise TypeError(f"pic should be PIL Image. Got {type(pic)}")
  151. if accimage is not None and isinstance(pic, accimage.Image):
  152. # accimage format is always uint8 internally, so always return uint8 here
  153. nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.uint8)
  154. pic.copyto(nppic)
  155. return torch.as_tensor(nppic)
  156. # handle PIL Image
  157. img = torch.as_tensor(np.array(pic, copy=True))
  158. img = img.view(pic.size[1], pic.size[0], F_pil.get_image_num_channels(pic))
  159. # put it from HWC to CHW format
  160. img = img.permute((2, 0, 1))
  161. return img
  162. def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float) -> torch.Tensor:
  163. """Convert a tensor image to the given ``dtype`` and scale the values accordingly
  164. This function does not support PIL Image.
  165. Args:
  166. image (torch.Tensor): Image to be converted
  167. dtype (torch.dtype): Desired data type of the output
  168. Returns:
  169. Tensor: Converted image
  170. .. note::
  171. When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly.
  172. If converted back and forth, this mismatch has no effect.
  173. Raises:
  174. RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as
  175. well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to
  176. overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range
  177. of the integer ``dtype``.
  178. """
  179. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  180. _log_api_usage_once(convert_image_dtype)
  181. if not isinstance(image, torch.Tensor):
  182. raise TypeError("Input img should be Tensor Image")
  183. return F_t.convert_image_dtype(image, dtype)
  184. def to_pil_image(pic, mode=None):
  185. """Convert a tensor or an ndarray to PIL Image. This function does not support torchscript.
  186. See :class:`~torchvision.transforms.ToPILImage` for more details.
  187. Args:
  188. pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
  189. mode (`PIL.Image mode`_): color space and pixel depth of input data (optional).
  190. .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes
  191. Returns:
  192. PIL Image: Image converted to PIL Image.
  193. """
  194. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  195. _log_api_usage_once(to_pil_image)
  196. if isinstance(pic, torch.Tensor):
  197. if pic.ndim == 3:
  198. pic = pic.permute((1, 2, 0))
  199. pic = pic.numpy(force=True)
  200. elif not isinstance(pic, np.ndarray):
  201. raise TypeError(f"pic should be Tensor or ndarray. Got {type(pic)}.")
  202. if pic.ndim == 2:
  203. # if 2D image, add channel dimension (HWC)
  204. pic = np.expand_dims(pic, 2)
  205. if pic.ndim != 3:
  206. raise ValueError(f"pic should be 2/3 dimensional. Got {pic.ndim} dimensions.")
  207. if pic.shape[-1] > 4:
  208. raise ValueError(f"pic should not have > 4 channels. Got {pic.shape[-1]} channels.")
  209. npimg = pic
  210. if np.issubdtype(npimg.dtype, np.floating) and mode != "F":
  211. npimg = (npimg * 255).astype(np.uint8)
  212. if npimg.shape[2] == 1:
  213. expected_mode = None
  214. npimg = npimg[:, :, 0]
  215. if npimg.dtype == np.uint8:
  216. expected_mode = "L"
  217. elif npimg.dtype == np.int16:
  218. expected_mode = "I;16" if sys.byteorder == "little" else "I;16B"
  219. elif npimg.dtype == np.int32:
  220. expected_mode = "I"
  221. elif npimg.dtype == np.float32:
  222. expected_mode = "F"
  223. if mode is not None and mode != expected_mode:
  224. raise ValueError(f"Incorrect mode ({mode}) supplied for input type {np.dtype}. Should be {expected_mode}")
  225. mode = expected_mode
  226. elif npimg.shape[2] == 2:
  227. permitted_2_channel_modes = ["LA"]
  228. if mode is not None and mode not in permitted_2_channel_modes:
  229. raise ValueError(f"Only modes {permitted_2_channel_modes} are supported for 2D inputs")
  230. if mode is None and npimg.dtype == np.uint8:
  231. mode = "LA"
  232. elif npimg.shape[2] == 4:
  233. permitted_4_channel_modes = ["RGBA", "CMYK", "RGBX"]
  234. if mode is not None and mode not in permitted_4_channel_modes:
  235. raise ValueError(f"Only modes {permitted_4_channel_modes} are supported for 4D inputs")
  236. if mode is None and npimg.dtype == np.uint8:
  237. mode = "RGBA"
  238. else:
  239. permitted_3_channel_modes = ["RGB", "YCbCr", "HSV"]
  240. if mode is not None and mode not in permitted_3_channel_modes:
  241. raise ValueError(f"Only modes {permitted_3_channel_modes} are supported for 3D inputs")
  242. if mode is None and npimg.dtype == np.uint8:
  243. mode = "RGB"
  244. if mode is None:
  245. raise TypeError(f"Input type {npimg.dtype} is not supported")
  246. return Image.fromarray(npimg, mode=mode)
  247. def normalize(tensor: Tensor, mean: List[float], std: List[float], inplace: bool = False) -> Tensor:
  248. """Normalize a float tensor image with mean and standard deviation.
  249. This transform does not support PIL Image.
  250. .. note::
  251. This transform acts out of place by default, i.e., it does not mutates the input tensor.
  252. See :class:`~torchvision.transforms.Normalize` for more details.
  253. Args:
  254. tensor (Tensor): Float tensor image of size (C, H, W) or (B, C, H, W) to be normalized.
  255. mean (sequence): Sequence of means for each channel.
  256. std (sequence): Sequence of standard deviations for each channel.
  257. inplace(bool,optional): Bool to make this operation inplace.
  258. Returns:
  259. Tensor: Normalized Tensor image.
  260. """
  261. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  262. _log_api_usage_once(normalize)
  263. if not isinstance(tensor, torch.Tensor):
  264. raise TypeError(f"img should be Tensor Image. Got {type(tensor)}")
  265. return F_t.normalize(tensor, mean=mean, std=std, inplace=inplace)
  266. def _compute_resized_output_size(
  267. image_size: Tuple[int, int], size: List[int], max_size: Optional[int] = None
  268. ) -> List[int]:
  269. if len(size) == 1: # specified size only for the smallest edge
  270. h, w = image_size
  271. short, long = (w, h) if w <= h else (h, w)
  272. requested_new_short = size if isinstance(size, int) else size[0]
  273. new_short, new_long = requested_new_short, int(requested_new_short * long / short)
  274. if max_size is not None:
  275. if max_size <= requested_new_short:
  276. raise ValueError(
  277. f"max_size = {max_size} must be strictly greater than the requested "
  278. f"size for the smaller edge size = {size}"
  279. )
  280. if new_long > max_size:
  281. new_short, new_long = int(max_size * new_short / new_long), max_size
  282. new_w, new_h = (new_short, new_long) if w <= h else (new_long, new_short)
  283. else: # specified both h and w
  284. new_w, new_h = size[1], size[0]
  285. return [new_h, new_w]
  286. def resize(
  287. img: Tensor,
  288. size: List[int],
  289. interpolation: InterpolationMode = InterpolationMode.BILINEAR,
  290. max_size: Optional[int] = None,
  291. antialias: Optional[bool] = True,
  292. ) -> Tensor:
  293. r"""Resize the input image to the given size.
  294. If the image is torch Tensor, it is expected
  295. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
  296. Args:
  297. img (PIL Image or Tensor): Image to be resized.
  298. size (sequence or int): Desired output size. If size is a sequence like
  299. (h, w), the output size will be matched to this. If size is an int,
  300. the smaller edge of the image will be matched to this number maintaining
  301. the aspect ratio. i.e, if height > width, then image will be rescaled to
  302. :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`.
  303. .. note::
  304. In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
  305. interpolation (InterpolationMode): Desired interpolation enum defined by
  306. :class:`torchvision.transforms.InterpolationMode`.
  307. Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``,
  308. ``InterpolationMode.NEAREST_EXACT``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are
  309. supported.
  310. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  311. max_size (int, optional): The maximum allowed for the longer edge of
  312. the resized image. If the longer edge of the image is greater
  313. than ``max_size`` after being resized according to ``size``,
  314. ``size`` will be overruled so that the longer edge is equal to
  315. ``max_size``.
  316. As a result, the smaller edge may be shorter than ``size``. This
  317. is only supported if ``size`` is an int (or a sequence of length
  318. 1 in torchscript mode).
  319. antialias (bool, optional): Whether to apply antialiasing.
  320. It only affects **tensors** with bilinear or bicubic modes and it is
  321. ignored otherwise: on PIL images, antialiasing is always applied on
  322. bilinear or bicubic modes; on other modes (for PIL images and
  323. tensors), antialiasing makes no sense and this parameter is ignored.
  324. Possible values are:
  325. - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
  326. Other mode aren't affected. This is probably what you want to use.
  327. - ``False``: will not apply antialiasing for tensors on any mode. PIL
  328. images are still antialiased on bilinear or bicubic modes, because
  329. PIL doesn't support no antialias.
  330. - ``None``: equivalent to ``False`` for tensors and ``True`` for
  331. PIL images. This value exists for legacy reasons and you probably
  332. don't want to use it unless you really know what you are doing.
  333. The default value changed from ``None`` to ``True`` in
  334. v0.17, for the PIL and Tensor backends to be consistent.
  335. Returns:
  336. PIL Image or Tensor: Resized image.
  337. """
  338. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  339. _log_api_usage_once(resize)
  340. if isinstance(interpolation, int):
  341. interpolation = _interpolation_modes_from_int(interpolation)
  342. elif not isinstance(interpolation, InterpolationMode):
  343. raise TypeError(
  344. "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant"
  345. )
  346. if isinstance(size, (list, tuple)):
  347. if len(size) not in [1, 2]:
  348. raise ValueError(
  349. f"Size must be an int or a 1 or 2 element tuple/list, not a {len(size)} element tuple/list"
  350. )
  351. if max_size is not None and len(size) != 1:
  352. raise ValueError(
  353. "max_size should only be passed if size specifies the length of the smaller edge, "
  354. "i.e. size should be an int or a sequence of length 1 in torchscript mode."
  355. )
  356. _, image_height, image_width = get_dimensions(img)
  357. if isinstance(size, int):
  358. size = [size]
  359. output_size = _compute_resized_output_size((image_height, image_width), size, max_size)
  360. if [image_height, image_width] == output_size:
  361. return img
  362. if not isinstance(img, torch.Tensor):
  363. if antialias is False:
  364. warnings.warn("Anti-alias option is always applied for PIL Image input. Argument antialias is ignored.")
  365. pil_interpolation = pil_modes_mapping[interpolation]
  366. return F_pil.resize(img, size=output_size, interpolation=pil_interpolation)
  367. return F_t.resize(img, size=output_size, interpolation=interpolation.value, antialias=antialias)
  368. def pad(img: Tensor, padding: List[int], fill: Union[int, float] = 0, padding_mode: str = "constant") -> Tensor:
  369. r"""Pad the given image on all sides with the given "pad" value.
  370. If the image is torch Tensor, it is expected
  371. to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric,
  372. at most 3 leading dimensions for mode edge,
  373. and an arbitrary number of leading dimensions for mode constant
  374. Args:
  375. img (PIL Image or Tensor): Image to be padded.
  376. padding (int or sequence): Padding on each border. If a single int is provided this
  377. is used to pad all borders. If sequence of length 2 is provided this is the padding
  378. on left/right and top/bottom respectively. If a sequence of length 4 is provided
  379. this is the padding for the left, top, right and bottom borders respectively.
  380. .. note::
  381. In torchscript mode padding as single int is not supported, use a sequence of
  382. length 1: ``[padding, ]``.
  383. fill (number or tuple): Pixel fill value for constant fill. Default is 0.
  384. If a tuple of length 3, it is used to fill R, G, B channels respectively.
  385. This value is only used when the padding_mode is constant.
  386. Only number is supported for torch Tensor.
  387. Only int or tuple value is supported for PIL Image.
  388. padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
  389. Default is constant.
  390. - constant: pads with a constant value, this value is specified with fill
  391. - edge: pads with the last value at the edge of the image.
  392. If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2
  393. - reflect: pads with reflection of image without repeating the last value on the edge.
  394. For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
  395. will result in [3, 2, 1, 2, 3, 4, 3, 2]
  396. - symmetric: pads with reflection of image repeating the last value on the edge.
  397. For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
  398. will result in [2, 1, 1, 2, 3, 4, 4, 3]
  399. Returns:
  400. PIL Image or Tensor: Padded image.
  401. """
  402. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  403. _log_api_usage_once(pad)
  404. if not isinstance(img, torch.Tensor):
  405. return F_pil.pad(img, padding=padding, fill=fill, padding_mode=padding_mode)
  406. return F_t.pad(img, padding=padding, fill=fill, padding_mode=padding_mode)
  407. def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor:
  408. """Crop the given image at specified location and output size.
  409. If the image is torch Tensor, it is expected
  410. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
  411. If image size is smaller than output size along any edge, image is padded with 0 and then cropped.
  412. Args:
  413. img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image.
  414. top (int): Vertical component of the top left corner of the crop box.
  415. left (int): Horizontal component of the top left corner of the crop box.
  416. height (int): Height of the crop box.
  417. width (int): Width of the crop box.
  418. Returns:
  419. PIL Image or Tensor: Cropped image.
  420. """
  421. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  422. _log_api_usage_once(crop)
  423. if not isinstance(img, torch.Tensor):
  424. return F_pil.crop(img, top, left, height, width)
  425. return F_t.crop(img, top, left, height, width)
  426. def center_crop(img: Tensor, output_size: List[int]) -> Tensor:
  427. """Crops the given image at the center.
  428. If the image is torch Tensor, it is expected
  429. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
  430. If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.
  431. Args:
  432. img (PIL Image or Tensor): Image to be cropped.
  433. output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int,
  434. it is used for both directions.
  435. Returns:
  436. PIL Image or Tensor: Cropped image.
  437. """
  438. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  439. _log_api_usage_once(center_crop)
  440. if isinstance(output_size, numbers.Number):
  441. output_size = (int(output_size), int(output_size))
  442. elif isinstance(output_size, (tuple, list)) and len(output_size) == 1:
  443. output_size = (output_size[0], output_size[0])
  444. _, image_height, image_width = get_dimensions(img)
  445. crop_height, crop_width = output_size
  446. if crop_width > image_width or crop_height > image_height:
  447. padding_ltrb = [
  448. (crop_width - image_width) // 2 if crop_width > image_width else 0,
  449. (crop_height - image_height) // 2 if crop_height > image_height else 0,
  450. (crop_width - image_width + 1) // 2 if crop_width > image_width else 0,
  451. (crop_height - image_height + 1) // 2 if crop_height > image_height else 0,
  452. ]
  453. img = pad(img, padding_ltrb, fill=0) # PIL uses fill value 0
  454. _, image_height, image_width = get_dimensions(img)
  455. if crop_width == image_width and crop_height == image_height:
  456. return img
  457. crop_top = int(round((image_height - crop_height) / 2.0))
  458. crop_left = int(round((image_width - crop_width) / 2.0))
  459. return crop(img, crop_top, crop_left, crop_height, crop_width)
  460. def resized_crop(
  461. img: Tensor,
  462. top: int,
  463. left: int,
  464. height: int,
  465. width: int,
  466. size: List[int],
  467. interpolation: InterpolationMode = InterpolationMode.BILINEAR,
  468. antialias: Optional[bool] = True,
  469. ) -> Tensor:
  470. """Crop the given image and resize it to desired size.
  471. If the image is torch Tensor, it is expected
  472. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
  473. Notably used in :class:`~torchvision.transforms.RandomResizedCrop`.
  474. Args:
  475. img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image.
  476. top (int): Vertical component of the top left corner of the crop box.
  477. left (int): Horizontal component of the top left corner of the crop box.
  478. height (int): Height of the crop box.
  479. width (int): Width of the crop box.
  480. size (sequence or int): Desired output size. Same semantics as ``resize``.
  481. interpolation (InterpolationMode): Desired interpolation enum defined by
  482. :class:`torchvision.transforms.InterpolationMode`.
  483. Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``,
  484. ``InterpolationMode.NEAREST_EXACT``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are
  485. supported.
  486. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  487. antialias (bool, optional): Whether to apply antialiasing.
  488. It only affects **tensors** with bilinear or bicubic modes and it is
  489. ignored otherwise: on PIL images, antialiasing is always applied on
  490. bilinear or bicubic modes; on other modes (for PIL images and
  491. tensors), antialiasing makes no sense and this parameter is ignored.
  492. Possible values are:
  493. - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
  494. Other mode aren't affected. This is probably what you want to use.
  495. - ``False``: will not apply antialiasing for tensors on any mode. PIL
  496. images are still antialiased on bilinear or bicubic modes, because
  497. PIL doesn't support no antialias.
  498. - ``None``: equivalent to ``False`` for tensors and ``True`` for
  499. PIL images. This value exists for legacy reasons and you probably
  500. don't want to use it unless you really know what you are doing.
  501. The default value changed from ``None`` to ``True`` in
  502. v0.17, for the PIL and Tensor backends to be consistent.
  503. Returns:
  504. PIL Image or Tensor: Cropped image.
  505. """
  506. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  507. _log_api_usage_once(resized_crop)
  508. img = crop(img, top, left, height, width)
  509. img = resize(img, size, interpolation, antialias=antialias)
  510. return img
  511. def hflip(img: Tensor) -> Tensor:
  512. """Horizontally flip the given image.
  513. Args:
  514. img (PIL Image or Tensor): Image to be flipped. If img
  515. is a Tensor, it is expected to be in [..., H, W] format,
  516. where ... means it can have an arbitrary number of leading
  517. dimensions.
  518. Returns:
  519. PIL Image or Tensor: Horizontally flipped image.
  520. """
  521. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  522. _log_api_usage_once(hflip)
  523. if not isinstance(img, torch.Tensor):
  524. return F_pil.hflip(img)
  525. return F_t.hflip(img)
  526. def _get_perspective_coeffs(startpoints: List[List[int]], endpoints: List[List[int]]) -> List[float]:
  527. """Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms.
  528. In Perspective Transform each pixel (x, y) in the original image gets transformed as,
  529. (x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy + 1) )
  530. Args:
  531. startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
  532. ``[top-left, top-right, bottom-right, bottom-left]`` of the original image.
  533. endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
  534. ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image.
  535. Returns:
  536. octuple (a, b, c, d, e, f, g, h) for transforming each pixel.
  537. """
  538. a_matrix = torch.zeros(2 * len(startpoints), 8, dtype=torch.float)
  539. for i, (p1, p2) in enumerate(zip(endpoints, startpoints)):
  540. a_matrix[2 * i, :] = torch.tensor([p1[0], p1[1], 1, 0, 0, 0, -p2[0] * p1[0], -p2[0] * p1[1]])
  541. a_matrix[2 * i + 1, :] = torch.tensor([0, 0, 0, p1[0], p1[1], 1, -p2[1] * p1[0], -p2[1] * p1[1]])
  542. b_matrix = torch.tensor(startpoints, dtype=torch.float).view(8)
  543. res = torch.linalg.lstsq(a_matrix, b_matrix, driver="gels").solution
  544. output: List[float] = res.tolist()
  545. return output
  546. def perspective(
  547. img: Tensor,
  548. startpoints: List[List[int]],
  549. endpoints: List[List[int]],
  550. interpolation: InterpolationMode = InterpolationMode.BILINEAR,
  551. fill: Optional[List[float]] = None,
  552. ) -> Tensor:
  553. """Perform perspective transform of the given image.
  554. If the image is torch Tensor, it is expected
  555. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
  556. Args:
  557. img (PIL Image or Tensor): Image to be transformed.
  558. startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
  559. ``[top-left, top-right, bottom-right, bottom-left]`` of the original image.
  560. endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
  561. ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image.
  562. interpolation (InterpolationMode): Desired interpolation enum defined by
  563. :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
  564. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
  565. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  566. fill (sequence or number, optional): Pixel fill value for the area outside the transformed
  567. image. If given a number, the value is used for all bands respectively.
  568. .. note::
  569. In torchscript mode single int/float value is not supported, please use a sequence
  570. of length 1: ``[value, ]``.
  571. Returns:
  572. PIL Image or Tensor: transformed Image.
  573. """
  574. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  575. _log_api_usage_once(perspective)
  576. coeffs = _get_perspective_coeffs(startpoints, endpoints)
  577. if isinstance(interpolation, int):
  578. interpolation = _interpolation_modes_from_int(interpolation)
  579. elif not isinstance(interpolation, InterpolationMode):
  580. raise TypeError(
  581. "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant"
  582. )
  583. if not isinstance(img, torch.Tensor):
  584. pil_interpolation = pil_modes_mapping[interpolation]
  585. return F_pil.perspective(img, coeffs, interpolation=pil_interpolation, fill=fill)
  586. return F_t.perspective(img, coeffs, interpolation=interpolation.value, fill=fill)
  587. def vflip(img: Tensor) -> Tensor:
  588. """Vertically flip the given image.
  589. Args:
  590. img (PIL Image or Tensor): Image to be flipped. If img
  591. is a Tensor, it is expected to be in [..., H, W] format,
  592. where ... means it can have an arbitrary number of leading
  593. dimensions.
  594. Returns:
  595. PIL Image or Tensor: Vertically flipped image.
  596. """
  597. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  598. _log_api_usage_once(vflip)
  599. if not isinstance(img, torch.Tensor):
  600. return F_pil.vflip(img)
  601. return F_t.vflip(img)
  602. def five_crop(img: Tensor, size: List[int]) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
  603. """Crop the given image into four corners and the central crop.
  604. If the image is torch Tensor, it is expected
  605. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
  606. .. Note::
  607. This transform returns a tuple of images and there may be a
  608. mismatch in the number of inputs and targets your ``Dataset`` returns.
  609. Args:
  610. img (PIL Image or Tensor): Image to be cropped.
  611. size (sequence or int): Desired output size of the crop. If size is an
  612. int instead of sequence like (h, w), a square crop (size, size) is
  613. made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
  614. Returns:
  615. tuple: tuple (tl, tr, bl, br, center)
  616. Corresponding top left, top right, bottom left, bottom right and center crop.
  617. """
  618. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  619. _log_api_usage_once(five_crop)
  620. if isinstance(size, numbers.Number):
  621. size = (int(size), int(size))
  622. elif isinstance(size, (tuple, list)) and len(size) == 1:
  623. size = (size[0], size[0])
  624. if len(size) != 2:
  625. raise ValueError("Please provide only two dimensions (h, w) for size.")
  626. _, image_height, image_width = get_dimensions(img)
  627. crop_height, crop_width = size
  628. if crop_width > image_width or crop_height > image_height:
  629. msg = "Requested crop size {} is bigger than input size {}"
  630. raise ValueError(msg.format(size, (image_height, image_width)))
  631. tl = crop(img, 0, 0, crop_height, crop_width)
  632. tr = crop(img, 0, image_width - crop_width, crop_height, crop_width)
  633. bl = crop(img, image_height - crop_height, 0, crop_height, crop_width)
  634. br = crop(img, image_height - crop_height, image_width - crop_width, crop_height, crop_width)
  635. center = center_crop(img, [crop_height, crop_width])
  636. return tl, tr, bl, br, center
  637. def ten_crop(
  638. img: Tensor, size: List[int], vertical_flip: bool = False
  639. ) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
  640. """Generate ten cropped images from the given image.
  641. Crop the given image into four corners and the central crop plus the
  642. flipped version of these (horizontal flipping is used by default).
  643. If the image is torch Tensor, it is expected
  644. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
  645. .. Note::
  646. This transform returns a tuple of images and there may be a
  647. mismatch in the number of inputs and targets your ``Dataset`` returns.
  648. Args:
  649. img (PIL Image or Tensor): Image to be cropped.
  650. size (sequence or int): Desired output size of the crop. If size is an
  651. int instead of sequence like (h, w), a square crop (size, size) is
  652. made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
  653. vertical_flip (bool): Use vertical flipping instead of horizontal
  654. Returns:
  655. tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip)
  656. Corresponding top left, top right, bottom left, bottom right and
  657. center crop and same for the flipped image.
  658. """
  659. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  660. _log_api_usage_once(ten_crop)
  661. if isinstance(size, numbers.Number):
  662. size = (int(size), int(size))
  663. elif isinstance(size, (tuple, list)) and len(size) == 1:
  664. size = (size[0], size[0])
  665. if len(size) != 2:
  666. raise ValueError("Please provide only two dimensions (h, w) for size.")
  667. first_five = five_crop(img, size)
  668. if vertical_flip:
  669. img = vflip(img)
  670. else:
  671. img = hflip(img)
  672. second_five = five_crop(img, size)
  673. return first_five + second_five
  674. def adjust_brightness(img: Tensor, brightness_factor: float) -> Tensor:
  675. """Adjust brightness of an image.
  676. Args:
  677. img (PIL Image or Tensor): Image to be adjusted.
  678. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  679. where ... means it can have an arbitrary number of leading dimensions.
  680. brightness_factor (float): How much to adjust the brightness. Can be
  681. any non-negative number. 0 gives a black image, 1 gives the
  682. original image while 2 increases the brightness by a factor of 2.
  683. Returns:
  684. PIL Image or Tensor: Brightness adjusted image.
  685. """
  686. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  687. _log_api_usage_once(adjust_brightness)
  688. if not isinstance(img, torch.Tensor):
  689. return F_pil.adjust_brightness(img, brightness_factor)
  690. return F_t.adjust_brightness(img, brightness_factor)
  691. def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor:
  692. """Adjust contrast of an image.
  693. Args:
  694. img (PIL Image or Tensor): Image to be adjusted.
  695. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  696. where ... means it can have an arbitrary number of leading dimensions.
  697. contrast_factor (float): How much to adjust the contrast. Can be any
  698. non-negative number. 0 gives a solid gray image, 1 gives the
  699. original image while 2 increases the contrast by a factor of 2.
  700. Returns:
  701. PIL Image or Tensor: Contrast adjusted image.
  702. """
  703. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  704. _log_api_usage_once(adjust_contrast)
  705. if not isinstance(img, torch.Tensor):
  706. return F_pil.adjust_contrast(img, contrast_factor)
  707. return F_t.adjust_contrast(img, contrast_factor)
  708. def adjust_saturation(img: Tensor, saturation_factor: float) -> Tensor:
  709. """Adjust color saturation of an image.
  710. Args:
  711. img (PIL Image or Tensor): Image to be adjusted.
  712. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  713. where ... means it can have an arbitrary number of leading dimensions.
  714. saturation_factor (float): How much to adjust the saturation. 0 will
  715. give a black and white image, 1 will give the original image while
  716. 2 will enhance the saturation by a factor of 2.
  717. Returns:
  718. PIL Image or Tensor: Saturation adjusted image.
  719. """
  720. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  721. _log_api_usage_once(adjust_saturation)
  722. if not isinstance(img, torch.Tensor):
  723. return F_pil.adjust_saturation(img, saturation_factor)
  724. return F_t.adjust_saturation(img, saturation_factor)
  725. def adjust_hue(img: Tensor, hue_factor: float) -> Tensor:
  726. """Adjust hue of an image.
  727. The image hue is adjusted by converting the image to HSV and
  728. cyclically shifting the intensities in the hue channel (H).
  729. The image is then converted back to original image mode.
  730. `hue_factor` is the amount of shift in H channel and must be in the
  731. interval `[-0.5, 0.5]`.
  732. See `Hue`_ for more details.
  733. .. _Hue: https://en.wikipedia.org/wiki/Hue
  734. Args:
  735. img (PIL Image or Tensor): Image to be adjusted.
  736. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  737. where ... means it can have an arbitrary number of leading dimensions.
  738. If img is PIL Image mode "1", "I", "F" and modes with transparency (alpha channel) are not supported.
  739. Note: the pixel values of the input image has to be non-negative for conversion to HSV space;
  740. thus it does not work if you normalize your image to an interval with negative values,
  741. or use an interpolation that generates negative values before using this function.
  742. hue_factor (float): How much to shift the hue channel. Should be in
  743. [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in
  744. HSV space in positive and negative direction respectively.
  745. 0 means no shift. Therefore, both -0.5 and 0.5 will give an image
  746. with complementary colors while 0 gives the original image.
  747. Returns:
  748. PIL Image or Tensor: Hue adjusted image.
  749. """
  750. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  751. _log_api_usage_once(adjust_hue)
  752. if not isinstance(img, torch.Tensor):
  753. return F_pil.adjust_hue(img, hue_factor)
  754. return F_t.adjust_hue(img, hue_factor)
  755. def adjust_gamma(img: Tensor, gamma: float, gain: float = 1) -> Tensor:
  756. r"""Perform gamma correction on an image.
  757. Also known as Power Law Transform. Intensities in RGB mode are adjusted
  758. based on the following equation:
  759. .. math::
  760. I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma}
  761. See `Gamma Correction`_ for more details.
  762. .. _Gamma Correction: https://en.wikipedia.org/wiki/Gamma_correction
  763. Args:
  764. img (PIL Image or Tensor): PIL Image to be adjusted.
  765. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  766. where ... means it can have an arbitrary number of leading dimensions.
  767. If img is PIL Image, modes with transparency (alpha channel) are not supported.
  768. gamma (float): Non negative real number, same as :math:`\gamma` in the equation.
  769. gamma larger than 1 make the shadows darker,
  770. while gamma smaller than 1 make dark regions lighter.
  771. gain (float): The constant multiplier.
  772. Returns:
  773. PIL Image or Tensor: Gamma correction adjusted image.
  774. """
  775. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  776. _log_api_usage_once(adjust_gamma)
  777. if not isinstance(img, torch.Tensor):
  778. return F_pil.adjust_gamma(img, gamma, gain)
  779. return F_t.adjust_gamma(img, gamma, gain)
  780. def _get_inverse_affine_matrix(
  781. center: List[float], angle: float, translate: List[float], scale: float, shear: List[float], inverted: bool = True
  782. ) -> List[float]:
  783. # Helper method to compute inverse matrix for affine transformation
  784. # Pillow requires inverse affine transformation matrix:
  785. # Affine matrix is : M = T * C * RotateScaleShear * C^-1
  786. #
  787. # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1]
  788. # C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1]
  789. # RotateScaleShear is rotation with scale and shear matrix
  790. #
  791. # RotateScaleShear(a, s, (sx, sy)) =
  792. # = R(a) * S(s) * SHy(sy) * SHx(sx)
  793. # = [ s*cos(a - sy)/cos(sy), s*(-cos(a - sy)*tan(sx)/cos(sy) - sin(a)), 0 ]
  794. # [ s*sin(a - sy)/cos(sy), s*(-sin(a - sy)*tan(sx)/cos(sy) + cos(a)), 0 ]
  795. # [ 0 , 0 , 1 ]
  796. # where R is a rotation matrix, S is a scaling matrix, and SHx and SHy are the shears:
  797. # SHx(s) = [1, -tan(s)] and SHy(s) = [1 , 0]
  798. # [0, 1 ] [-tan(s), 1]
  799. #
  800. # Thus, the inverse is M^-1 = C * RotateScaleShear^-1 * C^-1 * T^-1
  801. rot = math.radians(angle)
  802. sx = math.radians(shear[0])
  803. sy = math.radians(shear[1])
  804. cx, cy = center
  805. tx, ty = translate
  806. # RSS without scaling
  807. a = math.cos(rot - sy) / math.cos(sy)
  808. b = -math.cos(rot - sy) * math.tan(sx) / math.cos(sy) - math.sin(rot)
  809. c = math.sin(rot - sy) / math.cos(sy)
  810. d = -math.sin(rot - sy) * math.tan(sx) / math.cos(sy) + math.cos(rot)
  811. if inverted:
  812. # Inverted rotation matrix with scale and shear
  813. # det([[a, b], [c, d]]) == 1, since det(rotation) = 1 and det(shear) = 1
  814. matrix = [d, -b, 0.0, -c, a, 0.0]
  815. matrix = [x / scale for x in matrix]
  816. # Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1
  817. matrix[2] += matrix[0] * (-cx - tx) + matrix[1] * (-cy - ty)
  818. matrix[5] += matrix[3] * (-cx - tx) + matrix[4] * (-cy - ty)
  819. # Apply center translation: C * RSS^-1 * C^-1 * T^-1
  820. matrix[2] += cx
  821. matrix[5] += cy
  822. else:
  823. matrix = [a, b, 0.0, c, d, 0.0]
  824. matrix = [x * scale for x in matrix]
  825. # Apply inverse of center translation: RSS * C^-1
  826. matrix[2] += matrix[0] * (-cx) + matrix[1] * (-cy)
  827. matrix[5] += matrix[3] * (-cx) + matrix[4] * (-cy)
  828. # Apply translation and center : T * C * RSS * C^-1
  829. matrix[2] += cx + tx
  830. matrix[5] += cy + ty
  831. return matrix
  832. def rotate(
  833. img: Tensor,
  834. angle: float,
  835. interpolation: InterpolationMode = InterpolationMode.NEAREST,
  836. expand: bool = False,
  837. center: Optional[List[int]] = None,
  838. fill: Optional[List[float]] = None,
  839. ) -> Tensor:
  840. """Rotate the image by angle.
  841. If the image is torch Tensor, it is expected
  842. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
  843. Args:
  844. img (PIL Image or Tensor): image to be rotated.
  845. angle (number): rotation angle value in degrees, counter-clockwise.
  846. interpolation (InterpolationMode): Desired interpolation enum defined by
  847. :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
  848. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
  849. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  850. expand (bool, optional): Optional expansion flag.
  851. If true, expands the output image to make it large enough to hold the entire rotated image.
  852. If false or omitted, make the output image the same size as the input image.
  853. Note that the expand flag assumes rotation around the center and no translation.
  854. center (sequence, optional): Optional center of rotation. Origin is the upper left corner.
  855. Default is the center of the image.
  856. fill (sequence or number, optional): Pixel fill value for the area outside the transformed
  857. image. If given a number, the value is used for all bands respectively.
  858. .. note::
  859. In torchscript mode single int/float value is not supported, please use a sequence
  860. of length 1: ``[value, ]``.
  861. Returns:
  862. PIL Image or Tensor: Rotated image.
  863. .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
  864. """
  865. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  866. _log_api_usage_once(rotate)
  867. if isinstance(interpolation, int):
  868. interpolation = _interpolation_modes_from_int(interpolation)
  869. elif not isinstance(interpolation, InterpolationMode):
  870. raise TypeError(
  871. "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant"
  872. )
  873. if not isinstance(angle, (int, float)):
  874. raise TypeError("Argument angle should be int or float")
  875. if center is not None and not isinstance(center, (list, tuple)):
  876. raise TypeError("Argument center should be a sequence")
  877. if not isinstance(img, torch.Tensor):
  878. pil_interpolation = pil_modes_mapping[interpolation]
  879. return F_pil.rotate(img, angle=angle, interpolation=pil_interpolation, expand=expand, center=center, fill=fill)
  880. center_f = [0.0, 0.0]
  881. if center is not None:
  882. _, height, width = get_dimensions(img)
  883. # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center.
  884. center_f = [1.0 * (c - s * 0.5) for c, s in zip(center, [width, height])]
  885. # due to current incoherence of rotation angle direction between affine and rotate implementations
  886. # we need to set -angle.
  887. matrix = _get_inverse_affine_matrix(center_f, -angle, [0.0, 0.0], 1.0, [0.0, 0.0])
  888. return F_t.rotate(img, matrix=matrix, interpolation=interpolation.value, expand=expand, fill=fill)
  889. def affine(
  890. img: Tensor,
  891. angle: float,
  892. translate: List[int],
  893. scale: float,
  894. shear: List[float],
  895. interpolation: InterpolationMode = InterpolationMode.NEAREST,
  896. fill: Optional[List[float]] = None,
  897. center: Optional[List[int]] = None,
  898. ) -> Tensor:
  899. """Apply affine transformation on the image keeping image center invariant.
  900. If the image is torch Tensor, it is expected
  901. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
  902. Args:
  903. img (PIL Image or Tensor): image to transform.
  904. angle (number): rotation angle in degrees between -180 and 180, clockwise direction.
  905. translate (sequence of integers): horizontal and vertical translations (post-rotation translation)
  906. scale (float): overall scale
  907. shear (float or sequence): shear angle value in degrees between -180 to 180, clockwise direction.
  908. If a sequence is specified, the first value corresponds to a shear parallel to the x-axis, while
  909. the second value corresponds to a shear parallel to the y-axis.
  910. interpolation (InterpolationMode): Desired interpolation enum defined by
  911. :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
  912. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
  913. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  914. fill (sequence or number, optional): Pixel fill value for the area outside the transformed
  915. image. If given a number, the value is used for all bands respectively.
  916. .. note::
  917. In torchscript mode single int/float value is not supported, please use a sequence
  918. of length 1: ``[value, ]``.
  919. center (sequence, optional): Optional center of rotation. Origin is the upper left corner.
  920. Default is the center of the image.
  921. Returns:
  922. PIL Image or Tensor: Transformed image.
  923. """
  924. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  925. _log_api_usage_once(affine)
  926. if isinstance(interpolation, int):
  927. interpolation = _interpolation_modes_from_int(interpolation)
  928. elif not isinstance(interpolation, InterpolationMode):
  929. raise TypeError(
  930. "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant"
  931. )
  932. if not isinstance(angle, (int, float)):
  933. raise TypeError("Argument angle should be int or float")
  934. if not isinstance(translate, (list, tuple)):
  935. raise TypeError("Argument translate should be a sequence")
  936. if len(translate) != 2:
  937. raise ValueError("Argument translate should be a sequence of length 2")
  938. if scale <= 0.0:
  939. raise ValueError("Argument scale should be positive")
  940. if not isinstance(shear, (numbers.Number, (list, tuple))):
  941. raise TypeError("Shear should be either a single value or a sequence of two values")
  942. if isinstance(angle, int):
  943. angle = float(angle)
  944. if isinstance(translate, tuple):
  945. translate = list(translate)
  946. if isinstance(shear, numbers.Number):
  947. shear = [shear, 0.0]
  948. if isinstance(shear, tuple):
  949. shear = list(shear)
  950. if len(shear) == 1:
  951. shear = [shear[0], shear[0]]
  952. if len(shear) != 2:
  953. raise ValueError(f"Shear should be a sequence containing two values. Got {shear}")
  954. if center is not None and not isinstance(center, (list, tuple)):
  955. raise TypeError("Argument center should be a sequence")
  956. _, height, width = get_dimensions(img)
  957. if not isinstance(img, torch.Tensor):
  958. # center = (width * 0.5 + 0.5, height * 0.5 + 0.5)
  959. # it is visually better to estimate the center without 0.5 offset
  960. # otherwise image rotated by 90 degrees is shifted vs output image of torch.rot90 or F_t.affine
  961. if center is None:
  962. center = [width * 0.5, height * 0.5]
  963. matrix = _get_inverse_affine_matrix(center, angle, translate, scale, shear)
  964. pil_interpolation = pil_modes_mapping[interpolation]
  965. return F_pil.affine(img, matrix=matrix, interpolation=pil_interpolation, fill=fill)
  966. center_f = [0.0, 0.0]
  967. if center is not None:
  968. _, height, width = get_dimensions(img)
  969. # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center.
  970. center_f = [1.0 * (c - s * 0.5) for c, s in zip(center, [width, height])]
  971. translate_f = [1.0 * t for t in translate]
  972. matrix = _get_inverse_affine_matrix(center_f, angle, translate_f, scale, shear)
  973. return F_t.affine(img, matrix=matrix, interpolation=interpolation.value, fill=fill)
  974. # Looks like to_grayscale() is a stand-alone functional that is never called
  975. # from the transform classes. Perhaps it's still here for BC? I can't be
  976. # bothered to dig.
  977. @torch.jit.unused
  978. def to_grayscale(img, num_output_channels=1):
  979. """Convert PIL image of any mode (RGB, HSV, LAB, etc) to grayscale version of image.
  980. This transform does not support torch Tensor.
  981. Args:
  982. img (PIL Image): PIL Image to be converted to grayscale.
  983. num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default is 1.
  984. Returns:
  985. PIL Image: Grayscale version of the image.
  986. - if num_output_channels = 1 : returned image is single channel
  987. - if num_output_channels = 3 : returned image is 3 channel with r = g = b
  988. """
  989. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  990. _log_api_usage_once(to_grayscale)
  991. if isinstance(img, Image.Image):
  992. return F_pil.to_grayscale(img, num_output_channels)
  993. raise TypeError("Input should be PIL Image")
  994. def rgb_to_grayscale(img: Tensor, num_output_channels: int = 1) -> Tensor:
  995. """Convert RGB image to grayscale version of image.
  996. If the image is torch Tensor, it is expected
  997. to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions
  998. Note:
  999. Please, note that this method supports only RGB images as input. For inputs in other color spaces,
  1000. please, consider using :meth:`~torchvision.transforms.functional.to_grayscale` with PIL Image.
  1001. Args:
  1002. img (PIL Image or Tensor): RGB Image to be converted to grayscale.
  1003. num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default, 1.
  1004. Returns:
  1005. PIL Image or Tensor: Grayscale version of the image.
  1006. - if num_output_channels = 1 : returned image is single channel
  1007. - if num_output_channels = 3 : returned image is 3 channel with r = g = b
  1008. """
  1009. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  1010. _log_api_usage_once(rgb_to_grayscale)
  1011. if not isinstance(img, torch.Tensor):
  1012. return F_pil.to_grayscale(img, num_output_channels)
  1013. return F_t.rgb_to_grayscale(img, num_output_channels)
  1014. def erase(img: Tensor, i: int, j: int, h: int, w: int, v: Tensor, inplace: bool = False) -> Tensor:
  1015. """Erase the input Tensor Image with given value.
  1016. This transform does not support PIL Image.
  1017. Args:
  1018. img (Tensor Image): Tensor image of size (C, H, W) to be erased
  1019. i (int): i in (i,j) i.e coordinates of the upper left corner.
  1020. j (int): j in (i,j) i.e coordinates of the upper left corner.
  1021. h (int): Height of the erased region.
  1022. w (int): Width of the erased region.
  1023. v: Erasing value.
  1024. inplace(bool, optional): For in-place operations. By default, is set False.
  1025. Returns:
  1026. Tensor Image: Erased image.
  1027. """
  1028. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  1029. _log_api_usage_once(erase)
  1030. if not isinstance(img, torch.Tensor):
  1031. raise TypeError(f"img should be Tensor Image. Got {type(img)}")
  1032. return F_t.erase(img, i, j, h, w, v, inplace=inplace)
  1033. def gaussian_blur(img: Tensor, kernel_size: List[int], sigma: Optional[List[float]] = None) -> Tensor:
  1034. """Performs Gaussian blurring on the image by given kernel.
  1035. If the image is torch Tensor, it is expected
  1036. to have [..., H, W] shape, where ... means at most one leading dimension.
  1037. Args:
  1038. img (PIL Image or Tensor): Image to be blurred
  1039. kernel_size (sequence of ints or int): Gaussian kernel size. Can be a sequence of integers
  1040. like ``(kx, ky)`` or a single integer for square kernels.
  1041. .. note::
  1042. In torchscript mode kernel_size as single int is not supported, use a sequence of
  1043. length 1: ``[ksize, ]``.
  1044. sigma (sequence of floats or float, optional): Gaussian kernel standard deviation. Can be a
  1045. sequence of floats like ``(sigma_x, sigma_y)`` or a single float to define the
  1046. same sigma in both X/Y directions. If None, then it is computed using
  1047. ``kernel_size`` as ``sigma = 0.3 * ((kernel_size - 1) * 0.5 - 1) + 0.8``.
  1048. Default, None.
  1049. .. note::
  1050. In torchscript mode sigma as single float is
  1051. not supported, use a sequence of length 1: ``[sigma, ]``.
  1052. Returns:
  1053. PIL Image or Tensor: Gaussian Blurred version of the image.
  1054. """
  1055. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  1056. _log_api_usage_once(gaussian_blur)
  1057. if not isinstance(kernel_size, (int, list, tuple)):
  1058. raise TypeError(f"kernel_size should be int or a sequence of integers. Got {type(kernel_size)}")
  1059. if isinstance(kernel_size, int):
  1060. kernel_size = [kernel_size, kernel_size]
  1061. if len(kernel_size) != 2:
  1062. raise ValueError(f"If kernel_size is a sequence its length should be 2. Got {len(kernel_size)}")
  1063. for ksize in kernel_size:
  1064. if ksize % 2 == 0 or ksize < 0:
  1065. raise ValueError(f"kernel_size should have odd and positive integers. Got {kernel_size}")
  1066. if sigma is None:
  1067. sigma = [ksize * 0.15 + 0.35 for ksize in kernel_size]
  1068. if sigma is not None and not isinstance(sigma, (int, float, list, tuple)):
  1069. raise TypeError(f"sigma should be either float or sequence of floats. Got {type(sigma)}")
  1070. if isinstance(sigma, (int, float)):
  1071. sigma = [float(sigma), float(sigma)]
  1072. if isinstance(sigma, (list, tuple)) and len(sigma) == 1:
  1073. sigma = [sigma[0], sigma[0]]
  1074. if len(sigma) != 2:
  1075. raise ValueError(f"If sigma is a sequence, its length should be 2. Got {len(sigma)}")
  1076. for s in sigma:
  1077. if s <= 0.0:
  1078. raise ValueError(f"sigma should have positive values. Got {sigma}")
  1079. t_img = img
  1080. if not isinstance(img, torch.Tensor):
  1081. if not F_pil._is_pil_image(img):
  1082. raise TypeError(f"img should be PIL Image or Tensor. Got {type(img)}")
  1083. t_img = pil_to_tensor(img)
  1084. output = F_t.gaussian_blur(t_img, kernel_size, sigma)
  1085. if not isinstance(img, torch.Tensor):
  1086. output = to_pil_image(output, mode=img.mode)
  1087. return output
  1088. def invert(img: Tensor) -> Tensor:
  1089. """Invert the colors of an RGB/grayscale image.
  1090. Args:
  1091. img (PIL Image or Tensor): Image to have its colors inverted.
  1092. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  1093. where ... means it can have an arbitrary number of leading dimensions.
  1094. If img is PIL Image, it is expected to be in mode "L" or "RGB".
  1095. Returns:
  1096. PIL Image or Tensor: Color inverted image.
  1097. """
  1098. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  1099. _log_api_usage_once(invert)
  1100. if not isinstance(img, torch.Tensor):
  1101. return F_pil.invert(img)
  1102. return F_t.invert(img)
  1103. def posterize(img: Tensor, bits: int) -> Tensor:
  1104. """Posterize an image by reducing the number of bits for each color channel.
  1105. Args:
  1106. img (PIL Image or Tensor): Image to have its colors posterized.
  1107. If img is torch Tensor, it should be of type torch.uint8, and
  1108. it is expected to be in [..., 1 or 3, H, W] format, where ... means
  1109. it can have an arbitrary number of leading dimensions.
  1110. If img is PIL Image, it is expected to be in mode "L" or "RGB".
  1111. bits (int): The number of bits to keep for each channel (0-8).
  1112. Returns:
  1113. PIL Image or Tensor: Posterized image.
  1114. """
  1115. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  1116. _log_api_usage_once(posterize)
  1117. if not (0 <= bits <= 8):
  1118. raise ValueError(f"The number if bits should be between 0 and 8. Got {bits}")
  1119. if not isinstance(img, torch.Tensor):
  1120. return F_pil.posterize(img, bits)
  1121. return F_t.posterize(img, bits)
  1122. def solarize(img: Tensor, threshold: float) -> Tensor:
  1123. """Solarize an RGB/grayscale image by inverting all pixel values above a threshold.
  1124. Args:
  1125. img (PIL Image or Tensor): Image to have its colors inverted.
  1126. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  1127. where ... means it can have an arbitrary number of leading dimensions.
  1128. If img is PIL Image, it is expected to be in mode "L" or "RGB".
  1129. threshold (float): All pixels equal or above this value are inverted.
  1130. Returns:
  1131. PIL Image or Tensor: Solarized image.
  1132. """
  1133. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  1134. _log_api_usage_once(solarize)
  1135. if not isinstance(img, torch.Tensor):
  1136. return F_pil.solarize(img, threshold)
  1137. return F_t.solarize(img, threshold)
  1138. def adjust_sharpness(img: Tensor, sharpness_factor: float) -> Tensor:
  1139. """Adjust the sharpness of an image.
  1140. Args:
  1141. img (PIL Image or Tensor): Image to be adjusted.
  1142. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  1143. where ... means it can have an arbitrary number of leading dimensions.
  1144. sharpness_factor (float): How much to adjust the sharpness. Can be
  1145. any non-negative number. 0 gives a blurred image, 1 gives the
  1146. original image while 2 increases the sharpness by a factor of 2.
  1147. Returns:
  1148. PIL Image or Tensor: Sharpness adjusted image.
  1149. """
  1150. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  1151. _log_api_usage_once(adjust_sharpness)
  1152. if not isinstance(img, torch.Tensor):
  1153. return F_pil.adjust_sharpness(img, sharpness_factor)
  1154. return F_t.adjust_sharpness(img, sharpness_factor)
  1155. def autocontrast(img: Tensor) -> Tensor:
  1156. """Maximize contrast of an image by remapping its
  1157. pixels per channel so that the lowest becomes black and the lightest
  1158. becomes white.
  1159. Args:
  1160. img (PIL Image or Tensor): Image on which autocontrast is applied.
  1161. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  1162. where ... means it can have an arbitrary number of leading dimensions.
  1163. If img is PIL Image, it is expected to be in mode "L" or "RGB".
  1164. Returns:
  1165. PIL Image or Tensor: An image that was autocontrasted.
  1166. """
  1167. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  1168. _log_api_usage_once(autocontrast)
  1169. if not isinstance(img, torch.Tensor):
  1170. return F_pil.autocontrast(img)
  1171. return F_t.autocontrast(img)
  1172. def equalize(img: Tensor) -> Tensor:
  1173. """Equalize the histogram of an image by applying
  1174. a non-linear mapping to the input in order to create a uniform
  1175. distribution of grayscale values in the output.
  1176. Args:
  1177. img (PIL Image or Tensor): Image on which equalize is applied.
  1178. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  1179. where ... means it can have an arbitrary number of leading dimensions.
  1180. The tensor dtype must be ``torch.uint8`` and values are expected to be in ``[0, 255]``.
  1181. If img is PIL Image, it is expected to be in mode "P", "L" or "RGB".
  1182. Returns:
  1183. PIL Image or Tensor: An image that was equalized.
  1184. """
  1185. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  1186. _log_api_usage_once(equalize)
  1187. if not isinstance(img, torch.Tensor):
  1188. return F_pil.equalize(img)
  1189. return F_t.equalize(img)
  1190. def elastic_transform(
  1191. img: Tensor,
  1192. displacement: Tensor,
  1193. interpolation: InterpolationMode = InterpolationMode.BILINEAR,
  1194. fill: Optional[List[float]] = None,
  1195. ) -> Tensor:
  1196. """Transform a tensor image with elastic transformations.
  1197. Given alpha and sigma, it will generate displacement
  1198. vectors for all pixels based on random offsets. Alpha controls the strength
  1199. and sigma controls the smoothness of the displacements.
  1200. The displacements are added to an identity grid and the resulting grid is
  1201. used to grid_sample from the image.
  1202. Applications:
  1203. Randomly transforms the morphology of objects in images and produces a
  1204. see-through-water-like effect.
  1205. Args:
  1206. img (PIL Image or Tensor): Image on which elastic_transform is applied.
  1207. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  1208. where ... means it can have an arbitrary number of leading dimensions.
  1209. If img is PIL Image, it is expected to be in mode "P", "L" or "RGB".
  1210. displacement (Tensor): The displacement field. Expected shape is [1, H, W, 2].
  1211. interpolation (InterpolationMode): Desired interpolation enum defined by
  1212. :class:`torchvision.transforms.InterpolationMode`.
  1213. Default is ``InterpolationMode.BILINEAR``.
  1214. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  1215. fill (number or str or tuple): Pixel fill value for constant fill. Default is 0.
  1216. If a tuple of length 3, it is used to fill R, G, B channels respectively.
  1217. This value is only used when the padding_mode is constant.
  1218. """
  1219. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  1220. _log_api_usage_once(elastic_transform)
  1221. # Backward compatibility with integer value
  1222. if isinstance(interpolation, int):
  1223. warnings.warn(
  1224. "Argument interpolation should be of type InterpolationMode instead of int. "
  1225. "Please, use InterpolationMode enum."
  1226. )
  1227. interpolation = _interpolation_modes_from_int(interpolation)
  1228. if not isinstance(displacement, torch.Tensor):
  1229. raise TypeError("Argument displacement should be a Tensor")
  1230. t_img = img
  1231. if not isinstance(img, torch.Tensor):
  1232. if not F_pil._is_pil_image(img):
  1233. raise TypeError(f"img should be PIL Image or Tensor. Got {type(img)}")
  1234. t_img = pil_to_tensor(img)
  1235. shape = t_img.shape
  1236. shape = (1,) + shape[-2:] + (2,)
  1237. if shape != displacement.shape:
  1238. raise ValueError(f"Argument displacement shape should be {shape}, but given {displacement.shape}")
  1239. # TODO: if image shape is [N1, N2, ..., C, H, W] and
  1240. # displacement is [1, H, W, 2] we need to reshape input image
  1241. # such grid_sampler takes internal code for 4D input
  1242. output = F_t.elastic_transform(
  1243. t_img,
  1244. displacement,
  1245. interpolation=interpolation.value,
  1246. fill=fill,
  1247. )
  1248. if not isinstance(img, torch.Tensor):
  1249. output = to_pil_image(output, mode=img.mode)
  1250. return output