det_transforms.py 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  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 .imgaug_support import execute_imgaug
  23. from .ops import *
  24. from .box_utils import *
  25. import paddlex.utils.logging as logging
  26. class DetTransform:
  27. """检测数据处理基类
  28. """
  29. def __init__(self):
  30. pass
  31. class Compose(DetTransform):
  32. """根据数据预处理/增强列表对输入数据进行操作。
  33. 所有操作的输入图像流形状均是[H, W, C],其中H为图像高,W为图像宽,C为图像通道数。
  34. Args:
  35. transforms (list): 数据预处理/增强列表。
  36. Raises:
  37. TypeError: 形参数据类型不满足需求。
  38. ValueError: 数据长度不匹配。
  39. """
  40. def __init__(self, transforms):
  41. if not isinstance(transforms, list):
  42. raise TypeError('The transforms must be a list!')
  43. if len(transforms) < 1:
  44. raise ValueError('The length of transforms ' + \
  45. 'must be equal or larger than 1!')
  46. self.transforms = transforms
  47. self.batch_transforms = None
  48. self.use_mixup = False
  49. self.data_type = np.uint8
  50. self.to_rgb = True
  51. for t in self.transforms:
  52. if type(t).__name__ == 'MixupImage':
  53. self.use_mixup = True
  54. # 检查transforms里面的操作,目前支持PaddleX定义的或者是imgaug操作
  55. for op in self.transforms:
  56. if not isinstance(op, DetTransform):
  57. import imgaug.augmenters as iaa
  58. if not isinstance(op, iaa.Augmenter):
  59. raise Exception(
  60. "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/"
  61. )
  62. def __call__(self, im, im_info=None, label_info=None):
  63. """
  64. Args:
  65. im (str/np.ndarray): 图像路径/图像np.ndarray数据。
  66. im_info (dict): 存储与图像相关的信息,dict中的字段如下:
  67. - im_id (np.ndarray): 图像序列号,形状为(1,)。
  68. - image_shape (np.ndarray): 图像原始大小,形状为(2,),
  69. image_shape[0]为高,image_shape[1]为宽。
  70. - mixup (list): list为[im, im_info, label_info],分别对应
  71. 与当前图像进行mixup的图像np.ndarray数据、图像相关信息、标注框相关信息;
  72. 注意,当前epoch若无需进行mixup,则无该字段。
  73. label_info (dict): 存储与标注框相关的信息,dict中的字段如下:
  74. - gt_bbox (np.ndarray): 真实标注框坐标[x1, y1, x2, y2],形状为(n, 4),
  75. 其中n代表真实标注框的个数。
  76. - gt_class (np.ndarray): 每个真实标注框对应的类别序号,形状为(n, 1),
  77. 其中n代表真实标注框的个数。
  78. - gt_score (np.ndarray): 每个真实标注框对应的混合得分,形状为(n, 1),
  79. 其中n代表真实标注框的个数。
  80. - gt_poly (list): 每个真实标注框内的多边形分割区域,每个分割区域由点的x、y坐标组成,
  81. 长度为n,其中n代表真实标注框的个数。
  82. - is_crowd (np.ndarray): 每个真实标注框中是否是一组对象,形状为(n, 1),
  83. 其中n代表真实标注框的个数。
  84. - difficult (np.ndarray): 每个真实标注框中的对象是否为难识别对象,形状为(n, 1),
  85. 其中n代表真实标注框的个数。
  86. Returns:
  87. tuple: 根据网络所需字段所组成的tuple;
  88. 字段由transforms中的最后一个数据预处理操作决定。
  89. """
  90. def decode_image(im_file, im_info, label_info, input_channel=3):
  91. if im_info is None:
  92. im_info = dict()
  93. if isinstance(im_file, np.ndarray):
  94. if len(im_file.shape) != 3:
  95. raise Exception(
  96. "im should be 3-dimensions, but now is {}-dimensions".
  97. format(len(im_file.shape)))
  98. im = im_file
  99. else:
  100. try:
  101. if input_channel == 3:
  102. im = cv2.imread(im_file, cv2.IMREAD_ANYDEPTH |
  103. cv2.IMREAD_ANYCOLOR)
  104. else:
  105. im = cv2.imread(im_file, cv2.IMREAD_UNCHANGED)
  106. if im.ndim < 3:
  107. im = np.expand_dims(im, axis=-1)
  108. except:
  109. raise TypeError('Can\'t read The image file {}!'.format(
  110. im_file))
  111. self.data_type = im.dtype
  112. im = im.astype('float32')
  113. if input_channel == 3 and self.to_rgb:
  114. im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
  115. # make default im_info with [h, w, 1]
  116. im_info['im_resize_info'] = np.array(
  117. [im.shape[0], im.shape[1], 1.], dtype=np.float32)
  118. im_info['image_shape'] = np.array([im.shape[0],
  119. im.shape[1]]).astype('int32')
  120. if not self.use_mixup:
  121. if 'mixup' in im_info:
  122. del im_info['mixup']
  123. # decode mixup image
  124. if 'mixup' in im_info:
  125. im_info['mixup'] = \
  126. decode_image(im_info['mixup'][0],
  127. im_info['mixup'][1],
  128. im_info['mixup'][2],
  129. input_channel)
  130. if label_info is None:
  131. return (im, im_info)
  132. else:
  133. return (im, im_info, label_info)
  134. input_channel = getattr(self, 'input_channel', 3)
  135. outputs = decode_image(im, im_info, label_info, input_channel)
  136. im = outputs[0]
  137. im_info = outputs[1]
  138. if len(outputs) == 3:
  139. label_info = outputs[2]
  140. for op in self.transforms:
  141. if im is None:
  142. return None
  143. if isinstance(op, DetTransform):
  144. if op.__class__.__name__ == 'RandomDistort':
  145. op.to_rgb = self.to_rgb
  146. op.data_type = self.data_type
  147. outputs = op(im, im_info, label_info)
  148. im = outputs[0]
  149. else:
  150. import imgaug.augmenters as iaa
  151. if im.shape[-1] != 3:
  152. raise Exception(
  153. "Only the 3-channel RGB image is supported in the imgaug operator, but recieved image channel is {}".
  154. format(im.shape[-1]))
  155. if isinstance(op, iaa.Augmenter):
  156. im = execute_imgaug(op, im)
  157. if label_info is not None:
  158. outputs = (im, im_info, label_info)
  159. else:
  160. outputs = (im, im_info)
  161. return outputs
  162. def add_augmenters(self, augmenters):
  163. if not isinstance(augmenters, list):
  164. raise Exception(
  165. "augmenters should be list type in func add_augmenters()")
  166. transform_names = [type(x).__name__ for x in self.transforms]
  167. for aug in augmenters:
  168. if type(aug).__name__ in transform_names:
  169. logging.error(
  170. "{} is already in ComposedTransforms, need to remove it from add_augmenters().".
  171. format(type(aug).__name__))
  172. self.transforms = augmenters + self.transforms
  173. class ResizeByShort(DetTransform):
  174. """根据图像的短边调整图像大小(resize)。
  175. 1. 获取图像的长边和短边长度。
  176. 2. 根据短边与short_size的比例,计算长边的目标长度,
  177. 此时高、宽的resize比例为short_size/原图短边长度。
  178. 若short_size为数组,则随机从该数组中挑选一个数值
  179. 作为short_size。
  180. 3. 如果max_size>0,调整resize比例:
  181. 如果长边的目标长度>max_size,则高、宽的resize比例为max_size/原图长边长度。
  182. 4. 根据调整大小的比例对图像进行resize。
  183. Args:
  184. short_size (int|list): 短边目标长度。默认为800。
  185. max_size (int): 长边目标长度的最大限制。默认为1333。
  186. Raises:
  187. TypeError: 形参数据类型不满足需求。
  188. """
  189. def __init__(self, short_size=800, max_size=1333):
  190. self.max_size = int(max_size)
  191. if not (isinstance(short_size, int) or isinstance(short_size, list)):
  192. raise TypeError(
  193. "Type of short_size is invalid. Must be Integer or List, now is {}".
  194. format(type(short_size)))
  195. self.short_size = short_size
  196. if not (isinstance(self.max_size, int)):
  197. raise TypeError("max_size: input type is invalid.")
  198. def __call__(self, im, im_info=None, label_info=None):
  199. """
  200. Args:
  201. im (numnp.ndarraypy): 图像np.ndarray数据。
  202. im_info (dict, 可选): 存储与图像相关的信息。
  203. label_info (dict, 可选): 存储与标注框相关的信息。
  204. Returns:
  205. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  206. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  207. 存储与标注框相关信息的字典。
  208. 其中,im_info更新字段为:
  209. - im_resize_info (np.ndarray): resize后的图像高、resize后的图像宽、resize后的图像相对原始图的缩放比例
  210. 三者组成的np.ndarray,形状为(3,)。
  211. Raises:
  212. TypeError: 形参数据类型不满足需求。
  213. ValueError: 数据长度不匹配。
  214. """
  215. if im_info is None:
  216. im_info = dict()
  217. if not isinstance(im, np.ndarray):
  218. raise TypeError("ResizeByShort: image type is not numpy.")
  219. if len(im.shape) != 3:
  220. raise ValueError('ResizeByShort: image is not 3-dimensional.')
  221. im_short_size = min(im.shape[0], im.shape[1])
  222. im_long_size = max(im.shape[0], im.shape[1])
  223. if isinstance(self.short_size, list):
  224. # Case for multi-scale training
  225. selected_size = random.choice(self.short_size)
  226. else:
  227. selected_size = self.short_size
  228. scale = float(selected_size) / im_short_size
  229. if self.max_size > 0 and np.round(scale *
  230. im_long_size) > self.max_size:
  231. scale = float(self.max_size) / float(im_long_size)
  232. resized_width = int(round(im.shape[1] * scale))
  233. resized_height = int(round(im.shape[0] * scale))
  234. im_resize_info = [resized_height, resized_width, scale]
  235. im = cv2.resize(
  236. im, (resized_width, resized_height),
  237. interpolation=cv2.INTER_LINEAR)
  238. if im.ndim < 3:
  239. im = np.expand_dims(im, axis=-1)
  240. im_info['im_resize_info'] = np.array(im_resize_info).astype(np.float32)
  241. if label_info is None:
  242. return (im, im_info)
  243. else:
  244. return (im, im_info, label_info)
  245. class Padding(DetTransform):
  246. """1.将图像的长和宽padding至coarsest_stride的倍数。如输入图像为[300, 640],
  247. `coarest_stride`为32,则由于300不为32的倍数,因此在图像最右和最下使用0值
  248. 进行padding,最终输出图像为[320, 640]。
  249. 2.或者,将图像的长和宽padding到target_size指定的shape,如输入的图像为[300,640],
  250. a. `target_size` = 960,在图像最右和最下使用0值进行padding,最终输出
  251. 图像为[960, 960]。
  252. b. `target_size` = [640, 960],在图像最右和最下使用0值进行padding,最终
  253. 输出图像为[640, 960]。
  254. 1. 如果coarsest_stride为1,target_size为None则直接返回。
  255. 2. 获取图像的高H、宽W。
  256. 3. 计算填充后图像的高H_new、宽W_new。
  257. 4. 构建大小为(H_new, W_new, 3)像素值为0的np.ndarray,
  258. 并将原图的np.ndarray粘贴于左上角。
  259. Args:
  260. coarsest_stride (int): 填充后的图像长、宽为该参数的倍数,默认为1。
  261. target_size (int|list|tuple): 填充后的图像长、宽,默认为None,coarset_stride优先级更高。
  262. Raises:
  263. TypeError: 形参`target_size`数据类型不满足需求。
  264. ValueError: 形参`target_size`为(list|tuple)时,长度不满足需求。
  265. """
  266. def __init__(self, coarsest_stride=1, target_size=None):
  267. self.coarsest_stride = coarsest_stride
  268. if target_size is not None:
  269. if not isinstance(target_size, int):
  270. if not isinstance(target_size, tuple) and not isinstance(
  271. target_size, list):
  272. raise TypeError(
  273. "Padding: Type of target_size must in (int|list|tuple)."
  274. )
  275. elif len(target_size) != 2:
  276. raise ValueError(
  277. "Padding: Length of target_size must equal 2.")
  278. self.target_size = target_size
  279. def __call__(self, im, im_info=None, label_info=None):
  280. """
  281. Args:
  282. im (numnp.ndarraypy): 图像np.ndarray数据。
  283. im_info (dict, 可选): 存储与图像相关的信息。
  284. label_info (dict, 可选): 存储与标注框相关的信息。
  285. Returns:
  286. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  287. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  288. 存储与标注框相关信息的字典。
  289. Raises:
  290. TypeError: 形参数据类型不满足需求。
  291. ValueError: 数据长度不匹配。
  292. ValueError: coarsest_stride,target_size需有且只有一个被指定。
  293. ValueError: target_size小于原图的大小。
  294. """
  295. if im_info is None:
  296. im_info = dict()
  297. if not isinstance(im, np.ndarray):
  298. raise TypeError("Padding: image type is not numpy.")
  299. if len(im.shape) != 3:
  300. raise ValueError('Padding: image is not 3-dimensional.')
  301. im_h, im_w, im_c = im.shape[:]
  302. if isinstance(self.target_size, int):
  303. padding_im_h = self.target_size
  304. padding_im_w = self.target_size
  305. elif isinstance(self.target_size, list) or isinstance(self.target_size,
  306. tuple):
  307. padding_im_w = self.target_size[0]
  308. padding_im_h = self.target_size[1]
  309. elif self.coarsest_stride > 0:
  310. padding_im_h = int(
  311. np.ceil(im_h / self.coarsest_stride) * self.coarsest_stride)
  312. padding_im_w = int(
  313. np.ceil(im_w / self.coarsest_stride) * self.coarsest_stride)
  314. else:
  315. raise ValueError(
  316. "coarsest_stridei(>1) or target_size(list|int) need setting in Padding transform"
  317. )
  318. pad_height = padding_im_h - im_h
  319. pad_width = padding_im_w - im_w
  320. if pad_height < 0 or pad_width < 0:
  321. raise ValueError(
  322. 'the size of image should be less than target_size, but the size of image ({}, {}), is larger than target_size ({}, {})'
  323. .format(im_w, im_h, padding_im_w, padding_im_h))
  324. padding_im = np.zeros(
  325. (padding_im_h, padding_im_w, im_c), dtype=np.float32)
  326. padding_im[:im_h, :im_w, :] = im
  327. if label_info is None:
  328. return (padding_im, im_info)
  329. else:
  330. return (padding_im, im_info, label_info)
  331. class Resize(DetTransform):
  332. """调整图像大小(resize)。
  333. - 当目标大小(target_size)类型为int时,根据插值方式,
  334. 将图像resize为[target_size, target_size]。
  335. - 当目标大小(target_size)类型为list或tuple时,根据插值方式,
  336. 将图像resize为target_size。
  337. 注意:当插值方式为“RANDOM”时,则随机选取一种插值方式进行resize。
  338. Args:
  339. target_size (int/list/tuple): 短边目标长度。默认为608。
  340. interp (str): resize的插值方式,与opencv的插值方式对应,取值范围为
  341. ['NEAREST', 'LINEAR', 'CUBIC', 'AREA', 'LANCZOS4', 'RANDOM']。默认为"LINEAR"。
  342. Raises:
  343. TypeError: 形参数据类型不满足需求。
  344. ValueError: 插值方式不在['NEAREST', 'LINEAR', 'CUBIC',
  345. 'AREA', 'LANCZOS4', 'RANDOM']中。
  346. """
  347. # The interpolation mode
  348. interp_dict = {
  349. 'NEAREST': cv2.INTER_NEAREST,
  350. 'LINEAR': cv2.INTER_LINEAR,
  351. 'CUBIC': cv2.INTER_CUBIC,
  352. 'AREA': cv2.INTER_AREA,
  353. 'LANCZOS4': cv2.INTER_LANCZOS4
  354. }
  355. def __init__(self, target_size=608, interp='LINEAR'):
  356. self.interp = interp
  357. if not (interp == "RANDOM" or interp in self.interp_dict):
  358. raise ValueError("interp should be one of {}".format(
  359. self.interp_dict.keys()))
  360. if isinstance(target_size, list) or isinstance(target_size, tuple):
  361. if len(target_size) != 2:
  362. raise TypeError(
  363. 'when target is list or tuple, it should include 2 elements, but it is {}'
  364. .format(target_size))
  365. elif not isinstance(target_size, int):
  366. raise TypeError(
  367. "Type of target_size is invalid. Must be Integer or List or tuple, now is {}"
  368. .format(type(target_size)))
  369. self.target_size = target_size
  370. def __call__(self, im, im_info=None, label_info=None):
  371. """
  372. Args:
  373. im (np.ndarray): 图像np.ndarray数据。
  374. im_info (dict, 可选): 存储与图像相关的信息。
  375. label_info (dict, 可选): 存储与标注框相关的信息。
  376. Returns:
  377. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  378. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  379. 存储与标注框相关信息的字典。
  380. Raises:
  381. TypeError: 形参数据类型不满足需求。
  382. ValueError: 数据长度不匹配。
  383. """
  384. if im_info is None:
  385. im_info = dict()
  386. if not isinstance(im, np.ndarray):
  387. raise TypeError("Resize: image type is not numpy.")
  388. if len(im.shape) != 3:
  389. raise ValueError('Resize: image is not 3-dimensional.')
  390. if self.interp == "RANDOM":
  391. interp = random.choice(list(self.interp_dict.keys()))
  392. else:
  393. interp = self.interp
  394. im = resize(im, self.target_size, self.interp_dict[interp])
  395. if label_info is None:
  396. return (im, im_info)
  397. else:
  398. return (im, im_info, label_info)
  399. class RandomHorizontalFlip(DetTransform):
  400. """随机翻转图像、标注框、分割信息,模型训练时的数据增强操作。
  401. 1. 随机采样一个0-1之间的小数,当小数小于水平翻转概率时,
  402. 执行2-4步操作,否则直接返回。
  403. 2. 水平翻转图像。
  404. 3. 计算翻转后的真实标注框的坐标,更新label_info中的gt_bbox信息。
  405. 4. 计算翻转后的真实分割区域的坐标,更新label_info中的gt_poly信息。
  406. Args:
  407. prob (float): 随机水平翻转的概率。默认为0.5。
  408. Raises:
  409. TypeError: 形参数据类型不满足需求。
  410. """
  411. def __init__(self, prob=0.5):
  412. self.prob = prob
  413. if not isinstance(self.prob, float):
  414. raise TypeError("RandomHorizontalFlip: input type is invalid.")
  415. def __call__(self, im, im_info=None, label_info=None):
  416. """
  417. Args:
  418. im (np.ndarray): 图像np.ndarray数据。
  419. im_info (dict, 可选): 存储与图像相关的信息。
  420. label_info (dict, 可选): 存储与标注框相关的信息。
  421. Returns:
  422. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  423. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  424. 存储与标注框相关信息的字典。
  425. 其中,im_info更新字段为:
  426. - gt_bbox (np.ndarray): 水平翻转后的标注框坐标[x1, y1, x2, y2],形状为(n, 4),
  427. 其中n代表真实标注框的个数。
  428. - gt_poly (list): 水平翻转后的多边形分割区域的x、y坐标,长度为n,
  429. 其中n代表真实标注框的个数。
  430. Raises:
  431. TypeError: 形参数据类型不满足需求。
  432. ValueError: 数据长度不匹配。
  433. """
  434. if not isinstance(im, np.ndarray):
  435. raise TypeError(
  436. "RandomHorizontalFlip: image is not a numpy array.")
  437. if len(im.shape) != 3:
  438. raise ValueError(
  439. "RandomHorizontalFlip: image is not 3-dimensional.")
  440. if im_info is None or label_info is None:
  441. raise TypeError(
  442. 'Cannot do RandomHorizontalFlip! ' +
  443. 'Becasuse the im_info and label_info can not be None!')
  444. if 'gt_bbox' not in label_info:
  445. raise TypeError('Cannot do RandomHorizontalFlip! ' + \
  446. 'Becasuse gt_bbox is not in label_info!')
  447. image_shape = im_info['image_shape']
  448. gt_bbox = label_info['gt_bbox']
  449. height = image_shape[0]
  450. width = image_shape[1]
  451. if np.random.uniform(0, 1) < self.prob:
  452. im = horizontal_flip(im)
  453. if gt_bbox.shape[0] == 0:
  454. if label_info is None:
  455. return (im, im_info)
  456. else:
  457. return (im, im_info, label_info)
  458. label_info['gt_bbox'] = box_horizontal_flip(gt_bbox, width)
  459. if 'gt_poly' in label_info and \
  460. len(label_info['gt_poly']) != 0:
  461. label_info['gt_poly'] = segms_horizontal_flip(
  462. label_info['gt_poly'], height, width)
  463. if label_info is None:
  464. return (im, im_info)
  465. else:
  466. return (im, im_info, label_info)
  467. class Normalize(DetTransform):
  468. """对图像进行标准化。
  469. 1.像素值减去min_val
  470. 2.像素值除以(max_val-min_val)
  471. 3.对图像进行减均值除以标准差操作。
  472. Args:
  473. mean (list): 图像数据集的均值。默认值[0.5, 0.5, 0.5]。
  474. std (list): 图像数据集的标准差。默认值[0.5, 0.5, 0.5]。
  475. min_val (list): 图像数据集的最小值。默认值[0, 0, 0]。
  476. max_val (list): 图像数据集的最大值。默认值[255.0, 255.0, 255.0]。
  477. Raises:
  478. TypeError: 形参数据类型不满足需求。
  479. """
  480. def __init__(self,
  481. mean=[0.485, 0.456, 0.406],
  482. std=[0.229, 0.224, 0.225],
  483. min_val=[0, 0, 0],
  484. max_val=[255.0, 255.0, 255.0]):
  485. self.mean = mean
  486. self.std = std
  487. self.min_val = min_val
  488. self.max_val = max_val
  489. if not (isinstance(self.mean, list) and isinstance(self.std, list)):
  490. raise TypeError("NormalizeImage: input type is invalid.")
  491. if not (isinstance(self.min_val, list) and isinstance(self.max_val,
  492. list)):
  493. raise ValueError("{}: input type is invalid.".format(self))
  494. from functools import reduce
  495. if reduce(lambda x, y: x * y, self.std) == 0:
  496. raise TypeError('NormalizeImage: std is invalid!')
  497. def __call__(self, im, im_info=None, label_info=None):
  498. """
  499. Args:
  500. im (numnp.ndarraypy): 图像np.ndarray数据。
  501. im_info (dict, 可选): 存储与图像相关的信息。
  502. label_info (dict, 可选): 存储与标注框相关的信息。
  503. Returns:
  504. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  505. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  506. 存储与标注框相关信息的字典。
  507. """
  508. mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
  509. std = np.array(self.std)[np.newaxis, np.newaxis, :]
  510. im = normalize(im, mean, std, self.min_val, self.max_val)
  511. if label_info is None:
  512. return (im, im_info)
  513. else:
  514. return (im, im_info, label_info)
  515. class RandomDistort(DetTransform):
  516. """以一定的概率对图像进行随机像素内容变换,模型训练时的数据增强操作
  517. 1. 对变换的操作顺序进行随机化操作。
  518. 2. 按照1中的顺序以一定的概率对图像进行随机像素内容变换。
  519. 【注意】如果输入是uint8/uint16的RGB图像,该数据增强必须在数据增强Normalize之前使用。
  520. Args:
  521. brightness_range (float): 明亮度的缩放系数范围。
  522. 从[1-`brightness_range`, 1+`brightness_range`]中随机取值作为明亮度缩放因子`scale`,
  523. 按照公式`image = image * scale`调整图像明亮度。默认值为0.5。
  524. brightness_prob (float): 随机调整明亮度的概率。默认为0.5。
  525. contrast_range (float): 对比度的缩放系数范围。
  526. 从[1-`contrast_range`, 1+`contrast_range`]中随机取值作为对比度缩放因子`scale`,
  527. 按照公式`image = image * scale + (image_mean + 0.5) * (1 - scale)`调整图像对比度。默认为0.5。
  528. contrast_prob (float): 随机调整对比度的概率。默认为0.5。
  529. saturation_range (float): 饱和度的缩放系数范围。
  530. 从[1-`saturation_range`, 1+`saturation_range`]中随机取值作为饱和度缩放因子`scale`,
  531. 按照公式`image = gray * (1 - scale) + image * scale`,
  532. 其中`gray = R * 299/1000 + G * 587/1000+ B * 114/1000`。默认为0.5。
  533. saturation_prob (float): 随机调整饱和度的概率。默认为0.5。
  534. hue_range (int): 调整色相角度的差值取值范围。
  535. 从[-`hue_range`, `hue_range`]中随机取值作为色相角度调整差值`delta`,
  536. 按照公式`hue = hue + delta`调整色相角度 。默认为18,取值范围[0, 360]。
  537. hue_prob (float): 随机调整色调的概率。默认为0.5。
  538. """
  539. def __init__(self,
  540. brightness_range=0.5,
  541. brightness_prob=0.5,
  542. contrast_range=0.5,
  543. contrast_prob=0.5,
  544. saturation_range=0.5,
  545. saturation_prob=0.5,
  546. hue_range=18,
  547. hue_prob=0.5):
  548. self.brightness_range = brightness_range
  549. self.brightness_prob = brightness_prob
  550. self.contrast_range = contrast_range
  551. self.contrast_prob = contrast_prob
  552. self.saturation_range = saturation_range
  553. self.saturation_prob = saturation_prob
  554. self.hue_range = hue_range
  555. self.hue_prob = hue_prob
  556. def __call__(self, im, im_info=None, label_info=None):
  557. """
  558. Args:
  559. im (np.ndarray): 图像np.ndarray数据。
  560. im_info (dict, 可选): 存储与图像相关的信息。
  561. label_info (dict, 可选): 存储与标注框相关的信息。
  562. Returns:
  563. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  564. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  565. 存储与标注框相关信息的字典。
  566. """
  567. if im.shape[-1] != 3:
  568. raise Exception(
  569. "Only the 3-channel RGB image is supported in the RandomDistort operator, but recieved image channel is {}".
  570. format(im.shape[-1]))
  571. if self.data_type not in [np.uint8, np.uint16, np.float32]:
  572. raise Exception(
  573. "Only the uint8/uint16/float32 RGB image is supported in the RandomDistort operator, but recieved image data type is {}".
  574. format(self.data_type))
  575. brightness_lower = 1 - self.brightness_range
  576. brightness_upper = 1 + self.brightness_range
  577. contrast_lower = 1 - self.contrast_range
  578. contrast_upper = 1 + self.contrast_range
  579. saturation_lower = 1 - self.saturation_range
  580. saturation_upper = 1 + self.saturation_range
  581. hue_lower = -self.hue_range
  582. hue_upper = self.hue_range
  583. ops = [brightness, contrast, saturation, hue]
  584. random.shuffle(ops)
  585. params_dict = {
  586. 'brightness': {
  587. 'brightness_lower': brightness_lower,
  588. 'brightness_upper': brightness_upper,
  589. },
  590. 'contrast': {
  591. 'contrast_lower': contrast_lower,
  592. 'contrast_upper': contrast_upper,
  593. },
  594. 'saturation': {
  595. 'saturation_lower': saturation_lower,
  596. 'saturation_upper': saturation_upper,
  597. 'is_rgb': self.to_rgb,
  598. },
  599. 'hue': {
  600. 'hue_lower': hue_lower,
  601. 'hue_upper': hue_upper,
  602. 'is_rgb': self.to_rgb,
  603. }
  604. }
  605. prob_dict = {
  606. 'brightness': self.brightness_prob,
  607. 'contrast': self.contrast_prob,
  608. 'saturation': self.saturation_prob,
  609. 'hue': self.hue_prob
  610. }
  611. for id in range(4):
  612. params = params_dict[ops[id].__name__]
  613. prob = prob_dict[ops[id].__name__]
  614. params['im'] = im
  615. if np.random.uniform(0, 1) < prob:
  616. im = ops[id](**params)
  617. im = im.astype('float32')
  618. if label_info is None:
  619. return (im, im_info)
  620. else:
  621. return (im, im_info, label_info)
  622. class MixupImage(DetTransform):
  623. """对图像进行mixup操作,模型训练时的数据增强操作,目前仅YOLOv3模型支持该transform。
  624. 当label_info中不存在mixup字段时,直接返回,否则进行下述操作:
  625. 1. 从随机beta分布中抽取出随机因子factor。
  626. 2.
  627. - 当factor>=1.0时,去除label_info中的mixup字段,直接返回。
  628. - 当factor<=0.0时,直接返回label_info中的mixup字段,并在label_info中去除该字段。
  629. - 其余情况,执行下述操作:
  630. (1)原图像乘以factor,mixup图像乘以(1-factor),叠加2个结果。
  631. (2)拼接原图像标注框和mixup图像标注框。
  632. (3)拼接原图像标注框类别和mixup图像标注框类别。
  633. (4)原图像标注框混合得分乘以factor,mixup图像标注框混合得分乘以(1-factor),叠加2个结果。
  634. 3. 更新im_info中的image_shape信息。
  635. Args:
  636. alpha (float): 随机beta分布的下限。默认为1.5。
  637. beta (float): 随机beta分布的上限。默认为1.5。
  638. mixup_epoch (int): 在前mixup_epoch轮使用mixup增强操作;当该参数为-1时,该策略不会生效。
  639. 默认为-1。
  640. Raises:
  641. ValueError: 数据长度不匹配。
  642. """
  643. def __init__(self, alpha=1.5, beta=1.5, mixup_epoch=-1):
  644. self.alpha = alpha
  645. self.beta = beta
  646. if self.alpha <= 0.0:
  647. raise ValueError("alpha shold be positive in MixupImage")
  648. if self.beta <= 0.0:
  649. raise ValueError("beta shold be positive in MixupImage")
  650. self.mixup_epoch = mixup_epoch
  651. def _mixup_img(self, img1, img2, factor):
  652. h = max(img1.shape[0], img2.shape[0])
  653. w = max(img1.shape[1], img2.shape[1])
  654. img = np.zeros((h, w, img1.shape[2]), 'float32')
  655. img[:img1.shape[0], :img1.shape[1], :] = \
  656. img1.astype('float32') * factor
  657. img[:img2.shape[0], :img2.shape[1], :] += \
  658. img2.astype('float32') * (1.0 - factor)
  659. return img.astype('float32')
  660. def __call__(self, im, im_info=None, label_info=None):
  661. """
  662. Args:
  663. im (np.ndarray): 图像np.ndarray数据。
  664. im_info (dict, 可选): 存储与图像相关的信息。
  665. label_info (dict, 可选): 存储与标注框相关的信息。
  666. Returns:
  667. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  668. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  669. 存储与标注框相关信息的字典。
  670. 其中,im_info更新字段为:
  671. - image_shape (np.ndarray): mixup后的图像高、宽二者组成的np.ndarray,形状为(2,)。
  672. im_info删除的字段:
  673. - mixup (list): 与当前字段进行mixup的图像相关信息。
  674. label_info更新字段为:
  675. - gt_bbox (np.ndarray): mixup后真实标注框坐标,形状为(n, 4),
  676. 其中n代表真实标注框的个数。
  677. - gt_class (np.ndarray): mixup后每个真实标注框对应的类别序号,形状为(n, 1),
  678. 其中n代表真实标注框的个数。
  679. - gt_score (np.ndarray): mixup后每个真实标注框对应的混合得分,形状为(n, 1),
  680. 其中n代表真实标注框的个数。
  681. Raises:
  682. TypeError: 形参数据类型不满足需求。
  683. """
  684. if im_info is None:
  685. raise TypeError('Cannot do MixupImage! ' +
  686. 'Becasuse the im_info can not be None!')
  687. if 'mixup' not in im_info:
  688. if label_info is None:
  689. return (im, im_info)
  690. else:
  691. return (im, im_info, label_info)
  692. factor = np.random.beta(self.alpha, self.beta)
  693. factor = max(0.0, min(1.0, factor))
  694. if im_info['epoch'] > self.mixup_epoch \
  695. or factor >= 1.0:
  696. im_info.pop('mixup')
  697. if label_info is None:
  698. return (im, im_info)
  699. else:
  700. return (im, im_info, label_info)
  701. if factor <= 0.0:
  702. return im_info.pop('mixup')
  703. im = self._mixup_img(im, im_info['mixup'][0], factor)
  704. if label_info is None:
  705. raise TypeError('Cannot do MixupImage! ' +
  706. 'Becasuse the label_info can not be None!')
  707. if 'gt_bbox' not in label_info or \
  708. 'gt_class' not in label_info or \
  709. 'gt_score' not in label_info:
  710. raise TypeError('Cannot do MixupImage! ' + \
  711. 'Becasuse gt_bbox/gt_class/gt_score is not in label_info!')
  712. gt_bbox1 = label_info['gt_bbox']
  713. gt_bbox2 = im_info['mixup'][2]['gt_bbox']
  714. gt_class1 = label_info['gt_class']
  715. gt_class2 = im_info['mixup'][2]['gt_class']
  716. gt_score1 = label_info['gt_score']
  717. gt_score2 = im_info['mixup'][2]['gt_score']
  718. if 'gt_poly' in label_info:
  719. gt_poly1 = label_info['gt_poly']
  720. gt_poly2 = im_info['mixup'][2]['gt_poly']
  721. is_crowd1 = label_info['is_crowd']
  722. is_crowd2 = im_info['mixup'][2]['is_crowd']
  723. if 0 not in gt_class1 and 0 not in gt_class2:
  724. gt_bbox = np.concatenate((gt_bbox1, gt_bbox2), axis=0)
  725. gt_class = np.concatenate((gt_class1, gt_class2), axis=0)
  726. gt_score = np.concatenate(
  727. (gt_score1 * factor, gt_score2 * (1. - factor)), axis=0)
  728. if 'gt_poly' in label_info:
  729. label_info['gt_poly'] = gt_poly1 + gt_poly2
  730. is_crowd = np.concatenate((is_crowd1, is_crowd2), axis=0)
  731. elif 0 in gt_class1:
  732. gt_bbox = gt_bbox2
  733. gt_class = gt_class2
  734. gt_score = gt_score2 * (1. - factor)
  735. if 'gt_poly' in label_info:
  736. label_info['gt_poly'] = gt_poly2
  737. is_crowd = is_crowd2
  738. else:
  739. gt_bbox = gt_bbox1
  740. gt_class = gt_class1
  741. gt_score = gt_score1 * factor
  742. if 'gt_poly' in label_info:
  743. label_info['gt_poly'] = gt_poly1
  744. is_crowd = is_crowd1
  745. label_info['gt_bbox'] = gt_bbox
  746. label_info['gt_score'] = gt_score
  747. label_info['gt_class'] = gt_class
  748. label_info['is_crowd'] = is_crowd
  749. im_info['image_shape'] = np.array([im.shape[0],
  750. im.shape[1]]).astype('int32')
  751. im_info.pop('mixup')
  752. if label_info is None:
  753. return (im, im_info)
  754. else:
  755. return (im, im_info, label_info)
  756. class RandomExpand(DetTransform):
  757. """随机扩张图像,模型训练时的数据增强操作。
  758. 1. 随机选取扩张比例(扩张比例大于1时才进行扩张)。
  759. 2. 计算扩张后图像大小。
  760. 3. 初始化像素值为输入填充值的图像,并将原图像随机粘贴于该图像上。
  761. 4. 根据原图像粘贴位置换算出扩张后真实标注框的位置坐标。
  762. 5. 根据原图像粘贴位置换算出扩张后真实分割区域的位置坐标。
  763. Args:
  764. ratio (float): 图像扩张的最大比例。默认为4.0。
  765. prob (float): 随机扩张的概率。默认为0.5。
  766. fill_value (list): 扩张图像的初始填充值(0-255)。默认为[123.675, 116.28, 103.53]。
  767. """
  768. def __init__(self,
  769. ratio=4.,
  770. prob=0.5,
  771. fill_value=[123.675, 116.28, 103.53]):
  772. super(RandomExpand, self).__init__()
  773. assert ratio > 1.01, "expand ratio must be larger than 1.01"
  774. self.ratio = ratio
  775. self.prob = prob
  776. assert isinstance(fill_value, Sequence), \
  777. "fill value must be sequence"
  778. if not isinstance(fill_value, tuple):
  779. fill_value = tuple(fill_value)
  780. self.fill_value = fill_value
  781. def __call__(self, im, im_info=None, label_info=None):
  782. """
  783. Args:
  784. im (np.ndarray): 图像np.ndarray数据。
  785. im_info (dict, 可选): 存储与图像相关的信息。
  786. label_info (dict, 可选): 存储与标注框相关的信息。
  787. Returns:
  788. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  789. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  790. 存储与标注框相关信息的字典。
  791. 其中,im_info更新字段为:
  792. - image_shape (np.ndarray): 扩张后的图像高、宽二者组成的np.ndarray,形状为(2,)。
  793. label_info更新字段为:
  794. - gt_bbox (np.ndarray): 随机扩张后真实标注框坐标,形状为(n, 4),
  795. 其中n代表真实标注框的个数。
  796. - gt_class (np.ndarray): 随机扩张后每个真实标注框对应的类别序号,形状为(n, 1),
  797. 其中n代表真实标注框的个数。
  798. Raises:
  799. TypeError: 形参数据类型不满足需求。
  800. """
  801. if im_info is None or label_info is None:
  802. raise TypeError(
  803. 'Cannot do RandomExpand! ' +
  804. 'Becasuse the im_info and label_info can not be None!')
  805. if 'gt_bbox' not in label_info or \
  806. 'gt_class' not in label_info:
  807. raise TypeError('Cannot do RandomExpand! ' + \
  808. 'Becasuse gt_bbox/gt_class is not in label_info!')
  809. if np.random.uniform(0., 1.) > self.prob:
  810. return (im, im_info, label_info)
  811. if 'gt_class' in label_info and 0 in label_info['gt_class']:
  812. return (im, im_info, label_info)
  813. image_shape = im_info['image_shape']
  814. height = int(image_shape[0])
  815. width = int(image_shape[1])
  816. expand_ratio = np.random.uniform(1., self.ratio)
  817. h = int(height * expand_ratio)
  818. w = int(width * expand_ratio)
  819. if not h > height or not w > width:
  820. return (im, im_info, label_info)
  821. y = np.random.randint(0, h - height)
  822. x = np.random.randint(0, w - width)
  823. canvas = np.ones((h, w, 3), dtype=np.float32)
  824. canvas *= np.array(self.fill_value, dtype=np.float32)
  825. canvas[y:y + height, x:x + width, :] = im
  826. im_info['image_shape'] = np.array([h, w]).astype('int32')
  827. if 'gt_bbox' in label_info and len(label_info['gt_bbox']) > 0:
  828. label_info['gt_bbox'] += np.array([x, y] * 2, dtype=np.float32)
  829. if 'gt_poly' in label_info and len(label_info['gt_poly']) > 0:
  830. label_info['gt_poly'] = expand_segms(label_info['gt_poly'], x, y,
  831. height, width, expand_ratio)
  832. return (canvas, im_info, label_info)
  833. class RandomCrop(DetTransform):
  834. """随机裁剪图像。
  835. 1. 若allow_no_crop为True,则在thresholds加入’no_crop’。
  836. 2. 随机打乱thresholds。
  837. 3. 遍历thresholds中各元素:
  838. (1) 如果当前thresh为’no_crop’,则返回原始图像和标注信息。
  839. (2) 随机取出aspect_ratio和scaling中的值并由此计算出候选裁剪区域的高、宽、起始点。
  840. (3) 计算真实标注框与候选裁剪区域IoU,若全部真实标注框的IoU都小于thresh,则继续第3步。
  841. (4) 如果cover_all_box为True且存在真实标注框的IoU小于thresh,则继续第3步。
  842. (5) 筛选出位于候选裁剪区域内的真实标注框,若有效框的个数为0,则继续第3步,否则进行第4步。
  843. 4. 换算有效真值标注框相对候选裁剪区域的位置坐标。
  844. 5. 换算有效分割区域相对候选裁剪区域的位置坐标。
  845. Args:
  846. aspect_ratio (list): 裁剪后短边缩放比例的取值范围,以[min, max]形式表示。默认值为[.5, 2.]。
  847. thresholds (list): 判断裁剪候选区域是否有效所需的IoU阈值取值列表。默认值为[.0, .1, .3, .5, .7, .9]。
  848. scaling (list): 裁剪面积相对原面积的取值范围,以[min, max]形式表示。默认值为[.3, 1.]。
  849. num_attempts (int): 在放弃寻找有效裁剪区域前尝试的次数。默认值为50。
  850. allow_no_crop (bool): 是否允许未进行裁剪。默认值为True。
  851. cover_all_box (bool): 是否要求所有的真实标注框都必须在裁剪区域内。默认值为False。
  852. """
  853. def __init__(self,
  854. aspect_ratio=[.5, 2.],
  855. thresholds=[.0, .1, .3, .5, .7, .9],
  856. scaling=[.3, 1.],
  857. num_attempts=50,
  858. allow_no_crop=True,
  859. cover_all_box=False):
  860. self.aspect_ratio = aspect_ratio
  861. self.thresholds = thresholds
  862. self.scaling = scaling
  863. self.num_attempts = num_attempts
  864. self.allow_no_crop = allow_no_crop
  865. self.cover_all_box = cover_all_box
  866. def __call__(self, im, im_info=None, label_info=None):
  867. """
  868. Args:
  869. im (np.ndarray): 图像np.ndarray数据。
  870. im_info (dict, 可选): 存储与图像相关的信息。
  871. label_info (dict, 可选): 存储与标注框相关的信息。
  872. Returns:
  873. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  874. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  875. 存储与标注框相关信息的字典。
  876. 其中,im_info更新字段为:
  877. - image_shape (np.ndarray): 扩裁剪的图像高、宽二者组成的np.ndarray,形状为(2,)。
  878. label_info更新字段为:
  879. - gt_bbox (np.ndarray): 随机裁剪后真实标注框坐标,形状为(n, 4),
  880. 其中n代表真实标注框的个数。
  881. - gt_class (np.ndarray): 随机裁剪后每个真实标注框对应的类别序号,形状为(n, 1),
  882. 其中n代表真实标注框的个数。
  883. - gt_score (np.ndarray): 随机裁剪后每个真实标注框对应的混合得分,形状为(n, 1),
  884. 其中n代表真实标注框的个数。
  885. Raises:
  886. TypeError: 形参数据类型不满足需求。
  887. """
  888. if im_info is None or label_info is None:
  889. raise TypeError(
  890. 'Cannot do RandomCrop! ' +
  891. 'Becasuse the im_info and label_info can not be None!')
  892. if 'gt_bbox' not in label_info or \
  893. 'gt_class' not in label_info:
  894. raise TypeError('Cannot do RandomCrop! ' + \
  895. 'Becasuse gt_bbox/gt_class is not in label_info!')
  896. if len(label_info['gt_bbox']) == 0:
  897. return (im, im_info, label_info)
  898. if 'gt_class' in label_info and 0 in label_info['gt_class']:
  899. return (im, im_info, label_info)
  900. image_shape = im_info['image_shape']
  901. w = image_shape[1]
  902. h = image_shape[0]
  903. gt_bbox = label_info['gt_bbox']
  904. thresholds = list(self.thresholds)
  905. if self.allow_no_crop:
  906. thresholds.append('no_crop')
  907. np.random.shuffle(thresholds)
  908. for thresh in thresholds:
  909. if thresh == 'no_crop':
  910. return (im, im_info, label_info)
  911. found = False
  912. for i in range(self.num_attempts):
  913. scale = np.random.uniform(*self.scaling)
  914. min_ar, max_ar = self.aspect_ratio
  915. aspect_ratio = np.random.uniform(
  916. max(min_ar, scale**2), min(max_ar, scale**-2))
  917. crop_h = int(h * scale / np.sqrt(aspect_ratio))
  918. crop_w = int(w * scale * np.sqrt(aspect_ratio))
  919. crop_y = np.random.randint(0, h - crop_h)
  920. crop_x = np.random.randint(0, w - crop_w)
  921. crop_box = [crop_x, crop_y, crop_x + crop_w, crop_y + crop_h]
  922. iou = iou_matrix(
  923. gt_bbox, np.array(
  924. [crop_box], dtype=np.float32))
  925. if iou.max() < thresh:
  926. continue
  927. if self.cover_all_box and iou.min() < thresh:
  928. continue
  929. cropped_box, valid_ids = crop_box_with_center_constraint(
  930. gt_bbox, np.array(
  931. crop_box, dtype=np.float32))
  932. if valid_ids.size > 0:
  933. found = True
  934. break
  935. if found:
  936. if 'gt_poly' in label_info and len(label_info['gt_poly']) > 0:
  937. crop_polys = crop_segms(
  938. label_info['gt_poly'],
  939. valid_ids,
  940. np.array(
  941. crop_box, dtype=np.int64),
  942. h,
  943. w)
  944. if [] in crop_polys:
  945. delete_id = list()
  946. valid_polys = list()
  947. for id, crop_poly in enumerate(crop_polys):
  948. if crop_poly == []:
  949. delete_id.append(id)
  950. else:
  951. valid_polys.append(crop_poly)
  952. valid_ids = np.delete(valid_ids, delete_id)
  953. if len(valid_polys) == 0:
  954. return (im, im_info, label_info)
  955. label_info['gt_poly'] = valid_polys
  956. else:
  957. label_info['gt_poly'] = crop_polys
  958. im = crop_image(im, crop_box)
  959. label_info['gt_bbox'] = np.take(cropped_box, valid_ids, axis=0)
  960. label_info['gt_class'] = np.take(
  961. label_info['gt_class'], valid_ids, axis=0)
  962. im_info['image_shape'] = np.array(
  963. [crop_box[3] - crop_box[1],
  964. crop_box[2] - crop_box[0]]).astype('int32')
  965. if 'gt_score' in label_info:
  966. label_info['gt_score'] = np.take(
  967. label_info['gt_score'], valid_ids, axis=0)
  968. if 'is_crowd' in label_info:
  969. label_info['is_crowd'] = np.take(
  970. label_info['is_crowd'], valid_ids, axis=0)
  971. return (im, im_info, label_info)
  972. return (im, im_info, label_info)
  973. class CLAHE(DetTransform):
  974. """对图像进行对比度增强。
  975. Args:
  976. clip_limit (int|float): 颜色对比度的阈值,默认值为2.。
  977. tile_grid_size (list|tuple): 进行像素均衡化的网格大小。默认值为(8, 8)。
  978. Raises:
  979. TypeError: 形参数据类型不满足需求。
  980. """
  981. def __init__(self, clip_limit=2., tile_grid_size=(8, 8)):
  982. self.clip_limit = clip_limit
  983. self.tile_grid_size = tile_grid_size
  984. def __call__(self, im, im_info=None, label_info=None):
  985. """
  986. Args:
  987. im (numnp.ndarraypy): 图像np.ndarray数据。
  988. im_info (dict, 可选): 存储与图像相关的信息。
  989. label_info (dict, 可选): 存储与标注框相关的信息。
  990. Returns:
  991. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  992. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  993. 存储与标注框相关信息的字典。
  994. """
  995. if im.shape[-1] != 1:
  996. raise Exception(
  997. "Only the one-channel image is supported in the CLAHE transform, but recieved image channel is {}".
  998. format(im.shape[-1]))
  999. clahe = cv2.createCLAHE(
  1000. clipLimit=self.clip_limit, tileGridSize=self.tile_grid_size)
  1001. im = clahe.apply(im).astype(im.dtype)
  1002. if label_info is None:
  1003. return (im, im_info)
  1004. else:
  1005. return (im, im_info, label_info)
  1006. class ArrangeFasterRCNN(DetTransform):
  1007. """获取FasterRCNN模型训练/验证/预测所需信息。
  1008. Args:
  1009. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  1010. Raises:
  1011. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  1012. """
  1013. def __init__(self, mode=None):
  1014. if mode not in ['train', 'eval', 'test', 'quant']:
  1015. raise ValueError(
  1016. "mode must be in ['train', 'eval', 'test', 'quant']!")
  1017. self.mode = mode
  1018. def __call__(self, im, im_info=None, label_info=None):
  1019. """
  1020. Args:
  1021. im (np.ndarray): 图像np.ndarray数据。
  1022. im_info (dict, 可选): 存储与图像相关的信息。
  1023. label_info (dict, 可选): 存储与标注框相关的信息。
  1024. Returns:
  1025. tuple: 当mode为'train'时,返回(im, im_resize_info, gt_bbox, gt_class, is_crowd),分别对应
  1026. 图像np.ndarray数据、图像相当对于原图的resize信息、真实标注框、真实标注框对应的类别、真实标注框内是否是一组对象;
  1027. 当mode为'eval'时,返回(im, im_resize_info, im_id, im_shape, gt_bbox, gt_class, is_difficult),
  1028. 分别对应图像np.ndarray数据、图像相当对于原图的resize信息、图像id、图像大小信息、真实标注框、真实标注框对应的类别、
  1029. 真实标注框是否为难识别对象;当mode为'test'或'quant'时,返回(im, im_resize_info, im_shape),分别对应图像np.ndarray数据、
  1030. 图像相当对于原图的resize信息、图像大小信息。
  1031. Raises:
  1032. TypeError: 形参数据类型不满足需求。
  1033. ValueError: 数据长度不匹配。
  1034. """
  1035. im = permute(im, False)
  1036. if self.mode == 'train':
  1037. if im_info is None or label_info is None:
  1038. raise TypeError(
  1039. 'Cannot do ArrangeFasterRCNN! ' +
  1040. 'Becasuse the im_info and label_info can not be None!')
  1041. if len(label_info['gt_bbox']) != len(label_info['gt_class']):
  1042. raise ValueError("gt num mismatch: bbox and class.")
  1043. im_resize_info = im_info['im_resize_info']
  1044. gt_bbox = label_info['gt_bbox']
  1045. gt_class = label_info['gt_class']
  1046. is_crowd = label_info['is_crowd']
  1047. outputs = (im, im_resize_info, gt_bbox, gt_class, is_crowd)
  1048. elif self.mode == 'eval':
  1049. if im_info is None or label_info is None:
  1050. raise TypeError(
  1051. 'Cannot do ArrangeFasterRCNN! ' +
  1052. 'Becasuse the im_info and label_info can not be None!')
  1053. im_resize_info = im_info['im_resize_info']
  1054. im_id = im_info['im_id']
  1055. im_shape = np.array(
  1056. (im_info['image_shape'][0], im_info['image_shape'][1], 1),
  1057. dtype=np.float32)
  1058. gt_bbox = label_info['gt_bbox']
  1059. gt_class = label_info['gt_class']
  1060. is_difficult = label_info['difficult']
  1061. outputs = (im, im_resize_info, im_id, im_shape, gt_bbox, gt_class,
  1062. is_difficult)
  1063. else:
  1064. if im_info is None:
  1065. raise TypeError('Cannot do ArrangeFasterRCNN! ' +
  1066. 'Becasuse the im_info can not be None!')
  1067. im_resize_info = im_info['im_resize_info']
  1068. im_shape = np.array(
  1069. (im_info['image_shape'][0], im_info['image_shape'][1], 1),
  1070. dtype=np.float32)
  1071. outputs = (im, im_resize_info, im_shape)
  1072. return outputs
  1073. class ArrangeMaskRCNN(DetTransform):
  1074. """获取MaskRCNN模型训练/验证/预测所需信息。
  1075. Args:
  1076. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  1077. Raises:
  1078. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  1079. """
  1080. def __init__(self, mode=None):
  1081. if mode not in ['train', 'eval', 'test', 'quant']:
  1082. raise ValueError(
  1083. "mode must be in ['train', 'eval', 'test', 'quant']!")
  1084. self.mode = mode
  1085. def __call__(self, im, im_info=None, label_info=None):
  1086. """
  1087. Args:
  1088. im (np.ndarray): 图像np.ndarray数据。
  1089. im_info (dict, 可选): 存储与图像相关的信息。
  1090. label_info (dict, 可选): 存储与标注框相关的信息。
  1091. Returns:
  1092. tuple: 当mode为'train'时,返回(im, im_resize_info, gt_bbox, gt_class, is_crowd, gt_masks),分别对应
  1093. 图像np.ndarray数据、图像相当对于原图的resize信息、真实标注框、真实标注框对应的类别、真实标注框内是否是一组对象、
  1094. 真实分割区域;当mode为'eval'时,返回(im, im_resize_info, im_id, im_shape),分别对应图像np.ndarray数据、
  1095. 图像相当对于原图的resize信息、图像id、图像大小信息;当mode为'test'或'quant'时,返回(im, im_resize_info, im_shape),
  1096. 分别对应图像np.ndarray数据、图像相当对于原图的resize信息、图像大小信息。
  1097. Raises:
  1098. TypeError: 形参数据类型不满足需求。
  1099. ValueError: 数据长度不匹配。
  1100. """
  1101. im = permute(im, False)
  1102. if self.mode == 'train':
  1103. if im_info is None or label_info is None:
  1104. raise TypeError(
  1105. 'Cannot do ArrangeTrainMaskRCNN! ' +
  1106. 'Becasuse the im_info and label_info can not be None!')
  1107. if len(label_info['gt_bbox']) != len(label_info['gt_class']):
  1108. raise ValueError("gt num mismatch: bbox and class.")
  1109. im_resize_info = im_info['im_resize_info']
  1110. gt_bbox = label_info['gt_bbox']
  1111. gt_class = label_info['gt_class']
  1112. is_crowd = label_info['is_crowd']
  1113. assert 'gt_poly' in label_info
  1114. segms = label_info['gt_poly']
  1115. if len(segms) != 0:
  1116. assert len(segms) == is_crowd.shape[0]
  1117. gt_masks = []
  1118. valid = True
  1119. for i in range(len(segms)):
  1120. segm = segms[i]
  1121. gt_segm = []
  1122. if is_crowd[i]:
  1123. gt_segm.append([[0, 0]])
  1124. else:
  1125. for poly in segm:
  1126. if len(poly) == 0:
  1127. valid = False
  1128. break
  1129. gt_segm.append(np.array(poly).reshape(-1, 2))
  1130. if (not valid) or len(gt_segm) == 0:
  1131. break
  1132. gt_masks.append(gt_segm)
  1133. outputs = (im, im_resize_info, gt_bbox, gt_class, is_crowd,
  1134. gt_masks)
  1135. else:
  1136. if im_info is None:
  1137. raise TypeError('Cannot do ArrangeMaskRCNN! ' +
  1138. 'Becasuse the im_info can not be None!')
  1139. im_resize_info = im_info['im_resize_info']
  1140. im_shape = np.array(
  1141. (im_info['image_shape'][0], im_info['image_shape'][1], 1),
  1142. dtype=np.float32)
  1143. if self.mode == 'eval':
  1144. im_id = im_info['im_id']
  1145. outputs = (im, im_resize_info, im_id, im_shape)
  1146. else:
  1147. outputs = (im, im_resize_info, im_shape)
  1148. return outputs
  1149. class ArrangeYOLOv3(DetTransform):
  1150. """获取YOLOv3模型训练/验证/预测所需信息。
  1151. Args:
  1152. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  1153. Raises:
  1154. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  1155. """
  1156. def __init__(self, mode=None):
  1157. if mode not in ['train', 'eval', 'test', 'quant']:
  1158. raise ValueError(
  1159. "mode must be in ['train', 'eval', 'test', 'quant']!")
  1160. self.mode = mode
  1161. def __call__(self, im, im_info=None, label_info=None):
  1162. """
  1163. Args:
  1164. im (np.ndarray): 图像np.ndarray数据。
  1165. im_info (dict, 可选): 存储与图像相关的信息。
  1166. label_info (dict, 可选): 存储与标注框相关的信息。
  1167. Returns:
  1168. tuple: 当mode为'train'时,返回(im, gt_bbox, gt_class, gt_score, im_shape),分别对应
  1169. 图像np.ndarray数据、真实标注框、真实标注框对应的类别、真实标注框混合得分、图像大小信息;
  1170. 当mode为'eval'时,返回(im, im_shape, im_id, gt_bbox, gt_class, difficult),
  1171. 分别对应图像np.ndarray数据、图像大小信息、图像id、真实标注框、真实标注框对应的类别、
  1172. 真实标注框是否为难识别对象;当mode为'test'或'quant'时,返回(im, im_shape),
  1173. 分别对应图像np.ndarray数据、图像大小信息。
  1174. Raises:
  1175. TypeError: 形参数据类型不满足需求。
  1176. ValueError: 数据长度不匹配。
  1177. """
  1178. im = permute(im, False)
  1179. if self.mode == 'train':
  1180. if im_info is None or label_info is None:
  1181. raise TypeError(
  1182. 'Cannot do ArrangeYolov3! ' +
  1183. 'Becasuse the im_info and label_info can not be None!')
  1184. im_shape = im_info['image_shape']
  1185. if len(label_info['gt_bbox']) != len(label_info['gt_class']):
  1186. raise ValueError("gt num mismatch: bbox and class.")
  1187. if len(label_info['gt_bbox']) != len(label_info['gt_score']):
  1188. raise ValueError("gt num mismatch: bbox and score.")
  1189. gt_bbox = np.zeros((50, 4), dtype=im.dtype)
  1190. gt_class = np.zeros((50, ), dtype=np.int32)
  1191. gt_score = np.zeros((50, ), dtype=im.dtype)
  1192. gt_num = min(50, len(label_info['gt_bbox']))
  1193. if gt_num > 0:
  1194. label_info['gt_class'][:gt_num, 0] = label_info[
  1195. 'gt_class'][:gt_num, 0] - 1
  1196. if -1 not in label_info['gt_class']:
  1197. gt_bbox[:gt_num, :] = label_info['gt_bbox'][:gt_num, :]
  1198. gt_class[:gt_num] = label_info['gt_class'][:gt_num, 0]
  1199. gt_score[:gt_num] = label_info['gt_score'][:gt_num, 0]
  1200. # parse [x1, y1, x2, y2] to [x, y, w, h]
  1201. gt_bbox[:, 2:4] = gt_bbox[:, 2:4] - gt_bbox[:, :2]
  1202. gt_bbox[:, :2] = gt_bbox[:, :2] + gt_bbox[:, 2:4] / 2.
  1203. outputs = (im, gt_bbox, gt_class, gt_score, im_shape)
  1204. elif self.mode == 'eval':
  1205. if im_info is None or label_info is None:
  1206. raise TypeError(
  1207. 'Cannot do ArrangeYolov3! ' +
  1208. 'Becasuse the im_info and label_info can not be None!')
  1209. im_shape = im_info['image_shape']
  1210. if len(label_info['gt_bbox']) != len(label_info['gt_class']):
  1211. raise ValueError("gt num mismatch: bbox and class.")
  1212. im_id = im_info['im_id']
  1213. gt_bbox = np.zeros((50, 4), dtype=im.dtype)
  1214. gt_class = np.zeros((50, ), dtype=np.int32)
  1215. difficult = np.zeros((50, ), dtype=np.int32)
  1216. gt_num = min(50, len(label_info['gt_bbox']))
  1217. if gt_num > 0:
  1218. label_info['gt_class'][:gt_num, 0] = label_info[
  1219. 'gt_class'][:gt_num, 0] - 1
  1220. gt_bbox[:gt_num, :] = label_info['gt_bbox'][:gt_num, :]
  1221. gt_class[:gt_num] = label_info['gt_class'][:gt_num, 0]
  1222. difficult[:gt_num] = label_info['difficult'][:gt_num, 0]
  1223. outputs = (im, im_shape, im_id, gt_bbox, gt_class, difficult)
  1224. else:
  1225. if im_info is None:
  1226. raise TypeError('Cannot do ArrangeYolov3! ' +
  1227. 'Becasuse the im_info can not be None!')
  1228. im_shape = im_info['image_shape']
  1229. outputs = (im, im_shape)
  1230. return outputs
  1231. class ComposedRCNNTransforms(Compose):
  1232. """ RCNN模型(faster-rcnn/mask-rcnn)图像处理流程,具体如下,
  1233. 训练阶段:
  1234. 1. 随机以0.5的概率将图像水平翻转
  1235. 2. 图像归一化
  1236. 3. 图像按比例Resize,scale计算方式如下
  1237. scale = min_max_size[0] / short_size_of_image
  1238. if max_size_of_image * scale > min_max_size[1]:
  1239. scale = min_max_size[1] / max_size_of_image
  1240. 4. 将3步骤的长宽进行padding,使得长宽为32的倍数
  1241. 验证阶段:
  1242. 1. 图像归一化
  1243. 2. 图像按比例Resize,scale计算方式同上训练阶段
  1244. 3. 将2步骤的长宽进行padding,使得长宽为32的倍数
  1245. Args:
  1246. mode(str): 图像处理流程所处阶段,训练/验证/预测,分别对应'train', 'eval', 'test'
  1247. min_max_size(list): 图像在缩放时,最小边和最大边的约束条件
  1248. mean(list): 图像均值
  1249. std(list): 图像方差
  1250. random_horizontal_flip(bool): 是否以0.5的概率使用随机水平翻转增强,该仅在mode为`train`时生效,默认为True
  1251. """
  1252. def __init__(self,
  1253. mode,
  1254. min_max_size=[800, 1333],
  1255. mean=[0.485, 0.456, 0.406],
  1256. std=[0.229, 0.224, 0.225],
  1257. random_horizontal_flip=True):
  1258. if mode == 'train':
  1259. # 训练时的transforms,包含数据增强
  1260. transforms = [
  1261. Normalize(
  1262. mean=mean, std=std), ResizeByShort(
  1263. short_size=min_max_size[0], max_size=min_max_size[1]),
  1264. Padding(coarsest_stride=32)
  1265. ]
  1266. if random_horizontal_flip:
  1267. transforms.insert(0, RandomHorizontalFlip())
  1268. else:
  1269. # 验证/预测时的transforms
  1270. transforms = [
  1271. Normalize(
  1272. mean=mean, std=std), ResizeByShort(
  1273. short_size=min_max_size[0], max_size=min_max_size[1]),
  1274. Padding(coarsest_stride=32)
  1275. ]
  1276. super(ComposedRCNNTransforms, self).__init__(transforms)
  1277. class ComposedYOLOv3Transforms(Compose):
  1278. """YOLOv3模型的图像预处理流程,具体如下,
  1279. 训练阶段:
  1280. 1. 在前mixup_epoch轮迭代中,使用MixupImage策略,见https://paddlex.readthedocs.io/zh_CN/latest/apis/transforms/det_transforms.html#mixupimage
  1281. 2. 对图像进行随机扰动,包括亮度,对比度,饱和度和色调
  1282. 3. 随机扩充图像,见https://paddlex.readthedocs.io/zh_CN/latest/apis/transforms/det_transforms.html#randomexpand
  1283. 4. 随机裁剪图像
  1284. 5. 将4步骤的输出图像Resize成shape参数的大小
  1285. 6. 随机0.5的概率水平翻转图像
  1286. 7. 图像归一化
  1287. 验证/预测阶段:
  1288. 1. 将图像Resize成shape参数大小
  1289. 2. 图像归一化
  1290. Args:
  1291. mode(str): 图像处理流程所处阶段,训练/验证/预测,分别对应'train', 'eval', 'test'
  1292. shape(list): 输入模型中图像的大小,输入模型的图像会被Resize成此大小
  1293. mixup_epoch(int): 模型训练过程中,前mixup_epoch会使用mixup策略, 若设为-1,则表示不使用该策略
  1294. mean(list): 图像均值
  1295. std(list): 图像方差
  1296. random_distort(bool): 数据增强方式,参数仅在mode为`train`时生效,表示是否在训练过程中随机扰动图像,默认为True
  1297. random_expand(bool): 数据增强方式,参数仅在mode为`train`时生效,表示是否在训练过程中随机扩张图像,默认为True
  1298. random_crop(bool): 数据增强方式,参数仅在mode为`train`时生效,表示是否在训练过程中随机裁剪图像,默认为True
  1299. random_horizontal_flip(bool): 数据增强方式,参数仅在mode为`train`时生效,表示是否在训练过程中随机水平翻转图像,默认为True
  1300. """
  1301. def __init__(self,
  1302. mode,
  1303. shape=[608, 608],
  1304. mixup_epoch=250,
  1305. mean=[0.485, 0.456, 0.406],
  1306. std=[0.229, 0.224, 0.225],
  1307. random_distort=True,
  1308. random_expand=True,
  1309. random_crop=True,
  1310. random_horizontal_flip=True):
  1311. width = shape
  1312. if isinstance(shape, list):
  1313. if shape[0] != shape[1]:
  1314. raise Exception(
  1315. "In YOLOv3 model, width and height should be equal")
  1316. width = shape[0]
  1317. if width % 32 != 0:
  1318. raise Exception(
  1319. "In YOLOv3 model, width and height should be multiple of 32, e.g 224、256、320...."
  1320. )
  1321. if mode == 'train':
  1322. # 训练时的transforms,包含数据增强
  1323. transforms = [
  1324. MixupImage(mixup_epoch=mixup_epoch), Resize(
  1325. target_size=width, interp='RANDOM'), Normalize(
  1326. mean=mean, std=std)
  1327. ]
  1328. if random_horizontal_flip:
  1329. transforms.insert(1, RandomHorizontalFlip())
  1330. if random_crop:
  1331. transforms.insert(1, RandomCrop())
  1332. if random_expand:
  1333. transforms.insert(1, RandomExpand())
  1334. if random_distort:
  1335. transforms.insert(1, RandomDistort())
  1336. else:
  1337. # 验证/预测时的transforms
  1338. transforms = [
  1339. Resize(
  1340. target_size=width, interp='CUBIC'), Normalize(
  1341. mean=mean, std=std)
  1342. ]
  1343. super(ComposedYOLOv3Transforms, self).__init__(transforms)
  1344. class BatchRandomShape(DetTransform):
  1345. """调整图像大小(resize)。
  1346. 对batch数据中的每张图像全部resize到random_shapes中任意一个大小。
  1347. 注意:当插值方式为“RANDOM”时,则随机选取一种插值方式进行resize。
  1348. Args:
  1349. random_shapes (list): resize大小选择列表。
  1350. 默认为[320, 352, 384, 416, 448, 480, 512, 544, 576, 608]。
  1351. interp (str): resize的插值方式,与opencv的插值方式对应,取值范围为
  1352. ['NEAREST', 'LINEAR', 'CUBIC', 'AREA', 'LANCZOS4', 'RANDOM']。默认为"RANDOM"。
  1353. Raises:
  1354. ValueError: 插值方式不在['NEAREST', 'LINEAR', 'CUBIC',
  1355. 'AREA', 'LANCZOS4', 'RANDOM']中。
  1356. """
  1357. # The interpolation mode
  1358. interp_dict = {
  1359. 'NEAREST': cv2.INTER_NEAREST,
  1360. 'LINEAR': cv2.INTER_LINEAR,
  1361. 'CUBIC': cv2.INTER_CUBIC,
  1362. 'AREA': cv2.INTER_AREA,
  1363. 'LANCZOS4': cv2.INTER_LANCZOS4
  1364. }
  1365. def __init__(
  1366. self,
  1367. random_shapes=[320, 352, 384, 416, 448, 480, 512, 544, 576, 608],
  1368. interp='RANDOM'):
  1369. if not (interp == "RANDOM" or interp in self.interp_dict):
  1370. raise ValueError("interp should be one of {}".format(
  1371. self.interp_dict.keys()))
  1372. self.random_shapes = random_shapes
  1373. self.interp = interp
  1374. def __call__(self, batch_data):
  1375. """
  1376. Args:
  1377. batch_data (list): 由与图像相关的各种信息组成的batch数据。
  1378. Returns:
  1379. list: 由与图像相关的各种信息组成的batch数据。
  1380. """
  1381. shape = np.random.choice(self.random_shapes)
  1382. if self.interp == "RANDOM":
  1383. interp = random.choice(list(self.interp_dict.keys()))
  1384. else:
  1385. interp = self.interp
  1386. for data_id, data in enumerate(batch_data):
  1387. data_list = list(data)
  1388. im = data_list[0]
  1389. im = np.swapaxes(im, 1, 0)
  1390. im = np.swapaxes(im, 1, 2)
  1391. im = resize(im, shape, self.interp_dict[interp])
  1392. im = np.swapaxes(im, 1, 2)
  1393. im = np.swapaxes(im, 1, 0)
  1394. data_list[0] = im
  1395. batch_data[data_id] = tuple(data_list)
  1396. return batch_data
  1397. class GenerateYoloTarget(object):
  1398. """生成YOLOv3的ground truth(真实标注框)在不同特征层的位置转换信息。
  1399. 该transform只在YOLOv3计算细粒度loss时使用。
  1400. Args:
  1401. anchors (list|tuple): anchor框的宽度和高度。
  1402. anchor_masks (list|tuple): 在计算损失时,使用anchor的mask索引。
  1403. num_classes (int): 类别数。默认为80。
  1404. iou_thresh (float): iou阈值,当anchor和真实标注框的iou大于该阈值时,计入target。默认为1.0。
  1405. """
  1406. def __init__(self,
  1407. anchors,
  1408. anchor_masks,
  1409. downsample_ratios,
  1410. num_classes=80,
  1411. iou_thresh=1.):
  1412. super(GenerateYoloTarget, self).__init__()
  1413. self.anchors = anchors
  1414. self.anchor_masks = anchor_masks
  1415. self.downsample_ratios = downsample_ratios
  1416. self.num_classes = num_classes
  1417. self.iou_thresh = iou_thresh
  1418. def __call__(self, batch_data):
  1419. """
  1420. Args:
  1421. batch_data (list): 由与图像相关的各种信息组成的batch数据。
  1422. Returns:
  1423. list: 由与图像相关的各种信息组成的batch数据。
  1424. 其中,每个数据新添加的字段为:
  1425. - target0 (np.ndarray): YOLOv3的ground truth在特征层0的位置转换信息,
  1426. 形状为(特征层0的anchor数量, 6+类别数, 特征层0的h, 特征层0的w)。
  1427. - target1 (np.ndarray): YOLOv3的ground truth在特征层1的位置转换信息,
  1428. 形状为(特征层1的anchor数量, 6+类别数, 特征层1的h, 特征层1的w)。
  1429. - ...
  1430. -targetn (np.ndarray): YOLOv3的ground truth在特征层n的位置转换信息,
  1431. 形状为(特征层n的anchor数量, 6+类别数, 特征层n的h, 特征层n的w)。
  1432. n的是大小由anchor_masks的长度决定。
  1433. """
  1434. im = batch_data[0][0]
  1435. h = im.shape[1]
  1436. w = im.shape[2]
  1437. an_hw = np.array(self.anchors) / np.array([[w, h]])
  1438. for data_id, data in enumerate(batch_data):
  1439. gt_bbox = data[1]
  1440. gt_class = data[2]
  1441. gt_score = data[3]
  1442. im_shape = data[4]
  1443. origin_h = float(im_shape[0])
  1444. origin_w = float(im_shape[1])
  1445. data_list = list(data)
  1446. for i, (
  1447. mask, downsample_ratio
  1448. ) in enumerate(zip(self.anchor_masks, self.downsample_ratios)):
  1449. grid_h = int(h / downsample_ratio)
  1450. grid_w = int(w / downsample_ratio)
  1451. target = np.zeros(
  1452. (len(mask), 6 + self.num_classes, grid_h, grid_w),
  1453. dtype=np.float32)
  1454. for b in range(gt_bbox.shape[0]):
  1455. gx = gt_bbox[b, 0] / float(origin_w)
  1456. gy = gt_bbox[b, 1] / float(origin_h)
  1457. gw = gt_bbox[b, 2] / float(origin_w)
  1458. gh = gt_bbox[b, 3] / float(origin_h)
  1459. cls = gt_class[b]
  1460. score = gt_score[b]
  1461. if gw <= 0. or gh <= 0. or score <= 0.:
  1462. continue
  1463. # find best match anchor index
  1464. best_iou = 0.
  1465. best_idx = -1
  1466. for an_idx in range(an_hw.shape[0]):
  1467. iou = jaccard_overlap(
  1468. [0., 0., gw, gh],
  1469. [0., 0., an_hw[an_idx, 0], an_hw[an_idx, 1]])
  1470. if iou > best_iou:
  1471. best_iou = iou
  1472. best_idx = an_idx
  1473. gi = int(gx * grid_w)
  1474. gj = int(gy * grid_h)
  1475. # gtbox should be regresed in this layes if best match
  1476. # anchor index in anchor mask of this layer
  1477. if best_idx in mask:
  1478. best_n = mask.index(best_idx)
  1479. # x, y, w, h, scale
  1480. target[best_n, 0, gj, gi] = gx * grid_w - gi
  1481. target[best_n, 1, gj, gi] = gy * grid_h - gj
  1482. target[best_n, 2, gj, gi] = np.log(
  1483. gw * w / self.anchors[best_idx][0])
  1484. target[best_n, 3, gj, gi] = np.log(
  1485. gh * h / self.anchors[best_idx][1])
  1486. target[best_n, 4, gj, gi] = 2.0 - gw * gh
  1487. # objectness record gt_score
  1488. target[best_n, 5, gj, gi] = score
  1489. # classification
  1490. target[best_n, 6 + cls, gj, gi] = 1.
  1491. # For non-matched anchors, calculate the target if the iou
  1492. # between anchor and gt is larger than iou_thresh
  1493. if self.iou_thresh < 1:
  1494. for idx, mask_i in enumerate(mask):
  1495. if mask_i == best_idx: continue
  1496. iou = jaccard_overlap(
  1497. [0., 0., gw, gh],
  1498. [0., 0., an_hw[mask_i, 0], an_hw[mask_i, 1]])
  1499. if iou > self.iou_thresh:
  1500. # x, y, w, h, scale
  1501. target[idx, 0, gj, gi] = gx * grid_w - gi
  1502. target[idx, 1, gj, gi] = gy * grid_h - gj
  1503. target[idx, 2, gj, gi] = np.log(
  1504. gw * w / self.anchors[mask_i][0])
  1505. target[idx, 3, gj, gi] = np.log(
  1506. gh * h / self.anchors[mask_i][1])
  1507. target[idx, 4, gj, gi] = 2.0 - gw * gh
  1508. # objectness record gt_score
  1509. target[idx, 5, gj, gi] = score
  1510. # classification
  1511. target[idx, 6 + cls, gj, gi] = 1.
  1512. data_list.append(target)
  1513. batch_data[data_id] = tuple(data_list)
  1514. return batch_data