meta_arch.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. from __future__ import absolute_import
  2. from __future__ import division
  3. from __future__ import print_function
  4. import numpy as np
  5. import paddle
  6. import paddle.nn as nn
  7. import typing
  8. from paddlex.ppdet.core.workspace import register
  9. from paddlex.ppdet.modeling.post_process import nms
  10. __all__ = ['BaseArch']
  11. @register
  12. class BaseArch(nn.Layer):
  13. def __init__(self, data_format='NCHW'):
  14. super(BaseArch, self).__init__()
  15. self.data_format = data_format
  16. self.inputs = {}
  17. self.fuse_norm = False
  18. def load_meanstd(self, cfg_transform):
  19. self.scale = 1.
  20. self.mean = paddle.to_tensor([0.485, 0.456, 0.406]).reshape(
  21. (1, 3, 1, 1))
  22. self.std = paddle.to_tensor([0.229, 0.224, 0.225]).reshape(
  23. (1, 3, 1, 1))
  24. for item in cfg_transform:
  25. if 'NormalizeImage' in item:
  26. self.mean = paddle.to_tensor(item['NormalizeImage'][
  27. 'mean']).reshape((1, 3, 1, 1))
  28. self.std = paddle.to_tensor(item['NormalizeImage'][
  29. 'std']).reshape((1, 3, 1, 1))
  30. if item['NormalizeImage'].get('is_scale', True):
  31. self.scale = 1. / 255.
  32. break
  33. if self.data_format == 'NHWC':
  34. self.mean = self.mean.reshape(1, 1, 1, 3)
  35. self.std = self.std.reshape(1, 1, 1, 3)
  36. def forward(self, inputs):
  37. if self.data_format == 'NHWC':
  38. image = inputs['image']
  39. inputs['image'] = paddle.transpose(image, [0, 2, 3, 1])
  40. if self.fuse_norm:
  41. image = inputs['image']
  42. self.inputs['image'] = (image * self.scale - self.mean) / self.std
  43. self.inputs['im_shape'] = inputs['im_shape']
  44. self.inputs['scale_factor'] = inputs['scale_factor']
  45. else:
  46. self.inputs = inputs
  47. self.model_arch()
  48. if self.training:
  49. out = self.get_loss()
  50. else:
  51. inputs_list = []
  52. # multi-scale input
  53. if not isinstance(inputs, typing.Sequence):
  54. inputs_list.append(inputs)
  55. else:
  56. inputs_list.extend(inputs)
  57. outs = []
  58. for inp in inputs_list:
  59. self.inputs = inp
  60. outs.append(self.get_pred())
  61. # multi-scale test
  62. if len(outs) > 1:
  63. out = self.merge_multi_scale_predictions(outs)
  64. else:
  65. out = outs[0]
  66. return out
  67. def merge_multi_scale_predictions(self, outs):
  68. # default values for architectures not included in following list
  69. num_classes = 80
  70. nms_threshold = 0.5
  71. keep_top_k = 100
  72. if self.__class__.__name__ in ('CascadeRCNN', 'FasterRCNN', 'MaskRCNN'
  73. ):
  74. num_classes = self.bbox_head.num_classes
  75. keep_top_k = self.bbox_post_process.nms.keep_top_k
  76. nms_threshold = self.bbox_post_process.nms.nms_threshold
  77. else:
  78. raise Exception(
  79. "Multi scale test only supports CascadeRCNN, FasterRCNN and MaskRCNN for now"
  80. )
  81. final_boxes = []
  82. all_scale_outs = paddle.concat([o['bbox'] for o in outs]).numpy()
  83. for c in range(num_classes):
  84. idxs = all_scale_outs[:, 0] == c
  85. if np.count_nonzero(idxs) == 0:
  86. continue
  87. r = nms(all_scale_outs[idxs, 1:], nms_threshold)
  88. final_boxes.append(
  89. np.concatenate([np.full((r.shape[0], 1), c), r], 1))
  90. out = np.concatenate(final_boxes)
  91. out = np.concatenate(sorted(
  92. out, key=lambda e: e[1])[-keep_top_k:]).reshape((-1, 6))
  93. out = {
  94. 'bbox': paddle.to_tensor(out),
  95. 'bbox_num': paddle.to_tensor(np.array([out.shape[0], ]))
  96. }
  97. return out
  98. def build_inputs(self, data, input_def):
  99. inputs = {}
  100. for i, k in enumerate(input_def):
  101. inputs[k] = data[i]
  102. return inputs
  103. def model_arch(self, ):
  104. pass
  105. def get_loss(self, ):
  106. raise NotImplementedError("Should implement get_loss method!")
  107. def get_pred(self, ):
  108. raise NotImplementedError("Should implement get_pred method!")