iou.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
  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. """
  15. This code is refer from:
  16. https://github.com/whai362/PSENet/blob/python3/models/loss/iou.py
  17. """
  18. import paddle
  19. EPS = 1e-6
  20. def iou_single(a, b, mask, n_class):
  21. valid = mask == 1
  22. a = a.masked_select(valid)
  23. b = b.masked_select(valid)
  24. miou = []
  25. for i in range(n_class):
  26. if a.shape == [0] and a.shape == b.shape:
  27. inter = paddle.to_tensor(0.0)
  28. union = paddle.to_tensor(0.0)
  29. else:
  30. inter = ((a == i).logical_and(b == i)).astype('float32')
  31. union = ((a == i).logical_or(b == i)).astype('float32')
  32. miou.append(paddle.sum(inter) / (paddle.sum(union) + EPS))
  33. miou = sum(miou) / len(miou)
  34. return miou
  35. def iou(a, b, mask, n_class=2, reduce=True):
  36. batch_size = a.shape[0]
  37. a = a.reshape([batch_size, -1])
  38. b = b.reshape([batch_size, -1])
  39. mask = mask.reshape([batch_size, -1])
  40. iou = paddle.zeros((batch_size, ), dtype='float32')
  41. for i in range(batch_size):
  42. iou[i] = iou_single(a[i], b[i], mask[i], n_class)
  43. if reduce:
  44. iou = paddle.mean(iou)
  45. return iou