ops.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import paddle
  15. import paddle.nn.functional as F
  16. import paddle.nn as nn
  17. from paddle import ParamAttr
  18. from paddle.regularizer import L2Decay
  19. from paddle.fluid.framework import Variable, in_dygraph_mode
  20. from paddle.fluid import core
  21. from paddle.fluid.layer_helper import LayerHelper
  22. from paddle.fluid.data_feeder import check_variable_and_dtype, check_type, check_dtype
  23. __all__ = [
  24. 'roi_pool',
  25. 'roi_align',
  26. 'prior_box',
  27. 'generate_proposals',
  28. 'iou_similarity',
  29. 'box_coder',
  30. 'yolo_box',
  31. 'multiclass_nms',
  32. 'distribute_fpn_proposals',
  33. 'collect_fpn_proposals',
  34. 'matrix_nms',
  35. 'batch_norm',
  36. 'mish',
  37. ]
  38. def mish(x):
  39. return x * paddle.tanh(F.softplus(x))
  40. def batch_norm(ch,
  41. norm_type='bn',
  42. norm_decay=0.,
  43. freeze_norm=False,
  44. initializer=None,
  45. data_format='NCHW'):
  46. norm_lr = 0. if freeze_norm else 1.
  47. weight_attr = ParamAttr(
  48. initializer=initializer,
  49. learning_rate=norm_lr,
  50. regularizer=L2Decay(norm_decay),
  51. trainable=False if freeze_norm else True)
  52. bias_attr = ParamAttr(
  53. learning_rate=norm_lr,
  54. regularizer=L2Decay(norm_decay),
  55. trainable=False if freeze_norm else True)
  56. if norm_type in ['sync_bn', 'bn']:
  57. norm_layer = nn.BatchNorm2D(
  58. ch,
  59. weight_attr=weight_attr,
  60. bias_attr=bias_attr,
  61. data_format=data_format)
  62. norm_params = norm_layer.parameters()
  63. if freeze_norm:
  64. for param in norm_params:
  65. param.stop_gradient = True
  66. return norm_layer
  67. @paddle.jit.not_to_static
  68. def roi_pool(input,
  69. rois,
  70. output_size,
  71. spatial_scale=1.0,
  72. rois_num=None,
  73. name=None):
  74. """
  75. This operator implements the roi_pooling layer.
  76. Region of interest pooling (also known as RoI pooling) is to perform max pooling on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7).
  77. The operator has three steps:
  78. 1. Dividing each region proposal into equal-sized sections with output_size(h, w);
  79. 2. Finding the largest value in each section;
  80. 3. Copying these max values to the output buffer.
  81. For more information, please refer to https://stackoverflow.com/questions/43430056/what-is-roi-layer-in-fast-rcnn
  82. Args:
  83. input (Tensor): Input feature, 4D-Tensor with the shape of [N,C,H,W],
  84. where N is the batch size, C is the input channel, H is Height, W is weight.
  85. The data type is float32 or float64.
  86. rois (Tensor): ROIs (Regions of Interest) to pool over.
  87. 2D-Tensor or 2D-LoDTensor with the shape of [num_rois,4], the lod level is 1.
  88. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates,
  89. and (x2, y2) is the bottom right coordinates.
  90. output_size (int or tuple[int, int]): The pooled output size(h, w), data type is int32. If int, h and w are both equal to output_size.
  91. spatial_scale (float, optional): Multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling. Default: 1.0
  92. rois_num (Tensor): The number of RoIs in each image. Default: None
  93. name(str, optional): For detailed information, please refer
  94. to :ref:`api_guide_Name`. Usually name is no need to set and
  95. None by default.
  96. Returns:
  97. Tensor: The pooled feature, 4D-Tensor with the shape of [num_rois, C, output_size[0], output_size[1]].
  98. Examples:
  99. .. code-block:: python
  100. import paddle
  101. from paddlex.ppdet.modeling import ops
  102. paddle.enable_static()
  103. x = paddle.static.data(
  104. name='data', shape=[None, 256, 32, 32], dtype='float32')
  105. rois = paddle.static.data(
  106. name='rois', shape=[None, 4], dtype='float32')
  107. rois_num = paddle.static.data(name='rois_num', shape=[None], dtype='int32')
  108. pool_out = ops.roi_pool(
  109. input=x,
  110. rois=rois,
  111. output_size=(1, 1),
  112. spatial_scale=1.0,
  113. rois_num=rois_num)
  114. """
  115. check_type(output_size, 'output_size', (int, tuple), 'roi_pool')
  116. if isinstance(output_size, int):
  117. output_size = (output_size, output_size)
  118. pooled_height, pooled_width = output_size
  119. if in_dygraph_mode():
  120. assert rois_num is not None, "rois_num should not be None in dygraph mode."
  121. pool_out, argmaxes = core.ops.roi_pool(
  122. input, rois, rois_num, "pooled_height", pooled_height,
  123. "pooled_width", pooled_width, "spatial_scale", spatial_scale)
  124. return pool_out, argmaxes
  125. else:
  126. check_variable_and_dtype(input, 'input', ['float32'], 'roi_pool')
  127. check_variable_and_dtype(rois, 'rois', ['float32'], 'roi_pool')
  128. helper = LayerHelper('roi_pool', **locals())
  129. dtype = helper.input_dtype()
  130. pool_out = helper.create_variable_for_type_inference(dtype)
  131. argmaxes = helper.create_variable_for_type_inference(dtype='int32')
  132. inputs = {
  133. "X": input,
  134. "ROIs": rois,
  135. }
  136. if rois_num is not None:
  137. inputs['RoisNum'] = rois_num
  138. helper.append_op(
  139. type="roi_pool",
  140. inputs=inputs,
  141. outputs={"Out": pool_out,
  142. "Argmax": argmaxes},
  143. attrs={
  144. "pooled_height": pooled_height,
  145. "pooled_width": pooled_width,
  146. "spatial_scale": spatial_scale
  147. })
  148. return pool_out, argmaxes
  149. @paddle.jit.not_to_static
  150. def roi_align(input,
  151. rois,
  152. output_size,
  153. spatial_scale=1.0,
  154. sampling_ratio=-1,
  155. rois_num=None,
  156. aligned=True,
  157. name=None):
  158. """
  159. Region of interest align (also known as RoI align) is to perform
  160. bilinear interpolation on inputs of nonuniform sizes to obtain
  161. fixed-size feature maps (e.g. 7*7)
  162. Dividing each region proposal into equal-sized sections with
  163. the pooled_width and pooled_height. Location remains the origin
  164. result.
  165. In each ROI bin, the value of the four regularly sampled locations
  166. are computed directly through bilinear interpolation. The output is
  167. the mean of four locations.
  168. Thus avoid the misaligned problem.
  169. Args:
  170. input (Tensor): Input feature, 4D-Tensor with the shape of [N,C,H,W],
  171. where N is the batch size, C is the input channel, H is Height, W is weight.
  172. The data type is float32 or float64.
  173. rois (Tensor): ROIs (Regions of Interest) to pool over.It should be
  174. a 2-D Tensor or 2-D LoDTensor of shape (num_rois, 4), the lod level is 1.
  175. The data type is float32 or float64. Given as [[x1, y1, x2, y2], ...],
  176. (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates.
  177. output_size (int or tuple[int, int]): The pooled output size(h, w), data type is int32. If int, h and w are both equal to output_size.
  178. spatial_scale (float32, optional): Multiplicative spatial scale factor to translate ROI coords
  179. from their input scale to the scale used when pooling. Default: 1.0
  180. sampling_ratio(int32, optional): number of sampling points in the interpolation grid.
  181. If <=0, then grid points are adaptive to roi_width and pooled_w, likewise for height. Default: -1
  182. rois_num (Tensor): The number of RoIs in each image. Default: None
  183. name(str, optional): For detailed information, please refer
  184. to :ref:`api_guide_Name`. Usually name is no need to set and
  185. None by default.
  186. Returns:
  187. Tensor:
  188. Output: The output of ROIAlignOp is a 4-D tensor with shape (num_rois, channels, pooled_h, pooled_w). The data type is float32 or float64.
  189. Examples:
  190. .. code-block:: python
  191. import paddle
  192. from paddlex.ppdet.modeling import ops
  193. paddle.enable_static()
  194. x = paddle.static.data(
  195. name='data', shape=[None, 256, 32, 32], dtype='float32')
  196. rois = paddle.static.data(
  197. name='rois', shape=[None, 4], dtype='float32')
  198. rois_num = paddle.static.data(name='rois_num', shape=[None], dtype='int32')
  199. align_out = ops.roi_align(input=x,
  200. rois=rois,
  201. ouput_size=(7, 7),
  202. spatial_scale=0.5,
  203. sampling_ratio=-1,
  204. rois_num=rois_num)
  205. """
  206. check_type(output_size, 'output_size', (int, tuple), 'roi_align')
  207. if isinstance(output_size, int):
  208. output_size = (output_size, output_size)
  209. pooled_height, pooled_width = output_size
  210. if in_dygraph_mode():
  211. assert rois_num is not None, "rois_num should not be None in dygraph mode."
  212. align_out = core.ops.roi_align(
  213. input, rois, rois_num, "pooled_height", pooled_height,
  214. "pooled_width", pooled_width, "spatial_scale", spatial_scale,
  215. "sampling_ratio", sampling_ratio, "aligned", aligned)
  216. return align_out
  217. else:
  218. check_variable_and_dtype(input, 'input', ['float32', 'float64'],
  219. 'roi_align')
  220. check_variable_and_dtype(rois, 'rois', ['float32', 'float64'],
  221. 'roi_align')
  222. helper = LayerHelper('roi_align', **locals())
  223. dtype = helper.input_dtype()
  224. align_out = helper.create_variable_for_type_inference(dtype)
  225. inputs = {
  226. "X": input,
  227. "ROIs": rois,
  228. }
  229. if rois_num is not None:
  230. inputs['RoisNum'] = rois_num
  231. helper.append_op(
  232. type="roi_align",
  233. inputs=inputs,
  234. outputs={"Out": align_out},
  235. attrs={
  236. "pooled_height": pooled_height,
  237. "pooled_width": pooled_width,
  238. "spatial_scale": spatial_scale,
  239. "sampling_ratio": sampling_ratio,
  240. "aligned": aligned,
  241. })
  242. return align_out
  243. @paddle.jit.not_to_static
  244. def iou_similarity(x, y, box_normalized=True, name=None):
  245. """
  246. Computes intersection-over-union (IOU) between two box lists.
  247. Box list 'X' should be a LoDTensor and 'Y' is a common Tensor,
  248. boxes in 'Y' are shared by all instance of the batched inputs of X.
  249. Given two boxes A and B, the calculation of IOU is as follows:
  250. $$
  251. IOU(A, B) =
  252. \\frac{area(A\\cap B)}{area(A)+area(B)-area(A\\cap B)}
  253. $$
  254. Args:
  255. x (Tensor): Box list X is a 2-D Tensor with shape [N, 4] holds N
  256. boxes, each box is represented as [xmin, ymin, xmax, ymax],
  257. the shape of X is [N, 4]. [xmin, ymin] is the left top
  258. coordinate of the box if the input is image feature map, they
  259. are close to the origin of the coordinate system.
  260. [xmax, ymax] is the right bottom coordinate of the box.
  261. The data type is float32 or float64.
  262. y (Tensor): Box list Y holds M boxes, each box is represented as
  263. [xmin, ymin, xmax, ymax], the shape of X is [N, 4].
  264. [xmin, ymin] is the left top coordinate of the box if the
  265. input is image feature map, and [xmax, ymax] is the right
  266. bottom coordinate of the box. The data type is float32 or float64.
  267. box_normalized(bool): Whether treat the priorbox as a normalized box.
  268. Set true by default.
  269. name(str, optional): For detailed information, please refer
  270. to :ref:`api_guide_Name`. Usually name is no need to set and
  271. None by default.
  272. Returns:
  273. Tensor: The output of iou_similarity op, a tensor with shape [N, M]
  274. representing pairwise iou scores. The data type is same with x.
  275. Examples:
  276. .. code-block:: python
  277. import paddle
  278. from paddlex.ppdet.modeling import ops
  279. paddle.enable_static()
  280. x = paddle.static.data(name='x', shape=[None, 4], dtype='float32')
  281. y = paddle.static.data(name='y', shape=[None, 4], dtype='float32')
  282. iou = ops.iou_similarity(x=x, y=y)
  283. """
  284. if in_dygraph_mode():
  285. out = core.ops.iou_similarity(x, y, 'box_normalized', box_normalized)
  286. return out
  287. else:
  288. helper = LayerHelper("iou_similarity", **locals())
  289. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  290. helper.append_op(
  291. type="iou_similarity",
  292. inputs={"X": x,
  293. "Y": y},
  294. attrs={"box_normalized": box_normalized},
  295. outputs={"Out": out})
  296. return out
  297. @paddle.jit.not_to_static
  298. def collect_fpn_proposals(multi_rois,
  299. multi_scores,
  300. min_level,
  301. max_level,
  302. post_nms_top_n,
  303. rois_num_per_level=None,
  304. name=None):
  305. """
  306. **This OP only supports LoDTensor as input**. Concat multi-level RoIs
  307. (Region of Interest) and select N RoIs with respect to multi_scores.
  308. This operation performs the following steps:
  309. 1. Choose num_level RoIs and scores as input: num_level = max_level - min_level
  310. 2. Concat multi-level RoIs and scores
  311. 3. Sort scores and select post_nms_top_n scores
  312. 4. Gather RoIs by selected indices from scores
  313. 5. Re-sort RoIs by corresponding batch_id
  314. Args:
  315. multi_rois(list): List of RoIs to collect. Element in list is 2-D
  316. LoDTensor with shape [N, 4] and data type is float32 or float64,
  317. N is the number of RoIs.
  318. multi_scores(list): List of scores of RoIs to collect. Element in list
  319. is 2-D LoDTensor with shape [N, 1] and data type is float32 or
  320. float64, N is the number of RoIs.
  321. min_level(int): The lowest level of FPN layer to collect
  322. max_level(int): The highest level of FPN layer to collect
  323. post_nms_top_n(int): The number of selected RoIs
  324. rois_num_per_level(list, optional): The List of RoIs' numbers.
  325. Each element is 1-D Tensor which contains the RoIs' number of each
  326. image on each level and the shape is [B] and data type is
  327. int32, B is the number of images. If it is not None then return
  328. a 1-D Tensor contains the output RoIs' number of each image and
  329. the shape is [B]. Default: None
  330. name(str, optional): For detailed information, please refer
  331. to :ref:`api_guide_Name`. Usually name is no need to set and
  332. None by default.
  333. Returns:
  334. Variable:
  335. fpn_rois(Variable): 2-D LoDTensor with shape [N, 4] and data type is
  336. float32 or float64. Selected RoIs.
  337. rois_num(Tensor): 1-D Tensor contains the RoIs's number of each
  338. image. The shape is [B] and data type is int32. B is the number of
  339. images.
  340. Examples:
  341. .. code-block:: python
  342. import paddle
  343. from paddlex.ppdet.modeling import ops
  344. paddle.enable_static()
  345. multi_rois = []
  346. multi_scores = []
  347. for i in range(4):
  348. multi_rois.append(paddle.static.data(
  349. name='roi_'+str(i), shape=[None, 4], dtype='float32', lod_level=1))
  350. for i in range(4):
  351. multi_scores.append(paddle.static.data(
  352. name='score_'+str(i), shape=[None, 1], dtype='float32', lod_level=1))
  353. fpn_rois = ops.collect_fpn_proposals(
  354. multi_rois=multi_rois,
  355. multi_scores=multi_scores,
  356. min_level=2,
  357. max_level=5,
  358. post_nms_top_n=2000)
  359. """
  360. check_type(multi_rois, 'multi_rois', list, 'collect_fpn_proposals')
  361. check_type(multi_scores, 'multi_scores', list, 'collect_fpn_proposals')
  362. num_lvl = max_level - min_level + 1
  363. input_rois = multi_rois[:num_lvl]
  364. input_scores = multi_scores[:num_lvl]
  365. if in_dygraph_mode():
  366. assert rois_num_per_level is not None, "rois_num_per_level should not be None in dygraph mode."
  367. attrs = ('post_nms_topN', post_nms_top_n)
  368. output_rois, rois_num = core.ops.collect_fpn_proposals(
  369. input_rois, input_scores, rois_num_per_level, *attrs)
  370. return output_rois, rois_num
  371. else:
  372. helper = LayerHelper('collect_fpn_proposals', **locals())
  373. dtype = helper.input_dtype('multi_rois')
  374. check_dtype(dtype, 'multi_rois', ['float32', 'float64'],
  375. 'collect_fpn_proposals')
  376. output_rois = helper.create_variable_for_type_inference(dtype)
  377. output_rois.stop_gradient = True
  378. inputs = {
  379. 'MultiLevelRois': input_rois,
  380. 'MultiLevelScores': input_scores,
  381. }
  382. outputs = {'FpnRois': output_rois}
  383. if rois_num_per_level is not None:
  384. inputs['MultiLevelRoIsNum'] = rois_num_per_level
  385. rois_num = helper.create_variable_for_type_inference(dtype='int32')
  386. rois_num.stop_gradient = True
  387. outputs['RoisNum'] = rois_num
  388. helper.append_op(
  389. type='collect_fpn_proposals',
  390. inputs=inputs,
  391. outputs=outputs,
  392. attrs={'post_nms_topN': post_nms_top_n})
  393. return output_rois, rois_num
  394. @paddle.jit.not_to_static
  395. def distribute_fpn_proposals(fpn_rois,
  396. min_level,
  397. max_level,
  398. refer_level,
  399. refer_scale,
  400. pixel_offset=False,
  401. rois_num=None,
  402. name=None):
  403. r"""
  404. **This op only takes LoDTensor as input.** In Feature Pyramid Networks
  405. (FPN) models, it is needed to distribute all proposals into different FPN
  406. level, with respect to scale of the proposals, the referring scale and the
  407. referring level. Besides, to restore the order of proposals, we return an
  408. array which indicates the original index of rois in current proposals.
  409. To compute FPN level for each roi, the formula is given as follows:
  410. .. math::
  411. roi\_scale &= \sqrt{BBoxArea(fpn\_roi)}
  412. level = floor(&\log(\\frac{roi\_scale}{refer\_scale}) + refer\_level)
  413. where BBoxArea is a function to compute the area of each roi.
  414. Args:
  415. fpn_rois(Variable): 2-D Tensor with shape [N, 4] and data type is
  416. float32 or float64. The input fpn_rois.
  417. min_level(int32): The lowest level of FPN layer where the proposals come
  418. from.
  419. max_level(int32): The highest level of FPN layer where the proposals
  420. come from.
  421. refer_level(int32): The referring level of FPN layer with specified scale.
  422. refer_scale(int32): The referring scale of FPN layer with specified level.
  423. rois_num(Tensor): 1-D Tensor contains the number of RoIs in each image.
  424. The shape is [B] and data type is int32. B is the number of images.
  425. If it is not None then return a list of 1-D Tensor. Each element
  426. is the output RoIs' number of each image on the corresponding level
  427. and the shape is [B]. None by default.
  428. name(str, optional): For detailed information, please refer
  429. to :ref:`api_guide_Name`. Usually name is no need to set and
  430. None by default.
  431. Returns:
  432. Tuple:
  433. multi_rois(List) : A list of 2-D LoDTensor with shape [M, 4]
  434. and data type of float32 and float64. The length is
  435. max_level-min_level+1. The proposals in each FPN level.
  436. restore_ind(Variable): A 2-D Tensor with shape [N, 1], N is
  437. the number of total rois. The data type is int32. It is
  438. used to restore the order of fpn_rois.
  439. rois_num_per_level(List): A list of 1-D Tensor and each Tensor is
  440. the RoIs' number in each image on the corresponding level. The shape
  441. is [B] and data type of int32. B is the number of images
  442. Examples:
  443. .. code-block:: python
  444. import paddle
  445. from paddlex.ppdet.modeling import ops
  446. paddle.enable_static()
  447. fpn_rois = paddle.static.data(
  448. name='data', shape=[None, 4], dtype='float32', lod_level=1)
  449. multi_rois, restore_ind = ops.distribute_fpn_proposals(
  450. fpn_rois=fpn_rois,
  451. min_level=2,
  452. max_level=5,
  453. refer_level=4,
  454. refer_scale=224)
  455. """
  456. num_lvl = max_level - min_level + 1
  457. if in_dygraph_mode():
  458. assert rois_num is not None, "rois_num should not be None in dygraph mode."
  459. attrs = ('min_level', min_level, 'max_level', max_level, 'refer_level',
  460. refer_level, 'refer_scale', refer_scale, 'pixel_offset',
  461. pixel_offset)
  462. multi_rois, restore_ind, rois_num_per_level = core.ops.distribute_fpn_proposals(
  463. fpn_rois, rois_num, num_lvl, num_lvl, *attrs)
  464. return multi_rois, restore_ind, rois_num_per_level
  465. else:
  466. check_variable_and_dtype(fpn_rois, 'fpn_rois', ['float32', 'float64'],
  467. 'distribute_fpn_proposals')
  468. helper = LayerHelper('distribute_fpn_proposals', **locals())
  469. dtype = helper.input_dtype('fpn_rois')
  470. multi_rois = [
  471. helper.create_variable_for_type_inference(dtype)
  472. for i in range(num_lvl)
  473. ]
  474. restore_ind = helper.create_variable_for_type_inference(dtype='int32')
  475. inputs = {'FpnRois': fpn_rois}
  476. outputs = {
  477. 'MultiFpnRois': multi_rois,
  478. 'RestoreIndex': restore_ind,
  479. }
  480. if rois_num is not None:
  481. inputs['RoisNum'] = rois_num
  482. rois_num_per_level = [
  483. helper.create_variable_for_type_inference(dtype='int32')
  484. for i in range(num_lvl)
  485. ]
  486. outputs['MultiLevelRoIsNum'] = rois_num_per_level
  487. helper.append_op(
  488. type='distribute_fpn_proposals',
  489. inputs=inputs,
  490. outputs=outputs,
  491. attrs={
  492. 'min_level': min_level,
  493. 'max_level': max_level,
  494. 'refer_level': refer_level,
  495. 'refer_scale': refer_scale,
  496. 'pixel_offset': pixel_offset
  497. })
  498. return multi_rois, restore_ind, rois_num_per_level
  499. @paddle.jit.not_to_static
  500. def yolo_box(
  501. x,
  502. origin_shape,
  503. anchors,
  504. class_num,
  505. conf_thresh,
  506. downsample_ratio,
  507. clip_bbox=True,
  508. scale_x_y=1.,
  509. name=None, ):
  510. """
  511. This operator generates YOLO detection boxes from output of YOLOv3 network.
  512. The output of previous network is in shape [N, C, H, W], while H and W
  513. should be the same, H and W specify the grid size, each grid point predict
  514. given number boxes, this given number, which following will be represented as S,
  515. is specified by the number of anchors. In the second dimension(the channel
  516. dimension), C should be equal to S * (5 + class_num), class_num is the object
  517. category number of source dataset(such as 80 in coco dataset), so the
  518. second(channel) dimension, apart from 4 box location coordinates x, y, w, h,
  519. also includes confidence score of the box and class one-hot key of each anchor
  520. box.
  521. Assume the 4 location coordinates are :math:`t_x, t_y, t_w, t_h`, the box
  522. predictions should be as follows:
  523. $$
  524. b_x = \\sigma(t_x) + c_x
  525. $$
  526. $$
  527. b_y = \\sigma(t_y) + c_y
  528. $$
  529. $$
  530. b_w = p_w e^{t_w}
  531. $$
  532. $$
  533. b_h = p_h e^{t_h}
  534. $$
  535. in the equation above, :math:`c_x, c_y` is the left top corner of current grid
  536. and :math:`p_w, p_h` is specified by anchors.
  537. The logistic regression value of the 5th channel of each anchor prediction boxes
  538. represents the confidence score of each prediction box, and the logistic
  539. regression value of the last :attr:`class_num` channels of each anchor prediction
  540. boxes represents the classifcation scores. Boxes with confidence scores less than
  541. :attr:`conf_thresh` should be ignored, and box final scores is the product of
  542. confidence scores and classification scores.
  543. $$
  544. score_{pred} = score_{conf} * score_{class}
  545. $$
  546. Args:
  547. x (Tensor): The input tensor of YoloBox operator is a 4-D tensor with shape of [N, C, H, W].
  548. The second dimension(C) stores box locations, confidence score and
  549. classification one-hot keys of each anchor box. Generally, X should be the output of YOLOv3 network.
  550. The data type is float32 or float64.
  551. origin_shape (Tensor): The image size tensor of YoloBox operator, This is a 2-D tensor with shape of [N, 2].
  552. This tensor holds height and width of each input image used for resizing output box in input image
  553. scale. The data type is int32.
  554. anchors (list|tuple): The anchor width and height, it will be parsed pair by pair.
  555. class_num (int): The number of classes to predict.
  556. conf_thresh (float): The confidence scores threshold of detection boxes. Boxes with confidence scores
  557. under threshold should be ignored.
  558. downsample_ratio (int): The downsample ratio from network input to YoloBox operator input,
  559. so 32, 16, 8 should be set for the first, second, and thrid YoloBox operators.
  560. clip_bbox (bool): Whether clip output bonding box in Input(ImgSize) boundary. Default true.
  561. scale_x_y (float): Scale the center point of decoded bounding box. Default 1.0.
  562. name (string): The default value is None. Normally there is no need
  563. for user to set this property. For more information,
  564. please refer to :ref:`api_guide_Name`
  565. Returns:
  566. boxes Tensor: A 3-D tensor with shape [N, M, 4], the coordinates of boxes, N is the batch num,
  567. M is output box number, and the 3rd dimension stores [xmin, ymin, xmax, ymax] coordinates of boxes.
  568. scores Tensor: A 3-D tensor with shape [N, M, :attr:`class_num`], the coordinates of boxes, N is the batch num,
  569. M is output box number.
  570. Raises:
  571. TypeError: Attr anchors of yolo box must be list or tuple
  572. TypeError: Attr class_num of yolo box must be an integer
  573. TypeError: Attr conf_thresh of yolo box must be a float number
  574. Examples:
  575. .. code-block:: python
  576. import paddle
  577. from paddlex.ppdet.modeling import ops
  578. paddle.enable_static()
  579. x = paddle.static.data(name='x', shape=[None, 255, 13, 13], dtype='float32')
  580. img_size = paddle.static.data(name='img_size',shape=[None, 2],dtype='int64')
  581. anchors = [10, 13, 16, 30, 33, 23]
  582. boxes,scores = ops.yolo_box(x=x, img_size=img_size, class_num=80, anchors=anchors,
  583. conf_thresh=0.01, downsample_ratio=32)
  584. """
  585. helper = LayerHelper('yolo_box', **locals())
  586. if not isinstance(anchors, list) and not isinstance(anchors, tuple):
  587. raise TypeError("Attr anchors of yolo_box must be list or tuple")
  588. if not isinstance(class_num, int):
  589. raise TypeError("Attr class_num of yolo_box must be an integer")
  590. if not isinstance(conf_thresh, float):
  591. raise TypeError(
  592. "Attr ignore_thresh of yolo_box must be a float number")
  593. if in_dygraph_mode():
  594. attrs = ('anchors', anchors, 'class_num', class_num, 'conf_thresh',
  595. conf_thresh, 'downsample_ratio', downsample_ratio,
  596. 'clip_bbox', clip_bbox, 'scale_x_y', scale_x_y)
  597. boxes, scores = core.ops.yolo_box(x, origin_shape, *attrs)
  598. return boxes, scores
  599. else:
  600. boxes = helper.create_variable_for_type_inference(dtype=x.dtype)
  601. scores = helper.create_variable_for_type_inference(dtype=x.dtype)
  602. attrs = {
  603. "anchors": anchors,
  604. "class_num": class_num,
  605. "conf_thresh": conf_thresh,
  606. "downsample_ratio": downsample_ratio,
  607. "clip_bbox": clip_bbox,
  608. "scale_x_y": scale_x_y,
  609. }
  610. helper.append_op(
  611. type='yolo_box',
  612. inputs={
  613. "X": x,
  614. "ImgSize": origin_shape,
  615. },
  616. outputs={
  617. 'Boxes': boxes,
  618. 'Scores': scores,
  619. },
  620. attrs=attrs)
  621. return boxes, scores
  622. @paddle.jit.not_to_static
  623. def prior_box(input,
  624. image,
  625. min_sizes,
  626. max_sizes=None,
  627. aspect_ratios=[1.],
  628. variance=[0.1, 0.1, 0.2, 0.2],
  629. flip=False,
  630. clip=False,
  631. steps=[0.0, 0.0],
  632. offset=0.5,
  633. min_max_aspect_ratios_order=False,
  634. name=None):
  635. """
  636. This op generates prior boxes for SSD(Single Shot MultiBox Detector) algorithm.
  637. Each position of the input produce N prior boxes, N is determined by
  638. the count of min_sizes, max_sizes and aspect_ratios, The size of the
  639. box is in range(min_size, max_size) interval, which is generated in
  640. sequence according to the aspect_ratios.
  641. Parameters:
  642. input(Tensor): 4-D tensor(NCHW), the data type should be float32 or float64.
  643. image(Tensor): 4-D tensor(NCHW), the input image data of PriorBoxOp,
  644. the data type should be float32 or float64.
  645. min_sizes(list|tuple|float): the min sizes of generated prior boxes.
  646. max_sizes(list|tuple|None): the max sizes of generated prior boxes.
  647. Default: None.
  648. aspect_ratios(list|tuple|float): the aspect ratios of generated
  649. prior boxes. Default: [1.].
  650. variance(list|tuple): the variances to be encoded in prior boxes.
  651. Default:[0.1, 0.1, 0.2, 0.2].
  652. flip(bool): Whether to flip aspect ratios. Default:False.
  653. clip(bool): Whether to clip out-of-boundary boxes. Default: False.
  654. step(list|tuple): Prior boxes step across width and height, If
  655. step[0] equals to 0.0 or step[1] equals to 0.0, the prior boxes step across
  656. height or weight of the input will be automatically calculated.
  657. Default: [0., 0.]
  658. offset(float): Prior boxes center offset. Default: 0.5
  659. min_max_aspect_ratios_order(bool): If set True, the output prior box is
  660. in order of [min, max, aspect_ratios], which is consistent with
  661. Caffe. Please note, this order affects the weights order of
  662. convolution layer followed by and does not affect the final
  663. detection results. Default: False.
  664. name(str, optional): The default value is None. Normally there is no need for
  665. user to set this property. For more information, please refer to :ref:`api_guide_Name`
  666. Returns:
  667. Tuple: A tuple with two Variable (boxes, variances)
  668. boxes(Tensor): the output prior boxes of PriorBox.
  669. 4-D tensor, the layout is [H, W, num_priors, 4].
  670. H is the height of input, W is the width of input,
  671. num_priors is the total box count of each position of input.
  672. variances(Tensor): the expanded variances of PriorBox.
  673. 4-D tensor, the layput is [H, W, num_priors, 4].
  674. H is the height of input, W is the width of input
  675. num_priors is the total box count of each position of input
  676. Examples:
  677. .. code-block:: python
  678. import paddle
  679. from paddlex.ppdet.modeling import ops
  680. paddle.enable_static()
  681. input = paddle.static.data(name="input", shape=[None,3,6,9])
  682. image = paddle.static.data(name="image", shape=[None,3,9,12])
  683. box, var = ops.prior_box(
  684. input=input,
  685. image=image,
  686. min_sizes=[100.],
  687. clip=True,
  688. flip=True)
  689. """
  690. helper = LayerHelper("prior_box", **locals())
  691. dtype = helper.input_dtype()
  692. check_variable_and_dtype(
  693. input, 'input', ['uint8', 'int8', 'float32', 'float64'], 'prior_box')
  694. def _is_list_or_tuple_(data):
  695. return (isinstance(data, list) or isinstance(data, tuple))
  696. if not _is_list_or_tuple_(min_sizes):
  697. min_sizes = [min_sizes]
  698. if not _is_list_or_tuple_(aspect_ratios):
  699. aspect_ratios = [aspect_ratios]
  700. if not (_is_list_or_tuple_(steps) and len(steps) == 2):
  701. raise ValueError('steps should be a list or tuple ',
  702. 'with length 2, (step_width, step_height).')
  703. min_sizes = list(map(float, min_sizes))
  704. aspect_ratios = list(map(float, aspect_ratios))
  705. steps = list(map(float, steps))
  706. cur_max_sizes = None
  707. if max_sizes is not None and len(max_sizes) > 0 and max_sizes[0] > 0:
  708. if not _is_list_or_tuple_(max_sizes):
  709. max_sizes = [max_sizes]
  710. cur_max_sizes = max_sizes
  711. if in_dygraph_mode():
  712. attrs = ('min_sizes', min_sizes, 'aspect_ratios', aspect_ratios,
  713. 'variances', variance, 'flip', flip, 'clip', clip, 'step_w',
  714. steps[0], 'step_h', steps[1], 'offset', offset,
  715. 'min_max_aspect_ratios_order', min_max_aspect_ratios_order)
  716. if cur_max_sizes is not None:
  717. attrs += ('max_sizes', cur_max_sizes)
  718. box, var = core.ops.prior_box(input, image, *attrs)
  719. return box, var
  720. else:
  721. attrs = {
  722. 'min_sizes': min_sizes,
  723. 'aspect_ratios': aspect_ratios,
  724. 'variances': variance,
  725. 'flip': flip,
  726. 'clip': clip,
  727. 'step_w': steps[0],
  728. 'step_h': steps[1],
  729. 'offset': offset,
  730. 'min_max_aspect_ratios_order': min_max_aspect_ratios_order
  731. }
  732. if cur_max_sizes is not None:
  733. attrs['max_sizes'] = cur_max_sizes
  734. box = helper.create_variable_for_type_inference(dtype)
  735. var = helper.create_variable_for_type_inference(dtype)
  736. helper.append_op(
  737. type="prior_box",
  738. inputs={"Input": input,
  739. "Image": image},
  740. outputs={"Boxes": box,
  741. "Variances": var},
  742. attrs=attrs, )
  743. box.stop_gradient = True
  744. var.stop_gradient = True
  745. return box, var
  746. @paddle.jit.not_to_static
  747. def multiclass_nms(bboxes,
  748. scores,
  749. score_threshold,
  750. nms_top_k,
  751. keep_top_k,
  752. nms_threshold=0.3,
  753. normalized=True,
  754. nms_eta=1.,
  755. background_label=-1,
  756. return_index=False,
  757. return_rois_num=True,
  758. rois_num=None,
  759. name=None):
  760. """
  761. This operator is to do multi-class non maximum suppression (NMS) on
  762. boxes and scores.
  763. In the NMS step, this operator greedily selects a subset of detection bounding
  764. boxes that have high scores larger than score_threshold, if providing this
  765. threshold, then selects the largest nms_top_k confidences scores if nms_top_k
  766. is larger than -1. Then this operator pruns away boxes that have high IOU
  767. (intersection over union) overlap with already selected boxes by adaptive
  768. threshold NMS based on parameters of nms_threshold and nms_eta.
  769. Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
  770. per image if keep_top_k is larger than -1.
  771. Args:
  772. bboxes (Tensor): Two types of bboxes are supported:
  773. 1. (Tensor) A 3-D Tensor with shape
  774. [N, M, 4 or 8 16 24 32] represents the
  775. predicted locations of M bounding bboxes,
  776. N is the batch size. Each bounding box has four
  777. coordinate values and the layout is
  778. [xmin, ymin, xmax, ymax], when box size equals to 4.
  779. 2. (LoDTensor) A 3-D Tensor with shape [M, C, 4]
  780. M is the number of bounding boxes, C is the
  781. class number
  782. scores (Tensor): Two types of scores are supported:
  783. 1. (Tensor) A 3-D Tensor with shape [N, C, M]
  784. represents the predicted confidence predictions.
  785. N is the batch size, C is the class number, M is
  786. number of bounding boxes. For each category there
  787. are total M scores which corresponding M bounding
  788. boxes. Please note, M is equal to the 2nd dimension
  789. of BBoxes.
  790. 2. (LoDTensor) A 2-D LoDTensor with shape [M, C].
  791. M is the number of bbox, C is the class number.
  792. In this case, input BBoxes should be the second
  793. case with shape [M, C, 4].
  794. background_label (int): The index of background label, the background
  795. label will be ignored. If set to -1, then all
  796. categories will be considered. Default: 0
  797. score_threshold (float): Threshold to filter out bounding boxes with
  798. low confidence score. If not provided,
  799. consider all boxes.
  800. nms_top_k (int): Maximum number of detections to be kept according to
  801. the confidences after the filtering detections based
  802. on score_threshold.
  803. nms_threshold (float): The threshold to be used in NMS. Default: 0.3
  804. nms_eta (float): The threshold to be used in NMS. Default: 1.0
  805. keep_top_k (int): Number of total bboxes to be kept per image after NMS
  806. step. -1 means keeping all bboxes after NMS step.
  807. normalized (bool): Whether detections are normalized. Default: True
  808. return_index(bool): Whether return selected index. Default: False
  809. rois_num(Tensor): 1-D Tensor contains the number of RoIs in each image.
  810. The shape is [B] and data type is int32. B is the number of images.
  811. If it is not None then return a list of 1-D Tensor. Each element
  812. is the output RoIs' number of each image on the corresponding level
  813. and the shape is [B]. None by default.
  814. name(str): Name of the multiclass nms op. Default: None.
  815. Returns:
  816. A tuple with two Variables: (Out, Index) if return_index is True,
  817. otherwise, a tuple with one Variable(Out) is returned.
  818. Out: A 2-D LoDTensor with shape [No, 6] represents the detections.
  819. Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
  820. or A 2-D LoDTensor with shape [No, 10] represents the detections.
  821. Each row has 10 values: [label, confidence, x1, y1, x2, y2, x3, y3,
  822. x4, y4]. No is the total number of detections.
  823. If all images have not detected results, all elements in LoD will be
  824. 0, and output tensor is empty (None).
  825. Index: Only return when return_index is True. A 2-D LoDTensor with
  826. shape [No, 1] represents the selected index which type is Integer.
  827. The index is the absolute value cross batches. No is the same number
  828. as Out. If the index is used to gather other attribute such as age,
  829. one needs to reshape the input(N, M, 1) to (N * M, 1) as first, where
  830. N is the batch size and M is the number of boxes.
  831. Examples:
  832. .. code-block:: python
  833. import paddle
  834. from paddlex.ppdet.modeling import ops
  835. boxes = paddle.static.data(name='bboxes', shape=[81, 4],
  836. dtype='float32', lod_level=1)
  837. scores = paddle.static.data(name='scores', shape=[81],
  838. dtype='float32', lod_level=1)
  839. out, index = ops.multiclass_nms(bboxes=boxes,
  840. scores=scores,
  841. background_label=0,
  842. score_threshold=0.5,
  843. nms_top_k=400,
  844. nms_threshold=0.3,
  845. keep_top_k=200,
  846. normalized=False,
  847. return_index=True)
  848. """
  849. helper = LayerHelper('multiclass_nms3', **locals())
  850. if in_dygraph_mode():
  851. attrs = ('background_label', background_label, 'score_threshold',
  852. score_threshold, 'nms_top_k', nms_top_k, 'nms_threshold',
  853. nms_threshold, 'keep_top_k', keep_top_k, 'nms_eta', nms_eta,
  854. 'normalized', normalized)
  855. output, index, nms_rois_num = core.ops.multiclass_nms3(
  856. bboxes, scores, rois_num, *attrs)
  857. if not return_index:
  858. index = None
  859. return output, nms_rois_num, index
  860. else:
  861. output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
  862. index = helper.create_variable_for_type_inference(dtype='int32')
  863. inputs = {'BBoxes': bboxes, 'Scores': scores}
  864. outputs = {'Out': output, 'Index': index}
  865. if rois_num is not None:
  866. inputs['RoisNum'] = rois_num
  867. if return_rois_num:
  868. nms_rois_num = helper.create_variable_for_type_inference(
  869. dtype='int32')
  870. outputs['NmsRoisNum'] = nms_rois_num
  871. helper.append_op(
  872. type="multiclass_nms3",
  873. inputs=inputs,
  874. attrs={
  875. 'background_label': background_label,
  876. 'score_threshold': score_threshold,
  877. 'nms_top_k': nms_top_k,
  878. 'nms_threshold': nms_threshold,
  879. 'keep_top_k': keep_top_k,
  880. 'nms_eta': nms_eta,
  881. 'normalized': normalized
  882. },
  883. outputs=outputs)
  884. output.stop_gradient = True
  885. index.stop_gradient = True
  886. if not return_index:
  887. index = None
  888. if not return_rois_num:
  889. nms_rois_num = None
  890. return output, nms_rois_num, index
  891. @paddle.jit.not_to_static
  892. def matrix_nms(bboxes,
  893. scores,
  894. score_threshold,
  895. post_threshold,
  896. nms_top_k,
  897. keep_top_k,
  898. use_gaussian=False,
  899. gaussian_sigma=2.,
  900. background_label=0,
  901. normalized=True,
  902. return_index=False,
  903. return_rois_num=True,
  904. name=None):
  905. """
  906. **Matrix NMS**
  907. This operator does matrix non maximum suppression (NMS).
  908. First selects a subset of candidate bounding boxes that have higher scores
  909. than score_threshold (if provided), then the top k candidate is selected if
  910. nms_top_k is larger than -1. Score of the remaining candidate are then
  911. decayed according to the Matrix NMS scheme.
  912. Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
  913. per image if keep_top_k is larger than -1.
  914. Args:
  915. bboxes (Tensor): A 3-D Tensor with shape [N, M, 4] represents the
  916. predicted locations of M bounding bboxes,
  917. N is the batch size. Each bounding box has four
  918. coordinate values and the layout is
  919. [xmin, ymin, xmax, ymax], when box size equals to 4.
  920. The data type is float32 or float64.
  921. scores (Tensor): A 3-D Tensor with shape [N, C, M]
  922. represents the predicted confidence predictions.
  923. N is the batch size, C is the class number, M is
  924. number of bounding boxes. For each category there
  925. are total M scores which corresponding M bounding
  926. boxes. Please note, M is equal to the 2nd dimension
  927. of BBoxes. The data type is float32 or float64.
  928. score_threshold (float): Threshold to filter out bounding boxes with
  929. low confidence score.
  930. post_threshold (float): Threshold to filter out bounding boxes with
  931. low confidence score AFTER decaying.
  932. nms_top_k (int): Maximum number of detections to be kept according to
  933. the confidences after the filtering detections based
  934. on score_threshold.
  935. keep_top_k (int): Number of total bboxes to be kept per image after NMS
  936. step. -1 means keeping all bboxes after NMS step.
  937. use_gaussian (bool): Use Gaussian as the decay function. Default: False
  938. gaussian_sigma (float): Sigma for Gaussian decay function. Default: 2.0
  939. background_label (int): The index of background label, the background
  940. label will be ignored. If set to -1, then all
  941. categories will be considered. Default: 0
  942. normalized (bool): Whether detections are normalized. Default: True
  943. return_index(bool): Whether return selected index. Default: False
  944. return_rois_num(bool): whether return rois_num. Default: True
  945. name(str): Name of the matrix nms op. Default: None.
  946. Returns:
  947. A tuple with three Tensor: (Out, Index, RoisNum) if return_index is True,
  948. otherwise, a tuple with two Tensor (Out, RoisNum) is returned.
  949. Out (Tensor): A 2-D Tensor with shape [No, 6] containing the
  950. detection results.
  951. Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
  952. (After version 1.3, when no boxes detected, the lod is changed
  953. from {0} to {1})
  954. Index (Tensor): A 2-D Tensor with shape [No, 1] containing the
  955. selected indices, which are absolute values cross batches.
  956. rois_num (Tensor): A 1-D Tensor with shape [N] containing
  957. the number of detected boxes in each image.
  958. Examples:
  959. .. code-block:: python
  960. import paddle
  961. from paddlex.ppdet.modeling import ops
  962. boxes = paddle.static.data(name='bboxes', shape=[None,81, 4],
  963. dtype='float32', lod_level=1)
  964. scores = paddle.static.data(name='scores', shape=[None,81],
  965. dtype='float32', lod_level=1)
  966. out = ops.matrix_nms(bboxes=boxes, scores=scores, background_label=0,
  967. score_threshold=0.5, post_threshold=0.1,
  968. nms_top_k=400, keep_top_k=200, normalized=False)
  969. """
  970. check_variable_and_dtype(bboxes, 'BBoxes', ['float32', 'float64'],
  971. 'matrix_nms')
  972. check_variable_and_dtype(scores, 'Scores', ['float32', 'float64'],
  973. 'matrix_nms')
  974. check_type(score_threshold, 'score_threshold', float, 'matrix_nms')
  975. check_type(post_threshold, 'post_threshold', float, 'matrix_nms')
  976. check_type(nms_top_k, 'nums_top_k', int, 'matrix_nms')
  977. check_type(keep_top_k, 'keep_top_k', int, 'matrix_nms')
  978. check_type(normalized, 'normalized', bool, 'matrix_nms')
  979. check_type(use_gaussian, 'use_gaussian', bool, 'matrix_nms')
  980. check_type(gaussian_sigma, 'gaussian_sigma', float, 'matrix_nms')
  981. check_type(background_label, 'background_label', int, 'matrix_nms')
  982. if in_dygraph_mode():
  983. attrs = ('background_label', background_label, 'score_threshold',
  984. score_threshold, 'post_threshold', post_threshold,
  985. 'nms_top_k', nms_top_k, 'gaussian_sigma', gaussian_sigma,
  986. 'use_gaussian', use_gaussian, 'keep_top_k', keep_top_k,
  987. 'normalized', normalized)
  988. out, index, rois_num = core.ops.matrix_nms(bboxes, scores, *attrs)
  989. if not return_index:
  990. index = None
  991. if not return_rois_num:
  992. rois_num = None
  993. return out, rois_num, index
  994. else:
  995. helper = LayerHelper('matrix_nms', **locals())
  996. output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
  997. index = helper.create_variable_for_type_inference(dtype='int32')
  998. outputs = {'Out': output, 'Index': index}
  999. if return_rois_num:
  1000. rois_num = helper.create_variable_for_type_inference(dtype='int32')
  1001. outputs['RoisNum'] = rois_num
  1002. helper.append_op(
  1003. type="matrix_nms",
  1004. inputs={'BBoxes': bboxes,
  1005. 'Scores': scores},
  1006. attrs={
  1007. 'background_label': background_label,
  1008. 'score_threshold': score_threshold,
  1009. 'post_threshold': post_threshold,
  1010. 'nms_top_k': nms_top_k,
  1011. 'gaussian_sigma': gaussian_sigma,
  1012. 'use_gaussian': use_gaussian,
  1013. 'keep_top_k': keep_top_k,
  1014. 'normalized': normalized
  1015. },
  1016. outputs=outputs)
  1017. output.stop_gradient = True
  1018. if not return_index:
  1019. index = None
  1020. if not return_rois_num:
  1021. rois_num = None
  1022. return output, rois_num, index
  1023. def bipartite_match(dist_matrix,
  1024. match_type=None,
  1025. dist_threshold=None,
  1026. name=None):
  1027. """
  1028. This operator implements a greedy bipartite matching algorithm, which is
  1029. used to obtain the matching with the maximum distance based on the input
  1030. distance matrix. For input 2D matrix, the bipartite matching algorithm can
  1031. find the matched column for each row (matched means the largest distance),
  1032. also can find the matched row for each column. And this operator only
  1033. calculate matched indices from column to row. For each instance,
  1034. the number of matched indices is the column number of the input distance
  1035. matrix. **The OP only supports CPU**.
  1036. There are two outputs, matched indices and distance.
  1037. A simple description, this algorithm matched the best (maximum distance)
  1038. row entity to the column entity and the matched indices are not duplicated
  1039. in each row of ColToRowMatchIndices. If the column entity is not matched
  1040. any row entity, set -1 in ColToRowMatchIndices.
  1041. NOTE: the input DistMat can be LoDTensor (with LoD) or Tensor.
  1042. If LoDTensor with LoD, the height of ColToRowMatchIndices is batch size.
  1043. If Tensor, the height of ColToRowMatchIndices is 1.
  1044. NOTE: This API is a very low level API. It is used by :code:`ssd_loss`
  1045. layer. Please consider to use :code:`ssd_loss` instead.
  1046. Args:
  1047. dist_matrix(Tensor): This input is a 2-D LoDTensor with shape
  1048. [K, M]. The data type is float32 or float64. It is pair-wise
  1049. distance matrix between the entities represented by each row and
  1050. each column. For example, assumed one entity is A with shape [K],
  1051. another entity is B with shape [M]. The dist_matrix[i][j] is the
  1052. distance between A[i] and B[j]. The bigger the distance is, the
  1053. better matching the pairs are. NOTE: This tensor can contain LoD
  1054. information to represent a batch of inputs. One instance of this
  1055. batch can contain different numbers of entities.
  1056. match_type(str, optional): The type of matching method, should be
  1057. 'bipartite' or 'per_prediction'. None ('bipartite') by default.
  1058. dist_threshold(float32, optional): If `match_type` is 'per_prediction',
  1059. this threshold is to determine the extra matching bboxes based
  1060. on the maximum distance, 0.5 by default.
  1061. name(str, optional): For detailed information, please refer
  1062. to :ref:`api_guide_Name`. Usually name is no need to set and
  1063. None by default.
  1064. Returns:
  1065. Tuple:
  1066. matched_indices(Tensor): A 2-D Tensor with shape [N, M]. The data
  1067. type is int32. N is the batch size. If match_indices[i][j] is -1, it
  1068. means B[j] does not match any entity in i-th instance.
  1069. Otherwise, it means B[j] is matched to row
  1070. match_indices[i][j] in i-th instance. The row number of
  1071. i-th instance is saved in match_indices[i][j].
  1072. matched_distance(Tensor): A 2-D Tensor with shape [N, M]. The data
  1073. type is float32. N is batch size. If match_indices[i][j] is -1,
  1074. match_distance[i][j] is also -1.0. Otherwise, assumed
  1075. match_distance[i][j] = d, and the row offsets of each instance
  1076. are called LoD. Then match_distance[i][j] =
  1077. dist_matrix[d+LoD[i]][j].
  1078. Examples:
  1079. .. code-block:: python
  1080. import paddle
  1081. from paddlex.ppdet.modeling import ops
  1082. from paddlex.ppdet.modeling.utils import iou_similarity
  1083. paddle.enable_static()
  1084. x = paddle.static.data(name='x', shape=[None, 4], dtype='float32')
  1085. y = paddle.static.data(name='y', shape=[None, 4], dtype='float32')
  1086. iou = iou_similarity(x=x, y=y)
  1087. matched_indices, matched_dist = ops.bipartite_match(iou)
  1088. """
  1089. check_variable_and_dtype(dist_matrix, 'dist_matrix',
  1090. ['float32', 'float64'], 'bipartite_match')
  1091. if in_dygraph_mode():
  1092. match_indices, match_distance = core.ops.bipartite_match(
  1093. dist_matrix, "match_type", match_type, "dist_threshold",
  1094. dist_threshold)
  1095. return match_indices, match_distance
  1096. helper = LayerHelper('bipartite_match', **locals())
  1097. match_indices = helper.create_variable_for_type_inference(dtype='int32')
  1098. match_distance = helper.create_variable_for_type_inference(
  1099. dtype=dist_matrix.dtype)
  1100. helper.append_op(
  1101. type='bipartite_match',
  1102. inputs={'DistMat': dist_matrix},
  1103. attrs={
  1104. 'match_type': match_type,
  1105. 'dist_threshold': dist_threshold,
  1106. },
  1107. outputs={
  1108. 'ColToRowMatchIndices': match_indices,
  1109. 'ColToRowMatchDist': match_distance
  1110. })
  1111. return match_indices, match_distance
  1112. @paddle.jit.not_to_static
  1113. def box_coder(prior_box,
  1114. prior_box_var,
  1115. target_box,
  1116. code_type="encode_center_size",
  1117. box_normalized=True,
  1118. axis=0,
  1119. name=None):
  1120. r"""
  1121. **Box Coder Layer**
  1122. Encode/Decode the target bounding box with the priorbox information.
  1123. The Encoding schema described below:
  1124. .. math::
  1125. ox = (tx - px) / pw / pxv
  1126. oy = (ty - py) / ph / pyv
  1127. ow = \log(\abs(tw / pw)) / pwv
  1128. oh = \log(\abs(th / ph)) / phv
  1129. The Decoding schema described below:
  1130. .. math::
  1131. ox = (pw * pxv * tx * + px) - tw / 2
  1132. oy = (ph * pyv * ty * + py) - th / 2
  1133. ow = \exp(pwv * tw) * pw + tw / 2
  1134. oh = \exp(phv * th) * ph + th / 2
  1135. where `tx`, `ty`, `tw`, `th` denote the target box's center coordinates,
  1136. width and height respectively. Similarly, `px`, `py`, `pw`, `ph` denote
  1137. the priorbox's (anchor) center coordinates, width and height. `pxv`,
  1138. `pyv`, `pwv`, `phv` denote the variance of the priorbox and `ox`, `oy`,
  1139. `ow`, `oh` denote the encoded/decoded coordinates, width and height.
  1140. During Box Decoding, two modes for broadcast are supported. Say target
  1141. box has shape [N, M, 4], and the shape of prior box can be [N, 4] or
  1142. [M, 4]. Then prior box will broadcast to target box along the
  1143. assigned axis.
  1144. Args:
  1145. prior_box(Tensor): Box list prior_box is a 2-D Tensor with shape
  1146. [M, 4] holds M boxes and data type is float32 or float64. Each box
  1147. is represented as [xmin, ymin, xmax, ymax], [xmin, ymin] is the
  1148. left top coordinate of the anchor box, if the input is image feature
  1149. map, they are close to the origin of the coordinate system.
  1150. [xmax, ymax] is the right bottom coordinate of the anchor box.
  1151. prior_box_var(List|Tensor|None): prior_box_var supports three types
  1152. of input. One is Tensor with shape [M, 4] which holds M group and
  1153. data type is float32 or float64. The second is list consist of
  1154. 4 elements shared by all boxes and data type is float32 or float64.
  1155. Other is None and not involved in calculation.
  1156. target_box(Tensor): This input can be a 2-D LoDTensor with shape
  1157. [N, 4] when code_type is 'encode_center_size'. This input also can
  1158. be a 3-D Tensor with shape [N, M, 4] when code_type is
  1159. 'decode_center_size'. Each box is represented as
  1160. [xmin, ymin, xmax, ymax]. The data type is float32 or float64.
  1161. code_type(str): The code type used with the target box. It can be
  1162. `encode_center_size` or `decode_center_size`. `encode_center_size`
  1163. by default.
  1164. box_normalized(bool): Whether treat the priorbox as a normalized box.
  1165. Set true by default.
  1166. axis(int): Which axis in PriorBox to broadcast for box decode,
  1167. for example, if axis is 0 and TargetBox has shape [N, M, 4] and
  1168. PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4]
  1169. for decoding. It is only valid when code type is
  1170. `decode_center_size`. Set 0 by default.
  1171. name(str, optional): For detailed information, please refer
  1172. to :ref:`api_guide_Name`. Usually name is no need to set and
  1173. None by default.
  1174. Returns:
  1175. Tensor:
  1176. output_box(Tensor): When code_type is 'encode_center_size', the
  1177. output tensor of box_coder_op with shape [N, M, 4] representing the
  1178. result of N target boxes encoded with M Prior boxes and variances.
  1179. When code_type is 'decode_center_size', N represents the batch size
  1180. and M represents the number of decoded boxes.
  1181. Examples:
  1182. .. code-block:: python
  1183. import paddle
  1184. from paddlex.ppdet.modeling import ops
  1185. paddle.enable_static()
  1186. # For encode
  1187. prior_box_encode = paddle.static.data(name='prior_box_encode',
  1188. shape=[512, 4],
  1189. dtype='float32')
  1190. target_box_encode = paddle.static.data(name='target_box_encode',
  1191. shape=[81, 4],
  1192. dtype='float32')
  1193. output_encode = ops.box_coder(prior_box=prior_box_encode,
  1194. prior_box_var=[0.1,0.1,0.2,0.2],
  1195. target_box=target_box_encode,
  1196. code_type="encode_center_size")
  1197. # For decode
  1198. prior_box_decode = paddle.static.data(name='prior_box_decode',
  1199. shape=[512, 4],
  1200. dtype='float32')
  1201. target_box_decode = paddle.static.data(name='target_box_decode',
  1202. shape=[512, 81, 4],
  1203. dtype='float32')
  1204. output_decode = ops.box_coder(prior_box=prior_box_decode,
  1205. prior_box_var=[0.1,0.1,0.2,0.2],
  1206. target_box=target_box_decode,
  1207. code_type="decode_center_size",
  1208. box_normalized=False,
  1209. axis=1)
  1210. """
  1211. check_variable_and_dtype(prior_box, 'prior_box', ['float32', 'float64'],
  1212. 'box_coder')
  1213. check_variable_and_dtype(target_box, 'target_box', ['float32', 'float64'],
  1214. 'box_coder')
  1215. if in_dygraph_mode():
  1216. if isinstance(prior_box_var, Variable):
  1217. output_box = core.ops.box_coder(
  1218. prior_box, prior_box_var, target_box, "code_type", code_type,
  1219. "box_normalized", box_normalized, "axis", axis)
  1220. elif isinstance(prior_box_var, list):
  1221. output_box = core.ops.box_coder(
  1222. prior_box, None, target_box, "code_type", code_type,
  1223. "box_normalized", box_normalized, "axis", axis, "variance",
  1224. prior_box_var)
  1225. else:
  1226. raise TypeError(
  1227. "Input variance of box_coder must be Variable or list")
  1228. return output_box
  1229. else:
  1230. helper = LayerHelper("box_coder", **locals())
  1231. output_box = helper.create_variable_for_type_inference(
  1232. dtype=prior_box.dtype)
  1233. inputs = {"PriorBox": prior_box, "TargetBox": target_box}
  1234. attrs = {
  1235. "code_type": code_type,
  1236. "box_normalized": box_normalized,
  1237. "axis": axis
  1238. }
  1239. if isinstance(prior_box_var, Variable):
  1240. inputs['PriorBoxVar'] = prior_box_var
  1241. elif isinstance(prior_box_var, list):
  1242. attrs['variance'] = prior_box_var
  1243. else:
  1244. raise TypeError(
  1245. "Input variance of box_coder must be Variable or list")
  1246. helper.append_op(
  1247. type="box_coder",
  1248. inputs=inputs,
  1249. attrs=attrs,
  1250. outputs={"OutputBox": output_box})
  1251. return output_box
  1252. @paddle.jit.not_to_static
  1253. def generate_proposals(scores,
  1254. bbox_deltas,
  1255. im_shape,
  1256. anchors,
  1257. variances,
  1258. pre_nms_top_n=6000,
  1259. post_nms_top_n=1000,
  1260. nms_thresh=0.5,
  1261. min_size=0.1,
  1262. eta=1.0,
  1263. pixel_offset=False,
  1264. return_rois_num=False,
  1265. name=None):
  1266. """
  1267. **Generate proposal Faster-RCNN**
  1268. This operation proposes RoIs according to each box with their
  1269. probability to be a foreground object and
  1270. the box can be calculated by anchors. Bbox_deltais and scores
  1271. to be an object are the output of RPN. Final proposals
  1272. could be used to train detection net.
  1273. For generating proposals, this operation performs following steps:
  1274. 1. Transposes and resizes scores and bbox_deltas in size of
  1275. (H*W*A, 1) and (H*W*A, 4)
  1276. 2. Calculate box locations as proposals candidates.
  1277. 3. Clip boxes to image
  1278. 4. Remove predicted boxes with small area.
  1279. 5. Apply NMS to get final proposals as output.
  1280. Args:
  1281. scores(Tensor): A 4-D Tensor with shape [N, A, H, W] represents
  1282. the probability for each box to be an object.
  1283. N is batch size, A is number of anchors, H and W are height and
  1284. width of the feature map. The data type must be float32.
  1285. bbox_deltas(Tensor): A 4-D Tensor with shape [N, 4*A, H, W]
  1286. represents the difference between predicted box location and
  1287. anchor location. The data type must be float32.
  1288. im_shape(Tensor): A 2-D Tensor with shape [N, 2] represents H, W, the
  1289. origin image size or input size. The data type can be float32 or
  1290. float64.
  1291. anchors(Tensor): A 4-D Tensor represents the anchors with a layout
  1292. of [H, W, A, 4]. H and W are height and width of the feature map,
  1293. num_anchors is the box count of each position. Each anchor is
  1294. in (xmin, ymin, xmax, ymax) format an unnormalized. The data type must be float32.
  1295. variances(Tensor): A 4-D Tensor. The expanded variances of anchors with a layout of
  1296. [H, W, num_priors, 4]. Each variance is in
  1297. (xcenter, ycenter, w, h) format. The data type must be float32.
  1298. pre_nms_top_n(float): Number of total bboxes to be kept per
  1299. image before NMS. The data type must be float32. `6000` by default.
  1300. post_nms_top_n(float): Number of total bboxes to be kept per
  1301. image after NMS. The data type must be float32. `1000` by default.
  1302. nms_thresh(float): Threshold in NMS. The data type must be float32. `0.5` by default.
  1303. min_size(float): Remove predicted boxes with either height or
  1304. width < min_size. The data type must be float32. `0.1` by default.
  1305. eta(float): Apply in adaptive NMS, if adaptive `threshold > 0.5`,
  1306. `adaptive_threshold = adaptive_threshold * eta` in each iteration.
  1307. return_rois_num(bool): When setting True, it will return a 1D Tensor with shape [N, ] that includes Rois's
  1308. num of each image in one batch. The N is the image's num. For example, the tensor has values [4,5] that represents
  1309. the first image has 4 Rois, the second image has 5 Rois. It only used in rcnn model.
  1310. 'False' by default.
  1311. name(str, optional): For detailed information, please refer
  1312. to :ref:`api_guide_Name`. Usually name is no need to set and
  1313. None by default.
  1314. Returns:
  1315. tuple:
  1316. A tuple with format ``(rpn_rois, rpn_roi_probs)``.
  1317. - **rpn_rois**: The generated RoIs. 2-D Tensor with shape ``[N, 4]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
  1318. - **rpn_roi_probs**: The scores of generated RoIs. 2-D Tensor with shape ``[N, 1]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
  1319. Examples:
  1320. .. code-block:: python
  1321. import paddle
  1322. from paddlex.ppdet.modeling import ops
  1323. paddle.enable_static()
  1324. scores = paddle.static.data(name='scores', shape=[None, 4, 5, 5], dtype='float32')
  1325. bbox_deltas = paddle.static.data(name='bbox_deltas', shape=[None, 16, 5, 5], dtype='float32')
  1326. im_shape = paddle.static.data(name='im_shape', shape=[None, 2], dtype='float32')
  1327. anchors = paddle.static.data(name='anchors', shape=[None, 5, 4, 4], dtype='float32')
  1328. variances = paddle.static.data(name='variances', shape=[None, 5, 10, 4], dtype='float32')
  1329. rois, roi_probs = ops.generate_proposals(scores, bbox_deltas,
  1330. im_shape, anchors, variances)
  1331. """
  1332. if in_dygraph_mode():
  1333. assert return_rois_num, "return_rois_num should be True in dygraph mode."
  1334. attrs = ('pre_nms_topN', pre_nms_top_n, 'post_nms_topN',
  1335. post_nms_top_n, 'nms_thresh', nms_thresh, 'min_size',
  1336. min_size, 'eta', eta, 'pixel_offset', pixel_offset)
  1337. rpn_rois, rpn_roi_probs, rpn_rois_num = core.ops.generate_proposals_v2(
  1338. scores, bbox_deltas, im_shape, anchors, variances, *attrs)
  1339. return rpn_rois, rpn_roi_probs, rpn_rois_num
  1340. else:
  1341. helper = LayerHelper('generate_proposals_v2', **locals())
  1342. check_variable_and_dtype(scores, 'scores', ['float32'],
  1343. 'generate_proposals_v2')
  1344. check_variable_and_dtype(bbox_deltas, 'bbox_deltas', ['float32'],
  1345. 'generate_proposals_v2')
  1346. check_variable_and_dtype(im_shape, 'im_shape', ['float32', 'float64'],
  1347. 'generate_proposals_v2')
  1348. check_variable_and_dtype(anchors, 'anchors', ['float32'],
  1349. 'generate_proposals_v2')
  1350. check_variable_and_dtype(variances, 'variances', ['float32'],
  1351. 'generate_proposals_v2')
  1352. rpn_rois = helper.create_variable_for_type_inference(
  1353. dtype=bbox_deltas.dtype)
  1354. rpn_roi_probs = helper.create_variable_for_type_inference(
  1355. dtype=scores.dtype)
  1356. outputs = {
  1357. 'RpnRois': rpn_rois,
  1358. 'RpnRoiProbs': rpn_roi_probs,
  1359. }
  1360. if return_rois_num:
  1361. rpn_rois_num = helper.create_variable_for_type_inference(
  1362. dtype='int32')
  1363. rpn_rois_num.stop_gradient = True
  1364. outputs['RpnRoisNum'] = rpn_rois_num
  1365. helper.append_op(
  1366. type="generate_proposals_v2",
  1367. inputs={
  1368. 'Scores': scores,
  1369. 'BboxDeltas': bbox_deltas,
  1370. 'ImShape': im_shape,
  1371. 'Anchors': anchors,
  1372. 'Variances': variances
  1373. },
  1374. attrs={
  1375. 'pre_nms_topN': pre_nms_top_n,
  1376. 'post_nms_topN': post_nms_top_n,
  1377. 'nms_thresh': nms_thresh,
  1378. 'min_size': min_size,
  1379. 'eta': eta,
  1380. 'pixel_offset': pixel_offset
  1381. },
  1382. outputs=outputs)
  1383. rpn_rois.stop_gradient = True
  1384. rpn_roi_probs.stop_gradient = True
  1385. return rpn_rois, rpn_roi_probs, rpn_rois_num
  1386. def sigmoid_cross_entropy_with_logits(input,
  1387. label,
  1388. ignore_index=-100,
  1389. normalize=False):
  1390. output = F.binary_cross_entropy_with_logits(input, label, reduction='none')
  1391. mask_tensor = paddle.cast(label != ignore_index, 'float32')
  1392. output = paddle.multiply(output, mask_tensor)
  1393. if normalize:
  1394. sum_valid_mask = paddle.sum(mask_tensor)
  1395. output = output / sum_valid_mask
  1396. return output
  1397. def smooth_l1(input,
  1398. label,
  1399. inside_weight=None,
  1400. outside_weight=None,
  1401. sigma=None):
  1402. input_new = paddle.multiply(input, inside_weight)
  1403. label_new = paddle.multiply(label, inside_weight)
  1404. delta = 1 / (sigma * sigma)
  1405. out = F.smooth_l1_loss(input_new, label_new, reduction='none', delta=delta)
  1406. out = paddle.multiply(out, outside_weight)
  1407. out = out / delta
  1408. out = paddle.reshape(out, shape=[out.shape[0], -1])
  1409. out = paddle.sum(out, axis=1)
  1410. return out
  1411. def channel_shuffle(x, groups):
  1412. batch_size, num_channels, height, width = x.shape[0:4]
  1413. assert num_channels % groups == 0, 'num_channels should be divisible by groups'
  1414. channels_per_group = num_channels // groups
  1415. x = paddle.reshape(
  1416. x=x, shape=[batch_size, groups, channels_per_group, height, width])
  1417. x = paddle.transpose(x=x, perm=[0, 2, 1, 3, 4])
  1418. x = paddle.reshape(x=x, shape=[batch_size, num_channels, height, width])
  1419. return x
  1420. def get_static_shape(tensor):
  1421. shape = paddle.shape(tensor)
  1422. shape.stop_gradient = True
  1423. return shape