det_transforms.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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. try:
  15. from collections.abc import Sequence
  16. except Exception:
  17. from collections import Sequence
  18. import random
  19. import os.path as osp
  20. import numpy as np
  21. import cv2
  22. from PIL import Image, ImageEnhance
  23. from .ops import *
  24. from .box_utils import *
  25. class Compose:
  26. """根据数据预处理/增强列表对输入数据进行操作。
  27. 所有操作的输入图像流形状均是[H, W, C],其中H为图像高,W为图像宽,C为图像通道数。
  28. Args:
  29. transforms (list): 数据预处理/增强列表。
  30. Raises:
  31. TypeError: 形参数据类型不满足需求。
  32. ValueError: 数据长度不匹配。
  33. """
  34. def __init__(self, transforms):
  35. if not isinstance(transforms, list):
  36. raise TypeError('The transforms must be a list!')
  37. if len(transforms) < 1:
  38. raise ValueError('The length of transforms ' + \
  39. 'must be equal or larger than 1!')
  40. self.transforms = transforms
  41. self.use_mixup = False
  42. for t in self.transforms:
  43. if t.__class__.__name__ == 'MixupImage':
  44. self.use_mixup = True
  45. def __call__(self, im, im_info=None, label_info=None):
  46. """
  47. Args:
  48. im (str/np.ndarray): 图像路径/图像np.ndarray数据。
  49. im_info (dict): 存储与图像相关的信息,dict中的字段如下:
  50. - im_id (np.ndarray): 图像序列号,形状为(1,)。
  51. - origin_shape (np.ndarray): 图像原始大小,形状为(2,),
  52. origin_shape[0]为高,origin_shape[1]为宽。
  53. - mixup (list): list为[im, im_info, label_info],分别对应
  54. 与当前图像进行mixup的图像np.ndarray数据、图像相关信息、标注框相关信息;
  55. 注意,当前epoch若无需进行mixup,则无该字段。
  56. label_info (dict): 存储与标注框相关的信息,dict中的字段如下:
  57. - gt_bbox (np.ndarray): 真实标注框坐标[x1, y1, x2, y2],形状为(n, 4),
  58. 其中n代表真实标注框的个数。
  59. - gt_class (np.ndarray): 每个真实标注框对应的类别序号,形状为(n, 1),
  60. 其中n代表真实标注框的个数。
  61. - gt_score (np.ndarray): 每个真实标注框对应的混合得分,形状为(n, 1),
  62. 其中n代表真实标注框的个数。
  63. - gt_poly (list): 每个真实标注框内的多边形分割区域,每个分割区域由点的x、y坐标组成,
  64. 长度为n,其中n代表真实标注框的个数。
  65. - is_crowd (np.ndarray): 每个真实标注框中是否是一组对象,形状为(n, 1),
  66. 其中n代表真实标注框的个数。
  67. - difficult (np.ndarray): 每个真实标注框中的对象是否为难识别对象,形状为(n, 1),
  68. 其中n代表真实标注框的个数。
  69. Returns:
  70. tuple: 根据网络所需字段所组成的tuple;
  71. 字段由transforms中的最后一个数据预处理操作决定。
  72. """
  73. def decode_image(im_file, im_info, label_info):
  74. if im_info is None:
  75. im_info = dict()
  76. try:
  77. im = cv2.imread(im_file).astype('float32')
  78. except:
  79. raise TypeError(
  80. 'Can\'t read The image file {}!'.format(im_file))
  81. im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
  82. # make default im_info with [h, w, 1]
  83. im_info['im_resize_info'] = np.array(
  84. [im.shape[0], im.shape[1], 1.], dtype=np.float32)
  85. # copy augment_shape from origin_shape
  86. im_info['augment_shape'] = np.array([im.shape[0],
  87. im.shape[1]]).astype('int32')
  88. if not self.use_mixup:
  89. if 'mixup' in im_info:
  90. del im_info['mixup']
  91. # decode mixup image
  92. if 'mixup' in im_info:
  93. im_info['mixup'] = \
  94. decode_image(im_info['mixup'][0],
  95. im_info['mixup'][1],
  96. im_info['mixup'][2])
  97. if label_info is None:
  98. return (im, im_info)
  99. else:
  100. return (im, im_info, label_info)
  101. outputs = decode_image(im, im_info, label_info)
  102. im = outputs[0]
  103. im_info = outputs[1]
  104. if len(outputs) == 3:
  105. label_info = outputs[2]
  106. for op in self.transforms:
  107. if im is None:
  108. return None
  109. outputs = op(im, im_info, label_info)
  110. im = outputs[0]
  111. return outputs
  112. class ResizeByShort:
  113. """根据图像的短边调整图像大小(resize)。
  114. 1. 获取图像的长边和短边长度。
  115. 2. 根据短边与short_size的比例,计算长边的目标长度,
  116. 此时高、宽的resize比例为short_size/原图短边长度。
  117. 3. 如果max_size>0,调整resize比例:
  118. 如果长边的目标长度>max_size,则高、宽的resize比例为max_size/原图长边长度。
  119. 4. 根据调整大小的比例对图像进行resize。
  120. Args:
  121. target_size (int): 短边目标长度。默认为800。
  122. max_size (int): 长边目标长度的最大限制。默认为1333。
  123. Raises:
  124. TypeError: 形参数据类型不满足需求。
  125. """
  126. def __init__(self, short_size=800, max_size=1333):
  127. self.max_size = int(max_size)
  128. if not isinstance(short_size, int):
  129. raise TypeError(
  130. "Type of short_size is invalid. Must be Integer, now is {}".
  131. format(type(short_size)))
  132. self.short_size = short_size
  133. if not (isinstance(self.max_size, int)):
  134. raise TypeError("max_size: input type is invalid.")
  135. def __call__(self, im, im_info=None, label_info=None):
  136. """
  137. Args:
  138. im (numnp.ndarraypy): 图像np.ndarray数据。
  139. im_info (dict, 可选): 存储与图像相关的信息。
  140. label_info (dict, 可选): 存储与标注框相关的信息。
  141. Returns:
  142. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  143. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  144. 存储与标注框相关信息的字典。
  145. 其中,im_info更新字段为:
  146. - im_resize_info (np.ndarray): resize后的图像高、resize后的图像宽、resize后的图像相对原始图的缩放比例
  147. 三者组成的np.ndarray,形状为(3,)。
  148. Raises:
  149. TypeError: 形参数据类型不满足需求。
  150. ValueError: 数据长度不匹配。
  151. """
  152. if im_info is None:
  153. im_info = dict()
  154. if not isinstance(im, np.ndarray):
  155. raise TypeError("ResizeByShort: image type is not numpy.")
  156. if len(im.shape) != 3:
  157. raise ValueError('ResizeByShort: image is not 3-dimensional.')
  158. im_short_size = min(im.shape[0], im.shape[1])
  159. im_long_size = max(im.shape[0], im.shape[1])
  160. scale = float(self.short_size) / im_short_size
  161. if self.max_size > 0 and np.round(
  162. scale * im_long_size) > self.max_size:
  163. scale = float(self.max_size) / float(im_long_size)
  164. resized_width = int(round(im.shape[1] * scale))
  165. resized_height = int(round(im.shape[0] * scale))
  166. im_resize_info = [resized_height, resized_width, scale]
  167. im = cv2.resize(
  168. im, (resized_width, resized_height),
  169. interpolation=cv2.INTER_LINEAR)
  170. im_info['im_resize_info'] = np.array(im_resize_info).astype(np.float32)
  171. if label_info is None:
  172. return (im, im_info)
  173. else:
  174. return (im, im_info, label_info)
  175. class Padding:
  176. """将图像的长和宽padding至coarsest_stride的倍数。如输入图像为[300, 640],
  177. `coarest_stride`为32,则由于300不为32的倍数,因此在图像最右和最下使用0值
  178. 进行padding,最终输出图像为[320, 640]。
  179. 1. 如果coarsest_stride为1则直接返回。
  180. 2. 获取图像的高H、宽W。
  181. 3. 计算填充后图像的高H_new、宽W_new。
  182. 4. 构建大小为(H_new, W_new, 3)像素值为0的np.ndarray,
  183. 并将原图的np.ndarray粘贴于左上角。
  184. Args:
  185. coarsest_stride (int): 填充后的图像长、宽为该参数的倍数,默认为1。
  186. """
  187. def __init__(self, coarsest_stride=1):
  188. self.coarsest_stride = coarsest_stride
  189. def __call__(self, im, im_info=None, label_info=None):
  190. """
  191. Args:
  192. im (numnp.ndarraypy): 图像np.ndarray数据。
  193. im_info (dict, 可选): 存储与图像相关的信息。
  194. label_info (dict, 可选): 存储与标注框相关的信息。
  195. Returns:
  196. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  197. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  198. 存储与标注框相关信息的字典。
  199. Raises:
  200. TypeError: 形参数据类型不满足需求。
  201. ValueError: 数据长度不匹配。
  202. """
  203. if self.coarsest_stride == 1:
  204. if label_info is None:
  205. return (im, im_info)
  206. else:
  207. return (im, im_info, label_info)
  208. if im_info is None:
  209. im_info = dict()
  210. if not isinstance(im, np.ndarray):
  211. raise TypeError("Padding: image type is not numpy.")
  212. if len(im.shape) != 3:
  213. raise ValueError('Padding: image is not 3-dimensional.')
  214. im_h, im_w, im_c = im.shape[:]
  215. if self.coarsest_stride > 1:
  216. padding_im_h = int(
  217. np.ceil(im_h / self.coarsest_stride) * self.coarsest_stride)
  218. padding_im_w = int(
  219. np.ceil(im_w / self.coarsest_stride) * self.coarsest_stride)
  220. padding_im = np.zeros((padding_im_h, padding_im_w, im_c),
  221. dtype=np.float32)
  222. padding_im[:im_h, :im_w, :] = im
  223. if label_info is None:
  224. return (padding_im, im_info)
  225. else:
  226. return (padding_im, im_info, label_info)
  227. class Resize:
  228. """调整图像大小(resize)。
  229. - 当目标大小(target_size)类型为int时,根据插值方式,
  230. 将图像resize为[target_size, target_size]。
  231. - 当目标大小(target_size)类型为list或tuple时,根据插值方式,
  232. 将图像resize为target_size。
  233. 注意:当插值方式为“RANDOM”时,则随机选取一种插值方式进行resize。
  234. Args:
  235. target_size (int/list/tuple): 短边目标长度。默认为608。
  236. interp (str): resize的插值方式,与opencv的插值方式对应,取值范围为
  237. ['NEAREST', 'LINEAR', 'CUBIC', 'AREA', 'LANCZOS4', 'RANDOM']。默认为"LINEAR"。
  238. Raises:
  239. TypeError: 形参数据类型不满足需求。
  240. ValueError: 插值方式不在['NEAREST', 'LINEAR', 'CUBIC',
  241. 'AREA', 'LANCZOS4', 'RANDOM']中。
  242. """
  243. # The interpolation mode
  244. interp_dict = {
  245. 'NEAREST': cv2.INTER_NEAREST,
  246. 'LINEAR': cv2.INTER_LINEAR,
  247. 'CUBIC': cv2.INTER_CUBIC,
  248. 'AREA': cv2.INTER_AREA,
  249. 'LANCZOS4': cv2.INTER_LANCZOS4
  250. }
  251. def __init__(self, target_size=608, interp='LINEAR'):
  252. self.interp = interp
  253. if not (interp == "RANDOM" or interp in self.interp_dict):
  254. raise ValueError("interp should be one of {}".format(
  255. self.interp_dict.keys()))
  256. if isinstance(target_size, list) or isinstance(target_size, tuple):
  257. if len(target_size) != 2:
  258. raise TypeError(
  259. 'when target is list or tuple, it should include 2 elements, but it is {}'
  260. .format(target_size))
  261. elif not isinstance(target_size, int):
  262. raise TypeError(
  263. "Type of target_size is invalid. Must be Integer or List or tuple, now is {}"
  264. .format(type(target_size)))
  265. self.target_size = target_size
  266. def __call__(self, im, im_info=None, label_info=None):
  267. """
  268. Args:
  269. im (np.ndarray): 图像np.ndarray数据。
  270. im_info (dict, 可选): 存储与图像相关的信息。
  271. label_info (dict, 可选): 存储与标注框相关的信息。
  272. Returns:
  273. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  274. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  275. 存储与标注框相关信息的字典。
  276. Raises:
  277. TypeError: 形参数据类型不满足需求。
  278. ValueError: 数据长度不匹配。
  279. """
  280. if im_info is None:
  281. im_info = dict()
  282. if not isinstance(im, np.ndarray):
  283. raise TypeError("Resize: image type is not numpy.")
  284. if len(im.shape) != 3:
  285. raise ValueError('Resize: image is not 3-dimensional.')
  286. if self.interp == "RANDOM":
  287. interp = random.choice(list(self.interp_dict.keys()))
  288. else:
  289. interp = self.interp
  290. im = resize(im, self.target_size, self.interp_dict[interp])
  291. if label_info is None:
  292. return (im, im_info)
  293. else:
  294. return (im, im_info, label_info)
  295. class RandomHorizontalFlip:
  296. """随机翻转图像、标注框、分割信息,模型训练时的数据增强操作。
  297. 1. 随机采样一个0-1之间的小数,当小数小于水平翻转概率时,
  298. 执行2-4步操作,否则直接返回。
  299. 2. 水平翻转图像。
  300. 3. 计算翻转后的真实标注框的坐标,更新label_info中的gt_bbox信息。
  301. 4. 计算翻转后的真实分割区域的坐标,更新label_info中的gt_poly信息。
  302. Args:
  303. prob (float): 随机水平翻转的概率。默认为0.5。
  304. Raises:
  305. TypeError: 形参数据类型不满足需求。
  306. """
  307. def __init__(self, prob=0.5):
  308. self.prob = prob
  309. if not isinstance(self.prob, float):
  310. raise TypeError("RandomHorizontalFlip: input type is invalid.")
  311. def __call__(self, im, im_info=None, label_info=None):
  312. """
  313. Args:
  314. im (np.ndarray): 图像np.ndarray数据。
  315. im_info (dict, 可选): 存储与图像相关的信息。
  316. label_info (dict, 可选): 存储与标注框相关的信息。
  317. Returns:
  318. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  319. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  320. 存储与标注框相关信息的字典。
  321. 其中,im_info更新字段为:
  322. - gt_bbox (np.ndarray): 水平翻转后的标注框坐标[x1, y1, x2, y2],形状为(n, 4),
  323. 其中n代表真实标注框的个数。
  324. - gt_poly (list): 水平翻转后的多边形分割区域的x、y坐标,长度为n,
  325. 其中n代表真实标注框的个数。
  326. Raises:
  327. TypeError: 形参数据类型不满足需求。
  328. ValueError: 数据长度不匹配。
  329. """
  330. if not isinstance(im, np.ndarray):
  331. raise TypeError(
  332. "RandomHorizontalFlip: image is not a numpy array.")
  333. if len(im.shape) != 3:
  334. raise ValueError(
  335. "RandomHorizontalFlip: image is not 3-dimensional.")
  336. if im_info is None or label_info is None:
  337. raise TypeError(
  338. 'Cannot do RandomHorizontalFlip! ' +
  339. 'Becasuse the im_info and label_info can not be None!')
  340. if 'augment_shape' not in im_info:
  341. raise TypeError('Cannot do RandomHorizontalFlip! ' + \
  342. 'Becasuse augment_shape is not in im_info!')
  343. if 'gt_bbox' not in label_info:
  344. raise TypeError('Cannot do RandomHorizontalFlip! ' + \
  345. 'Becasuse gt_bbox is not in label_info!')
  346. augment_shape = im_info['augment_shape']
  347. gt_bbox = label_info['gt_bbox']
  348. height = augment_shape[0]
  349. width = augment_shape[1]
  350. if np.random.uniform(0, 1) < self.prob:
  351. im = horizontal_flip(im)
  352. if gt_bbox.shape[0] == 0:
  353. if label_info is None:
  354. return (im, im_info)
  355. else:
  356. return (im, im_info, label_info)
  357. label_info['gt_bbox'] = box_horizontal_flip(gt_bbox, width)
  358. if 'gt_poly' in label_info and \
  359. len(label_info['gt_poly']) != 0:
  360. label_info['gt_poly'] = segms_horizontal_flip(
  361. label_info['gt_poly'], height, width)
  362. if label_info is None:
  363. return (im, im_info)
  364. else:
  365. return (im, im_info, label_info)
  366. class Normalize:
  367. """对图像进行标准化。
  368. 1. 归一化图像到到区间[0.0, 1.0]。
  369. 2. 对图像进行减均值除以标准差操作。
  370. Args:
  371. mean (list): 图像数据集的均值。默认为[0.485, 0.456, 0.406]。
  372. std (list): 图像数据集的标准差。默认为[0.229, 0.224, 0.225]。
  373. Raises:
  374. TypeError: 形参数据类型不满足需求。
  375. """
  376. def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
  377. self.mean = mean
  378. self.std = std
  379. if not (isinstance(self.mean, list) and isinstance(self.std, list)):
  380. raise TypeError("NormalizeImage: input type is invalid.")
  381. from functools import reduce
  382. if reduce(lambda x, y: x * y, self.std) == 0:
  383. raise TypeError('NormalizeImage: std is invalid!')
  384. def __call__(self, im, im_info=None, label_info=None):
  385. """
  386. Args:
  387. im (numnp.ndarraypy): 图像np.ndarray数据。
  388. im_info (dict, 可选): 存储与图像相关的信息。
  389. label_info (dict, 可选): 存储与标注框相关的信息。
  390. Returns:
  391. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  392. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  393. 存储与标注框相关信息的字典。
  394. """
  395. mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
  396. std = np.array(self.std)[np.newaxis, np.newaxis, :]
  397. im = normalize(im, mean, std)
  398. if label_info is None:
  399. return (im, im_info)
  400. else:
  401. return (im, im_info, label_info)
  402. class RandomDistort:
  403. """以一定的概率对图像进行随机像素内容变换,模型训练时的数据增强操作
  404. 1. 对变换的操作顺序进行随机化操作。
  405. 2. 按照1中的顺序以一定的概率在范围[-range, range]对图像进行随机像素内容变换。
  406. Args:
  407. brightness_range (float): 明亮度因子的范围。默认为0.5。
  408. brightness_prob (float): 随机调整明亮度的概率。默认为0.5。
  409. contrast_range (float): 对比度因子的范围。默认为0.5。
  410. contrast_prob (float): 随机调整对比度的概率。默认为0.5。
  411. saturation_range (float): 饱和度因子的范围。默认为0.5。
  412. saturation_prob (float): 随机调整饱和度的概率。默认为0.5。
  413. hue_range (int): 色调因子的范围。默认为18。
  414. hue_prob (float): 随机调整色调的概率。默认为0.5。
  415. """
  416. def __init__(self,
  417. brightness_range=0.5,
  418. brightness_prob=0.5,
  419. contrast_range=0.5,
  420. contrast_prob=0.5,
  421. saturation_range=0.5,
  422. saturation_prob=0.5,
  423. hue_range=18,
  424. hue_prob=0.5):
  425. self.brightness_range = brightness_range
  426. self.brightness_prob = brightness_prob
  427. self.contrast_range = contrast_range
  428. self.contrast_prob = contrast_prob
  429. self.saturation_range = saturation_range
  430. self.saturation_prob = saturation_prob
  431. self.hue_range = hue_range
  432. self.hue_prob = hue_prob
  433. def __call__(self, im, im_info=None, label_info=None):
  434. """
  435. Args:
  436. im (np.ndarray): 图像np.ndarray数据。
  437. im_info (dict, 可选): 存储与图像相关的信息。
  438. label_info (dict, 可选): 存储与标注框相关的信息。
  439. Returns:
  440. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  441. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  442. 存储与标注框相关信息的字典。
  443. """
  444. brightness_lower = 1 - self.brightness_range
  445. brightness_upper = 1 + self.brightness_range
  446. contrast_lower = 1 - self.contrast_range
  447. contrast_upper = 1 + self.contrast_range
  448. saturation_lower = 1 - self.saturation_range
  449. saturation_upper = 1 + self.saturation_range
  450. hue_lower = -self.hue_range
  451. hue_upper = self.hue_range
  452. ops = [brightness, contrast, saturation, hue]
  453. random.shuffle(ops)
  454. params_dict = {
  455. 'brightness': {
  456. 'brightness_lower': brightness_lower,
  457. 'brightness_upper': brightness_upper
  458. },
  459. 'contrast': {
  460. 'contrast_lower': contrast_lower,
  461. 'contrast_upper': contrast_upper
  462. },
  463. 'saturation': {
  464. 'saturation_lower': saturation_lower,
  465. 'saturation_upper': saturation_upper
  466. },
  467. 'hue': {
  468. 'hue_lower': hue_lower,
  469. 'hue_upper': hue_upper
  470. }
  471. }
  472. prob_dict = {
  473. 'brightness': self.brightness_prob,
  474. 'contrast': self.contrast_prob,
  475. 'saturation': self.saturation_prob,
  476. 'hue': self.hue_prob
  477. }
  478. for id in range(4):
  479. params = params_dict[ops[id].__name__]
  480. prob = prob_dict[ops[id].__name__]
  481. params['im'] = im
  482. if np.random.uniform(0, 1) < prob:
  483. im = ops[id](**params)
  484. if label_info is None:
  485. return (im, im_info)
  486. else:
  487. return (im, im_info, label_info)
  488. class MixupImage:
  489. """对图像进行mixup操作,模型训练时的数据增强操作,目前仅YOLOv3模型支持该transform。
  490. 当label_info中不存在mixup字段时,直接返回,否则进行下述操作:
  491. 1. 从随机beta分布中抽取出随机因子factor。
  492. 2.
  493. - 当factor>=1.0时,去除label_info中的mixup字段,直接返回。
  494. - 当factor<=0.0时,直接返回label_info中的mixup字段,并在label_info中去除该字段。
  495. - 其余情况,执行下述操作:
  496. (1)原图像乘以factor,mixup图像乘以(1-factor),叠加2个结果。
  497. (2)拼接原图像标注框和mixup图像标注框。
  498. (3)拼接原图像标注框类别和mixup图像标注框类别。
  499. (4)原图像标注框混合得分乘以factor,mixup图像标注框混合得分乘以(1-factor),叠加2个结果。
  500. 3. 更新im_info中的augment_shape信息。
  501. Args:
  502. alpha (float): 随机beta分布的下限。默认为1.5。
  503. beta (float): 随机beta分布的上限。默认为1.5。
  504. mixup_epoch (int): 在前mixup_epoch轮使用mixup增强操作;当该参数为-1时,该策略不会生效。
  505. 默认为-1。
  506. Raises:
  507. ValueError: 数据长度不匹配。
  508. """
  509. def __init__(self, alpha=1.5, beta=1.5, mixup_epoch=-1):
  510. self.alpha = alpha
  511. self.beta = beta
  512. if self.alpha <= 0.0:
  513. raise ValueError("alpha shold be positive in MixupImage")
  514. if self.beta <= 0.0:
  515. raise ValueError("beta shold be positive in MixupImage")
  516. self.mixup_epoch = mixup_epoch
  517. def _mixup_img(self, img1, img2, factor):
  518. h = max(img1.shape[0], img2.shape[0])
  519. w = max(img1.shape[1], img2.shape[1])
  520. img = np.zeros((h, w, img1.shape[2]), 'float32')
  521. img[:img1.shape[0], :img1.shape[1], :] = \
  522. img1.astype('float32') * factor
  523. img[:img2.shape[0], :img2.shape[1], :] += \
  524. img2.astype('float32') * (1.0 - factor)
  525. return img.astype('float32')
  526. def __call__(self, im, im_info=None, label_info=None):
  527. """
  528. Args:
  529. im (np.ndarray): 图像np.ndarray数据。
  530. im_info (dict, 可选): 存储与图像相关的信息。
  531. label_info (dict, 可选): 存储与标注框相关的信息。
  532. Returns:
  533. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  534. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  535. 存储与标注框相关信息的字典。
  536. 其中,im_info更新字段为:
  537. - augment_shape (np.ndarray): mixup后的图像高、宽二者组成的np.ndarray,形状为(2,)。
  538. im_info删除的字段:
  539. - mixup (list): 与当前字段进行mixup的图像相关信息。
  540. label_info更新字段为:
  541. - gt_bbox (np.ndarray): mixup后真实标注框坐标,形状为(n, 4),
  542. 其中n代表真实标注框的个数。
  543. - gt_class (np.ndarray): mixup后每个真实标注框对应的类别序号,形状为(n, 1),
  544. 其中n代表真实标注框的个数。
  545. - gt_score (np.ndarray): mixup后每个真实标注框对应的混合得分,形状为(n, 1),
  546. 其中n代表真实标注框的个数。
  547. Raises:
  548. TypeError: 形参数据类型不满足需求。
  549. """
  550. if im_info is None:
  551. raise TypeError('Cannot do MixupImage! ' +
  552. 'Becasuse the im_info can not be None!')
  553. if 'mixup' not in im_info:
  554. if label_info is None:
  555. return (im, im_info)
  556. else:
  557. return (im, im_info, label_info)
  558. factor = np.random.beta(self.alpha, self.beta)
  559. factor = max(0.0, min(1.0, factor))
  560. if im_info['epoch'] > self.mixup_epoch \
  561. or factor >= 1.0:
  562. im_info.pop('mixup')
  563. if label_info is None:
  564. return (im, im_info)
  565. else:
  566. return (im, im_info, label_info)
  567. if factor <= 0.0:
  568. return im_info.pop('mixup')
  569. im = self._mixup_img(im, im_info['mixup'][0], factor)
  570. if label_info is None:
  571. raise TypeError('Cannot do MixupImage! ' +
  572. 'Becasuse the label_info can not be None!')
  573. if 'gt_bbox' not in label_info or \
  574. 'gt_class' not in label_info or \
  575. 'gt_score' not in label_info:
  576. raise TypeError('Cannot do MixupImage! ' + \
  577. 'Becasuse gt_bbox/gt_class/gt_score is not in label_info!')
  578. gt_bbox1 = label_info['gt_bbox']
  579. gt_bbox2 = im_info['mixup'][2]['gt_bbox']
  580. gt_bbox = np.concatenate((gt_bbox1, gt_bbox2), axis=0)
  581. gt_class1 = label_info['gt_class']
  582. gt_class2 = im_info['mixup'][2]['gt_class']
  583. gt_class = np.concatenate((gt_class1, gt_class2), axis=0)
  584. gt_score1 = label_info['gt_score']
  585. gt_score2 = im_info['mixup'][2]['gt_score']
  586. gt_score = np.concatenate(
  587. (gt_score1 * factor, gt_score2 * (1. - factor)), axis=0)
  588. if 'gt_poly' in label_info:
  589. gt_poly1 = label_info['gt_poly']
  590. gt_poly2 = im_info['mixup'][2]['gt_poly']
  591. label_info['gt_poly'] = gt_poly1 + gt_poly2
  592. is_crowd1 = label_info['is_crowd']
  593. is_crowd2 = im_info['mixup'][2]['is_crowd']
  594. is_crowd = np.concatenate((is_crowd1, is_crowd2), axis=0)
  595. label_info['gt_bbox'] = gt_bbox
  596. label_info['gt_score'] = gt_score
  597. label_info['gt_class'] = gt_class
  598. label_info['is_crowd'] = is_crowd
  599. im_info['augment_shape'] = np.array([im.shape[0],
  600. im.shape[1]]).astype('int32')
  601. im_info.pop('mixup')
  602. if label_info is None:
  603. return (im, im_info)
  604. else:
  605. return (im, im_info, label_info)
  606. class RandomExpand:
  607. """随机扩张图像,模型训练时的数据增强操作。
  608. 1. 随机选取扩张比例(扩张比例大于1时才进行扩张)。
  609. 2. 计算扩张后图像大小。
  610. 3. 初始化像素值为输入填充值的图像,并将原图像随机粘贴于该图像上。
  611. 4. 根据原图像粘贴位置换算出扩张后真实标注框的位置坐标。
  612. 5. 根据原图像粘贴位置换算出扩张后真实分割区域的位置坐标。
  613. Args:
  614. ratio (float): 图像扩张的最大比例。默认为4.0。
  615. prob (float): 随机扩张的概率。默认为0.5。
  616. fill_value (list): 扩张图像的初始填充值(0-255)。默认为[123.675, 116.28, 103.53]。
  617. """
  618. def __init__(self,
  619. ratio=4.,
  620. prob=0.5,
  621. fill_value=[123.675, 116.28, 103.53]):
  622. super(RandomExpand, self).__init__()
  623. assert ratio > 1.01, "expand ratio must be larger than 1.01"
  624. self.ratio = ratio
  625. self.prob = prob
  626. assert isinstance(fill_value, Sequence), \
  627. "fill value must be sequence"
  628. if not isinstance(fill_value, tuple):
  629. fill_value = tuple(fill_value)
  630. self.fill_value = fill_value
  631. def __call__(self, im, im_info=None, label_info=None):
  632. """
  633. Args:
  634. im (np.ndarray): 图像np.ndarray数据。
  635. im_info (dict, 可选): 存储与图像相关的信息。
  636. label_info (dict, 可选): 存储与标注框相关的信息。
  637. Returns:
  638. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  639. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  640. 存储与标注框相关信息的字典。
  641. 其中,im_info更新字段为:
  642. - augment_shape (np.ndarray): 扩张后的图像高、宽二者组成的np.ndarray,形状为(2,)。
  643. label_info更新字段为:
  644. - gt_bbox (np.ndarray): 随机扩张后真实标注框坐标,形状为(n, 4),
  645. 其中n代表真实标注框的个数。
  646. - gt_class (np.ndarray): 随机扩张后每个真实标注框对应的类别序号,形状为(n, 1),
  647. 其中n代表真实标注框的个数。
  648. Raises:
  649. TypeError: 形参数据类型不满足需求。
  650. """
  651. if im_info is None or label_info is None:
  652. raise TypeError(
  653. 'Cannot do RandomExpand! ' +
  654. 'Becasuse the im_info and label_info can not be None!')
  655. if 'augment_shape' not in im_info:
  656. raise TypeError('Cannot do RandomExpand! ' + \
  657. 'Becasuse augment_shape is not in im_info!')
  658. if 'gt_bbox' not in label_info or \
  659. 'gt_class' not in label_info:
  660. raise TypeError('Cannot do RandomExpand! ' + \
  661. 'Becasuse gt_bbox/gt_class is not in label_info!')
  662. if np.random.uniform(0., 1.) < self.prob:
  663. return (im, im_info, label_info)
  664. augment_shape = im_info['augment_shape']
  665. height = int(augment_shape[0])
  666. width = int(augment_shape[1])
  667. expand_ratio = np.random.uniform(1., self.ratio)
  668. h = int(height * expand_ratio)
  669. w = int(width * expand_ratio)
  670. if not h > height or not w > width:
  671. return (im, im_info, label_info)
  672. y = np.random.randint(0, h - height)
  673. x = np.random.randint(0, w - width)
  674. canvas = np.ones((h, w, 3), dtype=np.float32)
  675. canvas *= np.array(self.fill_value, dtype=np.float32)
  676. canvas[y:y + height, x:x + width, :] = im
  677. im_info['augment_shape'] = np.array([h, w]).astype('int32')
  678. if 'gt_bbox' in label_info and len(label_info['gt_bbox']) > 0:
  679. label_info['gt_bbox'] += np.array([x, y] * 2, dtype=np.float32)
  680. if 'gt_poly' in label_info and len(label_info['gt_poly']) > 0:
  681. label_info['gt_poly'] = expand_segms(label_info['gt_poly'], x, y,
  682. height, width, expand_ratio)
  683. return (canvas, im_info, label_info)
  684. class RandomCrop:
  685. """随机裁剪图像。
  686. 1. 若allow_no_crop为True,则在thresholds加入’no_crop’。
  687. 2. 随机打乱thresholds。
  688. 3. 遍历thresholds中各元素:
  689. (1) 如果当前thresh为’no_crop’,则返回原始图像和标注信息。
  690. (2) 随机取出aspect_ratio和scaling中的值并由此计算出候选裁剪区域的高、宽、起始点。
  691. (3) 计算真实标注框与候选裁剪区域IoU,若全部真实标注框的IoU都小于thresh,则继续第3步。
  692. (4) 如果cover_all_box为True且存在真实标注框的IoU小于thresh,则继续第3步。
  693. (5) 筛选出位于候选裁剪区域内的真实标注框,若有效框的个数为0,则继续第3步,否则进行第4步。
  694. 4. 换算有效真值标注框相对候选裁剪区域的位置坐标。
  695. 5. 换算有效分割区域相对候选裁剪区域的位置坐标。
  696. Args:
  697. aspect_ratio (list): 裁剪后短边缩放比例的取值范围,以[min, max]形式表示。默认值为[.5, 2.]。
  698. thresholds (list): 判断裁剪候选区域是否有效所需的IoU阈值取值列表。默认值为[.0, .1, .3, .5, .7, .9]。
  699. scaling (list): 裁剪面积相对原面积的取值范围,以[min, max]形式表示。默认值为[.3, 1.]。
  700. num_attempts (int): 在放弃寻找有效裁剪区域前尝试的次数。默认值为50。
  701. allow_no_crop (bool): 是否允许未进行裁剪。默认值为True。
  702. cover_all_box (bool): 是否要求所有的真实标注框都必须在裁剪区域内。默认值为False。
  703. """
  704. def __init__(self,
  705. aspect_ratio=[.5, 2.],
  706. thresholds=[.0, .1, .3, .5, .7, .9],
  707. scaling=[.3, 1.],
  708. num_attempts=50,
  709. allow_no_crop=True,
  710. cover_all_box=False):
  711. self.aspect_ratio = aspect_ratio
  712. self.thresholds = thresholds
  713. self.scaling = scaling
  714. self.num_attempts = num_attempts
  715. self.allow_no_crop = allow_no_crop
  716. self.cover_all_box = cover_all_box
  717. def __call__(self, im, im_info=None, label_info=None):
  718. """
  719. Args:
  720. im (np.ndarray): 图像np.ndarray数据。
  721. im_info (dict, 可选): 存储与图像相关的信息。
  722. label_info (dict, 可选): 存储与标注框相关的信息。
  723. Returns:
  724. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  725. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  726. 存储与标注框相关信息的字典。
  727. 其中,label_info更新字段为:
  728. - gt_bbox (np.ndarray): 随机裁剪后真实标注框坐标,形状为(n, 4),
  729. 其中n代表真实标注框的个数。
  730. - gt_class (np.ndarray): 随机裁剪后每个真实标注框对应的类别序号,形状为(n, 1),
  731. 其中n代表真实标注框的个数。
  732. - gt_score (np.ndarray): 随机裁剪后每个真实标注框对应的混合得分,形状为(n, 1),
  733. 其中n代表真实标注框的个数。
  734. Raises:
  735. TypeError: 形参数据类型不满足需求。
  736. """
  737. if im_info is None or label_info is None:
  738. raise TypeError(
  739. 'Cannot do RandomCrop! ' +
  740. 'Becasuse the im_info and label_info can not be None!')
  741. if 'augment_shape' not in im_info:
  742. raise TypeError('Cannot do RandomCrop! ' + \
  743. 'Becasuse augment_shape is not in im_info!')
  744. if 'gt_bbox' not in label_info or \
  745. 'gt_class' not in label_info:
  746. raise TypeError('Cannot do RandomCrop! ' + \
  747. 'Becasuse gt_bbox/gt_class is not in label_info!')
  748. if len(label_info['gt_bbox']) == 0:
  749. return (im, im_info, label_info)
  750. augment_shape = im_info['augment_shape']
  751. w = augment_shape[1]
  752. h = augment_shape[0]
  753. gt_bbox = label_info['gt_bbox']
  754. thresholds = list(self.thresholds)
  755. if self.allow_no_crop:
  756. thresholds.append('no_crop')
  757. np.random.shuffle(thresholds)
  758. for thresh in thresholds:
  759. if thresh == 'no_crop':
  760. return (im, im_info, label_info)
  761. found = False
  762. for i in range(self.num_attempts):
  763. scale = np.random.uniform(*self.scaling)
  764. min_ar, max_ar = self.aspect_ratio
  765. aspect_ratio = np.random.uniform(
  766. max(min_ar, scale**2), min(max_ar, scale**-2))
  767. crop_h = int(h * scale / np.sqrt(aspect_ratio))
  768. crop_w = int(w * scale * np.sqrt(aspect_ratio))
  769. crop_y = np.random.randint(0, h - crop_h)
  770. crop_x = np.random.randint(0, w - crop_w)
  771. crop_box = [crop_x, crop_y, crop_x + crop_w, crop_y + crop_h]
  772. iou = iou_matrix(gt_bbox, np.array([crop_box],
  773. dtype=np.float32))
  774. if iou.max() < thresh:
  775. continue
  776. if self.cover_all_box and iou.min() < thresh:
  777. continue
  778. cropped_box, valid_ids = crop_box_with_center_constraint(
  779. gt_bbox, np.array(crop_box, dtype=np.float32))
  780. if valid_ids.size > 0:
  781. found = True
  782. break
  783. if found:
  784. if 'gt_poly' in label_info and len(label_info['gt_poly']) > 0:
  785. crop_polys = crop_segms(label_info['gt_poly'], valid_ids,
  786. np.array(crop_box, dtype=np.int64),
  787. h, w)
  788. if [] in crop_polys:
  789. delete_id = list()
  790. valid_polys = list()
  791. for id, crop_poly in enumerate(crop_polys):
  792. if crop_poly == []:
  793. delete_id.append(id)
  794. else:
  795. valid_polys.append(crop_poly)
  796. valid_ids = np.delete(valid_ids, delete_id)
  797. if len(valid_polys) == 0:
  798. return (im, im_info, label_info)
  799. label_info['gt_poly'] = valid_polys
  800. else:
  801. label_info['gt_poly'] = crop_polys
  802. im = crop_image(im, crop_box)
  803. label_info['gt_bbox'] = np.take(cropped_box, valid_ids, axis=0)
  804. label_info['gt_class'] = np.take(
  805. label_info['gt_class'], valid_ids, axis=0)
  806. im_info['augment_shape'] = np.array(
  807. [crop_box[3] - crop_box[1],
  808. crop_box[2] - crop_box[0]]).astype('int32')
  809. if 'gt_score' in label_info:
  810. label_info['gt_score'] = np.take(
  811. label_info['gt_score'], valid_ids, axis=0)
  812. if 'is_crowd' in label_info:
  813. label_info['is_crowd'] = np.take(
  814. label_info['is_crowd'], valid_ids, axis=0)
  815. return (im, im_info, label_info)
  816. return (im, im_info, label_info)
  817. class ArrangeFasterRCNN:
  818. """获取FasterRCNN模型训练/验证/预测所需信息。
  819. Args:
  820. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  821. Raises:
  822. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  823. """
  824. def __init__(self, mode=None):
  825. if mode not in ['train', 'eval', 'test', 'quant']:
  826. raise ValueError(
  827. "mode must be in ['train', 'eval', 'test', 'quant']!")
  828. self.mode = mode
  829. def __call__(self, im, im_info=None, label_info=None):
  830. """
  831. Args:
  832. im (np.ndarray): 图像np.ndarray数据。
  833. im_info (dict, 可选): 存储与图像相关的信息。
  834. label_info (dict, 可选): 存储与标注框相关的信息。
  835. Returns:
  836. tuple: 当mode为'train'时,返回(im, im_resize_info, gt_bbox, gt_class, is_crowd),分别对应
  837. 图像np.ndarray数据、图像相当对于原图的resize信息、真实标注框、真实标注框对应的类别、真实标注框内是否是一组对象;
  838. 当mode为'eval'时,返回(im, im_resize_info, im_id, im_shape, gt_bbox, gt_class, is_difficult),
  839. 分别对应图像np.ndarray数据、图像相当对于原图的resize信息、图像id、图像大小信息、真实标注框、真实标注框对应的类别、
  840. 真实标注框是否为难识别对象;当mode为'test'或'quant'时,返回(im, im_resize_info, im_shape),分别对应图像np.ndarray数据、
  841. 图像相当对于原图的resize信息、图像大小信息。
  842. Raises:
  843. TypeError: 形参数据类型不满足需求。
  844. ValueError: 数据长度不匹配。
  845. """
  846. im = permute(im, False)
  847. if self.mode == 'train':
  848. if im_info is None or label_info is None:
  849. raise TypeError(
  850. 'Cannot do ArrangeFasterRCNN! ' +
  851. 'Becasuse the im_info and label_info can not be None!')
  852. if len(label_info['gt_bbox']) != len(label_info['gt_class']):
  853. raise ValueError("gt num mismatch: bbox and class.")
  854. im_resize_info = im_info['im_resize_info']
  855. gt_bbox = label_info['gt_bbox']
  856. gt_class = label_info['gt_class']
  857. is_crowd = label_info['is_crowd']
  858. outputs = (im, im_resize_info, gt_bbox, gt_class, is_crowd)
  859. elif self.mode == 'eval':
  860. if im_info is None or label_info is None:
  861. raise TypeError(
  862. 'Cannot do ArrangeFasterRCNN! ' +
  863. 'Becasuse the im_info and label_info can not be None!')
  864. im_resize_info = im_info['im_resize_info']
  865. im_id = im_info['im_id']
  866. im_shape = np.array(
  867. (im_info['augment_shape'][0], im_info['augment_shape'][1], 1),
  868. dtype=np.float32)
  869. gt_bbox = label_info['gt_bbox']
  870. gt_class = label_info['gt_class']
  871. is_difficult = label_info['difficult']
  872. outputs = (im, im_resize_info, im_id, im_shape, gt_bbox, gt_class,
  873. is_difficult)
  874. else:
  875. if im_info is None:
  876. raise TypeError('Cannot do ArrangeFasterRCNN! ' +
  877. 'Becasuse the im_info can not be None!')
  878. im_resize_info = im_info['im_resize_info']
  879. im_shape = np.array(
  880. (im_info['augment_shape'][0], im_info['augment_shape'][1], 1),
  881. dtype=np.float32)
  882. outputs = (im, im_resize_info, im_shape)
  883. return outputs
  884. class ArrangeMaskRCNN:
  885. """获取MaskRCNN模型训练/验证/预测所需信息。
  886. Args:
  887. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  888. Raises:
  889. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  890. """
  891. def __init__(self, mode=None):
  892. if mode not in ['train', 'eval', 'test', 'quant']:
  893. raise ValueError(
  894. "mode must be in ['train', 'eval', 'test', 'quant']!")
  895. self.mode = mode
  896. def __call__(self, im, im_info=None, label_info=None):
  897. """
  898. Args:
  899. im (np.ndarray): 图像np.ndarray数据。
  900. im_info (dict, 可选): 存储与图像相关的信息。
  901. label_info (dict, 可选): 存储与标注框相关的信息。
  902. Returns:
  903. tuple: 当mode为'train'时,返回(im, im_resize_info, gt_bbox, gt_class, is_crowd, gt_masks),分别对应
  904. 图像np.ndarray数据、图像相当对于原图的resize信息、真实标注框、真实标注框对应的类别、真实标注框内是否是一组对象、
  905. 真实分割区域;当mode为'eval'时,返回(im, im_resize_info, im_id, im_shape),分别对应图像np.ndarray数据、
  906. 图像相当对于原图的resize信息、图像id、图像大小信息;当mode为'test'或'quant'时,返回(im, im_resize_info, im_shape),
  907. 分别对应图像np.ndarray数据、图像相当对于原图的resize信息、图像大小信息。
  908. Raises:
  909. TypeError: 形参数据类型不满足需求。
  910. ValueError: 数据长度不匹配。
  911. """
  912. im = permute(im, False)
  913. if self.mode == 'train':
  914. if im_info is None or label_info is None:
  915. raise TypeError(
  916. 'Cannot do ArrangeTrainMaskRCNN! ' +
  917. 'Becasuse the im_info and label_info can not be None!')
  918. if len(label_info['gt_bbox']) != len(label_info['gt_class']):
  919. raise ValueError("gt num mismatch: bbox and class.")
  920. im_resize_info = im_info['im_resize_info']
  921. gt_bbox = label_info['gt_bbox']
  922. gt_class = label_info['gt_class']
  923. is_crowd = label_info['is_crowd']
  924. assert 'gt_poly' in label_info
  925. segms = label_info['gt_poly']
  926. if len(segms) != 0:
  927. assert len(segms) == is_crowd.shape[0]
  928. gt_masks = []
  929. valid = True
  930. for i in range(len(segms)):
  931. segm = segms[i]
  932. gt_segm = []
  933. if is_crowd[i]:
  934. gt_segm.append([[0, 0]])
  935. else:
  936. for poly in segm:
  937. if len(poly) == 0:
  938. valid = False
  939. break
  940. gt_segm.append(np.array(poly).reshape(-1, 2))
  941. if (not valid) or len(gt_segm) == 0:
  942. break
  943. gt_masks.append(gt_segm)
  944. outputs = (im, im_resize_info, gt_bbox, gt_class, is_crowd,
  945. gt_masks)
  946. else:
  947. if im_info is None:
  948. raise TypeError('Cannot do ArrangeMaskRCNN! ' +
  949. 'Becasuse the im_info can not be None!')
  950. im_resize_info = im_info['im_resize_info']
  951. im_shape = np.array(
  952. (im_info['augment_shape'][0], im_info['augment_shape'][1], 1),
  953. dtype=np.float32)
  954. if self.mode == 'eval':
  955. im_id = im_info['im_id']
  956. outputs = (im, im_resize_info, im_id, im_shape)
  957. else:
  958. outputs = (im, im_resize_info, im_shape)
  959. return outputs
  960. class ArrangeYOLOv3:
  961. """获取YOLOv3模型训练/验证/预测所需信息。
  962. Args:
  963. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  964. Raises:
  965. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  966. """
  967. def __init__(self, mode=None):
  968. if mode not in ['train', 'eval', 'test', 'quant']:
  969. raise ValueError(
  970. "mode must be in ['train', 'eval', 'test', 'quant']!")
  971. self.mode = mode
  972. def __call__(self, im, im_info=None, label_info=None):
  973. """
  974. Args:
  975. im (np.ndarray): 图像np.ndarray数据。
  976. im_info (dict, 可选): 存储与图像相关的信息。
  977. label_info (dict, 可选): 存储与标注框相关的信息。
  978. Returns:
  979. tuple: 当mode为'train'时,返回(im, gt_bbox, gt_class, gt_score, im_shape),分别对应
  980. 图像np.ndarray数据、真实标注框、真实标注框对应的类别、真实标注框混合得分、图像大小信息;
  981. 当mode为'eval'时,返回(im, im_shape, im_id, gt_bbox, gt_class, difficult),
  982. 分别对应图像np.ndarray数据、图像大小信息、图像id、真实标注框、真实标注框对应的类别、
  983. 真实标注框是否为难识别对象;当mode为'test'或'quant'时,返回(im, im_shape),
  984. 分别对应图像np.ndarray数据、图像大小信息。
  985. Raises:
  986. TypeError: 形参数据类型不满足需求。
  987. ValueError: 数据长度不匹配。
  988. """
  989. im = permute(im, False)
  990. if self.mode == 'train':
  991. if im_info is None or label_info is None:
  992. raise TypeError(
  993. 'Cannot do ArrangeYolov3! ' +
  994. 'Becasuse the im_info and label_info can not be None!')
  995. im_shape = im_info['augment_shape']
  996. if len(label_info['gt_bbox']) != len(label_info['gt_class']):
  997. raise ValueError("gt num mismatch: bbox and class.")
  998. if len(label_info['gt_bbox']) != len(label_info['gt_score']):
  999. raise ValueError("gt num mismatch: bbox and score.")
  1000. gt_bbox = np.zeros((50, 4), dtype=im.dtype)
  1001. gt_class = np.zeros((50, ), dtype=np.int32)
  1002. gt_score = np.zeros((50, ), dtype=im.dtype)
  1003. gt_num = min(50, len(label_info['gt_bbox']))
  1004. if gt_num > 0:
  1005. label_info['gt_class'][:gt_num, 0] = label_info[
  1006. 'gt_class'][:gt_num, 0] - 1
  1007. gt_bbox[:gt_num, :] = label_info['gt_bbox'][:gt_num, :]
  1008. gt_class[:gt_num] = label_info['gt_class'][:gt_num, 0]
  1009. gt_score[:gt_num] = label_info['gt_score'][:gt_num, 0]
  1010. # parse [x1, y1, x2, y2] to [x, y, w, h]
  1011. gt_bbox[:, 2:4] = gt_bbox[:, 2:4] - gt_bbox[:, :2]
  1012. gt_bbox[:, :2] = gt_bbox[:, :2] + gt_bbox[:, 2:4] / 2.
  1013. outputs = (im, gt_bbox, gt_class, gt_score, im_shape)
  1014. elif self.mode == 'eval':
  1015. if im_info is None or label_info is None:
  1016. raise TypeError(
  1017. 'Cannot do ArrangeYolov3! ' +
  1018. 'Becasuse the im_info and label_info can not be None!')
  1019. im_shape = im_info['augment_shape']
  1020. if len(label_info['gt_bbox']) != len(label_info['gt_class']):
  1021. raise ValueError("gt num mismatch: bbox and class.")
  1022. im_id = im_info['im_id']
  1023. gt_bbox = np.zeros((50, 4), dtype=im.dtype)
  1024. gt_class = np.zeros((50, ), dtype=np.int32)
  1025. difficult = np.zeros((50, ), dtype=np.int32)
  1026. gt_num = min(50, len(label_info['gt_bbox']))
  1027. if gt_num > 0:
  1028. label_info['gt_class'][:gt_num, 0] = label_info[
  1029. 'gt_class'][:gt_num, 0] - 1
  1030. gt_bbox[:gt_num, :] = label_info['gt_bbox'][:gt_num, :]
  1031. gt_class[:gt_num] = label_info['gt_class'][:gt_num, 0]
  1032. difficult[:gt_num] = label_info['difficult'][:gt_num, 0]
  1033. outputs = (im, im_shape, im_id, gt_bbox, gt_class, difficult)
  1034. else:
  1035. if im_info is None:
  1036. raise TypeError('Cannot do ArrangeYolov3! ' +
  1037. 'Becasuse the im_info can not be None!')
  1038. im_shape = im_info['augment_shape']
  1039. outputs = (im, im_shape)
  1040. return outputs