transforms.py 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  1. import math
  2. import numbers
  3. import random
  4. import warnings
  5. from collections.abc import Sequence
  6. from typing import List, Optional, Tuple, Union
  7. import torch
  8. from torch import Tensor
  9. try:
  10. import accimage
  11. except ImportError:
  12. accimage = None
  13. from ..utils import _log_api_usage_once
  14. from . import functional as F
  15. from .functional import _interpolation_modes_from_int, InterpolationMode
  16. __all__ = [
  17. "Compose",
  18. "ToTensor",
  19. "PILToTensor",
  20. "ConvertImageDtype",
  21. "ToPILImage",
  22. "Normalize",
  23. "Resize",
  24. "CenterCrop",
  25. "Pad",
  26. "Lambda",
  27. "RandomApply",
  28. "RandomChoice",
  29. "RandomOrder",
  30. "RandomCrop",
  31. "RandomHorizontalFlip",
  32. "RandomVerticalFlip",
  33. "RandomResizedCrop",
  34. "FiveCrop",
  35. "TenCrop",
  36. "LinearTransformation",
  37. "ColorJitter",
  38. "RandomRotation",
  39. "RandomAffine",
  40. "Grayscale",
  41. "RandomGrayscale",
  42. "RandomPerspective",
  43. "RandomErasing",
  44. "GaussianBlur",
  45. "InterpolationMode",
  46. "RandomInvert",
  47. "RandomPosterize",
  48. "RandomSolarize",
  49. "RandomAdjustSharpness",
  50. "RandomAutocontrast",
  51. "RandomEqualize",
  52. "ElasticTransform",
  53. ]
  54. class Compose:
  55. """Composes several transforms together. This transform does not support torchscript.
  56. Please, see the note below.
  57. Args:
  58. transforms (list of ``Transform`` objects): list of transforms to compose.
  59. Example:
  60. >>> transforms.Compose([
  61. >>> transforms.CenterCrop(10),
  62. >>> transforms.PILToTensor(),
  63. >>> transforms.ConvertImageDtype(torch.float),
  64. >>> ])
  65. .. note::
  66. In order to script the transformations, please use ``torch.nn.Sequential`` as below.
  67. >>> transforms = torch.nn.Sequential(
  68. >>> transforms.CenterCrop(10),
  69. >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
  70. >>> )
  71. >>> scripted_transforms = torch.jit.script(transforms)
  72. Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require
  73. `lambda` functions or ``PIL.Image``.
  74. """
  75. def __init__(self, transforms):
  76. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  77. _log_api_usage_once(self)
  78. self.transforms = transforms
  79. def __call__(self, img):
  80. for t in self.transforms:
  81. img = t(img)
  82. return img
  83. def __repr__(self) -> str:
  84. format_string = self.__class__.__name__ + "("
  85. for t in self.transforms:
  86. format_string += "\n"
  87. format_string += f" {t}"
  88. format_string += "\n)"
  89. return format_string
  90. class ToTensor:
  91. """Convert a PIL Image or ndarray to tensor and scale the values accordingly.
  92. This transform does not support torchscript.
  93. Converts a PIL Image or numpy.ndarray (H x W x C) in the range
  94. [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]
  95. if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1)
  96. or if the numpy.ndarray has dtype = np.uint8
  97. In the other cases, tensors are returned without scaling.
  98. .. note::
  99. Because the input image is scaled to [0.0, 1.0], this transformation should not be used when
  100. transforming target image masks. See the `references`_ for implementing the transforms for image masks.
  101. .. _references: https://github.com/pytorch/vision/tree/main/references/segmentation
  102. """
  103. def __init__(self) -> None:
  104. _log_api_usage_once(self)
  105. def __call__(self, pic):
  106. """
  107. Args:
  108. pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
  109. Returns:
  110. Tensor: Converted image.
  111. """
  112. return F.to_tensor(pic)
  113. def __repr__(self) -> str:
  114. return f"{self.__class__.__name__}()"
  115. class PILToTensor:
  116. """Convert a PIL Image to a tensor of the same type - this does not scale values.
  117. This transform does not support torchscript.
  118. Converts a PIL Image (H x W x C) to a Tensor of shape (C x H x W).
  119. """
  120. def __init__(self) -> None:
  121. _log_api_usage_once(self)
  122. def __call__(self, pic):
  123. """
  124. .. note::
  125. A deep copy of the underlying array is performed.
  126. Args:
  127. pic (PIL Image): Image to be converted to tensor.
  128. Returns:
  129. Tensor: Converted image.
  130. """
  131. return F.pil_to_tensor(pic)
  132. def __repr__(self) -> str:
  133. return f"{self.__class__.__name__}()"
  134. class ConvertImageDtype(torch.nn.Module):
  135. """Convert a tensor image to the given ``dtype`` and scale the values accordingly.
  136. This function does not support PIL Image.
  137. Args:
  138. dtype (torch.dtype): Desired data type of the output
  139. .. note::
  140. When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly.
  141. If converted back and forth, this mismatch has no effect.
  142. Raises:
  143. RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as
  144. well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to
  145. overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range
  146. of the integer ``dtype``.
  147. """
  148. def __init__(self, dtype: torch.dtype) -> None:
  149. super().__init__()
  150. _log_api_usage_once(self)
  151. self.dtype = dtype
  152. def forward(self, image):
  153. return F.convert_image_dtype(image, self.dtype)
  154. class ToPILImage:
  155. """Convert a tensor or an ndarray to PIL Image
  156. This transform does not support torchscript.
  157. Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape
  158. H x W x C to a PIL Image while adjusting the value range depending on the ``mode``.
  159. Args:
  160. mode (`PIL.Image mode`_): color space and pixel depth of input data (optional).
  161. If ``mode`` is ``None`` (default) there are some assumptions made about the input data:
  162. - If the input has 4 channels, the ``mode`` is assumed to be ``RGBA``.
  163. - If the input has 3 channels, the ``mode`` is assumed to be ``RGB``.
  164. - If the input has 2 channels, the ``mode`` is assumed to be ``LA``.
  165. - If the input has 1 channel, the ``mode`` is determined by the data type (i.e ``int``, ``float``, ``short``).
  166. .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes
  167. """
  168. def __init__(self, mode=None):
  169. _log_api_usage_once(self)
  170. self.mode = mode
  171. def __call__(self, pic):
  172. """
  173. Args:
  174. pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
  175. Returns:
  176. PIL Image: Image converted to PIL Image.
  177. """
  178. return F.to_pil_image(pic, self.mode)
  179. def __repr__(self) -> str:
  180. format_string = self.__class__.__name__ + "("
  181. if self.mode is not None:
  182. format_string += f"mode={self.mode}"
  183. format_string += ")"
  184. return format_string
  185. class Normalize(torch.nn.Module):
  186. """Normalize a tensor image with mean and standard deviation.
  187. This transform does not support PIL Image.
  188. Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n``
  189. channels, this transform will normalize each channel of the input
  190. ``torch.*Tensor`` i.e.,
  191. ``output[channel] = (input[channel] - mean[channel]) / std[channel]``
  192. .. note::
  193. This transform acts out of place, i.e., it does not mutate the input tensor.
  194. Args:
  195. mean (sequence): Sequence of means for each channel.
  196. std (sequence): Sequence of standard deviations for each channel.
  197. inplace(bool,optional): Bool to make this operation in-place.
  198. """
  199. def __init__(self, mean, std, inplace=False):
  200. super().__init__()
  201. _log_api_usage_once(self)
  202. self.mean = mean
  203. self.std = std
  204. self.inplace = inplace
  205. def forward(self, tensor: Tensor) -> Tensor:
  206. """
  207. Args:
  208. tensor (Tensor): Tensor image to be normalized.
  209. Returns:
  210. Tensor: Normalized Tensor image.
  211. """
  212. return F.normalize(tensor, self.mean, self.std, self.inplace)
  213. def __repr__(self) -> str:
  214. return f"{self.__class__.__name__}(mean={self.mean}, std={self.std})"
  215. class Resize(torch.nn.Module):
  216. """Resize the input image to the given size.
  217. If the image is torch Tensor, it is expected
  218. to have [..., H, W] shape, where ... means a maximum of two leading dimensions
  219. Args:
  220. size (sequence or int): Desired output size. If size is a sequence like
  221. (h, w), output size will be matched to this. If size is an int,
  222. smaller edge of the image will be matched to this number.
  223. i.e, if height > width, then image will be rescaled to
  224. (size * height / width, size).
  225. .. note::
  226. In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
  227. interpolation (InterpolationMode): Desired interpolation enum defined by
  228. :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
  229. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
  230. ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
  231. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  232. max_size (int, optional): The maximum allowed for the longer edge of
  233. the resized image. If the longer edge of the image is greater
  234. than ``max_size`` after being resized according to ``size``,
  235. ``size`` will be overruled so that the longer edge is equal to
  236. ``max_size``.
  237. As a result, the smaller edge may be shorter than ``size``. This
  238. is only supported if ``size`` is an int (or a sequence of length
  239. 1 in torchscript mode).
  240. antialias (bool, optional): Whether to apply antialiasing.
  241. It only affects **tensors** with bilinear or bicubic modes and it is
  242. ignored otherwise: on PIL images, antialiasing is always applied on
  243. bilinear or bicubic modes; on other modes (for PIL images and
  244. tensors), antialiasing makes no sense and this parameter is ignored.
  245. Possible values are:
  246. - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
  247. Other mode aren't affected. This is probably what you want to use.
  248. - ``False``: will not apply antialiasing for tensors on any mode. PIL
  249. images are still antialiased on bilinear or bicubic modes, because
  250. PIL doesn't support no antialias.
  251. - ``None``: equivalent to ``False`` for tensors and ``True`` for
  252. PIL images. This value exists for legacy reasons and you probably
  253. don't want to use it unless you really know what you are doing.
  254. The default value changed from ``None`` to ``True`` in
  255. v0.17, for the PIL and Tensor backends to be consistent.
  256. """
  257. def __init__(self, size, interpolation=InterpolationMode.BILINEAR, max_size=None, antialias=True):
  258. super().__init__()
  259. _log_api_usage_once(self)
  260. if not isinstance(size, (int, Sequence)):
  261. raise TypeError(f"Size should be int or sequence. Got {type(size)}")
  262. if isinstance(size, Sequence) and len(size) not in (1, 2):
  263. raise ValueError("If size is a sequence, it should have 1 or 2 values")
  264. self.size = size
  265. self.max_size = max_size
  266. if isinstance(interpolation, int):
  267. interpolation = _interpolation_modes_from_int(interpolation)
  268. self.interpolation = interpolation
  269. self.antialias = antialias
  270. def forward(self, img):
  271. """
  272. Args:
  273. img (PIL Image or Tensor): Image to be scaled.
  274. Returns:
  275. PIL Image or Tensor: Rescaled image.
  276. """
  277. return F.resize(img, self.size, self.interpolation, self.max_size, self.antialias)
  278. def __repr__(self) -> str:
  279. detail = f"(size={self.size}, interpolation={self.interpolation.value}, max_size={self.max_size}, antialias={self.antialias})"
  280. return f"{self.__class__.__name__}{detail}"
  281. class CenterCrop(torch.nn.Module):
  282. """Crops the given image at the center.
  283. If the image is torch Tensor, it is expected
  284. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
  285. If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.
  286. Args:
  287. size (sequence or int): Desired output size of the crop. If size is an
  288. int instead of sequence like (h, w), a square crop (size, size) is
  289. made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
  290. """
  291. def __init__(self, size):
  292. super().__init__()
  293. _log_api_usage_once(self)
  294. self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
  295. def forward(self, img):
  296. """
  297. Args:
  298. img (PIL Image or Tensor): Image to be cropped.
  299. Returns:
  300. PIL Image or Tensor: Cropped image.
  301. """
  302. return F.center_crop(img, self.size)
  303. def __repr__(self) -> str:
  304. return f"{self.__class__.__name__}(size={self.size})"
  305. class Pad(torch.nn.Module):
  306. """Pad the given image on all sides with the given "pad" value.
  307. If the image is torch Tensor, it is expected
  308. to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric,
  309. at most 3 leading dimensions for mode edge,
  310. and an arbitrary number of leading dimensions for mode constant
  311. Args:
  312. padding (int or sequence): Padding on each border. If a single int is provided this
  313. is used to pad all borders. If sequence of length 2 is provided this is the padding
  314. on left/right and top/bottom respectively. If a sequence of length 4 is provided
  315. this is the padding for the left, top, right and bottom borders respectively.
  316. .. note::
  317. In torchscript mode padding as single int is not supported, use a sequence of
  318. length 1: ``[padding, ]``.
  319. fill (number or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of
  320. length 3, it is used to fill R, G, B channels respectively.
  321. This value is only used when the padding_mode is constant.
  322. Only number is supported for torch Tensor.
  323. Only int or tuple value is supported for PIL Image.
  324. padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
  325. Default is constant.
  326. - constant: pads with a constant value, this value is specified with fill
  327. - edge: pads with the last value at the edge of the image.
  328. If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2
  329. - reflect: pads with reflection of image without repeating the last value on the edge.
  330. For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
  331. will result in [3, 2, 1, 2, 3, 4, 3, 2]
  332. - symmetric: pads with reflection of image repeating the last value on the edge.
  333. For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
  334. will result in [2, 1, 1, 2, 3, 4, 4, 3]
  335. """
  336. def __init__(self, padding, fill=0, padding_mode="constant"):
  337. super().__init__()
  338. _log_api_usage_once(self)
  339. if not isinstance(padding, (numbers.Number, tuple, list)):
  340. raise TypeError("Got inappropriate padding arg")
  341. if not isinstance(fill, (numbers.Number, tuple, list)):
  342. raise TypeError("Got inappropriate fill arg")
  343. if padding_mode not in ["constant", "edge", "reflect", "symmetric"]:
  344. raise ValueError("Padding mode should be either constant, edge, reflect or symmetric")
  345. if isinstance(padding, Sequence) and len(padding) not in [1, 2, 4]:
  346. raise ValueError(
  347. f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple"
  348. )
  349. self.padding = padding
  350. self.fill = fill
  351. self.padding_mode = padding_mode
  352. def forward(self, img):
  353. """
  354. Args:
  355. img (PIL Image or Tensor): Image to be padded.
  356. Returns:
  357. PIL Image or Tensor: Padded image.
  358. """
  359. return F.pad(img, self.padding, self.fill, self.padding_mode)
  360. def __repr__(self) -> str:
  361. return f"{self.__class__.__name__}(padding={self.padding}, fill={self.fill}, padding_mode={self.padding_mode})"
  362. class Lambda:
  363. """Apply a user-defined lambda as a transform. This transform does not support torchscript.
  364. Args:
  365. lambd (function): Lambda/function to be used for transform.
  366. """
  367. def __init__(self, lambd):
  368. _log_api_usage_once(self)
  369. if not callable(lambd):
  370. raise TypeError(f"Argument lambd should be callable, got {repr(type(lambd).__name__)}")
  371. self.lambd = lambd
  372. def __call__(self, img):
  373. return self.lambd(img)
  374. def __repr__(self) -> str:
  375. return f"{self.__class__.__name__}()"
  376. class RandomTransforms:
  377. """Base class for a list of transformations with randomness
  378. Args:
  379. transforms (sequence): list of transformations
  380. """
  381. def __init__(self, transforms):
  382. _log_api_usage_once(self)
  383. if not isinstance(transforms, Sequence):
  384. raise TypeError("Argument transforms should be a sequence")
  385. self.transforms = transforms
  386. def __call__(self, *args, **kwargs):
  387. raise NotImplementedError()
  388. def __repr__(self) -> str:
  389. format_string = self.__class__.__name__ + "("
  390. for t in self.transforms:
  391. format_string += "\n"
  392. format_string += f" {t}"
  393. format_string += "\n)"
  394. return format_string
  395. class RandomApply(torch.nn.Module):
  396. """Apply randomly a list of transformations with a given probability.
  397. .. note::
  398. In order to script the transformation, please use ``torch.nn.ModuleList`` as input instead of list/tuple of
  399. transforms as shown below:
  400. >>> transforms = transforms.RandomApply(torch.nn.ModuleList([
  401. >>> transforms.ColorJitter(),
  402. >>> ]), p=0.3)
  403. >>> scripted_transforms = torch.jit.script(transforms)
  404. Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require
  405. `lambda` functions or ``PIL.Image``.
  406. Args:
  407. transforms (sequence or torch.nn.Module): list of transformations
  408. p (float): probability
  409. """
  410. def __init__(self, transforms, p=0.5):
  411. super().__init__()
  412. _log_api_usage_once(self)
  413. self.transforms = transforms
  414. self.p = p
  415. def forward(self, img):
  416. if self.p < torch.rand(1):
  417. return img
  418. for t in self.transforms:
  419. img = t(img)
  420. return img
  421. def __repr__(self) -> str:
  422. format_string = self.__class__.__name__ + "("
  423. format_string += f"\n p={self.p}"
  424. for t in self.transforms:
  425. format_string += "\n"
  426. format_string += f" {t}"
  427. format_string += "\n)"
  428. return format_string
  429. class RandomOrder(RandomTransforms):
  430. """Apply a list of transformations in a random order. This transform does not support torchscript."""
  431. def __call__(self, img):
  432. order = list(range(len(self.transforms)))
  433. random.shuffle(order)
  434. for i in order:
  435. img = self.transforms[i](img)
  436. return img
  437. class RandomChoice(RandomTransforms):
  438. """Apply single transformation randomly picked from a list. This transform does not support torchscript."""
  439. def __init__(self, transforms, p=None):
  440. super().__init__(transforms)
  441. if p is not None and not isinstance(p, Sequence):
  442. raise TypeError("Argument p should be a sequence")
  443. self.p = p
  444. def __call__(self, *args):
  445. t = random.choices(self.transforms, weights=self.p)[0]
  446. return t(*args)
  447. def __repr__(self) -> str:
  448. return f"{super().__repr__()}(p={self.p})"
  449. class RandomCrop(torch.nn.Module):
  450. """Crop the given image at a random location.
  451. If the image is torch Tensor, it is expected
  452. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions,
  453. but if non-constant padding is used, the input is expected to have at most 2 leading dimensions
  454. Args:
  455. size (sequence or int): Desired output size of the crop. If size is an
  456. int instead of sequence like (h, w), a square crop (size, size) is
  457. made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
  458. padding (int or sequence, optional): Optional padding on each border
  459. of the image. Default is None. If a single int is provided this
  460. is used to pad all borders. If sequence of length 2 is provided this is the padding
  461. on left/right and top/bottom respectively. If a sequence of length 4 is provided
  462. this is the padding for the left, top, right and bottom borders respectively.
  463. .. note::
  464. In torchscript mode padding as single int is not supported, use a sequence of
  465. length 1: ``[padding, ]``.
  466. pad_if_needed (boolean): It will pad the image if smaller than the
  467. desired size to avoid raising an exception. Since cropping is done
  468. after padding, the padding seems to be done at a random offset.
  469. fill (number or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of
  470. length 3, it is used to fill R, G, B channels respectively.
  471. This value is only used when the padding_mode is constant.
  472. Only number is supported for torch Tensor.
  473. Only int or tuple value is supported for PIL Image.
  474. padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
  475. Default is constant.
  476. - constant: pads with a constant value, this value is specified with fill
  477. - edge: pads with the last value at the edge of the image.
  478. If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2
  479. - reflect: pads with reflection of image without repeating the last value on the edge.
  480. For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
  481. will result in [3, 2, 1, 2, 3, 4, 3, 2]
  482. - symmetric: pads with reflection of image repeating the last value on the edge.
  483. For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
  484. will result in [2, 1, 1, 2, 3, 4, 4, 3]
  485. """
  486. @staticmethod
  487. def get_params(img: Tensor, output_size: Tuple[int, int]) -> Tuple[int, int, int, int]:
  488. """Get parameters for ``crop`` for a random crop.
  489. Args:
  490. img (PIL Image or Tensor): Image to be cropped.
  491. output_size (tuple): Expected output size of the crop.
  492. Returns:
  493. tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.
  494. """
  495. _, h, w = F.get_dimensions(img)
  496. th, tw = output_size
  497. if h < th or w < tw:
  498. raise ValueError(f"Required crop size {(th, tw)} is larger than input image size {(h, w)}")
  499. if w == tw and h == th:
  500. return 0, 0, h, w
  501. i = torch.randint(0, h - th + 1, size=(1,)).item()
  502. j = torch.randint(0, w - tw + 1, size=(1,)).item()
  503. return i, j, th, tw
  504. def __init__(self, size, padding=None, pad_if_needed=False, fill=0, padding_mode="constant"):
  505. super().__init__()
  506. _log_api_usage_once(self)
  507. self.size = tuple(_setup_size(size, error_msg="Please provide only two dimensions (h, w) for size."))
  508. self.padding = padding
  509. self.pad_if_needed = pad_if_needed
  510. self.fill = fill
  511. self.padding_mode = padding_mode
  512. def forward(self, img):
  513. """
  514. Args:
  515. img (PIL Image or Tensor): Image to be cropped.
  516. Returns:
  517. PIL Image or Tensor: Cropped image.
  518. """
  519. if self.padding is not None:
  520. img = F.pad(img, self.padding, self.fill, self.padding_mode)
  521. _, height, width = F.get_dimensions(img)
  522. # pad the width if needed
  523. if self.pad_if_needed and width < self.size[1]:
  524. padding = [self.size[1] - width, 0]
  525. img = F.pad(img, padding, self.fill, self.padding_mode)
  526. # pad the height if needed
  527. if self.pad_if_needed and height < self.size[0]:
  528. padding = [0, self.size[0] - height]
  529. img = F.pad(img, padding, self.fill, self.padding_mode)
  530. i, j, h, w = self.get_params(img, self.size)
  531. return F.crop(img, i, j, h, w)
  532. def __repr__(self) -> str:
  533. return f"{self.__class__.__name__}(size={self.size}, padding={self.padding})"
  534. class RandomHorizontalFlip(torch.nn.Module):
  535. """Horizontally flip the given image randomly with a given probability.
  536. If the image is torch Tensor, it is expected
  537. to have [..., H, W] shape, where ... means an arbitrary number of leading
  538. dimensions
  539. Args:
  540. p (float): probability of the image being flipped. Default value is 0.5
  541. """
  542. def __init__(self, p=0.5):
  543. super().__init__()
  544. _log_api_usage_once(self)
  545. self.p = p
  546. def forward(self, img):
  547. """
  548. Args:
  549. img (PIL Image or Tensor): Image to be flipped.
  550. Returns:
  551. PIL Image or Tensor: Randomly flipped image.
  552. """
  553. if torch.rand(1) < self.p:
  554. return F.hflip(img)
  555. return img
  556. def __repr__(self) -> str:
  557. return f"{self.__class__.__name__}(p={self.p})"
  558. class RandomVerticalFlip(torch.nn.Module):
  559. """Vertically flip the given image randomly with a given probability.
  560. If the image is torch Tensor, it is expected
  561. to have [..., H, W] shape, where ... means an arbitrary number of leading
  562. dimensions
  563. Args:
  564. p (float): probability of the image being flipped. Default value is 0.5
  565. """
  566. def __init__(self, p=0.5):
  567. super().__init__()
  568. _log_api_usage_once(self)
  569. self.p = p
  570. def forward(self, img):
  571. """
  572. Args:
  573. img (PIL Image or Tensor): Image to be flipped.
  574. Returns:
  575. PIL Image or Tensor: Randomly flipped image.
  576. """
  577. if torch.rand(1) < self.p:
  578. return F.vflip(img)
  579. return img
  580. def __repr__(self) -> str:
  581. return f"{self.__class__.__name__}(p={self.p})"
  582. class RandomPerspective(torch.nn.Module):
  583. """Performs a random perspective transformation of the given image with a given probability.
  584. If the image is torch Tensor, it is expected
  585. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
  586. Args:
  587. distortion_scale (float): argument to control the degree of distortion and ranges from 0 to 1.
  588. Default is 0.5.
  589. p (float): probability of the image being transformed. Default is 0.5.
  590. interpolation (InterpolationMode): Desired interpolation enum defined by
  591. :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
  592. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
  593. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  594. fill (sequence or number): Pixel fill value for the area outside the transformed
  595. image. Default is ``0``. If given a number, the value is used for all bands respectively.
  596. """
  597. def __init__(self, distortion_scale=0.5, p=0.5, interpolation=InterpolationMode.BILINEAR, fill=0):
  598. super().__init__()
  599. _log_api_usage_once(self)
  600. self.p = p
  601. if isinstance(interpolation, int):
  602. interpolation = _interpolation_modes_from_int(interpolation)
  603. self.interpolation = interpolation
  604. self.distortion_scale = distortion_scale
  605. if fill is None:
  606. fill = 0
  607. elif not isinstance(fill, (Sequence, numbers.Number)):
  608. raise TypeError("Fill should be either a sequence or a number.")
  609. self.fill = fill
  610. def forward(self, img):
  611. """
  612. Args:
  613. img (PIL Image or Tensor): Image to be Perspectively transformed.
  614. Returns:
  615. PIL Image or Tensor: Randomly transformed image.
  616. """
  617. fill = self.fill
  618. channels, height, width = F.get_dimensions(img)
  619. if isinstance(img, Tensor):
  620. if isinstance(fill, (int, float)):
  621. fill = [float(fill)] * channels
  622. else:
  623. fill = [float(f) for f in fill]
  624. if torch.rand(1) < self.p:
  625. startpoints, endpoints = self.get_params(width, height, self.distortion_scale)
  626. return F.perspective(img, startpoints, endpoints, self.interpolation, fill)
  627. return img
  628. @staticmethod
  629. def get_params(width: int, height: int, distortion_scale: float) -> Tuple[List[List[int]], List[List[int]]]:
  630. """Get parameters for ``perspective`` for a random perspective transform.
  631. Args:
  632. width (int): width of the image.
  633. height (int): height of the image.
  634. distortion_scale (float): argument to control the degree of distortion and ranges from 0 to 1.
  635. Returns:
  636. List containing [top-left, top-right, bottom-right, bottom-left] of the original image,
  637. List containing [top-left, top-right, bottom-right, bottom-left] of the transformed image.
  638. """
  639. half_height = height // 2
  640. half_width = width // 2
  641. topleft = [
  642. int(torch.randint(0, int(distortion_scale * half_width) + 1, size=(1,)).item()),
  643. int(torch.randint(0, int(distortion_scale * half_height) + 1, size=(1,)).item()),
  644. ]
  645. topright = [
  646. int(torch.randint(width - int(distortion_scale * half_width) - 1, width, size=(1,)).item()),
  647. int(torch.randint(0, int(distortion_scale * half_height) + 1, size=(1,)).item()),
  648. ]
  649. botright = [
  650. int(torch.randint(width - int(distortion_scale * half_width) - 1, width, size=(1,)).item()),
  651. int(torch.randint(height - int(distortion_scale * half_height) - 1, height, size=(1,)).item()),
  652. ]
  653. botleft = [
  654. int(torch.randint(0, int(distortion_scale * half_width) + 1, size=(1,)).item()),
  655. int(torch.randint(height - int(distortion_scale * half_height) - 1, height, size=(1,)).item()),
  656. ]
  657. startpoints = [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]
  658. endpoints = [topleft, topright, botright, botleft]
  659. return startpoints, endpoints
  660. def __repr__(self) -> str:
  661. return f"{self.__class__.__name__}(p={self.p})"
  662. class RandomResizedCrop(torch.nn.Module):
  663. """Crop a random portion of image and resize it to a given size.
  664. If the image is torch Tensor, it is expected
  665. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
  666. A crop of the original image is made: the crop has a random area (H * W)
  667. and a random aspect ratio. This crop is finally resized to the given
  668. size. This is popularly used to train the Inception networks.
  669. Args:
  670. size (int or sequence): expected output size of the crop, for each edge. If size is an
  671. int instead of sequence like (h, w), a square output size ``(size, size)`` is
  672. made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
  673. .. note::
  674. In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
  675. scale (tuple of float): Specifies the lower and upper bounds for the random area of the crop,
  676. before resizing. The scale is defined with respect to the area of the original image.
  677. ratio (tuple of float): lower and upper bounds for the random aspect ratio of the crop, before
  678. resizing.
  679. interpolation (InterpolationMode): Desired interpolation enum defined by
  680. :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
  681. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
  682. ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
  683. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  684. antialias (bool, optional): Whether to apply antialiasing.
  685. It only affects **tensors** with bilinear or bicubic modes and it is
  686. ignored otherwise: on PIL images, antialiasing is always applied on
  687. bilinear or bicubic modes; on other modes (for PIL images and
  688. tensors), antialiasing makes no sense and this parameter is ignored.
  689. Possible values are:
  690. - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
  691. Other mode aren't affected. This is probably what you want to use.
  692. - ``False``: will not apply antialiasing for tensors on any mode. PIL
  693. images are still antialiased on bilinear or bicubic modes, because
  694. PIL doesn't support no antialias.
  695. - ``None``: equivalent to ``False`` for tensors and ``True`` for
  696. PIL images. This value exists for legacy reasons and you probably
  697. don't want to use it unless you really know what you are doing.
  698. The default value changed from ``None`` to ``True`` in
  699. v0.17, for the PIL and Tensor backends to be consistent.
  700. """
  701. def __init__(
  702. self,
  703. size,
  704. scale=(0.08, 1.0),
  705. ratio=(3.0 / 4.0, 4.0 / 3.0),
  706. interpolation=InterpolationMode.BILINEAR,
  707. antialias: Optional[bool] = True,
  708. ):
  709. super().__init__()
  710. _log_api_usage_once(self)
  711. self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
  712. if not isinstance(scale, Sequence):
  713. raise TypeError("Scale should be a sequence")
  714. if not isinstance(ratio, Sequence):
  715. raise TypeError("Ratio should be a sequence")
  716. if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
  717. warnings.warn("Scale and ratio should be of kind (min, max)")
  718. if isinstance(interpolation, int):
  719. interpolation = _interpolation_modes_from_int(interpolation)
  720. self.interpolation = interpolation
  721. self.antialias = antialias
  722. self.scale = scale
  723. self.ratio = ratio
  724. @staticmethod
  725. def get_params(img: Tensor, scale: List[float], ratio: List[float]) -> Tuple[int, int, int, int]:
  726. """Get parameters for ``crop`` for a random sized crop.
  727. Args:
  728. img (PIL Image or Tensor): Input image.
  729. scale (list): range of scale of the origin size cropped
  730. ratio (list): range of aspect ratio of the origin aspect ratio cropped
  731. Returns:
  732. tuple: params (i, j, h, w) to be passed to ``crop`` for a random
  733. sized crop.
  734. """
  735. _, height, width = F.get_dimensions(img)
  736. area = height * width
  737. log_ratio = torch.log(torch.tensor(ratio))
  738. for _ in range(10):
  739. target_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item()
  740. aspect_ratio = torch.exp(torch.empty(1).uniform_(log_ratio[0], log_ratio[1])).item()
  741. w = int(round(math.sqrt(target_area * aspect_ratio)))
  742. h = int(round(math.sqrt(target_area / aspect_ratio)))
  743. if 0 < w <= width and 0 < h <= height:
  744. i = torch.randint(0, height - h + 1, size=(1,)).item()
  745. j = torch.randint(0, width - w + 1, size=(1,)).item()
  746. return i, j, h, w
  747. # Fallback to central crop
  748. in_ratio = float(width) / float(height)
  749. if in_ratio < min(ratio):
  750. w = width
  751. h = int(round(w / min(ratio)))
  752. elif in_ratio > max(ratio):
  753. h = height
  754. w = int(round(h * max(ratio)))
  755. else: # whole image
  756. w = width
  757. h = height
  758. i = (height - h) // 2
  759. j = (width - w) // 2
  760. return i, j, h, w
  761. def forward(self, img):
  762. """
  763. Args:
  764. img (PIL Image or Tensor): Image to be cropped and resized.
  765. Returns:
  766. PIL Image or Tensor: Randomly cropped and resized image.
  767. """
  768. i, j, h, w = self.get_params(img, self.scale, self.ratio)
  769. return F.resized_crop(img, i, j, h, w, self.size, self.interpolation, antialias=self.antialias)
  770. def __repr__(self) -> str:
  771. interpolate_str = self.interpolation.value
  772. format_string = self.__class__.__name__ + f"(size={self.size}"
  773. format_string += f", scale={tuple(round(s, 4) for s in self.scale)}"
  774. format_string += f", ratio={tuple(round(r, 4) for r in self.ratio)}"
  775. format_string += f", interpolation={interpolate_str}"
  776. format_string += f", antialias={self.antialias})"
  777. return format_string
  778. class FiveCrop(torch.nn.Module):
  779. """Crop the given image into four corners and the central crop.
  780. If the image is torch Tensor, it is expected
  781. to have [..., H, W] shape, where ... means an arbitrary number of leading
  782. dimensions
  783. .. Note::
  784. This transform returns a tuple of images and there may be a mismatch in the number of
  785. inputs and targets your Dataset returns. See below for an example of how to deal with
  786. this.
  787. Args:
  788. size (sequence or int): Desired output size of the crop. If size is an ``int``
  789. instead of sequence like (h, w), a square crop of size (size, size) is made.
  790. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
  791. Example:
  792. >>> transform = Compose([
  793. >>> FiveCrop(size), # this is a list of PIL Images
  794. >>> Lambda(lambda crops: torch.stack([PILToTensor()(crop) for crop in crops])) # returns a 4D tensor
  795. >>> ])
  796. >>> #In your test loop you can do the following:
  797. >>> input, target = batch # input is a 5d tensor, target is 2d
  798. >>> bs, ncrops, c, h, w = input.size()
  799. >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops
  800. >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops
  801. """
  802. def __init__(self, size):
  803. super().__init__()
  804. _log_api_usage_once(self)
  805. self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
  806. def forward(self, img):
  807. """
  808. Args:
  809. img (PIL Image or Tensor): Image to be cropped.
  810. Returns:
  811. tuple of 5 images. Image can be PIL Image or Tensor
  812. """
  813. return F.five_crop(img, self.size)
  814. def __repr__(self) -> str:
  815. return f"{self.__class__.__name__}(size={self.size})"
  816. class TenCrop(torch.nn.Module):
  817. """Crop the given image into four corners and the central crop plus the flipped version of
  818. these (horizontal flipping is used by default).
  819. If the image is torch Tensor, it is expected
  820. to have [..., H, W] shape, where ... means an arbitrary number of leading
  821. dimensions
  822. .. Note::
  823. This transform returns a tuple of images and there may be a mismatch in the number of
  824. inputs and targets your Dataset returns. See below for an example of how to deal with
  825. this.
  826. Args:
  827. size (sequence or int): Desired output size of the crop. If size is an
  828. int instead of sequence like (h, w), a square crop (size, size) is
  829. made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
  830. vertical_flip (bool): Use vertical flipping instead of horizontal
  831. Example:
  832. >>> transform = Compose([
  833. >>> TenCrop(size), # this is a tuple of PIL Images
  834. >>> Lambda(lambda crops: torch.stack([PILToTensor()(crop) for crop in crops])) # returns a 4D tensor
  835. >>> ])
  836. >>> #In your test loop you can do the following:
  837. >>> input, target = batch # input is a 5d tensor, target is 2d
  838. >>> bs, ncrops, c, h, w = input.size()
  839. >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops
  840. >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops
  841. """
  842. def __init__(self, size, vertical_flip=False):
  843. super().__init__()
  844. _log_api_usage_once(self)
  845. self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
  846. self.vertical_flip = vertical_flip
  847. def forward(self, img):
  848. """
  849. Args:
  850. img (PIL Image or Tensor): Image to be cropped.
  851. Returns:
  852. tuple of 10 images. Image can be PIL Image or Tensor
  853. """
  854. return F.ten_crop(img, self.size, self.vertical_flip)
  855. def __repr__(self) -> str:
  856. return f"{self.__class__.__name__}(size={self.size}, vertical_flip={self.vertical_flip})"
  857. class LinearTransformation(torch.nn.Module):
  858. """Transform a tensor image with a square transformation matrix and a mean_vector computed
  859. offline.
  860. This transform does not support PIL Image.
  861. Given transformation_matrix and mean_vector, will flatten the torch.*Tensor and
  862. subtract mean_vector from it which is then followed by computing the dot
  863. product with the transformation matrix and then reshaping the tensor to its
  864. original shape.
  865. Applications:
  866. whitening transformation: Suppose X is a column vector zero-centered data.
  867. Then compute the data covariance matrix [D x D] with torch.mm(X.t(), X),
  868. perform SVD on this matrix and pass it as transformation_matrix.
  869. Args:
  870. transformation_matrix (Tensor): tensor [D x D], D = C x H x W
  871. mean_vector (Tensor): tensor [D], D = C x H x W
  872. """
  873. def __init__(self, transformation_matrix, mean_vector):
  874. super().__init__()
  875. _log_api_usage_once(self)
  876. if transformation_matrix.size(0) != transformation_matrix.size(1):
  877. raise ValueError(
  878. "transformation_matrix should be square. Got "
  879. f"{tuple(transformation_matrix.size())} rectangular matrix."
  880. )
  881. if mean_vector.size(0) != transformation_matrix.size(0):
  882. raise ValueError(
  883. f"mean_vector should have the same length {mean_vector.size(0)}"
  884. f" as any one of the dimensions of the transformation_matrix [{tuple(transformation_matrix.size())}]"
  885. )
  886. if transformation_matrix.device != mean_vector.device:
  887. raise ValueError(
  888. f"Input tensors should be on the same device. Got {transformation_matrix.device} and {mean_vector.device}"
  889. )
  890. if transformation_matrix.dtype != mean_vector.dtype:
  891. raise ValueError(
  892. f"Input tensors should have the same dtype. Got {transformation_matrix.dtype} and {mean_vector.dtype}"
  893. )
  894. self.transformation_matrix = transformation_matrix
  895. self.mean_vector = mean_vector
  896. def forward(self, tensor: Tensor) -> Tensor:
  897. """
  898. Args:
  899. tensor (Tensor): Tensor image to be whitened.
  900. Returns:
  901. Tensor: Transformed image.
  902. """
  903. shape = tensor.shape
  904. n = shape[-3] * shape[-2] * shape[-1]
  905. if n != self.transformation_matrix.shape[0]:
  906. raise ValueError(
  907. "Input tensor and transformation matrix have incompatible shape."
  908. + f"[{shape[-3]} x {shape[-2]} x {shape[-1]}] != "
  909. + f"{self.transformation_matrix.shape[0]}"
  910. )
  911. if tensor.device.type != self.mean_vector.device.type:
  912. raise ValueError(
  913. "Input tensor should be on the same device as transformation matrix and mean vector. "
  914. f"Got {tensor.device} vs {self.mean_vector.device}"
  915. )
  916. flat_tensor = tensor.view(-1, n) - self.mean_vector
  917. transformation_matrix = self.transformation_matrix.to(flat_tensor.dtype)
  918. transformed_tensor = torch.mm(flat_tensor, transformation_matrix)
  919. tensor = transformed_tensor.view(shape)
  920. return tensor
  921. def __repr__(self) -> str:
  922. s = (
  923. f"{self.__class__.__name__}(transformation_matrix="
  924. f"{self.transformation_matrix.tolist()}"
  925. f", mean_vector={self.mean_vector.tolist()})"
  926. )
  927. return s
  928. class ColorJitter(torch.nn.Module):
  929. """Randomly change the brightness, contrast, saturation and hue of an image.
  930. If the image is torch Tensor, it is expected
  931. to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
  932. If img is PIL Image, mode "1", "I", "F" and modes with transparency (alpha channel) are not supported.
  933. Args:
  934. brightness (float or tuple of float (min, max)): How much to jitter brightness.
  935. brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]
  936. or the given [min, max]. Should be non negative numbers.
  937. contrast (float or tuple of float (min, max)): How much to jitter contrast.
  938. contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]
  939. or the given [min, max]. Should be non-negative numbers.
  940. saturation (float or tuple of float (min, max)): How much to jitter saturation.
  941. saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]
  942. or the given [min, max]. Should be non negative numbers.
  943. hue (float or tuple of float (min, max)): How much to jitter hue.
  944. hue_factor is chosen uniformly from [-hue, hue] or the given [min, max].
  945. Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5.
  946. To jitter hue, the pixel values of the input image has to be non-negative for conversion to HSV space;
  947. thus it does not work if you normalize your image to an interval with negative values,
  948. or use an interpolation that generates negative values before using this function.
  949. """
  950. def __init__(
  951. self,
  952. brightness: Union[float, Tuple[float, float]] = 0,
  953. contrast: Union[float, Tuple[float, float]] = 0,
  954. saturation: Union[float, Tuple[float, float]] = 0,
  955. hue: Union[float, Tuple[float, float]] = 0,
  956. ) -> None:
  957. super().__init__()
  958. _log_api_usage_once(self)
  959. self.brightness = self._check_input(brightness, "brightness")
  960. self.contrast = self._check_input(contrast, "contrast")
  961. self.saturation = self._check_input(saturation, "saturation")
  962. self.hue = self._check_input(hue, "hue", center=0, bound=(-0.5, 0.5), clip_first_on_zero=False)
  963. @torch.jit.unused
  964. def _check_input(self, value, name, center=1, bound=(0, float("inf")), clip_first_on_zero=True):
  965. if isinstance(value, numbers.Number):
  966. if value < 0:
  967. raise ValueError(f"If {name} is a single number, it must be non negative.")
  968. value = [center - float(value), center + float(value)]
  969. if clip_first_on_zero:
  970. value[0] = max(value[0], 0.0)
  971. elif isinstance(value, (tuple, list)) and len(value) == 2:
  972. value = [float(value[0]), float(value[1])]
  973. else:
  974. raise TypeError(f"{name} should be a single number or a list/tuple with length 2.")
  975. if not bound[0] <= value[0] <= value[1] <= bound[1]:
  976. raise ValueError(f"{name} values should be between {bound}, but got {value}.")
  977. # if value is 0 or (1., 1.) for brightness/contrast/saturation
  978. # or (0., 0.) for hue, do nothing
  979. if value[0] == value[1] == center:
  980. return None
  981. else:
  982. return tuple(value)
  983. @staticmethod
  984. def get_params(
  985. brightness: Optional[List[float]],
  986. contrast: Optional[List[float]],
  987. saturation: Optional[List[float]],
  988. hue: Optional[List[float]],
  989. ) -> Tuple[Tensor, Optional[float], Optional[float], Optional[float], Optional[float]]:
  990. """Get the parameters for the randomized transform to be applied on image.
  991. Args:
  992. brightness (tuple of float (min, max), optional): The range from which the brightness_factor is chosen
  993. uniformly. Pass None to turn off the transformation.
  994. contrast (tuple of float (min, max), optional): The range from which the contrast_factor is chosen
  995. uniformly. Pass None to turn off the transformation.
  996. saturation (tuple of float (min, max), optional): The range from which the saturation_factor is chosen
  997. uniformly. Pass None to turn off the transformation.
  998. hue (tuple of float (min, max), optional): The range from which the hue_factor is chosen uniformly.
  999. Pass None to turn off the transformation.
  1000. Returns:
  1001. tuple: The parameters used to apply the randomized transform
  1002. along with their random order.
  1003. """
  1004. fn_idx = torch.randperm(4)
  1005. b = None if brightness is None else float(torch.empty(1).uniform_(brightness[0], brightness[1]))
  1006. c = None if contrast is None else float(torch.empty(1).uniform_(contrast[0], contrast[1]))
  1007. s = None if saturation is None else float(torch.empty(1).uniform_(saturation[0], saturation[1]))
  1008. h = None if hue is None else float(torch.empty(1).uniform_(hue[0], hue[1]))
  1009. return fn_idx, b, c, s, h
  1010. def forward(self, img):
  1011. """
  1012. Args:
  1013. img (PIL Image or Tensor): Input image.
  1014. Returns:
  1015. PIL Image or Tensor: Color jittered image.
  1016. """
  1017. fn_idx, brightness_factor, contrast_factor, saturation_factor, hue_factor = self.get_params(
  1018. self.brightness, self.contrast, self.saturation, self.hue
  1019. )
  1020. for fn_id in fn_idx:
  1021. if fn_id == 0 and brightness_factor is not None:
  1022. img = F.adjust_brightness(img, brightness_factor)
  1023. elif fn_id == 1 and contrast_factor is not None:
  1024. img = F.adjust_contrast(img, contrast_factor)
  1025. elif fn_id == 2 and saturation_factor is not None:
  1026. img = F.adjust_saturation(img, saturation_factor)
  1027. elif fn_id == 3 and hue_factor is not None:
  1028. img = F.adjust_hue(img, hue_factor)
  1029. return img
  1030. def __repr__(self) -> str:
  1031. s = (
  1032. f"{self.__class__.__name__}("
  1033. f"brightness={self.brightness}"
  1034. f", contrast={self.contrast}"
  1035. f", saturation={self.saturation}"
  1036. f", hue={self.hue})"
  1037. )
  1038. return s
  1039. class RandomRotation(torch.nn.Module):
  1040. """Rotate the image by angle.
  1041. If the image is torch Tensor, it is expected
  1042. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
  1043. Args:
  1044. degrees (sequence or number): Range of degrees to select from.
  1045. If degrees is a number instead of sequence like (min, max), the range of degrees
  1046. will be (-degrees, +degrees).
  1047. interpolation (InterpolationMode): Desired interpolation enum defined by
  1048. :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
  1049. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
  1050. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  1051. expand (bool, optional): Optional expansion flag.
  1052. If true, expands the output to make it large enough to hold the entire rotated image.
  1053. If false or omitted, make the output image the same size as the input image.
  1054. Note that the expand flag assumes rotation around the center and no translation.
  1055. center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner.
  1056. Default is the center of the image.
  1057. fill (sequence or number): Pixel fill value for the area outside the rotated
  1058. image. Default is ``0``. If given a number, the value is used for all bands respectively.
  1059. .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
  1060. """
  1061. def __init__(self, degrees, interpolation=InterpolationMode.NEAREST, expand=False, center=None, fill=0):
  1062. super().__init__()
  1063. _log_api_usage_once(self)
  1064. if isinstance(interpolation, int):
  1065. interpolation = _interpolation_modes_from_int(interpolation)
  1066. self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,))
  1067. if center is not None:
  1068. _check_sequence_input(center, "center", req_sizes=(2,))
  1069. self.center = center
  1070. self.interpolation = interpolation
  1071. self.expand = expand
  1072. if fill is None:
  1073. fill = 0
  1074. elif not isinstance(fill, (Sequence, numbers.Number)):
  1075. raise TypeError("Fill should be either a sequence or a number.")
  1076. self.fill = fill
  1077. @staticmethod
  1078. def get_params(degrees: List[float]) -> float:
  1079. """Get parameters for ``rotate`` for a random rotation.
  1080. Returns:
  1081. float: angle parameter to be passed to ``rotate`` for random rotation.
  1082. """
  1083. angle = float(torch.empty(1).uniform_(float(degrees[0]), float(degrees[1])).item())
  1084. return angle
  1085. def forward(self, img):
  1086. """
  1087. Args:
  1088. img (PIL Image or Tensor): Image to be rotated.
  1089. Returns:
  1090. PIL Image or Tensor: Rotated image.
  1091. """
  1092. fill = self.fill
  1093. channels, _, _ = F.get_dimensions(img)
  1094. if isinstance(img, Tensor):
  1095. if isinstance(fill, (int, float)):
  1096. fill = [float(fill)] * channels
  1097. else:
  1098. fill = [float(f) for f in fill]
  1099. angle = self.get_params(self.degrees)
  1100. return F.rotate(img, angle, self.interpolation, self.expand, self.center, fill)
  1101. def __repr__(self) -> str:
  1102. interpolate_str = self.interpolation.value
  1103. format_string = self.__class__.__name__ + f"(degrees={self.degrees}"
  1104. format_string += f", interpolation={interpolate_str}"
  1105. format_string += f", expand={self.expand}"
  1106. if self.center is not None:
  1107. format_string += f", center={self.center}"
  1108. if self.fill is not None:
  1109. format_string += f", fill={self.fill}"
  1110. format_string += ")"
  1111. return format_string
  1112. class RandomAffine(torch.nn.Module):
  1113. """Random affine transformation of the image keeping center invariant.
  1114. If the image is torch Tensor, it is expected
  1115. to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
  1116. Args:
  1117. degrees (sequence or number): Range of degrees to select from.
  1118. If degrees is a number instead of sequence like (min, max), the range of degrees
  1119. will be (-degrees, +degrees). Set to 0 to deactivate rotations.
  1120. translate (tuple, optional): tuple of maximum absolute fraction for horizontal
  1121. and vertical translations. For example translate=(a, b), then horizontal shift
  1122. is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
  1123. randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
  1124. scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
  1125. randomly sampled from the range a <= scale <= b. Will keep original scale by default.
  1126. shear (sequence or number, optional): Range of degrees to select from.
  1127. If shear is a number, a shear parallel to the x-axis in the range (-shear, +shear)
  1128. will be applied. Else if shear is a sequence of 2 values a shear parallel to the x-axis in the
  1129. range (shear[0], shear[1]) will be applied. Else if shear is a sequence of 4 values,
  1130. an x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.
  1131. Will not apply shear by default.
  1132. interpolation (InterpolationMode): Desired interpolation enum defined by
  1133. :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
  1134. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
  1135. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  1136. fill (sequence or number): Pixel fill value for the area outside the transformed
  1137. image. Default is ``0``. If given a number, the value is used for all bands respectively.
  1138. center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner.
  1139. Default is the center of the image.
  1140. .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
  1141. """
  1142. def __init__(
  1143. self,
  1144. degrees,
  1145. translate=None,
  1146. scale=None,
  1147. shear=None,
  1148. interpolation=InterpolationMode.NEAREST,
  1149. fill=0,
  1150. center=None,
  1151. ):
  1152. super().__init__()
  1153. _log_api_usage_once(self)
  1154. if isinstance(interpolation, int):
  1155. interpolation = _interpolation_modes_from_int(interpolation)
  1156. self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,))
  1157. if translate is not None:
  1158. _check_sequence_input(translate, "translate", req_sizes=(2,))
  1159. for t in translate:
  1160. if not (0.0 <= t <= 1.0):
  1161. raise ValueError("translation values should be between 0 and 1")
  1162. self.translate = translate
  1163. if scale is not None:
  1164. _check_sequence_input(scale, "scale", req_sizes=(2,))
  1165. for s in scale:
  1166. if s <= 0:
  1167. raise ValueError("scale values should be positive")
  1168. self.scale = scale
  1169. if shear is not None:
  1170. self.shear = _setup_angle(shear, name="shear", req_sizes=(2, 4))
  1171. else:
  1172. self.shear = shear
  1173. self.interpolation = interpolation
  1174. if fill is None:
  1175. fill = 0
  1176. elif not isinstance(fill, (Sequence, numbers.Number)):
  1177. raise TypeError("Fill should be either a sequence or a number.")
  1178. self.fill = fill
  1179. if center is not None:
  1180. _check_sequence_input(center, "center", req_sizes=(2,))
  1181. self.center = center
  1182. @staticmethod
  1183. def get_params(
  1184. degrees: List[float],
  1185. translate: Optional[List[float]],
  1186. scale_ranges: Optional[List[float]],
  1187. shears: Optional[List[float]],
  1188. img_size: List[int],
  1189. ) -> Tuple[float, Tuple[int, int], float, Tuple[float, float]]:
  1190. """Get parameters for affine transformation
  1191. Returns:
  1192. params to be passed to the affine transformation
  1193. """
  1194. angle = float(torch.empty(1).uniform_(float(degrees[0]), float(degrees[1])).item())
  1195. if translate is not None:
  1196. max_dx = float(translate[0] * img_size[0])
  1197. max_dy = float(translate[1] * img_size[1])
  1198. tx = int(round(torch.empty(1).uniform_(-max_dx, max_dx).item()))
  1199. ty = int(round(torch.empty(1).uniform_(-max_dy, max_dy).item()))
  1200. translations = (tx, ty)
  1201. else:
  1202. translations = (0, 0)
  1203. if scale_ranges is not None:
  1204. scale = float(torch.empty(1).uniform_(scale_ranges[0], scale_ranges[1]).item())
  1205. else:
  1206. scale = 1.0
  1207. shear_x = shear_y = 0.0
  1208. if shears is not None:
  1209. shear_x = float(torch.empty(1).uniform_(shears[0], shears[1]).item())
  1210. if len(shears) == 4:
  1211. shear_y = float(torch.empty(1).uniform_(shears[2], shears[3]).item())
  1212. shear = (shear_x, shear_y)
  1213. return angle, translations, scale, shear
  1214. def forward(self, img):
  1215. """
  1216. img (PIL Image or Tensor): Image to be transformed.
  1217. Returns:
  1218. PIL Image or Tensor: Affine transformed image.
  1219. """
  1220. fill = self.fill
  1221. channels, height, width = F.get_dimensions(img)
  1222. if isinstance(img, Tensor):
  1223. if isinstance(fill, (int, float)):
  1224. fill = [float(fill)] * channels
  1225. else:
  1226. fill = [float(f) for f in fill]
  1227. img_size = [width, height] # flip for keeping BC on get_params call
  1228. ret = self.get_params(self.degrees, self.translate, self.scale, self.shear, img_size)
  1229. return F.affine(img, *ret, interpolation=self.interpolation, fill=fill, center=self.center)
  1230. def __repr__(self) -> str:
  1231. s = f"{self.__class__.__name__}(degrees={self.degrees}"
  1232. s += f", translate={self.translate}" if self.translate is not None else ""
  1233. s += f", scale={self.scale}" if self.scale is not None else ""
  1234. s += f", shear={self.shear}" if self.shear is not None else ""
  1235. s += f", interpolation={self.interpolation.value}" if self.interpolation != InterpolationMode.NEAREST else ""
  1236. s += f", fill={self.fill}" if self.fill != 0 else ""
  1237. s += f", center={self.center}" if self.center is not None else ""
  1238. s += ")"
  1239. return s
  1240. class Grayscale(torch.nn.Module):
  1241. """Convert image to grayscale.
  1242. If the image is torch Tensor, it is expected
  1243. to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions
  1244. Args:
  1245. num_output_channels (int): (1 or 3) number of channels desired for output image
  1246. Returns:
  1247. PIL Image: Grayscale version of the input.
  1248. - If ``num_output_channels == 1`` : returned image is single channel
  1249. - If ``num_output_channels == 3`` : returned image is 3 channel with r == g == b
  1250. """
  1251. def __init__(self, num_output_channels=1):
  1252. super().__init__()
  1253. _log_api_usage_once(self)
  1254. self.num_output_channels = num_output_channels
  1255. def forward(self, img):
  1256. """
  1257. Args:
  1258. img (PIL Image or Tensor): Image to be converted to grayscale.
  1259. Returns:
  1260. PIL Image or Tensor: Grayscaled image.
  1261. """
  1262. return F.rgb_to_grayscale(img, num_output_channels=self.num_output_channels)
  1263. def __repr__(self) -> str:
  1264. return f"{self.__class__.__name__}(num_output_channels={self.num_output_channels})"
  1265. class RandomGrayscale(torch.nn.Module):
  1266. """Randomly convert image to grayscale with a probability of p (default 0.1).
  1267. If the image is torch Tensor, it is expected
  1268. to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions
  1269. Args:
  1270. p (float): probability that image should be converted to grayscale.
  1271. Returns:
  1272. PIL Image or Tensor: Grayscale version of the input image with probability p and unchanged
  1273. with probability (1-p).
  1274. - If input image is 1 channel: grayscale version is 1 channel
  1275. - If input image is 3 channel: grayscale version is 3 channel with r == g == b
  1276. """
  1277. def __init__(self, p=0.1):
  1278. super().__init__()
  1279. _log_api_usage_once(self)
  1280. self.p = p
  1281. def forward(self, img):
  1282. """
  1283. Args:
  1284. img (PIL Image or Tensor): Image to be converted to grayscale.
  1285. Returns:
  1286. PIL Image or Tensor: Randomly grayscaled image.
  1287. """
  1288. num_output_channels, _, _ = F.get_dimensions(img)
  1289. if torch.rand(1) < self.p:
  1290. return F.rgb_to_grayscale(img, num_output_channels=num_output_channels)
  1291. return img
  1292. def __repr__(self) -> str:
  1293. return f"{self.__class__.__name__}(p={self.p})"
  1294. class RandomErasing(torch.nn.Module):
  1295. """Randomly selects a rectangle region in a torch.Tensor image and erases its pixels.
  1296. This transform does not support PIL Image.
  1297. 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/abs/1708.04896
  1298. Args:
  1299. p: probability that the random erasing operation will be performed.
  1300. scale: range of proportion of erased area against input image.
  1301. ratio: range of aspect ratio of erased area.
  1302. value: erasing value. Default is 0. If a single int, it is used to
  1303. erase all pixels. If a tuple of length 3, it is used to erase
  1304. R, G, B channels respectively.
  1305. If a str of 'random', erasing each pixel with random values.
  1306. inplace: boolean to make this transform inplace. Default set to False.
  1307. Returns:
  1308. Erased Image.
  1309. Example:
  1310. >>> transform = transforms.Compose([
  1311. >>> transforms.RandomHorizontalFlip(),
  1312. >>> transforms.PILToTensor(),
  1313. >>> transforms.ConvertImageDtype(torch.float),
  1314. >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
  1315. >>> transforms.RandomErasing(),
  1316. >>> ])
  1317. """
  1318. def __init__(self, p=0.5, scale=(0.02, 0.33), ratio=(0.3, 3.3), value=0, inplace=False):
  1319. super().__init__()
  1320. _log_api_usage_once(self)
  1321. if not isinstance(value, (numbers.Number, str, tuple, list)):
  1322. raise TypeError("Argument value should be either a number or str or a sequence")
  1323. if isinstance(value, str) and value != "random":
  1324. raise ValueError("If value is str, it should be 'random'")
  1325. if not isinstance(scale, (tuple, list)):
  1326. raise TypeError("Scale should be a sequence")
  1327. if not isinstance(ratio, (tuple, list)):
  1328. raise TypeError("Ratio should be a sequence")
  1329. if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
  1330. warnings.warn("Scale and ratio should be of kind (min, max)")
  1331. if scale[0] < 0 or scale[1] > 1:
  1332. raise ValueError("Scale should be between 0 and 1")
  1333. if p < 0 or p > 1:
  1334. raise ValueError("Random erasing probability should be between 0 and 1")
  1335. self.p = p
  1336. self.scale = scale
  1337. self.ratio = ratio
  1338. self.value = value
  1339. self.inplace = inplace
  1340. @staticmethod
  1341. def get_params(
  1342. img: Tensor, scale: Tuple[float, float], ratio: Tuple[float, float], value: Optional[List[float]] = None
  1343. ) -> Tuple[int, int, int, int, Tensor]:
  1344. """Get parameters for ``erase`` for a random erasing.
  1345. Args:
  1346. img (Tensor): Tensor image to be erased.
  1347. scale (sequence): range of proportion of erased area against input image.
  1348. ratio (sequence): range of aspect ratio of erased area.
  1349. value (list, optional): erasing value. If None, it is interpreted as "random"
  1350. (erasing each pixel with random values). If ``len(value)`` is 1, it is interpreted as a number,
  1351. i.e. ``value[0]``.
  1352. Returns:
  1353. tuple: params (i, j, h, w, v) to be passed to ``erase`` for random erasing.
  1354. """
  1355. img_c, img_h, img_w = img.shape[-3], img.shape[-2], img.shape[-1]
  1356. area = img_h * img_w
  1357. log_ratio = torch.log(torch.tensor(ratio))
  1358. for _ in range(10):
  1359. erase_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item()
  1360. aspect_ratio = torch.exp(torch.empty(1).uniform_(log_ratio[0], log_ratio[1])).item()
  1361. h = int(round(math.sqrt(erase_area * aspect_ratio)))
  1362. w = int(round(math.sqrt(erase_area / aspect_ratio)))
  1363. if not (h < img_h and w < img_w):
  1364. continue
  1365. if value is None:
  1366. v = torch.empty([img_c, h, w], dtype=torch.float32).normal_()
  1367. else:
  1368. v = torch.tensor(value)[:, None, None]
  1369. i = torch.randint(0, img_h - h + 1, size=(1,)).item()
  1370. j = torch.randint(0, img_w - w + 1, size=(1,)).item()
  1371. return i, j, h, w, v
  1372. # Return original image
  1373. return 0, 0, img_h, img_w, img
  1374. def forward(self, img):
  1375. """
  1376. Args:
  1377. img (Tensor): Tensor image to be erased.
  1378. Returns:
  1379. img (Tensor): Erased Tensor image.
  1380. """
  1381. if torch.rand(1) < self.p:
  1382. # cast self.value to script acceptable type
  1383. if isinstance(self.value, (int, float)):
  1384. value = [float(self.value)]
  1385. elif isinstance(self.value, str):
  1386. value = None
  1387. elif isinstance(self.value, (list, tuple)):
  1388. value = [float(v) for v in self.value]
  1389. else:
  1390. value = self.value
  1391. if value is not None and not (len(value) in (1, img.shape[-3])):
  1392. raise ValueError(
  1393. "If value is a sequence, it should have either a single value or "
  1394. f"{img.shape[-3]} (number of input channels)"
  1395. )
  1396. x, y, h, w, v = self.get_params(img, scale=self.scale, ratio=self.ratio, value=value)
  1397. return F.erase(img, x, y, h, w, v, self.inplace)
  1398. return img
  1399. def __repr__(self) -> str:
  1400. s = (
  1401. f"{self.__class__.__name__}"
  1402. f"(p={self.p}, "
  1403. f"scale={self.scale}, "
  1404. f"ratio={self.ratio}, "
  1405. f"value={self.value}, "
  1406. f"inplace={self.inplace})"
  1407. )
  1408. return s
  1409. class GaussianBlur(torch.nn.Module):
  1410. """Blurs image with randomly chosen Gaussian blur.
  1411. If the image is torch Tensor, it is expected
  1412. to have [..., C, H, W] shape, where ... means at most one leading dimension.
  1413. Args:
  1414. kernel_size (int or sequence): Size of the Gaussian kernel.
  1415. sigma (float or tuple of float (min, max)): Standard deviation to be used for
  1416. creating kernel to perform blurring. If float, sigma is fixed. If it is tuple
  1417. of float (min, max), sigma is chosen uniformly at random to lie in the
  1418. given range.
  1419. Returns:
  1420. PIL Image or Tensor: Gaussian blurred version of the input image.
  1421. """
  1422. def __init__(self, kernel_size, sigma=(0.1, 2.0)):
  1423. super().__init__()
  1424. _log_api_usage_once(self)
  1425. self.kernel_size = _setup_size(kernel_size, "Kernel size should be a tuple/list of two integers")
  1426. for ks in self.kernel_size:
  1427. if ks <= 0 or ks % 2 == 0:
  1428. raise ValueError("Kernel size value should be an odd and positive number.")
  1429. if isinstance(sigma, numbers.Number):
  1430. if sigma <= 0:
  1431. raise ValueError("If sigma is a single number, it must be positive.")
  1432. sigma = (sigma, sigma)
  1433. elif isinstance(sigma, Sequence) and len(sigma) == 2:
  1434. if not 0.0 < sigma[0] <= sigma[1]:
  1435. raise ValueError("sigma values should be positive and of the form (min, max).")
  1436. else:
  1437. raise ValueError("sigma should be a single number or a list/tuple with length 2.")
  1438. self.sigma = sigma
  1439. @staticmethod
  1440. def get_params(sigma_min: float, sigma_max: float) -> float:
  1441. """Choose sigma for random gaussian blurring.
  1442. Args:
  1443. sigma_min (float): Minimum standard deviation that can be chosen for blurring kernel.
  1444. sigma_max (float): Maximum standard deviation that can be chosen for blurring kernel.
  1445. Returns:
  1446. float: Standard deviation to be passed to calculate kernel for gaussian blurring.
  1447. """
  1448. return torch.empty(1).uniform_(sigma_min, sigma_max).item()
  1449. def forward(self, img: Tensor) -> Tensor:
  1450. """
  1451. Args:
  1452. img (PIL Image or Tensor): image to be blurred.
  1453. Returns:
  1454. PIL Image or Tensor: Gaussian blurred image
  1455. """
  1456. sigma = self.get_params(self.sigma[0], self.sigma[1])
  1457. return F.gaussian_blur(img, self.kernel_size, [sigma, sigma])
  1458. def __repr__(self) -> str:
  1459. s = f"{self.__class__.__name__}(kernel_size={self.kernel_size}, sigma={self.sigma})"
  1460. return s
  1461. def _setup_size(size, error_msg):
  1462. if isinstance(size, numbers.Number):
  1463. return int(size), int(size)
  1464. if isinstance(size, Sequence) and len(size) == 1:
  1465. return size[0], size[0]
  1466. if len(size) != 2:
  1467. raise ValueError(error_msg)
  1468. return size
  1469. def _check_sequence_input(x, name, req_sizes):
  1470. msg = req_sizes[0] if len(req_sizes) < 2 else " or ".join([str(s) for s in req_sizes])
  1471. if not isinstance(x, Sequence):
  1472. raise TypeError(f"{name} should be a sequence of length {msg}.")
  1473. if len(x) not in req_sizes:
  1474. raise ValueError(f"{name} should be a sequence of length {msg}.")
  1475. def _setup_angle(x, name, req_sizes=(2,)):
  1476. if isinstance(x, numbers.Number):
  1477. if x < 0:
  1478. raise ValueError(f"If {name} is a single number, it must be positive.")
  1479. x = [-x, x]
  1480. else:
  1481. _check_sequence_input(x, name, req_sizes)
  1482. return [float(d) for d in x]
  1483. class RandomInvert(torch.nn.Module):
  1484. """Inverts the colors of the given image randomly with a given probability.
  1485. If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  1486. where ... means it can have an arbitrary number of leading dimensions.
  1487. If img is PIL Image, it is expected to be in mode "L" or "RGB".
  1488. Args:
  1489. p (float): probability of the image being color inverted. Default value is 0.5
  1490. """
  1491. def __init__(self, p=0.5):
  1492. super().__init__()
  1493. _log_api_usage_once(self)
  1494. self.p = p
  1495. def forward(self, img):
  1496. """
  1497. Args:
  1498. img (PIL Image or Tensor): Image to be inverted.
  1499. Returns:
  1500. PIL Image or Tensor: Randomly color inverted image.
  1501. """
  1502. if torch.rand(1).item() < self.p:
  1503. return F.invert(img)
  1504. return img
  1505. def __repr__(self) -> str:
  1506. return f"{self.__class__.__name__}(p={self.p})"
  1507. class RandomPosterize(torch.nn.Module):
  1508. """Posterize the image randomly with a given probability by reducing the
  1509. number of bits for each color channel. If the image is torch Tensor, it should be of type torch.uint8,
  1510. and it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
  1511. If img is PIL Image, it is expected to be in mode "L" or "RGB".
  1512. Args:
  1513. bits (int): number of bits to keep for each channel (0-8)
  1514. p (float): probability of the image being posterized. Default value is 0.5
  1515. """
  1516. def __init__(self, bits, p=0.5):
  1517. super().__init__()
  1518. _log_api_usage_once(self)
  1519. self.bits = bits
  1520. self.p = p
  1521. def forward(self, img):
  1522. """
  1523. Args:
  1524. img (PIL Image or Tensor): Image to be posterized.
  1525. Returns:
  1526. PIL Image or Tensor: Randomly posterized image.
  1527. """
  1528. if torch.rand(1).item() < self.p:
  1529. return F.posterize(img, self.bits)
  1530. return img
  1531. def __repr__(self) -> str:
  1532. return f"{self.__class__.__name__}(bits={self.bits},p={self.p})"
  1533. class RandomSolarize(torch.nn.Module):
  1534. """Solarize the image randomly with a given probability by inverting all pixel
  1535. values above a threshold. If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format,
  1536. where ... means it can have an arbitrary number of leading dimensions.
  1537. If img is PIL Image, it is expected to be in mode "L" or "RGB".
  1538. Args:
  1539. threshold (float): all pixels equal or above this value are inverted.
  1540. p (float): probability of the image being solarized. Default value is 0.5
  1541. """
  1542. def __init__(self, threshold, p=0.5):
  1543. super().__init__()
  1544. _log_api_usage_once(self)
  1545. self.threshold = threshold
  1546. self.p = p
  1547. def forward(self, img):
  1548. """
  1549. Args:
  1550. img (PIL Image or Tensor): Image to be solarized.
  1551. Returns:
  1552. PIL Image or Tensor: Randomly solarized image.
  1553. """
  1554. if torch.rand(1).item() < self.p:
  1555. return F.solarize(img, self.threshold)
  1556. return img
  1557. def __repr__(self) -> str:
  1558. return f"{self.__class__.__name__}(threshold={self.threshold},p={self.p})"
  1559. class RandomAdjustSharpness(torch.nn.Module):
  1560. """Adjust the sharpness of the image randomly with a given probability. If the image is torch Tensor,
  1561. it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
  1562. Args:
  1563. sharpness_factor (float): How much to adjust the sharpness. Can be
  1564. any non-negative number. 0 gives a blurred image, 1 gives the
  1565. original image while 2 increases the sharpness by a factor of 2.
  1566. p (float): probability of the image being sharpened. Default value is 0.5
  1567. """
  1568. def __init__(self, sharpness_factor, p=0.5):
  1569. super().__init__()
  1570. _log_api_usage_once(self)
  1571. self.sharpness_factor = sharpness_factor
  1572. self.p = p
  1573. def forward(self, img):
  1574. """
  1575. Args:
  1576. img (PIL Image or Tensor): Image to be sharpened.
  1577. Returns:
  1578. PIL Image or Tensor: Randomly sharpened image.
  1579. """
  1580. if torch.rand(1).item() < self.p:
  1581. return F.adjust_sharpness(img, self.sharpness_factor)
  1582. return img
  1583. def __repr__(self) -> str:
  1584. return f"{self.__class__.__name__}(sharpness_factor={self.sharpness_factor},p={self.p})"
  1585. class RandomAutocontrast(torch.nn.Module):
  1586. """Autocontrast the pixels of the given image randomly with a given probability.
  1587. If the image is torch Tensor, it is expected
  1588. to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
  1589. If img is PIL Image, it is expected to be in mode "L" or "RGB".
  1590. Args:
  1591. p (float): probability of the image being autocontrasted. Default value is 0.5
  1592. """
  1593. def __init__(self, p=0.5):
  1594. super().__init__()
  1595. _log_api_usage_once(self)
  1596. self.p = p
  1597. def forward(self, img):
  1598. """
  1599. Args:
  1600. img (PIL Image or Tensor): Image to be autocontrasted.
  1601. Returns:
  1602. PIL Image or Tensor: Randomly autocontrasted image.
  1603. """
  1604. if torch.rand(1).item() < self.p:
  1605. return F.autocontrast(img)
  1606. return img
  1607. def __repr__(self) -> str:
  1608. return f"{self.__class__.__name__}(p={self.p})"
  1609. class RandomEqualize(torch.nn.Module):
  1610. """Equalize the histogram of the given image randomly with a given probability.
  1611. If the image is torch Tensor, it is expected
  1612. to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
  1613. If img is PIL Image, it is expected to be in mode "P", "L" or "RGB".
  1614. Args:
  1615. p (float): probability of the image being equalized. Default value is 0.5
  1616. """
  1617. def __init__(self, p=0.5):
  1618. super().__init__()
  1619. _log_api_usage_once(self)
  1620. self.p = p
  1621. def forward(self, img):
  1622. """
  1623. Args:
  1624. img (PIL Image or Tensor): Image to be equalized.
  1625. Returns:
  1626. PIL Image or Tensor: Randomly equalized image.
  1627. """
  1628. if torch.rand(1).item() < self.p:
  1629. return F.equalize(img)
  1630. return img
  1631. def __repr__(self) -> str:
  1632. return f"{self.__class__.__name__}(p={self.p})"
  1633. class ElasticTransform(torch.nn.Module):
  1634. """Transform a tensor image with elastic transformations.
  1635. Given alpha and sigma, it will generate displacement
  1636. vectors for all pixels based on random offsets. Alpha controls the strength
  1637. and sigma controls the smoothness of the displacements.
  1638. The displacements are added to an identity grid and the resulting grid is
  1639. used to grid_sample from the image.
  1640. Applications:
  1641. Randomly transforms the morphology of objects in images and produces a
  1642. see-through-water-like effect.
  1643. Args:
  1644. alpha (float or sequence of floats): Magnitude of displacements. Default is 50.0.
  1645. sigma (float or sequence of floats): Smoothness of displacements. Default is 5.0.
  1646. interpolation (InterpolationMode): Desired interpolation enum defined by
  1647. :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
  1648. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
  1649. The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
  1650. fill (sequence or number): Pixel fill value for the area outside the transformed
  1651. image. Default is ``0``. If given a number, the value is used for all bands respectively.
  1652. """
  1653. def __init__(self, alpha=50.0, sigma=5.0, interpolation=InterpolationMode.BILINEAR, fill=0):
  1654. super().__init__()
  1655. _log_api_usage_once(self)
  1656. if not isinstance(alpha, (float, Sequence)):
  1657. raise TypeError(f"alpha should be float or a sequence of floats. Got {type(alpha)}")
  1658. if isinstance(alpha, Sequence) and len(alpha) != 2:
  1659. raise ValueError(f"If alpha is a sequence its length should be 2. Got {len(alpha)}")
  1660. if isinstance(alpha, Sequence):
  1661. for element in alpha:
  1662. if not isinstance(element, float):
  1663. raise TypeError(f"alpha should be a sequence of floats. Got {type(element)}")
  1664. if isinstance(alpha, float):
  1665. alpha = [float(alpha), float(alpha)]
  1666. if isinstance(alpha, (list, tuple)) and len(alpha) == 1:
  1667. alpha = [alpha[0], alpha[0]]
  1668. self.alpha = alpha
  1669. if not isinstance(sigma, (float, Sequence)):
  1670. raise TypeError(f"sigma should be float or a sequence of floats. Got {type(sigma)}")
  1671. if isinstance(sigma, Sequence) and len(sigma) != 2:
  1672. raise ValueError(f"If sigma is a sequence its length should be 2. Got {len(sigma)}")
  1673. if isinstance(sigma, Sequence):
  1674. for element in sigma:
  1675. if not isinstance(element, float):
  1676. raise TypeError(f"sigma should be a sequence of floats. Got {type(element)}")
  1677. if isinstance(sigma, float):
  1678. sigma = [float(sigma), float(sigma)]
  1679. if isinstance(sigma, (list, tuple)) and len(sigma) == 1:
  1680. sigma = [sigma[0], sigma[0]]
  1681. self.sigma = sigma
  1682. if isinstance(interpolation, int):
  1683. interpolation = _interpolation_modes_from_int(interpolation)
  1684. self.interpolation = interpolation
  1685. if isinstance(fill, (int, float)):
  1686. fill = [float(fill)]
  1687. elif isinstance(fill, (list, tuple)):
  1688. fill = [float(f) for f in fill]
  1689. else:
  1690. raise TypeError(f"fill should be int or float or a list or tuple of them. Got {type(fill)}")
  1691. self.fill = fill
  1692. @staticmethod
  1693. def get_params(alpha: List[float], sigma: List[float], size: List[int]) -> Tensor:
  1694. dx = torch.rand([1, 1] + size) * 2 - 1
  1695. if sigma[0] > 0.0:
  1696. kx = int(8 * sigma[0] + 1)
  1697. # if kernel size is even we have to make it odd
  1698. if kx % 2 == 0:
  1699. kx += 1
  1700. dx = F.gaussian_blur(dx, [kx, kx], sigma)
  1701. dx = dx * alpha[0] / size[0]
  1702. dy = torch.rand([1, 1] + size) * 2 - 1
  1703. if sigma[1] > 0.0:
  1704. ky = int(8 * sigma[1] + 1)
  1705. # if kernel size is even we have to make it odd
  1706. if ky % 2 == 0:
  1707. ky += 1
  1708. dy = F.gaussian_blur(dy, [ky, ky], sigma)
  1709. dy = dy * alpha[1] / size[1]
  1710. return torch.concat([dx, dy], 1).permute([0, 2, 3, 1]) # 1 x H x W x 2
  1711. def forward(self, tensor: Tensor) -> Tensor:
  1712. """
  1713. Args:
  1714. tensor (PIL Image or Tensor): Image to be transformed.
  1715. Returns:
  1716. PIL Image or Tensor: Transformed image.
  1717. """
  1718. _, height, width = F.get_dimensions(tensor)
  1719. displacement = self.get_params(self.alpha, self.sigma, [height, width])
  1720. return F.elastic_transform(tensor, displacement, self.interpolation, self.fill)
  1721. def __repr__(self):
  1722. format_string = self.__class__.__name__
  1723. format_string += f"(alpha={self.alpha}"
  1724. format_string += f", sigma={self.sigma}"
  1725. format_string += f", interpolation={self.interpolation}"
  1726. format_string += f", fill={self.fill})"
  1727. return format_string