detector.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  1. # Copyright (c) 2021 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. from __future__ import absolute_import
  15. import collections
  16. import copy
  17. import os
  18. import os.path as osp
  19. import six
  20. import numpy as np
  21. import paddle
  22. from paddle.static import InputSpec
  23. import ppdet
  24. from ppdet.modeling.proposal_generator.target_layer import BBoxAssigner, MaskAssigner
  25. import paddlex
  26. import paddlex.utils.logging as logging
  27. from paddlex.cv.transforms.operators import _NormalizeBox, _PadBox, _BboxXYXY2XYWH, Resize, Padding
  28. from paddlex.cv.transforms.batch_operators import BatchCompose, BatchRandomResize, BatchRandomResizeByShort, _BatchPadding, _Gt2YoloTarget
  29. from paddlex.cv.transforms import arrange_transforms
  30. from .base import BaseModel
  31. from .utils.det_metrics import VOCMetric, COCOMetric
  32. from .utils.ema import ExponentialMovingAverage
  33. from paddlex.utils.checkpoint import det_pretrain_weights_dict
  34. __all__ = [
  35. "YOLOv3", "FasterRCNN", "PPYOLO", "PPYOLOTiny", "PPYOLOv2", "MaskRCNN"
  36. ]
  37. class BaseDetector(BaseModel):
  38. def __init__(self, model_name, num_classes=80, **params):
  39. self.init_params.update(locals())
  40. super(BaseDetector, self).__init__('detector')
  41. if not hasattr(ppdet.modeling, model_name):
  42. raise Exception("ERROR: There's no model named {}.".format(
  43. model_name))
  44. self.model_name = model_name
  45. self.num_classes = num_classes
  46. self.labels = None
  47. self.net = self.build_net(**params)
  48. def build_net(self, **params):
  49. with paddle.utils.unique_name.guard():
  50. net = ppdet.modeling.__dict__[self.model_name](**params)
  51. return net
  52. def _fix_transforms_shape(self, image_shape):
  53. raise NotImplementedError("_fix_transforms_shape: not implemented!")
  54. def _define_input_spec(self, image_shape):
  55. input_spec = [{
  56. "image": InputSpec(
  57. shape=image_shape, name='image', dtype='float32'),
  58. "im_shape": InputSpec(
  59. shape=[image_shape[0], 2], name='im_shape', dtype='float32'),
  60. "scale_factor": InputSpec(
  61. shape=[image_shape[0], 2],
  62. name='scale_factor',
  63. dtype='float32')
  64. }]
  65. return input_spec
  66. def _check_image_shape(self, image_shape):
  67. if len(image_shape) == 2:
  68. image_shape = [1, 3] + image_shape
  69. if image_shape[-2] % 32 > 0 or image_shape[-1] % 32 > 0:
  70. raise Exception(
  71. "Height and width in fixed_input_shape must be a multiple of 32, but received {}.".
  72. format(image_shape[-2:]))
  73. return image_shape
  74. def _get_test_inputs(self, image_shape):
  75. if image_shape is not None:
  76. image_shape = self._check_image_shape(image_shape)
  77. self._fix_transforms_shape(image_shape[-2:])
  78. else:
  79. image_shape = [None, 3, -1, -1]
  80. self.fixed_input_shape = image_shape
  81. return self._define_input_spec(image_shape)
  82. def _get_backbone(self, backbone_name, **params):
  83. backbone = getattr(ppdet.modeling, backbone_name)(**params)
  84. return backbone
  85. def run(self, net, inputs, mode):
  86. net_out = net(inputs)
  87. if mode in ['train', 'eval']:
  88. outputs = net_out
  89. else:
  90. for key in ['im_shape', 'scale_factor']:
  91. net_out[key] = inputs[key]
  92. outputs = dict()
  93. for key in net_out:
  94. outputs[key] = net_out[key].numpy()
  95. return outputs
  96. def default_optimizer(self, parameters, learning_rate, warmup_steps,
  97. warmup_start_lr, lr_decay_epochs, lr_decay_gamma,
  98. num_steps_each_epoch):
  99. boundaries = [b * num_steps_each_epoch for b in lr_decay_epochs]
  100. values = [(lr_decay_gamma**i) * learning_rate
  101. for i in range(len(lr_decay_epochs) + 1)]
  102. scheduler = paddle.optimizer.lr.PiecewiseDecay(
  103. boundaries=boundaries, values=values)
  104. if warmup_steps > 0:
  105. if warmup_steps > lr_decay_epochs[0] * num_steps_each_epoch:
  106. logging.error(
  107. "In function train(), parameters should satisfy: "
  108. "warmup_steps <= lr_decay_epochs[0]*num_samples_in_train_dataset",
  109. exit=False)
  110. logging.error(
  111. "See this doc for more information: "
  112. "https://github.com/PaddlePaddle/PaddleX/blob/develop/docs/appendix/parameters.md#notice",
  113. exit=False)
  114. scheduler = paddle.optimizer.lr.LinearWarmup(
  115. learning_rate=scheduler,
  116. warmup_steps=warmup_steps,
  117. start_lr=warmup_start_lr,
  118. end_lr=learning_rate)
  119. optimizer = paddle.optimizer.Momentum(
  120. scheduler,
  121. momentum=.9,
  122. weight_decay=paddle.regularizer.L2Decay(coeff=1e-04),
  123. parameters=parameters)
  124. return optimizer
  125. def train(self,
  126. num_epochs,
  127. train_dataset,
  128. train_batch_size=64,
  129. eval_dataset=None,
  130. optimizer=None,
  131. save_interval_epochs=1,
  132. log_interval_steps=10,
  133. save_dir='output',
  134. pretrain_weights='IMAGENET',
  135. learning_rate=.001,
  136. warmup_steps=0,
  137. warmup_start_lr=0.0,
  138. lr_decay_epochs=(216, 243),
  139. lr_decay_gamma=0.1,
  140. metric=None,
  141. use_ema=False,
  142. early_stop=False,
  143. early_stop_patience=5,
  144. use_vdl=True):
  145. """
  146. Train the model.
  147. Args:
  148. num_epochs(int): The number of epochs.
  149. train_dataset(paddlex.dataset): Training dataset.
  150. train_batch_size(int, optional): Total batch size among all cards used in training. Defaults to 64.
  151. eval_dataset(paddlex.dataset, optional):
  152. Evaluation dataset. If None, the model will not be evaluated during training process. Defaults to None.
  153. optimizer(paddle.optimizer.Optimizer or None, optional):
  154. Optimizer used for training. If None, a default optimizer is used. Defaults to None.
  155. save_interval_epochs(int, optional): Epoch interval for saving the model. Defaults to 1.
  156. log_interval_steps(int, optional): Step interval for printing training information. Defaults to 10.
  157. save_dir(str, optional): Directory to save the model. Defaults to 'output'.
  158. pretrain_weights(str or None, optional):
  159. None or name/path of pretrained weights. If None, no pretrained weights will be loaded. Defaults to 'IMAGENET'.
  160. learning_rate(float, optional): Learning rate for training. Defaults to .001.
  161. warmup_steps(int, optional): The number of steps of warm-up training. Defaults to 0.
  162. warmup_start_lr(float, optional): Start learning rate of warm-up training. Defaults to 0..
  163. lr_decay_epochs(list or tuple, optional): Epoch milestones for learning rate decay. Defaults to (216, 243).
  164. lr_decay_gamma(float, optional): Gamma coefficient of learning rate decay. Defaults to .1.
  165. metric({'VOC', 'COCO', None}, optional):
  166. Evaluation metric. If None, determine the metric according to the dataset format. Defaults to None.
  167. use_ema(bool, optional): Whether to use exponential moving average strategy. Defaults to False.
  168. early_stop(bool, optional): Whether to adopt early stop strategy. Defaults to False.
  169. early_stop_patience(int, optional): Early stop patience. Defaults to 5.
  170. use_vdl(bool, optional): Whether to use VisualDL to monitor the training process. Defaults to True.
  171. """
  172. if train_dataset.__class__.__name__ == 'VOCDetection':
  173. train_dataset.data_fields = {
  174. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  175. 'difficult'
  176. }
  177. elif train_dataset.__class__.__name__ == 'CocoDetection':
  178. if self.__class__.__name__ == 'MaskRCNN':
  179. train_dataset.data_fields = {
  180. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  181. 'gt_poly', 'is_crowd'
  182. }
  183. else:
  184. train_dataset.data_fields = {
  185. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  186. 'is_crowd'
  187. }
  188. if metric is None:
  189. if eval_dataset.__class__.__name__ == 'VOCDetection':
  190. self.metric = 'voc'
  191. elif eval_dataset.__class__.__name__ == 'CocoDetection':
  192. self.metric = 'coco'
  193. else:
  194. assert metric.lower() in ['coco', 'voc'], \
  195. "Evaluation metric {} is not supported, please choose form 'COCO' and 'VOC'"
  196. self.metric = metric.lower()
  197. self.labels = train_dataset.labels
  198. self.num_max_boxes = train_dataset.num_max_boxes
  199. train_dataset.batch_transforms = self._compose_batch_transform(
  200. train_dataset.transforms, mode='train')
  201. # build optimizer if not defined
  202. if optimizer is None:
  203. num_steps_each_epoch = len(train_dataset) // train_batch_size
  204. self.optimizer = self.default_optimizer(
  205. parameters=self.net.parameters(),
  206. learning_rate=learning_rate,
  207. warmup_steps=warmup_steps,
  208. warmup_start_lr=warmup_start_lr,
  209. lr_decay_epochs=lr_decay_epochs,
  210. lr_decay_gamma=lr_decay_gamma,
  211. num_steps_each_epoch=num_steps_each_epoch)
  212. else:
  213. self.optimizer = optimizer
  214. # initiate weights
  215. if pretrain_weights is not None and not osp.exists(pretrain_weights):
  216. if pretrain_weights not in det_pretrain_weights_dict['_'.join(
  217. [self.model_name, self.backbone_name])]:
  218. logging.warning(
  219. "Path of pretrain_weights('{}') does not exist!".format(
  220. pretrain_weights))
  221. pretrain_weights = det_pretrain_weights_dict['_'.join(
  222. [self.model_name, self.backbone_name])][0]
  223. logging.warning("Pretrain_weights is forcibly set to '{}'. "
  224. "If you don't want to use pretrain weights, "
  225. "set pretrain_weights to be None.".format(
  226. pretrain_weights))
  227. elif pretrain_weights is not None and osp.exists(pretrain_weights):
  228. if osp.splitext(pretrain_weights)[-1] != '.pdparams':
  229. logging.error(
  230. "Invalid pretrain weights. Please specify a '.pdparams' file.",
  231. exit=True)
  232. pretrained_dir = osp.join(save_dir, 'pretrain')
  233. self.net_initialize(
  234. pretrain_weights=pretrain_weights, save_dir=pretrained_dir)
  235. if use_ema:
  236. ema = ExponentialMovingAverage(
  237. decay=.9998, model=self.net, use_thres_step=True)
  238. else:
  239. ema = None
  240. # start train loop
  241. self.train_loop(
  242. num_epochs=num_epochs,
  243. train_dataset=train_dataset,
  244. train_batch_size=train_batch_size,
  245. eval_dataset=eval_dataset,
  246. save_interval_epochs=save_interval_epochs,
  247. log_interval_steps=log_interval_steps,
  248. save_dir=save_dir,
  249. ema=ema,
  250. early_stop=early_stop,
  251. early_stop_patience=early_stop_patience,
  252. use_vdl=use_vdl)
  253. def quant_aware_train(self,
  254. num_epochs,
  255. train_dataset,
  256. train_batch_size=64,
  257. eval_dataset=None,
  258. optimizer=None,
  259. save_interval_epochs=1,
  260. log_interval_steps=10,
  261. save_dir='output',
  262. learning_rate=.00001,
  263. warmup_steps=0,
  264. warmup_start_lr=0.0,
  265. lr_decay_epochs=(216, 243),
  266. lr_decay_gamma=0.1,
  267. metric=None,
  268. use_ema=False,
  269. early_stop=False,
  270. early_stop_patience=5,
  271. use_vdl=True,
  272. quant_config=None):
  273. """
  274. Quantization-aware training.
  275. Args:
  276. num_epochs(int): The number of epochs.
  277. train_dataset(paddlex.dataset): Training dataset.
  278. train_batch_size(int, optional): Total batch size among all cards used in training. Defaults to 64.
  279. eval_dataset(paddlex.dataset, optional):
  280. Evaluation dataset. If None, the model will not be evaluated during training process. Defaults to None.
  281. optimizer(paddle.optimizer.Optimizer or None, optional):
  282. Optimizer used for training. If None, a default optimizer is used. Defaults to None.
  283. save_interval_epochs(int, optional): Epoch interval for saving the model. Defaults to 1.
  284. log_interval_steps(int, optional): Step interval for printing training information. Defaults to 10.
  285. save_dir(str, optional): Directory to save the model. Defaults to 'output'.
  286. learning_rate(float, optional): Learning rate for training. Defaults to .001.
  287. warmup_steps(int, optional): The number of steps of warm-up training. Defaults to 0.
  288. warmup_start_lr(float, optional): Start learning rate of warm-up training. Defaults to 0..
  289. lr_decay_epochs(list or tuple, optional): Epoch milestones for learning rate decay. Defaults to (216, 243).
  290. lr_decay_gamma(float, optional): Gamma coefficient of learning rate decay. Defaults to .1.
  291. metric({'VOC', 'COCO', None}, optional):
  292. Evaluation metric. If None, determine the metric according to the dataset format. Defaults to None.
  293. use_ema(bool, optional): Whether to use exponential moving average strategy. Defaults to False.
  294. early_stop(bool, optional): Whether to adopt early stop strategy. Defaults to False.
  295. early_stop_patience(int, optional): Early stop patience. Defaults to 5.
  296. use_vdl(bool, optional): Whether to use VisualDL to monitor the training process. Defaults to True.
  297. quant_config(dict or None, optional): Quantization configuration. If None, a default rule of thumb
  298. configuration will be used. Defaults to None.
  299. """
  300. self._prepare_qat(quant_config)
  301. self.train(
  302. num_epochs=num_epochs,
  303. train_dataset=train_dataset,
  304. train_batch_size=train_batch_size,
  305. eval_dataset=eval_dataset,
  306. optimizer=optimizer,
  307. save_interval_epochs=save_interval_epochs,
  308. log_interval_steps=log_interval_steps,
  309. save_dir=save_dir,
  310. pretrain_weights=None,
  311. learning_rate=learning_rate,
  312. warmup_steps=warmup_steps,
  313. warmup_start_lr=warmup_start_lr,
  314. lr_decay_epochs=lr_decay_epochs,
  315. lr_decay_gamma=lr_decay_gamma,
  316. metric=metric,
  317. use_ema=use_ema,
  318. early_stop=early_stop,
  319. early_stop_patience=early_stop_patience,
  320. use_vdl=use_vdl)
  321. def evaluate(self,
  322. eval_dataset,
  323. batch_size=1,
  324. metric=None,
  325. return_details=False):
  326. """
  327. Evaluate the model.
  328. Args:
  329. eval_dataset(paddlex.dataset): Evaluation dataset.
  330. batch_size(int, optional): Total batch size among all cards used for evaluation. Defaults to 1.
  331. metric({'VOC', 'COCO', None}, optional):
  332. Evaluation metric. If None, determine the metric according to the dataset format. Defaults to None.
  333. return_details(bool, optional): Whether to return evaluation details. Defaults to False.
  334. Returns:
  335. collections.OrderedDict with key-value pairs: {"mAP(0.50, 11point)":`mean average precision`}.
  336. """
  337. if metric is None:
  338. if not hasattr(self, 'metric'):
  339. if eval_dataset.__class__.__name__ == 'VOCDetection':
  340. self.metric = 'voc'
  341. elif eval_dataset.__class__.__name__ == 'CocoDetection':
  342. self.metric = 'coco'
  343. else:
  344. assert metric.lower() in ['coco', 'voc'], \
  345. "Evaluation metric {} is not supported, please choose form 'COCO' and 'VOC'"
  346. self.metric = metric.lower()
  347. if self.metric == 'voc':
  348. eval_dataset.data_fields = {
  349. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  350. 'difficult'
  351. }
  352. elif self.metric == 'coco':
  353. if self.__class__.__name__ == 'MaskRCNN':
  354. eval_dataset.data_fields = {
  355. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  356. 'gt_poly', 'is_crowd'
  357. }
  358. else:
  359. eval_dataset.data_fields = {
  360. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  361. 'is_crowd'
  362. }
  363. eval_dataset.batch_transforms = self._compose_batch_transform(
  364. eval_dataset.transforms, mode='eval')
  365. arrange_transforms(
  366. model_type=self.model_type,
  367. transforms=eval_dataset.transforms,
  368. mode='eval')
  369. self.net.eval()
  370. nranks = paddle.distributed.get_world_size()
  371. local_rank = paddle.distributed.get_rank()
  372. if nranks > 1:
  373. # Initialize parallel environment if not done.
  374. if not paddle.distributed.parallel.parallel_helper._is_parallel_ctx_initialized(
  375. ):
  376. paddle.distributed.init_parallel_env()
  377. if batch_size > 1:
  378. logging.warning(
  379. "Detector only supports single card evaluation with batch_size=1 "
  380. "during evaluation, so batch_size is forcibly set to 1.")
  381. batch_size = 1
  382. if nranks < 2 or local_rank == 0:
  383. self.eval_data_loader = self.build_data_loader(
  384. eval_dataset, batch_size=batch_size, mode='eval')
  385. is_bbox_normalized = False
  386. if eval_dataset.batch_transforms is not None:
  387. is_bbox_normalized = any(
  388. isinstance(t, _NormalizeBox)
  389. for t in eval_dataset.batch_transforms.batch_transforms)
  390. if self.metric == 'voc':
  391. eval_metric = VOCMetric(
  392. labels=eval_dataset.labels,
  393. coco_gt=copy.deepcopy(eval_dataset.coco_gt),
  394. is_bbox_normalized=is_bbox_normalized,
  395. classwise=False)
  396. else:
  397. eval_metric = COCOMetric(
  398. coco_gt=copy.deepcopy(eval_dataset.coco_gt),
  399. classwise=False)
  400. scores = collections.OrderedDict()
  401. logging.info(
  402. "Start to evaluate(total_samples={}, total_steps={})...".
  403. format(eval_dataset.num_samples, eval_dataset.num_samples))
  404. with paddle.no_grad():
  405. for step, data in enumerate(self.eval_data_loader):
  406. outputs = self.run(self.net, data, 'eval')
  407. eval_metric.update(data, outputs)
  408. eval_metric.accumulate()
  409. self.eval_details = eval_metric.details
  410. scores.update(eval_metric.get())
  411. eval_metric.reset()
  412. if return_details:
  413. return scores, self.eval_details
  414. return scores
  415. def predict(self, img_file, transforms=None):
  416. """
  417. Do inference.
  418. Args:
  419. img_file(List[np.ndarray or str], str or np.ndarray): img_file(list or str or np.array):
  420. Image path or decoded image data in a BGR format, which also could constitute a list,
  421. meaning all images to be predicted as a mini-batch.
  422. transforms(paddlex.transforms.Compose or None, optional):
  423. Transforms for inputs. If None, the transforms for evaluation process will be used. Defaults to None.
  424. Returns:
  425. If img_file is a string or np.array, the result is a list of dict with key-value pairs:
  426. {"category_id": `category_id`, "category": `category`, "bbox": `[x, y, w, h]`, "score": `score`}.
  427. If img_file is a list, the result is a list composed of dicts with the corresponding fields:
  428. category_id(int): the predicted category ID. 0 represents the first category in the dataset, and so on.
  429. category(str): category name
  430. bbox(list): bounding box in [x, y, w, h] format
  431. score(str): confidence
  432. mask(dict): Only for instance segmentation task. Mask of the object in RLE format
  433. """
  434. if transforms is None and not hasattr(self, 'test_transforms'):
  435. raise Exception("transforms need to be defined, now is None.")
  436. if transforms is None:
  437. transforms = self.test_transforms
  438. if isinstance(img_file, (str, np.ndarray)):
  439. images = [img_file]
  440. else:
  441. images = img_file
  442. batch_samples = self._preprocess(images, transforms)
  443. self.net.eval()
  444. outputs = self.run(self.net, batch_samples, 'test')
  445. prediction = self._postprocess(outputs)
  446. if isinstance(img_file, (str, np.ndarray)):
  447. prediction = prediction[0]
  448. return prediction
  449. def _preprocess(self, images, transforms):
  450. arrange_transforms(
  451. model_type=self.model_type, transforms=transforms, mode='test')
  452. batch_samples = list()
  453. for im in images:
  454. sample = {'image': im}
  455. batch_samples.append(transforms(sample))
  456. batch_transforms = self._compose_batch_transform(transforms, 'test')
  457. batch_samples = batch_transforms(batch_samples)
  458. for k, v in batch_samples.items():
  459. batch_samples[k] = paddle.to_tensor(v)
  460. return batch_samples
  461. def _postprocess(self, batch_pred):
  462. infer_result = {}
  463. if 'bbox' in batch_pred:
  464. bboxes = batch_pred['bbox']
  465. bbox_nums = batch_pred['bbox_num']
  466. det_res = []
  467. k = 0
  468. for i in range(len(bbox_nums)):
  469. det_nums = bbox_nums[i]
  470. for j in range(det_nums):
  471. dt = bboxes[k]
  472. k = k + 1
  473. num_id, score, xmin, ymin, xmax, ymax = dt.tolist()
  474. if int(num_id) < 0:
  475. continue
  476. category = self.labels[int(num_id)]
  477. w = xmax - xmin
  478. h = ymax - ymin
  479. bbox = [xmin, ymin, w, h]
  480. dt_res = {
  481. 'category_id': int(num_id),
  482. 'category': category,
  483. 'bbox': bbox,
  484. 'score': score
  485. }
  486. det_res.append(dt_res)
  487. infer_result['bbox'] = det_res
  488. if 'mask' in batch_pred:
  489. masks = batch_pred['mask']
  490. bboxes = batch_pred['bbox']
  491. mask_nums = batch_pred['bbox_num']
  492. seg_res = []
  493. k = 0
  494. for i in range(len(mask_nums)):
  495. det_nums = mask_nums[i]
  496. for j in range(det_nums):
  497. mask = masks[k].astype(np.uint8)
  498. score = float(bboxes[k][1])
  499. label = int(bboxes[k][0])
  500. k = k + 1
  501. if label == -1:
  502. continue
  503. category = self.labels[int(label)]
  504. import pycocotools.mask as mask_util
  505. rle = mask_util.encode(
  506. np.array(
  507. mask[:, :, None], order="F", dtype="uint8"))[0]
  508. if six.PY3:
  509. if 'counts' in rle:
  510. rle['counts'] = rle['counts'].decode("utf8")
  511. sg_res = {
  512. 'category_id': int(label),
  513. 'category': category,
  514. 'mask': rle,
  515. 'score': score
  516. }
  517. seg_res.append(sg_res)
  518. infer_result['mask'] = seg_res
  519. bbox_num = batch_pred['bbox_num']
  520. results = []
  521. start = 0
  522. for num in bbox_num:
  523. end = start + num
  524. curr_res = infer_result['bbox'][start:end]
  525. if 'mask' in infer_result:
  526. mask_res = infer_result['mask'][start:end]
  527. for box, mask in zip(curr_res, mask_res):
  528. box.update(mask)
  529. results.append(curr_res)
  530. start = end
  531. return results
  532. class YOLOv3(BaseDetector):
  533. def __init__(self,
  534. num_classes=80,
  535. backbone='MobileNetV1',
  536. anchors=[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  537. [59, 119], [116, 90], [156, 198], [373, 326]],
  538. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  539. ignore_threshold=0.7,
  540. nms_score_threshold=0.01,
  541. nms_topk=1000,
  542. nms_keep_topk=100,
  543. nms_iou_threshold=0.45,
  544. label_smooth=False):
  545. self.init_params = locals()
  546. if backbone not in [
  547. 'MobileNetV1', 'MobileNetV1_ssld', 'MobileNetV3',
  548. 'MobileNetV3_ssld', 'DarkNet53', 'ResNet50_vd_dcn', 'ResNet34'
  549. ]:
  550. raise ValueError(
  551. "backbone: {} is not supported. Please choose one of "
  552. "('MobileNetV1', 'MobileNetV1_ssld', 'MobileNetV3', 'MobileNetV3_ssld', 'DarkNet53', 'ResNet50_vd_dcn', 'ResNet34')".
  553. format(backbone))
  554. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  555. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  556. norm_type = 'sync_bn'
  557. else:
  558. norm_type = 'bn'
  559. self.backbone_name = backbone
  560. if 'MobileNetV1' in backbone:
  561. norm_type = 'bn'
  562. backbone = self._get_backbone('MobileNet', norm_type=norm_type)
  563. elif 'MobileNetV3' in backbone:
  564. backbone = self._get_backbone(
  565. 'MobileNetV3', norm_type=norm_type, feature_maps=[7, 13, 16])
  566. elif backbone == 'ResNet50_vd_dcn':
  567. backbone = self._get_backbone(
  568. 'ResNet',
  569. norm_type=norm_type,
  570. variant='d',
  571. return_idx=[1, 2, 3],
  572. dcn_v2_stages=[3],
  573. freeze_at=-1,
  574. freeze_norm=False)
  575. elif backbone == 'ResNet34':
  576. backbone = self._get_backbone(
  577. 'ResNet',
  578. depth=34,
  579. norm_type=norm_type,
  580. return_idx=[1, 2, 3],
  581. freeze_at=-1,
  582. freeze_norm=False,
  583. norm_decay=0.)
  584. else:
  585. backbone = self._get_backbone('DarkNet', norm_type=norm_type)
  586. neck = ppdet.modeling.YOLOv3FPN(
  587. norm_type=norm_type,
  588. in_channels=[i.channels for i in backbone.out_shape])
  589. loss = ppdet.modeling.YOLOv3Loss(
  590. num_classes=num_classes,
  591. ignore_thresh=ignore_threshold,
  592. label_smooth=label_smooth)
  593. yolo_head = ppdet.modeling.YOLOv3Head(
  594. in_channels=[i.channels for i in neck.out_shape],
  595. anchors=anchors,
  596. anchor_masks=anchor_masks,
  597. num_classes=num_classes,
  598. loss=loss)
  599. post_process = ppdet.modeling.BBoxPostProcess(
  600. decode=ppdet.modeling.YOLOBox(num_classes=num_classes),
  601. nms=ppdet.modeling.MultiClassNMS(
  602. score_threshold=nms_score_threshold,
  603. nms_top_k=nms_topk,
  604. keep_top_k=nms_keep_topk,
  605. nms_threshold=nms_iou_threshold))
  606. params = {
  607. 'backbone': backbone,
  608. 'neck': neck,
  609. 'yolo_head': yolo_head,
  610. 'post_process': post_process
  611. }
  612. super(YOLOv3, self).__init__(
  613. model_name='YOLOv3', num_classes=num_classes, **params)
  614. self.anchors = anchors
  615. self.anchor_masks = anchor_masks
  616. def _compose_batch_transform(self, transforms, mode='train'):
  617. if mode == 'train':
  618. default_batch_transforms = [
  619. _BatchPadding(pad_to_stride=-1), _NormalizeBox(),
  620. _PadBox(getattr(self, 'num_max_boxes', 50)), _BboxXYXY2XYWH(),
  621. _Gt2YoloTarget(
  622. anchor_masks=self.anchor_masks,
  623. anchors=self.anchors,
  624. downsample_ratios=getattr(self, 'downsample_ratios',
  625. [32, 16, 8]),
  626. num_classes=self.num_classes)
  627. ]
  628. else:
  629. default_batch_transforms = [_BatchPadding(pad_to_stride=-1)]
  630. if mode == 'eval' and self.metric == 'voc':
  631. collate_batch = False
  632. else:
  633. collate_batch = True
  634. custom_batch_transforms = []
  635. for i, op in enumerate(transforms.transforms):
  636. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  637. if mode != 'train':
  638. raise Exception(
  639. "{} cannot be present in the {} transforms. ".format(
  640. op.__class__.__name__, mode) +
  641. "Please check the {} transforms.".format(mode))
  642. custom_batch_transforms.insert(0, copy.deepcopy(op))
  643. batch_transforms = BatchCompose(
  644. custom_batch_transforms + default_batch_transforms,
  645. collate_batch=collate_batch)
  646. return batch_transforms
  647. def _fix_transforms_shape(self, image_shape):
  648. if hasattr(self, 'test_transforms'):
  649. if self.test_transforms is not None:
  650. has_resize_op = False
  651. resize_op_idx = -1
  652. normalize_op_idx = len(self.test_transforms.transforms)
  653. for idx, op in enumerate(self.test_transforms.transforms):
  654. name = op.__class__.__name__
  655. if name == 'Resize':
  656. has_resize_op = True
  657. resize_op_idx = idx
  658. if name == 'Normalize':
  659. normalize_op_idx = idx
  660. if not has_resize_op:
  661. self.test_transforms.transforms.insert(
  662. normalize_op_idx,
  663. Resize(
  664. target_size=image_shape, interp='CUBIC'))
  665. else:
  666. self.test_transforms.transforms[
  667. resize_op_idx].target_size = image_shape
  668. class FasterRCNN(BaseDetector):
  669. def __init__(self,
  670. num_classes=80,
  671. backbone='ResNet50',
  672. with_fpn=True,
  673. with_dcn=False,
  674. aspect_ratios=[0.5, 1.0, 2.0],
  675. anchor_sizes=[[32], [64], [128], [256], [512]],
  676. keep_top_k=100,
  677. nms_threshold=0.5,
  678. score_threshold=0.05,
  679. fpn_num_channels=256,
  680. rpn_batch_size_per_im=256,
  681. rpn_fg_fraction=0.5,
  682. test_pre_nms_top_n=None,
  683. test_post_nms_top_n=1000):
  684. self.init_params = locals()
  685. if backbone not in [
  686. 'ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet34',
  687. 'ResNet34_vd', 'ResNet101', 'ResNet101_vd', 'HRNet_W18'
  688. ]:
  689. raise ValueError(
  690. "backbone: {} is not supported. Please choose one of "
  691. "('ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet34', 'ResNet34_vd', "
  692. "'ResNet101', 'ResNet101_vd', 'HRNet_W18')".format(backbone))
  693. self.backbone_name = backbone
  694. dcn_v2_stages = [1, 2, 3] if with_dcn else [-1]
  695. if backbone == 'HRNet_W18':
  696. if not with_fpn:
  697. logging.warning(
  698. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  699. format(backbone))
  700. with_fpn = True
  701. if with_dcn:
  702. logging.warning(
  703. "Backbone {} should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  704. format(backbone))
  705. backbone = self._get_backbone(
  706. 'HRNet', width=18, freeze_at=0, return_idx=[0, 1, 2, 3])
  707. elif backbone == 'ResNet50_vd_ssld':
  708. if not with_fpn:
  709. logging.warning(
  710. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  711. format(backbone))
  712. with_fpn = True
  713. backbone = self._get_backbone(
  714. 'ResNet',
  715. variant='d',
  716. norm_type='bn',
  717. freeze_at=0,
  718. return_idx=[0, 1, 2, 3],
  719. num_stages=4,
  720. lr_mult_list=[0.05, 0.05, 0.1, 0.15],
  721. dcn_v2_stages=dcn_v2_stages)
  722. elif 'ResNet50' in backbone:
  723. if with_fpn:
  724. backbone = self._get_backbone(
  725. 'ResNet',
  726. variant='d' if '_vd' in backbone else 'b',
  727. norm_type='bn',
  728. freeze_at=0,
  729. return_idx=[0, 1, 2, 3],
  730. num_stages=4,
  731. dcn_v2_stages=dcn_v2_stages)
  732. else:
  733. if with_dcn:
  734. logging.warning(
  735. "Backbone {} without fpn should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  736. format(backbone))
  737. backbone = self._get_backbone(
  738. 'ResNet',
  739. variant='d' if '_vd' in backbone else 'b',
  740. norm_type='bn',
  741. freeze_at=0,
  742. return_idx=[2],
  743. num_stages=3)
  744. elif 'ResNet34' in backbone:
  745. if not with_fpn:
  746. logging.warning(
  747. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  748. format(backbone))
  749. with_fpn = True
  750. backbone = self._get_backbone(
  751. 'ResNet',
  752. depth=34,
  753. variant='d' if 'vd' in backbone else 'b',
  754. norm_type='bn',
  755. freeze_at=0,
  756. return_idx=[0, 1, 2, 3],
  757. num_stages=4,
  758. dcn_v2_stages=dcn_v2_stages)
  759. else:
  760. if not with_fpn:
  761. logging.warning(
  762. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  763. format(backbone))
  764. with_fpn = True
  765. backbone = self._get_backbone(
  766. 'ResNet',
  767. depth=101,
  768. variant='d' if 'vd' in backbone else 'b',
  769. norm_type='bn',
  770. freeze_at=0,
  771. return_idx=[0, 1, 2, 3],
  772. num_stages=4,
  773. dcn_v2_stages=dcn_v2_stages)
  774. rpn_in_channel = backbone.out_shape[0].channels
  775. if with_fpn:
  776. self.backbone_name = self.backbone_name + '_fpn'
  777. if 'HRNet' in self.backbone_name:
  778. neck = ppdet.modeling.HRFPN(
  779. in_channels=[i.channels for i in backbone.out_shape],
  780. out_channel=fpn_num_channels,
  781. spatial_scales=[
  782. 1.0 / i.stride for i in backbone.out_shape
  783. ],
  784. share_conv=False)
  785. else:
  786. neck = ppdet.modeling.FPN(
  787. in_channels=[i.channels for i in backbone.out_shape],
  788. out_channel=fpn_num_channels,
  789. spatial_scales=[
  790. 1.0 / i.stride for i in backbone.out_shape
  791. ])
  792. rpn_in_channel = neck.out_shape[0].channels
  793. anchor_generator_cfg = {
  794. 'aspect_ratios': aspect_ratios,
  795. 'anchor_sizes': anchor_sizes,
  796. 'strides': [4, 8, 16, 32, 64]
  797. }
  798. train_proposal_cfg = {
  799. 'min_size': 0.0,
  800. 'nms_thresh': .7,
  801. 'pre_nms_top_n': 2000,
  802. 'post_nms_top_n': 1000,
  803. 'topk_after_collect': True
  804. }
  805. test_proposal_cfg = {
  806. 'min_size': 0.0,
  807. 'nms_thresh': .7,
  808. 'pre_nms_top_n': 1000
  809. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  810. 'post_nms_top_n': test_post_nms_top_n
  811. }
  812. head = ppdet.modeling.TwoFCHead(
  813. in_channel=neck.out_shape[0].channels, out_channel=1024)
  814. roi_extractor_cfg = {
  815. 'resolution': 7,
  816. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  817. 'sampling_ratio': 0,
  818. 'aligned': True
  819. }
  820. with_pool = False
  821. else:
  822. neck = None
  823. anchor_generator_cfg = {
  824. 'aspect_ratios': aspect_ratios,
  825. 'anchor_sizes': anchor_sizes,
  826. 'strides': [16]
  827. }
  828. train_proposal_cfg = {
  829. 'min_size': 0.0,
  830. 'nms_thresh': .7,
  831. 'pre_nms_top_n': 12000,
  832. 'post_nms_top_n': 2000,
  833. 'topk_after_collect': False
  834. }
  835. test_proposal_cfg = {
  836. 'min_size': 0.0,
  837. 'nms_thresh': .7,
  838. 'pre_nms_top_n': 6000
  839. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  840. 'post_nms_top_n': test_post_nms_top_n
  841. }
  842. head = ppdet.modeling.Res5Head()
  843. roi_extractor_cfg = {
  844. 'resolution': 14,
  845. 'spatial_scale': [1. / i.stride for i in backbone.out_shape],
  846. 'sampling_ratio': 0,
  847. 'aligned': True
  848. }
  849. with_pool = True
  850. rpn_target_assign_cfg = {
  851. 'batch_size_per_im': rpn_batch_size_per_im,
  852. 'fg_fraction': rpn_fg_fraction,
  853. 'negative_overlap': .3,
  854. 'positive_overlap': .7,
  855. 'use_random': True
  856. }
  857. rpn_head = ppdet.modeling.RPNHead(
  858. anchor_generator=anchor_generator_cfg,
  859. rpn_target_assign=rpn_target_assign_cfg,
  860. train_proposal=train_proposal_cfg,
  861. test_proposal=test_proposal_cfg,
  862. in_channel=rpn_in_channel)
  863. bbox_assigner = BBoxAssigner(num_classes=num_classes)
  864. bbox_head = ppdet.modeling.BBoxHead(
  865. head=head,
  866. in_channel=head.out_shape[0].channels,
  867. roi_extractor=roi_extractor_cfg,
  868. with_pool=with_pool,
  869. bbox_assigner=bbox_assigner,
  870. num_classes=num_classes)
  871. bbox_post_process = ppdet.modeling.BBoxPostProcess(
  872. num_classes=num_classes,
  873. decode=ppdet.modeling.RCNNBox(num_classes=num_classes),
  874. nms=ppdet.modeling.MultiClassNMS(
  875. score_threshold=score_threshold,
  876. keep_top_k=keep_top_k,
  877. nms_threshold=nms_threshold))
  878. params = {
  879. 'backbone': backbone,
  880. 'neck': neck,
  881. 'rpn_head': rpn_head,
  882. 'bbox_head': bbox_head,
  883. 'bbox_post_process': bbox_post_process
  884. }
  885. self.with_fpn = with_fpn
  886. super(FasterRCNN, self).__init__(
  887. model_name='FasterRCNN', num_classes=num_classes, **params)
  888. def _compose_batch_transform(self, transforms, mode='train'):
  889. if mode == 'train':
  890. default_batch_transforms = [
  891. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  892. ]
  893. collate_batch = False
  894. else:
  895. default_batch_transforms = [
  896. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  897. ]
  898. collate_batch = True
  899. custom_batch_transforms = []
  900. for i, op in enumerate(transforms.transforms):
  901. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  902. if mode != 'train':
  903. raise Exception(
  904. "{} cannot be present in the {} transforms. ".format(
  905. op.__class__.__name__, mode) +
  906. "Please check the {} transforms.".format(mode))
  907. custom_batch_transforms.insert(0, copy.deepcopy(op))
  908. batch_transforms = BatchCompose(
  909. custom_batch_transforms + default_batch_transforms,
  910. collate_batch=collate_batch)
  911. return batch_transforms
  912. def _fix_transforms_shape(self, image_shape):
  913. if hasattr(self, 'test_transforms'):
  914. if self.test_transforms is not None:
  915. has_resize_op = False
  916. resize_op_idx = -1
  917. normalize_op_idx = len(self.test_transforms.transforms)
  918. for idx, op in enumerate(self.test_transforms.transforms):
  919. name = op.__class__.__name__
  920. if name == 'ResizeByShort':
  921. has_resize_op = True
  922. resize_op_idx = idx
  923. if name == 'Normalize':
  924. normalize_op_idx = idx
  925. if not has_resize_op:
  926. self.test_transforms.transforms.insert(
  927. normalize_op_idx,
  928. Resize(
  929. target_size=image_shape,
  930. keep_ratio=True,
  931. interp='CUBIC'))
  932. else:
  933. self.test_transforms.transforms[resize_op_idx] = Resize(
  934. target_size=image_shape,
  935. keep_ratio=True,
  936. interp='CUBIC')
  937. self.test_transforms.transforms.append(
  938. Padding(im_padding_value=[0., 0., 0.]))
  939. def _get_test_inputs(self, image_shape):
  940. if image_shape is not None:
  941. image_shape = self._check_image_shape(image_shape)
  942. self._fix_transforms_shape(image_shape[-2:])
  943. else:
  944. image_shape = [None, 3, -1, -1]
  945. if self.with_fpn:
  946. self.test_transforms.transforms.append(
  947. Padding(im_padding_value=[0., 0., 0.]))
  948. self.fixed_input_shape = image_shape
  949. return self._define_input_spec(image_shape)
  950. class PPYOLO(YOLOv3):
  951. def __init__(self,
  952. num_classes=80,
  953. backbone='ResNet50_vd_dcn',
  954. anchors=None,
  955. anchor_masks=None,
  956. use_coord_conv=True,
  957. use_iou_aware=True,
  958. use_spp=True,
  959. use_drop_block=True,
  960. scale_x_y=1.05,
  961. ignore_threshold=0.7,
  962. label_smooth=False,
  963. use_iou_loss=True,
  964. use_matrix_nms=True,
  965. nms_score_threshold=0.01,
  966. nms_topk=-1,
  967. nms_keep_topk=100,
  968. nms_iou_threshold=0.45):
  969. self.init_params = locals()
  970. if backbone not in [
  971. 'ResNet50_vd_dcn', 'ResNet18_vd', 'MobileNetV3_large',
  972. 'MobileNetV3_small'
  973. ]:
  974. raise ValueError(
  975. "backbone: {} is not supported. Please choose one of "
  976. "('ResNet50_vd_dcn', 'ResNet18_vd', 'MobileNetV3_large', 'MobileNetV3_small')".
  977. format(backbone))
  978. self.backbone_name = backbone
  979. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  980. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  981. norm_type = 'sync_bn'
  982. else:
  983. norm_type = 'bn'
  984. if anchors is None and anchor_masks is None:
  985. if 'MobileNetV3' in backbone:
  986. anchors = [[11, 18], [34, 47], [51, 126], [115, 71],
  987. [120, 195], [254, 235]]
  988. anchor_masks = [[3, 4, 5], [0, 1, 2]]
  989. elif backbone == 'ResNet50_vd_dcn':
  990. anchors = [[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  991. [59, 119], [116, 90], [156, 198], [373, 326]]
  992. anchor_masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
  993. else:
  994. anchors = [[10, 14], [23, 27], [37, 58], [81, 82], [135, 169],
  995. [344, 319]]
  996. anchor_masks = [[3, 4, 5], [0, 1, 2]]
  997. elif anchors is None or anchor_masks is None:
  998. raise ValueError("Please define both anchors and anchor_masks.")
  999. if backbone == 'ResNet50_vd_dcn':
  1000. backbone = self._get_backbone(
  1001. 'ResNet',
  1002. variant='d',
  1003. norm_type=norm_type,
  1004. return_idx=[1, 2, 3],
  1005. dcn_v2_stages=[3],
  1006. freeze_at=-1,
  1007. freeze_norm=False,
  1008. norm_decay=0.)
  1009. downsample_ratios = [32, 16, 8]
  1010. elif backbone == 'ResNet18_vd':
  1011. backbone = self._get_backbone(
  1012. 'ResNet',
  1013. depth=18,
  1014. variant='d',
  1015. norm_type=norm_type,
  1016. return_idx=[2, 3],
  1017. freeze_at=-1,
  1018. freeze_norm=False,
  1019. norm_decay=0.)
  1020. downsample_ratios = [32, 16, 8]
  1021. elif backbone == 'MobileNetV3_large':
  1022. backbone = self._get_backbone(
  1023. 'MobileNetV3',
  1024. model_name='large',
  1025. norm_type=norm_type,
  1026. scale=1,
  1027. with_extra_blocks=False,
  1028. extra_block_filters=[],
  1029. feature_maps=[13, 16])
  1030. downsample_ratios = [32, 16]
  1031. elif backbone == 'MobileNetV3_small':
  1032. backbone = self._get_backbone(
  1033. 'MobileNetV3',
  1034. model_name='small',
  1035. norm_type=norm_type,
  1036. scale=1,
  1037. with_extra_blocks=False,
  1038. extra_block_filters=[],
  1039. feature_maps=[9, 12])
  1040. downsample_ratios = [32, 16]
  1041. neck = ppdet.modeling.PPYOLOFPN(
  1042. norm_type=norm_type,
  1043. in_channels=[i.channels for i in backbone.out_shape],
  1044. coord_conv=use_coord_conv,
  1045. drop_block=use_drop_block,
  1046. spp=use_spp,
  1047. conv_block_num=0 if ('MobileNetV3' in self.backbone_name or
  1048. self.backbone_name == 'ResNet18_vd') else 2)
  1049. loss = ppdet.modeling.YOLOv3Loss(
  1050. num_classes=num_classes,
  1051. ignore_thresh=ignore_threshold,
  1052. downsample=downsample_ratios,
  1053. label_smooth=label_smooth,
  1054. scale_x_y=scale_x_y,
  1055. iou_loss=ppdet.modeling.IouLoss(
  1056. loss_weight=2.5, loss_square=True) if use_iou_loss else None,
  1057. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1058. if use_iou_aware else None)
  1059. yolo_head = ppdet.modeling.YOLOv3Head(
  1060. in_channels=[i.channels for i in neck.out_shape],
  1061. anchors=anchors,
  1062. anchor_masks=anchor_masks,
  1063. num_classes=num_classes,
  1064. loss=loss,
  1065. iou_aware=use_iou_aware)
  1066. if use_matrix_nms:
  1067. nms = ppdet.modeling.MatrixNMS(
  1068. keep_top_k=nms_keep_topk,
  1069. score_threshold=nms_score_threshold,
  1070. post_threshold=.05
  1071. if 'MobileNetV3' in self.backbone_name else .01,
  1072. nms_top_k=nms_topk,
  1073. background_label=-1)
  1074. else:
  1075. nms = ppdet.modeling.MultiClassNMS(
  1076. score_threshold=nms_score_threshold,
  1077. nms_top_k=nms_topk,
  1078. keep_top_k=nms_keep_topk,
  1079. nms_threshold=nms_iou_threshold)
  1080. post_process = ppdet.modeling.BBoxPostProcess(
  1081. decode=ppdet.modeling.YOLOBox(
  1082. num_classes=num_classes,
  1083. conf_thresh=.005
  1084. if 'MobileNetV3' in self.backbone_name else .01,
  1085. scale_x_y=scale_x_y),
  1086. nms=nms)
  1087. params = {
  1088. 'backbone': backbone,
  1089. 'neck': neck,
  1090. 'yolo_head': yolo_head,
  1091. 'post_process': post_process
  1092. }
  1093. super(YOLOv3, self).__init__(
  1094. model_name='YOLOv3', num_classes=num_classes, **params)
  1095. self.anchors = anchors
  1096. self.anchor_masks = anchor_masks
  1097. self.downsample_ratios = downsample_ratios
  1098. self.model_name = 'PPYOLO'
  1099. class PPYOLOTiny(YOLOv3):
  1100. def __init__(self,
  1101. num_classes=80,
  1102. backbone='MobileNetV3',
  1103. anchors=[[10, 15], [24, 36], [72, 42], [35, 87], [102, 96],
  1104. [60, 170], [220, 125], [128, 222], [264, 266]],
  1105. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  1106. use_iou_aware=False,
  1107. use_spp=True,
  1108. use_drop_block=True,
  1109. scale_x_y=1.05,
  1110. ignore_threshold=0.5,
  1111. label_smooth=False,
  1112. use_iou_loss=True,
  1113. use_matrix_nms=False,
  1114. nms_score_threshold=0.005,
  1115. nms_topk=1000,
  1116. nms_keep_topk=100,
  1117. nms_iou_threshold=0.45):
  1118. self.init_params = locals()
  1119. if backbone != 'MobileNetV3':
  1120. logging.warning(
  1121. "PPYOLOTiny only supports MobileNetV3 as backbone. "
  1122. "Backbone is forcibly set to MobileNetV3.")
  1123. self.backbone_name = 'MobileNetV3'
  1124. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1125. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1126. norm_type = 'sync_bn'
  1127. else:
  1128. norm_type = 'bn'
  1129. backbone = self._get_backbone(
  1130. 'MobileNetV3',
  1131. model_name='large',
  1132. norm_type=norm_type,
  1133. scale=.5,
  1134. with_extra_blocks=False,
  1135. extra_block_filters=[],
  1136. feature_maps=[7, 13, 16])
  1137. downsample_ratios = [32, 16, 8]
  1138. neck = ppdet.modeling.PPYOLOTinyFPN(
  1139. detection_block_channels=[160, 128, 96],
  1140. in_channels=[i.channels for i in backbone.out_shape],
  1141. spp=use_spp,
  1142. drop_block=use_drop_block)
  1143. loss = ppdet.modeling.YOLOv3Loss(
  1144. num_classes=num_classes,
  1145. ignore_thresh=ignore_threshold,
  1146. downsample=downsample_ratios,
  1147. label_smooth=label_smooth,
  1148. scale_x_y=scale_x_y,
  1149. iou_loss=ppdet.modeling.IouLoss(
  1150. loss_weight=2.5, loss_square=True) if use_iou_loss else None,
  1151. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1152. if use_iou_aware else None)
  1153. yolo_head = ppdet.modeling.YOLOv3Head(
  1154. in_channels=[i.channels for i in neck.out_shape],
  1155. anchors=anchors,
  1156. anchor_masks=anchor_masks,
  1157. num_classes=num_classes,
  1158. loss=loss,
  1159. iou_aware=use_iou_aware)
  1160. if use_matrix_nms:
  1161. nms = ppdet.modeling.MatrixNMS(
  1162. keep_top_k=nms_keep_topk,
  1163. score_threshold=nms_score_threshold,
  1164. post_threshold=.05,
  1165. nms_top_k=nms_topk,
  1166. background_label=-1)
  1167. else:
  1168. nms = ppdet.modeling.MultiClassNMS(
  1169. score_threshold=nms_score_threshold,
  1170. nms_top_k=nms_topk,
  1171. keep_top_k=nms_keep_topk,
  1172. nms_threshold=nms_iou_threshold)
  1173. post_process = ppdet.modeling.BBoxPostProcess(
  1174. decode=ppdet.modeling.YOLOBox(
  1175. num_classes=num_classes,
  1176. conf_thresh=.005,
  1177. downsample_ratio=32,
  1178. clip_bbox=True,
  1179. scale_x_y=scale_x_y),
  1180. nms=nms)
  1181. params = {
  1182. 'backbone': backbone,
  1183. 'neck': neck,
  1184. 'yolo_head': yolo_head,
  1185. 'post_process': post_process
  1186. }
  1187. super(YOLOv3, self).__init__(
  1188. model_name='YOLOv3', num_classes=num_classes, **params)
  1189. self.anchors = anchors
  1190. self.anchor_masks = anchor_masks
  1191. self.downsample_ratios = downsample_ratios
  1192. self.model_name = 'PPYOLOTiny'
  1193. class PPYOLOv2(YOLOv3):
  1194. def __init__(self,
  1195. num_classes=80,
  1196. backbone='ResNet50_vd_dcn',
  1197. anchors=[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  1198. [59, 119], [116, 90], [156, 198], [373, 326]],
  1199. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  1200. use_iou_aware=True,
  1201. use_spp=True,
  1202. use_drop_block=True,
  1203. scale_x_y=1.05,
  1204. ignore_threshold=0.7,
  1205. label_smooth=False,
  1206. use_iou_loss=True,
  1207. use_matrix_nms=True,
  1208. nms_score_threshold=0.01,
  1209. nms_topk=-1,
  1210. nms_keep_topk=100,
  1211. nms_iou_threshold=0.45):
  1212. self.init_params = locals()
  1213. if backbone not in ['ResNet50_vd_dcn', 'ResNet101_vd_dcn']:
  1214. raise ValueError(
  1215. "backbone: {} is not supported. Please choose one of "
  1216. "('ResNet50_vd_dcn', 'ResNet18_vd')".format(backbone))
  1217. self.backbone_name = backbone
  1218. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1219. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1220. norm_type = 'sync_bn'
  1221. else:
  1222. norm_type = 'bn'
  1223. if backbone == 'ResNet50_vd_dcn':
  1224. backbone = self._get_backbone(
  1225. 'ResNet',
  1226. variant='d',
  1227. norm_type=norm_type,
  1228. return_idx=[1, 2, 3],
  1229. dcn_v2_stages=[3],
  1230. freeze_at=-1,
  1231. freeze_norm=False,
  1232. norm_decay=0.)
  1233. downsample_ratios = [32, 16, 8]
  1234. elif backbone == 'ResNet101_vd_dcn':
  1235. backbone = self._get_backbone(
  1236. 'ResNet',
  1237. depth=101,
  1238. variant='d',
  1239. norm_type=norm_type,
  1240. return_idx=[1, 2, 3],
  1241. dcn_v2_stages=[3],
  1242. freeze_at=-1,
  1243. freeze_norm=False,
  1244. norm_decay=0.)
  1245. downsample_ratios = [32, 16, 8]
  1246. neck = ppdet.modeling.PPYOLOPAN(
  1247. norm_type=norm_type,
  1248. in_channels=[i.channels for i in backbone.out_shape],
  1249. drop_block=use_drop_block,
  1250. block_size=3,
  1251. keep_prob=.9,
  1252. spp=use_spp)
  1253. loss = ppdet.modeling.YOLOv3Loss(
  1254. num_classes=num_classes,
  1255. ignore_thresh=ignore_threshold,
  1256. downsample=downsample_ratios,
  1257. label_smooth=label_smooth,
  1258. scale_x_y=scale_x_y,
  1259. iou_loss=ppdet.modeling.IouLoss(
  1260. loss_weight=2.5, loss_square=True) if use_iou_loss else None,
  1261. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1262. if use_iou_aware else None)
  1263. yolo_head = ppdet.modeling.YOLOv3Head(
  1264. in_channels=[i.channels for i in neck.out_shape],
  1265. anchors=anchors,
  1266. anchor_masks=anchor_masks,
  1267. num_classes=num_classes,
  1268. loss=loss,
  1269. iou_aware=use_iou_aware,
  1270. iou_aware_factor=.5)
  1271. if use_matrix_nms:
  1272. nms = ppdet.modeling.MatrixNMS(
  1273. keep_top_k=nms_keep_topk,
  1274. score_threshold=nms_score_threshold,
  1275. post_threshold=.01,
  1276. nms_top_k=nms_topk,
  1277. background_label=-1)
  1278. else:
  1279. nms = ppdet.modeling.MultiClassNMS(
  1280. score_threshold=nms_score_threshold,
  1281. nms_top_k=nms_topk,
  1282. keep_top_k=nms_keep_topk,
  1283. nms_threshold=nms_iou_threshold)
  1284. post_process = ppdet.modeling.BBoxPostProcess(
  1285. decode=ppdet.modeling.YOLOBox(
  1286. num_classes=num_classes,
  1287. conf_thresh=.01,
  1288. downsample_ratio=32,
  1289. clip_bbox=True,
  1290. scale_x_y=scale_x_y),
  1291. nms=nms)
  1292. params = {
  1293. 'backbone': backbone,
  1294. 'neck': neck,
  1295. 'yolo_head': yolo_head,
  1296. 'post_process': post_process
  1297. }
  1298. super(YOLOv3, self).__init__(
  1299. model_name='YOLOv3', num_classes=num_classes, **params)
  1300. self.anchors = anchors
  1301. self.anchor_masks = anchor_masks
  1302. self.downsample_ratios = downsample_ratios
  1303. self.model_name = 'PPYOLOv2'
  1304. def _get_test_inputs(self, image_shape):
  1305. if image_shape is not None:
  1306. image_shape = self._check_image_shape(image_shape)
  1307. self._fix_transforms_shape(image_shape[-2:])
  1308. else:
  1309. image_shape = [None, 3, 608, 608]
  1310. logging.warning(
  1311. '[Important!!!] When exporting inference model for {},'.format(
  1312. self.__class__.__name__) +
  1313. ' if fixed_input_shape is not set, it will be forcibly set to [None, 3, 608, 608]. '
  1314. +
  1315. 'Please check image shape after transforms is [3, 608, 608], if not, fixed_input_shape '
  1316. + 'should be specified manually.')
  1317. self.fixed_input_shape = image_shape
  1318. return self._define_input_spec(image_shape)
  1319. class MaskRCNN(BaseDetector):
  1320. def __init__(self,
  1321. num_classes=80,
  1322. backbone='ResNet50_vd',
  1323. with_fpn=True,
  1324. with_dcn=False,
  1325. aspect_ratios=[0.5, 1.0, 2.0],
  1326. anchor_sizes=[[32], [64], [128], [256], [512]],
  1327. keep_top_k=100,
  1328. nms_threshold=0.5,
  1329. score_threshold=0.05,
  1330. fpn_num_channels=256,
  1331. rpn_batch_size_per_im=256,
  1332. rpn_fg_fraction=0.5,
  1333. test_pre_nms_top_n=None,
  1334. test_post_nms_top_n=1000):
  1335. self.init_params = locals()
  1336. if backbone not in [
  1337. 'ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet101',
  1338. 'ResNet101_vd'
  1339. ]:
  1340. raise ValueError(
  1341. "backbone: {} is not supported. Please choose one of "
  1342. "('ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet101', 'ResNet101_vd')".
  1343. format(backbone))
  1344. self.backbone_name = backbone + '_fpn' if with_fpn else backbone
  1345. dcn_v2_stages = [1, 2, 3] if with_dcn else [-1]
  1346. if backbone == 'ResNet50':
  1347. if with_fpn:
  1348. backbone = self._get_backbone(
  1349. 'ResNet',
  1350. norm_type='bn',
  1351. freeze_at=0,
  1352. return_idx=[0, 1, 2, 3],
  1353. num_stages=4,
  1354. dcn_v2_stages=dcn_v2_stages)
  1355. else:
  1356. if with_dcn:
  1357. logging.warning(
  1358. "Backbone {} should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  1359. format(backbone))
  1360. backbone = self._get_backbone(
  1361. 'ResNet',
  1362. norm_type='bn',
  1363. freeze_at=0,
  1364. return_idx=[2],
  1365. num_stages=3)
  1366. elif 'ResNet50_vd' in backbone:
  1367. if not with_fpn:
  1368. logging.warning(
  1369. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  1370. format(backbone))
  1371. with_fpn = True
  1372. backbone = self._get_backbone(
  1373. 'ResNet',
  1374. variant='d',
  1375. norm_type='bn',
  1376. freeze_at=0,
  1377. return_idx=[0, 1, 2, 3],
  1378. num_stages=4,
  1379. lr_mult_list=[0.05, 0.05, 0.1, 0.15]
  1380. if '_ssld' in backbone else [1.0, 1.0, 1.0, 1.0],
  1381. dcn_v2_stages=dcn_v2_stages)
  1382. else:
  1383. if not with_fpn:
  1384. logging.warning(
  1385. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  1386. format(backbone))
  1387. with_fpn = True
  1388. backbone = self._get_backbone(
  1389. 'ResNet',
  1390. variant='d' if '_vd' in backbone else 'b',
  1391. depth=101,
  1392. norm_type='bn',
  1393. freeze_at=0,
  1394. return_idx=[0, 1, 2, 3],
  1395. num_stages=4,
  1396. dcn_v2_stages=dcn_v2_stages)
  1397. rpn_in_channel = backbone.out_shape[0].channels
  1398. if with_fpn:
  1399. neck = ppdet.modeling.FPN(
  1400. in_channels=[i.channels for i in backbone.out_shape],
  1401. out_channel=fpn_num_channels,
  1402. spatial_scales=[1.0 / i.stride for i in backbone.out_shape])
  1403. rpn_in_channel = neck.out_shape[0].channels
  1404. anchor_generator_cfg = {
  1405. 'aspect_ratios': aspect_ratios,
  1406. 'anchor_sizes': anchor_sizes,
  1407. 'strides': [4, 8, 16, 32, 64]
  1408. }
  1409. train_proposal_cfg = {
  1410. 'min_size': 0.0,
  1411. 'nms_thresh': .7,
  1412. 'pre_nms_top_n': 2000,
  1413. 'post_nms_top_n': 1000,
  1414. 'topk_after_collect': True
  1415. }
  1416. test_proposal_cfg = {
  1417. 'min_size': 0.0,
  1418. 'nms_thresh': .7,
  1419. 'pre_nms_top_n': 1000
  1420. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  1421. 'post_nms_top_n': test_post_nms_top_n
  1422. }
  1423. bb_head = ppdet.modeling.TwoFCHead(
  1424. in_channel=neck.out_shape[0].channels, out_channel=1024)
  1425. bb_roi_extractor_cfg = {
  1426. 'resolution': 7,
  1427. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  1428. 'sampling_ratio': 0,
  1429. 'aligned': True
  1430. }
  1431. with_pool = False
  1432. m_head = ppdet.modeling.MaskFeat(
  1433. in_channel=neck.out_shape[0].channels,
  1434. out_channel=256,
  1435. num_convs=4)
  1436. m_roi_extractor_cfg = {
  1437. 'resolution': 14,
  1438. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  1439. 'sampling_ratio': 0,
  1440. 'aligned': True
  1441. }
  1442. mask_assigner = MaskAssigner(
  1443. num_classes=num_classes, mask_resolution=28)
  1444. share_bbox_feat = False
  1445. else:
  1446. neck = None
  1447. anchor_generator_cfg = {
  1448. 'aspect_ratios': aspect_ratios,
  1449. 'anchor_sizes': anchor_sizes,
  1450. 'strides': [16]
  1451. }
  1452. train_proposal_cfg = {
  1453. 'min_size': 0.0,
  1454. 'nms_thresh': .7,
  1455. 'pre_nms_top_n': 12000,
  1456. 'post_nms_top_n': 2000,
  1457. 'topk_after_collect': False
  1458. }
  1459. test_proposal_cfg = {
  1460. 'min_size': 0.0,
  1461. 'nms_thresh': .7,
  1462. 'pre_nms_top_n': 6000
  1463. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  1464. 'post_nms_top_n': test_post_nms_top_n
  1465. }
  1466. bb_head = ppdet.modeling.Res5Head()
  1467. bb_roi_extractor_cfg = {
  1468. 'resolution': 14,
  1469. 'spatial_scale': [1. / i.stride for i in backbone.out_shape],
  1470. 'sampling_ratio': 0,
  1471. 'aligned': True
  1472. }
  1473. with_pool = True
  1474. m_head = ppdet.modeling.MaskFeat(
  1475. in_channel=bb_head.out_shape[0].channels,
  1476. out_channel=256,
  1477. num_convs=0)
  1478. m_roi_extractor_cfg = {
  1479. 'resolution': 14,
  1480. 'spatial_scale': [1. / i.stride for i in backbone.out_shape],
  1481. 'sampling_ratio': 0,
  1482. 'aligned': True
  1483. }
  1484. mask_assigner = MaskAssigner(
  1485. num_classes=num_classes, mask_resolution=14)
  1486. share_bbox_feat = True
  1487. rpn_target_assign_cfg = {
  1488. 'batch_size_per_im': rpn_batch_size_per_im,
  1489. 'fg_fraction': rpn_fg_fraction,
  1490. 'negative_overlap': .3,
  1491. 'positive_overlap': .7,
  1492. 'use_random': True
  1493. }
  1494. rpn_head = ppdet.modeling.RPNHead(
  1495. anchor_generator=anchor_generator_cfg,
  1496. rpn_target_assign=rpn_target_assign_cfg,
  1497. train_proposal=train_proposal_cfg,
  1498. test_proposal=test_proposal_cfg,
  1499. in_channel=rpn_in_channel)
  1500. bbox_assigner = BBoxAssigner(num_classes=num_classes)
  1501. bbox_head = ppdet.modeling.BBoxHead(
  1502. head=bb_head,
  1503. in_channel=bb_head.out_shape[0].channels,
  1504. roi_extractor=bb_roi_extractor_cfg,
  1505. with_pool=with_pool,
  1506. bbox_assigner=bbox_assigner,
  1507. num_classes=num_classes)
  1508. mask_head = ppdet.modeling.MaskHead(
  1509. head=m_head,
  1510. roi_extractor=m_roi_extractor_cfg,
  1511. mask_assigner=mask_assigner,
  1512. share_bbox_feat=share_bbox_feat,
  1513. num_classes=num_classes)
  1514. bbox_post_process = ppdet.modeling.BBoxPostProcess(
  1515. num_classes=num_classes,
  1516. decode=ppdet.modeling.RCNNBox(num_classes=num_classes),
  1517. nms=ppdet.modeling.MultiClassNMS(
  1518. score_threshold=score_threshold,
  1519. keep_top_k=keep_top_k,
  1520. nms_threshold=nms_threshold))
  1521. mask_post_process = ppdet.modeling.MaskPostProcess(binary_thresh=.5)
  1522. params = {
  1523. 'backbone': backbone,
  1524. 'neck': neck,
  1525. 'rpn_head': rpn_head,
  1526. 'bbox_head': bbox_head,
  1527. 'mask_head': mask_head,
  1528. 'bbox_post_process': bbox_post_process,
  1529. 'mask_post_process': mask_post_process
  1530. }
  1531. self.with_fpn = with_fpn
  1532. super(MaskRCNN, self).__init__(
  1533. model_name='MaskRCNN', num_classes=num_classes, **params)
  1534. def _compose_batch_transform(self, transforms, mode='train'):
  1535. if mode == 'train':
  1536. default_batch_transforms = [
  1537. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  1538. ]
  1539. collate_batch = False
  1540. else:
  1541. default_batch_transforms = [
  1542. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  1543. ]
  1544. collate_batch = True
  1545. custom_batch_transforms = []
  1546. for i, op in enumerate(transforms.transforms):
  1547. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  1548. if mode != 'train':
  1549. raise Exception(
  1550. "{} cannot be present in the {} transforms. ".format(
  1551. op.__class__.__name__, mode) +
  1552. "Please check the {} transforms.".format(mode))
  1553. custom_batch_transforms.insert(0, copy.deepcopy(op))
  1554. batch_transforms = BatchCompose(
  1555. custom_batch_transforms + default_batch_transforms,
  1556. collate_batch=collate_batch)
  1557. return batch_transforms
  1558. def _fix_transforms_shape(self, image_shape):
  1559. if hasattr(self, 'test_transforms'):
  1560. if self.test_transforms is not None:
  1561. has_resize_op = False
  1562. resize_op_idx = -1
  1563. normalize_op_idx = len(self.test_transforms.transforms)
  1564. for idx, op in enumerate(self.test_transforms.transforms):
  1565. name = op.__class__.__name__
  1566. if name == 'ResizeByShort':
  1567. has_resize_op = True
  1568. resize_op_idx = idx
  1569. if name == 'Normalize':
  1570. normalize_op_idx = idx
  1571. if not has_resize_op:
  1572. self.test_transforms.transforms.insert(
  1573. normalize_op_idx,
  1574. Resize(
  1575. target_size=image_shape,
  1576. keep_ratio=True,
  1577. interp='CUBIC'))
  1578. else:
  1579. self.test_transforms.transforms[resize_op_idx] = Resize(
  1580. target_size=image_shape,
  1581. keep_ratio=True,
  1582. interp='CUBIC')
  1583. self.test_transforms.transforms.append(
  1584. Padding(im_padding_value=[0., 0., 0.]))
  1585. def _get_test_inputs(self, image_shape):
  1586. if image_shape is not None:
  1587. image_shape = self._check_image_shape(image_shape)
  1588. self._fix_transforms_shape(image_shape[-2:])
  1589. else:
  1590. image_shape = [None, 3, -1, -1]
  1591. if self.with_fpn:
  1592. self.test_transforms.transforms.append(
  1593. Padding(im_padding_value=[0., 0., 0.]))
  1594. self.fixed_input_shape = image_shape
  1595. return self._define_input_spec(image_shape)