visualization.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright 2025 Yakhyokhuja Valikhujaev
  2. # Author: Yakhyokhuja Valikhujaev
  3. # GitHub: https://github.com/yakhyo
  4. from typing import List, Union
  5. import cv2
  6. import numpy as np
  7. def draw_detections(
  8. image: np.ndarray,
  9. bboxes: Union[List[np.ndarray], List[List[float]]],
  10. scores: Union[np.ndarray, List[float]],
  11. landmarks: Union[List[np.ndarray], List[List[List[float]]]],
  12. vis_threshold: float = 0.6,
  13. ):
  14. """
  15. Draws bounding boxes, scores, and landmarks from separate lists onto an image.
  16. Args:
  17. image (np.ndarray): The image to draw on.
  18. bboxes (List[np.ndarray] or List[List[float]]): List of bounding boxes. Each bbox can be
  19. np.ndarray with shape (4,) or list [x1, y1, x2, y2].
  20. scores (List[float] or np.ndarray): List or array of confidence scores.
  21. landmarks (List[np.ndarray] or List[List[List[float]]]): List of landmark sets. Each landmark
  22. set can be np.ndarray with shape (5, 2) or nested list [[[x,y],...],...].
  23. vis_threshold (float): Confidence threshold for filtering which detections to draw.
  24. """
  25. _colors = [(0, 0, 255), (0, 255, 255), (255, 0, 255), (0, 255, 0), (255, 0, 0)]
  26. # Filter detections by score
  27. keep_indices = [i for i, score in enumerate(scores) if score >= vis_threshold]
  28. # Draw the filtered detections
  29. for i in keep_indices:
  30. bbox = np.array(bboxes[i], dtype=np.int32)
  31. score = scores[i]
  32. landmark_set = np.array(landmarks[i], dtype=np.int32)
  33. # Calculate adaptive thickness
  34. thickness = max(1, int(min(bbox[2] - bbox[0], bbox[3] - bbox[1]) / 100))
  35. # Draw bounding box
  36. cv2.rectangle(image, tuple(bbox[:2]), tuple(bbox[2:]), (0, 0, 255), thickness)
  37. # Draw score
  38. cv2.putText(
  39. image,
  40. f'{score:.2f}',
  41. (bbox[0], bbox[1] - 10),
  42. cv2.FONT_HERSHEY_SIMPLEX,
  43. 0.5,
  44. (255, 255, 255),
  45. thickness,
  46. )
  47. # Draw landmarks
  48. for j, point in enumerate(landmark_set):
  49. cv2.circle(image, tuple(point), thickness + 1, _colors[j], -1)