You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
1.8 KiB
40 lines
1.8 KiB
2 years ago
|
from pathlib import Path
|
||
|
|
||
1 year ago
|
from ultralytics import SAM, YOLO
|
||
2 years ago
|
|
||
|
|
||
|
def auto_annotate(data, det_model='yolov8x.pt', sam_model='sam_b.pt', device='', output_dir=None):
|
||
2 years ago
|
"""
|
||
|
Automatically annotates images using a YOLO object detection model and a SAM segmentation model.
|
||
|
Args:
|
||
|
data (str): Path to a folder containing images to be annotated.
|
||
|
det_model (str, optional): Pre-trained YOLO detection model. Defaults to 'yolov8x.pt'.
|
||
|
sam_model (str, optional): Pre-trained SAM segmentation model. Defaults to 'sam_b.pt'.
|
||
|
device (str, optional): Device to run the models on. Defaults to an empty string (CPU or GPU, if available).
|
||
2 years ago
|
output_dir (str | None | optional): Directory to save the annotated results.
|
||
2 years ago
|
Defaults to a 'labels' folder in the same directory as 'data'.
|
||
|
"""
|
||
2 years ago
|
det_model = YOLO(det_model)
|
||
1 year ago
|
sam_model = SAM(sam_model)
|
||
2 years ago
|
|
||
|
if not output_dir:
|
||
|
output_dir = Path(str(data)).parent / 'labels'
|
||
|
Path(output_dir).mkdir(exist_ok=True, parents=True)
|
||
|
|
||
1 year ago
|
det_results = det_model(data, stream=True, device=device)
|
||
2 years ago
|
|
||
|
for result in det_results:
|
||
|
boxes = result.boxes.xyxy # Boxes object for bbox outputs
|
||
|
class_ids = result.boxes.cls.int().tolist() # noqa
|
||
2 years ago
|
if len(class_ids):
|
||
1 year ago
|
sam_results = sam_model(result.orig_img, bboxes=boxes, verbose=False, save=False, device=device)
|
||
|
segments = sam_results[0].masks.xyn # noqa
|
||
2 years ago
|
|
||
|
with open(str(Path(output_dir) / Path(result.path).stem) + '.txt', 'w') as f:
|
||
|
for i in range(len(segments)):
|
||
|
s = segments[i]
|
||
|
if len(s) == 0:
|
||
|
continue
|
||
|
segment = map(str, segments[i].reshape(-1).tolist())
|
||
|
f.write(f'{class_ids[i]} ' + ' '.join(segment) + '\n')
|