detector.py 67 KB

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