det_transforms.py 64 KB

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