-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblob_counter.py
More file actions
50 lines (37 loc) · 1.51 KB
/
Copy pathblob_counter.py
File metadata and controls
50 lines (37 loc) · 1.51 KB
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
import logging
import cv2
import torch
from ultralytics import YOLO
class BlobCounterBase:
def __init__(self):
pass
def count_blobs(self, image, **kwargs):
raise NotImplementedError("count_blobs must be implemented by subclasses.")
class YOLOBlobCounter(BlobCounterBase):
def __init__(self, model_path):
# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# logging.info(f"Using device: {device}")
super().__init__()
self.model = YOLO(model_path)
self.model.to(torch.device("cpu"))
def count_blobs(self, image, **kwargs):
# Ensure image is RGB
logging.info("Running YOLO inference on image...")
if image.ndim == 2:
img_rgb = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
elif image.shape[2] == 3:
img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
else:
raise ValueError("Unsupported image shape for YOLO inference.")
# Run YOLO inference
results = self.model.predict(source=img_rgb, verbose=False)
keypoints = []
# Handle results
if not results or not hasattr(results[0], "boxes") or results[0].boxes is None:
return keypoints
boxes = results[0].boxes
xywh = boxes.xywh.cpu().numpy() if hasattr(boxes, "xywh") else []
for x_center, y_center, w, h in xywh:
size = max(w, h)
keypoints.append(cv2.KeyPoint(float(x_center), float(y_center), float(size)))
return keypoints