You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

transforms.py 56 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475
  1. # A synchronized version modified from https://github.com/pytorch/vision
  2. from __future__ import division
  3. import torch
  4. import math
  5. import sys
  6. import random
  7. from PIL import Image
  8. try:
  9. import accimage
  10. except ImportError:
  11. accimage = None
  12. import numpy as np
  13. import numbers
  14. import types
  15. import collections
  16. import warnings
  17. import typing
  18. from . import functional as F
  19. if sys.version_info < (3, 3):
  20. Sequence = collections.Sequence
  21. Iterable = collections.Iterable
  22. else:
  23. Sequence = collections.abc.Sequence
  24. Iterable = collections.abc.Iterable
  25. __all__ = [ "Sync", "Multi","Compose", "ToTensor", "ToPILImage", "Normalize", "Resize", "Scale", "CenterCrop", "Pad",
  26. "Lambda", "RandomApply", "RandomChoice", "RandomOrder", "RandomCrop", "RandomHorizontalFlip",
  27. "RandomVerticalFlip", "RandomResizedCrop", "RandomSizedCrop", "FiveCrop", "TenCrop", "LinearTransformation",
  28. "ColorJitter", "RandomRotation", "RandomAffine", "Grayscale", "RandomGrayscale",
  29. "RandomPerspective", "FlipChannels", "RandomErasing", "ToRGB", "ToGRAY"]
  30. _pil_interpolation_to_str = {
  31. Image.NEAREST: 'PIL.Image.NEAREST',
  32. Image.BILINEAR: 'PIL.Image.BILINEAR',
  33. Image.BICUBIC: 'PIL.Image.BICUBIC',
  34. Image.LANCZOS: 'PIL.Image.LANCZOS',
  35. Image.HAMMING: 'PIL.Image.HAMMING',
  36. Image.BOX: 'PIL.Image.BOX',
  37. }
  38. class Sync(object):
  39. def __init__(self, *transforms):
  40. self.transforms = transforms
  41. def __call__(self, *inputs):
  42. shared_params = None
  43. outputs = []
  44. if len(self.transforms)==1:
  45. for input in inputs:
  46. out, shared_params = self.transforms[0](input, params=shared_params, return_params=True)
  47. outputs.append( out )
  48. else:
  49. assert len(inputs) == len(self.transforms), \
  50. "Expected %d inputs, but got %d"%( len(self.transforms), len(inputs) )
  51. for (input, trans) in zip( inputs, self.transforms ):
  52. out, shared_params = trans(input, params=shared_params, return_params=True)
  53. outputs.append( out )
  54. return outputs
  55. def _format_transform_repr(self, transform, head):
  56. lines = transform.__repr__().splitlines()
  57. return (["{}{}".format(head, lines[0])] +
  58. ["{}{}".format(" " * len(head), line) for line in lines[1:]])
  59. def __repr__(self):
  60. body = [self.__class__.__name__]
  61. for transform in self.transforms:
  62. body += self._format_transform_repr(transform, "Transform: ")
  63. return '\n'.join(body)
  64. class Multi(object):
  65. def __init__(self, *transforms):
  66. self.transforms = transforms
  67. def __call__(self, *inputs):
  68. if len(self.transforms)==1:
  69. outputs = [ self.transforms[0](input) for input in inputs ]
  70. else:
  71. assert len(inputs) == len(self.transforms), \
  72. "Expected %d inputs, but got %d"%( len(self.transforms), len(inputs) )
  73. outputs = []
  74. for (input, trans) in zip( inputs, self.transforms ):
  75. outputs.append( trans(input) if trans is not None else input )
  76. return outputs
  77. def _format_transform_repr(self, transform, head):
  78. lines = transform.__repr__().splitlines()
  79. return (["{}{}".format(head, lines[0])] +
  80. ["{}{}".format(" " * len(head), line) for line in lines[1:]])
  81. def __repr__(self):
  82. body = [self.__class__.__name__]
  83. for transform in self.transforms:
  84. body += self._format_transform_repr(transform, "Transform: ")
  85. return '\n'.join(body)
  86. class Compose(object):
  87. """Composes several transforms together.
  88. Args:
  89. transforms (list of ``Transform`` objects): list of transforms to compose.
  90. Example:
  91. >>> transforms.Compose([
  92. >>> transforms.CenterCrop(10),
  93. >>> transforms.ToTensor(),
  94. >>> ])
  95. """
  96. def __init__(self, transforms):
  97. self.transforms = []
  98. for t in transforms:
  99. if isinstance( t, typing.Sequence ):
  100. self.transforms.append( Multi( t ) )
  101. else:
  102. self.transforms.append(t)
  103. def __call__(self, *imgs):
  104. if len(imgs)==1:
  105. imgs = imgs[0]
  106. for t in self.transforms:
  107. imgs = t(imgs)
  108. return imgs
  109. else:
  110. for t in self.transforms:
  111. imgs = t(*imgs)
  112. return imgs
  113. def __repr__(self):
  114. format_string = self.__class__.__name__ + '('
  115. for t in self.transforms:
  116. format_string += '\n'
  117. format_string += ' {0}'.format(t)
  118. format_string += '\n)'
  119. return format_string
  120. class ToTensor(object):
  121. """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
  122. Converts a PIL Image or numpy.ndarray (H x W x C) in the range
  123. [0, 255] to a torch.FloatTensor of shape (C x H x W).
  124. This class is identical to torchvision.transforms.ToTensor if normalize=True.
  125. If normalize=False, tensors of type dtype will be returned without scaling.
  126. """
  127. def __init__(self, normalize=True, dtype=None):
  128. self.normalize=normalize
  129. self.dtype=dtype
  130. def __call__(self, pic, params=None, return_params=False):
  131. """
  132. Args:
  133. pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
  134. Returns:
  135. Tensor: Converted image.
  136. """
  137. if return_params:
  138. return F.to_tensor(pic, self.normalize, self.dtype), None
  139. return F.to_tensor(pic, self.normalize, self.dtype)
  140. def __repr__(self):
  141. return self.__class__.__name__ + '(Normalize={0})'.format(self.normalize)
  142. class ToPILImage(object):
  143. """Convert a tensor or an ndarray to PIL Image.
  144. Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape
  145. H x W x C to a PIL Image while preserving the value range.
  146. Args:
  147. mode (`PIL.Image mode`_): color space and pixel depth of input data (optional).
  148. If ``mode`` is ``None`` (default) there are some assumptions made about the input data:
  149. - If the input has 4 channels, the ``mode`` is assumed to be ``RGBA``.
  150. - If the input has 3 channels, the ``mode`` is assumed to be ``RGB``.
  151. - If the input has 2 channels, the ``mode`` is assumed to be ``LA``.
  152. - If the input has 1 channel, the ``mode`` is determined by the data type (i.e ``int``, ``float``,
  153. ``short``).
  154. .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes
  155. """
  156. def __init__(self, mode=None):
  157. self.mode = mode
  158. def __call__(self, pic, params=None, return_params=False):
  159. """
  160. Args:
  161. pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
  162. Returns:
  163. PIL Image: Image converted to PIL Image.
  164. """
  165. if return_params:
  166. return F.to_pil_image(pic, self.mode), None
  167. return F.to_pil_image(pic, self.mode)
  168. def __repr__(self):
  169. format_string = self.__class__.__name__ + '('
  170. if self.mode is not None:
  171. format_string += 'mode={0}'.format(self.mode)
  172. format_string += ')'
  173. return format_string
  174. class Normalize(object):
  175. """Normalize a tensor image with mean and standard deviation.
  176. Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels, this transform
  177. will normalize each channel of the input ``torch.*Tensor`` i.e.
  178. ``input[channel] = (input[channel] - mean[channel]) / std[channel]``
  179. .. note:
  180. This transform acts out of place, i.e., it does not mutates the input tensor.
  181. Args:
  182. mean (sequence): Sequence of means for each channel.
  183. std (sequence): Sequence of standard deviations for each channel.
  184. """
  185. def __init__(self, mean, std, inplace=False):
  186. self.mean = mean
  187. self.std = std
  188. self.inplace = inplace
  189. def __call__(self, tensor, params=None, return_params=False ):
  190. """
  191. Args:
  192. tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
  193. Returns:
  194. Tensor: Normalized Tensor image.
  195. """
  196. if return_params:
  197. F.normalize(tensor, self.mean, self.std, self.inplace), None
  198. return F.normalize(tensor, self.mean, self.std, self.inplace)
  199. def __repr__(self):
  200. return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)
  201. class Resize(object):
  202. """Resize the input PIL Image to the given size.
  203. Args:
  204. size (sequence or int): Desired output size. If size is a sequence like
  205. (h, w), output size will be matched to this. If size is an int,
  206. smaller edge of the image will be matched to this number.
  207. i.e, if height > width, then image will be rescaled to
  208. (size * height / width, size)
  209. interpolation (int, optional): Desired interpolation. Default is
  210. ``PIL.Image.BILINEAR``
  211. """
  212. def __init__(self, size, interpolation=Image.BILINEAR):
  213. assert isinstance(size, int) or (isinstance(size, Iterable) and len(size) == 2)
  214. self.size = size
  215. self.interpolation = interpolation
  216. def __call__(self, img, params=None, return_params=False):
  217. """
  218. Args:
  219. img (PIL Image): Image to be scaled.
  220. Returns:
  221. PIL Image: Rescaled image.
  222. """
  223. if return_params:
  224. return F.resize(img, self.size, self.interpolation), None
  225. return F.resize(img, self.size, self.interpolation)
  226. def __repr__(self):
  227. interpolate_str = _pil_interpolation_to_str[self.interpolation]
  228. return self.__class__.__name__ + '(size={0}, interpolation={1})'.format(self.size, interpolate_str)
  229. class Scale(Resize):
  230. """
  231. Note: This transform is deprecated in favor of Resize.
  232. """
  233. def __init__(self, *args, **kwargs):
  234. warnings.warn("The use of the transforms.Scale transform is deprecated, " +
  235. "please use transforms.Resize instead.")
  236. super(Scale, self).__init__(*args, **kwargs)
  237. class CenterCrop(object):
  238. """Crops the given PIL Image at the center.
  239. Args:
  240. size (sequence or int): Desired output size of the crop. If size is an
  241. int instead of sequence like (h, w), a square crop (size, size) is
  242. made.
  243. """
  244. def __init__(self, size):
  245. if isinstance(size, numbers.Number):
  246. self.size = (int(size), int(size))
  247. else:
  248. self.size = size
  249. def __call__(self, img, params=None, return_params=False):
  250. """
  251. Args:
  252. img (PIL Image): Image to be cropped.
  253. Returns:
  254. PIL Image: Cropped image.
  255. """
  256. if return_params:
  257. return F.center_crop(img, self.size), None
  258. return F.center_crop(img, self.size)
  259. def __repr__(self):
  260. return self.__class__.__name__ + '(size={0})'.format(self.size)
  261. class Pad(object):
  262. """Pad the given PIL Image on all sides with the given "pad" value.
  263. Args:
  264. padding (int or tuple): Padding on each border. If a single int is provided this
  265. is used to pad all borders. If tuple of length 2 is provided this is the padding
  266. on left/right and top/bottom respectively. If a tuple of length 4 is provided
  267. this is the padding for the left, top, right and bottom borders
  268. respectively.
  269. fill (int or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of
  270. length 3, it is used to fill R, G, B channels respectively.
  271. This value is only used when the padding_mode is constant
  272. padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
  273. Default is constant.
  274. - constant: pads with a constant value, this value is specified with fill
  275. - edge: pads with the last value at the edge of the image
  276. - reflect: pads with reflection of image without repeating the last value on the edge
  277. For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
  278. will result in [3, 2, 1, 2, 3, 4, 3, 2]
  279. - symmetric: pads with reflection of image repeating the last value on the edge
  280. For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
  281. will result in [2, 1, 1, 2, 3, 4, 4, 3]
  282. """
  283. def __init__(self, padding, fill=0, padding_mode='constant'):
  284. assert isinstance(padding, (numbers.Number, tuple))
  285. assert isinstance(fill, (numbers.Number, str, tuple))
  286. assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric']
  287. if isinstance(padding, Sequence) and len(padding) not in [2, 4]:
  288. raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " +
  289. "{} element tuple".format(len(padding)))
  290. self.padding = padding
  291. self.fill = fill
  292. self.padding_mode = padding_mode
  293. def __call__(self, img, params=None, return_params=False ):
  294. """
  295. Args:
  296. img (PIL Image): Image to be padded.
  297. Returns:
  298. PIL Image: Padded image.
  299. """
  300. if return_params:
  301. return F.pad(img, self.padding, self.fill, self.padding_mode), None
  302. return F.pad(img, self.padding, self.fill, self.padding_mode)
  303. def __repr__(self):
  304. return self.__class__.__name__ + '(padding={0}, fill={1}, padding_mode={2})'.\
  305. format(self.padding, self.fill, self.padding_mode)
  306. class Lambda(object):
  307. """Apply a user-defined lambda as a transform.
  308. Args:
  309. lambd (function): Lambda/function to be used for transform.
  310. """
  311. def __init__(self, lambd):
  312. assert callable(lambd), repr(type(lambd).__name__) + " object is not callable"
  313. self.lambd = lambd
  314. def __call__(self, img, params=None, return_params=False):
  315. if return_params:
  316. return self.lambd(img), None
  317. return self.lambd(img)
  318. def __repr__(self):
  319. return self.__class__.__name__ + '()'
  320. class RandomTransforms(object):
  321. """Base class for a list of transformations with randomness
  322. Args:
  323. transforms (list or tuple): list of transformations
  324. """
  325. def __init__(self, transforms):
  326. assert isinstance(transforms, (list, tuple))
  327. self.transforms = transforms
  328. def __call__(self, *args, **kwargs):
  329. raise NotImplementedError()
  330. def __repr__(self):
  331. format_string = self.__class__.__name__ + '('
  332. for t in self.transforms:
  333. format_string += '\n'
  334. format_string += ' {0}'.format(t)
  335. format_string += '\n)'
  336. return format_string
  337. class RandomApply(RandomTransforms):
  338. """Apply randomly a list of transformations with a given probability
  339. Args:
  340. transforms (list or tuple): list of transformations
  341. p (float): probability
  342. """
  343. def __init__(self, transforms, p=0.5):
  344. super(RandomApply, self).__init__(transforms)
  345. self.p = p
  346. def __call__(self, img, params=None, return_params=False):
  347. if params is None:
  348. p = random.random()
  349. else:
  350. p = params
  351. if self.p < p:
  352. return img
  353. for t in self.transforms:
  354. img = t(img)
  355. if return_params:
  356. return img, p
  357. return img
  358. def __repr__(self):
  359. format_string = self.__class__.__name__ + '('
  360. format_string += '\n p={}'.format(self.p)
  361. for t in self.transforms:
  362. format_string += '\n'
  363. format_string += ' {0}'.format(t)
  364. format_string += '\n)'
  365. return format_string
  366. class RandomOrder(RandomTransforms):
  367. """Apply a list of transformations in a random order
  368. """
  369. def __call__(self, img, params=None, return_params=False):
  370. if params is None: # no sync
  371. order = list(range(len(self.transforms)))
  372. random.shuffle(order)
  373. else:
  374. order = params
  375. for i in order:
  376. img = self.transforms[i](img)
  377. if return_params:
  378. return img, order
  379. return img
  380. class RandomChoice(RandomTransforms):
  381. """Apply single transformation randomly picked from a list
  382. """
  383. def __call__(self, img, params=None, return_params=False):
  384. if params is None:
  385. t = random.choice(self.transforms)
  386. else:
  387. t = params
  388. if return_params:
  389. return t(img), t
  390. return t(img)
  391. class RandomCrop(object):
  392. """Crop the given PIL Image at a random location.
  393. Args:
  394. size (sequence or int): Desired output size of the crop. If size is an
  395. int instead of sequence like (h, w), a square crop (size, size) is
  396. made.
  397. padding (int or sequence, optional): Optional padding on each border
  398. of the image. Default is None, i.e no padding. If a sequence of length
  399. 4 is provided, it is used to pad left, top, right, bottom borders
  400. respectively. If a sequence of length 2 is provided, it is used to
  401. pad left/right, top/bottom borders, respectively.
  402. pad_if_needed (boolean): It will pad the image if smaller than the
  403. desired size to avoid raising an exception. Since cropping is done
  404. after padding, the padding seems to be done at a random offset.
  405. fill: Pixel fill value for constant fill. Default is 0. If a tuple of
  406. length 3, it is used to fill R, G, B channels respectively.
  407. This value is only used when the padding_mode is constant
  408. padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
  409. - constant: pads with a constant value, this value is specified with fill
  410. - edge: pads with the last value on the edge of the image
  411. - reflect: pads with reflection of image (without repeating the last value on the edge)
  412. padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
  413. will result in [3, 2, 1, 2, 3, 4, 3, 2]
  414. - symmetric: pads with reflection of image (repeating the last value on the edge)
  415. padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
  416. will result in [2, 1, 1, 2, 3, 4, 4, 3]
  417. """
  418. def __init__(self, size, padding=None, pad_if_needed=False, fill=0, padding_mode='constant'):
  419. if isinstance(size, numbers.Number):
  420. self.size = (int(size), int(size))
  421. else:
  422. self.size = size
  423. self.padding = padding
  424. self.pad_if_needed = pad_if_needed
  425. self.fill = fill
  426. self.padding_mode = padding_mode
  427. @staticmethod
  428. def get_params(img, output_size):
  429. """Get parameters for ``crop`` for a random crop.
  430. Args:
  431. img (PIL Image): Image to be cropped.
  432. output_size (tuple): Expected output size of the crop.
  433. Returns:
  434. tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.
  435. """
  436. w, h = img.size
  437. th, tw = output_size
  438. if w == tw and h == th:
  439. return 0, 0, h, w
  440. i = random.randint(0, h - th)
  441. j = random.randint(0, w - tw)
  442. return i, j, th, tw
  443. def __call__(self, img, params=None, return_params=False):
  444. """
  445. Args:
  446. img (PIL Image): Image to be cropped.
  447. Returns:
  448. PIL Image: Cropped image.
  449. """
  450. if self.padding is not None:
  451. img = F.pad(img, self.padding, self.fill, self.padding_mode)
  452. # pad the width if needed
  453. if self.pad_if_needed and img.size[0] < self.size[1]:
  454. img = F.pad(img, (self.size[1] - img.size[0], 0), self.fill, self.padding_mode)
  455. # pad the height if needed
  456. if self.pad_if_needed and img.size[1] < self.size[0]:
  457. img = F.pad(img, (0, self.size[0] - img.size[1]), self.fill, self.padding_mode)
  458. if params is None: # no sync
  459. i, j, h, w = self.get_params(img, self.size)
  460. else:
  461. i, j, h, w = params
  462. if return_params:
  463. return F.crop(img, i, j, h, w), (i,j,h,w)
  464. return F.crop(img, i, j, h, w)
  465. def __repr__(self):
  466. return self.__class__.__name__ + '(size={0}, padding={1})'.format(self.size, self.padding)
  467. class RandomHorizontalFlip(object):
  468. """Horizontally flip the given PIL Image randomly with a given probability.
  469. Args:
  470. p (float): probability of the image being flipped. Default value is 0.5
  471. """
  472. def __init__(self, p=0.5):
  473. self.p = p
  474. def __call__(self, img, params=None, return_params=False):
  475. """
  476. Args:
  477. img (PIL Image): Image to be flipped.
  478. Returns:
  479. PIL Image: Randomly flipped image.
  480. """
  481. if params is None:
  482. p = random.random()
  483. else:
  484. p = params
  485. if p < self.p:
  486. if return_params:
  487. return F.hflip(img), p
  488. return F.hflip(img)
  489. if return_params:
  490. return img, p
  491. return img
  492. def __repr__(self):
  493. return self.__class__.__name__ + '(p={})'.format(self.p)
  494. class RandomVerticalFlip(object):
  495. """Vertically flip the given PIL Image randomly with a given probability.
  496. Args:
  497. p (float): probability of the image being flipped. Default value is 0.5
  498. """
  499. def __init__(self, p=0.5):
  500. self.p = p
  501. def __call__(self, img, params=None, return_params=False):
  502. """
  503. Args:
  504. img (PIL Image): Image to be flipped.
  505. Returns:
  506. PIL Image: Randomly flipped image.
  507. """
  508. if params is None: # no sync
  509. p = random.random()
  510. else:
  511. p = params
  512. if p < self.p:
  513. return F.vflip(img)
  514. if return_params:
  515. return img, p
  516. return img
  517. def __repr__(self):
  518. return self.__class__.__name__ + '(p={})'.format(self.p)
  519. class RandomPerspective(object):
  520. """Performs Perspective transformation of the given PIL Image randomly with a given probability.
  521. Args:
  522. interpolation : Default- Image.BICUBIC
  523. p (float): probability of the image being perspectively transformed. Default value is 0.5
  524. distortion_scale(float): it controls the degree of distortion and ranges from 0 to 1. Default value is 0.5.
  525. """
  526. def __init__(self, distortion_scale=0.5, p=0.5, interpolation=Image.BICUBIC):
  527. self.p = p
  528. self.interpolation = interpolation
  529. self.distortion_scale = distortion_scale
  530. def __call__(self, img, params=None, return_params=False):
  531. """
  532. Args:
  533. img (PIL Image): Image to be Perspectively transformed.
  534. Returns:
  535. PIL Image: Random perspectivley transformed image.
  536. """
  537. if not F._is_pil_image(img):
  538. raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
  539. if params is None : # no sync or the first transform
  540. p = random.random()
  541. width, height = img.size
  542. startpoints, endpoints = self.get_params(width, height, self.distortion_scale)
  543. else:
  544. p, startpoints, endpoints = params
  545. if p<self.p:
  546. if return_params:
  547. return F.perspective(img, startpoints, endpoints, self.interpolation), (p, startpoints, endpoints)
  548. return F.perspective(img, startpoints, endpoints, self.interpolation)
  549. if return_params:
  550. return img, (p, startpoints, endpoints)
  551. return img
  552. @staticmethod
  553. def get_params(width, height, distortion_scale):
  554. """Get parameters for ``perspective`` for a random perspective transform.
  555. Args:
  556. width : width of the image.
  557. height : height of the image.
  558. Returns:
  559. List containing [top-left, top-right, bottom-right, bottom-left] of the original image,
  560. List containing [top-left, top-right, bottom-right, bottom-left] of the transformed image.
  561. """
  562. half_height = int(height / 2)
  563. half_width = int(width / 2)
  564. topleft = (random.randint(0, int(distortion_scale * half_width)),
  565. random.randint(0, int(distortion_scale * half_height)))
  566. topright = (random.randint(width - int(distortion_scale * half_width) - 1, width - 1),
  567. random.randint(0, int(distortion_scale * half_height)))
  568. botright = (random.randint(width - int(distortion_scale * half_width) - 1, width - 1),
  569. random.randint(height - int(distortion_scale * half_height) - 1, height - 1))
  570. botleft = (random.randint(0, int(distortion_scale * half_width)),
  571. random.randint(height - int(distortion_scale * half_height) - 1, height - 1))
  572. startpoints = [(0, 0), (width - 1, 0), (width - 1, height - 1), (0, height - 1)]
  573. endpoints = [topleft, topright, botright, botleft]
  574. return startpoints, endpoints
  575. def __repr__(self):
  576. return self.__class__.__name__ + '(p={})'.format(self.p)
  577. class RandomResizedCrop(object):
  578. """Crop the given PIL Image to random size and aspect ratio.
  579. A crop of random size (default: of 0.08 to 1.0) of the original size and a random
  580. aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
  581. is finally resized to given size.
  582. This is popularly used to train the Inception networks.
  583. Args:
  584. size: expected output size of each edge
  585. scale: range of size of the origin size cropped
  586. ratio: range of aspect ratio of the origin aspect ratio cropped
  587. interpolation: Default: PIL.Image.BILINEAR
  588. """
  589. def __init__(self, size, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.), interpolation=Image.BILINEAR):
  590. if isinstance(size, tuple):
  591. self.size = size
  592. else:
  593. self.size = (size, size)
  594. if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
  595. warnings.warn("range should be of kind (min, max)")
  596. self.interpolation = interpolation
  597. self.scale = scale
  598. self.ratio = ratio
  599. @staticmethod
  600. def get_params(img, scale, ratio):
  601. """Get parameters for ``crop`` for a random sized crop.
  602. Args:
  603. img (PIL Image): Image to be cropped.
  604. scale (tuple): range of size of the origin size cropped
  605. ratio (tuple): range of aspect ratio of the origin aspect ratio cropped
  606. Returns:
  607. tuple: params (i, j, h, w) to be passed to ``crop`` for a random
  608. sized crop.
  609. """
  610. area = img.size[0] * img.size[1]
  611. for attempt in range(10):
  612. target_area = random.uniform(*scale) * area
  613. log_ratio = (math.log(ratio[0]), math.log(ratio[1]))
  614. aspect_ratio = math.exp(random.uniform(*log_ratio))
  615. w = int(round(math.sqrt(target_area * aspect_ratio)))
  616. h = int(round(math.sqrt(target_area / aspect_ratio)))
  617. if w <= img.size[0] and h <= img.size[1]:
  618. i = random.randint(0, img.size[1] - h)
  619. j = random.randint(0, img.size[0] - w)
  620. return i, j, h, w
  621. # Fallback to central crop
  622. in_ratio = img.size[0] / img.size[1]
  623. if (in_ratio < min(ratio)):
  624. w = img.size[0]
  625. h = w / min(ratio)
  626. elif (in_ratio > max(ratio)):
  627. h = img.size[1]
  628. w = h * max(ratio)
  629. else: # whole image
  630. w = img.size[0]
  631. h = img.size[1]
  632. i = (img.size[1] - h) // 2
  633. j = (img.size[0] - w) // 2
  634. return i, j, h, w
  635. def __call__(self, img, params=None, return_params=False):
  636. """
  637. Args:
  638. img (PIL Image): Image to be cropped and resized.
  639. Returns:
  640. PIL Image: Randomly cropped and resized image.
  641. """
  642. if params is None: # no sync
  643. i, j, h, w = self.get_params(img, self.scale, self.ratio)
  644. else:
  645. i, j, h, w = params
  646. if return_params:
  647. return F.resized_crop(img, i, j, h, w, self.size, self.interpolation), (i,j,h,w)
  648. return F.resized_crop(img, i, j, h, w, self.size, self.interpolation)
  649. def __repr__(self):
  650. interpolate_str = _pil_interpolation_to_str[self.interpolation]
  651. format_string = self.__class__.__name__ + '(size={0}'.format(self.size)
  652. format_string += ', scale={0}'.format(tuple(round(s, 4) for s in self.scale))
  653. format_string += ', ratio={0}'.format(tuple(round(r, 4) for r in self.ratio))
  654. format_string += ', interpolation={0})'.format(interpolate_str)
  655. return format_string
  656. class RandomSizedCrop(RandomResizedCrop):
  657. """
  658. Note: This transform is deprecated in favor of RandomResizedCrop.
  659. """
  660. def __init__(self, *args, **kwargs):
  661. warnings.warn("The use of the transforms.RandomSizedCrop transform is deprecated, " +
  662. "please use transforms.RandomResizedCrop instead.")
  663. super(RandomSizedCrop, self).__init__(*args, **kwargs)
  664. class FiveCrop(object):
  665. """Crop the given PIL Image into four corners and the central crop
  666. .. Note:
  667. This transform returns a tuple of images and there may be a mismatch in the number of
  668. inputs and targets your Dataset returns. See below for an example of how to deal with
  669. this.
  670. Args:
  671. size (sequence or int): Desired output size of the crop. If size is an ``int``
  672. instead of sequence like (h, w), a square crop of size (size, size) is made.
  673. Example:
  674. >>> transform = Compose([
  675. >>> FiveCrop(size), # this is a list of PIL Images
  676. >>> Lambda(lambda crops: torch.stack([ToTensor()(crop) for crop in crops])) # returns a 4D tensor
  677. >>> ])
  678. >>> #In your test loop you can do the following:
  679. >>> input, target = batch # input is a 5d tensor, target is 2d
  680. >>> bs, ncrops, c, h, w = input.size()
  681. >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops
  682. >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops
  683. """
  684. def __init__(self, size):
  685. self.size = size
  686. if isinstance(size, numbers.Number):
  687. self.size = (int(size), int(size))
  688. else:
  689. assert len(size) == 2, "Please provide only two dimensions (h, w) for size."
  690. self.size = size
  691. def __call__(self, img, params=None, return_params=False):
  692. if return_params:
  693. return F.five_crop(img, self.size), None
  694. return F.five_crop(img, self.size)
  695. def __repr__(self):
  696. return self.__class__.__name__ + '(size={0})'.format(self.size)
  697. class TenCrop(object):
  698. """Crop the given PIL Image into four corners and the central crop plus the flipped version of
  699. these (horizontal flipping is used by default)
  700. .. Note:
  701. This transform returns a tuple of images and there may be a mismatch in the number of
  702. inputs and targets your Dataset returns. See below for an example of how to deal with
  703. this.
  704. Args:
  705. size (sequence or int): Desired output size of the crop. If size is an
  706. int instead of sequence like (h, w), a square crop (size, size) is
  707. made.
  708. vertical_flip (bool): Use vertical flipping instead of horizontal
  709. Example:
  710. >>> transform = Compose([
  711. >>> TenCrop(size), # this is a list of PIL Images
  712. >>> Lambda(lambda crops: torch.stack([ToTensor()(crop) for crop in crops])) # returns a 4D tensor
  713. >>> ])
  714. >>> #In your test loop you can do the following:
  715. >>> input, target = batch # input is a 5d tensor, target is 2d
  716. >>> bs, ncrops, c, h, w = input.size()
  717. >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops
  718. >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops
  719. """
  720. def __init__(self, size, vertical_flip=False):
  721. self.size = size
  722. if isinstance(size, numbers.Number):
  723. self.size = (int(size), int(size))
  724. else:
  725. assert len(size) == 2, "Please provide only two dimensions (h, w) for size."
  726. self.size = size
  727. self.vertical_flip = vertical_flip
  728. def __call__(self, img, params=None, return_params=False):
  729. if return_params:
  730. return F.ten_crop(img, self.size, self.vertical_flip), None
  731. return F.ten_crop(img, self.size, self.vertical_flip)
  732. def __repr__(self):
  733. return self.__class__.__name__ + '(size={0}, vertical_flip={1})'.format(self.size, self.vertical_flip)
  734. class LinearTransformation(object):
  735. """Transform a tensor image with a square transformation matrix and a mean_vector computed
  736. offline.
  737. Given transformation_matrix and mean_vector, will flatten the torch.*Tensor and
  738. subtract mean_vector from it which is then followed by computing the dot
  739. product with the transformation matrix and then reshaping the tensor to its
  740. original shape.
  741. Applications:
  742. whitening transformation: Suppose X is a column vector zero-centered data.
  743. Then compute the data covariance matrix [D x D] with torch.mm(X.t(), X),
  744. perform SVD on this matrix and pass it as transformation_matrix.
  745. Args:
  746. transformation_matrix (Tensor): tensor [D x D], D = C x H x W
  747. mean_vector (Tensor): tensor [D], D = C x H x W
  748. """
  749. def __init__(self, transformation_matrix, mean_vector):
  750. if transformation_matrix.size(0) != transformation_matrix.size(1):
  751. raise ValueError("transformation_matrix should be square. Got " +
  752. "[{} x {}] rectangular matrix.".format(*transformation_matrix.size()))
  753. if mean_vector.size(0) != transformation_matrix.size(0):
  754. raise ValueError("mean_vector should have the same length {}".format(mean_vector.size(0)) +
  755. " as any one of the dimensions of the transformation_matrix [{} x {}]"
  756. .format(transformation_matrix.size()))
  757. self.transformation_matrix = transformation_matrix
  758. self.mean_vector = mean_vector
  759. def __call__(self, tensor, params=None, return_params=False):
  760. """
  761. Args:
  762. tensor (Tensor): Tensor image of size (C, H, W) to be whitened.
  763. Returns:
  764. Tensor: Transformed image.
  765. """
  766. if tensor.size(0) * tensor.size(1) * tensor.size(2) != self.transformation_matrix.size(0):
  767. raise ValueError("tensor and transformation matrix have incompatible shape." +
  768. "[{} x {} x {}] != ".format(*tensor.size()) +
  769. "{}".format(self.transformation_matrix.size(0)))
  770. flat_tensor = tensor.view(1, -1) - self.mean_vector
  771. transformed_tensor = torch.mm(flat_tensor, self.transformation_matrix)
  772. tensor = transformed_tensor.view(tensor.size())
  773. if return_params:
  774. return tensor, None
  775. return tensor
  776. def __repr__(self):
  777. format_string = self.__class__.__name__ + '(transformation_matrix='
  778. format_string += (str(self.transformation_matrix.tolist()) + ')')
  779. format_string += (", (mean_vector=" + str(self.mean_vector.tolist()) + ')')
  780. return format_string
  781. class ColorJitter(object):
  782. """Randomly change the brightness, contrast and saturation of an image.
  783. Args:
  784. brightness (float or tuple of float (min, max)): How much to jitter brightness.
  785. brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]
  786. or the given [min, max]. Should be non negative numbers.
  787. contrast (float or tuple of float (min, max)): How much to jitter contrast.
  788. contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]
  789. or the given [min, max]. Should be non negative numbers.
  790. saturation (float or tuple of float (min, max)): How much to jitter saturation.
  791. saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]
  792. or the given [min, max]. Should be non negative numbers.
  793. hue (float or tuple of float (min, max)): How much to jitter hue.
  794. hue_factor is chosen uniformly from [-hue, hue] or the given [min, max].
  795. Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5.
  796. """
  797. def __init__(self, brightness=0, contrast=0, saturation=0, hue=0):
  798. self.brightness = self._check_input(brightness, 'brightness')
  799. self.contrast = self._check_input(contrast, 'contrast')
  800. self.saturation = self._check_input(saturation, 'saturation')
  801. self.hue = self._check_input(hue, 'hue', center=0, bound=(-0.5, 0.5),
  802. clip_first_on_zero=False)
  803. def _check_input(self, value, name, center=1, bound=(0, float('inf')), clip_first_on_zero=True):
  804. if isinstance(value, numbers.Number):
  805. if value < 0:
  806. raise ValueError("If {} is a single number, it must be non negative.".format(name))
  807. value = [center - value, center + value]
  808. if clip_first_on_zero:
  809. value[0] = max(value[0], 0)
  810. elif isinstance(value, (tuple, list)) and len(value) == 2:
  811. if not bound[0] <= value[0] <= value[1] <= bound[1]:
  812. raise ValueError("{} values should be between {}".format(name, bound))
  813. else:
  814. raise TypeError("{} should be a single number or a list/tuple with lenght 2.".format(name))
  815. # if value is 0 or (1., 1.) for brightness/contrast/saturation
  816. # or (0., 0.) for hue, do nothing
  817. if value[0] == value[1] == center:
  818. value = None
  819. return value
  820. @staticmethod
  821. def get_params(brightness, contrast, saturation, hue):
  822. """Get a randomized transform to be applied on image.
  823. Arguments are same as that of __init__.
  824. Returns:
  825. Transform which randomly adjusts brightness, contrast and
  826. saturation in a random order.
  827. """
  828. transforms = []
  829. if brightness is not None:
  830. brightness_factor = random.uniform(brightness[0], brightness[1])
  831. transforms.append(Lambda(lambda img: F.adjust_brightness(img, brightness_factor)))
  832. if contrast is not None:
  833. contrast_factor = random.uniform(contrast[0], contrast[1])
  834. transforms.append(Lambda(lambda img: F.adjust_contrast(img, contrast_factor)))
  835. if saturation is not None:
  836. saturation_factor = random.uniform(saturation[0], saturation[1])
  837. transforms.append(Lambda(lambda img: F.adjust_saturation(img, saturation_factor)))
  838. if hue is not None:
  839. hue_factor = random.uniform(hue[0], hue[1])
  840. transforms.append(Lambda(lambda img: F.adjust_hue(img, hue_factor)))
  841. random.shuffle(transforms)
  842. transform = Compose(transforms)
  843. return transform
  844. def __call__(self, img, params=None, return_params=False):
  845. """
  846. Args:
  847. img (PIL Image): Input image.
  848. Returns:
  849. PIL Image: Color jittered image.
  850. """
  851. sync_group = getattr( self, 'sync_group', None )
  852. if params is None: # no sync
  853. transform = self.get_params(self.brightness, self.contrast,
  854. self.saturation, self.hue)
  855. else:
  856. transform = params
  857. if return_params:
  858. return transform(img), transform
  859. return transform(img)
  860. def __repr__(self):
  861. format_string = self.__class__.__name__ + '('
  862. format_string += 'brightness={0}'.format(self.brightness)
  863. format_string += ', contrast={0}'.format(self.contrast)
  864. format_string += ', saturation={0}'.format(self.saturation)
  865. format_string += ', hue={0})'.format(self.hue)
  866. return format_string
  867. class RandomRotation(object):
  868. """Rotate the image by angle.
  869. Args:
  870. degrees (sequence or float or int): Range of degrees to select from.
  871. If degrees is a number instead of sequence like (min, max), the range of degrees
  872. will be (-degrees, +degrees).
  873. resample ({PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC}, optional):
  874. An optional resampling filter. See `filters`_ for more information.
  875. If omitted, or if the image has mode "1" or "P", it is set to PIL.Image.NEAREST.
  876. expand (bool, optional): Optional expansion flag.
  877. If true, expands the output to make it large enough to hold the entire rotated image.
  878. If false or omitted, make the output image the same size as the input image.
  879. Note that the expand flag assumes rotation around the center and no translation.
  880. center (2-tuple, optional): Optional center of rotation.
  881. Origin is the upper left corner.
  882. Default is the center of the image.
  883. .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
  884. """
  885. def __init__(self, degrees, resample=False, expand=False, center=None):
  886. if isinstance(degrees, numbers.Number):
  887. if degrees < 0:
  888. raise ValueError("If degrees is a single number, it must be positive.")
  889. self.degrees = (-degrees, degrees)
  890. else:
  891. if len(degrees) != 2:
  892. raise ValueError("If degrees is a sequence, it must be of len 2.")
  893. self.degrees = degrees
  894. self.resample = resample
  895. self.expand = expand
  896. self.center = center
  897. @staticmethod
  898. def get_params(degrees):
  899. """Get parameters for ``rotate`` for a random rotation.
  900. Returns:
  901. sequence: params to be passed to ``rotate`` for random rotation.
  902. """
  903. angle = random.uniform(degrees[0], degrees[1])
  904. return angle
  905. def __call__(self, img, params=None, return_params=False):
  906. """
  907. Args:
  908. img (PIL Image): Image to be rotated.
  909. Returns:
  910. PIL Image: Rotated image.
  911. """
  912. sync_group = getattr(self, 'sync_group', None)
  913. if params is None: # no sync
  914. angle = self.get_params(self.degrees)
  915. else:
  916. angle = params
  917. if return_params:
  918. return F.rotate(img, angle, self.resample, self.expand, self.center), angle
  919. return F.rotate(img, angle, self.resample, self.expand, self.center)
  920. def __repr__(self):
  921. format_string = self.__class__.__name__ + '(degrees={0}'.format(self.degrees)
  922. format_string += ', resample={0}'.format(self.resample)
  923. format_string += ', expand={0}'.format(self.expand)
  924. if self.center is not None:
  925. format_string += ', center={0}'.format(self.center)
  926. format_string += ')'
  927. return format_string
  928. class RandomAffine(object):
  929. """Random affine transformation of the image keeping center invariant
  930. Args:
  931. degrees (sequence or float or int): Range of degrees to select from.
  932. If degrees is a number instead of sequence like (min, max), the range of degrees
  933. will be (-degrees, +degrees). Set to 0 to deactivate rotations.
  934. translate (tuple, optional): tuple of maximum absolute fraction for horizontal
  935. and vertical translations. For example translate=(a, b), then horizontal shift
  936. is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
  937. randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
  938. scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
  939. randomly sampled from the range a <= scale <= b. Will keep original scale by default.
  940. shear (sequence or float or int, optional): Range of degrees to select from.
  941. If degrees is a number instead of sequence like (min, max), the range of degrees
  942. will be (-degrees, +degrees). Will not apply shear by default
  943. resample ({PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC}, optional):
  944. An optional resampling filter. See `filters`_ for more information.
  945. If omitted, or if the image has mode "1" or "P", it is set to PIL.Image.NEAREST.
  946. fillcolor (int): Optional fill color for the area outside the transform in the output image. (Pillow>=5.0.0)
  947. .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
  948. """
  949. def __init__(self, degrees, translate=None, scale=None, shear=None, resample=False, fillcolor=0):
  950. sync_group = None
  951. if isinstance(degrees, numbers.Number):
  952. if degrees < 0:
  953. raise ValueError("If degrees is a single number, it must be positive.")
  954. self.degrees = (-degrees, degrees)
  955. else:
  956. assert isinstance(degrees, (tuple, list)) and len(degrees) == 2, \
  957. "degrees should be a list or tuple and it must be of length 2."
  958. self.degrees = degrees
  959. if translate is not None:
  960. assert isinstance(translate, (tuple, list)) and len(translate) == 2, \
  961. "translate should be a list or tuple and it must be of length 2."
  962. for t in translate:
  963. if not (0.0 <= t <= 1.0):
  964. raise ValueError("translation values should be between 0 and 1")
  965. self.translate = translate
  966. if scale is not None:
  967. assert isinstance(scale, (tuple, list)) and len(scale) == 2, \
  968. "scale should be a list or tuple and it must be of length 2."
  969. for s in scale:
  970. if s <= 0:
  971. raise ValueError("scale values should be positive")
  972. self.scale = scale
  973. if shear is not None:
  974. if isinstance(shear, numbers.Number):
  975. if shear < 0:
  976. raise ValueError("If shear is a single number, it must be positive.")
  977. self.shear = (-shear, shear)
  978. else:
  979. assert isinstance(shear, (tuple, list)) and len(shear) == 2, \
  980. "shear should be a list or tuple and it must be of length 2."
  981. self.shear = shear
  982. else:
  983. self.shear = shear
  984. self.resample = resample
  985. self.fillcolor = fillcolor
  986. @staticmethod
  987. def get_params(degrees, translate, scale_ranges, shears, img_size):
  988. """Get parameters for affine transformation
  989. Returns:
  990. sequence: params to be passed to the affine transformation
  991. """
  992. angle = random.uniform(degrees[0], degrees[1])
  993. if translate is not None:
  994. max_dx = translate[0] * img_size[0]
  995. max_dy = translate[1] * img_size[1]
  996. translations = (np.round(random.uniform(-max_dx, max_dx)),
  997. np.round(random.uniform(-max_dy, max_dy)))
  998. else:
  999. translations = (0, 0)
  1000. if scale_ranges is not None:
  1001. scale = random.uniform(scale_ranges[0], scale_ranges[1])
  1002. else:
  1003. scale = 1.0
  1004. if shears is not None:
  1005. shear = random.uniform(shears[0], shears[1])
  1006. else:
  1007. shear = 0.0
  1008. return angle, translations, scale, shear
  1009. def __call__(self, img, params=None, return_params=False):
  1010. """
  1011. img (PIL Image): Image to be transformed.
  1012. Returns:
  1013. PIL Image: Affine transformed image.
  1014. """
  1015. if params is None: # no sync
  1016. params = self.get_params(self.degrees, self.translate, self.scale, self.shear, img.size)
  1017. if return_params:
  1018. return F.affine(img, *params, resample=self.resample, fillcolor=self.fillcolor), params
  1019. return F.affine(img, *params, resample=self.resample, fillcolor=self.fillcolor)
  1020. def __repr__(self):
  1021. s = '{name}(degrees={degrees}'
  1022. if self.translate is not None:
  1023. s += ', translate={translate}'
  1024. if self.scale is not None:
  1025. s += ', scale={scale}'
  1026. if self.shear is not None:
  1027. s += ', shear={shear}'
  1028. if self.resample > 0:
  1029. s += ', resample={resample}'
  1030. if self.fillcolor != 0:
  1031. s += ', fillcolor={fillcolor}'
  1032. s += ')'
  1033. d = dict(self.__dict__)
  1034. d['resample'] = _pil_interpolation_to_str[d['resample']]
  1035. return s.format(name=self.__class__.__name__, **d)
  1036. class ToRGB(object):
  1037. def __call__(self, img, params=None, return_params=False):
  1038. """
  1039. Args:
  1040. img (PIL Image): Image to be converted to grayscale.
  1041. Returns:
  1042. PIL Image: Randomly grayscaled image.
  1043. """
  1044. if return_params:
  1045. return img.convert('RGB'), None
  1046. return img.convert('RGB')
  1047. class ToGRAY(object):
  1048. def __call__(self, img, params=None, return_params=False):
  1049. """
  1050. Args:
  1051. img (PIL Image): Image to be converted to grayscale.
  1052. Returns:
  1053. PIL Image: Randomly grayscaled image.
  1054. """
  1055. if return_params:
  1056. return img.convert('GRAY'), None
  1057. return img.convert('GRAY')
  1058. class Grayscale(object):
  1059. """Convert image to grayscale.
  1060. Args:
  1061. num_output_channels (int): (1 or 3) number of channels desired for output image
  1062. Returns:
  1063. PIL Image: Grayscale version of the input.
  1064. - If num_output_channels == 1 : returned image is single channel
  1065. - If num_output_channels == 3 : returned image is 3 channel with r == g == b
  1066. """
  1067. def __init__(self, num_output_channels=1):
  1068. self.num_output_channels = num_output_channels
  1069. def __call__(self, img, params=None, return_params=False):
  1070. """
  1071. Args:
  1072. img (PIL Image): Image to be converted to grayscale.
  1073. Returns:
  1074. PIL Image: Randomly grayscaled image.
  1075. """
  1076. if return_params:
  1077. return F.to_grayscale(img, num_output_channels=self.num_output_channels), None
  1078. return F.to_grayscale(img, num_output_channels=self.num_output_channels)
  1079. def __repr__(self):
  1080. return self.__class__.__name__ + '(num_output_channels={0})'.format(self.num_output_channels)
  1081. class RandomGrayscale(object):
  1082. """Randomly convert image to grayscale with a probability of p (default 0.1).
  1083. Args:
  1084. p (float): probability that image should be converted to grayscale.
  1085. Returns:
  1086. PIL Image: Grayscale version of the input image with probability p and unchanged
  1087. with probability (1-p).
  1088. - If input image is 1 channel: grayscale version is 1 channel
  1089. - If input image is 3 channel: grayscale version is 3 channel with r == g == b
  1090. """
  1091. def __init__(self, p=0.1):
  1092. self.p = p
  1093. sync_group = None
  1094. def __call__(self, img, params=None, return_params=False):
  1095. """
  1096. Args:
  1097. img (PIL Image): Image to be converted to grayscale.
  1098. Returns:
  1099. PIL Image: Randomly grayscaled image.
  1100. """
  1101. num_output_channels = 1 if img.mode == 'L' else 3
  1102. if params is None: # no sync
  1103. p = random.random()
  1104. else:
  1105. p = params
  1106. if p < self.p:
  1107. if return_params:
  1108. return F.to_grayscale(img, num_output_channels=num_output_channels), p
  1109. return F.to_grayscale(img, num_output_channels=num_output_channels)
  1110. if return_params:
  1111. return img, p
  1112. return img
  1113. def __repr__(self):
  1114. return self.__class__.__name__ + '(p={0})'.format(self.p)
  1115. class FlipChannels(object):
  1116. def __call__(self, img, params=None, return_params=False):
  1117. if return_params:
  1118. return F.flip_channels( img ), None
  1119. return F.flip_channels( img )
  1120. def __repr__(self):
  1121. return self.__class__.__name__ + '()'.format()
  1122. class RandomErasing(object):
  1123. """ Randomly selects a rectangle region in an image and erases its pixels.
  1124. 'Random Erasing Data Augmentation' by Zhong et al.
  1125. See https://arxiv.org/pdf/1708.04896.pdf
  1126. Args:
  1127. p: probability that the random erasing operation will be performed.
  1128. scale: range of proportion of erased area against input image.
  1129. ratio: range of aspect ratio of erased area.
  1130. value: erasing value. Default is 0. If a single int, it is used to
  1131. erase all pixels. If a tuple of length 3, it is used to erase
  1132. R, G, B channels respectively.
  1133. If a str of 'random', erasing each pixel with random values.
  1134. inplace: boolean to make this transform inplace. Default set to False.
  1135. Returns:
  1136. Erased Image.
  1137. # Examples:
  1138. >>> transform = transforms.Compose([
  1139. >>> transforms.RandomHorizontalFlip(),
  1140. >>> transforms.ToTensor(),
  1141. >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
  1142. >>> transforms.RandomErasing(),
  1143. >>> ])
  1144. """
  1145. def __init__(self, p=0.5, scale=(0.02, 0.33), ratio=(0.3, 3.3), value=0, inplace=False):
  1146. assert isinstance(value, (numbers.Number, str, tuple, list))
  1147. if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
  1148. warnings.warn("range should be of kind (min, max)")
  1149. if scale[0] < 0 or scale[1] > 1:
  1150. raise ValueError("range of scale should be between 0 and 1")
  1151. if p < 0 or p > 1:
  1152. raise ValueError("range of random erasing probability should be between 0 and 1")
  1153. self.p = p
  1154. self.scale = scale
  1155. self.ratio = ratio
  1156. self.value = value
  1157. self.inplace = inplace
  1158. @staticmethod
  1159. def get_params(img, scale, ratio, value=0):
  1160. """Get parameters for ``erase`` for a random erasing.
  1161. Args:
  1162. img (Tensor): Tensor image of size (C, H, W) to be erased.
  1163. scale: range of proportion of erased area against input image.
  1164. ratio: range of aspect ratio of erased area.
  1165. Returns:
  1166. tuple: params (i, j, h, w, v) to be passed to ``erase`` for random erasing.
  1167. """
  1168. img_c, img_h, img_w = img.shape
  1169. area = img_h * img_w
  1170. for attempt in range(10):
  1171. erase_area = random.uniform(scale[0], scale[1]) * area
  1172. aspect_ratio = random.uniform(ratio[0], ratio[1])
  1173. h = int(round(math.sqrt(erase_area * aspect_ratio)))
  1174. w = int(round(math.sqrt(erase_area / aspect_ratio)))
  1175. if h < img_h and w < img_w:
  1176. i = random.randint(0, img_h - h)
  1177. j = random.randint(0, img_w - w)
  1178. if isinstance(value, numbers.Number):
  1179. v = value
  1180. elif isinstance(value, torch._six.string_classes):
  1181. v = torch.empty([img_c, h, w], dtype=torch.float32).normal_()
  1182. elif isinstance(value, (list, tuple)):
  1183. v = torch.tensor(value, dtype=torch.float32).view(-1, 1, 1).expand(-1, h, w)
  1184. return i, j, h, w, v
  1185. # Return original image
  1186. return 0, 0, img_h, img_w, img
  1187. def __call__(self, img, params=None, return_params=False):
  1188. """
  1189. Args:
  1190. img (Tensor): Tensor image of size (C, H, W) to be erased.
  1191. Returns:
  1192. img (Tensor): Erased Tensor image.
  1193. """
  1194. if params is None: # no sync
  1195. p = random.uniform(0, 1)
  1196. x, y, h, w, v = self.get_params(img, scale=self.scale, ratio=self.ratio, value=self.value)
  1197. else:
  1198. p, x, y, h, w, v = params
  1199. if p<self.p:
  1200. if return_params:
  1201. return F.erase(img, x, y, h, w, v, self.inplace), (p, x, y, h, w, v)
  1202. return F.erase(img, x, y, h, w, v, self.inplace)
  1203. if return_params:
  1204. return img, (p, x, y, h, w, v)
  1205. return img

一站式算法开发平台、高性能分布式深度学习框架、先进算法模型库、视觉模型炼知平台、数据可视化分析平台等一系列平台及工具,在模型高效分布式训练、数据处理和可视分析、模型炼知和轻量化等技术上形成独特优势,目前已在产学研等各领域近千家单位及个人提供AI应用赋能