utils.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # -*- coding: utf-8 -*-
  2. from typing import List
  3. import os
  4. from PIL import Image
  5. import numpy as np
  6. import cv2
  7. from shapely.geometry import Polygon
  8. from collections import OrderedDict
  9. def str2bool(v: str) -> bool:
  10. return v.lower() in ("yes", "y", "true", "t", "1")
  11. def copyStateDict(state_dict):
  12. if list(state_dict.keys())[0].startswith("module"):
  13. start_idx = 1
  14. else:
  15. start_idx = 0
  16. new_state_dict = OrderedDict()
  17. for k, v in state_dict.items():
  18. name = ".".join(k.split(".")[start_idx:])
  19. new_state_dict[name] = v
  20. return new_state_dict
  21. def draw_boxes(image: Image.Image, boxes: List[List[List[int]]], line_thickness: int = 2) -> Image.Image:
  22. img = np.array(image)
  23. for i, box in enumerate(boxes):
  24. poly_ = np.array(box_to_poly(box)).astype(np.int32).reshape((-1))
  25. poly_ = poly_.reshape(-1, 2)
  26. cv2.polylines(img, [poly_.reshape((-1, 1, 2))], True, color=(0, 0, 255), thickness=line_thickness)
  27. ptColor = (0, 255, 255)
  28. return Image.fromarray(img)
  29. def draw_polygons(image: Image.Image, polygons: List[List[List[int]]], line_thickness: int = 2) -> Image.Image:
  30. img = np.array(image)
  31. for i, poly in enumerate(polygons):
  32. poly_ = np.array(poly).astype(np.int32).reshape((-1))
  33. poly_ = poly_.reshape(-1, 2)
  34. cv2.polylines(img, [poly_.reshape((-1, 1, 2))], True, color=(0, 0, 255), thickness=line_thickness)
  35. ptColor = (0, 255, 255)
  36. return Image.fromarray(img)
  37. def box_to_poly(box: List[List[int]]) -> List[List[int]]:
  38. return [box[0], [box[0][0], box[1][1]], box[1], [box[1][0], box[0][1]]]
  39. def boxes_area(bboxes: List[List[List[int]]]) -> int:
  40. total_S = 0
  41. for box in bboxes:
  42. pgon = Polygon(box_to_poly(box))
  43. S = pgon.area
  44. total_S+=S
  45. return total_S
  46. def polygons_area(polygons: List[List[List[int]]]) -> int:
  47. total_S = 0
  48. for poly in polygons:
  49. pgon = Polygon(poly)
  50. S = pgon.area
  51. total_S+=S
  52. return total_S