Подсчёт объектов в областях с помощью Ultralytics YOLO26
Решение RegionCounter в Ultralytics YOLO26 отслеживает объекты между видеокадрами и на каждом кадре считает объекты, центры ограничительных рамок которых находятся внутри заданных тобой областей. Каждая область отображается на кадре вместе со своим текущим счётчиком, поэтому ты можешь отслеживать несколько зон — например, проходы в магазине, полосы движения или производственные участки — одним вызовом Python или командой CLI.
Смотри: Подсчет объектов в разных областях с помощью Ultralytics YOLO | Решения Ultralytics
Зачем нужен подсчёт по областям?#
- Несколько зон за один проход: передай словарь именованных многоугольников — для каждой зоны на кадре будет отображаться отдельный счётчик, и один видеопоток охватит все нужные тебе области.
- Встроенное отслеживание: решение самостоятельно выполняет обнаружение YOLO26 и отслеживание объектов, поэтому не нужно отдельно настраивать конвейер отслеживания.
- Счётчики для программной обработки: после обработки каждого кадра возвращается объект результатов со словарём счётчиков по областям, который можно использовать в панелях мониторинга, оповещениях и журналах.
Применение в реальных условиях#
| Розничная торговля | Рыночные улицы |
|---|---|
![]() | ![]() |
| Подсчёт людей в областях с помощью Ultralytics YOLO | Подсчёт людей в толпе по областям с помощью Ultralytics YOLO |
Как подсчитывать объекты в областях с помощью Ultralytics YOLO#
Запусти решение RegionCounter для видеоисточника из CLI или Python. Область можно задать списком точек (одна зона) или словарём, который сопоставляет названия зон со списками точек. В примере на Python ниже объекты подсчитываются в двух именованных областях, а обработанные кадры записываются в выходной видеофайл:
# 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:
| Аргумент | Тип | По умолчанию | Описание |
|---|---|---|---|
model | str | None | Путь к файлу модели Ultralytics YOLO. |
region | list или dict | None | Точки, задающие интересующую область: список кортежей (x, y) или словарь, сопоставляющий названия областей со списками точек для нескольких областей (только RegionCounter). Если None, решения, которым требуется область, используют заданную по умолчанию область. |
line_width | int | 2 | Толщина линий рамок, ключевых точек и счётчиков, которые рисует решение. |
verbose | bool | True | Включает журнал решения для каждого кадра с указанием формы входных данных, количества объектов по классам и скорости обработки. Сам вызов отслеживания всегда выполняется без вывода сообщений. |
Решение RegionCounter позволяет задавать параметры отслеживания объектов:
| Аргумент | Тип | По умолчанию | Описание |
|---|---|---|---|
tracker | str | 'tracktrack.yaml' | Задаёт алгоритм отслеживания. Встроенные варианты: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml. |
conf | float | 0.25 | Задаёт порог уверенности для обнаружений: при более низких значениях можно отслеживать больше объектов, но возрастает вероятность ложноположительных срабатываний. |
iou | float | 0.5 | Задаёт порог пересечения над объединением (IoU) для фильтрации перекрывающихся обнаружений. |
classes | list | None | Фильтрует результаты по индексу класса. Например, classes=[0, 2, 3] отслеживает только указанные классы. |
device | str | None | Задаёт устройство для инференса (например, cpu, cuda:0 или 0). Позволяет выбрать CPU, определённый GPU или другое вычислительное устройство для выполнения модели. |
imgsz | int or tuple | 640 | Целевой размер изображения для инференса: целое число для квадратного изображения или пара (height, width). Размеры корректируются с учётом шага модели. |
max_det | int | 300 | Максимальное количество обнаружений, сохраняемых в каждом кадре перед отслеживанием; ограничивает число объектов, обрабатываемых решением в насыщенных сценах. |
quantize | int or str | None | Точность инференса: 16 (FP16) или 32/unset (FP32) для моделей PyTorch и TorchScript не на CPU; для других форматов точность определяется артефактом модели и средой выполнения. Заменяет устаревший аргумент half. |
Также поддерживаются следующие настройки визуализации:
| Аргумент | Тип | По умолчанию | Описание |
|---|---|---|---|
show | bool | False | Если True, показывает аннотированные изображения или видео в окне. Полезно для мгновенной визуальной проверки во время разработки или тестирования. |
show_conf | bool | True | Показывает оценку уверенности каждой детекции рядом с меткой. Позволяет оценить уверенность модели в каждой детекции. |
show_labels | bool | True | Показывает метки каждой детекции на визуализации. Помогает сразу понять, какие объекты обнаружены. |
Как работает подсчёт по областям#
Решение RegionCounter преобразует каждую переданную область в многоугольник, состоящий как минимум из трёх точек. Простой список точек задаёт одну зону с именем Region#01, а словарь позволяет использовать собственные названия зон; каждая зона отображается отдельным цветом из палитры Ultralytics. Затем каждый кадр обрабатывается в три этапа:
- YOLO26 отслеживает объекты и обнаруживает каждый из них в кадре
- Для каждого отслеживаемого объекта решение вычисляет центр ограничивающей рамки и проверяет, в какие многоугольные области он попадает
- Счётчик каждой области отображается в её центре, а перед обработкой следующего кадра счётчики сбрасываются
Поскольку счётчики сбрасываются на каждом кадре, число, отображаемое для области, показывает её текущую заполненность — то есть сколько объектов находится в ней прямо сейчас, а не накопительный итог. Чтобы вести накопительный подсчёт объектов, пересекающих границу, используй решение ObjectCounter.
Каждый вызов также возвращает объект результатов, атрибут plot_im которого содержит размеченный кадр, а словарь region_counts сопоставляет названия областей с их счётчиками, чтобы ты мог передать эти данные в логику своего приложения.
Заключение#
Решение RegionCounter в Ultralytics YOLO26 позволяет отслеживать текущее число объектов в любом количестве именованных зон с помощью всего нескольких строк кода. Чтобы расширить возможности, подсчитывай пересечения границ с помощью подсчёта объектов, отслеживай объекты в одной зоне с помощью TrackZone или изучи другие решения Ultralytics.
Часто задаваемые вопросы#
Ultralytics YOLO26 подсчитывает объекты в областях, отслеживая каждый объект в кадре и проверяя, находится ли центр его ограничивающей рамки внутри каждого многоугольника, заданного пользователем. Число, отображаемое для области, показывает её текущую заполненность в этом кадре, а не накопительный итог. Параметры настройки перечислены в разделе
RegionCounter()Arguments.Передай аргумент
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с индексами классов, которые нужно оставить, напримерclasses=[0], чтобы считать только людей с моделью, предварительно обученной на COCO. Полный список аргументов, связанных с отслеживанием, находится в разделеRegionCounter()«Аргументы».RegionCounterпоказывает, сколько объектов находится внутри каждой многоугольной зоны в текущем кадре, а ObjectCounter подсчитывает объекты по мере пересечения ими линии или границы области и отслеживает общее количество вошедших и вышедших объектов. ИспользуйRegionCounterдля отслеживания текущей заполненности одной или нескольких зон иObjectCounterдля подсчёта входов и выходов; области в виде линий поддерживаются только вObjectCounter.
Комментарии99
Задай вопрос, поделись результатами или помоги кому-нибудь.
pedmindset
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
Glenn JocherUltralytics@pedmindset yes, it is possible to count objects crossing multiple regions using Ultralytics YOLO11. You can utilize the
RegionCounterclass 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
amulyaamaggididivami
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?
RizwanMunawar
@amulyaamaggididivami Hi, can you please try reversing the region coordinates, like mentioned? I believe this will work.
region_points = [(1134, 416), (1135, 714)]amulyaamaggididivami
I have tried that, but it is not working
RizwanMunawar(изменено)
@amulyaamaggididivami, well, in that case, you can clone the
ultralyticsrepository and build it locally with the changes in the code line here: https://github.com/ultralytics/ultralytics/blob/fa5d0bffbd63adfc302e9c118ffe5caa6447a044/ultralytics/solutions/object_counter.py#L135Edit: Can you please also try using the region points, rather than line points?
amulyaamaggididivami
Sure, thanks
1
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.
Forlin12
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.
SudhanshuBlaze
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
morussk
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.
RizwanMunawar
@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
Solutionsclass 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
dimasfadhila
hello, what dataset do you use for object detection in this region?
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.
rejens
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
Glenn JocherUltralytics(изменено)@rejens
RegionCounterreturns a results object, so call it on each frame and read the per-region counts fromregion_counts:results = region(im0) print(results.region_counts) # e.g. {'Region#01': 3} im0 = results.plot_imThe counts are for the current frame (they reset on every frame). Let me know if you need further clarification!
Darkbutbright
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?
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 itsdisplay_counts()method (inultralytics/solutions/object_counter.py) through theSolutionAnnotator, so you can adjust the text rendering there. You can also call the solution and draw your own text on the returnedplot_imwithcv2.putText(), usingresults.in_countandresults.out_count. Let me know if you need further clarification!Darkbutbright
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)?
Glenn JocherUltralytics@Darkbutbright thank you for your question! You can find detailed instructions and documentation for the
solutionsclass 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!
kemalfrk
Hello, select the area with mouse events how to write the code that counts these classes if it enters a class.Thanks
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!
MuhammedEnesGurkan
Hello, I use object counter but ı want to count only sheeps how can ı set classes_names to sheeps. Please help me
Glenn JocherUltralytics@MuhammedEnesGurkan to count only sheep, use the
--classesargument 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.

