autoaugment_utils.py 64 KB

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