functional.py 62 KB

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