layout.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from __future__ import annotations
  2. from typing import Dict, List, Optional
  3. import numpy as np
  4. class LayoutBox:
  5. def __init__(
  6. self,
  7. clazz: int,
  8. bbox: List[int],
  9. conf: float,
  10. clazz_name: Optional[str] = None,
  11. ):
  12. self.clazz = clazz
  13. self.clazz_name = clazz_name
  14. self.bbox = bbox
  15. self.conf = conf
  16. @property
  17. def ltrb(self):
  18. l, t, r, b = self.bbox
  19. return [int(x) for x in [l, t, r, b]]
  20. @property
  21. def area(self):
  22. l, t, r, b = self.ltrb
  23. return (r - l + 1) * (b - t + 1)
  24. def iou(self, other):
  25. boxA = self.ltrb
  26. boxB = other.ltrb
  27. boxA = [int(x) for x in boxA]
  28. boxB = [int(x) for x in boxB]
  29. xA = max(boxA[0], boxB[0])
  30. yA = max(boxA[1], boxB[1])
  31. xB = min(boxA[2], boxB[2])
  32. yB = min(boxA[3], boxB[3])
  33. interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
  34. boxAArea = self.area
  35. boxBArea = other.area
  36. iou = interArea / float(boxAArea + boxBArea - interArea)
  37. return iou
  38. def to_dict(self) -> Dict:
  39. return {
  40. "class": self.clazz,
  41. "class_name": self.clazz_name,
  42. "bbox": self.bbox,
  43. "confidence": self.conf,
  44. }
  45. def to_service_dict(self) -> Dict:
  46. """
  47. 返回中间服务所需的格式
  48. """
  49. return {
  50. "class": self.clazz,
  51. "class_name": self.clazz_name,
  52. "bbox": self.ltrb,
  53. "confidence": self.conf,
  54. }
  55. @classmethod
  56. def from_dict(cls, d) -> LayoutBox:
  57. return cls(
  58. clazz=d["class"],
  59. clazz_name=d["class_name"],
  60. bbox=d["bbox"],
  61. conf=d["confidence"],
  62. )
  63. def __repr__(self):
  64. return f"LayoutBox(class={self.clazz}, class_name={self.clazz_name}, bbox={self.bbox}, conf={self.conf})"