det_transforms.py 57 KB

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