autoaugment_utils.py 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  1. # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # Reference:
  15. # https://github.com/tensorflow/tpu/blob/master/models/official/detection/utils/autoaugment_utils.py
  16. """AutoAugment util file."""
  17. from __future__ import absolute_import
  18. from __future__ import division
  19. from __future__ import print_function
  20. import inspect
  21. import math
  22. from PIL import Image, ImageEnhance
  23. import numpy as np
  24. import cv2
  25. from copy import deepcopy
  26. # This signifies the max integer that the controller RNN could predict for the
  27. # augmentation scheme.
  28. _MAX_LEVEL = 10.
  29. # Represents an invalid bounding box that is used for checking for padding
  30. # lists of bounding box coordinates for a few augmentation operations
  31. _INVALID_BOX = [[-1.0, -1.0, -1.0, -1.0]]
  32. def policy_v0():
  33. """Autoaugment policy that was used in AutoAugment Detection Paper."""
  34. # Each tuple is an augmentation operation of the form
  35. # (operation, probability, magnitude). Each element in policy is a
  36. # sub-policy that will be applied sequentially on the image.
  37. policy = [
  38. [('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)],
  39. [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)],
  40. [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)],
  41. [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)],
  42. [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)],
  43. ]
  44. return policy
  45. def policy_v1():
  46. """Autoaugment policy that was used in AutoAugment Detection Paper."""
  47. # Each tuple is an augmentation operation of the form
  48. # (operation, probability, magnitude). Each element in policy is a
  49. # sub-policy that will be applied sequentially on the image.
  50. policy = [
  51. [('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)],
  52. [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)],
  53. [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)],
  54. [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)],
  55. [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)],
  56. [('Color', 0.0, 0), ('ShearX_Only_BBoxes', 0.8, 4)],
  57. [('ShearY_Only_BBoxes', 0.8, 2), ('Flip_Only_BBoxes', 0.0, 10)],
  58. [('Equalize', 0.6, 10), ('TranslateX_BBox', 0.2, 2)],
  59. [('Color', 1.0, 10), ('TranslateY_Only_BBoxes', 0.4, 6)],
  60. [('Rotate_BBox', 0.8, 10), ('Contrast', 0.0, 10)], # ,
  61. [('Cutout', 0.2, 2), ('Brightness', 0.8, 10)],
  62. [('Color', 1.0, 6), ('Equalize', 1.0, 2)],
  63. [('Cutout_Only_BBoxes', 0.4, 6), ('TranslateY_Only_BBoxes', 0.8, 2)],
  64. [('Color', 0.2, 8), ('Rotate_BBox', 0.8, 10)],
  65. [('Sharpness', 0.4, 4), ('TranslateY_Only_BBoxes', 0.0, 4)],
  66. [('Sharpness', 1.0, 4), ('SolarizeAdd', 0.4, 4)],
  67. [('Rotate_BBox', 1.0, 8), ('Sharpness', 0.2, 8)],
  68. [('ShearY_BBox', 0.6, 10), ('Equalize_Only_BBoxes', 0.6, 8)],
  69. [('ShearX_BBox', 0.2, 6), ('TranslateY_Only_BBoxes', 0.2, 10)],
  70. [('SolarizeAdd', 0.6, 8), ('Brightness', 0.8, 10)],
  71. ]
  72. return policy
  73. def policy_vtest():
  74. """Autoaugment test policy for debugging."""
  75. # Each tuple is an augmentation operation of the form
  76. # (operation, probability, magnitude). Each element in policy is a
  77. # sub-policy that will be applied sequentially on the image.
  78. policy = [[('TranslateX_BBox', 1.0, 4), ('Equalize', 1.0, 10)], ]
  79. return policy
  80. def policy_v2():
  81. """Additional policy that performs well on object detection."""
  82. # Each tuple is an augmentation operation of the form
  83. # (operation, probability, magnitude). Each element in policy is a
  84. # sub-policy that will be applied sequentially on the image.
  85. policy = [
  86. [('Color', 0.0, 6), ('Cutout', 0.6, 8), ('Sharpness', 0.4, 8)],
  87. [('Rotate_BBox', 0.4, 8), ('Sharpness', 0.4, 2),
  88. ('Rotate_BBox', 0.8, 10)],
  89. [('TranslateY_BBox', 1.0, 8), ('AutoContrast', 0.8, 2)],
  90. [('AutoContrast', 0.4, 6), ('ShearX_BBox', 0.8, 8),
  91. ('Brightness', 0.0, 10)],
  92. [('SolarizeAdd', 0.2, 6), ('Contrast', 0.0, 10),
  93. ('AutoContrast', 0.6, 0)],
  94. [('Cutout', 0.2, 0), ('Solarize', 0.8, 8), ('Color', 1.0, 4)],
  95. [('TranslateY_BBox', 0.0, 4), ('Equalize', 0.6, 8),
  96. ('Solarize', 0.0, 10)],
  97. [('TranslateY_BBox', 0.2, 2), ('ShearY_BBox', 0.8, 8),
  98. ('Rotate_BBox', 0.8, 8)],
  99. [('Cutout', 0.8, 8), ('Brightness', 0.8, 8), ('Cutout', 0.2, 2)],
  100. [('Color', 0.8, 4), ('TranslateY_BBox', 1.0, 6),
  101. ('Rotate_BBox', 0.6, 6)],
  102. [('Rotate_BBox', 0.6, 10), ('BBox_Cutout', 1.0, 4), ('Cutout', 0.2, 8)],
  103. [('Rotate_BBox', 0.0, 0), ('Equalize', 0.6, 6),
  104. ('ShearY_BBox', 0.6, 8)],
  105. [('Brightness', 0.8, 8), ('AutoContrast', 0.4, 2),
  106. ('Brightness', 0.2, 2)],
  107. [('TranslateY_BBox', 0.4, 8), ('Solarize', 0.4, 6),
  108. ('SolarizeAdd', 0.2, 10)],
  109. [('Contrast', 1.0, 10), ('SolarizeAdd', 0.2, 8), ('Equalize', 0.2, 4)],
  110. ]
  111. return policy
  112. def policy_v3():
  113. """"Additional policy that performs well on object detection."""
  114. # Each tuple is an augmentation operation of the form
  115. # (operation, probability, magnitude). Each element in policy is a
  116. # sub-policy that will be applied sequentially on the image.
  117. policy = [
  118. [('Posterize', 0.8, 2), ('TranslateX_BBox', 1.0, 8)],
  119. [('BBox_Cutout', 0.2, 10), ('Sharpness', 1.0, 8)],
  120. [('Rotate_BBox', 0.6, 8), ('Rotate_BBox', 0.8, 10)],
  121. [('Equalize', 0.8, 10), ('AutoContrast', 0.2, 10)],
  122. [('SolarizeAdd', 0.2, 2), ('TranslateY_BBox', 0.2, 8)],
  123. [('Sharpness', 0.0, 2), ('Color', 0.4, 8)],
  124. [('Equalize', 1.0, 8), ('TranslateY_BBox', 1.0, 8)],
  125. [('Posterize', 0.6, 2), ('Rotate_BBox', 0.0, 10)],
  126. [('AutoContrast', 0.6, 0), ('Rotate_BBox', 1.0, 6)],
  127. [('Equalize', 0.0, 4), ('Cutout', 0.8, 10)],
  128. [('Brightness', 1.0, 2), ('TranslateY_BBox', 1.0, 6)],
  129. [('Contrast', 0.0, 2), ('ShearY_BBox', 0.8, 0)],
  130. [('AutoContrast', 0.8, 10), ('Contrast', 0.2, 10)],
  131. [('Rotate_BBox', 1.0, 10), ('Cutout', 1.0, 10)],
  132. [('SolarizeAdd', 0.8, 6), ('Equalize', 0.8, 8)],
  133. ]
  134. return policy
  135. def _equal(val1, val2, eps=1e-8):
  136. return abs(val1 - val2) <= eps
  137. def blend(image1, image2, factor):
  138. """Blend image1 and image2 using 'factor'.
  139. Factor can be above 0.0. A value of 0.0 means only image1 is used.
  140. A value of 1.0 means only image2 is used. A value between 0.0 and
  141. 1.0 means we linearly interpolate the pixel values between the two
  142. images. A value greater than 1.0 "extrapolates" the difference
  143. between the two pixel values, and we clip the results to values
  144. between 0 and 255.
  145. Args:
  146. image1: An image Tensor of type uint8.
  147. image2: An image Tensor of type uint8.
  148. factor: A floating point value above 0.0.
  149. Returns:
  150. A blended image Tensor of type uint8.
  151. """
  152. if factor == 0.0:
  153. return image1
  154. if factor == 1.0:
  155. return image2
  156. image1 = image1.astype(np.float32)
  157. image2 = image2.astype(np.float32)
  158. difference = image2 - image1
  159. scaled = factor * difference
  160. # Do addition in float.
  161. temp = image1 + scaled
  162. # Interpolate
  163. if factor > 0.0 and factor < 1.0:
  164. # Interpolation means we always stay within 0 and 255.
  165. return temp.astype(np.uint8)
  166. # Extrapolate:
  167. #
  168. # We need to clip and then cast.
  169. return np.clip(temp, a_min=0, a_max=255).astype(np.uint8)
  170. def cutout(image, pad_size, replace=0):
  171. """Apply cutout (https://arxiv.org/abs/1708.04552) to image.
  172. This operation applies a (2*pad_size x 2*pad_size) mask of zeros to
  173. a random location within `img`. The pixel values filled in will be of the
  174. value `replace`. The located where the mask will be applied is randomly
  175. chosen uniformly over the whole image.
  176. Args:
  177. image: An image Tensor of type uint8.
  178. pad_size: Specifies how big the zero mask that will be generated is that
  179. is applied to the image. The mask will be of size
  180. (2*pad_size x 2*pad_size).
  181. replace: What pixel value to fill in the image in the area that has
  182. the cutout mask applied to it.
  183. Returns:
  184. An image Tensor that is of type uint8.
  185. Example:
  186. img = cv2.imread( "/home/vis/gry/train/img_data/test.jpg", cv2.COLOR_BGR2RGB )
  187. new_img = cutout(img, pad_size=50, replace=0)
  188. """
  189. image_height, image_width = image.shape[0], image.shape[1]
  190. cutout_center_height = np.random.randint(low=0, high=image_height)
  191. cutout_center_width = np.random.randint(low=0, high=image_width)
  192. lower_pad = np.maximum(0, cutout_center_height - pad_size)
  193. upper_pad = np.maximum(0, image_height - cutout_center_height - pad_size)
  194. left_pad = np.maximum(0, cutout_center_width - pad_size)
  195. right_pad = np.maximum(0, image_width - cutout_center_width - pad_size)
  196. cutout_shape = [
  197. image_height - (lower_pad + upper_pad),
  198. image_width - (left_pad + right_pad)
  199. ]
  200. padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]
  201. mask = np.pad(np.zeros(
  202. cutout_shape, dtype=image.dtype),
  203. padding_dims,
  204. 'constant',
  205. constant_values=1)
  206. mask = np.expand_dims(mask, -1)
  207. mask = np.tile(mask, [1, 1, 3])
  208. image = np.where(
  209. np.equal(mask, 0),
  210. np.ones_like(
  211. image, dtype=image.dtype) * replace,
  212. image)
  213. return image.astype(np.uint8)
  214. def solarize(image, threshold=128):
  215. # For each pixel in the image, select the pixel
  216. # if the value is less than the threshold.
  217. # Otherwise, subtract 255 from the pixel.
  218. return np.where(image < threshold, image, 255 - image)
  219. def solarize_add(image, addition=0, threshold=128):
  220. # For each pixel in the image less than threshold
  221. # we add 'addition' amount to it and then clip the
  222. # pixel value to be between 0 and 255. The value
  223. # of 'addition' is between -128 and 128.
  224. added_image = image.astype(np.int64) + addition
  225. added_image = np.clip(added_image, a_min=0, a_max=255).astype(np.uint8)
  226. return np.where(image < threshold, added_image, image)
  227. def color(image, factor):
  228. """use cv2 to deal"""
  229. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  230. degenerate = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
  231. return blend(degenerate, image, factor)
  232. # refer to https://github.com/4uiiurz1/pytorch-auto-augment/blob/024b2eac4140c38df8342f09998e307234cafc80/auto_augment.py#L197
  233. def contrast(img, factor):
  234. img = ImageEnhance.Contrast(Image.fromarray(img)).enhance(factor)
  235. return np.array(img)
  236. def brightness(image, factor):
  237. """Equivalent of PIL Brightness."""
  238. degenerate = np.zeros_like(image)
  239. return blend(degenerate, image, factor)
  240. def posterize(image, bits):
  241. """Equivalent of PIL Posterize."""
  242. shift = 8 - bits
  243. return np.left_shift(np.right_shift(image, shift), shift)
  244. def rotate(image, degrees, replace):
  245. """Rotates the image by degrees either clockwise or counterclockwise.
  246. Args:
  247. image: An image Tensor of type uint8.
  248. degrees: Float, a scalar angle in degrees to rotate all images by. If
  249. degrees is positive the image will be rotated clockwise otherwise it will
  250. be rotated counterclockwise.
  251. replace: A one or three value 1D tensor to fill empty pixels caused by
  252. the rotate operation.
  253. Returns:
  254. The rotated version of image.
  255. """
  256. image = wrap(image)
  257. image = Image.fromarray(image)
  258. image = image.rotate(degrees)
  259. image = np.array(image, dtype=np.uint8)
  260. return unwrap(image, replace)
  261. def random_shift_bbox(image,
  262. bbox,
  263. pixel_scaling,
  264. replace,
  265. new_min_bbox_coords=None):
  266. """Move the bbox and the image content to a slightly new random location.
  267. Args:
  268. image: 3D uint8 Tensor.
  269. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
  270. of type float that represents the normalized coordinates between 0 and 1.
  271. The potential values for the new min corner of the bbox will be between
  272. [old_min - pixel_scaling * bbox_height/2,
  273. old_min - pixel_scaling * bbox_height/2].
  274. pixel_scaling: A float between 0 and 1 that specifies the pixel range
  275. that the new bbox location will be sampled from.
  276. replace: A one or three value 1D tensor to fill empty pixels.
  277. new_min_bbox_coords: If not None, then this is a tuple that specifies the
  278. (min_y, min_x) coordinates of the new bbox. Normally this is randomly
  279. specified, but this allows it to be manually set. The coordinates are
  280. the absolute coordinates between 0 and image height/width and are int32.
  281. Returns:
  282. The new image that will have the shifted bbox location in it along with
  283. the new bbox that contains the new coordinates.
  284. """
  285. # Obtains image height and width and create helper clip functions.
  286. image_height, image_width = image.shape[0], image.shape[1]
  287. image_height = float(image_height)
  288. image_width = float(image_width)
  289. def clip_y(val):
  290. return np.clip(val, a_min=0, a_max=image_height - 1).astype(np.int32)
  291. def clip_x(val):
  292. return np.clip(val, a_min=0, a_max=image_width - 1).astype(np.int32)
  293. # Convert bbox to pixel coordinates.
  294. min_y = int(image_height * bbox[0])
  295. min_x = int(image_width * bbox[1])
  296. max_y = clip_y(image_height * bbox[2])
  297. max_x = clip_x(image_width * bbox[3])
  298. bbox_height, bbox_width = (max_y - min_y + 1, max_x - min_x + 1)
  299. image_height = int(image_height)
  300. image_width = int(image_width)
  301. # Select the new min/max bbox ranges that are used for sampling the
  302. # new min x/y coordinates of the shifted bbox.
  303. minval_y = clip_y(min_y - np.int32(pixel_scaling * float(bbox_height) /
  304. 2.0))
  305. maxval_y = clip_y(min_y + np.int32(pixel_scaling * float(bbox_height) /
  306. 2.0))
  307. minval_x = clip_x(min_x - np.int32(pixel_scaling * float(bbox_width) / 2.0))
  308. maxval_x = clip_x(min_x + np.int32(pixel_scaling * float(bbox_width) / 2.0))
  309. # Sample and calculate the new unclipped min/max coordinates of the new bbox.
  310. if new_min_bbox_coords is None:
  311. unclipped_new_min_y = np.random.randint(
  312. low=minval_y, high=maxval_y, dtype=np.int32)
  313. unclipped_new_min_x = np.random.randint(
  314. low=minval_x, high=maxval_x, dtype=np.int32)
  315. else:
  316. unclipped_new_min_y, unclipped_new_min_x = (
  317. clip_y(new_min_bbox_coords[0]), clip_x(new_min_bbox_coords[1]))
  318. unclipped_new_max_y = unclipped_new_min_y + bbox_height - 1
  319. unclipped_new_max_x = unclipped_new_min_x + bbox_width - 1
  320. # Determine if any of the new bbox was shifted outside the current image.
  321. # This is used for determining if any of the original bbox content should be
  322. # discarded.
  323. new_min_y, new_min_x, new_max_y, new_max_x = (
  324. clip_y(unclipped_new_min_y), clip_x(unclipped_new_min_x),
  325. clip_y(unclipped_new_max_y), clip_x(unclipped_new_max_x))
  326. shifted_min_y = (new_min_y - unclipped_new_min_y) + min_y
  327. shifted_max_y = max_y - (unclipped_new_max_y - new_max_y)
  328. shifted_min_x = (new_min_x - unclipped_new_min_x) + min_x
  329. shifted_max_x = max_x - (unclipped_new_max_x - new_max_x)
  330. # Create the new bbox tensor by converting pixel integer values to floats.
  331. new_bbox = np.stack([
  332. float(new_min_y) / float(image_height), float(new_min_x) /
  333. float(image_width), float(new_max_y) / float(image_height),
  334. float(new_max_x) / float(image_width)
  335. ])
  336. # Copy the contents in the bbox and fill the old bbox location
  337. # with gray (128).
  338. bbox_content = image[shifted_min_y:shifted_max_y + 1, shifted_min_x:
  339. shifted_max_x + 1, :]
  340. def mask_and_add_image(min_y_, min_x_, max_y_, max_x_, mask, content_tensor,
  341. image_):
  342. """Applies mask to bbox region in image then adds content_tensor to it."""
  343. mask = np.pad(mask, [[min_y_, (image_height - 1) - max_y_],
  344. [min_x_, (image_width - 1) - max_x_], [0, 0]],
  345. 'constant',
  346. constant_values=1)
  347. content_tensor = np.pad(content_tensor,
  348. [[min_y_, (image_height - 1) - max_y_],
  349. [min_x_, (image_width - 1) - max_x_], [0, 0]],
  350. 'constant',
  351. constant_values=0)
  352. return image_ * mask + content_tensor
  353. # Zero out original bbox location.
  354. mask = np.zeros_like(image)[min_y:max_y + 1, min_x:max_x + 1, :]
  355. grey_tensor = np.zeros_like(mask) + replace[0]
  356. image = mask_and_add_image(min_y, min_x, max_y, max_x, mask, grey_tensor,
  357. image)
  358. # Fill in bbox content to new bbox location.
  359. mask = np.zeros_like(bbox_content)
  360. image = mask_and_add_image(new_min_y, new_min_x, new_max_y, new_max_x, mask,
  361. bbox_content, image)
  362. return image.astype(np.uint8), new_bbox
  363. def _clip_bbox(min_y, min_x, max_y, max_x):
  364. """Clip bounding box coordinates between 0 and 1.
  365. Args:
  366. min_y: Normalized bbox coordinate of type float between 0 and 1.
  367. min_x: Normalized bbox coordinate of type float between 0 and 1.
  368. max_y: Normalized bbox coordinate of type float between 0 and 1.
  369. max_x: Normalized bbox coordinate of type float between 0 and 1.
  370. Returns:
  371. Clipped coordinate values between 0 and 1.
  372. """
  373. min_y = np.clip(min_y, a_min=0, a_max=1.0)
  374. min_x = np.clip(min_x, a_min=0, a_max=1.0)
  375. max_y = np.clip(max_y, a_min=0, a_max=1.0)
  376. max_x = np.clip(max_x, a_min=0, a_max=1.0)
  377. return min_y, min_x, max_y, max_x
  378. def _check_bbox_area(min_y, min_x, max_y, max_x, delta=0.05):
  379. """Adjusts bbox coordinates to make sure the area is > 0.
  380. Args:
  381. min_y: Normalized bbox coordinate of type float between 0 and 1.
  382. min_x: Normalized bbox coordinate of type float between 0 and 1.
  383. max_y: Normalized bbox coordinate of type float between 0 and 1.
  384. max_x: Normalized bbox coordinate of type float between 0 and 1.
  385. delta: Float, this is used to create a gap of size 2 * delta between
  386. bbox min/max coordinates that are the same on the boundary.
  387. This prevents the bbox from having an area of zero.
  388. Returns:
  389. Tuple of new bbox coordinates between 0 and 1 that will now have a
  390. guaranteed area > 0.
  391. """
  392. height = max_y - min_y
  393. width = max_x - min_x
  394. def _adjust_bbox_boundaries(min_coord, max_coord):
  395. # Make sure max is never 0 and min is never 1.
  396. max_coord = np.maximum(max_coord, 0.0 + delta)
  397. min_coord = np.minimum(min_coord, 1.0 - delta)
  398. return min_coord, max_coord
  399. if _equal(height, 0):
  400. min_y, max_y = _adjust_bbox_boundaries(min_y, max_y)
  401. if _equal(width, 0):
  402. min_x, max_x = _adjust_bbox_boundaries(min_x, max_x)
  403. return min_y, min_x, max_y, max_x
  404. def _scale_bbox_only_op_probability(prob):
  405. """Reduce the probability of the bbox-only operation.
  406. Probability is reduced so that we do not distort the content of too many
  407. bounding boxes that are close to each other. The value of 3.0 was a chosen
  408. hyper parameter when designing the autoaugment algorithm that we found
  409. empirically to work well.
  410. Args:
  411. prob: Float that is the probability of applying the bbox-only operation.
  412. Returns:
  413. Reduced probability.
  414. """
  415. return prob / 3.0
  416. def _apply_bbox_augmentation(image, bbox, augmentation_func, *args):
  417. """Applies augmentation_func to the subsection of image indicated by bbox.
  418. Args:
  419. image: 3D uint8 Tensor.
  420. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
  421. of type float that represents the normalized coordinates between 0 and 1.
  422. augmentation_func: Augmentation function that will be applied to the
  423. subsection of image.
  424. *args: Additional parameters that will be passed into augmentation_func
  425. when it is called.
  426. Returns:
  427. A modified version of image, where the bbox location in the image will
  428. have `ugmentation_func applied to it.
  429. """
  430. image_height = image.shape[0]
  431. image_width = image.shape[1]
  432. min_y = int(image_height * bbox[0])
  433. min_x = int(image_width * bbox[1])
  434. max_y = int(image_height * bbox[2])
  435. max_x = int(image_width * bbox[3])
  436. # Clip to be sure the max values do not fall out of range.
  437. max_y = np.minimum(max_y, image_height - 1)
  438. max_x = np.minimum(max_x, image_width - 1)
  439. # Get the sub-tensor that is the image within the bounding box region.
  440. bbox_content = image[min_y:max_y + 1, min_x:max_x + 1, :]
  441. # Apply the augmentation function to the bbox portion of the image.
  442. augmented_bbox_content = augmentation_func(bbox_content, *args)
  443. # Pad the augmented_bbox_content and the mask to match the shape of original
  444. # image.
  445. augmented_bbox_content = np.pad(
  446. augmented_bbox_content, [[min_y, (image_height - 1) - max_y],
  447. [min_x, (image_width - 1) - max_x], [0, 0]],
  448. 'constant',
  449. constant_values=1)
  450. # Create a mask that will be used to zero out a part of the original image.
  451. mask_tensor = np.zeros_like(bbox_content)
  452. mask_tensor = np.pad(mask_tensor,
  453. [[min_y, (image_height - 1) - max_y],
  454. [min_x, (image_width - 1) - max_x], [0, 0]],
  455. 'constant',
  456. constant_values=1)
  457. # Replace the old bbox content with the new augmented content.
  458. image = image * mask_tensor + augmented_bbox_content
  459. return image.astype(np.uint8)
  460. def _concat_bbox(bbox, bboxes):
  461. """Helper function that concates bbox to bboxes along the first dimension."""
  462. # Note if all elements in bboxes are -1 (_INVALID_BOX), then this means
  463. # we discard bboxes and start the bboxes Tensor with the current bbox.
  464. bboxes_sum_check = np.sum(bboxes)
  465. bbox = np.expand_dims(bbox, 0)
  466. # This check will be true when it is an _INVALID_BOX
  467. if _equal(bboxes_sum_check, -4):
  468. bboxes = bbox
  469. else:
  470. bboxes = np.concatenate([bboxes, bbox], 0)
  471. return bboxes
  472. def _apply_bbox_augmentation_wrapper(image, bbox, new_bboxes, prob,
  473. augmentation_func, func_changes_bbox,
  474. *args):
  475. """Applies _apply_bbox_augmentation with probability prob.
  476. Args:
  477. image: 3D uint8 Tensor.
  478. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
  479. of type float that represents the normalized coordinates between 0 and 1.
  480. new_bboxes: 2D Tensor that is a list of the bboxes in the image after they
  481. have been altered by aug_func. These will only be changed when
  482. func_changes_bbox is set to true. Each bbox has 4 elements
  483. (min_y, min_x, max_y, max_x) of type float that are the normalized
  484. bbox coordinates between 0 and 1.
  485. prob: Float that is the probability of applying _apply_bbox_augmentation.
  486. augmentation_func: Augmentation function that will be applied to the
  487. subsection of image.
  488. func_changes_bbox: Boolean. Does augmentation_func return bbox in addition
  489. to image.
  490. *args: Additional parameters that will be passed into augmentation_func
  491. when it is called.
  492. Returns:
  493. A tuple. Fist element is a modified version of image, where the bbox
  494. location in the image will have augmentation_func applied to it if it is
  495. chosen to be called with probability `prob`. The second element is a
  496. Tensor of Tensors of length 4 that will contain the altered bbox after
  497. applying augmentation_func.
  498. """
  499. should_apply_op = (np.random.rand() + prob >= 1)
  500. if func_changes_bbox:
  501. if should_apply_op:
  502. augmented_image, bbox = augmentation_func(image, bbox, *args)
  503. else:
  504. augmented_image, bbox = (image, bbox)
  505. else:
  506. if should_apply_op:
  507. augmented_image = _apply_bbox_augmentation(image, bbox,
  508. augmentation_func, *args)
  509. else:
  510. augmented_image = image
  511. new_bboxes = _concat_bbox(bbox, new_bboxes)
  512. return augmented_image.astype(np.uint8), new_bboxes
  513. def _apply_multi_bbox_augmentation(image, bboxes, prob, aug_func,
  514. func_changes_bbox, *args):
  515. """Applies aug_func to the image for each bbox in bboxes.
  516. Args:
  517. image: 3D uint8 Tensor.
  518. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox
  519. has 4 elements (min_y, min_x, max_y, max_x) of type float.
  520. prob: Float that is the probability of applying aug_func to a specific
  521. bounding box within the image.
  522. aug_func: Augmentation function that will be applied to the
  523. subsections of image indicated by the bbox values in bboxes.
  524. func_changes_bbox: Boolean. Does augmentation_func return bbox in addition
  525. to image.
  526. *args: Additional parameters that will be passed into augmentation_func
  527. when it is called.
  528. Returns:
  529. A modified version of image, where each bbox location in the image will
  530. have augmentation_func applied to it if it is chosen to be called with
  531. probability prob independently across all bboxes. Also the final
  532. bboxes are returned that will be unchanged if func_changes_bbox is set to
  533. false and if true, the new altered ones will be returned.
  534. """
  535. # Will keep track of the new altered bboxes after aug_func is repeatedly
  536. # applied. The -1 values are a dummy value and this first Tensor will be
  537. # removed upon appending the first real bbox.
  538. new_bboxes = np.array(_INVALID_BOX)
  539. # If the bboxes are empty, then just give it _INVALID_BOX. The result
  540. # will be thrown away.
  541. bboxes = np.array((_INVALID_BOX)) if bboxes.size == 0 else bboxes
  542. assert bboxes.shape[1] == 4, "bboxes.shape[1] must be 4!!!!"
  543. # pylint:disable=g-long-lambda
  544. # pylint:disable=line-too-long
  545. wrapped_aug_func = lambda _image, bbox, _new_bboxes: _apply_bbox_augmentation_wrapper(_image, bbox, _new_bboxes, prob, aug_func, func_changes_bbox, *args)
  546. # pylint:enable=g-long-lambda
  547. # pylint:enable=line-too-long
  548. # Setup the while_loop.
  549. num_bboxes = bboxes.shape[0] # We loop until we go over all bboxes.
  550. idx = 0 # Counter for the while loop.
  551. # Conditional function when to end the loop once we go over all bboxes
  552. # images_and_bboxes contain (_image, _new_bboxes)
  553. def cond(_idx, _images_and_bboxes):
  554. return _idx < num_bboxes
  555. # Shuffle the bboxes so that the augmentation order is not deterministic if
  556. # we are not changing the bboxes with aug_func.
  557. # if not func_changes_bbox:
  558. # print(bboxes)
  559. # loop_bboxes = np.take(bboxes,np.random.permutation(bboxes.shape[0]),axis=0)
  560. # print(loop_bboxes)
  561. # else:
  562. # loop_bboxes = bboxes
  563. # we can not shuffle the bbox because it does not contain class information here
  564. loop_bboxes = deepcopy(bboxes)
  565. # Main function of while_loop where we repeatedly apply augmentation on the
  566. # bboxes in the image.
  567. # pylint:disable=g-long-lambda
  568. body = lambda _idx, _images_and_bboxes: [
  569. _idx + 1, wrapped_aug_func(_images_and_bboxes[0],
  570. loop_bboxes[_idx],
  571. _images_and_bboxes[1])]
  572. while (cond(idx, (image, new_bboxes))):
  573. idx, (image, new_bboxes) = body(idx, (image, new_bboxes))
  574. # Either return the altered bboxes or the original ones depending on if
  575. # we altered them in anyway.
  576. if func_changes_bbox:
  577. final_bboxes = new_bboxes
  578. else:
  579. final_bboxes = bboxes
  580. return image, final_bboxes
  581. def _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, aug_func,
  582. func_changes_bbox, *args):
  583. """Checks to be sure num bboxes > 0 before calling inner function."""
  584. num_bboxes = len(bboxes)
  585. new_image = deepcopy(image)
  586. new_bboxes = deepcopy(bboxes)
  587. if num_bboxes != 0:
  588. new_image, new_bboxes = _apply_multi_bbox_augmentation(
  589. new_image, new_bboxes, prob, aug_func, func_changes_bbox, *args)
  590. return new_image, new_bboxes
  591. def rotate_only_bboxes(image, bboxes, prob, degrees, replace):
  592. """Apply rotate to each bbox in the image with probability prob."""
  593. func_changes_bbox = False
  594. prob = _scale_bbox_only_op_probability(prob)
  595. return _apply_multi_bbox_augmentation_wrapper(
  596. image, bboxes, prob, rotate, func_changes_bbox, degrees, replace)
  597. def shear_x_only_bboxes(image, bboxes, prob, level, replace):
  598. """Apply shear_x to each bbox in the image with probability prob."""
  599. func_changes_bbox = False
  600. prob = _scale_bbox_only_op_probability(prob)
  601. return _apply_multi_bbox_augmentation_wrapper(
  602. image, bboxes, prob, shear_x, func_changes_bbox, level, replace)
  603. def shear_y_only_bboxes(image, bboxes, prob, level, replace):
  604. """Apply shear_y to each bbox in the image with probability prob."""
  605. func_changes_bbox = False
  606. prob = _scale_bbox_only_op_probability(prob)
  607. return _apply_multi_bbox_augmentation_wrapper(
  608. image, bboxes, prob, shear_y, func_changes_bbox, level, replace)
  609. def translate_x_only_bboxes(image, bboxes, prob, pixels, replace):
  610. """Apply translate_x to each bbox in the image with probability prob."""
  611. func_changes_bbox = False
  612. prob = _scale_bbox_only_op_probability(prob)
  613. return _apply_multi_bbox_augmentation_wrapper(
  614. image, bboxes, prob, translate_x, func_changes_bbox, pixels, replace)
  615. def translate_y_only_bboxes(image, bboxes, prob, pixels, replace):
  616. """Apply translate_y to each bbox in the image with probability prob."""
  617. func_changes_bbox = False
  618. prob = _scale_bbox_only_op_probability(prob)
  619. return _apply_multi_bbox_augmentation_wrapper(
  620. image, bboxes, prob, translate_y, func_changes_bbox, pixels, replace)
  621. def flip_only_bboxes(image, bboxes, prob):
  622. """Apply flip_lr to each bbox in the image with probability prob."""
  623. func_changes_bbox = False
  624. prob = _scale_bbox_only_op_probability(prob)
  625. return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob,
  626. np.fliplr, func_changes_bbox)
  627. def solarize_only_bboxes(image, bboxes, prob, threshold):
  628. """Apply solarize to each bbox in the image with probability prob."""
  629. func_changes_bbox = False
  630. prob = _scale_bbox_only_op_probability(prob)
  631. return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, solarize,
  632. func_changes_bbox, threshold)
  633. def equalize_only_bboxes(image, bboxes, prob):
  634. """Apply equalize to each bbox in the image with probability prob."""
  635. func_changes_bbox = False
  636. prob = _scale_bbox_only_op_probability(prob)
  637. return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, equalize,
  638. func_changes_bbox)
  639. def cutout_only_bboxes(image, bboxes, prob, pad_size, replace):
  640. """Apply cutout to each bbox in the image with probability prob."""
  641. func_changes_bbox = False
  642. prob = _scale_bbox_only_op_probability(prob)
  643. return _apply_multi_bbox_augmentation_wrapper(
  644. image, bboxes, prob, cutout, func_changes_bbox, pad_size, replace)
  645. def _rotate_bbox(bbox, image_height, image_width, degrees):
  646. """Rotates the bbox coordinated by degrees.
  647. Args:
  648. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
  649. of type float that represents the normalized coordinates between 0 and 1.
  650. image_height: Int, height of the image.
  651. image_width: Int, height of the image.
  652. degrees: Float, a scalar angle in degrees to rotate all images by. If
  653. degrees is positive the image will be rotated clockwise otherwise it will
  654. be rotated counterclockwise.
  655. Returns:
  656. A tensor of the same shape as bbox, but now with the rotated coordinates.
  657. """
  658. image_height, image_width = (float(image_height), float(image_width))
  659. # Convert from degrees to radians.
  660. degrees_to_radians = math.pi / 180.0
  661. radians = degrees * degrees_to_radians
  662. # Translate the bbox to the center of the image and turn the normalized 0-1
  663. # coordinates to absolute pixel locations.
  664. # Y coordinates are made negative as the y axis of images goes down with
  665. # increasing pixel values, so we negate to make sure x axis and y axis points
  666. # are in the traditionally positive direction.
  667. min_y = -int(image_height * (bbox[0] - 0.5))
  668. min_x = int(image_width * (bbox[1] - 0.5))
  669. max_y = -int(image_height * (bbox[2] - 0.5))
  670. max_x = int(image_width * (bbox[3] - 0.5))
  671. coordinates = np.stack([[min_y, min_x], [min_y, max_x], [max_y, min_x],
  672. [max_y, max_x]]).astype(np.float32)
  673. # Rotate the coordinates according to the rotation matrix clockwise if
  674. # radians is positive, else negative
  675. rotation_matrix = np.stack([[math.cos(radians), math.sin(radians)],
  676. [-math.sin(radians), math.cos(radians)]])
  677. new_coords = np.matmul(rotation_matrix,
  678. np.transpose(coordinates)).astype(np.int32)
  679. # Find min/max values and convert them back to normalized 0-1 floats.
  680. min_y = -(float(np.max(new_coords[0, :])) / image_height - 0.5)
  681. min_x = float(np.min(new_coords[1, :])) / image_width + 0.5
  682. max_y = -(float(np.min(new_coords[0, :])) / image_height - 0.5)
  683. max_x = float(np.max(new_coords[1, :])) / image_width + 0.5
  684. # Clip the bboxes to be sure the fall between [0, 1].
  685. min_y, min_x, max_y, max_x = _clip_bbox(min_y, min_x, max_y, max_x)
  686. min_y, min_x, max_y, max_x = _check_bbox_area(min_y, min_x, max_y, max_x)
  687. return np.stack([min_y, min_x, max_y, max_x])
  688. def rotate_with_bboxes(image, bboxes, degrees, replace):
  689. # Rotate the image.
  690. image = rotate(image, degrees, replace)
  691. # Convert bbox coordinates to pixel values.
  692. image_height, image_width = image.shape[:2]
  693. # pylint:disable=g-long-lambda
  694. wrapped_rotate_bbox = lambda bbox: _rotate_bbox(bbox, image_height, image_width, degrees)
  695. # pylint:enable=g-long-lambda
  696. new_bboxes = np.zeros_like(bboxes)
  697. for idx in range(len(bboxes)):
  698. new_bboxes[idx] = wrapped_rotate_bbox(bboxes[idx])
  699. return image, new_bboxes
  700. def translate_x(image, pixels, replace):
  701. """Equivalent of PIL Translate in X dimension."""
  702. image = Image.fromarray(wrap(image))
  703. image = image.transform(image.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0))
  704. return unwrap(np.array(image), replace)
  705. def translate_y(image, pixels, replace):
  706. """Equivalent of PIL Translate in Y dimension."""
  707. image = Image.fromarray(wrap(image))
  708. image = image.transform(image.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels))
  709. return unwrap(np.array(image), replace)
  710. def _shift_bbox(bbox, image_height, image_width, pixels, shift_horizontal):
  711. """Shifts the bbox coordinates by pixels.
  712. Args:
  713. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
  714. of type float that represents the normalized coordinates between 0 and 1.
  715. image_height: Int, height of the image.
  716. image_width: Int, width of the image.
  717. pixels: An int. How many pixels to shift the bbox.
  718. shift_horizontal: Boolean. If true then shift in X dimension else shift in
  719. Y dimension.
  720. Returns:
  721. A tensor of the same shape as bbox, but now with the shifted coordinates.
  722. """
  723. pixels = int(pixels)
  724. # Convert bbox to integer pixel locations.
  725. min_y = int(float(image_height) * bbox[0])
  726. min_x = int(float(image_width) * bbox[1])
  727. max_y = int(float(image_height) * bbox[2])
  728. max_x = int(float(image_width) * bbox[3])
  729. if shift_horizontal:
  730. min_x = np.maximum(0, min_x - pixels)
  731. max_x = np.minimum(image_width, max_x - pixels)
  732. else:
  733. min_y = np.maximum(0, min_y - pixels)
  734. max_y = np.minimum(image_height, max_y - pixels)
  735. # Convert bbox back to floats.
  736. min_y = float(min_y) / float(image_height)
  737. min_x = float(min_x) / float(image_width)
  738. max_y = float(max_y) / float(image_height)
  739. max_x = float(max_x) / float(image_width)
  740. # Clip the bboxes to be sure the fall between [0, 1].
  741. min_y, min_x, max_y, max_x = _clip_bbox(min_y, min_x, max_y, max_x)
  742. min_y, min_x, max_y, max_x = _check_bbox_area(min_y, min_x, max_y, max_x)
  743. return np.stack([min_y, min_x, max_y, max_x])
  744. def translate_bbox(image, bboxes, pixels, replace, shift_horizontal):
  745. """Equivalent of PIL Translate in X/Y dimension that shifts image and bbox.
  746. Args:
  747. image: 3D uint8 Tensor.
  748. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox
  749. has 4 elements (min_y, min_x, max_y, max_x) of type float with values
  750. between [0, 1].
  751. pixels: An int. How many pixels to shift the image and bboxes
  752. replace: A one or three value 1D tensor to fill empty pixels.
  753. shift_horizontal: Boolean. If true then shift in X dimension else shift in
  754. Y dimension.
  755. Returns:
  756. A tuple containing a 3D uint8 Tensor that will be the result of translating
  757. image by pixels. The second element of the tuple is bboxes, where now
  758. the coordinates will be shifted to reflect the shifted image.
  759. """
  760. if shift_horizontal:
  761. image = translate_x(image, pixels, replace)
  762. else:
  763. image = translate_y(image, pixels, replace)
  764. # Convert bbox coordinates to pixel values.
  765. image_height, image_width = image.shape[0], image.shape[1]
  766. # pylint:disable=g-long-lambda
  767. wrapped_shift_bbox = lambda bbox: _shift_bbox(bbox, image_height, image_width, pixels, shift_horizontal)
  768. # pylint:enable=g-long-lambda
  769. new_bboxes = deepcopy(bboxes)
  770. num_bboxes = len(bboxes)
  771. for idx in range(num_bboxes):
  772. new_bboxes[idx] = wrapped_shift_bbox(bboxes[idx])
  773. return image.astype(np.uint8), new_bboxes
  774. def shear_x(image, level, replace):
  775. """Equivalent of PIL Shearing in X dimension."""
  776. # Shear parallel to x axis is a projective transform
  777. # with a matrix form of:
  778. # [1 level
  779. # 0 1].
  780. image = Image.fromarray(wrap(image))
  781. image = image.transform(image.size, Image.AFFINE, (1, level, 0, 0, 1, 0))
  782. return unwrap(np.array(image), replace)
  783. def shear_y(image, level, replace):
  784. """Equivalent of PIL Shearing in Y dimension."""
  785. # Shear parallel to y axis is a projective transform
  786. # with a matrix form of:
  787. # [1 0
  788. # level 1].
  789. image = Image.fromarray(wrap(image))
  790. image = image.transform(image.size, Image.AFFINE, (1, 0, 0, level, 1, 0))
  791. return unwrap(np.array(image), replace)
  792. def _shear_bbox(bbox, image_height, image_width, level, shear_horizontal):
  793. """Shifts the bbox according to how the image was sheared.
  794. Args:
  795. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
  796. of type float that represents the normalized coordinates between 0 and 1.
  797. image_height: Int, height of the image.
  798. image_width: Int, height of the image.
  799. level: Float. How much to shear the image.
  800. shear_horizontal: If true then shear in X dimension else shear in
  801. the Y dimension.
  802. Returns:
  803. A tensor of the same shape as bbox, but now with the shifted coordinates.
  804. """
  805. image_height, image_width = (float(image_height), float(image_width))
  806. # Change bbox coordinates to be pixels.
  807. min_y = int(image_height * bbox[0])
  808. min_x = int(image_width * bbox[1])
  809. max_y = int(image_height * bbox[2])
  810. max_x = int(image_width * bbox[3])
  811. coordinates = np.stack(
  812. [[min_y, min_x], [min_y, max_x], [max_y, min_x], [max_y, max_x]])
  813. coordinates = coordinates.astype(np.float32)
  814. # Shear the coordinates according to the translation matrix.
  815. if shear_horizontal:
  816. translation_matrix = np.stack([[1, 0], [-level, 1]])
  817. else:
  818. translation_matrix = np.stack([[1, -level], [0, 1]])
  819. translation_matrix = translation_matrix.astype(np.float32)
  820. new_coords = np.matmul(translation_matrix,
  821. np.transpose(coordinates)).astype(np.int32)
  822. # Find min/max values and convert them back to floats.
  823. min_y = float(np.min(new_coords[0, :])) / image_height
  824. min_x = float(np.min(new_coords[1, :])) / image_width
  825. max_y = float(np.max(new_coords[0, :])) / image_height
  826. max_x = float(np.max(new_coords[1, :])) / image_width
  827. # Clip the bboxes to be sure the fall between [0, 1].
  828. min_y, min_x, max_y, max_x = _clip_bbox(min_y, min_x, max_y, max_x)
  829. min_y, min_x, max_y, max_x = _check_bbox_area(min_y, min_x, max_y, max_x)
  830. return np.stack([min_y, min_x, max_y, max_x])
  831. def shear_with_bboxes(image, bboxes, level, replace, shear_horizontal):
  832. """Applies Shear Transformation to the image and shifts the bboxes.
  833. Args:
  834. image: 3D uint8 Tensor.
  835. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox
  836. has 4 elements (min_y, min_x, max_y, max_x) of type float with values
  837. between [0, 1].
  838. level: Float. How much to shear the image. This value will be between
  839. -0.3 to 0.3.
  840. replace: A one or three value 1D tensor to fill empty pixels.
  841. shear_horizontal: Boolean. If true then shear in X dimension else shear in
  842. the Y dimension.
  843. Returns:
  844. A tuple containing a 3D uint8 Tensor that will be the result of shearing
  845. image by level. The second element of the tuple is bboxes, where now
  846. the coordinates will be shifted to reflect the sheared image.
  847. """
  848. if shear_horizontal:
  849. image = shear_x(image, level, replace)
  850. else:
  851. image = shear_y(image, level, replace)
  852. # Convert bbox coordinates to pixel values.
  853. image_height, image_width = image.shape[:2]
  854. # pylint:disable=g-long-lambda
  855. wrapped_shear_bbox = lambda bbox: _shear_bbox(bbox, image_height, image_width, level, shear_horizontal)
  856. # pylint:enable=g-long-lambda
  857. new_bboxes = deepcopy(bboxes)
  858. num_bboxes = len(bboxes)
  859. for idx in range(num_bboxes):
  860. new_bboxes[idx] = wrapped_shear_bbox(bboxes[idx])
  861. return image.astype(np.uint8), new_bboxes
  862. def autocontrast(image):
  863. """Implements Autocontrast function from PIL.
  864. Args:
  865. image: A 3D uint8 tensor.
  866. Returns:
  867. The image after it has had autocontrast applied to it and will be of type
  868. uint8.
  869. """
  870. def scale_channel(image):
  871. """Scale the 2D image using the autocontrast rule."""
  872. # A possibly cheaper version can be done using cumsum/unique_with_counts
  873. # over the histogram values, rather than iterating over the entire image.
  874. # to compute mins and maxes.
  875. lo = float(np.min(image))
  876. hi = float(np.max(image))
  877. # Scale the image, making the lowest value 0 and the highest value 255.
  878. def scale_values(im):
  879. scale = 255.0 / (hi - lo)
  880. offset = -lo * scale
  881. im = im.astype(np.float32) * scale + offset
  882. img = np.clip(im, a_min=0, a_max=255.0)
  883. return im.astype(np.uint8)
  884. result = scale_values(image) if hi > lo else image
  885. return result
  886. # Assumes RGB for now. Scales each channel independently
  887. # and then stacks the result.
  888. s1 = scale_channel(image[:, :, 0])
  889. s2 = scale_channel(image[:, :, 1])
  890. s3 = scale_channel(image[:, :, 2])
  891. image = np.stack([s1, s2, s3], 2)
  892. return image
  893. def sharpness(image, factor):
  894. """Implements Sharpness function from PIL."""
  895. orig_image = image
  896. image = image.astype(np.float32)
  897. # Make image 4D for conv operation.
  898. # SMOOTH PIL Kernel.
  899. kernel = np.array([[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=np.float32) / 13.
  900. result = cv2.filter2D(image, -1, kernel).astype(np.uint8)
  901. # Blend the final result.
  902. return blend(result, orig_image, factor)
  903. def equalize(image):
  904. """Implements Equalize function from PIL using."""
  905. def scale_channel(im, c):
  906. """Scale the data in the channel to implement equalize."""
  907. im = im[:, :, c].astype(np.int32)
  908. # Compute the histogram of the image channel.
  909. histo, _ = np.histogram(im, range=[0, 255], bins=256)
  910. # For the purposes of computing the step, filter out the nonzeros.
  911. nonzero = np.where(np.not_equal(histo, 0))
  912. nonzero_histo = np.reshape(np.take(histo, nonzero), [-1])
  913. step = (np.sum(nonzero_histo) - nonzero_histo[-1]) // 255
  914. def build_lut(histo, step):
  915. # Compute the cumulative sum, shifting by step // 2
  916. # and then normalization by step.
  917. lut = (np.cumsum(histo) + (step // 2)) // step
  918. # Shift lut, prepending with 0.
  919. lut = np.concatenate([[0], lut[:-1]], 0)
  920. # Clip the counts to be in range. This is done
  921. # in the C code for image.point.
  922. return np.clip(lut, a_min=0, a_max=255).astype(np.uint8)
  923. # If step is zero, return the original image. Otherwise, build
  924. # lut from the full histogram and step and then index from it.
  925. if step == 0:
  926. result = im
  927. else:
  928. result = np.take(build_lut(histo, step), im)
  929. return result.astype(np.uint8)
  930. # Assumes RGB for now. Scales each channel independently
  931. # and then stacks the result.
  932. s1 = scale_channel(image, 0)
  933. s2 = scale_channel(image, 1)
  934. s3 = scale_channel(image, 2)
  935. image = np.stack([s1, s2, s3], 2)
  936. return image
  937. def wrap(image):
  938. """Returns 'image' with an extra channel set to all 1s."""
  939. shape = image.shape
  940. extended_channel = 255 * np.ones([shape[0], shape[1], 1], image.dtype)
  941. extended = np.concatenate([image, extended_channel], 2).astype(image.dtype)
  942. return extended
  943. def unwrap(image, replace):
  944. """Unwraps an image produced by wrap.
  945. Where there is a 0 in the last channel for every spatial position,
  946. the rest of the three channels in that spatial dimension are grayed
  947. (set to 128). Operations like translate and shear on a wrapped
  948. Tensor will leave 0s in empty locations. Some transformations look
  949. at the intensity of values to do preprocessing, and we want these
  950. empty pixels to assume the 'average' value, rather than pure black.
  951. Args:
  952. image: A 3D Image Tensor with 4 channels.
  953. replace: A one or three value 1D tensor to fill empty pixels.
  954. Returns:
  955. image: A 3D image Tensor with 3 channels.
  956. """
  957. image_shape = image.shape
  958. # Flatten the spatial dimensions.
  959. flattened_image = np.reshape(image, [-1, image_shape[2]])
  960. # Find all pixels where the last channel is zero.
  961. alpha_channel = flattened_image[:, 3]
  962. replace = np.concatenate([replace, np.ones([1], image.dtype)], 0)
  963. # Where they are zero, fill them in with 'replace'.
  964. alpha_channel = np.reshape(alpha_channel, (-1, 1))
  965. alpha_channel = np.tile(alpha_channel, reps=(1, flattened_image.shape[1]))
  966. flattened_image = np.where(
  967. np.equal(alpha_channel, 0),
  968. np.ones_like(
  969. flattened_image, dtype=image.dtype) * replace,
  970. flattened_image)
  971. image = np.reshape(flattened_image, image_shape)
  972. image = image[:, :, :3]
  973. return image.astype(np.uint8)
  974. def _cutout_inside_bbox(image, bbox, pad_fraction):
  975. """Generates cutout mask and the mean pixel value of the bbox.
  976. First a location is randomly chosen within the image as the center where the
  977. cutout mask will be applied. Note this can be towards the boundaries of the
  978. image, so the full cutout mask may not be applied.
  979. Args:
  980. image: 3D uint8 Tensor.
  981. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
  982. of type float that represents the normalized coordinates between 0 and 1.
  983. pad_fraction: Float that specifies how large the cutout mask should be in
  984. in reference to the size of the original bbox. If pad_fraction is 0.25,
  985. then the cutout mask will be of shape
  986. (0.25 * bbox height, 0.25 * bbox width).
  987. Returns:
  988. A tuple. Fist element is a tensor of the same shape as image where each
  989. element is either a 1 or 0 that is used to determine where the image
  990. will have cutout applied. The second element is the mean of the pixels
  991. in the image where the bbox is located.
  992. mask value: [0,1]
  993. """
  994. image_height, image_width = image.shape[0], image.shape[1]
  995. # Transform from shape [1, 4] to [4].
  996. bbox = np.squeeze(bbox)
  997. min_y = int(float(image_height) * bbox[0])
  998. min_x = int(float(image_width) * bbox[1])
  999. max_y = int(float(image_height) * bbox[2])
  1000. max_x = int(float(image_width) * bbox[3])
  1001. # Calculate the mean pixel values in the bounding box, which will be used
  1002. # to fill the cutout region.
  1003. mean = np.mean(image[min_y:max_y + 1, min_x:max_x + 1], axis=(0, 1))
  1004. # Cutout mask will be size pad_size_heigh * 2 by pad_size_width * 2 if the
  1005. # region lies entirely within the bbox.
  1006. box_height = max_y - min_y + 1
  1007. box_width = max_x - min_x + 1
  1008. pad_size_height = int(pad_fraction * (box_height / 2))
  1009. pad_size_width = int(pad_fraction * (box_width / 2))
  1010. # Sample the center location in the image where the zero mask will be applied.
  1011. cutout_center_height = np.random.randint(min_y, max_y + 1, dtype=np.int32)
  1012. cutout_center_width = np.random.randint(min_x, max_x + 1, dtype=np.int32)
  1013. lower_pad = np.maximum(0, cutout_center_height - pad_size_height)
  1014. upper_pad = np.maximum(
  1015. 0, image_height - cutout_center_height - pad_size_height)
  1016. left_pad = np.maximum(0, cutout_center_width - pad_size_width)
  1017. right_pad = np.maximum(0,
  1018. image_width - cutout_center_width - pad_size_width)
  1019. cutout_shape = [
  1020. image_height - (lower_pad + upper_pad),
  1021. image_width - (left_pad + right_pad)
  1022. ]
  1023. padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]
  1024. mask = np.pad(np.zeros(
  1025. cutout_shape, dtype=image.dtype),
  1026. padding_dims,
  1027. 'constant',
  1028. constant_values=1)
  1029. mask = np.expand_dims(mask, 2)
  1030. mask = np.tile(mask, [1, 1, 3])
  1031. return mask, mean
  1032. def bbox_cutout(image, bboxes, pad_fraction, replace_with_mean):
  1033. """Applies cutout to the image according to bbox information.
  1034. This is a cutout variant that using bbox information to make more informed
  1035. decisions on where to place the cutout mask.
  1036. Args:
  1037. image: 3D uint8 Tensor.
  1038. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox
  1039. has 4 elements (min_y, min_x, max_y, max_x) of type float with values
  1040. between [0, 1].
  1041. pad_fraction: Float that specifies how large the cutout mask should be in
  1042. in reference to the size of the original bbox. If pad_fraction is 0.25,
  1043. then the cutout mask will be of shape
  1044. (0.25 * bbox height, 0.25 * bbox width).
  1045. replace_with_mean: Boolean that specified what value should be filled in
  1046. where the cutout mask is applied. Since the incoming image will be of
  1047. uint8 and will not have had any mean normalization applied, by default
  1048. we set the value to be 128. If replace_with_mean is True then we find
  1049. the mean pixel values across the channel dimension and use those to fill
  1050. in where the cutout mask is applied.
  1051. Returns:
  1052. A tuple. First element is a tensor of the same shape as image that has
  1053. cutout applied to it. Second element is the bboxes that were passed in
  1054. that will be unchanged.
  1055. """
  1056. def apply_bbox_cutout(image, bboxes, pad_fraction):
  1057. """Applies cutout to a single bounding box within image."""
  1058. # Choose a single bounding box to apply cutout to.
  1059. random_index = np.random.randint(0, bboxes.shape[0], dtype=np.int32)
  1060. # Select the corresponding bbox and apply cutout.
  1061. chosen_bbox = np.take(bboxes, random_index, axis=0)
  1062. mask, mean = _cutout_inside_bbox(image, chosen_bbox, pad_fraction)
  1063. # When applying cutout we either set the pixel value to 128 or to the mean
  1064. # value inside the bbox.
  1065. replace = mean if replace_with_mean else [128] * 3
  1066. # Apply the cutout mask to the image. Where the mask is 0 we fill it with
  1067. # `replace`.
  1068. image = np.where(
  1069. np.equal(mask, 0),
  1070. np.ones_like(
  1071. image, dtype=image.dtype) * replace,
  1072. image).astype(image.dtype)
  1073. return image
  1074. # Check to see if there are boxes, if so then apply boxcutout.
  1075. if len(bboxes) != 0:
  1076. image = apply_bbox_cutout(image, bboxes, pad_fraction)
  1077. return image, bboxes
  1078. NAME_TO_FUNC = {
  1079. 'AutoContrast': autocontrast,
  1080. 'Equalize': equalize,
  1081. 'Posterize': posterize,
  1082. 'Solarize': solarize,
  1083. 'SolarizeAdd': solarize_add,
  1084. 'Color': color,
  1085. 'Contrast': contrast,
  1086. 'Brightness': brightness,
  1087. 'Sharpness': sharpness,
  1088. 'Cutout': cutout,
  1089. 'BBox_Cutout': bbox_cutout,
  1090. 'Rotate_BBox': rotate_with_bboxes,
  1091. # pylint:disable=g-long-lambda
  1092. 'TranslateX_BBox': lambda image, bboxes, pixels, replace: translate_bbox(
  1093. image, bboxes, pixels, replace, shift_horizontal=True),
  1094. 'TranslateY_BBox': lambda image, bboxes, pixels, replace: translate_bbox(
  1095. image, bboxes, pixels, replace, shift_horizontal=False),
  1096. 'ShearX_BBox': lambda image, bboxes, level, replace: shear_with_bboxes(
  1097. image, bboxes, level, replace, shear_horizontal=True),
  1098. 'ShearY_BBox': lambda image, bboxes, level, replace: shear_with_bboxes(
  1099. image, bboxes, level, replace, shear_horizontal=False),
  1100. # pylint:enable=g-long-lambda
  1101. 'Rotate_Only_BBoxes': rotate_only_bboxes,
  1102. 'ShearX_Only_BBoxes': shear_x_only_bboxes,
  1103. 'ShearY_Only_BBoxes': shear_y_only_bboxes,
  1104. 'TranslateX_Only_BBoxes': translate_x_only_bboxes,
  1105. 'TranslateY_Only_BBoxes': translate_y_only_bboxes,
  1106. 'Flip_Only_BBoxes': flip_only_bboxes,
  1107. 'Solarize_Only_BBoxes': solarize_only_bboxes,
  1108. 'Equalize_Only_BBoxes': equalize_only_bboxes,
  1109. 'Cutout_Only_BBoxes': cutout_only_bboxes,
  1110. }
  1111. def _randomly_negate_tensor(tensor):
  1112. """With 50% prob turn the tensor negative."""
  1113. should_flip = np.floor(np.random.rand() + 0.5) >= 1
  1114. final_tensor = tensor if should_flip else -tensor
  1115. return final_tensor
  1116. def _rotate_level_to_arg(level):
  1117. level = (level / _MAX_LEVEL) * 30.
  1118. level = _randomly_negate_tensor(level)
  1119. return (level, )
  1120. def _shrink_level_to_arg(level):
  1121. """Converts level to ratio by which we shrink the image content."""
  1122. if level == 0:
  1123. return (1.0, ) # if level is zero, do not shrink the image
  1124. # Maximum shrinking ratio is 2.9.
  1125. level = 2. / (_MAX_LEVEL / level) + 0.9
  1126. return (level, )
  1127. def _enhance_level_to_arg(level):
  1128. return ((level / _MAX_LEVEL) * 1.8 + 0.1, )
  1129. def _shear_level_to_arg(level):
  1130. level = (level / _MAX_LEVEL) * 0.3
  1131. # Flip level to negative with 50% chance.
  1132. level = _randomly_negate_tensor(level)
  1133. return (level, )
  1134. def _translate_level_to_arg(level, translate_const):
  1135. level = (level / _MAX_LEVEL) * float(translate_const)
  1136. # Flip level to negative with 50% chance.
  1137. level = _randomly_negate_tensor(level)
  1138. return (level, )
  1139. def _bbox_cutout_level_to_arg(level, hparams):
  1140. cutout_pad_fraction = (level /
  1141. _MAX_LEVEL) * 0.75 # hparams.cutout_max_pad_fraction
  1142. return (cutout_pad_fraction, False) # hparams.cutout_bbox_replace_with_mean
  1143. def level_to_arg(hparams):
  1144. return {
  1145. 'AutoContrast': lambda level: (),
  1146. 'Equalize': lambda level: (),
  1147. 'Posterize': lambda level: (int((level / _MAX_LEVEL) * 4), ),
  1148. 'Solarize': lambda level: (int((level / _MAX_LEVEL) * 256), ),
  1149. 'SolarizeAdd': lambda level: (int((level / _MAX_LEVEL) * 110), ),
  1150. 'Color': _enhance_level_to_arg,
  1151. 'Contrast': _enhance_level_to_arg,
  1152. 'Brightness': _enhance_level_to_arg,
  1153. 'Sharpness': _enhance_level_to_arg,
  1154. 'Cutout':
  1155. lambda level: (int((level / _MAX_LEVEL) * 100), ), # hparams.cutout_const=100
  1156. # pylint:disable=g-long-lambda
  1157. 'BBox_Cutout': lambda level: _bbox_cutout_level_to_arg(level, hparams),
  1158. 'TranslateX_BBox':
  1159. lambda level: _translate_level_to_arg(level, 250), # hparams.translate_const=250
  1160. 'TranslateY_BBox':
  1161. lambda level: _translate_level_to_arg(level, 250), # hparams.translate_cons
  1162. # pylint:enable=g-long-lambda
  1163. 'ShearX_BBox': _shear_level_to_arg,
  1164. 'ShearY_BBox': _shear_level_to_arg,
  1165. 'Rotate_BBox': _rotate_level_to_arg,
  1166. 'Rotate_Only_BBoxes': _rotate_level_to_arg,
  1167. 'ShearX_Only_BBoxes': _shear_level_to_arg,
  1168. 'ShearY_Only_BBoxes': _shear_level_to_arg,
  1169. # pylint:disable=g-long-lambda
  1170. 'TranslateX_Only_BBoxes':
  1171. lambda level: _translate_level_to_arg(level, 120), # hparams.translate_bbox_const
  1172. 'TranslateY_Only_BBoxes':
  1173. lambda level: _translate_level_to_arg(level, 120), # hparams.translate_bbox_const
  1174. # pylint:enable=g-long-lambda
  1175. 'Flip_Only_BBoxes': lambda level: (),
  1176. 'Solarize_Only_BBoxes':
  1177. lambda level: (int((level / _MAX_LEVEL) * 256), ),
  1178. 'Equalize_Only_BBoxes': lambda level: (),
  1179. # pylint:disable=g-long-lambda
  1180. 'Cutout_Only_BBoxes':
  1181. lambda level: (int((level / _MAX_LEVEL) * 50), ), # hparams.cutout_bbox_const
  1182. # pylint:enable=g-long-lambda
  1183. }
  1184. def bbox_wrapper(func):
  1185. """Adds a bboxes function argument to func and returns unchanged bboxes."""
  1186. def wrapper(images, bboxes, *args, **kwargs):
  1187. return (func(images, *args, **kwargs), bboxes)
  1188. return wrapper
  1189. def _parse_policy_info(name, prob, level, replace_value, augmentation_hparams):
  1190. """Return the function that corresponds to `name` and update `level` param."""
  1191. func = NAME_TO_FUNC[name]
  1192. args = level_to_arg(augmentation_hparams)[name](level)
  1193. # Check to see if prob is passed into function. This is used for operations
  1194. # where we alter bboxes independently.
  1195. # pytype:disable=wrong-arg-types
  1196. if 'prob' in inspect.getfullargspec(func)[0]:
  1197. args = tuple([prob] + list(args))
  1198. # pytype:enable=wrong-arg-types
  1199. # Add in replace arg if it is required for the function that is being called.
  1200. if 'replace' in inspect.getfullargspec(func)[0]:
  1201. # Make sure replace is the final argument
  1202. assert 'replace' == inspect.getfullargspec(func)[0][-1]
  1203. args = tuple(list(args) + [replace_value])
  1204. # Add bboxes as the second positional argument for the function if it does
  1205. # not already exist.
  1206. if 'bboxes' not in inspect.getfullargspec(func)[0]:
  1207. func = bbox_wrapper(func)
  1208. return (func, prob, args)
  1209. def _apply_func_with_prob(func, image, args, prob, bboxes):
  1210. """Apply `func` to image w/ `args` as input with probability `prob`."""
  1211. assert isinstance(args, tuple)
  1212. assert 'bboxes' == inspect.getfullargspec(func)[0][1]
  1213. # If prob is a function argument, then this randomness is being handled
  1214. # inside the function, so make sure it is always called.
  1215. if 'prob' in inspect.getfullargspec(func)[0]:
  1216. prob = 1.0
  1217. # Apply the function with probability `prob`.
  1218. should_apply_op = np.floor(np.random.rand() + 0.5) >= 1
  1219. if should_apply_op:
  1220. augmented_image, augmented_bboxes = func(image, bboxes, *args)
  1221. else:
  1222. augmented_image, augmented_bboxes = (image, bboxes)
  1223. return augmented_image, augmented_bboxes
  1224. def select_and_apply_random_policy(policies, image, bboxes):
  1225. """Select a random policy from `policies` and apply it to `image`."""
  1226. policy_to_select = np.random.randint(0, len(policies), dtype=np.int32)
  1227. # policy_to_select = 6 # for test
  1228. for (i, policy) in enumerate(policies):
  1229. if i == policy_to_select:
  1230. image, bboxes = policy(image, bboxes)
  1231. return (image, bboxes)
  1232. def build_and_apply_nas_policy(policies, image, bboxes, augmentation_hparams):
  1233. """Build a policy from the given policies passed in and apply to image.
  1234. Args:
  1235. policies: list of lists of tuples in the form `(func, prob, level)`, `func`
  1236. is a string name of the augmentation function, `prob` is the probability
  1237. of applying the `func` operation, `level` is the input argument for
  1238. `func`.
  1239. image: numpy array that the resulting policy will be applied to.
  1240. bboxes:
  1241. augmentation_hparams: Hparams associated with the NAS learned policy.
  1242. Returns:
  1243. A version of image that now has data augmentation applied to it based on
  1244. the `policies` pass into the function. Additionally, returns bboxes if
  1245. a value for them is passed in that is not None
  1246. """
  1247. replace_value = [128, 128, 128]
  1248. # func is the string name of the augmentation function, prob is the
  1249. # probability of applying the operation and level is the parameter associated
  1250. # tf_policies are functions that take in an image and return an augmented
  1251. # image.
  1252. tf_policies = []
  1253. for policy in policies:
  1254. tf_policy = []
  1255. # Link string name to the correct python function and make sure the correct
  1256. # argument is passed into that function.
  1257. for policy_info in policy:
  1258. policy_info = list(
  1259. policy_info) + [replace_value, augmentation_hparams]
  1260. tf_policy.append(_parse_policy_info(*policy_info))
  1261. # Now build the tf policy that will apply the augmentation procedue
  1262. # on image.
  1263. def make_final_policy(tf_policy_):
  1264. def final_policy(image_, bboxes_):
  1265. for func, prob, args in tf_policy_:
  1266. image_, bboxes_ = _apply_func_with_prob(func, image_, args,
  1267. prob, bboxes_)
  1268. return image_, bboxes_
  1269. return final_policy
  1270. tf_policies.append(make_final_policy(tf_policy))
  1271. augmented_images, augmented_bboxes = select_and_apply_random_policy(
  1272. tf_policies, image, bboxes)
  1273. # If no bounding boxes were specified, then just return the images.
  1274. return (augmented_images, augmented_bboxes)
  1275. # TODO(barretzoph): Add in ArXiv link once paper is out.
  1276. def distort_image_with_autoaugment(image, bboxes, augmentation_name):
  1277. """Applies the AutoAugment policy to `image` and `bboxes`.
  1278. Args:
  1279. image: `Tensor` of shape [height, width, 3] representing an image.
  1280. bboxes: `Tensor` of shape [N, 4] representing ground truth boxes that are
  1281. normalized between [0, 1].
  1282. augmentation_name: The name of the AutoAugment policy to use. The available
  1283. options are `v0`, `v1`, `v2`, `v3` and `test`. `v0` is the policy used for
  1284. all of the results in the paper and was found to achieve the best results
  1285. on the COCO dataset. `v1`, `v2` and `v3` are additional good policies
  1286. found on the COCO dataset that have slight variation in what operations
  1287. were used during the search procedure along with how many operations are
  1288. applied in parallel to a single image (2 vs 3).
  1289. Returns:
  1290. A tuple containing the augmented versions of `image` and `bboxes`.
  1291. """
  1292. available_policies = {
  1293. 'v0': policy_v0,
  1294. 'v1': policy_v1,
  1295. 'v2': policy_v2,
  1296. 'v3': policy_v3,
  1297. 'test': policy_vtest
  1298. }
  1299. if augmentation_name not in available_policies:
  1300. raise ValueError('Invalid augmentation_name: {}'.format(
  1301. augmentation_name))
  1302. policy = available_policies[augmentation_name]()
  1303. augmentation_hparams = {}
  1304. return build_and_apply_nas_policy(policy, image, bboxes,
  1305. augmentation_hparams)