autoaugment_utils.py 64 KB

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