det_transforms.py 72 KB

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