functional.py 65 KB

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