line_zone does not update in_count and out_count?
Search before asking
- [x] I have searched the Supervision issues and found no similar feature requests.
Question
I follow the example https://supervision.roboflow.com/latest/notebooks/count-objects-crossing-the-line/ to want to count number of car. My version is 0.24.0
Here is my code.
from pathlib import Path
import cv2
import numpy as np
from ultralytics import YOLO
import logging
from datetime import datetime
import argparse
import os
from typing import Union, Dict
import supervision as sv
class YOLOCounter:
"""Counts objects using YOLOv8 as they cross a line."""
def __init__(self, model_path: str, output_dir: str):
"""
Initialize counter with model and output paths.
Args:
model_path: Path to model file or name of pretrained model (e.g., 'yolov8n')
output_dir: Directory to save counting results
"""
try:
# self.model = YOLO(model_path)
self.model = YOLO("yolov8n.pt")
logging.info(f"Successfully loaded model: {model_path}")
except Exception as e:
raise ValueError(f"Failed to load model from {model_path}: {str(e)}")
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.bounding_box_annotator = sv.BoundingBoxAnnotator(thickness=1)
self.label_annotator = sv.LabelAnnotator(text_thickness=1, text_scale=0.5)
self.trace_annotator = sv.TraceAnnotator()
self.line_zone = sv.LineZone(start=sv.Point(0, 10), end=sv.Point(1296, 10))
self.line_zone_annotator = sv.LineZoneAnnotator(
thickness=2,
text_thickness=1,
text_scale=1,
text_orient_to_line=True,
text_offset=0,
display_out_count = False,
display_in_count = True,
# custom_in_text="Number of objects: ",
)
self.byte_tracker = sv.ByteTrack()
# Setup logging
self._setup_logging()
def _setup_logging(self):
"""Setup logging configuration."""
log_dir = self.output_dir / 'logs'
log_dir.mkdir(exist_ok=True)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(message)s',
handlers=[
logging.FileHandler(log_dir / f'counting_log_{timestamp}.txt'),
logging.StreamHandler()
]
)
def count_objects_in_video(self,
video_path: Union[str, Path],
conf: float = 0.25,
line_position: float = 0.5) -> Dict:
"""
Count objects crossing a line in video using YOLO.
Args:
video_path: Path to video file
conf: Confidence threshold
line_position: Position of the counting line (0-1, relative to frame height)
"""
video_path = Path(video_path)
if not video_path.exists():
raise FileNotFoundError(f"Video file not found: {video_path}")
video_info = sv.VideoInfo.from_video_path(video_path)
print("video_info", video_info, video_info.resolution_wh)
sv.process_video(
source_path = video_path,
target_path = self.output_dir / 'tracking_count.mp4',
callback=self.callback,
# show_progress=True,
)
def callback(self, frame: np.ndarray, index:int) -> np.ndarray:
results = self.model(frame, verbose=False, conf=0.7)[0]
detections = sv.Detections.from_ultralytics(results)
detections = self.byte_tracker.update_with_detections(detections)
labels = [
f"#{tracker_id} {self.model.names[class_id]} {confidence:0.2f}"
for confidence, class_id, tracker_id
in zip(detections.confidence, detections.class_id, detections.tracker_id)
]
print("labels", labels)
annotated_frame = frame.copy()
annotated_frame = self.trace_annotator.annotate(
scene=annotated_frame,
detections=detections)
annotated_frame = self.bounding_box_annotator.annotate(
scene=annotated_frame,
detections=detections)
annotated_frame = self.label_annotator.annotate(
scene=annotated_frame,
detections=detections,
labels=labels)
self.line_zone.trigger(detections)
print("self.line_zone", self.line_zone)
print("self.line_zone.out_count", self.line_zone.out_count)
print("self.line_zone.in_count", self.line_zone.in_count)
return self.line_zone_annotator.annotate(annotated_frame, line_counter=self.line_zone)
def is_valid_model_path(model_path):
"""Check if the provided model path is valid."""
# List of known pretrained model names
pretrained_models = ['yolov8n', 'yolov8s', 'yolov8m', 'yolov8l', 'yolov8x']
# Check if it's a pretrained model name
if any(model_path.startswith(name) for name in pretrained_models):
return True
# Check if it's a file that exists
if os.path.isfile(model_path) and model_path.endswith('.pt'):
return True
return False
def main():
parser = argparse.ArgumentParser(description='Run YOLO object counting')
parser.add_argument('--model_path', type=str,
default="yolov8n",
help='Path to model weights (.pt) or pretrained model name (e.g., yolov8n)')
parser.add_argument('--output_dir', type=str,
default="outputs/counting",
help='Directory to save counting results')
parser.add_argument('--source', type=str, required=True,
help='Path to video file')
parser.add_argument('--conf', type=float, default=0.25,
help='Confidence threshold (0-1)')
parser.add_argument('--line_position', type=float, default=0.5,
help='Position of the counting line (0-1, relative to frame height)')
args = parser.parse_args()
# Validate model path
if not is_valid_model_path(args.model_path):
if not args.model_path.endswith('.pt'):
print(f"Warning: Model path '{args.model_path}' doesn't end with .pt")
print("If this is a pretrained model name, it will be downloaded")
else:
print(f"Warning: Model file '{args.model_path}' doesn't exist")
# Initialize counter
print(f"\nInitializing counter with model: {args.model_path}")
counter = YOLOCounter(args.model_path, args.output_dir)
# Process source based on type
source_path = Path(args.source)
print(f"Processing video: {source_path}")
if source_path.is_file():
if source_path.suffix in ['.mp4', '.avi', '.mov']:
# Count objects in video
stats = counter.count_objects_in_video(
source_path,
conf=args.conf,
line_position=args.line_position
)
# print("\nCounting Statistics:")
# for key, value in stats.items():
# print(f"{key}: {value}")
else:
raise ValueError("Source must be a video file (.mp4, .avi, .mov)")
else:
raise ValueError(f"Invalid source path: {source_path}")
if __name__ == "__main__":
main()
To run the above code
python src/models/06.tracking_count.py --source outputs/videos/view35_sequence2.avi
Here is the log
Initializing counter with model: yolov8n
SupervisionWarnings: BoundingBoxAnnotator is deprecated: `BoundingBoxAnnotator` is deprecated and has been renamed to `BoxAnnotator`. `BoundingBoxAnnotator` will be removed in supervision-0.26.0.
Processing video: outputs/videos/view35_sequence2.avi
video_info VideoInfo(width=1296, height=972, fps=2, total_frames=48) (1296, 972)
labels ['#1 car 0.76']
self.line_zone.out_count 0
self.line_zone.in_count 0
labels []
self.line_zone.out_count 0
self.line_zone.in_count 0
labels []
self.line_zone.out_count 0
self.line_zone.in_count 0
labels ['#2 car 0.94']
self.line_zone.out_count 0
self.line_zone.in_count 0
labels []
self.line_zone.out_count 0
self.line_zone.in_count 0
labels ['#1 car 0.75']
self.line_zone.out_count 0
self.line_zone.in_count 0
labels ['#1 car 0.90']
self.line_zone.out_count 0
self.line_zone.in_count 0
labels ['#1 car 0.90']
self.line_zone.out_count 0
self.line_zone.in_count 0
labels ['#1 car 0.91']
self.line_zone.out_count 0
self.line_zone.in_count 0
labels ['#2 car 0.91']
self.line_zone.out_count 0
self.line_zone.in_count 0
labels ['#2 car 0.87']
self.line_zone.out_count 0
self.line_zone.in_count 0
labels []
..
As you can see, it seems that the tracking works well but the line_zone does not update in_count and out_count. How can I fix this?
Additional
No response
It seems that the project is not maintained anymore?
Duplicate of #
It seems that the project is not maintained anymore?
Update the code in your callback() function to add xy_center to the detections object before triggering the line zone. detections = self.byte_tracker.update_with_detections(detections)
ADD THIS LINE to compute the center points
detections = detections.with_centers() def callback(self, frame: np.ndarray, index:int) -> np.ndarray: results = self.model(frame, verbose=False, conf=0.7)[0] detections = sv.Detections.from_ultralytics(results) detections = self.byte_tracker.update_with_detections(detections)
# Compute detection centers (required for LineZone)
detections = detections.with_centers()
labels = [
f"#{tracker_id} {self.model.names[class_id]} {confidence:0.2f}"
for confidence, class_id, tracker_id
in zip(detections.confidence, detections.class_id, detections.tracker_id)
]
annotated_frame = frame.copy()
annotated_frame = self.trace_annotator.annotate(scene=annotated_frame, detections=detections)
annotated_frame = self.bounding_box_annotator.annotate(scene=annotated_frame, detections=detections)
annotated_frame = self.label_annotator.annotate(scene=annotated_frame, detections=detections, labels=labels)
# Trigger counting based on centers
self.line_zone.trigger(detections)
# Log counts
print("self.line_zone.out_count", self.line_zone.out_count)
print("self.line_zone.in_count", self.line_zone.in_count)
# Annotate frame with line zone
return self.line_zone_annotator.annotate(annotated_frame, line_counter=self.line_zone)
Once detections.with_centers() is added, and the line is correctly placed across the region vehicles actually pass, the line_zone will begin detecting crossings, and in_count / out_count will increase correctly.
The counts staying at 0 is almost always because LineZone only counts detections that carry a tracker_id. It tracks each object across frames and increments the count when a tracked object crosses the line, so the detections passed to trigger() have to come from a tracker. The bounding box anchors are computed internally from xyxy, so you do not need to add centers to the detections yourself.
Minimal working pattern:
import supervision as sv
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
tracker = sv.ByteTrack()
line_zone = sv.LineZone(start=sv.Point(0, 500), end=sv.Point(1280, 500))
for frame in frames:
result = model(frame)[0]
detections = sv.Detections.from_ultralytics(result)
detections = tracker.update_with_detections(detections) # adds tracker_id
line_zone.trigger(detections)
print(line_zone.in_count, line_zone.out_count)
A couple of things worth checking if counts are still 0:
- The line endpoints actually cross the paths the objects travel along (a line off to the side of the traffic will never be crossed).
- You are on a recent release. 0.24.0 is quite old; current is 0.29.0, and there have been counting fixes since then, so
pip install --upgrade supervisionis worth doing before debugging further.
The tracking in your log is fine — the problem is the line placement:
self.line_zone = sv.LineZone(start=sv.Point(0, 10), end=sv.Point(1296, 10))
This puts the counting line 10 px from the top edge of the frame, and that placement can never count anything.
Why: LineZone counts a crossing only when a tracked object is first seen with all four bounding-box corners on one side of the line, and later with all four on the other side. Frames where the box straddles the line are skipped (in 0.24.0 this is the is_uniformly_triggered check; in current releases the equivalent left/right-trigger check). With the line at y=10, a car's box would have to fit entirely inside the top 10 px of the frame for the "before" state to ever be recorded — impossible. So cars enter the frame already straddling or below the line, the state never flips, and in_count/out_count stay 0 forever. The tracker IDs in your log (#1 car 0.90, …) confirm tracking is working.
This reproduces without any video or model, on your exact version:
import numpy as np
import supervision as sv # tested on 0.24.0 and current develop
FRAME_H, CAR_W, CAR_H = 720, 120, 100
def drive_through(line_y: int) -> tuple[int, int]:
line = sv.LineZone(start=sv.Point(0, line_y), end=sv.Point(1296, line_y))
for y_top in range(-CAR_H, FRAME_H + 1, 20): # car drives top -> bottom
y1, y2 = max(0, y_top), min(FRAME_H, y_top + CAR_H)
if y2 <= y1:
line.trigger(sv.Detections.empty())
continue
line.trigger(sv.Detections(
xyxy=np.array([[500., y1, 500. + CAR_W, y2]], dtype=np.float32),
class_id=np.array([2]),
confidence=np.array([0.9]),
tracker_id=np.array([1]),
))
return line.in_count, line.out_count
print(drive_through(10)) # (0, 0) <- your symptom
print(drive_through(360)) # counts the crossing
Fix: place the line away from the frame edges — e.g. mid-frame. Your count_objects_in_video already accepts line_position: float = 0.5 but never uses it:
y = int(video_info.height * line_position)
self.line_zone = sv.LineZone(start=sv.Point(0, y), end=sv.Point(video_info.width, y))
If your boxes are large relative to the frame, you can also relax the all-corners requirement with triggering_anchors=[sv.Position.CENTER], so only the box center needs to cross.
A note on the earlier suggestions in this thread: detections.with_centers() does not exist in supervision (not in 0.24.0 or any release), and the detections here do carry tracker_id, so the issue isn't a missing tracker — it's purely the line placement.
Investigated with Claude Code — repro run on 0.24.0 and current develop.