iou_aware.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. from paddle import fluid
  18. def _split_ioup(output, an_num, num_classes):
  19. """
  20. Split new output feature map to output, predicted iou
  21. along channel dimension
  22. """
  23. ioup = fluid.layers.slice(output, axes=[1], starts=[0], ends=[an_num])
  24. ioup = fluid.layers.sigmoid(ioup)
  25. oriout = fluid.layers.slice(
  26. output, axes=[1], starts=[an_num], ends=[an_num * (num_classes + 6)])
  27. return (ioup, oriout)
  28. def _de_sigmoid(x, eps=1e-7):
  29. x = fluid.layers.clip(x, eps, 1 / eps)
  30. one = fluid.layers.fill_constant(
  31. shape=[1, 1, 1, 1], dtype=x.dtype, value=1.)
  32. x = fluid.layers.clip((one / x - 1.0), eps, 1 / eps)
  33. x = -fluid.layers.log(x)
  34. return x
  35. def _postprocess_output(ioup, output, an_num, num_classes, iou_aware_factor):
  36. """
  37. post process output objectness score
  38. """
  39. tensors = []
  40. stride = output.shape[1] // an_num
  41. for m in range(an_num):
  42. tensors.append(
  43. fluid.layers.slice(
  44. output,
  45. axes=[1],
  46. starts=[stride * m + 0],
  47. ends=[stride * m + 4]))
  48. obj = fluid.layers.slice(
  49. output, axes=[1], starts=[stride * m + 4], ends=[stride * m + 5])
  50. obj = fluid.layers.sigmoid(obj)
  51. ip = fluid.layers.slice(ioup, axes=[1], starts=[m], ends=[m + 1])
  52. new_obj = fluid.layers.pow(obj, (
  53. 1 - iou_aware_factor)) * fluid.layers.pow(ip, iou_aware_factor)
  54. new_obj = _de_sigmoid(new_obj)
  55. tensors.append(new_obj)
  56. tensors.append(
  57. fluid.layers.slice(
  58. output,
  59. axes=[1],
  60. starts=[stride * m + 5],
  61. ends=[stride * m + 5 + num_classes]))
  62. output = fluid.layers.concat(tensors, axis=1)
  63. return output
  64. def get_iou_aware_score(output, an_num, num_classes, iou_aware_factor):
  65. ioup, output = _split_ioup(output, an_num, num_classes)
  66. output = _postprocess_output(ioup, output, an_num, num_classes,
  67. iou_aware_factor)
  68. return output