
Export Dataset in YOLO Format for Detection or Segmentation
Source:R/utils_yolo_train.R
yolo_dataset_export.RdAutomatically generates a structured YOLO dataset (images/, labels/,
and data.yaml) for object detection (task = "detect") or instance
segmentation (task = "segment"). Annotations can be produced automatically
via deep learning foundation models:
Manual interactive annotation with
model = "manual"(draw bounding boxes directly with 2 clicks per box: zero AI models or GPU required).One-shot visual exemplar auto-labeling with
model = "persam"(Roboflow-style 1-click annotation).Zero-shot text prompt detection with
model = "grounded-sam"(e.g.prompt = "people").Assisted labeling / pseudo-labeling with pre-trained or fine-tuned YOLO models (
model = "custom.onnx").Classical image analysis with
analyze_objects()(model = NULL).
Usage
yolo_dataset_export(
img,
model = NULL,
annotations = "auto",
dir = NULL,
task = c("detect", "segment"),
class_names = c("object"),
class_id = NULL,
prompt = NULL,
prompt_mode = c("first", "each"),
interactive = is.null(prompt) && !is.null(model) && is.character(model) &&
identical(tolower(model[1]), "persam") && base::interactive(),
sim_threshold = 0.5,
min_dist = 20,
box_threshold = 0.25,
text_threshold = 0.25,
iou_threshold = 0.5,
feat_res = 256,
max_objects = NULL,
split_ratio = c(0.7, 0.2, 0.1),
n_points = 40L,
min_area = 15,
filter_edge = FALSE,
crop_to_objects = FALSE,
crop_margin = 0.05,
box_margin = 0.05,
sahi = FALSE,
slice_height = 640,
slice_width = 640,
overlap_height_ratio = 0.2,
overlap_width_ratio = 0.2,
match_metric = c("IOS", "IOU"),
match_threshold = 0.5,
full_image_inference = TRUE,
sahi_if = NULL,
sahi_metric = c("mean", "median", "min"),
sahi_if_empty = TRUE,
lower_size = NULL,
upper_size = NULL,
size_mode = c("relative", "absolute"),
show_similarity = FALSE,
superres_map = FALSE,
review = TRUE,
rainbow = TRUE,
show_bbox = TRUE,
show_polygon = TRUE,
show_points = FALSE,
show_labels = TRUE,
show_conf = TRUE,
bbox = show_bbox,
polygon = show_polygon,
points = show_points,
labels = show_labels,
badge = TRUE,
engine = c("gpu", "cpu"),
sam_device = c("auto", "gpu", "cpu"),
device_id = -1,
move = TRUE,
overwrite = TRUE,
as_job = FALSE,
verbose = TRUE,
...
)Arguments
- img
An
imageobject, a list ofimageobjects, a file path, or a directory path containing images to annotate.- model
Model to use for dataset annotation:
"manual"(or"box","boxes","draw"): Pure manual bounding box labeling. Click 2 opposite corners per box with zero AI models, zero downloads, and instant response."persam": One-shot visual exemplar segmentation and detection (Roboflow-style 1-click auto-labeling)."grounded-sam": Zero-shot text-prompted instance segmentation & detection.Path to a trained YOLO
.onnxmodel (e.g."capsulas_det.onnx"): Assisted labeling / pseudo-labeling."ben2","u2netp","birefnet-lite": Salient foreground object auto-segmentation.NULL(default): Uses classical computer vision segmentation viaanalyze_objects().
- annotations
Annotations source when
model = NULL. Can be:"auto"(default): automatically callsanalyze_objects()on each image.An object or list of objects returned by
analyze_objects().A custom list of contour matrices or bounding boxes.
- dir
Output directory path for the YOLO dataset. If
NULL(default whenimgis a directory path), the dataset structure (images/,labels/,data.yaml) is generated directly insideimg. Specify a directory name only if you wish to create a separate dataset folder.- task
Task type:
"detect"(default) for bounding-box detection or"segment"for polygon instance segmentation.- class_names
Character vector of class names (e.g.
c("capsula")orc("grain", "defect")). Defaults toc("object").- class_id
Numeric class ID or vector of IDs. Defaults to
NULL, which automatically assigns sequential IDs (0, 1, ...) matchingclass_names.- prompt
Prompt specification for deep learning models:
For
model = "persam": Exemplar coordinates (c(x, y)or matrix). IfNULLandinteractive = TRUE, prompts for clicks on the image.For
model = "grounded-sam": Character text prompt (e.g."people","grain","leaf"). Defaults toclass_namesif not supplied.
- prompt_mode
Exemplar prompting mode when labeling multiple images with PerSAM:
"each"(default for interactive): Prompts for exemplar clicks on each image."first": Prompts for exemplar clicks only on the first image, applying the points across all images.
- interactive
Logical. If
TRUE, activates the interactive visual labeling workflow in the plot window, allowing the user to click exemplars, review instant detections with confidence tags, and confirm or adjust. Defaults toTRUEifmodel = "persam",prompt = NULL, and R is running interactively.- sim_threshold
Numeric cosine similarity threshold in
[0, 1]formodel = "persam". Defaults to0.50.- min_dist
Minimum distance (in pixels) between detected objects/peaks for PerSAM exemplar segmentation. Defaults to
20.- box_threshold
Bounding box confidence threshold for Grounded-SAM or YOLO models. Defaults to
0.25.- text_threshold
Text confidence threshold for Grounded-SAM. Defaults to
0.25.- iou_threshold
Non-Maximum Suppression (NMS) IoU threshold. Defaults to
0.50.- feat_res
Feature map resolution for PerSAM (
64,256(default),"sr", or1024).- max_objects
Maximum number of objects detected per image. Defaults to
300.- split_ratio
Numeric vector of length 3 for
c(train, val, test)split. Defaults toc(0.70, 0.20, 0.10). If a vector of length 2 is provided,c(train, val)is assumed. If a single number is given, it is treated as the training proportion.- n_points
Target number of polygon vertices per object for segmentation (default
40). Points are sampled evenly along the contour to keep label files compact and clean.- min_area
Minimum object area (in pixels) to include in the dataset. Defaults to
15.- filter_edge
Logical. Whether to automatically filter out spurious border-cut artifacts touching image edges (default:
FALSE).- crop_to_objects
Logical. If
TRUE, crops the image to the bounding box containing all detected objects plus a margin (default:FALSE).- crop_margin
Numeric. Margin fraction added around the object bounding box when
crop_to_objects = TRUE(default:0.05, i.e., 5%).- box_margin
Safety margin (padding proportion) added around detected bounding boxes before segmenting with Meta SAM 2.1 (e.g.
0.05expands 5% on each side). Prevents masks from cutting off object borders. Defaults to0.05(5%). It is used only for segmentation with SAM: withtask = "detect", the boxes written to the labels are the detected boxes, without margin (in earlier versions they were enlarged bybox_marginon each side, i.e. 10% wider and taller with the default). To expand detection labels on purpose, passpad(fraction per side) through....- sahi
Logical. If
TRUE, applies Slicing-Aided Hyper Inference (SAHI) during YOLO pre-labeling, dividing high-resolution images into overlapping slices to detect small and crowded objects with high precision. Defaults toFALSE.- slice_height, slice_width
Integer dimensions (in pixels) for SAHI slices. Defaults to
640.- overlap_height_ratio, overlap_width_ratio
Overlap ratio between adjacent slices along height and width. Defaults to
0.20(20%).- match_metric
Match metric used for merging slice predictions across boundaries:
"IOS"(Intersection over Smaller, default) or"IOU".- match_threshold
Threshold for match metric to merge overlapping slice predictions. Defaults to
0.50.- full_image_inference
Logical. If
TRUE(default), runs an additional full-image inference pass alongside slice predictions to ensure large objects spanning across multiple slices are captured.- sahi_if
Conditional SAHI trigger. Can be
NULL(default, disabled),TRUE(activates SAHI if average relative box area <= 1% of total image area), or a numeric threshold in(0, 1](e.g.0.005for 0.5% or0.02for 2%). When specified, standard inference runs first; if the objects are small relative to the canvas (or if no objects are detected whensahi_if_empty = TRUE), SAHI is automatically triggered to recover fine details and small instances.- sahi_metric
Character metric to aggregate relative bounding box areas when checking
sahi_if. One of"mean"(default),"median", or"min".- sahi_if_empty
Logical. If
TRUE(default), automatically triggers SAHI when standard inference finds 0 objects on an image larger than the slice dimensions.- lower_size
Optional numeric value to filter out small detected objects. When
size_mode = "relative"(default), objects with a bounding box area less thanlower_sizetimes the mean area of all candidate boxes in that image are removed (e.g.,lower_size = 0.2removes small debris, dust, or grains smaller than 20% of the average object size). Whensize_mode = "absolute", objects with an area (in pixels) belowlower_sizeare removed. Defaults toNULL(no lower size filter).- upper_size
Optional numeric value to filter out abnormally large detected objects. When
size_mode = "relative"(default), objects with a bounding box area greater thanupper_sizetimes the mean area of all candidate boxes in that image are removed (e.g.,upper_size = 2.0removes objects larger than 200% of the average object size). Whensize_mode = "absolute", objects with an area (in pixels) aboveupper_sizeare removed. Defaults toNULL(no upper size filter).- size_mode
Character string specifying how
lower_sizeandupper_sizeare interpreted."relative"(default) treats values as proportions/multiples of the mean bounding box area."absolute"treats values as area in pixels.- show_similarity
Logical. If
TRUE, displays a side-by-side 2-panel preview showing the detected objects on the left and the PerSAM Cosine Similarity Map ("Matriz de Coincidencia") on the right. Defaults toFALSE.- superres_map
Logical. If
TRUE, applies Real-ESRGAN 4x super-resolution on the PerSAM similarity map with bilateral semantic background gating. Default isFALSE.- review
Logical or integer. If
TRUE(default), writes annotated review images to areview/subfolder. An integer can be provided (e.g.review = 100) to randomly sample that number of images across the dataset for review previews. Defaults toTRUE. subfolder indirfor visual inspection of all images. An integer can be provided (e.g.review = 30) to limit the number of review images generated.- rainbow
Logical. If
TRUE(default), plots instances in distinct rainbow colors during interactive review.- show_bbox
Logical. Whether to draw bounding boxes on review previews. Defaults to
TRUE. Supported alias:bbox.- show_polygon
Logical. Whether to draw segmentation polygons on review previews. Defaults to
TRUE. Supported alias:polygon.- show_points
Logical. If
TRUE, draws points at the centroid of each object using the same color as the box. Defaults toFALSE. Supported alias:points.- show_labels
Logical. Whether to display class name on labels/badges during review previews. Defaults to
TRUE. Supported aliases:show_class,labels.- show_conf
Logical. Whether to display confidence score on labels/badges during review previews. Defaults to
TRUE. Supported alias:show_scores.- bbox, polygon, points, labels
Backward-compatible aliases for
show_bbox,show_polygon,show_points, andshow_labels.- badge
Logical. Whether to draw a filled background badge behind labels during interactive review. Defaults to
TRUE.- engine
Computing device engine:
"cpu"(default) or"gpu".- sam_device
Execution device for SAM 2.1 inference:
"auto"(default),"gpu", or"cpu".- device_id
GPU device ID (default
-1).- move
Logical. If
TRUE(default), moves the source images directly into the dataset'simages/split directories instead of copying them.- overwrite
Logical. If
TRUE(default), overwrites existing dataset files indir.- as_job
Logical. If
TRUEand running inside RStudio, runs the dataset export as an RStudio Background Job in the Jobs tab, keeping the current R session free. Defaults toFALSE.- verbose
Logical. If
TRUE(default), displays live progress information.- ...
Additional arguments passed directly to
analyze_objects()whenmodel = NULLandannotations = "auto"(e.g.index = "B",watershed = TRUE,tolerance = 1).
Value
An invisible list containing:
dir: Root directory of the dataset.yaml_file: Full path to the generateddata.yaml.train_images: Vector of paths to training images.val_images: Vector of paths to validation images.test_images: Vector of paths to test images (if test split was generated).review_dir: Path to the review directory containing visual previews (ifreview = TRUE).n_objects: Total number of annotated objects across the dataset.
Details
Automated and Semi-Automated Annotation Modes
PerSAM One-Shot Exemplar Auto-Labeling (
model = "persam"): The user clicks on 1 or more exemplar objects in the plot window. PerSAM extracts visual embeddings from SAM 2.1, calculates the spatial cosine feature similarity map ("matriz de coincidencia"), and identifies all matching instances across the image. Wheninteractive = TRUE, an interactive confirmation menu allows accepting detections (), retrying clicks ( 'r'), or fine-tuning the similarity threshold ('t 0.55') in real-time.Grounded-SAM Text Prompting (
model = "grounded-sam"): Accepts natural language text descriptions (e.g.prompt = "people",prompt = "coffee grain", orclass_names = c("person", "bicycle")) to locate and segment all matching objects.YOLO Pre-Labeling / Active Learning (
model = "<model>.onnx"): Applies an existing trained YOLO model to unannotated images to produce draft labels for rapid dataset expansion. If a YOLO detection model is passed withtask = "segment",plimanautomatically pairs the detected bounding boxes with Meta SAM 2.1 to extract precise sub-pixel instance segmentation polygons.Classical Image Analysis (
model = NULL): Extracts contours viaanalyze_objects()using thresholding, color indexes, and watershed algorithms.
The exported directory adheres to the standard structure expected by YOLOv8, YOLO11, and YOLO26:
Examples
if (FALSE) { # interactive()
library(pliman)
# 1. Semi-Automated 1-Click Labeling with PerSAM:
# Click 1 capsule on screen -> PerSAM finds all 40+ capsules and writes YOLO boxes!
yolo_dataset_export(
"capsulas_raw/",
model = "persam",
task = "detect",
class_names = "capsula",
dir = "dataset_capsulas"
)
# 2. Zero-Shot Text Prompt Labeling with Grounded-SAM:
# Annotate every person in photos automatically:
yolo_dataset_export(
"crowd_photos/",
model = "grounded-sam",
prompt = "people",
class_names = "person",
dir = "dataset_people"
)
# 3. Classical Auto-Annotation with analyze_objects:
yolo_dataset_export(
"cafe_grains/",
task = "segment",
class_names = "grao_cafe",
index = "B",
watershed = TRUE
)
}