Martin Tomov commited on
Commit
58f6d0d
1 Parent(s): ce4fb35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -6
app.py CHANGED
@@ -46,7 +46,7 @@ class DetectionResult:
46
  )
47
  )
48
 
49
- def annotate(image: Union[Image.Image, np.ndarray], detection_results: List[DetectionResult]) -> np.ndarray:
50
  image_cv2 = np.array(image) if isinstance(image, Image.Image) else image
51
  image_cv2 = cv2.cvtColor(image_cv2, cv2.COLOR_RGB2BGR)
52
 
@@ -57,19 +57,25 @@ def annotate(image: Union[Image.Image, np.ndarray], detection_results: List[Dete
57
  mask = detection.mask
58
  color = np.random.randint(0, 256, size=3).tolist()
59
 
60
- cv2.rectangle(image_cv2, (box.xmin, box.ymin), (box.xmax, box.ymax), color, 2)
61
- cv2.putText(image_cv2, f'{label}: {score:.2f}', (box.xmin, box.ymin - 10),
62
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
63
 
64
  if mask is not None:
65
  mask_uint8 = (mask * 255).astype(np.uint8)
66
  contours, _ = cv2.findContours(mask_uint8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
67
- cv2.drawContours(image_cv2, contours, -1, color, 2)
 
 
 
 
 
 
 
68
 
69
  return cv2.cvtColor(image_cv2, cv2.COLOR_BGR2RGB)
70
 
71
  def plot_detections(image: Union[Image.Image, np.ndarray], detections: List[DetectionResult]) -> np.ndarray:
72
- annotated_image = annotate(image, detections)
73
  return annotated_image
74
 
75
  def load_image(image: Union[str, Image.Image]) -> Image.Image:
 
46
  )
47
  )
48
 
49
+ def annotate_with_transparency(image: Union[Image.Image, np.ndarray], detection_results: List[DetectionResult]) -> np.ndarray:
50
  image_cv2 = np.array(image) if isinstance(image, Image.Image) else image
51
  image_cv2 = cv2.cvtColor(image_cv2, cv2.COLOR_RGB2BGR)
52
 
 
57
  mask = detection.mask
58
  color = np.random.randint(0, 256, size=3).tolist()
59
 
60
+ # Overlay with transparent background
61
+ overlay = np.zeros_like(image_cv2, dtype=np.uint8)
 
62
 
63
  if mask is not None:
64
  mask_uint8 = (mask * 255).astype(np.uint8)
65
  contours, _ = cv2.findContours(mask_uint8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
66
+ cv2.drawContours(overlay, contours, -1, color, -1) # Draw filled contours on the overlay
67
+
68
+ # Blend the overlay with the original image
69
+ alpha = 0.5 # Alpha value to control transparency
70
+ image_cv2 = cv2.addWeighted(image_cv2, 1, overlay, alpha, 0)
71
+
72
+ cv2.putText(image_cv2, f'{label}: {score:.2f}', (box.xmin, box.ymin - 10),
73
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
74
 
75
  return cv2.cvtColor(image_cv2, cv2.COLOR_BGR2RGB)
76
 
77
  def plot_detections(image: Union[Image.Image, np.ndarray], detections: List[DetectionResult]) -> np.ndarray:
78
+ annotated_image = annotate_with_transparency(image, detections)
79
  return annotated_image
80
 
81
  def load_image(image: Union[str, Image.Image]) -> Image.Image: