operators.py 51 KB

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