
Real-Time Video Object Detection with YOLO (ONNX Runtime)
Source:R/utils_video.R
video_detect_dl.RdPerforms real-time object detection and tracking on video files (.mp4, .avi,
.mov) or live camera feeds (webcam) using YOLO models via native C++ ONNX
Runtime. When return_data = TRUE, it computes an extensive ecological and
temporal community profile (richness, abundance, Shannon diversity, Simpson
index, Pielou evenness, species accumulation curves, and class persistence
rates).
Usage
video_detect_dl(
video = 0,
model = "yolo26n",
conf_threshold = 0.25,
iou_threshold = 0.45,
labels = NULL,
classes = NULL,
detect = TRUE,
output = NULL,
save_video = !is.null(output),
return_data = TRUE,
track = FALSE,
min_frames = 20L,
interpolate_box = FALSE,
interpolate_mask = FALSE,
trail = FALSE,
cex = 1,
pad = 1,
badge = TRUE,
show_text = TRUE,
show_conf = TRUE,
show_class = TRUE,
show_id = FALSE,
text_size = 1,
text_size_telemetry = NULL,
text_size_objects = NULL,
text_size_roi = NULL,
count_line = NULL,
count_line_orientation = c("vertical", "horizontal"),
count_line_label = NULL,
count_direction = c("both", "forward", "backward"),
roi = NULL,
roi_orientation = c("vertical", "horizontal"),
roi_mode = c("crop", "filter"),
roi_label = "ROI / MONITORED ZONE",
hide_outside_roi = TRUE,
hide_counted = TRUE,
flash_counted = TRUE,
fullscreen = FALSE,
window_size = NULL,
window_scale = 1,
resolution = NULL,
crop = NULL,
backend = c("native", "auto"),
skeleton = TRUE,
kpt_threshold = 0.3,
kpt_radius = 4,
bbox = TRUE,
show_box = NULL,
show_point = FALSE,
point_radius = 4,
point_col = NULL,
mask = TRUE,
alpha = 0.4,
saturation = 1,
contrast = 1,
heatmap = FALSE,
heatmap_alpha = 0.75,
heatmap_decay = 0.98,
sahi = FALSE,
slice_height = NULL,
slice_width = NULL,
overlap_ratio = 0.2,
save_crops = FALSE,
crops_dir = NULL,
start_time = NULL,
end_time = NULL,
show = NULL,
show_fps = TRUE,
telemetry = c("detailed", "simple", "none"),
smoot_stat = 20,
hud_pos = c("top-right", "top-left", "bottom-left", "bottom-right", "top", "bottom"),
hud_layout = c("vertical", "horizontal"),
infer_every = 1L,
max_frames = NULL,
fps = NULL,
col = NULL,
lwd = 2,
rainbow = TRUE,
engine = c("gpu", "cpu"),
device_id = -1,
threads = 0,
dir = pliman_model_dir(),
imgsz = NULL,
filter_nested = TRUE,
max_det = 0,
as_job = FALSE,
verbose = TRUE,
tracker = c("ocsort_byte", "ocsort", "bytetrack", "sort", "simple"),
tracker_control = list(),
bitrate = NULL,
...
)
video_detect(
video = 0,
model = "yolo26n",
conf_threshold = 0.25,
iou_threshold = 0.45,
labels = NULL,
classes = NULL,
detect = TRUE,
output = NULL,
save_video = !is.null(output),
return_data = TRUE,
track = FALSE,
min_frames = 20L,
interpolate_box = FALSE,
interpolate_mask = FALSE,
trail = FALSE,
cex = 1,
pad = 1,
badge = TRUE,
show_text = TRUE,
show_conf = TRUE,
show_class = TRUE,
show_id = FALSE,
text_size = 1,
text_size_telemetry = NULL,
text_size_objects = NULL,
text_size_roi = NULL,
count_line = NULL,
count_line_orientation = c("vertical", "horizontal"),
count_line_label = NULL,
count_direction = c("both", "forward", "backward"),
roi = NULL,
roi_orientation = c("vertical", "horizontal"),
roi_mode = c("crop", "filter"),
roi_label = "ROI / MONITORED ZONE",
hide_outside_roi = TRUE,
hide_counted = TRUE,
flash_counted = TRUE,
fullscreen = FALSE,
window_size = NULL,
window_scale = 1,
resolution = NULL,
crop = NULL,
backend = c("native", "auto"),
skeleton = TRUE,
kpt_threshold = 0.3,
kpt_radius = 4,
bbox = TRUE,
show_box = NULL,
show_point = FALSE,
point_radius = 4,
point_col = NULL,
mask = TRUE,
alpha = 0.4,
saturation = 1,
contrast = 1,
heatmap = FALSE,
heatmap_alpha = 0.75,
heatmap_decay = 0.98,
sahi = FALSE,
slice_height = NULL,
slice_width = NULL,
overlap_ratio = 0.2,
save_crops = FALSE,
crops_dir = NULL,
start_time = NULL,
end_time = NULL,
show = NULL,
show_fps = TRUE,
telemetry = c("detailed", "simple", "none"),
smoot_stat = 20,
hud_pos = c("top-right", "top-left", "bottom-left", "bottom-right", "top", "bottom"),
hud_layout = c("vertical", "horizontal"),
infer_every = 1L,
max_frames = NULL,
fps = NULL,
col = NULL,
lwd = 2,
rainbow = TRUE,
engine = c("gpu", "cpu"),
device_id = -1,
threads = 0,
dir = pliman_model_dir(),
imgsz = NULL,
filter_nested = TRUE,
max_det = 0,
as_job = FALSE,
verbose = TRUE,
tracker = c("ocsort_byte", "ocsort", "bytetrack", "sort", "simple"),
tracker_control = list(),
bitrate = NULL,
...
)Arguments
- video
Input video source. Either a camera index (e.g.
0,1), a camera name or substring (e.g."EMEET","HD User Facing"),"camera"(default camera0), or a path to a video file (e.g.,"field_drone.mp4").- model
Model name or path to a custom ONNX file. Defaults to
"yolo26n". Pre-trained options include"yolo26n","yolo26s","yolov8n","yolov8s","yolov11n", etc., or a full path to a custom user-trained.onnxmodel.- conf_threshold
Minimum confidence threshold for candidate detections (default 0.25).
- iou_threshold
IoU threshold for Non-Maximum Suppression (default 0.45).
- labels
Optional character vector of class names. If
NULL(default), labels are automatically detected from model metadata or fallback to standard classes.- classes
Optional character vector of specific class names to filter and retain. If specified, only detections matching these classes will be kept.
- detect
Logical. Whether to run object detection model inference. If
FALSE, the camera/video stream runs in pass-through mode without neural network inference, allowing fast real-time streaming and recording. Defaults toTRUE.- output
Optional output file path (e.g.
"annotated_video.mp4") to save the processed video.- save_video
Logical. Whether to save the processed video. Automatically
TRUEifoutputis specified.- return_data
Logical. Whether to compute and return the detection dataset and ecological summary statistics (default
TRUE). IfFALSE, returnsinvisible(NULL).- track
Logical. Whether to enable multi-object tracking and assign persistent IDs (
#1,#2, etc.) across frames. Defaults toFALSE.- min_frames
Minimum number of frames an object must persist to be retained. When tracking, it is also the number of hits a track needs before its box/point is drawn, which suppresses flickering false positives. Defaults to
20L. Set to0orNULLto retain all detections.- interpolate_box
Logical. Whether to temporally interpolate bounding box positions for tracked objects across briefly lost or occluded frames using velocity motion vectors (default
FALSE). In practice, a confirmed track that misses a detection on an inferred frame keeps being drawn at its velocity-extrapolated position for up tomax_lostinferred frames.- interpolate_mask
Logical. Whether to interpolate instance segmentation masks alongside interpolated bounding boxes (default
FALSE).- trail
Logical. Whether to draw historical trajectory motion trail lines behind tracked objects when
track = TRUE. Defaults toFALSE.- cex
Size factor for label text (default
1.0). Use smaller values (e.g.,cex = 0.2or0.5) to reduce text size for dense scenes or many objects.- pad
Padding multiplier controlling the area/background badge size around label text (default
1.0). Can be a single value or a length-2 vectorc(pad_x, pad_y). Usepad = 0or smaller values for a compact area.- badge
Logical. Whether to draw a solid background badge behind label text (default
TRUE). IfFALSE, only the text is drawn directly.- show_text
Logical. Whether to display text badges above bounding boxes (default
TRUE).- show_conf
Logical. Whether to display confidence scores in badges (default
TRUE).- show_class
Logical. Whether to display class label names in badges (default
TRUE).- show_id
Logical. Whether to display persistent tracking IDs (
#1,#2) in badges whentrack = TRUE(defaultFALSE).- text_size
Numeric font scale for bounding box text labels and/or telemetry HUD (alias for
cex, default1.0). Can be a single numeric value (applied to both objects and telemetry HUD) or a numeric vector of length 2c(objects, telemetry)to scale them independently (e.g.text_size = c(1, 3)).- text_size_telemetry
Numeric font scale specifically for the telemetry HUD overlay (e.g.,
text_size_telemetry = 3). If provided, overrides the telemetry component oftext_size. Set to0to hide telemetry text.- text_size_objects
Numeric font scale specifically for detected object bounding box labels and badges (e.g.,
text_size_objects = 1). If provided, overrides the object component oftext_size.- text_size_roi
Numeric font scale specifically for Region of Interest (ROI).
- count_line
Optional virtual counting tripwire line. Can be specified as a single numeric value between
0and1(indicating relative position along the axis, e.g.0.5for center) combined withcount_line_orientation, or legacy 4-element coordinatesc(x1, y1, x2, y2). Objects crossing this virtual line are counted.- count_line_orientation
Orientation of the counting line when
count_lineis a single scalar: either"vertical"(default) or"horizontal". Can also be passed ascount_line_dir.- count_line_label
Optional label displayed along the counting line (default
NULL, no text).- count_direction
Character string specifying which crossing direction(s) trigger counting when
count_lineis set:"both"(default),"forward", or"backward"."forward"is a left-to-right crossing of a vertical line or a top-to-bottom crossing of a horizontal line.- roi
Optional Region of Interest coordinates. Can be specified as a numeric vector of length 2
c(min, max)in relative coordinates (0to1) combined withroi_orientation(e.g.,roi = c(0.2, 0.8), roi_orientation = "vertical"), or legacy 4-element coordinatesc(xmin, ymin, xmax, ymax).- roi_orientation
Orientation of the ROI band when
roihas length 2: either"vertical"(default) or"horizontal". Can also be passed asroi_dir.- roi_mode
Either
"crop"(infer only inside ROI) or"filter"(detect everywhere, retain only detections inside ROI).- roi_label
Label displayed on the ROI box (default
"ROI / MONITORED ZONE").- hide_outside_roi
Logical. Whether to remove / suppress bounding boxes and visual annotations for objects outside the ROI zone. Defaults to
TRUEwhenroiis provided.- hide_counted
Logical. Whether to remove / suppress bounding boxes for objects that have already crossed the virtual counting line. Defaults to
TRUEwhen counting / tracking is active.- flash_counted
Logical. Whether to show a brief neon green confirmation flash (~12 frames) when an object crosses the counting line before removing its bounding box. Defaults to
TRUE.- fullscreen
Logical. Whether to display the video feed in full screen mode (default
FALSE).- window_size
Optional numeric vector
c(width, height)for the display window.- window_scale
Scaling factor for the display window (default 1.0).
- resolution
Optional camera capture resolution as a numeric vector
c(width, height), e.g.c(1920, 1080)orc(1280, 720). Default isNULL(uses native sensor resolution).- crop
Optional frame cropping. Set to
"1:1","square", orTRUEfor an automatic 1:1 centered square crop (e.g. 1080x1080 or 720x720), orc(width, height)for a custom centered rectangular crop. Default isNULL.- backend
Camera and display backend:
"native"(default, uses native Windows Media Foundation / Win32 GDI with zero external dependencies).- skeleton
Logical. Whether to render the 17-keypoint anatomical skeleton when running pose estimation models (e.g.
"yolo26n-pose"). Defaults toTRUE.- kpt_threshold
Minimum confidence threshold for rendering individual keypoints and skeleton limbs (default 0.3).
- kpt_radius
Integer radius of keypoint joint markers in pixels (default 4).
- bbox, show_box
Logical. Whether to render bounding boxes around detected objects or people (default
TRUE).- show_point
Logical. Whether to render centroid markers/points for detected objects (default
FALSE).- point_radius
Integer radius of centroid markers in pixels (default 4).
- point_col
Optional color for centroid markers. If
NULL(default), matches the object's class/instance palette.- mask
Logical. Whether to render semi-transparent instance segmentation masks when using segmentation models (default
TRUE).- alpha
Opacity/transparency of instance segmentation masks (default
0.4, range0to1).- saturation
Numeric color saturation multiplier applied in-place via native C++ OpenMP fixed-point arithmetic (default
1.0). Values> 1.0(e.g.,1.3or1.5) boost vividness on flat/washed-out.rawor log-profile footage with zero FPS penalty.- contrast
Numeric contrast multiplier around midpoint luma applied in-place via native C++ OpenMP fixed-point arithmetic (default
1.0). Values> 1.0(e.g.,1.2or1.4) enhance dynamic range on flat footage with zero FPS penalty.- heatmap
Logical. Whether to render a cumulative spatial density heatmap overlay for detected objects. Defaults to
FALSE.- heatmap_alpha
Numeric opacity in
[0, 1]for the spatial density heatmap overlay. Defaults to0.75.- heatmap_decay
Numeric decay factor in
(0, 1]controlling how quickly older detections fade from the heatmap per frame. Defaults to0.98.- sahi
Logical. Whether to enable SAHI (Slicing Aided Hyper Inference) tiled detection on each video frame for small/distant objects. Defaults to
FALSE.- slice_height
Optional integer height of SAHI sliding window slices (in pixels). Defaults to
NULL(auto-sized).- slice_width
Optional integer width of SAHI sliding window slices (in pixels). Defaults to
NULL(auto-sized).- overlap_ratio
Numeric overlap fraction in
[0, 0.5)between adjacent SAHI slices. Defaults to0.2.- save_crops
Logical. Whether to save cropped images of detected objects to disk. Defaults to
FALSE.- crops_dir
Optional character directory path where cropped object images are saved when
save_crops = TRUE. Defaults toNULL.- start_time
Optional numeric start timestamp (in seconds) from which to begin processing a video file. Defaults to
NULL.- end_time
Optional numeric end timestamp (in seconds) at which to stop processing a video file. Defaults to
NULL.- show
Logical. Whether to display the video feed with bounding boxes in real time.
NULL(default) meansinteractive()for cameras andFALSEfor video files. On Windows frames are shown in a native window; on other systems the R graphics device is used, which is much slower (see "Performance").- show_fps
Logical. Whether to overlay a real-time FPS and detection counter badge (default
TRUE).- telemetry
Telemetry HUD display mode:
"detailed"(default, glassmorphic diagnostic HUD card with real-time FPS, latency breakdown (inference, tracking, GUI), object counts, confidence statistics, flow rate, motion velocity, ROI occupancy, and 20-frame sparkline trend),"simple"(compact FPS, in-zone, and count badges), or"none"(disables HUD overlay).- smoot_stat
Window size (in frames) for moving average of telemetry statistics (default
20). Internally, the moving average of metrics (SPEED, LATENCY, INF, TRK, GUI, CONF, FLOW, MOTION, SIZE, ROI OCC) is updated on every single frame, but displayed values on the telemetry HUD are refreshed everysmoot_statframes. Frame number, in-zone count, counted total, and active tracks are displayed instantaneously on every frame. Supported aliases:smooth_stat,smooth_stats,smoot_stats.- hud_pos
Screen position of the telemetry HUD card: either a preset string (
"top-right"(default, avoids top-left ROI zone),"top-left","bottom-left","bottom-right","top", or"bottom"), or a numeric vector of length 2c(x, y)specifying relative coordinates in range 0 to 1 across frame width and height (e.g.,c(0.2, 0.5)).- hud_layout
Layout style of the telemetry HUD:
"vertical"(default modern multi-row glassmorphic card) or"horizontal"(sleek capsule pill bar).- infer_every
Integer stride for neural network inference (default
1L, running inference on every frame). Setting e.g.infer_every = 2L(or using aliasstride = 2/skip_frames = 1) runs the heavy neural network on the first frame and on everyinfer_every-th frame; the intermediate frames reuse (hold) the detections, tracks and masks of the last inferred frame without re-running the tracker, cutting compute time roughly by the stride factor. Track velocities,max_lostand the crossing test therefore operate per inferred frame, so fast objects need a smaller stride.- max_frames
Optional maximum number of frames to process. Default is
NULL(all frames).- fps
Target framerate for video output. If
NULL(default), matches the source video or camera.- col
Optional color or palette for bounding boxes. If
NULL, distinct colors are assigned.- lwd
Line width for bounding boxes (default 2).
- rainbow
Logical. If
TRUE, assigns distinct colors per detected instance.- engine
Execution engine:
"gpu"(DirectML, default) or"cpu".- device_id
GPU device ID (default -1 for auto).
- threads
Number of CPU threads (default 0 for auto-tuning).
- dir
Directory where pre-trained models are stored (default
pliman_model_dir()).- imgsz
Target input image resolution for YOLO inference (e.g.,
640,960, or1024). IfNULL(default), inferred automatically from the model or defaults to640.- filter_nested
Logical. If
TRUE(default), removes boxes that contain a smaller, confident box (typical double detections of the same object). Set toFALSEto keep every detection returned by the model.- max_det
Integer. Maximum number of detections kept per frame (or per SAHI tile) after non-maximum suppression, highest scores first.
0(default) keeps all.- as_job
Logical. If
TRUEand running inside RStudio, dispatches the video processing task to an asynchronous RStudio Background Job, keeping the R console free. Default isFALSE.- verbose
Logical. Whether to show progress messages.
- tracker
Association method used when tracking:
"ocsort_byte"(default),"ocsort","bytetrack","sort"or"simple"; see the tracking section. Passing this argument with a value other than"simple"turnstrackon. With"ocsort_byte"and"bytetrack"the network is run with the confidencelow_thresh(default 0.1) while tracking, so that weak detections can extend existing tracks; they never start a track.- tracker_control
Named list overriding individual settings of
tracker, usually built withvideo_tracker_control().- bitrate
Bitrate of the saved H.264 video, in megabits per second (e.g.
bitrate = 40). Defaults toNULL, which uses about 0.15 bit per pixel per frame, between 1 and 20 Mbit/s (about 9 Mbit/s for 1080p at 30 fps). At a fixed bitrate, frames with many annotations (hundreds of boxes over the whole frame) are compressed harder and show block artifacts; raise it when frames will be extracted for figures (e.g. withframe_to_img()). Applies to the native Windows (Media Foundation) writer; ignored by theavfallback.- ...
Additional arguments passed to graphics plotting functions or aliases (
camera,cam,device,infer,inference,save,return_df,return_detections).
Value
If return_data = TRUE, an object of class c("pliman_video_detect", "list") containing:
summary: Adata.frameof video-level metadata and ecological diversity metrics:video_source,model,engine,total_frames,fps,duration_sec,total_detections(\(N\)),total_richness(\(S\)),unique_objects(\(U\)),avg_abundance_frame(\(\bar{N}\)),max_abundance_frame(\(N_{\text{peak}}\)),peak_frame(\(t_{\text{peak}}\)),peak_time_sec(\(T_{\text{peak}}\)),shannon_index(\(H'\)),simpson_index(\(1-D\)),pielou_evenness(\(J'\)), and optionallytotal_counted(whencount_lineis used).by_class: Adata.framesorted by total detections detailing per-class metrics:class,total_detections(\(n_c\)),relative_abundance(\(p_c\), \unique_objects(\(U_c\)),n_frames_present(\(F_c\)),occurrence_rate(\(O_c\), \mean_abundance_when_present(\(\bar{n}_{c, \text{present}}\)),mean_abundance_overall(\(\bar{n}_{c, \text{overall}}\)),max_per_frame,mean_confidence(\(\bar{s}_c\)),first_seen_sec(\(t_{\text{first}, c}\)),last_seen_sec(\(t_{\text{last}, c}\)), and optionallytotal_counted.unique_objects: Adata.frameaggregating every unique tracked object across all observed frames:id,label,n_frames,first_frame,last_frame,duration_sec,mean_score, and (when using instance segmentation models) detailed morphological shape features:area(in pixels),area_sd,perimeter,radius_mean,length,width,circularity,eccentricity, andasp_ratio.temporal: Adata.frameof frame-by-frame time series at resolution \(t \in \{1, \dots, F\}\):frame,timestamp(in seconds), instantaneousabundance(\(N_t\)), instantaneousrichness(\(S_t\)), instantaneousshannondiversity (\(H'_t\)), and individual count columns for every detected class.cumulative: Adata.frameof cumulative progression:frame,timestamp,cumulative_detections(\(N_{\text{cum}}(t)\)),cumulative_richness(Species Accumulation Curve / Collector's Curve, \(S_{\text{cum}}(t)\)), and optionallycumulative_unique_objects(\(U_{\text{cum}}(t)\)).diversity: Alistcontaining global ecological diversity indices:richness_S(\(S\)),total_abundance_N(\(N\)),shannon_H(\(H'\)),simpson_1_minus_D(\(1 - D\)),simpson_D(\(D\)),pielou_J(\(J'\)),berger_parker_d(\(d\)),mean_richness_per_frame, andmean_abundance_per_frame.detections: Adata.frameof all raw candidate detections across all frames:frame,timestamp,id,xmin,ymin,xmax,ymax,label,score, andclass_id(plus shape features when running segmentation models).crossings: (Optional) Adata.frameof virtual tripwire crossing events whencount_lineis specified.keypoints: (Optional) Adata.frameof 17 keypoint anatomical landmarks when running pose estimation models.roi,roi_mode,count_line,output: Additional metadata reflecting execution configuration.
If return_data = FALSE, returns invisible(NULL).
Details
Ecological and Analytical Framework
In automated phenotyping, precision agriculture, ecological monitoring, and industrial inspection, a video stream represents a continuous temporal transect composed of \(F\) sequential frames recorded at a frame rate of \(\text{FPS}\) frames per second. In each frame \(t \in \{1, \dots, F\}\), deep neural network inference detects candidate bounding boxes belonging to \(S_t\) recognized classes.
By aggregating detections over space and time, video_detect_dl translates raw computer vision
detections into standardized ecological metrics, quantifying instantaneous community state,
temporal persistence, class dominance, and cumulative discovery rates.
Abundance Metrics and Density Dynamics
Abundance characterizes the numerical density of detected objects:
Instantaneous Abundance (\(N_t\)): The total count of object instances detected in frame \(t\): $$N_t = \sum_{c=1}^S n_{t, c}$$ where \(n_{t, c}\) is the count of detected objects belonging to class \(c\) in frame \(t\), and \(S\) is the total number of candidate classes.
Total Video Abundance (\(N\)): The cumulative sum of all detections identified across the processed footage: $$N = \sum_{t=1}^F N_t = \sum_{c=1}^S n_c$$ where \(n_c = \sum_{t=1}^F n_{t, c}\) is the total detection count for class \(c\).
Average Abundance per Frame (\(\bar{N}\)): Quantifies the baseline object density per frame: $$\bar{N} = \frac{N}{F}$$
Peak Abundance (\(N_{\text{peak}}\)): The maximum instantaneous count observed in any single frame: $$N_{\text{peak}} = \max_{1 \le t \le F} N_t$$ The exact frame index \(t_{\text{peak}} = \operatorname{argmax}_t N_t\) and corresponding timestamp (in seconds) \(T_{\text{peak}} = (t_{\text{peak}} - 1) / \text{FPS}\) identify the moment of maximum congestion or cluster density.
Richness and Species Accumulation Dynamics
Richness quantifies class variety and categorical complexity over time:
Instantaneous Richness (\(S_t\)): The number of distinct classes co-occurring simultaneously in frame \(t\): $$S_t = \sum_{c=1}^S \mathbb{I}(n_{t, c} > 0)$$ where \(\mathbb{I}(\cdot)\) is the indicator function equal to 1 if class \(c\) has at least one detection in frame \(t\), and 0 otherwise.
Total Video Richness (\(S\)): The total count of unique classes recognized across the entire video: $$S = |\{c : n_c > 0\}|$$
Cumulative Richness / Species Accumulation Curve (Collector's Curve): $$S_{\text{cum}}(t) = |\{c : \exists t' \le t \text{ such that } n_{t', c} > 0\}|$$ The Collector's Curve plots the progressive discovery of novel classes over time. A plateau indicates that sampling effort (video duration) is sufficient to capture the full assemblage of classes present in the environment.
Cumulative Detections (\(N_{\text{cum}}(t)\)): $$N_{\text{cum}}(t) = \sum_{t'=1}^t N_{t'}$$ Tracking the cumulative volume of detections provides insights into detection throughput and arrival rates.
Per-Class Ecological Metrics and Constancy
For each class \(c\), video_detect_dl extracts detailed persistence and distribution metrics:
Total Detections (\(n_c\)): Total bounding box instances identified for class \(c\).
Relative Abundance (\(p_c\)): The percentage contribution of class \(c\) to total video detections: $$p_c = \frac{n_c}{N} \times 100\%$$
Frames Present (\(F_c\)): The number of frames in which class \(c\) was detected at least once: $$F_c = \sum_{t=1}^F \mathbb{I}(n_{t, c} > 0)$$
Occurrence Rate / Constancy (\(O_c\)): The temporal persistence of class \(c\) across the video footage: $$O_c = \frac{F_c}{F} \times 100\%$$ In ecological literature, species with \(O_c \ge 50\%\) are classified as constant, \(25\% \le O_c < 50\%\) as accessory, and \(O_c < 25\%\) as accidental.
Mean Abundance When Present: The expected number of individuals per frame given that the class is present: $$\bar{n}_{c, \text{present}} = \frac{n_c}{\max(1, F_c)}$$
Mean Abundance Overall: The unconditional expected number of individuals per frame across all processed frames: $$\bar{n}_{c, \text{overall}} = \frac{n_c}{F}$$
Maximum per Frame (\(\max_t n_{t, c}\)): Peak instantaneous count of class \(c\).
Mean Confidence (\(\bar{s}_c\)): The arithmetic mean of detection confidence scores for class \(c\): $$\bar{s}_c = \frac{1}{n_c} \sum_{i=1}^{n_c} \text{score}_i$$
Temporal Span: First observed timestamp (\(t_{\text{first}, c}\)) and last observed timestamp (\(t_{\text{last}, c}\)) in seconds.
Diversity, Dominance, and Evenness Indices
Summary diversity indices synthesize class variety and equitability into scalar coefficients:
Shannon-Wiener Diversity Index (\(H'\)): $$H' = -\sum_{c=1}^S p_c \ln(p_c)$$ where \(p_c = n_c / N\). \(H'\) quantifies the uncertainty in predicting the class identity of a randomly sampled detection. Higher values indicate higher diversity and a more equitable distribution across classes. In addition to the global video-level index, \(H'_t\) is computed dynamically for each frame in the
$temporaldata frame.Simpson's Diversity Index (\(1 - D\)) and Dominance (\(D\)): $$D = \sum_{c=1}^S p_c^2, \qquad 1 - D = 1 - \sum_{c=1}^S p_c^2$$ \(D\) represents the probability that two randomly chosen detections belong to the same class (dominance), while \(1 - D\) (Gini-Simpson index) represents the probability that they belong to different classes. Values range from 0 (monoculture / single class dominating entirely) to \(1 - 1/S\) (maximal diversity).
Pielou's Evenness Index (\(J'\)): $$J' = \frac{H'}{\ln(S)}$$ for \(S > 1\) (with \(J' = 1.0\) if \(S = 1\), and \(J' = 0.0\) if \(S = 0\)). \(J'\) normalizes Shannon diversity against its theoretical maximum (\(H'_{\text{max}} = \ln(S)\)), providing an equitability index bounded between 0 and 1. A value of 1.0 indicates that all classes are detected with equal frequency.
Berger-Parker Dominance Index (\(d\)): $$d = \max_{1 \le c \le S} (p_c)$$ Quantifies the proportional dominance of the most abundant single class in the assemblage.
Multi-Object Tracking and Unique Entity Counting
When track = TRUE, a C++ tracking-by-detection tracker associates detections of the
same class across inferred frames. The method is chosen with tracker:
"ocsort_byte"(default):"ocsort"plus the low-score second pass of"bytetrack". It is the most complete option."ocsort":"sort"plus observation-centric re-update, momentum and recovery."bytetrack":"sort"plus a second association pass over low-score detections, with score-weighted IoU in the first pass."sort": constant-velocity Kalman filter and optimal (Hungarian) assignment on the IoU between predicted and detected boxes."simple": the former tracker. Greedy IoU association followed by greedy centroid-distance association (max_dist, default 150 px), with an exponentially smoothed velocity instead of a Kalman filter.
In all of them, unmatched tracks are carried by the motion model for up to max_lost
inferred frames, and new tracks are drawn and counted only after min_frames hits.
Individual components and thresholds are set with video_tracker_control();
min_iou, max_dist, max_lost and max_history passed through ... are still
honoured. These are implementations of the published association rules inside this
pipeline, not ports of the reference code (for instance, the returned boxes are the
detected ones, not the filtered ones). None of the methods compensates camera motion or
uses appearance (re-identification) features. The methods other than "simple" rely on
box overlap between consecutive inferred frames, so very small or fast objects that do
not overlap may need distance_stage = TRUE, a smaller infer_every or "simple".
Unique Objects (\(U\)): Persistent IDs (
#1,#2, ...) track physical entities over time, preventing double-counting when calculating true entity abundance: $$U = |\{ \text{distinct persistent IDs} > 0 \}|$$ For each class \(c\), \(U_c\) records the unique tracked individuals assigned to that class.Cumulative Unique Objects Curve (\(U_{\text{cum}}(t)\)): Tracks the progressive entry of novel unique physical entities into the monitored frame.
Virtual Tripwire Counting (
count_line): When a virtual line is provided asc(x1, y1, x2, y2)in normalized coordinates \([0, 1]\), the trajectory segments between consecutive centroids \(\mathbf{p}_{t-1}\) and \(\mathbf{p}_t\) of tracked objects are evaluated for intersection with the virtual line segment. Crossing events are registered precisely when the signed 2D cross-product changes orientation, cataloguing the event frame, timestamp, persistent ID, and class label in$crossings.
Visualization and S3 Methods
The returned object has class c("pliman_video_detect", "list") and provides built-in S3 methods:
plot(x, type = ...): Renders clean, publication-ready graphics. Supportedtypeoptions:"temporal"(default): Two-panel stacked time series displaying total abundance \(N(t)\) and richness \(S(t)\)."abundance": Multi-class abundance trajectories over time."richness": Step-function curve of class richness over time."cumulative": Two-panel plot of the Species Accumulation Curve (Collector's Curve) and cumulative detection volume."class": Horizontal barplot displaying total detections and relative abundance percentages for each class."all": 2x2 multi-panel overview combining abundance, richness, class distribution, and the Collector's Curve.
summary(x): Formats and displays an overview table with video metadata, ecological metrics, and class distribution.print(x): Displays an informative console summary with key video metrics and class rankings.as.data.frame(x),head(x),tail(x),dim(x),nrow(x),ncol(x),x$column,x[i, j]: Provide transparent backward compatibility with data frame operations on raw detections.
Performance
Decoding, letterboxing, inference, tracking, drawing and encoding run in C++; the ONNX session is created once and warmed up before the first frame, so the reported FPS reflects steady-state speed. The main levers are:
engine = "gpu"(DirectML) vs."cpu"withthreads. GPU gains depend on the hardware; FP16 models (yolo_export_fp16()) only help on GPUs with native half-precision throughput (e.g. Tensor Cores).imgsz: inference cost grows roughly with the square of the input size.infer_every: run the model every k frames and hold the last result in between.fps: subsample the video before inference.show = FALSE,telemetry = "none"andsave_video = FALSEremove the drawing and display work; outside Windowsshow = TRUErenders through the R graphics device, which is very slow.sahi = TRUEmultiplies the inference cost by the number of tiles.max_detcaps the number of detections handled per frame in dense scenes.
Use yolo_benchmark() to measure the model alone on your hardware.
Examples
if (FALSE) { # interactive()
library(pliman)
# 1. Video detection and ecological diversity analysis
dets <- video_detect_dl(
video = "field_drone.mp4",
model = "yolo26n",
conf_threshold = 0.5,
return_data = TRUE,
output = "annotated_field.mp4"
)
# Summary table of ecological metrics
summary(dets)
# Plot community temporal dynamics (abundance & richness)
plot(dets, type = "temporal")
# Plot Species Accumulation Curve (Collector's Curve)
plot(dets, type = "cumulative")
# Plot multi-class abundance trajectories
plot(dets, type = "abundance")
# Multi-panel 2x2 diagnostic overview
plot(dets, type = "all")
# Access per-class breakdown
dets$by_class
# 2. Multi-object tracking with virtual tripwire line counting
tracked_dets <- video_detect_dl(
video = "conveyor_belt.mp4",
model = "seed_weights.onnx",
track = TRUE,
count_line = c(0.5, 0, 0.5, 1), # vertical counting tripwire
return_data = TRUE
)
}