operators.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. # copyright (c) 2021 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. import numpy as np
  15. import cv2
  16. import copy
  17. import random
  18. from PIL import Image
  19. import paddlex
  20. try:
  21. from collections.abc import Sequence
  22. except Exception:
  23. from collections import Sequence
  24. from numbers import Number
  25. from .functions import normalize, horizontal_flip, permute, vertical_flip, center_crop, is_poly, \
  26. horizontal_flip_poly, horizontal_flip_rle, vertical_flip_poly, vertical_flip_rle, crop_poly, \
  27. crop_rle, expand_poly, expand_rle, resize_poly, resize_rle
  28. __all__ = [
  29. "Compose", "Decode", "Resize", "RandomResize", "ResizeByShort",
  30. "RandomResizeByShort", "RandomHorizontalFlip", "RandomVerticalFlip",
  31. "Normalize", "CenterCrop", "RandomCrop", "RandomExpand", "Padding",
  32. "MixupImage", "RandomDistort", "ArrangeSegmenter", "ArrangeClassifier",
  33. "ArrangeDetector"
  34. ]
  35. interp_dict = {
  36. 'NEAREST': cv2.INTER_NEAREST,
  37. 'LINEAR': cv2.INTER_LINEAR,
  38. 'CUBIC': cv2.INTER_CUBIC,
  39. 'AREA': cv2.INTER_AREA,
  40. 'LANCZOS4': cv2.INTER_LANCZOS4
  41. }
  42. class Transform(object):
  43. """
  44. Parent class of all data augmentation operations
  45. """
  46. def __init__(self):
  47. pass
  48. def apply_im(self, image):
  49. pass
  50. def apply_mask(self, mask):
  51. pass
  52. def apply_bbox(self, bbox):
  53. pass
  54. def apply_segm(self, segms):
  55. pass
  56. def apply(self, sample):
  57. sample['image'] = self.apply_im(sample['image'])
  58. if 'mask' in sample:
  59. sample['mask'] = self.apply_mask(sample['mask'])
  60. if 'gt_bbox' in sample:
  61. sample['gt_bbox'] = self.apply_bbox(sample['gt_bbox'])
  62. return sample
  63. def __call__(self, sample):
  64. if isinstance(sample, Sequence):
  65. sample = [self.apply(s) for s in sample]
  66. else:
  67. sample = self.apply(sample)
  68. return sample
  69. class Compose(Transform):
  70. """
  71. Apply a series of data augmentation to the input.
  72. All input images are in Height-Width-Channel ([H, W, C]) format.
  73. Args:
  74. transforms (List[paddlex.transforms.Transform]): List of data preprocess or augmentations.
  75. Raises:
  76. TypeError: Invalid type of transforms.
  77. ValueError: Invalid length of transforms.
  78. """
  79. def __init__(self, transforms):
  80. super(Compose, self).__init__()
  81. if not isinstance(transforms, list):
  82. raise TypeError(
  83. 'Type of transforms is invalid. Must be List, but received is {}'
  84. .format(type(transforms)))
  85. if len(transforms) < 1:
  86. raise ValueError(
  87. 'Length of transforms must not be less than 1, but received is {}'
  88. .format(len(transforms)))
  89. self.transforms = transforms
  90. self.decode_image = Decode()
  91. self.arrange_outputs = None
  92. self.apply_im_only = False
  93. def __call__(self, sample):
  94. if self.apply_im_only and 'mask' in sample:
  95. mask_backup = copy.deepcopy(sample['mask'])
  96. del sample['mask']
  97. sample = self.decode_image(sample)
  98. for op in self.transforms:
  99. # skip batch transforms amd mixup
  100. if isinstance(op, (paddlex.transforms.BatchRandomResize,
  101. paddlex.transforms.BatchRandomResizeByShort,
  102. MixupImage)):
  103. continue
  104. sample = op(sample)
  105. if self.arrange_outputs is not None:
  106. if self.apply_im_only:
  107. sample['mask'] = mask_backup
  108. sample = self.arrange_outputs(sample)
  109. return sample
  110. class Decode(Transform):
  111. """
  112. Decode image(s) in input.
  113. Args:
  114. to_rgb (bool, optional): If True, convert input images from BGR format to RGB format. Defaults to True.
  115. """
  116. def __init__(self, to_rgb=True):
  117. super(Decode, self).__init__()
  118. self.to_rgb = to_rgb
  119. def read_img(self, img_path):
  120. return cv2.imread(img_path, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_ANYCOLOR |
  121. cv2.IMREAD_COLOR)
  122. def apply_im(self, im_path):
  123. if isinstance(im_path, str):
  124. try:
  125. image = self.read_img(im_path)
  126. except:
  127. raise ValueError('Cannot read the image file {}!'.format(
  128. im_path))
  129. else:
  130. image = im_path
  131. if self.to_rgb:
  132. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  133. return image
  134. def apply_mask(self, mask):
  135. try:
  136. mask = np.asarray(Image.open(mask))
  137. except:
  138. raise ValueError("Cannot read the mask file {}!".format(mask))
  139. if len(mask.shape) != 2:
  140. raise Exception(
  141. "Mask should be a 1-channel image, but recevied is a {}-channel image.".
  142. format(mask.shape[2]))
  143. return mask
  144. def apply(self, sample):
  145. """
  146. Args:
  147. sample (dict): Input sample, containing 'image' at least.
  148. Returns:
  149. dict: Decoded sample.
  150. """
  151. sample['image'] = self.apply_im(sample['image'])
  152. if 'mask' in sample:
  153. sample['mask'] = self.apply_mask(sample['mask'])
  154. im_height, im_width, _ = sample['image'].shape
  155. se_height, se_width = sample['mask'].shape
  156. if im_height != se_height or im_width != se_width:
  157. raise Exception(
  158. "The height or width of the im is not same as the mask")
  159. sample['im_shape'] = np.array(
  160. sample['image'].shape[:2], dtype=np.float32)
  161. sample['scale_factor'] = np.array([1., 1.], dtype=np.float32)
  162. return sample
  163. class Resize(Transform):
  164. """
  165. Resize input.
  166. - If target_size is an int,resize the image(s) to (target_size, target_size).
  167. - If target_size is a list or tuple, resize the image(s) to target_size.
  168. Attention:If interp is 'RANDOM', the interpolation method will be chose randomly.
  169. Args:
  170. target_size (int, List[int] or Tuple[int]): Target size. If int, the height and width share the same target_size.
  171. Otherwise, target_size represents [target height, target width].
  172. interp ({'NEAREST', 'LINEAR', 'CUBIC', 'AREA', 'LANCZOS4', 'RANDOM'}, optional):
  173. Interpolation method of resize. Defaults to 'LINEAR'.
  174. keep_ratio (bool): the resize scale of width/height is same and width/height after resized is not greater
  175. than target width/height. Defaults to False.
  176. Raises:
  177. TypeError: Invalid type of target_size.
  178. ValueError: Invalid interpolation method.
  179. """
  180. def __init__(self, target_size, interp='LINEAR', keep_ratio=False):
  181. super(Resize, self).__init__()
  182. if not (interp == "RANDOM" or interp in interp_dict):
  183. raise ValueError("interp should be one of {}".format(
  184. interp_dict.keys()))
  185. if isinstance(target_size, int):
  186. target_size = (target_size, target_size)
  187. else:
  188. if not (isinstance(target_size,
  189. (list, tuple)) and len(target_size) == 2):
  190. raise TypeError(
  191. "target_size should be an int or a list of length 2, but received {}".
  192. format(target_size))
  193. # (height, width)
  194. self.target_size = target_size
  195. self.interp = interp
  196. self.keep_ratio = keep_ratio
  197. def apply_im(self, image, interp):
  198. image = cv2.resize(
  199. image, (self.target_size[1], self.target_size[0]),
  200. interpolation=interp)
  201. return image
  202. def apply_mask(self, mask):
  203. mask = cv2.resize(
  204. mask, (self.target_size[1], self.target_size[0]),
  205. interpolation=cv2.INTER_NEAREST)
  206. return mask
  207. def apply_bbox(self, bbox, scale):
  208. im_scale_x, im_scale_y = scale
  209. bbox[:, 0::2] *= im_scale_x
  210. bbox[:, 1::2] *= im_scale_y
  211. bbox[:, 0::2] = np.clip(bbox[:, 0::2], 0, self.target_size[1])
  212. bbox[:, 1::2] = np.clip(bbox[:, 1::2], 0, self.target_size[0])
  213. return bbox
  214. def apply_segm(self, segms, im_size, scale):
  215. im_h, im_w = im_size
  216. im_scale_x, im_scale_y = scale
  217. resized_segms = []
  218. for segm in segms:
  219. if is_poly(segm):
  220. # Polygon format
  221. resized_segms.append([
  222. resize_poly(poly, im_scale_x, im_scale_y) for poly in segm
  223. ])
  224. else:
  225. # RLE format
  226. resized_segms.append(
  227. resize_rle(segm, im_h, im_w, im_scale_x, im_scale_y))
  228. return resized_segms
  229. def apply(self, sample):
  230. if self.interp == "RANDOM":
  231. interp = random.choice(list(interp_dict.values()))
  232. else:
  233. interp = interp_dict[self.interp]
  234. im_h, im_w = sample['image'].shape[:2]
  235. im_scale_y = self.target_size[0] / im_h
  236. im_scale_x = self.target_size[1] / im_w
  237. target_size = list(self.target_size)
  238. if self.keep_ratio:
  239. scale = min(im_scale_y, im_scale_x)
  240. target_w = int(round(im_w * scale))
  241. target_h = int(round(im_h * scale))
  242. target_size = [target_w, target_h]
  243. im_scale_y = target_h / im_h
  244. im_scale_x = target_w / im_w
  245. sample['image'] = self.apply_im(sample['image'], interp)
  246. if 'mask' in sample:
  247. sample['mask'] = self.apply_mask(sample['mask'])
  248. if 'gt_bbox' in sample and len(sample['gt_bbox']) > 0:
  249. sample['gt_bbox'] = self.apply_bbox(sample['gt_bbox'],
  250. [im_scale_x, im_scale_y])
  251. if 'gt_poly' in sample and len(sample['gt_poly']) > 0:
  252. sample['gt_poly'] = self.apply_segm(
  253. sample['gt_poly'], [im_h, im_w], [im_scale_x, im_scale_y])
  254. sample['im_shape'] = np.asarray(
  255. sample['image'].shape[:2], dtype=np.float32)
  256. if 'scale_factor' in sample:
  257. scale_factor = sample['scale_factor']
  258. sample['scale_factor'] = np.asarray(
  259. [scale_factor[0] * im_scale_y, scale_factor[1] * im_scale_x],
  260. dtype=np.float32)
  261. return sample
  262. class RandomResize(Transform):
  263. """
  264. Resize input to random sizes.
  265. Attention:If interp is 'RANDOM', the interpolation method will be chose randomly.
  266. Args:
  267. target_sizes (List[int], List[list or tuple] or Tuple[lsit or tuple]):
  268. Multiple target sizes, each target size is an int or list/tuple.
  269. interp ({'NEAREST', 'LINEAR', 'CUBIC', 'AREA', 'LANCZOS4', 'RANDOM'}, optional):
  270. Interpolation method of resize. Defaults to 'LINEAR'.
  271. Raises:
  272. TypeError: Invalid type of target_size.
  273. ValueError: Invalid interpolation method.
  274. See Also:
  275. Resize input to a specific size.
  276. """
  277. def __init__(self, target_sizes, interp='LINEAR'):
  278. super(RandomResize, self).__init__()
  279. if not (interp == "RANDOM" or interp in interp_dict):
  280. raise ValueError("interp should be one of {}".format(
  281. interp_dict.keys()))
  282. self.interp = interp
  283. assert isinstance(target_sizes, list), \
  284. "target_size must be List"
  285. for i, item in enumerate(target_sizes):
  286. if isinstance(item, int):
  287. target_sizes[i] = (item, item)
  288. self.target_size = target_sizes
  289. def apply(self, sample):
  290. height, width = random.choice(self.target_size)
  291. resizer = Resize((height, width), interp=self.interp)
  292. sample = resizer(sample)
  293. return sample
  294. class ResizeByShort(Transform):
  295. """
  296. Resize input with keeping the aspect ratio.
  297. Attention:If interp is 'RANDOM', the interpolation method will be chose randomly.
  298. Args:
  299. short_size (int): Target size of the shorter side of the image(s).
  300. max_size (int, optional): The upper bound of longer side of the image(s). If max_size is -1, no upper bound is applied. Defaults to -1.
  301. interp ({'NEAREST', 'LINEAR', 'CUBIC', 'AREA', 'LANCZOS4', 'RANDOM'}, optional): Interpolation method of resize. Defaults to 'LINEAR'.
  302. Raises:
  303. ValueError: Invalid interpolation method.
  304. """
  305. def __init__(self, short_size=256, max_size=-1, interp='LINEAR'):
  306. if not (interp == "RANDOM" or interp in interp_dict):
  307. raise ValueError("interp should be one of {}".format(
  308. interp_dict.keys()))
  309. super(ResizeByShort, self).__init__()
  310. self.short_size = short_size
  311. self.max_size = max_size
  312. self.interp = interp
  313. def apply_im(self, image, interp, target_size):
  314. image = cv2.resize(image, target_size, interpolation=interp)
  315. return image
  316. def apply_mask(self, mask, target_size):
  317. mask = cv2.resize(mask, target_size, interpolation=cv2.INTER_NEAREST)
  318. return mask
  319. def apply_bbox(self, bbox, scale, target_size):
  320. im_scale_x, im_scale_y = scale
  321. bbox[:, 0::2] *= im_scale_x
  322. bbox[:, 1::2] *= im_scale_y
  323. bbox[:, 0::2] = np.clip(bbox[:, 0::2], 0, target_size[1])
  324. bbox[:, 1::2] = np.clip(bbox[:, 1::2], 0, target_size[0])
  325. return bbox
  326. def apply_segm(self, segms, im_size, scale):
  327. im_h, im_w = im_size
  328. im_scale_x, im_scale_y = scale
  329. resized_segms = []
  330. for segm in segms:
  331. if is_poly(segm):
  332. # Polygon format
  333. resized_segms.append([
  334. resize_poly(poly, im_scale_x, im_scale_y) for poly in segm
  335. ])
  336. else:
  337. # RLE format
  338. resized_segms.append(
  339. resize_rle(segm, im_h, im_w, im_scale_x, im_scale_y))
  340. return resized_segms
  341. def apply(self, sample):
  342. if self.interp == "RANDOM":
  343. interp = random.choice(list(interp_dict.values()))
  344. else:
  345. interp = interp_dict[self.interp]
  346. im_h, im_w = sample['image'].shape[:2]
  347. im_short_size = min(im_h, im_w)
  348. im_long_size = max(im_h, im_w)
  349. scale = float(self.short_size) / float(im_short_size)
  350. if 0 < self.max_size < np.round(scale * im_long_size):
  351. scale = float(self.max_size) / float(im_long_size)
  352. target_w = int(round(im_w * scale))
  353. target_h = int(round(im_h * scale))
  354. target_size = (target_w, target_h)
  355. sample['image'] = self.apply_im(sample['image'], interp, target_size)
  356. im_scale_y = target_h / im_h
  357. im_scale_x = target_w / im_w
  358. if 'mask' in sample:
  359. sample['mask'] = self.apply_mask(sample['mask'], target_size)
  360. if 'gt_bbox' in sample and len(sample['gt_bbox']) > 0:
  361. sample['gt_bbox'] = self.apply_bbox(
  362. sample['gt_bbox'], [im_scale_x, im_scale_y], target_size)
  363. if 'gt_poly' in sample and len(sample['gt_poly']) > 0:
  364. sample['gt_poly'] = self.apply_segm(
  365. sample['gt_poly'], [im_h, im_w], [im_scale_x, im_scale_y])
  366. sample['im_shape'] = np.asarray(
  367. sample['image'].shape[:2], dtype=np.float32)
  368. if 'scale_factor' in sample:
  369. scale_factor = sample['scale_factor']
  370. sample['scale_factor'] = np.asarray(
  371. [scale_factor[0] * im_scale_y, scale_factor[1] * im_scale_x],
  372. dtype=np.float32)
  373. return sample
  374. class RandomResizeByShort(Transform):
  375. """
  376. Resize input to random sizes with keeping the aspect ratio.
  377. Attention:If interp is 'RANDOM', the interpolation method will be chose randomly.
  378. Args:
  379. short_sizes (List[int]): Target size of the shorter side of the image(s).
  380. max_size (int, optional): The upper bound of longer side of the image(s). If max_size is -1, no upper bound is applied. Defaults to -1.
  381. interp ({'NEAREST', 'LINEAR', 'CUBIC', 'AREA', 'LANCZOS4', 'RANDOM'}, optional): Interpolation method of resize. Defaults to 'LINEAR'.
  382. Raises:
  383. TypeError: Invalid type of target_size.
  384. ValueError: Invalid interpolation method.
  385. See Also:
  386. ResizeByShort: Resize image(s) in input with keeping the aspect ratio.
  387. """
  388. def __init__(self, short_sizes, max_size=-1, interp='LINEAR'):
  389. super(RandomResizeByShort, self).__init__()
  390. if not (interp == "RANDOM" or interp in interp_dict):
  391. raise ValueError("interp should be one of {}".format(
  392. interp_dict.keys()))
  393. self.interp = interp
  394. assert isinstance(short_sizes, list), \
  395. "short_sizes must be List"
  396. self.short_sizes = short_sizes
  397. self.max_size = max_size
  398. def apply(self, sample):
  399. short_size = random.choice(self.short_sizes)
  400. resizer = ResizeByShort(
  401. short_size=short_size, max_size=self.max_size, interp=self.interp)
  402. sample = resizer(sample)
  403. return sample
  404. class RandomHorizontalFlip(Transform):
  405. """
  406. Randomly flip the input horizontally.
  407. Args:
  408. prob(float, optional): Probability of flipping the input. Defaults to .5.
  409. """
  410. def __init__(self, prob=0.5):
  411. super(RandomHorizontalFlip, self).__init__()
  412. self.prob = prob
  413. def apply_im(self, image):
  414. image = horizontal_flip(image)
  415. return image
  416. def apply_mask(self, mask):
  417. mask = horizontal_flip(mask)
  418. return mask
  419. def apply_bbox(self, bbox, width):
  420. oldx1 = bbox[:, 0].copy()
  421. oldx2 = bbox[:, 2].copy()
  422. bbox[:, 0] = width - oldx2
  423. bbox[:, 2] = width - oldx1
  424. return bbox
  425. def apply_segm(self, segms, height, width):
  426. flipped_segms = []
  427. for segm in segms:
  428. if is_poly(segm):
  429. # Polygon format
  430. flipped_segms.append(
  431. [horizontal_flip_poly(poly, width) for poly in segm])
  432. else:
  433. # RLE format
  434. flipped_segms.append(horizontal_flip_rle(segm, height, width))
  435. return flipped_segms
  436. def apply(self, sample):
  437. if random.random() < self.prob:
  438. im_h, im_w = sample['image'].shape[:2]
  439. sample['image'] = self.apply_im(sample['image'])
  440. if 'mask' in sample:
  441. sample['mask'] = self.apply_mask(sample['mask'])
  442. if 'gt_bbox' in sample and len(sample['gt_bbox']) > 0:
  443. sample['gt_bbox'] = self.apply_bbox(sample['gt_bbox'], im_w)
  444. if 'gt_poly' in sample and len(sample['gt_poly']) > 0:
  445. sample['gt_poly'] = self.apply_segm(sample['gt_poly'], im_h,
  446. im_w)
  447. return sample
  448. class RandomVerticalFlip(Transform):
  449. """
  450. Randomly flip the input vertically.
  451. Args:
  452. prob(float, optional): Probability of flipping the input. Defaults to .5.
  453. """
  454. def __init__(self, prob=0.5):
  455. super(RandomVerticalFlip, self).__init__()
  456. self.prob = prob
  457. def apply_im(self, image):
  458. image = vertical_flip(image)
  459. return image
  460. def apply_mask(self, mask):
  461. mask = vertical_flip(mask)
  462. return mask
  463. def apply_bbox(self, bbox, height):
  464. oldy1 = bbox[:, 1].copy()
  465. oldy2 = bbox[:, 3].copy()
  466. bbox[:, 0] = height - oldy2
  467. bbox[:, 2] = height - oldy1
  468. return bbox
  469. def apply_segm(self, segms, height, width):
  470. flipped_segms = []
  471. for segm in segms:
  472. if is_poly(segm):
  473. # Polygon format
  474. flipped_segms.append(
  475. [vertical_flip_poly(poly, height) for poly in segm])
  476. else:
  477. # RLE format
  478. flipped_segms.append(vertical_flip_rle(segm, height, width))
  479. return flipped_segms
  480. def apply(self, sample):
  481. if random.random() < self.prob:
  482. im_h, im_w = sample['image'].shape[:2]
  483. sample['image'] = self.apply_im(sample['image'])
  484. if 'mask' in sample:
  485. sample['mask'] = self.apply_mask(sample['mask'])
  486. if 'gt_bbox' in sample and len(sample['gt_bbox']) > 0:
  487. sample['gt_bbox'] = self.apply_bbox(sample['gt_bbox'], im_h)
  488. if 'gt_poly' in sample and len(sample['gt_poly']) > 0:
  489. sample['gt_poly'] = self.apply_segm(sample['gt_poly'], im_h,
  490. im_w)
  491. return sample
  492. class Normalize(Transform):
  493. """
  494. Apply min-max normalization to the image(s) in input.
  495. 1. im = (im - min_value) * 1 / (max_value - min_value)
  496. 2. im = im - mean
  497. 3. im = im / std
  498. Args:
  499. mean(List[float] or Tuple[float], optional): Mean of input image(s). Defaults to [0.485, 0.456, 0.406].
  500. std(List[float] or Tuple[float], optional): Standard deviation of input image(s). Defaults to [0.229, 0.224, 0.225].
  501. min_val(List[float] or Tuple[float], optional): Minimum value of input image(s). Defaults to [0, 0, 0, ].
  502. max_val(List[float] or Tuple[float], optional): Max value of input image(s). Defaults to [255., 255., 255.].
  503. is_scale(bool, optional): If True, the image pixel values will be divided by 255.
  504. """
  505. def __init__(self,
  506. mean=[0.485, 0.456, 0.406],
  507. std=[0.229, 0.224, 0.225],
  508. min_val=[0, 0, 0],
  509. max_val=[255., 255., 255.],
  510. is_scale=True):
  511. super(Normalize, self).__init__()
  512. from functools import reduce
  513. if reduce(lambda x, y: x * y, std) == 0:
  514. raise ValueError(
  515. 'Std should not have 0, but received is {}'.format(std))
  516. if is_scale:
  517. if reduce(lambda x, y: x * y,
  518. [a - b for a, b in zip(max_val, min_val)]) == 0:
  519. raise ValueError(
  520. '(max_val - min_val) should not have 0, but received is {}'.
  521. format((np.asarray(max_val) - np.asarray(min_val)).tolist(
  522. )))
  523. self.mean = mean
  524. self.std = std
  525. self.min_val = min_val
  526. self.max_val = max_val
  527. self.is_scale = is_scale
  528. def apply_im(self, image):
  529. image = image.astype(np.float32)
  530. mean = np.asarray(
  531. self.mean, dtype=np.float32)[np.newaxis, np.newaxis, :]
  532. std = np.asarray(self.std, dtype=np.float32)[np.newaxis, np.newaxis, :]
  533. image = normalize(image, mean, std, self.min_val, self.max_val)
  534. return image
  535. def apply(self, sample):
  536. sample['image'] = self.apply_im(sample['image'])
  537. return sample
  538. class CenterCrop(Transform):
  539. """
  540. Crop the input at the center.
  541. 1. Locate the center of the image.
  542. 2. Crop the sample.
  543. Args:
  544. crop_size(int, optional): target size of the cropped image(s). Defaults to 224.
  545. """
  546. def __init__(self, crop_size=224):
  547. super(CenterCrop, self).__init__()
  548. self.crop_size = crop_size
  549. def apply_im(self, image):
  550. image = center_crop(image, self.crop_size)
  551. return image
  552. def apply_mask(self, mask):
  553. mask = center_crop(mask)
  554. return mask
  555. def apply(self, sample):
  556. sample['image'] = self.apply_im(sample['image'])
  557. if 'mask' in sample:
  558. sample['mask'] = self.apply_mask(sample['mask'])
  559. return sample
  560. class RandomCrop(Transform):
  561. """
  562. Randomly crop the input.
  563. 1. Compute the height and width of cropped area according to aspect_ratio and scaling.
  564. 2. Locate the upper left corner of cropped area randomly.
  565. 3. Crop the image(s).
  566. 4. Resize the cropped area to crop_size by crop_size.
  567. Args:
  568. crop_size(int or None, optional): Target size of the cropped area. If None, the cropped area will not be resized. Defaults to None.
  569. aspect_ratio (List[float], optional): Aspect ratio of cropped region.
  570. in [min, max] format. Defaults to [.5, .2].
  571. thresholds (List[float], optional): Iou thresholds to decide a valid bbox crop. Defaults to [.0, .1, .3, .5, .7, .9].
  572. scaling (List[float], optional): Ratio between the cropped region and the original image.
  573. in [min, max] format, default [.3, 1.].
  574. num_attempts (int, optional): The number of tries before giving up. Defaults to 50.
  575. allow_no_crop (bool, optional): Whether returning without doing crop is allowed. Defaults to True.
  576. cover_all_box (bool, optional): Whether to ensure all bboxes are covered in the final crop. Defaults to False.
  577. """
  578. def __init__(self,
  579. crop_size=None,
  580. aspect_ratio=[.5, 2.],
  581. thresholds=[.0, .1, .3, .5, .7, .9],
  582. scaling=[.3, 1.],
  583. num_attempts=50,
  584. allow_no_crop=True,
  585. cover_all_box=False):
  586. super(RandomCrop, self).__init__()
  587. self.crop_size = crop_size
  588. self.aspect_ratio = aspect_ratio
  589. self.thresholds = thresholds
  590. self.scaling = scaling
  591. self.num_attempts = num_attempts
  592. self.allow_no_crop = allow_no_crop
  593. self.cover_all_box = cover_all_box
  594. def _generate_crop_info(self, sample):
  595. im_h, im_w = sample['image'].shape[:2]
  596. if 'gt_bbox' in sample and len(sample['gt_bbox']) > 0:
  597. thresholds = self.thresholds
  598. if self.allow_no_crop:
  599. thresholds.append('no_crop')
  600. np.random.shuffle(thresholds)
  601. for thresh in thresholds:
  602. if thresh == 'no_crop':
  603. return None
  604. for i in range(self.num_attempts):
  605. crop_box = self._get_crop_box(im_h, im_w)
  606. if crop_box is None:
  607. continue
  608. iou = self._iou_matrix(
  609. sample['gt_bbox'],
  610. np.array(
  611. [crop_box], dtype=np.float32))
  612. if iou.max() < thresh:
  613. continue
  614. if self.cover_all_box and iou.min() < thresh:
  615. continue
  616. cropped_box, valid_ids = self._crop_box_with_center_constraint(
  617. sample['gt_bbox'],
  618. np.array(
  619. crop_box, dtype=np.float32))
  620. if valid_ids.size > 0:
  621. return crop_box, cropped_box, valid_ids
  622. else:
  623. for i in range(self.num_attempts):
  624. crop_box = self._get_crop_box(im_h, im_w)
  625. if crop_box is None:
  626. continue
  627. return crop_box, None, None
  628. return None
  629. def _get_crop_box(self, im_h, im_w):
  630. scale = np.random.uniform(*self.scaling)
  631. if self.aspect_ratio is not None:
  632. min_ar, max_ar = self.aspect_ratio
  633. aspect_ratio = np.random.uniform(
  634. max(min_ar, scale**2), min(max_ar, scale**-2))
  635. h_scale = scale / np.sqrt(aspect_ratio)
  636. w_scale = scale * np.sqrt(aspect_ratio)
  637. else:
  638. h_scale = np.random.uniform(*self.scaling)
  639. w_scale = np.random.uniform(*self.scaling)
  640. crop_h = im_h * h_scale
  641. crop_w = im_w * w_scale
  642. if self.aspect_ratio is None:
  643. if crop_h / crop_w < 0.5 or crop_h / crop_w > 2.0:
  644. return None
  645. crop_h = int(crop_h)
  646. crop_w = int(crop_w)
  647. crop_y = np.random.randint(0, im_h - crop_h)
  648. crop_x = np.random.randint(0, im_w - crop_w)
  649. return [crop_x, crop_y, crop_x + crop_w, crop_y + crop_h]
  650. def _iou_matrix(self, a, b):
  651. tl_i = np.maximum(a[:, np.newaxis, :2], b[:, :2])
  652. br_i = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
  653. area_i = np.prod(br_i - tl_i, axis=2) * (tl_i < br_i).all(axis=2)
  654. area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
  655. area_b = np.prod(b[:, 2:] - b[:, :2], axis=1)
  656. area_o = (area_a[:, np.newaxis] + area_b - area_i)
  657. return area_i / (area_o + 1e-10)
  658. def _crop_box_with_center_constraint(self, box, crop):
  659. cropped_box = box.copy()
  660. cropped_box[:, :2] = np.maximum(box[:, :2], crop[:2])
  661. cropped_box[:, 2:] = np.minimum(box[:, 2:], crop[2:])
  662. cropped_box[:, :2] -= crop[:2]
  663. cropped_box[:, 2:] -= crop[:2]
  664. centers = (box[:, :2] + box[:, 2:]) / 2
  665. valid = np.logical_and(crop[:2] <= centers,
  666. centers < crop[2:]).all(axis=1)
  667. valid = np.logical_and(
  668. valid, (cropped_box[:, :2] < cropped_box[:, 2:]).all(axis=1))
  669. return cropped_box, np.where(valid)[0]
  670. def _crop_segm(self, segms, valid_ids, crop, height, width):
  671. crop_segms = []
  672. for id in valid_ids:
  673. segm = segms[id]
  674. if is_poly(segm):
  675. # Polygon format
  676. crop_segms.append(crop_poly(segm, crop))
  677. else:
  678. # RLE format
  679. crop_segms.append(crop_rle(segm, crop, height, width))
  680. return crop_segms
  681. def apply_im(self, image, crop):
  682. x1, y1, x2, y2 = crop
  683. return image[y1:y2, x1:x2, :]
  684. def apply_mask(self, mask, crop):
  685. x1, y1, x2, y2 = crop
  686. return mask[y1:y2, x1:x2, :]
  687. def apply(self, sample):
  688. crop_info = self._generate_crop_info(sample)
  689. if crop_info is not None:
  690. crop_box, cropped_box, valid_ids = crop_info
  691. im_h, im_w = sample['image'].shape[:2]
  692. sample['image'] = self.apply_im(sample['image'], crop_box)
  693. if 'gt_poly' in sample and len(sample['gt_poly']) > 0:
  694. crop_polys = self._crop_segm(
  695. sample['gt_poly'],
  696. valid_ids,
  697. np.array(
  698. crop_box, dtype=np.int64),
  699. im_h,
  700. im_w)
  701. if [] in crop_polys:
  702. delete_id = list()
  703. valid_polys = list()
  704. for idx, poly in enumerate(crop_polys):
  705. if not crop_poly:
  706. delete_id.append(idx)
  707. else:
  708. valid_polys.append(poly)
  709. valid_ids = np.delete(valid_ids, delete_id)
  710. if not valid_polys:
  711. return sample
  712. sample['gt_poly'] = valid_polys
  713. else:
  714. sample['gt_poly'] = crop_polys
  715. if 'gt_bbox' in sample and len(sample['gt_bbox']) > 0:
  716. sample['gt_bbox'] = np.take(cropped_box, valid_ids, axis=0)
  717. sample['gt_class'] = np.take(
  718. sample['gt_class'], valid_ids, axis=0)
  719. if 'gt_score' in sample:
  720. sample['gt_score'] = np.take(
  721. sample['gt_score'], valid_ids, axis=0)
  722. if 'is_crowd' in sample:
  723. sample['is_crowd'] = np.take(
  724. sample['is_crowd'], valid_ids, axis=0)
  725. if 'mask' in sample:
  726. sample['mask'] = self.apply_mask(sample['mask'], crop_box)
  727. if self.crop_size is not None:
  728. sample = Resize((self.crop_size, self.crop_size))(sample)
  729. return sample
  730. class RandomExpand(Transform):
  731. """
  732. Randomly expand the input by padding to the lower right side of the image(s) in input.
  733. Args:
  734. upper_ratio(float, optional): The maximum ratio to which the original image is expanded. Defaults to 4..
  735. prob(float, optional): The probability of apply expanding. Defaults to .5.
  736. im_padding_value(List[float] or Tuple[float], optional): RGB filling value for the image. Defaults to (127.5, 127.5, 127.5).
  737. label_padding_value(int, optional): Filling value for the mask. Defaults to 255.
  738. """
  739. def __init__(self,
  740. upper_ratio=4.,
  741. prob=.5,
  742. im_padding_value=(127.5, 127.5, 127.5),
  743. label_padding_value=255):
  744. super(RandomExpand, self).__init__()
  745. assert upper_ratio > 1.01, "expand ratio must be larger than 1.01"
  746. self.upper_ratio = upper_ratio
  747. self.prob = prob
  748. assert isinstance(im_padding_value, (Number, Sequence)), \
  749. "fill value must be either float or sequence"
  750. if isinstance(im_padding_value, Number):
  751. im_padding_value = (im_padding_value, ) * 3
  752. if not isinstance(im_padding_value, tuple):
  753. im_padding_value = tuple(im_padding_value)
  754. self.im_padding_value = im_padding_value
  755. self.label_padding_value = label_padding_value
  756. def apply(self, sample):
  757. if random.random() < self.prob:
  758. im_h, im_w = sample['image'].shape[:2]
  759. ratio = np.random.uniform(1., self.upper_ratio)
  760. h = int(im_h * ratio)
  761. w = int(im_w * ratio)
  762. if h > im_h and w > im_w:
  763. y = np.random.randint(0, h - im_h)
  764. x = np.random.randint(0, w - im_w)
  765. target_size = (h, w)
  766. offsets = (x, y)
  767. sample = Padding(
  768. target_size=target_size,
  769. pad_mode=-1,
  770. offsets=offsets,
  771. im_padding_value=self.im_padding_value,
  772. label_padding_value=self.label_padding_value)(sample)
  773. return sample
  774. class Padding(Transform):
  775. def __init__(self,
  776. target_size=None,
  777. pad_mode=0,
  778. offsets=None,
  779. im_padding_value=(127.5, 127.5, 127.5),
  780. label_padding_value=255,
  781. size_divisor=32):
  782. """
  783. Pad image to a specified size or multiple of size_divisor.
  784. Args:
  785. target_size(int, Sequence, optional): Image target size, if None, pad to multiple of size_divisor. Defaults to None.
  786. pad_mode({-1, 0, 1, 2}, optional): Pad mode, currently only supports four modes [-1, 0, 1, 2]. if -1, use specified offsets
  787. if 0, only pad to right and bottom. If 1, pad according to center. If 2, only pad left and top. Defaults to 0.
  788. im_padding_value(Sequence[float]): RGB value of pad area. Defaults to (127.5, 127.5, 127.5).
  789. label_padding_value(int, optional): Filling value for the mask. Defaults to 255.
  790. size_divisor(int): Image width and height after padding is a multiple of size_divisor
  791. """
  792. super(Padding, self).__init__()
  793. if isinstance(target_size, (list, tuple)):
  794. if len(target_size) != 2:
  795. raise ValueError(
  796. '`target_size` should include 2 elements, but it is {}'.
  797. format(target_size))
  798. if isinstance(target_size, int):
  799. target_size = [target_size] * 2
  800. assert pad_mode in [
  801. -1, 0, 1, 2
  802. ], 'currently only supports four modes [-1, 0, 1, 2]'
  803. if pad_mode == -1:
  804. assert offsets, 'if pad_mode is -1, offsets should not be None'
  805. self.target_size = target_size
  806. self.size_divisor = size_divisor
  807. self.pad_mode = pad_mode
  808. self.offsets = offsets
  809. self.im_padding_value = im_padding_value
  810. self.label_padding_value = label_padding_value
  811. def apply_im(self, image, offsets, target_size):
  812. x, y = offsets
  813. im_h, im_w = image.shape[:2]
  814. h, w = target_size
  815. canvas = np.ones((h, w, 3), dtype=np.float32)
  816. canvas *= np.array(self.im_padding_value, dtype=np.float32)
  817. canvas[y:y + im_h, x:x + im_w, :] = image.astype(np.float32)
  818. return canvas
  819. def apply_mask(self, mask, offsets, target_size):
  820. x, y = offsets
  821. im_h, im_w = mask.shape[:2]
  822. h, w = target_size
  823. canvas = np.ones((h, w), dtype=np.float32)
  824. canvas *= np.array(self.label_padding_value, dtype=np.float32)
  825. canvas[y:y + im_h, x:x + im_w] = mask.astype(np.float32)
  826. return canvas
  827. def apply_bbox(self, bbox, offsets):
  828. return bbox + np.array(offsets * 2, dtype=np.float32)
  829. def apply_segm(self, segms, offsets, im_size, size):
  830. x, y = offsets
  831. height, width = im_size
  832. h, w = size
  833. expanded_segms = []
  834. for segm in segms:
  835. if is_poly(segm):
  836. # Polygon format
  837. expanded_segms.append(
  838. [expand_poly(poly, x, y) for poly in segm])
  839. else:
  840. # RLE format
  841. expanded_segms.append(
  842. expand_rle(segm, x, y, height, width, h, w))
  843. return expanded_segms
  844. def apply(self, sample):
  845. im_h, im_w = sample['image'].shape[:2]
  846. if self.target_size:
  847. h, w = self.target_size
  848. assert (
  849. im_h <= h and im_w <= w
  850. ), 'target size ({}, {}) cannot be less than image size ({}, {})'\
  851. .format(h, w, im_h, im_w)
  852. else:
  853. h = (np.ceil(im_h // self.size_divisor) *
  854. self.size_divisor).astype(int)
  855. w = (np.ceil(im_w / self.size_divisor) *
  856. self.size_divisor).astype(int)
  857. if h == im_h and w == im_w:
  858. return sample
  859. if self.pad_mode == -1:
  860. offsets = self.offsets
  861. elif self.pad_mode == 0:
  862. offsets = [0, 0]
  863. elif self.pad_mode == 1:
  864. offsets = [(h - im_h) // 2, (w - im_w) // 2]
  865. else:
  866. offsets = [h - im_h, w - im_w]
  867. sample['image'] = self.apply_im(sample['image'], offsets, (h, w))
  868. if 'mask' in sample:
  869. sample['mask'] = self.apply_mask(sample['mask'], offsets, (h, w))
  870. if 'gt_bbox' in sample and len(sample['gt_bbox']) > 0:
  871. sample['gt_bbox'] = self.apply_bbox(sample['gt_bbox'], offsets)
  872. if 'gt_poly' in sample and len(sample['gt_poly']) > 0:
  873. sample['gt_poly'] = self.apply_segm(
  874. sample['gt_poly'], offsets, im_size=[im_h, im_w], size=[h, w])
  875. return sample
  876. class MixupImage(Transform):
  877. def __init__(self, alpha=1.5, beta=1.5, mixup_epoch=-1):
  878. """
  879. Mixup two images and their gt_bbbox/gt_score.
  880. Args:
  881. alpha (float, optional): Alpha parameter of beta distribution. Defaults to 1.5.
  882. beta (float, optional): Beta parameter of beta distribution. Defaults to 1.5.
  883. """
  884. super(MixupImage, self).__init__()
  885. if alpha <= 0.0:
  886. raise ValueError("alpha should be positive in {}".format(self))
  887. if beta <= 0.0:
  888. raise ValueError("beta should be positive in {}".format(self))
  889. self.alpha = alpha
  890. self.beta = beta
  891. self.mixup_epoch = mixup_epoch
  892. def apply_im(self, image1, image2, factor):
  893. h = max(image1.shape[0], image2.shape[0])
  894. w = max(image1.shape[1], image2.shape[1])
  895. img = np.zeros((h, w, image1.shape[2]), 'float32')
  896. img[:image1.shape[0], :image1.shape[1], :] = \
  897. image1.astype('float32') * factor
  898. img[:image2.shape[0], :image2.shape[1], :] += \
  899. image2.astype('float32') * (1.0 - factor)
  900. return img.astype('uint8')
  901. def __call__(self, sample):
  902. if not isinstance(sample, Sequence):
  903. return sample
  904. assert len(sample) == 2, 'mixup need two samples'
  905. factor = np.random.beta(self.alpha, self.beta)
  906. factor = max(0.0, min(1.0, factor))
  907. if factor >= 1.0:
  908. return sample[0]
  909. if factor <= 0.0:
  910. return sample[1]
  911. image = self.apply_im(sample[0]['image'], sample[1]['image'], factor)
  912. result = copy.deepcopy(sample[0])
  913. result['image'] = image
  914. # apply bbox and score
  915. if 'gt_bbox' in sample[0]:
  916. gt_bbox1 = sample[0]['gt_bbox']
  917. gt_bbox2 = sample[1]['gt_bbox']
  918. gt_bbox = np.concatenate((gt_bbox1, gt_bbox2), axis=0)
  919. result['gt_bbox'] = gt_bbox
  920. if 'gt_poly' in sample[0]:
  921. gt_poly1 = sample[0]['gt_poly']
  922. gt_poly2 = sample[1]['gt_poly']
  923. gt_poly = gt_poly1 + gt_poly2
  924. result['gt_poly'] = gt_poly
  925. if 'gt_class' in sample[0]:
  926. gt_class1 = sample[0]['gt_class']
  927. gt_class2 = sample[1]['gt_class']
  928. gt_class = np.concatenate((gt_class1, gt_class2), axis=0)
  929. result['gt_class'] = gt_class
  930. gt_score1 = np.ones_like(sample[0]['gt_class'])
  931. gt_score2 = np.ones_like(sample[1]['gt_class'])
  932. gt_score = np.concatenate(
  933. (gt_score1 * factor, gt_score2 * (1. - factor)), axis=0)
  934. result['gt_score'] = gt_score
  935. if 'is_crowd' in sample[0]:
  936. is_crowd1 = sample[0]['is_crowd']
  937. is_crowd2 = sample[1]['is_crowd']
  938. is_crowd = np.concatenate((is_crowd1, is_crowd2), axis=0)
  939. result['is_crowd'] = is_crowd
  940. if 'difficult' in sample[0]:
  941. is_difficult1 = sample[0]['difficult']
  942. is_difficult2 = sample[1]['difficult']
  943. is_difficult = np.concatenate(
  944. (is_difficult1, is_difficult2), axis=0)
  945. result['difficult'] = is_difficult
  946. return result
  947. class RandomDistort(Transform):
  948. """
  949. Random color distortion.
  950. Args:
  951. brightness_range(float, optional): Range of brightness distortion. Defaults to .5.
  952. brightness_prob(float, optional): Probability of brightness distortion. Defaults to .5.
  953. contrast_range(float, optional): Range of contrast distortion. Defaults to .5.
  954. contrast_prob(float, optional): Probability of contrast distortion. Defaults to .5.
  955. saturation_range(float, optional): Range of saturation distortion. Defaults to .5.
  956. saturation_prob(float, optional): Probability of saturation distortion. Defaults to .5.
  957. hue_range(float, optional): Range of hue distortion. Defaults to .5.
  958. hue_prob(float, optional): Probability of hue distortion. Defaults to .5.
  959. random_apply (bool, optional): whether to apply in random (yolo) or fixed (SSD)
  960. order. Defaults to True.
  961. count (int, optional): the number of doing distortion. Defaults to 4.
  962. shuffle_channel (bool, optional): whether to swap channels randomly. Defaults to False.
  963. """
  964. def __init__(self,
  965. brightness_range=0.5,
  966. brightness_prob=0.5,
  967. contrast_range=0.5,
  968. contrast_prob=0.5,
  969. saturation_range=0.5,
  970. saturation_prob=0.5,
  971. hue_range=18,
  972. hue_prob=0.5,
  973. random_apply=True,
  974. count=4,
  975. shuffle_channel=False):
  976. super(RandomDistort, self).__init__()
  977. self.brightness_range = [1 - brightness_range, 1 + brightness_range]
  978. self.brightness_prob = brightness_prob
  979. self.contrast_range = [1 - contrast_range, 1 + contrast_range]
  980. self.contrast_prob = contrast_prob
  981. self.saturation_range = [1 - saturation_range, 1 + saturation_range]
  982. self.saturation_prob = saturation_prob
  983. self.hue_range = [1 - hue_range, 1 + hue_range]
  984. self.hue_prob = hue_prob
  985. self.random_apply = random_apply
  986. self.count = count
  987. self.shuffle_channel = shuffle_channel
  988. def apply_hue(self, image):
  989. low, high = self.hue_range
  990. if np.random.uniform(0., 1.) < self.hue_prob:
  991. return image
  992. image = image.astype(np.float32)
  993. # it works, but result differ from HSV version
  994. delta = np.random.uniform(low, high)
  995. u = np.cos(delta * np.pi)
  996. w = np.sin(delta * np.pi)
  997. bt = np.array([[1.0, 0.0, 0.0], [0.0, u, -w], [0.0, w, u]])
  998. tyiq = np.array([[0.299, 0.587, 0.114], [0.596, -0.274, -0.321],
  999. [0.211, -0.523, 0.311]])
  1000. ityiq = np.array([[1.0, 0.956, 0.621], [1.0, -0.272, -0.647],
  1001. [1.0, -1.107, 1.705]])
  1002. t = np.dot(np.dot(ityiq, bt), tyiq).T
  1003. image = np.dot(image, t)
  1004. return image
  1005. def apply_saturation(self, image):
  1006. low, high = self.saturation_range
  1007. if np.random.uniform(0., 1.) < self.saturation_prob:
  1008. return image
  1009. delta = np.random.uniform(low, high)
  1010. image = image.astype(np.float32)
  1011. # it works, but result differ from HSV version
  1012. gray = image * np.array([[[0.299, 0.587, 0.114]]], dtype=np.float32)
  1013. gray = gray.sum(axis=2, keepdims=True)
  1014. gray *= (1.0 - delta)
  1015. image *= delta
  1016. image += gray
  1017. return image
  1018. def apply_contrast(self, image):
  1019. low, high = self.contrast_range
  1020. if np.random.uniform(0., 1.) < self.contrast_prob:
  1021. return image
  1022. delta = np.random.uniform(low, high)
  1023. image = image.astype(np.float32)
  1024. image *= delta
  1025. return image
  1026. def apply_brightness(self, image):
  1027. low, high = self.brightness_range
  1028. if np.random.uniform(0., 1.) < self.brightness_prob:
  1029. return image
  1030. delta = np.random.uniform(low, high)
  1031. image = image.astype(np.float32)
  1032. image += delta
  1033. return image
  1034. def apply(self, sample):
  1035. if self.random_apply:
  1036. functions = [
  1037. self.apply_brightness, self.apply_contrast,
  1038. self.apply_saturation, self.apply_hue
  1039. ]
  1040. distortions = np.random.permutation(functions)[:self.count]
  1041. for func in distortions:
  1042. sample['image'] = func(sample['image'])
  1043. return sample
  1044. sample['image'] = self.apply_brightness(sample['image'])
  1045. mode = np.random.randint(0, 2)
  1046. if mode:
  1047. sample['image'] = self.apply_contrast(sample['image'])
  1048. sample['image'] = self.apply_saturation(sample['image'])
  1049. sample['image'] = self.apply_hue(sample['image'])
  1050. if not mode:
  1051. sample['image'] = self.apply_contrast(sample['image'])
  1052. if self.shuffle_channel:
  1053. if np.random.randint(0, 2):
  1054. sample['image'] = sample['image'][..., np.random.permutation(
  1055. 3)]
  1056. return sample
  1057. class _PadBox(Transform):
  1058. def __init__(self, num_max_boxes=50):
  1059. """
  1060. Pad zeros to bboxes if number of bboxes is less than num_max_boxes.
  1061. Args:
  1062. num_max_boxes (int, optional): the max number of bboxes. Defaults to 50.
  1063. """
  1064. self.num_max_boxes = num_max_boxes
  1065. super(_PadBox, self).__init__()
  1066. def apply(self, sample):
  1067. gt_num = min(self.num_max_boxes, len(sample['gt_bbox']))
  1068. num_max = self.num_max_boxes
  1069. pad_bbox = np.zeros((num_max, 4), dtype=np.float32)
  1070. if gt_num > 0:
  1071. pad_bbox[:gt_num, :] = sample['gt_bbox'][:gt_num, :]
  1072. sample['gt_bbox'] = pad_bbox
  1073. if 'gt_class' in sample:
  1074. pad_class = np.zeros((num_max, ), dtype=np.int32)
  1075. if gt_num > 0:
  1076. pad_class[:gt_num] = sample['gt_class'][:gt_num, 0]
  1077. sample['gt_class'] = pad_class
  1078. if 'gt_score' in sample:
  1079. pad_score = np.zeros((num_max, ), dtype=np.float32)
  1080. if gt_num > 0:
  1081. pad_score[:gt_num] = sample['gt_score'][:gt_num, 0]
  1082. sample['gt_score'] = pad_score
  1083. # in training, for example in op ExpandImage,
  1084. # the bbox and gt_class is expanded, but the difficult is not,
  1085. # so, judging by it's length
  1086. if 'difficult' in sample:
  1087. pad_diff = np.zeros((num_max, ), dtype=np.int32)
  1088. if gt_num > 0:
  1089. pad_diff[:gt_num] = sample['difficult'][:gt_num, 0]
  1090. sample['difficult'] = pad_diff
  1091. if 'is_crowd' in sample:
  1092. pad_crowd = np.zeros((num_max, ), dtype=np.int32)
  1093. if gt_num > 0:
  1094. pad_crowd[:gt_num] = sample['is_crowd'][:gt_num, 0]
  1095. sample['is_crowd'] = pad_crowd
  1096. return sample
  1097. class _NormalizeBox(Transform):
  1098. def __init__(self):
  1099. super(_NormalizeBox, self).__init__()
  1100. def apply(self, sample):
  1101. height, width = sample['image'].shape[:2]
  1102. for i in range(sample['gt_bbox'].shape[0]):
  1103. sample['gt_bbox'][i][0] = sample['gt_bbox'][i][0] / width
  1104. sample['gt_bbox'][i][1] = sample['gt_bbox'][i][1] / height
  1105. sample['gt_bbox'][i][2] = sample['gt_bbox'][i][2] / width
  1106. sample['gt_bbox'][i][3] = sample['gt_bbox'][i][3] / height
  1107. return sample
  1108. class _BboxXYXY2XYWH(Transform):
  1109. """
  1110. Convert bbox XYXY format to XYWH format.
  1111. """
  1112. def __init__(self):
  1113. super(_BboxXYXY2XYWH, self).__init__()
  1114. def apply(self, sample):
  1115. bbox = sample['gt_bbox']
  1116. bbox[:, 2:4] = bbox[:, 2:4] - bbox[:, :2]
  1117. bbox[:, :2] = bbox[:, :2] + bbox[:, 2:4] / 2.
  1118. sample['gt_bbox'] = bbox
  1119. return sample
  1120. class _Permute(Transform):
  1121. def __init__(self):
  1122. super(_Permute, self).__init__()
  1123. def apply(self, sample):
  1124. sample['image'] = permute(sample['image'], False)
  1125. return sample
  1126. class ArrangeSegmenter(Transform):
  1127. def __init__(self, mode):
  1128. super(ArrangeSegmenter, self).__init__()
  1129. if mode not in ['train', 'eval', 'test', 'quant']:
  1130. raise ValueError(
  1131. "mode should be defined as one of ['train', 'eval', 'test', 'quant']!"
  1132. )
  1133. self.mode = mode
  1134. def apply(self, sample):
  1135. if 'mask' in sample:
  1136. mask = sample['mask']
  1137. image = permute(sample['image'], False)
  1138. if self.mode == 'train':
  1139. mask = mask.astype('int64')
  1140. return image, mask
  1141. if self.mode == 'eval':
  1142. mask = np.asarray(Image.open(mask))
  1143. mask = mask[np.newaxis, :, :].astype('int64')
  1144. return image, mask
  1145. if self.mode == 'test':
  1146. return image,
  1147. class ArrangeClassifier(Transform):
  1148. def __init__(self, mode):
  1149. super(ArrangeClassifier, self).__init__()
  1150. if mode not in ['train', 'eval', 'test', 'quant']:
  1151. raise ValueError(
  1152. "mode should be defined as one of ['train', 'eval', 'test', 'quant']!"
  1153. )
  1154. self.mode = mode
  1155. def apply(self, sample):
  1156. image = permute(sample['image'], False)
  1157. if self.mode in ['train', 'eval']:
  1158. return image, sample['label']
  1159. else:
  1160. return image
  1161. class ArrangeDetector(Transform):
  1162. def __init__(self, mode):
  1163. super(ArrangeDetector, self).__init__()
  1164. if mode not in ['train', 'eval', 'test', 'quant']:
  1165. raise ValueError(
  1166. "mode should be defined as one of ['train', 'eval', 'test', 'quant']!"
  1167. )
  1168. self.mode = mode
  1169. def apply(self, sample):
  1170. if self.mode == 'eval' and 'gt_poly' in sample:
  1171. del sample['gt_poly']
  1172. return sample