# Line Counter

{% hint style="info" %}
This API Reference is based on DeGirum Tools version 1.2.0.
{% endhint %}

## Line Count Analyzer Module Overview <a href="#line-count-analyzer-module-overview" id="line-count-analyzer-module-overview"></a>

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

1. Define lines to monitor within video frames
2. Create a LineCounter instance with desired settings
3. Process inference results through the analyzer chain
4. Access crossing counts from result.line\_counts
5. 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 crossings
* `SingleLineCounts`: Tracks directional counts for absolute frame directions
* `LineCounts`: Extends SingleLineCounts with per-class counting
* `SingleVectorCounts`: Tracks directional counts relative to line orientation
* `VectorCounts`: Extends SingleVectorCounts with per-class counting

Configuration Options

* `lines`: List of line coordinates (x1, y1, x2, y2) to monitor
* `anchor_point`: Bounding box point used for crossing detection
* `whole_trail`: Use entire trail or just latest segment
* `count_first_crossing`: Count each object once per line
* `absolute_directions`: Use absolute or relative directions
* `per_class_display`: Enable per-class counting
* `show_overlay`: Enable visual annotations
* `annotation_color`: Customize overlay appearance
* `window_name`: Enable interactive line adjustment

## Classes <a href="#classes" id="classes"></a>

## SingleLineCounts <a href="#singlelinecounts" id="singlelinecounts"></a>

`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:

| Name     | Type  | Description                                                                     |
| -------- | ----- | ------------------------------------------------------------------------------- |
| `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 <a href="#linecounts" id="linecounts"></a>

`LineCounts`

Bases: `SingleLineCounts`

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:

| Name        | Type                          | Description                                                                                                                                      |
| ----------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `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` | `Dict[str, SingleLineCounts]` | Mapping from class label to a `SingleLineCounts` object for that class. Each entry holds the counts of crossings for that specific object class. |

## SingleVectorCounts <a href="#singlevectorcounts" id="singlevectorcounts"></a>

`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` when `absolute_directions=False` (relative direction mode).

Attributes:

| Name    | Type  | Description                                                            |
| ------- | ----- | ---------------------------------------------------------------------- |
| `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 <a href="#vectorcounts" id="vectorcounts"></a>

`VectorCounts`

Bases: `SingleVectorCounts`

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` when `per_class_display=True` and `absolute_directions=False`.

Attributes:

| Name        | Type                            | Description                                                                                                                                             |
| ----------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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` | `Dict[str, SingleVectorCounts]` | 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 <a href="#linecounter" id="linecounter"></a>

`LineCounter`

Bases: `ResultAnalyzerBase`

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 or `VectorCounts` in relative mode) and can breakdown counts by object class (if `per_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.

### LineCounter Methods <a href="#linecounter-methods" id="linecounter-methods"></a>

#### \_\_init\_\_(lines, ...) <a href="#init" id="init"></a>

`__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, return_direction_in_results=False)`

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:

| Name                          | Type          | Description                                                                                                                     | Default         |
| ----------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------- |
| `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`          |
| `return_direction_in_results` | `bool`        | If True, add a `cross_line_direction` list to each detection, describing the direction of crossing for each line. Default False | `False`         |

#### analyze(result) <a href="#analyze" id="analyze"></a>

`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.

If `self._return_direction_in_results` is True, also adds a `cross_line_direction` list, aligned with `cross_line`:

{% code overflow="wrap" %}

```yaml
- In absolute mode (absolute_directions=True):
    cross_line_direction[i] is a dict:
        {
            "horizontal": "left" or "right",
            "vertical": "top" or "bottom",
        }

- In relative mode (absolute_directions=False):
    cross_line_direction[i] is "left" or "right"
```

{% endcode %}

#### annotate(result, ...) <a href="#annotate" id="annotate"></a>

`annotate(result, image)`

Draws the defined lines and crossing counts on the image.

Parameters:

| Name     | Type                                                                                                                             | Description                                       | Default    |
| -------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | ---------- |
| `result` | [InferenceResults](https://docs.degirum.com/pysdk/user-guide-pysdk/api-ref/postprocessor#degirum.postprocessor.inferenceresults) | Model result that contains updated `line_counts`. | *required* |
| `image`  | `ndarray`                                                                                                                        | BGR image to annotate.                            | *required* |

Returns:

| Name    | Type      | Description      |
| ------- | --------- | ---------------- |
| `image` | `ndarray` | Annotated image. |

#### reset <a href="#reset" id="reset"></a>

`reset()`

Reset line crossing counts and crossing history. Clears all previously counted trails and counters.

#### window\_attach(win\_name) <a href="#window_attach" id="window_attach"></a>

`window_attach(win_name)`

Attaches OpenCV window for interactive line adjustment.

Installs mouse callbacks enabling line dragging.

Parameters:

| Name       | Type  | Description                | Default    |
| ---------- | ----- | -------------------------- | ---------- |
| `win_name` | `str` | Name of the OpenCV window. | *required* |
