Skip to content

Note

Click here to download the full example code

Mosquito Segmentation Tutorial

This tutorial demonstrates how to use the culicidaelab library to perform mosquito segmentation on images. We'll cover:

  1. Setting up the segmentation model
  2. Loading segmentation data from the dataset
  3. Running segmentation
  4. Visualizing results
  5. Evaluating performance with ground truth masks

Install the culicidaelab library if not already installed

!pip install -q culicidaelab[full]
or, if you have access to GPU
!pip install -q culicidaelab[full-gpu]
Import necessary libraries

import matplotlib.pyplot as plt
import numpy as np

from culicidaelab import MosquitoSegmenter, MosquitoDetector
from culicidaelab import DatasetsManager, get_settings

1. Initialize Settings and Load Dataset

First, we'll initialize our settings, create MosquitoSegmenter and load the segmentation dataset:

Get settings instance and initialize dataset manager

settings = get_settings()
manager = DatasetsManager(settings)

# Load segmentation dataset
seg_data = manager.load_dataset("segmentation", split="train[:20]")

# Initialize segmenter and detector
segmenter = MosquitoSegmenter(settings=settings, load_model=True)
detector = MosquitoDetector(settings=settings, load_model=True)

Out:

Cache hit for split config: train[:20] C:\Users\lenova\AppData\Local\culicidaelab\culicidaelab\datasets\mosquito_segmentation\9e9940e1c673b6f0

2. Inspect a Segmentation Sample

Let's examine a sample from the segmentation dataset to understand its structure:

Inspect a segmentation sample

seg_sample = seg_data[0]
seg_image = seg_sample["image"]
seg_mask = np.array(seg_sample["label"])  # Convert mask to numpy array

print(f"Image size: {seg_image.size}")
print(f"Segmentation mask shape: {seg_mask.shape}")
print(f"Unique values in mask: {np.unique(seg_mask)}")  # 0 is background, 1 and above is mosquito

# Create a colored overlay for the mask
# Where the mask is 1 and above (mosquito), we make it red
overlay = np.zeros((*seg_mask.shape, 4), dtype=np.uint8)
overlay[seg_mask >= 1] = [255, 0, 0, 128]  # Red color with 50% opacity

Out:

Image size: (224, 224)
Segmentation mask shape: (224, 224)
Unique values in mask: [  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78
  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
 158 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254]

3. Run Segmentation on Dataset Image

Now we can run the segmentation model on our dataset image:

Run detection to get bounding boxes

result = detector.predict(seg_image)
bboxes = [detection.box.to_numpy() for detection in result.detections]
# Run segmentation with detection boxes
predicted_mask = segmenter.predict(seg_image, detection_boxes=np.array(bboxes))

# Create visualizations
annotated_image = detector.visualize(seg_image, result)
segmented_image = segmenter.visualize(annotated_image, predicted_mask)

4. Visualize Results with Ground Truth Comparison

Let's visualize the segmentation results alongside the ground truth mask:

plt.figure(figsize=(20, 10))

# Original image
plt.subplot(2, 4, 1)
plt.imshow(seg_image)
plt.axis("off")
plt.title("Original Image")

# Ground truth mask
plt.subplot(2, 4, 2)
plt.imshow(seg_mask, cmap="gray")
plt.axis("off")
plt.title("Ground Truth Mask")

# Ground truth overlay
plt.subplot(2, 4, 3)
plt.imshow(seg_image)
plt.imshow(overlay, alpha=0.5)
plt.axis("off")
plt.title("Ground Truth Overlay")

# Detections
plt.subplot(2, 4, 4)
plt.imshow(annotated_image)
plt.axis("off")
plt.title("Detected Mosquitoes")

# Predicted mask
plt.subplot(2, 4, 5)
plt.imshow(predicted_mask.mask, cmap="gray")
plt.axis("off")
plt.title("Predicted Mask")

# Predicted overlay
predicted_overlay = np.zeros((*predicted_mask.mask.shape, 4), dtype=np.uint8)
predicted_overlay[predicted_mask.mask >= 0.5] = [0, 255, 0, 128]  # Green for predictions
plt.subplot(2, 4, 6)
plt.imshow(seg_image)
plt.imshow(predicted_overlay, alpha=0.5)
plt.axis("off")
plt.title("Predicted Overlay")

# Combined overlay (ground truth + predictions)
combined_overlay = np.zeros((*predicted_mask.mask.shape, 4), dtype=np.uint8)
combined_overlay[seg_mask >= 1] = [255, 0, 0, 128]  # Red for ground truth
combined_overlay[predicted_mask.mask >= 0.5] = [0, 255, 0, 128]  # Green for predictions
plt.subplot(2, 4, 7)
plt.imshow(seg_image)
plt.imshow(combined_overlay, alpha=0.5)
plt.axis("off")
plt.title("Combined Overlay\n(Red: GT, Green: Pred)")

# Final segmented image
plt.subplot(2, 4, 8)
plt.imshow(segmented_image)
plt.axis("off")
plt.title("Final Segmented Image")

plt.tight_layout()
plt.show()

Original Image, Ground Truth Mask, Ground Truth Overlay, Detected Mosquitoes, Predicted Mask, Predicted Overlay, Combined Overlay (Red: GT, Green: Pred), Final Segmented Image

Out:

C:/Users/lenova/CascadeProjects/culicidaelab/docs/en/examples/tutorial_part_3_mosquito_segmentation.py:168: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
  plt.show()

5. Evaluate Segmentation Performance

Let's evaluate the segmentation results using the ground truth mask:

metrics = segmenter.evaluate(
    prediction=predicted_mask,
    ground_truth=seg_mask,
)
print("Segmentation Evaluation Metrics:")
for key, value in metrics.items():
    if isinstance(value, float):
        print(f"  {key}: {value:.4f}")
    else:
        print(f"  {key}: {value}")

Out:

Segmentation Evaluation Metrics:
  iou: 0.8464
  precision: 0.9984
  recall: 0.8476
  f1: 0.9168

Total running time of the script: ( 0 minutes 15.147 seconds)

Download Python source code: tutorial_part_3_mosquito_segmentation.py

Download Jupyter notebook: tutorial_part_3_mosquito_segmentation.ipynb

Gallery generated by mkdocs-gallery