开始使用

使用 Ultralytics YOLO26 统计区域内的目标

Ultralytics YOLO26中的 RegionCounter 解决方案会跨视频帧跟踪对象,并在每一帧中统计中心位于你所定义各区域内的对象数量。边界框中心落入区域的对象会被计数。每个区域都会绘制在帧上,并显示实时计数,因此你只需一次 Python 调用或 CLI 命令,即可监控多个区域,例如商店通道、道路车道或生产区域。



观看: 使用 Ultralytics YOLO 在不同区域进行目标计数 | Ultralytics Solutions

为什么要使用区域计数?#

  • 一次处理多个区域: 传入一个包含命名多边形的字典,每个区域都会在帧上显示独立计数,因此一个视频流就能覆盖你关注的所有区域。
  • 内置跟踪: 该解决方案会在内部运行 YOLO26 检测和目标跟踪,因此无需单独搭建跟踪流水线。
  • 支持通过程序读取计数: 每个处理后的帧都会返回一个结果对象,其中包含区域计数词典,可直接用于仪表板、警报或日志记录。

实际应用#

零售集市街道
Ultralytics YOLO 在零售店绘制的多边形区域内统计人数Ultralytics YOLO 在拥挤的集市街道画面上叠加显示区域计数
Ultralytics YOLO 区域人数统计Ultralytics YOLO 区域人群计数

如何使用 Ultralytics YOLO 统计区域内的目标#

通过 CLI 或 Python 在视频源上运行 RegionCounter 解决方案。区域可以是点列表(单个区域),也可以是将区域名称映射到点列表的字典。下面的 Python 示例会统计两个命名区域中的目标,并将处理后的帧写入输出视频文件:

使用 Ultralytics YOLO 进行区域计数
# Run a region counting example
yolo solutions region show=True

# Pass a source video
yolo solutions region source="path/to/video.mp4"

# Pass a custom region
yolo solutions region region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]"

RegionCounter() 参数#

下面是 RegionCounter 参数表:

参数类型默认值说明
modelstrNoneUltralytics YOLO 模型文件的路径。
regionlist 或 dictNone定义感兴趣区域的点,可以是 (x, y) 元组列表,也可以是将区域名称映射到点列表的字典(仅支持多个 RegionCounter 区域)。如果为 None,则需要区域的解决方案会退回到预定义的默认区域。
line_widthint2解决方案绘制的框、关键点和计数的线条粗细。
verboseboolTrue启用逐帧日志,记录输入形状、类别计数和处理速度。跟踪调用本身始终不会输出日志。

RegionCounter 解决方案支持使用目标跟踪参数:

参数类型默认值说明
trackerstr'tracktrack.yaml'指定要使用的跟踪算法。内置选项:botsort.yaml、bytetrack.yaml、ocsort.yaml、deepocsort.yaml、fasttrack.yaml、tracktrack.yaml。
conffloat0.25设置检测的置信度阈值;较低的值允许跟踪更多物体,但可能会包含误检。
ioufloat0.5设置用于筛除重叠检测结果的交并比 (IoU) 阈值。
classeslistNone按类别索引筛选结果。例如,classes=[0, 2, 3] 只跟踪指定类别。
devicestrNone指定推理设备(例如 cpu、cuda:0 或 0)。用户可以选择 CPU、特定 GPU 或其他计算设备来运行模型。
imgszint or tuple640目标推理图像尺寸:正方形图像使用整数,或使用 (height, width) 对。图像尺寸会调整为模型步幅的整数倍。
max_detint300跟踪前每帧保留的最大检测数量,用于限制解决方案在密集场景中处理的物体数量。
quantizeint or strNone推理精度:对于非 CPU 上运行的 PyTorch 和 TorchScript 模型,使用 16 (FP16) 或 32/unset (FP32) 进行选择;其他格式使用其模型文件和运行时所选的精度。此参数替代已弃用的 half 参数。

此外,还支持以下可视化设置:

参数类型默认值说明
showboolFalse如果 True,则在窗口中显示带标注的图像或视频。适用于在开发或测试期间即时查看结果。
show_confboolTrue在每个检测结果的标签旁显示置信度分数,帮助了解模型对该检测结果的确信程度。
show_labelsboolTrue在可视化输出中显示每个检测结果的标签,便于立即了解检测到的对象。

区域计数的工作原理#

RegionCounter 解决方案会将你传入的每个区域转换为一个多边形,每个区域至少包含三个点。普通点列表会变成一个名为 Region#01 的单一区域,而字典则会保留你指定的区域名称;每个区域都会使用 Ultralytics 调色板中的独立颜色绘制。随后,每一帧都会经过以下三个步骤处理:

  1. YOLO26 跟踪会检测并追踪帧中的每个对象
  2. 对于每个跟踪到的目标,解决方案都会计算其边界框中心,并检查该中心位于哪些区域多边形内
  3. 每个区域的计数会显示在该区域中心,并在处理下一帧之前重置

由于计数会在每一帧重新开始,区域上显示的数字表示当前占用量,也就是此刻区域内的目标数量,而不是累计总数。若要累计统计穿过边界的目标数量,请改用 ObjectCounter 解决方案。

每次调用还会返回一个结果对象,其中 plot_im 属性保存已标注的帧,region_counts 字典则将区域名称映射到对应计数,因此你可以将这些数字传入自己的应用逻辑。

结论#

只需几行代码,Ultralytics YOLO26 RegionCounter 解决方案就能监控任意多个命名区域中的实时目标计数。若要进一步扩展,可以使用目标计数统计穿越边界的目标,使用 TrackZone跟踪单个区域内的目标,或探索其他 Ultralytics Solutions。

常见问题#

  • Ultralytics YOLO26 会跟踪帧中的每个目标,并检查其边界框中心是否位于每个用户定义的多边形内,以此统计区域内的目标。区域上显示的计数是该帧的当前占用量,而非累计总数。配置选项列于 RegionCounter() 参数部分。

  • 将 region 参数设为一个把区域名称映射到点列表的字典,如主示例所示:

    from ultralytics import solutions
    
    region_points = {
        "region-01": [(50, 50), (250, 50), (250, 250), (50, 250)],
        "region-02": [(640, 640), (780, 640), (780, 720), (640, 720)],
    }
    regioncounter = solutions.RegionCounter(region=region_points, model="yolo26n.pt", show=True)

    每个命名区域都会以独立颜色绘制,并显示独立计数。

  • 每次 regioncounter(im0) 调用返回的对象都带有一个 region_counts 字典,该字典将区域名称映射到对应计数;对象还包含 plot_im(已标注的帧)和 total_tracks(跟踪到的目标数量)。打印结果对象即可查看所有可用字段。

  • 是的。传入 classes 参数以及要保留的类别索引,例如使用 COCO 预训练模型时,传入 classes=[0] 仅统计 person。所有与跟踪相关的参数都列在 RegionCounter() 参数部分。

  • RegionCounter 会显示当前帧中每个多边形区域内有多少个目标,而 ObjectCounter 会在目标穿过线段或区域边界时累计计数,并跟踪进入和离开的总数。使用 RegionCounter 查看一个或多个区域的实时占用情况,使用 ObjectCounter 统计进入和离开的数量;只有 ObjectCounter 支持线形区域。

评论99

提出问题、分享结果,或帮助其他人。

  1. pedmindsetGitHub

    Been trying to figure this out for a while now. I want to ask, can I use object counting in regions with instance sementation and tracking? You want to count vehicles that cross two specific regions, like so Object 001 crossed region A and region B. Is this possible to do

    1
    1. Glenn JocherUltralytics

      @pedmindset yes, it is possible to count objects crossing multiple regions using Ultralytics YOLO11. You can utilize the RegionCounter class to define multiple regions and track objects across them. The objects' movement through these regions can be tracked using persistent IDs, enabling you to determine which object crossed which regions. For implementation details, refer to the Region Counting Guide.

      1
  2. amulyaamaggididivamiGitHub
    import cv2
    from ultralytics import solutions
    
    # Load video file
    cap = cv2.VideoCapture("retail-store.mp4")
    assert cap.isOpened(), "Error reading video file"
    
    # Define the counting line coordinates (adjust as per your scene)
    region_points = [(1135, 714), (1134, 416)]
    
    # Get video properties
    w, h, fps = (int(cap.get(x)) for x in (
        cv2.CAP_PROP_FRAME_WIDTH,
        cv2.CAP_PROP_FRAME_HEIGHT,
        cv2.CAP_PROP_FPS,
    ))
    
    # Setup video writer for output
    video_writer = cv2.VideoWriter(
        "object_counting_output.mp4",
        cv2.VideoWriter_fourcc(*"mp4v"),
        fps,
        (w, h),
    )
    
    # Initialize the object counter
    counter = solutions.ObjectCounter(
        show=False,                 # Don't show live preview
        region=region_points,       # Line coordinates
        model="yolo11n.pt",         # YOLO model
        classes=[0],                # Class 0 = person
        line_width=3,
    )
    
    # Process video frame by frame
    while cap.isOpened():
        success, frame = cap.read()
        if not success:
            print("Video processing complete.")
            break
    
        # Run the counter on the frame
        results = counter(frame)
    
        # Write to output video
        video_writer.write(results.plot_im)
    
    # Cleanup
    cap.release()
    video_writer.release()
    cv2.destroyAllWindows()
    
    print(f"✅ Processing complete. Saved as 'object_counting_output.mp4'")

    I’m getting the count reversed — the number of people entering is shown as OUT, and those exiting are shown as IN. How can I fix this?

    1. RizwanMunawarGitHub

      @amulyaamaggididivami Hi, can you please try reversing the region coordinates, like mentioned? I believe this will work.

      region_points = [(1134, 416), (1135, 714)]
    2. Glenn JocherUltralytics

      @SudhanshuBlaze IN/OUT for line counters is image-axis based, not compass: for a mostly vertical line, IN = motion to the right (+x) and OUT = left; for a mostly horizontal line, IN = down (+y) and OUT = up; you can relabel to N/S/E/W post-process like this:

      def label_dirs(results, p1, p2):
          (x1, y1), (x2, y2) = p1, p2
          vertical = abs(x1 - x2) < abs(y1 - y2)
          return ({"eastbound": results.in_count, "westbound": results.out_count} if vertical
                  else {"southbound": results.in_count, "northbound": results.out_count})

      Details of the IN/OUT logic are in the count_objects method of the ObjectCounter reference.

  3. Forlin12GitHub

    Hello, I would like to know how it works to remove how many objects there are per instant region because I can't extract this information.

  4. SudhanshuBlazeGitHub

    Hi,

    I was wondering in the case of LINE counters, if there's a thumb rule to translate the IN, OUT count to North->South, East-> West, something like this. How do I know which direction is IN and which direction is OUT in the case of LINE counters?

    My coordinates: line_counter1 = [(842, 1434), (640, 2200)]
    line_counter2 = [(1028, 1304), (1094, 1038)]
    line_counter3 = [(1068, 1038), (684, 1048)]
    line_counter4 = [(2498, 546), (3276, 572)]
    line_counter5 = [(3244, 786), (3414, 904)]
    line_counter6 = [(1830, 958), (1668, 710)]

    Thanks in advance

  5. morusskGitHub

    Hey, I am trying to use solutions.RegionCounter() with conf less than 0.25 but it seems to be ignoring it, is that by design? If I use conf > 0.25 it is taken into account and counts only detections with confidence higher than conf in particular region but lower then 0.25 seems to be ignored and those detections have not chance of being counted by solutions.RegionCounter(). Please advice.

    1. RizwanMunawarGitHub

      @morussk Hi, thanks for sharing the details. The counting in region feature relies on object tracking rather than standalone predictions. As a result, detections with a confidence score below 0.25 are ignored by default.

      However, this behaviour can be modified by adjusting the track_high_thresh parameter. Currently, the Solutions class doesn’t support adjusting tracking configuration core options directly, but you can adjust it by cloning the code and modifying the tracker's configurations file.

      Note: We always recommend using the latest version of the Ultralytics Python package. You can update it by running: pip install -U ultralytics.

      Thanks.

      1
    1. Glenn JocherUltralytics

      @dimasfadhila for region-based object counting in the Ultralytics example, we use models pre-trained on the COCO dataset by default, which includes 80 common object classes. You can see the full class list in our COCO dataset documentation. If you need to count custom objects, you'll want to train on your own dataset using YOLO's training mode.

  6. rejensGitHub

    Process video

    while cap.isOpened(): success, im0 = cap.read() # Read the video frame. if not success: break im0 = region.count(im0) # Count the objects in different regions of frame. cv2.imshow("frame", im0) if cv2.waitKey(1) & 0xFF == ord('q'): break

    this successfully did count and display the objects inside the region, how can i retrieve the number of counts, seems region.count(im0) returns the image only.

    thanks

    1. Glenn JocherUltralytics(已编辑)

      @rejens RegionCounter returns a results object, so call it on each frame and read the per-region counts from region_counts:

      results = region(im0)
      print(results.region_counts)  # e.g. {'Region#01': 3}
      im0 = results.plot_im

      The counts are for the current frame (they reset on every frame). Let me know if you need further clarification!

  7. DarkbutbrightGitHub

    hi,counter = solutions.ObjectCounter(paras),im0 = counter.count(im0),Can the type information, font size, and position of the count in the video be set?

    1. Glenn JocherUltralytics(已编辑)

      @Darkbutbright yes, you can customize the text information, font size and position of the count by modifying the solution source code. For ObjectCounter, the counts are drawn in its display_counts() method (in ultralytics/solutions/object_counter.py) through the SolutionAnnotator, so you can adjust the text rendering there. You can also call the solution and draw your own text on the returned plot_im with cv2.putText(), using results.in_count and results.out_count. Let me know if you need further clarification!

    2. DarkbutbrightGitHub

      Thank you for your patient answer, but I really don't know where to get the detailed instructions (documents) of the solutions class. Could you please tell me how to get it (including more clear instructions for using other classes of yolo)?

    3. Glenn JocherUltralytics

      @Darkbutbright thank you for your question! You can find detailed instructions and documentation for the solutions class and other YOLO functionalities in the Ultralytics Docs. For specific examples, such as region counting or object tracking, check the solutions guide or the respective sections in the repository. Let me know if you need assistance with a particular use case!

  8. kemalfrkGitHub

    Hello, select the area with mouse events how to write the code that counts these classes if it enters a class.Thanks

    1. Glenn JocherUltralytics

      @kemalfrk to implement object counting in specific regions using mouse events, you can modify the region points dynamically by capturing mouse click events and updating the region coordinates in real-time. You can refer to the Ultralytics YOLOv8 region counting example for guidance on how to set up and use the RegionCounter. If you have further questions or need additional customization, feel free to ask!

    1. Glenn JocherUltralytics

      @MuhammedEnesGurkan to count only sheep, use the --classes argument to specify the class index for sheep in your model. For example, if sheep are class 2, run: python yolov8_region_counter.py --source "path/to/video.mp4" --classes 2. Adjust the class index as needed based on your model's class mapping.