det_transforms.py 62 KB

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