det_transforms.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  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. import paddlex.utils.logging as logging
  27. class DetTransform:
  28. """检测数据处理基类
  29. """
  30. def __init__(self):
  31. pass
  32. class Compose(DetTransform):
  33. """根据数据预处理/增强列表对输入数据进行操作。
  34. 所有操作的输入图像流形状均是[H, W, C],其中H为图像高,W为图像宽,C为图像通道数。
  35. Args:
  36. transforms (list): 数据预处理/增强列表。
  37. Raises:
  38. TypeError: 形参数据类型不满足需求。
  39. ValueError: 数据长度不匹配。
  40. """
  41. def __init__(self, transforms):
  42. if not isinstance(transforms, list):
  43. raise TypeError('The transforms must be a list!')
  44. if len(transforms) < 1:
  45. raise ValueError('The length of transforms ' + \
  46. 'must be equal or larger than 1!')
  47. self.transforms = transforms
  48. self.use_mixup = False
  49. for t in self.transforms:
  50. if type(t).__name__ == 'MixupImage':
  51. self.use_mixup = True
  52. # 检查transforms里面的操作,目前支持PaddleX定义的或者是imgaug操作
  53. for op in self.transforms:
  54. if not isinstance(op, DetTransform):
  55. import imgaug.augmenters as iaa
  56. if not isinstance(op, iaa.Augmenter):
  57. raise Exception(
  58. "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/"
  59. )
  60. def __call__(self, im, im_info=None, label_info=None):
  61. """
  62. Args:
  63. im (str/np.ndarray): 图像路径/图像np.ndarray数据。
  64. im_info (dict): 存储与图像相关的信息,dict中的字段如下:
  65. - im_id (np.ndarray): 图像序列号,形状为(1,)。
  66. - image_shape (np.ndarray): 图像原始大小,形状为(2,),
  67. image_shape[0]为高,image_shape[1]为宽。
  68. - mixup (list): list为[im, im_info, label_info],分别对应
  69. 与当前图像进行mixup的图像np.ndarray数据、图像相关信息、标注框相关信息;
  70. 注意,当前epoch若无需进行mixup,则无该字段。
  71. label_info (dict): 存储与标注框相关的信息,dict中的字段如下:
  72. - gt_bbox (np.ndarray): 真实标注框坐标[x1, y1, x2, y2],形状为(n, 4),
  73. 其中n代表真实标注框的个数。
  74. - gt_class (np.ndarray): 每个真实标注框对应的类别序号,形状为(n, 1),
  75. 其中n代表真实标注框的个数。
  76. - gt_score (np.ndarray): 每个真实标注框对应的混合得分,形状为(n, 1),
  77. 其中n代表真实标注框的个数。
  78. - gt_poly (list): 每个真实标注框内的多边形分割区域,每个分割区域由点的x、y坐标组成,
  79. 长度为n,其中n代表真实标注框的个数。
  80. - is_crowd (np.ndarray): 每个真实标注框中是否是一组对象,形状为(n, 1),
  81. 其中n代表真实标注框的个数。
  82. - difficult (np.ndarray): 每个真实标注框中的对象是否为难识别对象,形状为(n, 1),
  83. 其中n代表真实标注框的个数。
  84. Returns:
  85. tuple: 根据网络所需字段所组成的tuple;
  86. 字段由transforms中的最后一个数据预处理操作决定。
  87. """
  88. def decode_image(im_file, im_info, label_info):
  89. if im_info is None:
  90. im_info = dict()
  91. if isinstance(im_file, np.ndarray):
  92. if len(im_file.shape) != 3:
  93. raise Exception(
  94. "im should be 3-dimensions, but now is {}-dimensions".
  95. format(len(im_file.shape)))
  96. im = im_file
  97. else:
  98. try:
  99. im = cv2.imread(im_file).astype('float32')
  100. except:
  101. raise TypeError('Can\'t read The image file {}!'.format(
  102. im_file))
  103. im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
  104. # make default im_info with [h, w, 1]
  105. im_info['im_resize_info'] = np.array(
  106. [im.shape[0], im.shape[1], 1.], dtype=np.float32)
  107. im_info['image_shape'] = np.array([im.shape[0],
  108. im.shape[1]]).astype('int32')
  109. if not self.use_mixup:
  110. if 'mixup' in im_info:
  111. del im_info['mixup']
  112. # decode mixup image
  113. if 'mixup' in im_info:
  114. im_info['mixup'] = \
  115. decode_image(im_info['mixup'][0],
  116. im_info['mixup'][1],
  117. im_info['mixup'][2])
  118. if label_info is None:
  119. return (im, im_info)
  120. else:
  121. return (im, im_info, label_info)
  122. outputs = decode_image(im, im_info, label_info)
  123. im = outputs[0]
  124. im_info = outputs[1]
  125. if len(outputs) == 3:
  126. label_info = outputs[2]
  127. for op in self.transforms:
  128. if im is None:
  129. return None
  130. if isinstance(op, DetTransform):
  131. outputs = op(im, im_info, label_info)
  132. im = outputs[0]
  133. else:
  134. im = execute_imgaug(op, im)
  135. if label_info is not None:
  136. outputs = (im, im_info, label_info)
  137. else:
  138. outputs = (im, im_info)
  139. return outputs
  140. def add_augmenters(self, augmenters):
  141. if not isinstance(augmenters, list):
  142. raise Exception(
  143. "augmenters should be list type in func add_augmenters()")
  144. transform_names = [type(x).__name__ for x in self.transforms]
  145. for aug in augmenters:
  146. if type(aug).__name__ in transform_names:
  147. logging.error(
  148. "{} is already in ComposedTransforms, need to remove it from add_augmenters().".
  149. format(type(aug).__name__))
  150. self.transforms = augmenters + self.transforms
  151. class ResizeByShort(DetTransform):
  152. """根据图像的短边调整图像大小(resize)。
  153. 1. 获取图像的长边和短边长度。
  154. 2. 根据短边与short_size的比例,计算长边的目标长度,
  155. 此时高、宽的resize比例为short_size/原图短边长度。
  156. 3. 如果max_size>0,调整resize比例:
  157. 如果长边的目标长度>max_size,则高、宽的resize比例为max_size/原图长边长度。
  158. 4. 根据调整大小的比例对图像进行resize。
  159. Args:
  160. target_size (int): 短边目标长度。默认为800。
  161. max_size (int): 长边目标长度的最大限制。默认为1333。
  162. Raises:
  163. TypeError: 形参数据类型不满足需求。
  164. """
  165. def __init__(self, short_size=800, max_size=1333):
  166. self.max_size = int(max_size)
  167. if not isinstance(short_size, int):
  168. raise TypeError(
  169. "Type of short_size is invalid. Must be Integer, now is {}".
  170. format(type(short_size)))
  171. self.short_size = short_size
  172. if not (isinstance(self.max_size, int)):
  173. raise TypeError("max_size: input type is invalid.")
  174. def __call__(self, im, im_info=None, label_info=None):
  175. """
  176. Args:
  177. im (numnp.ndarraypy): 图像np.ndarray数据。
  178. im_info (dict, 可选): 存储与图像相关的信息。
  179. label_info (dict, 可选): 存储与标注框相关的信息。
  180. Returns:
  181. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  182. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  183. 存储与标注框相关信息的字典。
  184. 其中,im_info更新字段为:
  185. - im_resize_info (np.ndarray): resize后的图像高、resize后的图像宽、resize后的图像相对原始图的缩放比例
  186. 三者组成的np.ndarray,形状为(3,)。
  187. Raises:
  188. TypeError: 形参数据类型不满足需求。
  189. ValueError: 数据长度不匹配。
  190. """
  191. if im_info is None:
  192. im_info = dict()
  193. if not isinstance(im, np.ndarray):
  194. raise TypeError("ResizeByShort: image type is not numpy.")
  195. if len(im.shape) != 3:
  196. raise ValueError('ResizeByShort: image is not 3-dimensional.')
  197. im_short_size = min(im.shape[0], im.shape[1])
  198. im_long_size = max(im.shape[0], im.shape[1])
  199. scale = float(self.short_size) / im_short_size
  200. if self.max_size > 0 and np.round(scale * im_long_size) > self.max_size:
  201. scale = float(self.max_size) / float(im_long_size)
  202. resized_width = int(round(im.shape[1] * scale))
  203. resized_height = int(round(im.shape[0] * scale))
  204. im_resize_info = [resized_height, resized_width, scale]
  205. im = cv2.resize(
  206. im, (resized_width, resized_height), interpolation=cv2.INTER_LINEAR)
  207. im_info['im_resize_info'] = np.array(im_resize_info).astype(np.float32)
  208. if label_info is None:
  209. return (im, im_info)
  210. else:
  211. return (im, im_info, label_info)
  212. class Padding(DetTransform):
  213. """1.将图像的长和宽padding至coarsest_stride的倍数。如输入图像为[300, 640],
  214. `coarest_stride`为32,则由于300不为32的倍数,因此在图像最右和最下使用0值
  215. 进行padding,最终输出图像为[320, 640]。
  216. 2.或者,将图像的长和宽padding到target_size指定的shape,如输入的图像为[300,640],
  217. a. `target_size` = 960,在图像最右和最下使用0值进行padding,最终输出
  218. 图像为[960, 960]。
  219. b. `target_size` = [640, 960],在图像最右和最下使用0值进行padding,最终
  220. 输出图像为[640, 960]。
  221. 1. 如果coarsest_stride为1,target_size为None则直接返回。
  222. 2. 获取图像的高H、宽W。
  223. 3. 计算填充后图像的高H_new、宽W_new。
  224. 4. 构建大小为(H_new, W_new, 3)像素值为0的np.ndarray,
  225. 并将原图的np.ndarray粘贴于左上角。
  226. Args:
  227. coarsest_stride (int): 填充后的图像长、宽为该参数的倍数,默认为1。
  228. target_size (int|list|tuple): 填充后的图像长、宽,默认为None,coarset_stride优先级更高。
  229. Raises:
  230. TypeError: 形参`target_size`数据类型不满足需求。
  231. ValueError: 形参`target_size`为(list|tuple)时,长度不满足需求。
  232. """
  233. def __init__(self, coarsest_stride=1, target_size=None):
  234. self.coarsest_stride = coarsest_stride
  235. if target_size is not None:
  236. if not isinstance(target_size, int):
  237. if not isinstance(target_size, tuple) and not isinstance(
  238. target_size, list):
  239. raise TypeError(
  240. "Padding: Type of target_size must in (int|list|tuple).")
  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(self.target_size,
  272. 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(
  291. (padding_im_h, padding_im_w, im_c), 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("RandomHorizontalFlip: image is not a numpy array.")
  402. if len(im.shape) != 3:
  403. raise ValueError(
  404. "RandomHorizontalFlip: image is not 3-dimensional.")
  405. if im_info is None or label_info is None:
  406. raise TypeError(
  407. 'Cannot do RandomHorizontalFlip! ' +
  408. 'Becasuse the im_info and label_info can not be None!')
  409. if 'gt_bbox' not in label_info:
  410. raise TypeError('Cannot do RandomHorizontalFlip! ' + \
  411. 'Becasuse gt_bbox is not in label_info!')
  412. image_shape = im_info['image_shape']
  413. gt_bbox = label_info['gt_bbox']
  414. height = image_shape[0]
  415. width = image_shape[1]
  416. if np.random.uniform(0, 1) < self.prob:
  417. im = horizontal_flip(im)
  418. if gt_bbox.shape[0] == 0:
  419. if label_info is None:
  420. return (im, im_info)
  421. else:
  422. return (im, im_info, label_info)
  423. label_info['gt_bbox'] = box_horizontal_flip(gt_bbox, width)
  424. if 'gt_poly' in label_info and \
  425. len(label_info['gt_poly']) != 0:
  426. label_info['gt_poly'] = segms_horizontal_flip(
  427. label_info['gt_poly'], height, width)
  428. if label_info is None:
  429. return (im, im_info)
  430. else:
  431. return (im, im_info, label_info)
  432. class Normalize(DetTransform):
  433. """对图像进行标准化。
  434. 1. 归一化图像到到区间[0.0, 1.0]。
  435. 2. 对图像进行减均值除以标准差操作。
  436. Args:
  437. mean (list): 图像数据集的均值。默认为[0.485, 0.456, 0.406]。
  438. std (list): 图像数据集的标准差。默认为[0.229, 0.224, 0.225]。
  439. Raises:
  440. TypeError: 形参数据类型不满足需求。
  441. """
  442. def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
  443. self.mean = mean
  444. self.std = std
  445. if not (isinstance(self.mean, list) and isinstance(self.std, list)):
  446. raise TypeError("NormalizeImage: input type is invalid.")
  447. from functools import reduce
  448. if reduce(lambda x, y: x * y, self.std) == 0:
  449. raise TypeError('NormalizeImage: std is invalid!')
  450. def __call__(self, im, im_info=None, label_info=None):
  451. """
  452. Args:
  453. im (numnp.ndarraypy): 图像np.ndarray数据。
  454. im_info (dict, 可选): 存储与图像相关的信息。
  455. label_info (dict, 可选): 存储与标注框相关的信息。
  456. Returns:
  457. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  458. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  459. 存储与标注框相关信息的字典。
  460. """
  461. mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
  462. std = np.array(self.std)[np.newaxis, np.newaxis, :]
  463. im = normalize(im, mean, std)
  464. if label_info is None:
  465. return (im, im_info)
  466. else:
  467. return (im, im_info, label_info)
  468. class RandomDistort(DetTransform):
  469. """以一定的概率对图像进行随机像素内容变换,模型训练时的数据增强操作
  470. 1. 对变换的操作顺序进行随机化操作。
  471. 2. 按照1中的顺序以一定的概率在范围[-range, range]对图像进行随机像素内容变换。
  472. Args:
  473. brightness_range (float): 明亮度因子的范围。默认为0.5。
  474. brightness_prob (float): 随机调整明亮度的概率。默认为0.5。
  475. contrast_range (float): 对比度因子的范围。默认为0.5。
  476. contrast_prob (float): 随机调整对比度的概率。默认为0.5。
  477. saturation_range (float): 饱和度因子的范围。默认为0.5。
  478. saturation_prob (float): 随机调整饱和度的概率。默认为0.5。
  479. hue_range (int): 色调因子的范围。默认为18。
  480. hue_prob (float): 随机调整色调的概率。默认为0.5。
  481. """
  482. def __init__(self,
  483. brightness_range=0.5,
  484. brightness_prob=0.5,
  485. contrast_range=0.5,
  486. contrast_prob=0.5,
  487. saturation_range=0.5,
  488. saturation_prob=0.5,
  489. hue_range=18,
  490. hue_prob=0.5):
  491. self.brightness_range = brightness_range
  492. self.brightness_prob = brightness_prob
  493. self.contrast_range = contrast_range
  494. self.contrast_prob = contrast_prob
  495. self.saturation_range = saturation_range
  496. self.saturation_prob = saturation_prob
  497. self.hue_range = hue_range
  498. self.hue_prob = hue_prob
  499. def __call__(self, im, im_info=None, label_info=None):
  500. """
  501. Args:
  502. im (np.ndarray): 图像np.ndarray数据。
  503. im_info (dict, 可选): 存储与图像相关的信息。
  504. label_info (dict, 可选): 存储与标注框相关的信息。
  505. Returns:
  506. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  507. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  508. 存储与标注框相关信息的字典。
  509. """
  510. brightness_lower = 1 - self.brightness_range
  511. brightness_upper = 1 + self.brightness_range
  512. contrast_lower = 1 - self.contrast_range
  513. contrast_upper = 1 + self.contrast_range
  514. saturation_lower = 1 - self.saturation_range
  515. saturation_upper = 1 + self.saturation_range
  516. hue_lower = -self.hue_range
  517. hue_upper = self.hue_range
  518. ops = [brightness, contrast, saturation, hue]
  519. random.shuffle(ops)
  520. params_dict = {
  521. 'brightness': {
  522. 'brightness_lower': brightness_lower,
  523. 'brightness_upper': brightness_upper
  524. },
  525. 'contrast': {
  526. 'contrast_lower': contrast_lower,
  527. 'contrast_upper': contrast_upper
  528. },
  529. 'saturation': {
  530. 'saturation_lower': saturation_lower,
  531. 'saturation_upper': saturation_upper
  532. },
  533. 'hue': {
  534. 'hue_lower': hue_lower,
  535. 'hue_upper': hue_upper
  536. }
  537. }
  538. prob_dict = {
  539. 'brightness': self.brightness_prob,
  540. 'contrast': self.contrast_prob,
  541. 'saturation': self.saturation_prob,
  542. 'hue': self.hue_prob
  543. }
  544. for id in range(4):
  545. params = params_dict[ops[id].__name__]
  546. prob = prob_dict[ops[id].__name__]
  547. params['im'] = im
  548. if np.random.uniform(0, 1) < prob:
  549. im = ops[id](**params)
  550. im = im.astype('float32')
  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_class1 = label_info['gt_class']
  648. gt_class2 = im_info['mixup'][2]['gt_class']
  649. gt_score1 = label_info['gt_score']
  650. gt_score2 = im_info['mixup'][2]['gt_score']
  651. if 'gt_poly' in label_info:
  652. gt_poly1 = label_info['gt_poly']
  653. gt_poly2 = im_info['mixup'][2]['gt_poly']
  654. is_crowd1 = label_info['is_crowd']
  655. is_crowd2 = im_info['mixup'][2]['is_crowd']
  656. if 0 not in gt_class1 and 0 not in gt_class2:
  657. gt_bbox = np.concatenate((gt_bbox1, gt_bbox2), axis=0)
  658. gt_class = np.concatenate((gt_class1, gt_class2), axis=0)
  659. gt_score = np.concatenate(
  660. (gt_score1 * factor, gt_score2 * (1. - factor)), axis=0)
  661. if 'gt_poly' in label_info:
  662. label_info['gt_poly'] = gt_poly1 + gt_poly2
  663. is_crowd = np.concatenate((is_crowd1, is_crowd2), axis=0)
  664. elif 0 in gt_class1:
  665. gt_bbox = gt_bbox2
  666. gt_class = gt_class2
  667. gt_score = gt_score2 * (1. - factor)
  668. if 'gt_poly' in label_info:
  669. label_info['gt_poly'] = gt_poly2
  670. is_crowd = is_crowd2
  671. else:
  672. gt_bbox = gt_bbox1
  673. gt_class = gt_class1
  674. gt_score = gt_score1 * factor
  675. if 'gt_poly' in label_info:
  676. label_info['gt_poly'] = gt_poly1
  677. is_crowd = is_crowd1
  678. label_info['gt_bbox'] = gt_bbox
  679. label_info['gt_score'] = gt_score
  680. label_info['gt_class'] = gt_class
  681. label_info['is_crowd'] = is_crowd
  682. im_info['image_shape'] = np.array([im.shape[0],
  683. im.shape[1]]).astype('int32')
  684. im_info.pop('mixup')
  685. if label_info is None:
  686. return (im, im_info)
  687. else:
  688. return (im, im_info, label_info)
  689. class RandomExpand(DetTransform):
  690. """随机扩张图像,模型训练时的数据增强操作。
  691. 1. 随机选取扩张比例(扩张比例大于1时才进行扩张)。
  692. 2. 计算扩张后图像大小。
  693. 3. 初始化像素值为输入填充值的图像,并将原图像随机粘贴于该图像上。
  694. 4. 根据原图像粘贴位置换算出扩张后真实标注框的位置坐标。
  695. 5. 根据原图像粘贴位置换算出扩张后真实分割区域的位置坐标。
  696. Args:
  697. ratio (float): 图像扩张的最大比例。默认为4.0。
  698. prob (float): 随机扩张的概率。默认为0.5。
  699. fill_value (list): 扩张图像的初始填充值(0-255)。默认为[123.675, 116.28, 103.53]。
  700. """
  701. def __init__(self, ratio=4., prob=0.5,
  702. fill_value=[123.675, 116.28, 103.53]):
  703. super(RandomExpand, self).__init__()
  704. assert ratio > 1.01, "expand ratio must be larger than 1.01"
  705. self.ratio = ratio
  706. self.prob = prob
  707. assert isinstance(fill_value, Sequence), \
  708. "fill value must be sequence"
  709. if not isinstance(fill_value, tuple):
  710. fill_value = tuple(fill_value)
  711. self.fill_value = fill_value
  712. def __call__(self, im, im_info=None, label_info=None):
  713. """
  714. Args:
  715. im (np.ndarray): 图像np.ndarray数据。
  716. im_info (dict, 可选): 存储与图像相关的信息。
  717. label_info (dict, 可选): 存储与标注框相关的信息。
  718. Returns:
  719. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  720. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  721. 存储与标注框相关信息的字典。
  722. 其中,im_info更新字段为:
  723. - image_shape (np.ndarray): 扩张后的图像高、宽二者组成的np.ndarray,形状为(2,)。
  724. label_info更新字段为:
  725. - gt_bbox (np.ndarray): 随机扩张后真实标注框坐标,形状为(n, 4),
  726. 其中n代表真实标注框的个数。
  727. - gt_class (np.ndarray): 随机扩张后每个真实标注框对应的类别序号,形状为(n, 1),
  728. 其中n代表真实标注框的个数。
  729. Raises:
  730. TypeError: 形参数据类型不满足需求。
  731. """
  732. if im_info is None or label_info is None:
  733. raise TypeError(
  734. 'Cannot do RandomExpand! ' +
  735. 'Becasuse the im_info and label_info can not be None!')
  736. if 'gt_bbox' not in label_info or \
  737. 'gt_class' not in label_info:
  738. raise TypeError('Cannot do RandomExpand! ' + \
  739. 'Becasuse gt_bbox/gt_class is not in label_info!')
  740. if np.random.uniform(0., 1.) > self.prob:
  741. return (im, im_info, label_info)
  742. if 'gt_class' in label_info and 0 in label_info['gt_class']:
  743. return (im, im_info, label_info)
  744. image_shape = im_info['image_shape']
  745. height = int(image_shape[0])
  746. width = int(image_shape[1])
  747. expand_ratio = np.random.uniform(1., self.ratio)
  748. h = int(height * expand_ratio)
  749. w = int(width * expand_ratio)
  750. if not h > height or not w > width:
  751. return (im, im_info, label_info)
  752. y = np.random.randint(0, h - height)
  753. x = np.random.randint(0, w - width)
  754. canvas = np.ones((h, w, 3), dtype=np.float32)
  755. canvas *= np.array(self.fill_value, dtype=np.float32)
  756. canvas[y:y + height, x:x + width, :] = im
  757. im_info['image_shape'] = np.array([h, w]).astype('int32')
  758. if 'gt_bbox' in label_info and len(label_info['gt_bbox']) > 0:
  759. label_info['gt_bbox'] += np.array([x, y] * 2, dtype=np.float32)
  760. if 'gt_poly' in label_info and len(label_info['gt_poly']) > 0:
  761. label_info['gt_poly'] = expand_segms(label_info['gt_poly'], x, y,
  762. height, width, expand_ratio)
  763. return (canvas, im_info, label_info)
  764. class RandomCrop(DetTransform):
  765. """随机裁剪图像。
  766. 1. 若allow_no_crop为True,则在thresholds加入’no_crop’。
  767. 2. 随机打乱thresholds。
  768. 3. 遍历thresholds中各元素:
  769. (1) 如果当前thresh为’no_crop’,则返回原始图像和标注信息。
  770. (2) 随机取出aspect_ratio和scaling中的值并由此计算出候选裁剪区域的高、宽、起始点。
  771. (3) 计算真实标注框与候选裁剪区域IoU,若全部真实标注框的IoU都小于thresh,则继续第3步。
  772. (4) 如果cover_all_box为True且存在真实标注框的IoU小于thresh,则继续第3步。
  773. (5) 筛选出位于候选裁剪区域内的真实标注框,若有效框的个数为0,则继续第3步,否则进行第4步。
  774. 4. 换算有效真值标注框相对候选裁剪区域的位置坐标。
  775. 5. 换算有效分割区域相对候选裁剪区域的位置坐标。
  776. Args:
  777. aspect_ratio (list): 裁剪后短边缩放比例的取值范围,以[min, max]形式表示。默认值为[.5, 2.]。
  778. thresholds (list): 判断裁剪候选区域是否有效所需的IoU阈值取值列表。默认值为[.0, .1, .3, .5, .7, .9]。
  779. scaling (list): 裁剪面积相对原面积的取值范围,以[min, max]形式表示。默认值为[.3, 1.]。
  780. num_attempts (int): 在放弃寻找有效裁剪区域前尝试的次数。默认值为50。
  781. allow_no_crop (bool): 是否允许未进行裁剪。默认值为True。
  782. cover_all_box (bool): 是否要求所有的真实标注框都必须在裁剪区域内。默认值为False。
  783. """
  784. def __init__(self,
  785. aspect_ratio=[.5, 2.],
  786. thresholds=[.0, .1, .3, .5, .7, .9],
  787. scaling=[.3, 1.],
  788. num_attempts=50,
  789. allow_no_crop=True,
  790. cover_all_box=False):
  791. self.aspect_ratio = aspect_ratio
  792. self.thresholds = thresholds
  793. self.scaling = scaling
  794. self.num_attempts = num_attempts
  795. self.allow_no_crop = allow_no_crop
  796. self.cover_all_box = cover_all_box
  797. def __call__(self, im, im_info=None, label_info=None):
  798. """
  799. Args:
  800. im (np.ndarray): 图像np.ndarray数据。
  801. im_info (dict, 可选): 存储与图像相关的信息。
  802. label_info (dict, 可选): 存储与标注框相关的信息。
  803. Returns:
  804. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  805. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  806. 存储与标注框相关信息的字典。
  807. 其中,im_info更新字段为:
  808. - image_shape (np.ndarray): 扩裁剪的图像高、宽二者组成的np.ndarray,形状为(2,)。
  809. label_info更新字段为:
  810. - gt_bbox (np.ndarray): 随机裁剪后真实标注框坐标,形状为(n, 4),
  811. 其中n代表真实标注框的个数。
  812. - gt_class (np.ndarray): 随机裁剪后每个真实标注框对应的类别序号,形状为(n, 1),
  813. 其中n代表真实标注框的个数。
  814. - gt_score (np.ndarray): 随机裁剪后每个真实标注框对应的混合得分,形状为(n, 1),
  815. 其中n代表真实标注框的个数。
  816. Raises:
  817. TypeError: 形参数据类型不满足需求。
  818. """
  819. if im_info is None or label_info is None:
  820. raise TypeError(
  821. 'Cannot do RandomCrop! ' +
  822. 'Becasuse the im_info and label_info can not be None!')
  823. if 'gt_bbox' not in label_info or \
  824. 'gt_class' not in label_info:
  825. raise TypeError('Cannot do RandomCrop! ' + \
  826. 'Becasuse gt_bbox/gt_class is not in label_info!')
  827. if len(label_info['gt_bbox']) == 0:
  828. return (im, im_info, label_info)
  829. if 'gt_class' in label_info and 0 in label_info['gt_class']:
  830. return (im, im_info, label_info)
  831. image_shape = im_info['image_shape']
  832. w = image_shape[1]
  833. h = image_shape[0]
  834. gt_bbox = label_info['gt_bbox']
  835. thresholds = list(self.thresholds)
  836. if self.allow_no_crop:
  837. thresholds.append('no_crop')
  838. np.random.shuffle(thresholds)
  839. for thresh in thresholds:
  840. if thresh == 'no_crop':
  841. return (im, im_info, label_info)
  842. found = False
  843. for i in range(self.num_attempts):
  844. scale = np.random.uniform(*self.scaling)
  845. min_ar, max_ar = self.aspect_ratio
  846. aspect_ratio = np.random.uniform(
  847. max(min_ar, scale**2), min(max_ar, scale**-2))
  848. crop_h = int(h * scale / np.sqrt(aspect_ratio))
  849. crop_w = int(w * scale * np.sqrt(aspect_ratio))
  850. crop_y = np.random.randint(0, h - crop_h)
  851. crop_x = np.random.randint(0, w - crop_w)
  852. crop_box = [crop_x, crop_y, crop_x + crop_w, crop_y + crop_h]
  853. iou = iou_matrix(
  854. gt_bbox, np.array(
  855. [crop_box], dtype=np.float32))
  856. if iou.max() < thresh:
  857. continue
  858. if self.cover_all_box and iou.min() < thresh:
  859. continue
  860. cropped_box, valid_ids = crop_box_with_center_constraint(
  861. gt_bbox, np.array(
  862. crop_box, dtype=np.float32))
  863. if valid_ids.size > 0:
  864. found = True
  865. break
  866. if found:
  867. if 'gt_poly' in label_info and len(label_info['gt_poly']) > 0:
  868. crop_polys = crop_segms(
  869. label_info['gt_poly'],
  870. valid_ids,
  871. np.array(
  872. crop_box, dtype=np.int64),
  873. h,
  874. w)
  875. if [] in crop_polys:
  876. delete_id = list()
  877. valid_polys = list()
  878. for id, crop_poly in enumerate(crop_polys):
  879. if crop_poly == []:
  880. delete_id.append(id)
  881. else:
  882. valid_polys.append(crop_poly)
  883. valid_ids = np.delete(valid_ids, delete_id)
  884. if len(valid_polys) == 0:
  885. return (im, im_info, label_info)
  886. label_info['gt_poly'] = valid_polys
  887. else:
  888. label_info['gt_poly'] = crop_polys
  889. im = crop_image(im, crop_box)
  890. label_info['gt_bbox'] = np.take(cropped_box, valid_ids, axis=0)
  891. label_info['gt_class'] = np.take(
  892. label_info['gt_class'], valid_ids, axis=0)
  893. im_info['image_shape'] = np.array(
  894. [crop_box[3] - crop_box[1],
  895. crop_box[2] - crop_box[0]]).astype('int32')
  896. if 'gt_score' in label_info:
  897. label_info['gt_score'] = np.take(
  898. label_info['gt_score'], valid_ids, axis=0)
  899. if 'is_crowd' in label_info:
  900. label_info['is_crowd'] = np.take(
  901. label_info['is_crowd'], valid_ids, axis=0)
  902. return (im, im_info, label_info)
  903. return (im, im_info, label_info)
  904. class ArrangeFasterRCNN(DetTransform):
  905. """获取FasterRCNN模型训练/验证/预测所需信息。
  906. Args:
  907. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  908. Raises:
  909. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  910. """
  911. def __init__(self, mode=None):
  912. if mode not in ['train', 'eval', 'test', 'quant']:
  913. raise ValueError(
  914. "mode must be in ['train', 'eval', 'test', 'quant']!")
  915. self.mode = mode
  916. def __call__(self, im, im_info=None, label_info=None):
  917. """
  918. Args:
  919. im (np.ndarray): 图像np.ndarray数据。
  920. im_info (dict, 可选): 存储与图像相关的信息。
  921. label_info (dict, 可选): 存储与标注框相关的信息。
  922. Returns:
  923. tuple: 当mode为'train'时,返回(im, im_resize_info, gt_bbox, gt_class, is_crowd),分别对应
  924. 图像np.ndarray数据、图像相当对于原图的resize信息、真实标注框、真实标注框对应的类别、真实标注框内是否是一组对象;
  925. 当mode为'eval'时,返回(im, im_resize_info, im_id, im_shape, gt_bbox, gt_class, is_difficult),
  926. 分别对应图像np.ndarray数据、图像相当对于原图的resize信息、图像id、图像大小信息、真实标注框、真实标注框对应的类别、
  927. 真实标注框是否为难识别对象;当mode为'test'或'quant'时,返回(im, im_resize_info, im_shape),分别对应图像np.ndarray数据、
  928. 图像相当对于原图的resize信息、图像大小信息。
  929. Raises:
  930. TypeError: 形参数据类型不满足需求。
  931. ValueError: 数据长度不匹配。
  932. """
  933. im = permute(im, False)
  934. if self.mode == 'train':
  935. if im_info is None or label_info is None:
  936. raise TypeError(
  937. 'Cannot do ArrangeFasterRCNN! ' +
  938. 'Becasuse the im_info and label_info can not be None!')
  939. if len(label_info['gt_bbox']) != len(label_info['gt_class']):
  940. raise ValueError("gt num mismatch: bbox and class.")
  941. im_resize_info = im_info['im_resize_info']
  942. gt_bbox = label_info['gt_bbox']
  943. gt_class = label_info['gt_class']
  944. is_crowd = label_info['is_crowd']
  945. outputs = (im, im_resize_info, gt_bbox, gt_class, is_crowd)
  946. elif self.mode == 'eval':
  947. if im_info is None or label_info is None:
  948. raise TypeError(
  949. 'Cannot do ArrangeFasterRCNN! ' +
  950. 'Becasuse the im_info and label_info can not be None!')
  951. im_resize_info = im_info['im_resize_info']
  952. im_id = im_info['im_id']
  953. im_shape = np.array(
  954. (im_info['image_shape'][0], im_info['image_shape'][1], 1),
  955. dtype=np.float32)
  956. gt_bbox = label_info['gt_bbox']
  957. gt_class = label_info['gt_class']
  958. is_difficult = label_info['difficult']
  959. outputs = (im, im_resize_info, im_id, im_shape, gt_bbox, gt_class,
  960. is_difficult)
  961. else:
  962. if im_info is None:
  963. raise TypeError('Cannot do ArrangeFasterRCNN! ' +
  964. 'Becasuse the im_info can not be None!')
  965. im_resize_info = im_info['im_resize_info']
  966. im_shape = np.array(
  967. (im_info['image_shape'][0], im_info['image_shape'][1], 1),
  968. dtype=np.float32)
  969. outputs = (im, im_resize_info, im_shape)
  970. return outputs
  971. class ArrangeMaskRCNN(DetTransform):
  972. """获取MaskRCNN模型训练/验证/预测所需信息。
  973. Args:
  974. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  975. Raises:
  976. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  977. """
  978. def __init__(self, mode=None):
  979. if mode not in ['train', 'eval', 'test', 'quant']:
  980. raise ValueError(
  981. "mode must be in ['train', 'eval', 'test', 'quant']!")
  982. self.mode = mode
  983. def __call__(self, im, im_info=None, label_info=None):
  984. """
  985. Args:
  986. im (np.ndarray): 图像np.ndarray数据。
  987. im_info (dict, 可选): 存储与图像相关的信息。
  988. label_info (dict, 可选): 存储与标注框相关的信息。
  989. Returns:
  990. tuple: 当mode为'train'时,返回(im, im_resize_info, gt_bbox, gt_class, is_crowd, gt_masks),分别对应
  991. 图像np.ndarray数据、图像相当对于原图的resize信息、真实标注框、真实标注框对应的类别、真实标注框内是否是一组对象、
  992. 真实分割区域;当mode为'eval'时,返回(im, im_resize_info, im_id, im_shape),分别对应图像np.ndarray数据、
  993. 图像相当对于原图的resize信息、图像id、图像大小信息;当mode为'test'或'quant'时,返回(im, im_resize_info, im_shape),
  994. 分别对应图像np.ndarray数据、图像相当对于原图的resize信息、图像大小信息。
  995. Raises:
  996. TypeError: 形参数据类型不满足需求。
  997. ValueError: 数据长度不匹配。
  998. """
  999. im = permute(im, False)
  1000. if self.mode == 'train':
  1001. if im_info is None or label_info is None:
  1002. raise TypeError(
  1003. 'Cannot do ArrangeTrainMaskRCNN! ' +
  1004. 'Becasuse the im_info and label_info can not be None!')
  1005. if len(label_info['gt_bbox']) != len(label_info['gt_class']):
  1006. raise ValueError("gt num mismatch: bbox and class.")
  1007. im_resize_info = im_info['im_resize_info']
  1008. gt_bbox = label_info['gt_bbox']
  1009. gt_class = label_info['gt_class']
  1010. is_crowd = label_info['is_crowd']
  1011. assert 'gt_poly' in label_info
  1012. segms = label_info['gt_poly']
  1013. if len(segms) != 0:
  1014. assert len(segms) == is_crowd.shape[0]
  1015. gt_masks = []
  1016. valid = True
  1017. for i in range(len(segms)):
  1018. segm = segms[i]
  1019. gt_segm = []
  1020. if is_crowd[i]:
  1021. gt_segm.append([[0, 0]])
  1022. else:
  1023. for poly in segm:
  1024. if len(poly) == 0:
  1025. valid = False
  1026. break
  1027. gt_segm.append(np.array(poly).reshape(-1, 2))
  1028. if (not valid) or len(gt_segm) == 0:
  1029. break
  1030. gt_masks.append(gt_segm)
  1031. outputs = (im, im_resize_info, gt_bbox, gt_class, is_crowd,
  1032. gt_masks)
  1033. else:
  1034. if im_info is None:
  1035. raise TypeError('Cannot do ArrangeMaskRCNN! ' +
  1036. 'Becasuse the im_info can not be None!')
  1037. im_resize_info = im_info['im_resize_info']
  1038. im_shape = np.array(
  1039. (im_info['image_shape'][0], im_info['image_shape'][1], 1),
  1040. dtype=np.float32)
  1041. if self.mode == 'eval':
  1042. im_id = im_info['im_id']
  1043. outputs = (im, im_resize_info, im_id, im_shape)
  1044. else:
  1045. outputs = (im, im_resize_info, im_shape)
  1046. return outputs
  1047. class ArrangeYOLOv3(DetTransform):
  1048. """获取YOLOv3模型训练/验证/预测所需信息。
  1049. Args:
  1050. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  1051. Raises:
  1052. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  1053. """
  1054. def __init__(self, mode=None):
  1055. if mode not in ['train', 'eval', 'test', 'quant']:
  1056. raise ValueError(
  1057. "mode must be in ['train', 'eval', 'test', 'quant']!")
  1058. self.mode = mode
  1059. def __call__(self, im, im_info=None, label_info=None):
  1060. """
  1061. Args:
  1062. im (np.ndarray): 图像np.ndarray数据。
  1063. im_info (dict, 可选): 存储与图像相关的信息。
  1064. label_info (dict, 可选): 存储与标注框相关的信息。
  1065. Returns:
  1066. tuple: 当mode为'train'时,返回(im, gt_bbox, gt_class, gt_score, im_shape),分别对应
  1067. 图像np.ndarray数据、真实标注框、真实标注框对应的类别、真实标注框混合得分、图像大小信息;
  1068. 当mode为'eval'时,返回(im, im_shape, im_id, gt_bbox, gt_class, difficult),
  1069. 分别对应图像np.ndarray数据、图像大小信息、图像id、真实标注框、真实标注框对应的类别、
  1070. 真实标注框是否为难识别对象;当mode为'test'或'quant'时,返回(im, im_shape),
  1071. 分别对应图像np.ndarray数据、图像大小信息。
  1072. Raises:
  1073. TypeError: 形参数据类型不满足需求。
  1074. ValueError: 数据长度不匹配。
  1075. """
  1076. im = permute(im, False)
  1077. if self.mode == 'train':
  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. if len(label_info['gt_bbox']) != len(label_info['gt_score']):
  1086. raise ValueError("gt num mismatch: bbox and score.")
  1087. gt_bbox = np.zeros((50, 4), dtype=im.dtype)
  1088. gt_class = np.zeros((50, ), dtype=np.int32)
  1089. gt_score = np.zeros((50, ), dtype=im.dtype)
  1090. gt_num = min(50, len(label_info['gt_bbox']))
  1091. if gt_num > 0:
  1092. label_info['gt_class'][:gt_num, 0] = label_info[
  1093. 'gt_class'][:gt_num, 0] - 1
  1094. if -1 not in label_info['gt_class']:
  1095. gt_bbox[:gt_num, :] = label_info['gt_bbox'][:gt_num, :]
  1096. gt_class[:gt_num] = label_info['gt_class'][:gt_num, 0]
  1097. gt_score[:gt_num] = label_info['gt_score'][:gt_num, 0]
  1098. # parse [x1, y1, x2, y2] to [x, y, w, h]
  1099. gt_bbox[:, 2:4] = gt_bbox[:, 2:4] - gt_bbox[:, :2]
  1100. gt_bbox[:, :2] = gt_bbox[:, :2] + gt_bbox[:, 2:4] / 2.
  1101. outputs = (im, gt_bbox, gt_class, gt_score, im_shape)
  1102. elif self.mode == 'eval':
  1103. if im_info is None or label_info is None:
  1104. raise TypeError(
  1105. 'Cannot do ArrangeYolov3! ' +
  1106. 'Becasuse the im_info and label_info can not be None!')
  1107. im_shape = im_info['image_shape']
  1108. if len(label_info['gt_bbox']) != len(label_info['gt_class']):
  1109. raise ValueError("gt num mismatch: bbox and class.")
  1110. im_id = im_info['im_id']
  1111. gt_bbox = np.zeros((50, 4), dtype=im.dtype)
  1112. gt_class = np.zeros((50, ), dtype=np.int32)
  1113. difficult = np.zeros((50, ), dtype=np.int32)
  1114. gt_num = min(50, len(label_info['gt_bbox']))
  1115. if gt_num > 0:
  1116. label_info['gt_class'][:gt_num, 0] = label_info[
  1117. 'gt_class'][:gt_num, 0] - 1
  1118. gt_bbox[:gt_num, :] = label_info['gt_bbox'][:gt_num, :]
  1119. gt_class[:gt_num] = label_info['gt_class'][:gt_num, 0]
  1120. difficult[:gt_num] = label_info['difficult'][:gt_num, 0]
  1121. outputs = (im, im_shape, im_id, gt_bbox, gt_class, difficult)
  1122. else:
  1123. if im_info is None:
  1124. raise TypeError('Cannot do ArrangeYolov3! ' +
  1125. 'Becasuse the im_info can not be None!')
  1126. im_shape = im_info['image_shape']
  1127. outputs = (im, im_shape)
  1128. return outputs
  1129. class ComposedRCNNTransforms(Compose):
  1130. """ RCNN模型(faster-rcnn/mask-rcnn)图像处理流程,具体如下,
  1131. 训练阶段:
  1132. 1. 随机以0.5的概率将图像水平翻转
  1133. 2. 图像归一化
  1134. 3. 图像按比例Resize,scale计算方式如下
  1135. scale = min_max_size[0] / short_size_of_image
  1136. if max_size_of_image * scale > min_max_size[1]:
  1137. scale = min_max_size[1] / max_size_of_image
  1138. 4. 将3步骤的长宽进行padding,使得长宽为32的倍数
  1139. 验证阶段:
  1140. 1. 图像归一化
  1141. 2. 图像按比例Resize,scale计算方式同上训练阶段
  1142. 3. 将2步骤的长宽进行padding,使得长宽为32的倍数
  1143. Args:
  1144. mode(str): 图像处理流程所处阶段,训练/验证/预测,分别对应'train', 'eval', 'test'
  1145. min_max_size(list): 图像在缩放时,最小边和最大边的约束条件
  1146. mean(list): 图像均值
  1147. std(list): 图像方差
  1148. random_horizontal_flip(bool): 是否以0.5的概率使用随机水平翻转增强,该仅在mode为`train`时生效,默认为True
  1149. """
  1150. def __init__(self,
  1151. mode,
  1152. min_max_size=[800, 1333],
  1153. mean=[0.485, 0.456, 0.406],
  1154. std=[0.229, 0.224, 0.225],
  1155. random_horizontal_flip=True):
  1156. if mode == 'train':
  1157. # 训练时的transforms,包含数据增强
  1158. transforms = [
  1159. Normalize(
  1160. mean=mean, std=std), ResizeByShort(
  1161. short_size=min_max_size[0], max_size=min_max_size[1]),
  1162. Padding(coarsest_stride=32)
  1163. ]
  1164. if random_horizontal_flip:
  1165. transforms.insert(0, RandomHorizontalFlip())
  1166. else:
  1167. # 验证/预测时的transforms
  1168. transforms = [
  1169. Normalize(
  1170. mean=mean, std=std), ResizeByShort(
  1171. short_size=min_max_size[0], max_size=min_max_size[1]),
  1172. Padding(coarsest_stride=32)
  1173. ]
  1174. super(ComposedRCNNTransforms, self).__init__(transforms)
  1175. class ComposedYOLOv3Transforms(Compose):
  1176. """YOLOv3模型的图像预处理流程,具体如下,
  1177. 训练阶段:
  1178. 1. 在前mixup_epoch轮迭代中,使用MixupImage策略,见https://paddlex.readthedocs.io/zh_CN/latest/apis/transforms/det_transforms.html#mixupimage
  1179. 2. 对图像进行随机扰动,包括亮度,对比度,饱和度和色调
  1180. 3. 随机扩充图像,见https://paddlex.readthedocs.io/zh_CN/latest/apis/transforms/det_transforms.html#randomexpand
  1181. 4. 随机裁剪图像
  1182. 5. 将4步骤的输出图像Resize成shape参数的大小
  1183. 6. 随机0.5的概率水平翻转图像
  1184. 7. 图像归一化
  1185. 验证/预测阶段:
  1186. 1. 将图像Resize成shape参数大小
  1187. 2. 图像归一化
  1188. Args:
  1189. mode(str): 图像处理流程所处阶段,训练/验证/预测,分别对应'train', 'eval', 'test'
  1190. shape(list): 输入模型中图像的大小,输入模型的图像会被Resize成此大小
  1191. mixup_epoch(int): 模型训练过程中,前mixup_epoch会使用mixup策略, 若设为-1,则表示不使用该策略
  1192. mean(list): 图像均值
  1193. std(list): 图像方差
  1194. random_distort(bool): 数据增强方式,参数仅在mode为`train`时生效,表示是否在训练过程中随机扰动图像,默认为True
  1195. random_expand(bool): 数据增强方式,参数仅在mode为`train`时生效,表示是否在训练过程中随机扩张图像,默认为True
  1196. random_crop(bool): 数据增强方式,参数仅在mode为`train`时生效,表示是否在训练过程中随机裁剪图像,默认为True
  1197. random_horizontal_flip(bool): 数据增强方式,参数仅在mode为`train`时生效,表示是否在训练过程中随机水平翻转图像,默认为True
  1198. """
  1199. def __init__(self,
  1200. mode,
  1201. shape=[608, 608],
  1202. mixup_epoch=250,
  1203. mean=[0.485, 0.456, 0.406],
  1204. std=[0.229, 0.224, 0.225],
  1205. random_distort=True,
  1206. random_expand=True,
  1207. random_crop=True,
  1208. random_horizontal_flip=True):
  1209. width = shape
  1210. if isinstance(shape, list):
  1211. if shape[0] != shape[1]:
  1212. raise Exception(
  1213. "In YOLOv3 model, width and height should be equal")
  1214. width = shape[0]
  1215. if width % 32 != 0:
  1216. raise Exception(
  1217. "In YOLOv3 model, width and height should be multiple of 32, e.g 224、256、320...."
  1218. )
  1219. if mode == 'train':
  1220. # 训练时的transforms,包含数据增强
  1221. transforms = [
  1222. MixupImage(mixup_epoch=mixup_epoch), Resize(
  1223. target_size=width, interp='RANDOM'), Normalize(
  1224. mean=mean, std=std)
  1225. ]
  1226. if random_horizontal_flip:
  1227. transforms.insert(1, RandomHorizontalFlip())
  1228. if random_crop:
  1229. transforms.insert(1, RandomCrop())
  1230. if random_expand:
  1231. transforms.insert(1, RandomExpand())
  1232. if random_distort:
  1233. transforms.insert(1, RandomDistort())
  1234. else:
  1235. # 验证/预测时的transforms
  1236. transforms = [
  1237. Resize(
  1238. target_size=width, interp='CUBIC'), Normalize(
  1239. mean=mean, std=std)
  1240. ]
  1241. super(ComposedYOLOv3Transforms, self).__init__(transforms)