det_transforms.py 77 KB

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