detector.py 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692
  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. 0 represents the first category in the dataset, and so on.
  423. category(str): category name
  424. bbox(list): bounding box in [x, y, w, h] format
  425. score(str): confidence
  426. mask(dict): Only for instance segmentation task. Mask of the object in RLE format
  427. """
  428. if transforms is None and not hasattr(self, 'test_transforms'):
  429. raise Exception("transforms need to be defined, now is None.")
  430. if transforms is None:
  431. transforms = self.test_transforms
  432. if isinstance(img_file, (str, np.ndarray)):
  433. images = [img_file]
  434. else:
  435. images = img_file
  436. batch_samples = self._preprocess(images, transforms)
  437. self.net.eval()
  438. outputs = self.run(self.net, batch_samples, 'test')
  439. prediction = self._postprocess(outputs)
  440. if isinstance(img_file, (str, np.ndarray)):
  441. prediction = prediction[0]
  442. return prediction
  443. def _preprocess(self, images, transforms):
  444. arrange_transforms(
  445. model_type=self.model_type, transforms=transforms, mode='test')
  446. batch_samples = list()
  447. for im in images:
  448. sample = {'image': im}
  449. batch_samples.append(transforms(sample))
  450. batch_transforms = self._compose_batch_transform(transforms, 'test')
  451. batch_samples = batch_transforms(batch_samples)
  452. for k, v in batch_samples.items():
  453. batch_samples[k] = paddle.to_tensor(v)
  454. return batch_samples
  455. def _postprocess(self, batch_pred):
  456. infer_result = {}
  457. if 'bbox' in batch_pred:
  458. bboxes = batch_pred['bbox']
  459. bbox_nums = batch_pred['bbox_num']
  460. det_res = []
  461. k = 0
  462. for i in range(len(bbox_nums)):
  463. det_nums = bbox_nums[i]
  464. for j in range(det_nums):
  465. dt = bboxes[k]
  466. k = k + 1
  467. num_id, score, xmin, ymin, xmax, ymax = dt.tolist()
  468. if int(num_id) < 0:
  469. continue
  470. category = self.labels[int(num_id)]
  471. w = xmax - xmin
  472. h = ymax - ymin
  473. bbox = [xmin, ymin, w, h]
  474. dt_res = {
  475. 'category_id': int(num_id),
  476. 'category': category,
  477. 'bbox': bbox,
  478. 'score': score
  479. }
  480. det_res.append(dt_res)
  481. infer_result['bbox'] = det_res
  482. if 'mask' in batch_pred:
  483. masks = batch_pred['mask']
  484. bboxes = batch_pred['bbox']
  485. mask_nums = batch_pred['bbox_num']
  486. seg_res = []
  487. k = 0
  488. for i in range(len(mask_nums)):
  489. det_nums = mask_nums[i]
  490. for j in range(det_nums):
  491. mask = masks[k].astype(np.uint8)
  492. score = float(bboxes[k][1])
  493. label = int(bboxes[k][0])
  494. k = k + 1
  495. if label == -1:
  496. continue
  497. category = self.labels[int(label)]
  498. import pycocotools.mask as mask_util
  499. rle = mask_util.encode(
  500. np.array(
  501. mask[:, :, None], order="F", dtype="uint8"))[0]
  502. if six.PY3:
  503. if 'counts' in rle:
  504. rle['counts'] = rle['counts'].decode("utf8")
  505. sg_res = {
  506. 'category_id': int(label),
  507. 'category': category,
  508. 'mask': rle,
  509. 'score': score
  510. }
  511. seg_res.append(sg_res)
  512. infer_result['mask'] = seg_res
  513. bbox_num = batch_pred['bbox_num']
  514. results = []
  515. start = 0
  516. for num in bbox_num:
  517. end = start + num
  518. curr_res = infer_result['bbox'][start:end]
  519. if 'mask' in infer_result:
  520. mask_res = infer_result['mask'][start:end]
  521. for box, mask in zip(curr_res, mask_res):
  522. box.update(mask)
  523. results.append(curr_res)
  524. start = end
  525. return results
  526. class YOLOv3(BaseDetector):
  527. def __init__(self,
  528. num_classes=80,
  529. backbone='MobileNetV1',
  530. anchors=[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  531. [59, 119], [116, 90], [156, 198], [373, 326]],
  532. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  533. ignore_threshold=0.7,
  534. nms_score_threshold=0.01,
  535. nms_topk=1000,
  536. nms_keep_topk=100,
  537. nms_iou_threshold=0.45,
  538. label_smooth=False):
  539. self.init_params = locals()
  540. if backbone not in [
  541. 'MobileNetV1', 'MobileNetV1_ssld', 'MobileNetV3',
  542. 'MobileNetV3_ssld', 'DarkNet53', 'ResNet50_vd_dcn', 'ResNet34'
  543. ]:
  544. raise ValueError(
  545. "backbone: {} is not supported. Please choose one of "
  546. "('MobileNetV1', 'MobileNetV1_ssld', 'MobileNetV3', 'MobileNetV3_ssld', 'DarkNet53', 'ResNet50_vd_dcn', 'ResNet34')".
  547. format(backbone))
  548. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  549. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  550. norm_type = 'sync_bn'
  551. else:
  552. norm_type = 'bn'
  553. self.backbone_name = backbone
  554. if 'MobileNetV1' in backbone:
  555. norm_type = 'bn'
  556. backbone = self._get_backbone('MobileNet', norm_type=norm_type)
  557. elif 'MobileNetV3' in backbone:
  558. backbone = self._get_backbone(
  559. 'MobileNetV3', norm_type=norm_type, feature_maps=[7, 13, 16])
  560. elif backbone == 'ResNet50_vd_dcn':
  561. backbone = self._get_backbone(
  562. 'ResNet',
  563. norm_type=norm_type,
  564. variant='d',
  565. return_idx=[1, 2, 3],
  566. dcn_v2_stages=[3],
  567. freeze_at=-1,
  568. freeze_norm=False)
  569. elif backbone == 'ResNet34':
  570. backbone = self._get_backbone(
  571. 'ResNet',
  572. depth=34,
  573. norm_type=norm_type,
  574. return_idx=[1, 2, 3],
  575. freeze_at=-1,
  576. freeze_norm=False,
  577. norm_decay=0.)
  578. else:
  579. backbone = self._get_backbone('DarkNet', norm_type=norm_type)
  580. neck = ppdet.modeling.YOLOv3FPN(
  581. norm_type=norm_type,
  582. in_channels=[i.channels for i in backbone.out_shape])
  583. loss = ppdet.modeling.YOLOv3Loss(
  584. num_classes=num_classes,
  585. ignore_thresh=ignore_threshold,
  586. label_smooth=label_smooth)
  587. yolo_head = ppdet.modeling.YOLOv3Head(
  588. in_channels=[i.channels for i in neck.out_shape],
  589. anchors=anchors,
  590. anchor_masks=anchor_masks,
  591. num_classes=num_classes,
  592. loss=loss)
  593. post_process = ppdet.modeling.BBoxPostProcess(
  594. decode=ppdet.modeling.YOLOBox(num_classes=num_classes),
  595. nms=ppdet.modeling.MultiClassNMS(
  596. score_threshold=nms_score_threshold,
  597. nms_top_k=nms_topk,
  598. keep_top_k=nms_keep_topk,
  599. nms_threshold=nms_iou_threshold))
  600. params = {
  601. 'backbone': backbone,
  602. 'neck': neck,
  603. 'yolo_head': yolo_head,
  604. 'post_process': post_process
  605. }
  606. super(YOLOv3, self).__init__(
  607. model_name='YOLOv3', num_classes=num_classes, **params)
  608. self.anchors = anchors
  609. self.anchor_masks = anchor_masks
  610. def _compose_batch_transform(self, transforms, mode='train'):
  611. if mode == 'train':
  612. default_batch_transforms = [
  613. _BatchPadding(pad_to_stride=-1), _NormalizeBox(),
  614. _PadBox(getattr(self, 'num_max_boxes', 50)), _BboxXYXY2XYWH(),
  615. _Gt2YoloTarget(
  616. anchor_masks=self.anchor_masks,
  617. anchors=self.anchors,
  618. downsample_ratios=getattr(self, 'downsample_ratios',
  619. [32, 16, 8]),
  620. num_classes=self.num_classes)
  621. ]
  622. else:
  623. default_batch_transforms = [_BatchPadding(pad_to_stride=-1)]
  624. if mode == 'eval' and self.metric == 'voc':
  625. collate_batch = False
  626. else:
  627. collate_batch = True
  628. custom_batch_transforms = []
  629. for i, op in enumerate(transforms.transforms):
  630. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  631. if mode != 'train':
  632. raise Exception(
  633. "{} cannot be present in the {} transforms. ".format(
  634. op.__class__.__name__, mode) +
  635. "Please check the {} transforms.".format(mode))
  636. custom_batch_transforms.insert(0, copy.deepcopy(op))
  637. batch_transforms = BatchCompose(
  638. custom_batch_transforms + default_batch_transforms,
  639. collate_batch=collate_batch)
  640. return batch_transforms
  641. def _fix_transforms_shape(self, image_shape):
  642. if hasattr(self, 'test_transforms'):
  643. if self.test_transforms is not None:
  644. has_resize_op = False
  645. resize_op_idx = -1
  646. normalize_op_idx = len(self.test_transforms.transforms)
  647. for idx, op in enumerate(self.test_transforms.transforms):
  648. name = op.__class__.__name__
  649. if name == 'Resize':
  650. has_resize_op = True
  651. resize_op_idx = idx
  652. if name == 'Normalize':
  653. normalize_op_idx = idx
  654. if not has_resize_op:
  655. self.test_transforms.transforms.insert(
  656. normalize_op_idx,
  657. Resize(
  658. target_size=image_shape, interp='CUBIC'))
  659. else:
  660. self.test_transforms.transforms[
  661. resize_op_idx].target_size = image_shape
  662. class FasterRCNN(BaseDetector):
  663. def __init__(self,
  664. num_classes=80,
  665. backbone='ResNet50',
  666. with_fpn=True,
  667. aspect_ratios=[0.5, 1.0, 2.0],
  668. anchor_sizes=[[32], [64], [128], [256], [512]],
  669. keep_top_k=100,
  670. nms_threshold=0.5,
  671. score_threshold=0.05,
  672. fpn_num_channels=256,
  673. rpn_batch_size_per_im=256,
  674. rpn_fg_fraction=0.5,
  675. test_pre_nms_top_n=None,
  676. test_post_nms_top_n=1000):
  677. self.init_params = locals()
  678. if backbone not in [
  679. 'ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet34',
  680. 'ResNet34_vd', 'ResNet101', 'ResNet101_vd', 'HRNet_W18'
  681. ]:
  682. raise ValueError(
  683. "backbone: {} is not supported. Please choose one of "
  684. "('ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet34', 'ResNet34_vd', "
  685. "'ResNet101', 'ResNet101_vd', 'HRNet_W18')".format(backbone))
  686. self.backbone_name = backbone
  687. if backbone == 'HRNet_W18':
  688. if not with_fpn:
  689. logging.warning(
  690. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  691. format(backbone))
  692. with_fpn = True
  693. backbone = self._get_backbone(
  694. 'HRNet', width=18, freeze_at=0, return_idx=[0, 1, 2, 3])
  695. elif backbone == 'ResNet50_vd_ssld':
  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. backbone = self._get_backbone(
  702. 'ResNet',
  703. variant='d',
  704. norm_type='bn',
  705. freeze_at=0,
  706. return_idx=[0, 1, 2, 3],
  707. num_stages=4,
  708. lr_mult_list=[0.05, 0.05, 0.1, 0.15])
  709. elif 'ResNet50' in backbone:
  710. if with_fpn:
  711. backbone = self._get_backbone(
  712. 'ResNet',
  713. variant='d' if '_vd' in backbone else 'b',
  714. norm_type='bn',
  715. freeze_at=0,
  716. return_idx=[0, 1, 2, 3],
  717. num_stages=4)
  718. else:
  719. backbone = self._get_backbone(
  720. 'ResNet',
  721. variant='d' if '_vd' in backbone else 'b',
  722. norm_type='bn',
  723. freeze_at=0,
  724. return_idx=[2],
  725. num_stages=3)
  726. elif 'ResNet34' in backbone:
  727. if not with_fpn:
  728. logging.warning(
  729. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  730. format(backbone))
  731. with_fpn = True
  732. backbone = self._get_backbone(
  733. 'ResNet',
  734. depth=34,
  735. variant='d' if 'vd' in backbone else 'b',
  736. norm_type='bn',
  737. freeze_at=0,
  738. return_idx=[0, 1, 2, 3],
  739. num_stages=4)
  740. else:
  741. if not with_fpn:
  742. logging.warning(
  743. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  744. format(backbone))
  745. with_fpn = True
  746. backbone = self._get_backbone(
  747. 'ResNet',
  748. depth=101,
  749. variant='d' if 'vd' in backbone else 'b',
  750. norm_type='bn',
  751. freeze_at=0,
  752. return_idx=[0, 1, 2, 3],
  753. num_stages=4)
  754. rpn_in_channel = backbone.out_shape[0].channels
  755. if with_fpn:
  756. self.backbone_name = self.backbone_name + '_fpn'
  757. if 'HRNet' in self.backbone_name:
  758. neck = ppdet.modeling.HRFPN(
  759. in_channels=[i.channels for i in backbone.out_shape],
  760. out_channel=fpn_num_channels,
  761. spatial_scales=[
  762. 1.0 / i.stride for i in backbone.out_shape
  763. ],
  764. share_conv=False)
  765. else:
  766. neck = ppdet.modeling.FPN(
  767. in_channels=[i.channels for i in backbone.out_shape],
  768. out_channel=fpn_num_channels,
  769. spatial_scales=[
  770. 1.0 / i.stride for i in backbone.out_shape
  771. ])
  772. rpn_in_channel = neck.out_shape[0].channels
  773. anchor_generator_cfg = {
  774. 'aspect_ratios': aspect_ratios,
  775. 'anchor_sizes': anchor_sizes,
  776. 'strides': [4, 8, 16, 32, 64]
  777. }
  778. train_proposal_cfg = {
  779. 'min_size': 0.0,
  780. 'nms_thresh': .7,
  781. 'pre_nms_top_n': 2000,
  782. 'post_nms_top_n': 1000,
  783. 'topk_after_collect': True
  784. }
  785. test_proposal_cfg = {
  786. 'min_size': 0.0,
  787. 'nms_thresh': .7,
  788. 'pre_nms_top_n': 1000
  789. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  790. 'post_nms_top_n': test_post_nms_top_n
  791. }
  792. head = ppdet.modeling.TwoFCHead(
  793. in_channel=neck.out_shape[0].channels, out_channel=1024)
  794. roi_extractor_cfg = {
  795. 'resolution': 7,
  796. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  797. 'sampling_ratio': 0,
  798. 'aligned': True
  799. }
  800. with_pool = False
  801. else:
  802. neck = None
  803. anchor_generator_cfg = {
  804. 'aspect_ratios': aspect_ratios,
  805. 'anchor_sizes': anchor_sizes,
  806. 'strides': [16]
  807. }
  808. train_proposal_cfg = {
  809. 'min_size': 0.0,
  810. 'nms_thresh': .7,
  811. 'pre_nms_top_n': 12000,
  812. 'post_nms_top_n': 2000,
  813. 'topk_after_collect': False
  814. }
  815. test_proposal_cfg = {
  816. 'min_size': 0.0,
  817. 'nms_thresh': .7,
  818. 'pre_nms_top_n': 6000
  819. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  820. 'post_nms_top_n': test_post_nms_top_n
  821. }
  822. head = ppdet.modeling.Res5Head()
  823. roi_extractor_cfg = {
  824. 'resolution': 14,
  825. 'spatial_scale': [1. / i.stride for i in backbone.out_shape],
  826. 'sampling_ratio': 0,
  827. 'aligned': True
  828. }
  829. with_pool = True
  830. rpn_target_assign_cfg = {
  831. 'batch_size_per_im': rpn_batch_size_per_im,
  832. 'fg_fraction': rpn_fg_fraction,
  833. 'negative_overlap': .3,
  834. 'positive_overlap': .7,
  835. 'use_random': True
  836. }
  837. rpn_head = ppdet.modeling.RPNHead(
  838. anchor_generator=anchor_generator_cfg,
  839. rpn_target_assign=rpn_target_assign_cfg,
  840. train_proposal=train_proposal_cfg,
  841. test_proposal=test_proposal_cfg,
  842. in_channel=rpn_in_channel)
  843. bbox_assigner = BBoxAssigner(num_classes=num_classes)
  844. bbox_head = ppdet.modeling.BBoxHead(
  845. head=head,
  846. in_channel=head.out_shape[0].channels,
  847. roi_extractor=roi_extractor_cfg,
  848. with_pool=with_pool,
  849. bbox_assigner=bbox_assigner,
  850. num_classes=num_classes)
  851. bbox_post_process = ppdet.modeling.BBoxPostProcess(
  852. num_classes=num_classes,
  853. decode=ppdet.modeling.RCNNBox(num_classes=num_classes),
  854. nms=ppdet.modeling.MultiClassNMS(
  855. score_threshold=score_threshold,
  856. keep_top_k=keep_top_k,
  857. nms_threshold=nms_threshold))
  858. params = {
  859. 'backbone': backbone,
  860. 'neck': neck,
  861. 'rpn_head': rpn_head,
  862. 'bbox_head': bbox_head,
  863. 'bbox_post_process': bbox_post_process
  864. }
  865. self.with_fpn = with_fpn
  866. super(FasterRCNN, self).__init__(
  867. model_name='FasterRCNN', num_classes=num_classes, **params)
  868. def _compose_batch_transform(self, transforms, mode='train'):
  869. if mode == 'train':
  870. default_batch_transforms = [
  871. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  872. ]
  873. collate_batch = False
  874. else:
  875. default_batch_transforms = [
  876. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  877. ]
  878. collate_batch = True
  879. custom_batch_transforms = []
  880. for i, op in enumerate(transforms.transforms):
  881. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  882. if mode != 'train':
  883. raise Exception(
  884. "{} cannot be present in the {} transforms. ".format(
  885. op.__class__.__name__, mode) +
  886. "Please check the {} transforms.".format(mode))
  887. custom_batch_transforms.insert(0, copy.deepcopy(op))
  888. batch_transforms = BatchCompose(
  889. custom_batch_transforms + default_batch_transforms,
  890. collate_batch=collate_batch)
  891. return batch_transforms
  892. def _fix_transforms_shape(self, image_shape):
  893. if hasattr(self, 'test_transforms'):
  894. if self.test_transforms is not None:
  895. has_resize_op = False
  896. resize_op_idx = -1
  897. normalize_op_idx = len(self.test_transforms.transforms)
  898. for idx, op in enumerate(self.test_transforms.transforms):
  899. name = op.__class__.__name__
  900. if name == 'ResizeByShort':
  901. has_resize_op = True
  902. resize_op_idx = idx
  903. if name == 'Normalize':
  904. normalize_op_idx = idx
  905. if not has_resize_op:
  906. self.test_transforms.transforms.insert(
  907. normalize_op_idx,
  908. Resize(
  909. target_size=image_shape,
  910. keep_ratio=True,
  911. interp='CUBIC'))
  912. else:
  913. self.test_transforms.transforms[resize_op_idx] = Resize(
  914. target_size=image_shape,
  915. keep_ratio=True,
  916. interp='CUBIC')
  917. self.test_transforms.transforms.append(
  918. Padding(im_padding_value=[0., 0., 0.]))
  919. class PPYOLO(YOLOv3):
  920. def __init__(self,
  921. num_classes=80,
  922. backbone='ResNet50_vd_dcn',
  923. anchors=None,
  924. anchor_masks=None,
  925. use_coord_conv=True,
  926. use_iou_aware=True,
  927. use_spp=True,
  928. use_drop_block=True,
  929. scale_x_y=1.05,
  930. ignore_threshold=0.7,
  931. label_smooth=False,
  932. use_iou_loss=True,
  933. use_matrix_nms=True,
  934. nms_score_threshold=0.01,
  935. nms_topk=-1,
  936. nms_keep_topk=100,
  937. nms_iou_threshold=0.45):
  938. self.init_params = locals()
  939. if backbone not in [
  940. 'ResNet50_vd_dcn', 'ResNet18_vd', 'MobileNetV3_large',
  941. 'MobileNetV3_small'
  942. ]:
  943. raise ValueError(
  944. "backbone: {} is not supported. Please choose one of "
  945. "('ResNet50_vd_dcn', 'ResNet18_vd', 'MobileNetV3_large', 'MobileNetV3_small')".
  946. format(backbone))
  947. self.backbone_name = backbone
  948. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  949. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  950. norm_type = 'sync_bn'
  951. else:
  952. norm_type = 'bn'
  953. if anchors is None and anchor_masks is None:
  954. if 'MobileNetV3' in backbone:
  955. anchors = [[11, 18], [34, 47], [51, 126], [115, 71],
  956. [120, 195], [254, 235]]
  957. anchor_masks = [[3, 4, 5], [0, 1, 2]]
  958. elif backbone == 'ResNet50_vd_dcn':
  959. anchors = [[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  960. [59, 119], [116, 90], [156, 198], [373, 326]]
  961. anchor_masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
  962. else:
  963. anchors = [[10, 14], [23, 27], [37, 58], [81, 82], [135, 169],
  964. [344, 319]]
  965. anchor_masks = [[3, 4, 5], [0, 1, 2]]
  966. elif anchors is None or anchor_masks is None:
  967. raise ValueError("Please define both anchors and anchor_masks.")
  968. if backbone == 'ResNet50_vd_dcn':
  969. backbone = self._get_backbone(
  970. 'ResNet',
  971. variant='d',
  972. norm_type=norm_type,
  973. return_idx=[1, 2, 3],
  974. dcn_v2_stages=[3],
  975. freeze_at=-1,
  976. freeze_norm=False,
  977. norm_decay=0.)
  978. downsample_ratios = [32, 16, 8]
  979. elif backbone == 'ResNet18_vd':
  980. backbone = self._get_backbone(
  981. 'ResNet',
  982. depth=18,
  983. variant='d',
  984. norm_type=norm_type,
  985. return_idx=[2, 3],
  986. freeze_at=-1,
  987. freeze_norm=False,
  988. norm_decay=0.)
  989. downsample_ratios = [32, 16, 8]
  990. elif backbone == 'MobileNetV3_large':
  991. backbone = self._get_backbone(
  992. 'MobileNetV3',
  993. model_name='large',
  994. norm_type=norm_type,
  995. scale=1,
  996. with_extra_blocks=False,
  997. extra_block_filters=[],
  998. feature_maps=[13, 16])
  999. downsample_ratios = [32, 16]
  1000. elif backbone == 'MobileNetV3_small':
  1001. backbone = self._get_backbone(
  1002. 'MobileNetV3',
  1003. model_name='small',
  1004. norm_type=norm_type,
  1005. scale=1,
  1006. with_extra_blocks=False,
  1007. extra_block_filters=[],
  1008. feature_maps=[9, 12])
  1009. downsample_ratios = [32, 16]
  1010. neck = ppdet.modeling.PPYOLOFPN(
  1011. norm_type=norm_type,
  1012. in_channels=[i.channels for i in backbone.out_shape],
  1013. coord_conv=use_coord_conv,
  1014. drop_block=use_drop_block,
  1015. spp=use_spp,
  1016. conv_block_num=0 if ('MobileNetV3' in self.backbone_name or
  1017. self.backbone_name == 'ResNet18_vd') else 2)
  1018. loss = ppdet.modeling.YOLOv3Loss(
  1019. num_classes=num_classes,
  1020. ignore_thresh=ignore_threshold,
  1021. downsample=downsample_ratios,
  1022. label_smooth=label_smooth,
  1023. scale_x_y=scale_x_y,
  1024. iou_loss=ppdet.modeling.IouLoss(
  1025. loss_weight=2.5, loss_square=True) if use_iou_loss else None,
  1026. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1027. if use_iou_aware else None)
  1028. yolo_head = ppdet.modeling.YOLOv3Head(
  1029. in_channels=[i.channels for i in neck.out_shape],
  1030. anchors=anchors,
  1031. anchor_masks=anchor_masks,
  1032. num_classes=num_classes,
  1033. loss=loss,
  1034. iou_aware=use_iou_aware)
  1035. if use_matrix_nms:
  1036. nms = ppdet.modeling.MatrixNMS(
  1037. keep_top_k=nms_keep_topk,
  1038. score_threshold=nms_score_threshold,
  1039. post_threshold=.05
  1040. if 'MobileNetV3' in self.backbone_name else .01,
  1041. nms_top_k=nms_topk,
  1042. background_label=-1)
  1043. else:
  1044. nms = ppdet.modeling.MultiClassNMS(
  1045. score_threshold=nms_score_threshold,
  1046. nms_top_k=nms_topk,
  1047. keep_top_k=nms_keep_topk,
  1048. nms_threshold=nms_iou_threshold)
  1049. post_process = ppdet.modeling.BBoxPostProcess(
  1050. decode=ppdet.modeling.YOLOBox(
  1051. num_classes=num_classes,
  1052. conf_thresh=.005
  1053. if 'MobileNetV3' in self.backbone_name else .01,
  1054. scale_x_y=scale_x_y),
  1055. nms=nms)
  1056. params = {
  1057. 'backbone': backbone,
  1058. 'neck': neck,
  1059. 'yolo_head': yolo_head,
  1060. 'post_process': post_process
  1061. }
  1062. super(YOLOv3, self).__init__(
  1063. model_name='YOLOv3', num_classes=num_classes, **params)
  1064. self.anchors = anchors
  1065. self.anchor_masks = anchor_masks
  1066. self.downsample_ratios = downsample_ratios
  1067. self.model_name = 'PPYOLO'
  1068. class PPYOLOTiny(YOLOv3):
  1069. def __init__(self,
  1070. num_classes=80,
  1071. backbone='MobileNetV3',
  1072. anchors=[[10, 15], [24, 36], [72, 42], [35, 87], [102, 96],
  1073. [60, 170], [220, 125], [128, 222], [264, 266]],
  1074. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  1075. use_iou_aware=False,
  1076. use_spp=True,
  1077. use_drop_block=True,
  1078. scale_x_y=1.05,
  1079. ignore_threshold=0.5,
  1080. label_smooth=False,
  1081. use_iou_loss=True,
  1082. use_matrix_nms=False,
  1083. nms_score_threshold=0.005,
  1084. nms_topk=1000,
  1085. nms_keep_topk=100,
  1086. nms_iou_threshold=0.45):
  1087. self.init_params = locals()
  1088. if backbone != 'MobileNetV3':
  1089. logging.warning(
  1090. "PPYOLOTiny only supports MobileNetV3 as backbone. "
  1091. "Backbone is forcibly set to MobileNetV3.")
  1092. self.backbone_name = 'MobileNetV3'
  1093. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1094. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1095. norm_type = 'sync_bn'
  1096. else:
  1097. norm_type = 'bn'
  1098. backbone = self._get_backbone(
  1099. 'MobileNetV3',
  1100. model_name='large',
  1101. norm_type=norm_type,
  1102. scale=.5,
  1103. with_extra_blocks=False,
  1104. extra_block_filters=[],
  1105. feature_maps=[7, 13, 16])
  1106. downsample_ratios = [32, 16, 8]
  1107. neck = ppdet.modeling.PPYOLOTinyFPN(
  1108. detection_block_channels=[160, 128, 96],
  1109. in_channels=[i.channels for i in backbone.out_shape],
  1110. spp=use_spp,
  1111. drop_block=use_drop_block)
  1112. loss = ppdet.modeling.YOLOv3Loss(
  1113. num_classes=num_classes,
  1114. ignore_thresh=ignore_threshold,
  1115. downsample=downsample_ratios,
  1116. label_smooth=label_smooth,
  1117. scale_x_y=scale_x_y,
  1118. iou_loss=ppdet.modeling.IouLoss(
  1119. loss_weight=2.5, loss_square=True) if use_iou_loss else None,
  1120. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1121. if use_iou_aware else None)
  1122. yolo_head = ppdet.modeling.YOLOv3Head(
  1123. in_channels=[i.channels for i in neck.out_shape],
  1124. anchors=anchors,
  1125. anchor_masks=anchor_masks,
  1126. num_classes=num_classes,
  1127. loss=loss,
  1128. iou_aware=use_iou_aware)
  1129. if use_matrix_nms:
  1130. nms = ppdet.modeling.MatrixNMS(
  1131. keep_top_k=nms_keep_topk,
  1132. score_threshold=nms_score_threshold,
  1133. post_threshold=.05,
  1134. nms_top_k=nms_topk,
  1135. background_label=-1)
  1136. else:
  1137. nms = ppdet.modeling.MultiClassNMS(
  1138. score_threshold=nms_score_threshold,
  1139. nms_top_k=nms_topk,
  1140. keep_top_k=nms_keep_topk,
  1141. nms_threshold=nms_iou_threshold)
  1142. post_process = ppdet.modeling.BBoxPostProcess(
  1143. decode=ppdet.modeling.YOLOBox(
  1144. num_classes=num_classes,
  1145. conf_thresh=.005,
  1146. downsample_ratio=32,
  1147. clip_bbox=True,
  1148. scale_x_y=scale_x_y),
  1149. nms=nms)
  1150. params = {
  1151. 'backbone': backbone,
  1152. 'neck': neck,
  1153. 'yolo_head': yolo_head,
  1154. 'post_process': post_process
  1155. }
  1156. super(YOLOv3, self).__init__(
  1157. model_name='YOLOv3', num_classes=num_classes, **params)
  1158. self.anchors = anchors
  1159. self.anchor_masks = anchor_masks
  1160. self.downsample_ratios = downsample_ratios
  1161. self.model_name = 'PPYOLOTiny'
  1162. class PPYOLOv2(YOLOv3):
  1163. def __init__(self,
  1164. num_classes=80,
  1165. backbone='ResNet50_vd_dcn',
  1166. anchors=[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  1167. [59, 119], [116, 90], [156, 198], [373, 326]],
  1168. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  1169. use_iou_aware=True,
  1170. use_spp=True,
  1171. use_drop_block=True,
  1172. scale_x_y=1.05,
  1173. ignore_threshold=0.7,
  1174. label_smooth=False,
  1175. use_iou_loss=True,
  1176. use_matrix_nms=True,
  1177. nms_score_threshold=0.01,
  1178. nms_topk=-1,
  1179. nms_keep_topk=100,
  1180. nms_iou_threshold=0.45):
  1181. self.init_params = locals()
  1182. if backbone not in ['ResNet50_vd_dcn', 'ResNet101_vd_dcn']:
  1183. raise ValueError(
  1184. "backbone: {} is not supported. Please choose one of "
  1185. "('ResNet50_vd_dcn', 'ResNet18_vd')".format(backbone))
  1186. self.backbone_name = backbone
  1187. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1188. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1189. norm_type = 'sync_bn'
  1190. else:
  1191. norm_type = 'bn'
  1192. if backbone == 'ResNet50_vd_dcn':
  1193. backbone = self._get_backbone(
  1194. 'ResNet',
  1195. variant='d',
  1196. norm_type=norm_type,
  1197. return_idx=[1, 2, 3],
  1198. dcn_v2_stages=[3],
  1199. freeze_at=-1,
  1200. freeze_norm=False,
  1201. norm_decay=0.)
  1202. downsample_ratios = [32, 16, 8]
  1203. elif backbone == 'ResNet101_vd_dcn':
  1204. backbone = self._get_backbone(
  1205. 'ResNet',
  1206. depth=101,
  1207. variant='d',
  1208. norm_type=norm_type,
  1209. return_idx=[1, 2, 3],
  1210. dcn_v2_stages=[3],
  1211. freeze_at=-1,
  1212. freeze_norm=False,
  1213. norm_decay=0.)
  1214. downsample_ratios = [32, 16, 8]
  1215. neck = ppdet.modeling.PPYOLOPAN(
  1216. norm_type=norm_type,
  1217. in_channels=[i.channels for i in backbone.out_shape],
  1218. drop_block=use_drop_block,
  1219. block_size=3,
  1220. keep_prob=.9,
  1221. spp=use_spp)
  1222. loss = ppdet.modeling.YOLOv3Loss(
  1223. num_classes=num_classes,
  1224. ignore_thresh=ignore_threshold,
  1225. downsample=downsample_ratios,
  1226. label_smooth=label_smooth,
  1227. scale_x_y=scale_x_y,
  1228. iou_loss=ppdet.modeling.IouLoss(
  1229. loss_weight=2.5, loss_square=True) if use_iou_loss else None,
  1230. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1231. if use_iou_aware else None)
  1232. yolo_head = ppdet.modeling.YOLOv3Head(
  1233. in_channels=[i.channels for i in neck.out_shape],
  1234. anchors=anchors,
  1235. anchor_masks=anchor_masks,
  1236. num_classes=num_classes,
  1237. loss=loss,
  1238. iou_aware=use_iou_aware,
  1239. iou_aware_factor=.5)
  1240. if use_matrix_nms:
  1241. nms = ppdet.modeling.MatrixNMS(
  1242. keep_top_k=nms_keep_topk,
  1243. score_threshold=nms_score_threshold,
  1244. post_threshold=.01,
  1245. nms_top_k=nms_topk,
  1246. background_label=-1)
  1247. else:
  1248. nms = ppdet.modeling.MultiClassNMS(
  1249. score_threshold=nms_score_threshold,
  1250. nms_top_k=nms_topk,
  1251. keep_top_k=nms_keep_topk,
  1252. nms_threshold=nms_iou_threshold)
  1253. post_process = ppdet.modeling.BBoxPostProcess(
  1254. decode=ppdet.modeling.YOLOBox(
  1255. num_classes=num_classes,
  1256. conf_thresh=.01,
  1257. downsample_ratio=32,
  1258. clip_bbox=True,
  1259. scale_x_y=scale_x_y),
  1260. nms=nms)
  1261. params = {
  1262. 'backbone': backbone,
  1263. 'neck': neck,
  1264. 'yolo_head': yolo_head,
  1265. 'post_process': post_process
  1266. }
  1267. super(YOLOv3, self).__init__(
  1268. model_name='YOLOv3', num_classes=num_classes, **params)
  1269. self.anchors = anchors
  1270. self.anchor_masks = anchor_masks
  1271. self.downsample_ratios = downsample_ratios
  1272. self.model_name = 'PPYOLOv2'
  1273. def _get_test_inputs(self, image_shape):
  1274. if image_shape is not None:
  1275. if len(image_shape) == 2:
  1276. image_shape = [None, 3] + image_shape
  1277. if image_shape[-2] % 32 > 0 or image_shape[-1] % 32 > 0:
  1278. raise Exception(
  1279. "Height and width in fixed_input_shape must be a multiple of 32, but recieved is {}.".
  1280. format(image_shape[-2:]))
  1281. self._fix_transforms_shape(image_shape[-2:])
  1282. else:
  1283. logging.warning(
  1284. '[Important!!!] When exporting inference model for {},'.format(
  1285. self.__class__.__name__) +
  1286. ' if fixed_input_shape is not set, it will be forcibly set to [None, 3, 608, 608]. '
  1287. +
  1288. 'Please check image shape after transforms is [3, 608, 608], if not, fixed_input_shape '
  1289. + 'should be specified manually.')
  1290. image_shape = [None, 3, 608, 608]
  1291. input_spec = [{
  1292. "image": InputSpec(
  1293. shape=image_shape, name='image', dtype='float32'),
  1294. "im_shape": InputSpec(
  1295. shape=[image_shape[0], 2], name='im_shape', dtype='float32'),
  1296. "scale_factor": InputSpec(
  1297. shape=[image_shape[0], 2],
  1298. name='scale_factor',
  1299. dtype='float32')
  1300. }]
  1301. return input_spec
  1302. class MaskRCNN(BaseDetector):
  1303. def __init__(self,
  1304. num_classes=80,
  1305. backbone='ResNet50_vd',
  1306. with_fpn=True,
  1307. aspect_ratios=[0.5, 1.0, 2.0],
  1308. anchor_sizes=[[32], [64], [128], [256], [512]],
  1309. keep_top_k=100,
  1310. nms_threshold=0.5,
  1311. score_threshold=0.05,
  1312. fpn_num_channels=256,
  1313. rpn_batch_size_per_im=256,
  1314. rpn_fg_fraction=0.5,
  1315. test_pre_nms_top_n=None,
  1316. test_post_nms_top_n=1000):
  1317. self.init_params = locals()
  1318. if backbone not in [
  1319. 'ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet101',
  1320. 'ResNet101_vd'
  1321. ]:
  1322. raise ValueError(
  1323. "backbone: {} is not supported. Please choose one of "
  1324. "('ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet101', 'ResNet101_vd')".
  1325. format(backbone))
  1326. self.backbone_name = backbone + '_fpn' if with_fpn else backbone
  1327. if backbone == 'ResNet50':
  1328. if with_fpn:
  1329. backbone = self._get_backbone(
  1330. 'ResNet',
  1331. norm_type='bn',
  1332. freeze_at=0,
  1333. return_idx=[0, 1, 2, 3],
  1334. num_stages=4)
  1335. else:
  1336. backbone = self._get_backbone(
  1337. 'ResNet',
  1338. norm_type='bn',
  1339. freeze_at=0,
  1340. return_idx=[2],
  1341. num_stages=3)
  1342. elif 'ResNet50_vd' in backbone:
  1343. if not with_fpn:
  1344. logging.warning(
  1345. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  1346. format(backbone))
  1347. with_fpn = True
  1348. backbone = self._get_backbone(
  1349. 'ResNet',
  1350. variant='d',
  1351. norm_type='bn',
  1352. freeze_at=0,
  1353. return_idx=[0, 1, 2, 3],
  1354. num_stages=4,
  1355. lr_mult_list=[0.05, 0.05, 0.1, 0.15]
  1356. if '_ssld' in backbone else [1.0, 1.0, 1.0, 1.0])
  1357. else:
  1358. if not with_fpn:
  1359. logging.warning(
  1360. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  1361. format(backbone))
  1362. with_fpn = True
  1363. backbone = self._get_backbone(
  1364. 'ResNet',
  1365. variant='d' if '_vd' in backbone else 'b',
  1366. depth=101,
  1367. norm_type='bn',
  1368. freeze_at=0,
  1369. return_idx=[0, 1, 2, 3],
  1370. num_stages=4)
  1371. rpn_in_channel = backbone.out_shape[0].channels
  1372. if with_fpn:
  1373. neck = ppdet.modeling.FPN(
  1374. in_channels=[i.channels for i in backbone.out_shape],
  1375. out_channel=fpn_num_channels,
  1376. spatial_scales=[1.0 / i.stride for i in backbone.out_shape])
  1377. rpn_in_channel = neck.out_shape[0].channels
  1378. anchor_generator_cfg = {
  1379. 'aspect_ratios': aspect_ratios,
  1380. 'anchor_sizes': anchor_sizes,
  1381. 'strides': [4, 8, 16, 32, 64]
  1382. }
  1383. train_proposal_cfg = {
  1384. 'min_size': 0.0,
  1385. 'nms_thresh': .7,
  1386. 'pre_nms_top_n': 2000,
  1387. 'post_nms_top_n': 1000,
  1388. 'topk_after_collect': True
  1389. }
  1390. test_proposal_cfg = {
  1391. 'min_size': 0.0,
  1392. 'nms_thresh': .7,
  1393. 'pre_nms_top_n': 1000
  1394. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  1395. 'post_nms_top_n': test_post_nms_top_n
  1396. }
  1397. bb_head = ppdet.modeling.TwoFCHead(
  1398. in_channel=neck.out_shape[0].channels, out_channel=1024)
  1399. bb_roi_extractor_cfg = {
  1400. 'resolution': 7,
  1401. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  1402. 'sampling_ratio': 0,
  1403. 'aligned': True
  1404. }
  1405. with_pool = False
  1406. m_head = ppdet.modeling.MaskFeat(
  1407. in_channel=neck.out_shape[0].channels,
  1408. out_channel=256,
  1409. num_convs=4)
  1410. m_roi_extractor_cfg = {
  1411. 'resolution': 14,
  1412. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  1413. 'sampling_ratio': 0,
  1414. 'aligned': True
  1415. }
  1416. mask_assigner = MaskAssigner(
  1417. num_classes=num_classes, mask_resolution=28)
  1418. share_bbox_feat = False
  1419. else:
  1420. neck = None
  1421. anchor_generator_cfg = {
  1422. 'aspect_ratios': aspect_ratios,
  1423. 'anchor_sizes': anchor_sizes,
  1424. 'strides': [16]
  1425. }
  1426. train_proposal_cfg = {
  1427. 'min_size': 0.0,
  1428. 'nms_thresh': .7,
  1429. 'pre_nms_top_n': 12000,
  1430. 'post_nms_top_n': 2000,
  1431. 'topk_after_collect': False
  1432. }
  1433. test_proposal_cfg = {
  1434. 'min_size': 0.0,
  1435. 'nms_thresh': .7,
  1436. 'pre_nms_top_n': 6000
  1437. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  1438. 'post_nms_top_n': test_post_nms_top_n
  1439. }
  1440. bb_head = ppdet.modeling.Res5Head()
  1441. bb_roi_extractor_cfg = {
  1442. 'resolution': 14,
  1443. 'spatial_scale': [1. / i.stride for i in backbone.out_shape],
  1444. 'sampling_ratio': 0,
  1445. 'aligned': True
  1446. }
  1447. with_pool = True
  1448. m_head = ppdet.modeling.MaskFeat(
  1449. in_channel=bb_head.out_shape[0].channels,
  1450. out_channel=256,
  1451. num_convs=0)
  1452. m_roi_extractor_cfg = {
  1453. 'resolution': 14,
  1454. 'spatial_scale': [1. / i.stride for i in backbone.out_shape],
  1455. 'sampling_ratio': 0,
  1456. 'aligned': True
  1457. }
  1458. mask_assigner = MaskAssigner(
  1459. num_classes=num_classes, mask_resolution=14)
  1460. share_bbox_feat = True
  1461. rpn_target_assign_cfg = {
  1462. 'batch_size_per_im': rpn_batch_size_per_im,
  1463. 'fg_fraction': rpn_fg_fraction,
  1464. 'negative_overlap': .3,
  1465. 'positive_overlap': .7,
  1466. 'use_random': True
  1467. }
  1468. rpn_head = ppdet.modeling.RPNHead(
  1469. anchor_generator=anchor_generator_cfg,
  1470. rpn_target_assign=rpn_target_assign_cfg,
  1471. train_proposal=train_proposal_cfg,
  1472. test_proposal=test_proposal_cfg,
  1473. in_channel=rpn_in_channel)
  1474. bbox_assigner = BBoxAssigner(num_classes=num_classes)
  1475. bbox_head = ppdet.modeling.BBoxHead(
  1476. head=bb_head,
  1477. in_channel=bb_head.out_shape[0].channels,
  1478. roi_extractor=bb_roi_extractor_cfg,
  1479. with_pool=with_pool,
  1480. bbox_assigner=bbox_assigner,
  1481. num_classes=num_classes)
  1482. mask_head = ppdet.modeling.MaskHead(
  1483. head=m_head,
  1484. roi_extractor=m_roi_extractor_cfg,
  1485. mask_assigner=mask_assigner,
  1486. share_bbox_feat=share_bbox_feat,
  1487. num_classes=num_classes)
  1488. bbox_post_process = ppdet.modeling.BBoxPostProcess(
  1489. num_classes=num_classes,
  1490. decode=ppdet.modeling.RCNNBox(num_classes=num_classes),
  1491. nms=ppdet.modeling.MultiClassNMS(
  1492. score_threshold=score_threshold,
  1493. keep_top_k=keep_top_k,
  1494. nms_threshold=nms_threshold))
  1495. mask_post_process = ppdet.modeling.MaskPostProcess(binary_thresh=.5)
  1496. params = {
  1497. 'backbone': backbone,
  1498. 'neck': neck,
  1499. 'rpn_head': rpn_head,
  1500. 'bbox_head': bbox_head,
  1501. 'mask_head': mask_head,
  1502. 'bbox_post_process': bbox_post_process,
  1503. 'mask_post_process': mask_post_process
  1504. }
  1505. self.with_fpn = with_fpn
  1506. super(MaskRCNN, self).__init__(
  1507. model_name='MaskRCNN', num_classes=num_classes, **params)
  1508. def _compose_batch_transform(self, transforms, mode='train'):
  1509. if mode == 'train':
  1510. default_batch_transforms = [
  1511. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  1512. ]
  1513. collate_batch = False
  1514. else:
  1515. default_batch_transforms = [
  1516. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  1517. ]
  1518. collate_batch = True
  1519. custom_batch_transforms = []
  1520. for i, op in enumerate(transforms.transforms):
  1521. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  1522. if mode != 'train':
  1523. raise Exception(
  1524. "{} cannot be present in the {} transforms. ".format(
  1525. op.__class__.__name__, mode) +
  1526. "Please check the {} transforms.".format(mode))
  1527. custom_batch_transforms.insert(0, copy.deepcopy(op))
  1528. batch_transforms = BatchCompose(
  1529. custom_batch_transforms + default_batch_transforms,
  1530. collate_batch=collate_batch)
  1531. return batch_transforms
  1532. def _fix_transforms_shape(self, image_shape):
  1533. if hasattr(self, 'test_transforms'):
  1534. if self.test_transforms is not None:
  1535. has_resize_op = False
  1536. resize_op_idx = -1
  1537. normalize_op_idx = len(self.test_transforms.transforms)
  1538. for idx, op in enumerate(self.test_transforms.transforms):
  1539. name = op.__class__.__name__
  1540. if name == 'ResizeByShort':
  1541. has_resize_op = True
  1542. resize_op_idx = idx
  1543. if name == 'Normalize':
  1544. normalize_op_idx = idx
  1545. if not has_resize_op:
  1546. self.test_transforms.transforms.insert(
  1547. normalize_op_idx,
  1548. Resize(
  1549. target_size=image_shape,
  1550. keep_ratio=True,
  1551. interp='CUBIC'))
  1552. else:
  1553. self.test_transforms.transforms[resize_op_idx] = Resize(
  1554. target_size=image_shape,
  1555. keep_ratio=True,
  1556. interp='CUBIC')
  1557. self.test_transforms.transforms.append(
  1558. Padding(im_padding_value=[0., 0., 0.]))