det_transforms.py 54 KB

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