autoaugment_utils.py 64 KB

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