Line Count
Line Count Analyzer Module Overview
This module provides an analyzer (LineCounter
) for detecting and counting objects as they cross
user-defined lines within video frames. It enables precise tracking of object movements across
virtual boundaries for applications like traffic monitoring and crowd management.
Key Features
Flexible Line Definitions: Support for multiple lines defined by endpoints
Directional Counting: Track crossings in absolute (up/down/left/right) or relative directions
Object Trail Tracking: Use tracked object paths for accurate crossing detection
Per-Class Counting: Maintain separate counts for different object classes
Visual Overlay: Display crossing lines and count statistics on frames
Interactive Editing: Optional OpenCV mouse callback for line adjustment
First Crossing Mode: Option to count each object only once per line
Trail Analysis: Support for analyzing entire object trails or just latest segments
Typical Usage
Define lines to monitor within video frames
Create a LineCounter instance with desired settings
Process inference results through the analyzer chain
Access crossing counts from result.line_counts
Optionally visualize lines and counts using annotate method
Integration Notes
Requires ObjectTracker analyzer upstream for trail data
Works with any detection results containing bounding boxes
Supports standard DeGirum PySDK result formats
Handles partial/missing detections gracefully
Key Classes
LineCounter
: Main analyzer class for counting line crossingsSingleLineCounts
: Tracks directional counts for absolute frame directionsLineCounts
: Extends SingleLineCounts with per-class countingSingleVectorCounts
: Tracks directional counts relative to line orientationVectorCounts
: Extends SingleVectorCounts with per-class counting
Configuration Options
lines
: List of line coordinates (x1, y1, x2, y2) to monitoranchor_point
: Bounding box point used for crossing detectionwhole_trail
: Use entire trail or just latest segmentcount_first_crossing
: Count each object once per lineabsolute_directions
: Use absolute or relative directionsper_class_display
: Enable per-class countingshow_overlay
: Enable visual annotationsannotation_color
: Customize overlay appearancewindow_name
: Enable interactive line adjustment
Classes
SingleLineCounts
SingleLineCounts
Holds counts of line crossings in four directions.
This class records the number of objects that crossed a line in each cardinal direction
relative to the frame: leftward, rightward, upward, and downward. It is typically used
within a LineCounter
result to represent the counts for one monitored line when counting
with absolute directions.
Attributes:
left
int
Number of objects crossing the line moving leftward (e.g., from right to left).
right
int
Number of objects crossing the line moving rightward (left to right).
top
int
Number of objects crossing the line moving upward (from bottom toward top).
bottom
int
Number of objects crossing the line moving downward (from top toward bottom).
LineCounts
LineCounts
Extends SingleLineCounts to include per-class crossing counts.
This class tracks line crossing counts with a breakdown by object class. In addition to the
total counts for all objects (inherited attributes left, right, top, bottom), it maintains
a dictionary of counts for each object class label. It is typically used by LineCounter
when per_class_display=True
to provide class-specific crossing statistics for each line.
Attributes:
left
int
Total number of objects crossing leftward (all classes combined).
right
int
Total number of objects crossing rightward (all classes combined).
top
int
Total number of objects crossing upward (all classes combined).
bottom
int
Total number of objects crossing downward (all classes combined).
for_class
Mapping from class label to a SingleLineCounts
object for that class. Each entry holds the counts of crossings for that specific object class.
SingleVectorCounts
SingleVectorCounts
Holds counts of line crossings relative to a line's orientation.
This class is used for counting crossing events in the two opposite directions defined by a line
(as opposed to absolute frame directions). It measures how many objects crossed from one side of
the line to the other. Specifically, right
represents crossings from the left side to the right
side of the line (following the line's direction vector), and left
represents crossings from the
right side to the left side of the line. This is used by LineCounter
whenabsolute_directions=False
(relative direction mode).
Attributes:
right
int
Count of objects crossing from the line's left side to its right side.
left
int
Count of objects crossing from the line's right side to its left side.
VectorCounts
VectorCounts
Extends SingleVectorCounts to include per-class crossing counts.
This class maintains overall crossing counts for a line (relative to its orientation) and also
tracks counts per object class. It inherits the total left
and right
counts (for all objects)
from SingleVectorCounts
, and adds a dictionary of per-class counts. It is used by LineCounter
whenper_class_display=True
and absolute_directions=False
.
Attributes:
left
int
Total number of objects crossing from the right side to the left side of the line (all classes).
right
int
Total number of objects crossing from the left side to the right side of the line (all classes).
for_class
Mapping from class label to a SingleVectorCounts
object for that class. Each entry contains the left/right counts for objects of that specific class.
LineCounter
LineCounter
Counts objects crossing specified lines in a video stream.
This analyzer processes tracked object trajectories to detect and tally crossing events for each predefined line. It monitors a list of user-defined lines and increments the appropriate count whenever an object's trail crosses a line, determining the direction of each crossing event.
Key features
Supports absolute (frame-axis) mode counting in four directions, or relative (line-oriented) mode counting in two directions.
Options to use an object's entire trail versus just the latest segment for crossing detection (
whole_trail
), and to count only the first crossing per object (count_first_crossing
).Can accumulate counts over multiple frames or reset counts each frame (
accumulate
flag).Maintains counts for each line (as
LineCounts
in absolute mode orVectorCounts
in relative mode) and can breakdown counts by object class (ifper_class_display=True
).Provides an
annotate(image, result)
method to overlay the lines and current counts on video frames.Supports interactive line adjustment via an OpenCV window (see the
window_attach()
method).
After calling analyze(result)
on a detection/tracking result, the result
object is augmented with
a new attribute line_counts
. This attribute is a list of count objects (one per line) representing
the crossing totals. Each element is either a LineCounts
(for absolute directions) or VectorCounts
(for relative directions) instance. If per_class_display
is enabled, each count object also contains
a for_class
dictionary for per-class counts. Additionally, each detection entry in result.results
receives a boolean list cross_line
indicating which lines that object's trail has crossed (True/False
for each monitored line).
Note
This analyzer requires that object trajectories (trails) are available in the result
(e.g.,
provided by an ObjectTracker
), since counting is based on each object's movement across frames.
Functions
__init__(lines, ...)
__init__(lines, anchor_point=AnchorPoint.BOTTOM_CENTER, *, whole_trail=True, count_first_crossing=True, absolute_directions=False, accumulate=True, per_class_display=False, show_overlay=True, annotation_color=None, annotation_line_width=None, window_name=None)
Initialize a LineCounter with specified lines and counting options.
Creates a new line counter instance that will track object crossings over the specified lines. The counter can operate in either absolute (frame-axis) or relative (line-oriented) counting modes, and supports various options for trail analysis and visualization.
Parameters:
lines
List[tuple]
List of line coordinates, each as (x1, y1, x2, y2).
required
anchor_point
AnchorPoint
Anchor point on bbox for trails. Default is BOTTOM_CENTER.
BOTTOM_CENTER
whole_trail
bool
Use entire trail or last segment only for intersection. Default True.
True
count_first_crossing
bool
Count only first crossing per trail if True. Default True.
True
absolute_directions
bool
Directions relative to image axes if True. Default False.
False
accumulate
bool
Accumulate counts over frames if True. Default True.
True
per_class_display
bool
Display counts per object class if True. Default False.
False
show_overlay
bool
Draw annotations if True. Default True.
True
annotation_color
tuple
RGB color for annotations. Default is complement of overlay color.
None
annotation_line_width
int
Thickness of annotation lines.
None
window_name
str
OpenCV window name to attach for interactive adjustment.
None
_install_mouse_callback
_install_mouse_callback()
Internal method to install the OpenCV mouse callback on the attached window.
_lazy_init
_lazy_init()
Perform deferred initialization such as installing the mouse callback if a window name has been set and the callback hasn't been installed yet.
_line_to_vector(line)
_line_to_vector(line)
Return vector defined by line segment.
Parameters:
line
list or ndarray
Two endpoints of a line [x1, y1, x2, y2].
required
Returns:
np.ndarray: Vector representing the direction of the line (x2 - x1, y2 - y1).
_mouse_callback(event, ...)
_mouse_callback(event, x, y, flags, self)
staticmethod
Mouse event callback for interactive line editing.
Supports:
Left-click and drag to move entire line.
Right-click and drag to move individual line endpoints.
Updates internal line state on changes.
Parameters:
event
int
OpenCV mouse event code.
required
x
int
X coordinate of the mouse event.
required
y
int
Y coordinate of the mouse event.
required
flags
int
Additional event flags.
required
self
Any
Instance of LineCounter.
required
_projection(a, ...)
_projection(a, b)
Return projection of vector b onto vector a.
Parameters:
a
ndarray
Base vector.
required
b
ndarray
Vector to project.
required
Returns:
np.ndarray: Projection of b onto a.
analyze(result)
analyze(result)
Analyzes object trails for line crossings and updates crossing counts.
Checks every tracked trail in result.trails
for intersections with all lines,
computes crossing direction, updates counts, and adds line_counts
attribute
to the result.
Adds a cross_line
boolean list to each detected object's dictionary indicating
which lines they crossed on this frame.
Parameters:
result
InferenceResults
Model result object containing trails and detection info.
required
Returns:
None
This method modifies the input result object in-place.
Raises:
AttributeError
If result object is missing required attributes.
TypeError
If result object is not of the expected type.
window_attach(win_name)
window_attach(win_name)
Attaches OpenCV window for interactive line adjustment.
Installs mouse callbacks enabling line dragging.
Parameters:
win_name
str
Name of the OpenCV window.
required
Last updated
Was this helpful?