operators.py 51 KB

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