transforms.py 84 KB

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