Đếm đối tượng trong vùng bằng Ultralytics YOLO26#
Giải pháp RegionCounter trong Ultralytics YOLO26 theo dõi đối tượng qua các khung hình video và đếm, ở mỗi khung hình, những đối tượng có tâm hộp giới hạn nằm bên trong từng vùng do bạn xác định. Mỗi vùng được vẽ trên khung hình kèm số đếm trực tiếp riêng, giúp bạn giám sát nhiều khu vực như lối đi trong cửa hàng, làn đường hoặc khu vực sản xuất chỉ bằng một lệnh gọi Python hoặc lệnh CLI.
Xem: Đếm đối tượng trong các vùng khác nhau bằng Ultralytics YOLO | Giải pháp Ultralytics
Tại sao nên đếm theo vùng?#
- Nhiều khu vực trong một lượt xử lý: Truyền vào một dictionary gồm các đa giác được đặt tên, mỗi khu vực sẽ có số lượng riêng được vẽ lên khung hình, nhờ đó một luồng video bao quát mọi khu vực bạn quan tâm.
- Tích hợp sẵn chức năng theo dõi: Giải pháp chạy YOLO26 để phát hiện và theo dõi đối tượng bên trong, vì vậy bạn không cần thiết lập một pipeline theo dõi riêng.
- Có thể đọc số lượng bằng chương trình: Mỗi khung hình đã xử lý trả về một đối tượng kết quả chứa dictionary số lượng theo vùng, sẵn sàng dùng cho dashboard, cảnh báo hoặc ghi log.
Ứng dụng thực tế#
| Bán lẻ | Đường phố khu chợ |
|---|---|
![]() | ![]() |
| Ultralytics YOLO đếm người trong vùng | Ultralytics YOLO đếm đám đông trong vùng |
Cách đếm đối tượng trong vùng bằng Ultralytics YOLO#
Chạy giải pháp RegionCounter trên nguồn video từ CLI hoặc Python. Một vùng có thể là danh sách điểm (một khu vực duy nhất) hoặc dictionary ánh xạ tên khu vực với danh sách điểm. Ví dụ Python bên dưới đếm đối tượng trong hai khu vực được đặt tên và ghi các khung hình đã xử lý vào một tệp video đầu ra:
# 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)]"Các đối số của RegionCounter()#
Dưới đây là bảng các đối số của RegionCounter:
| Đối số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
model | str | None | Đường dẫn đến tệp model Ultralytics YOLO. |
region | list hoặc dict | None | Các điểm xác định vùng quan tâm, dưới dạng danh sách tuple (x, y) hoặc từ điển ánh xạ tên vùng với danh sách điểm cho nhiều vùng (chỉ dùng RegionCounter). Khi là None, các giải pháp cần vùng sẽ dùng vùng mặc định được xác định trước. |
line_width | int | 2 | Độ dày đường viền của box, keypoint và số đếm mà giải pháp vẽ. |
verbose | bool | True | Bật nhật ký theo từng frame của giải pháp, gồm shape đầu vào, số lượng class và tốc độ xử lý. Bản thân lệnh gọi tracking luôn không ghi nhật ký. |
Giải pháp RegionCounter cho phép sử dụng các tham số theo dõi đối tượng:
| Đối số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
tracker | str | 'tracktrack.yaml' | Chỉ định thuật toán theo dõi cần sử dụng. Các tùy chọn tích hợp sẵn: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml. |
conf | float | 0.25 | Đặt ngưỡng confidence cho các đối tượng được phát hiện; giá trị thấp hơn cho phép theo dõi nhiều đối tượng hơn nhưng có thể bao gồm cả kết quả dương tính giả. |
iou | float | 0.7 | Đặt ngưỡng Intersection over Union (IoU) để lọc các đối tượng phát hiện bị chồng lấn. |
classes | list | None | Lọc kết quả theo chỉ mục class. Ví dụ: classes=[0, 2, 3] chỉ theo dõi các class được chỉ định. |
device | str | None | Chỉ định thiết bị dùng để suy luận (ví dụ: cpu, cuda:0 hoặc 0). Cho phép người dùng chọn CPU, một GPU cụ thể hoặc thiết bị tính toán khác để chạy model. |
imgsz | int or tuple | 640 | Kích thước ảnh suy luận mục tiêu: số nguyên cho ảnh vuông hoặc cặp (height, width). Kích thước sẽ được điều chỉnh theo stride của model. |
max_det | int | 300 | Số lượng đối tượng phát hiện tối đa được giữ lại trong mỗi khung hình trước khi theo dõi, giới hạn số đối tượng mà một giải pháp xử lý trong các cảnh dày đặc. |
quantize | int or str | None | Độ chính xác suy luận: 16 (FP16) hoặc 32/unset (FP32) cho model PyTorch và TorchScript khi chạy ngoài CPU; các định dạng khác sử dụng độ chính xác do artifact và runtime của chúng lựa chọn. Thay thế đối số half đã lỗi thời. |
Ngoài ra, các cài đặt trực quan hóa sau đây cũng được hỗ trợ:
| Đối số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
show | bool | False | Nếu True, hiển thị ảnh hoặc video đã được chú thích trong một cửa sổ. Hữu ích để nhận phản hồi trực quan ngay lập tức trong quá trình phát triển hoặc kiểm thử. |
show_conf | bool | True | Hiển thị điểm confidence bên cạnh nhãn của mỗi detection. Cho biết mức độ chắc chắn của model đối với từng detection. |
show_labels | bool | True | Hiển thị nhãn cho mỗi detection trong đầu ra trực quan. Giúp nhận biết ngay các đối tượng được phát hiện. |
Cách hoạt động của tính năng đếm theo vùng#
Giải pháp RegionCounter chuyển từng vùng bạn truyền vào thành một đa giác, với ít nhất ba điểm cho mỗi vùng. Một danh sách điểm thông thường sẽ trở thành một khu vực duy nhất có tên Region#01, trong khi dictionary giữ nguyên tên khu vực bạn đặt; mỗi khu vực được vẽ bằng một màu riêng từ bảng màu Ultralytics. Sau đó, mỗi khung hình được xử lý qua ba bước:
- YOLO26 tracking phát hiện và theo dõi mọi đối tượng trong khung hình
- Với mỗi đối tượng được theo dõi, giải pháp tính tâm bounding box và kiểm tra xem đối tượng có nằm bên trong đa giác của vùng nào hay không
- Số lượng của mỗi vùng được vẽ tại tâm vùng đó, và bộ đếm được đặt lại trước khung hình tiếp theo
Vì số lượng được đặt lại ở mỗi khung hình, con số hiển thị trên một vùng là số đối tượng hiện có bên trong vùng đó, chứ không phải tổng tích lũy. Để đếm tích lũy các đối tượng cắt qua ranh giới, hãy dùng giải pháp ObjectCounter.
Mỗi lần gọi cũng trả về một đối tượng kết quả, trong đó thuộc tính plot_im chứa khung hình đã chú thích và dictionary region_counts ánh xạ tên vùng với số lượng tương ứng, nhờ đó bạn có thể đưa các số liệu vào logic ứng dụng của riêng mình.
Kết luận#
Giải pháp RegionCounter của Ultralytics YOLO26 giám sát số lượng đối tượng trực tiếp trong số lượng khu vực được đặt tên tùy ý chỉ với vài dòng code. Để mở rộng thêm, hãy đếm đối tượng cắt qua ranh giới bằng tính năng đếm đối tượng, theo dõi đối tượng bên trong một khu vực bằng TrackZone, hoặc khám phá các Ultralytics Solutions khác.
Câu hỏi thường gặp#
Ultralytics YOLO26 đếm đối tượng trong vùng bằng cách theo dõi từng đối tượng trong khung hình và kiểm tra xem tâm bounding box của đối tượng có nằm bên trong từng đa giác do người dùng xác định hay không. Số lượng hiển thị trên một vùng là số đối tượng hiện có trong khung hình đó, không phải tổng tích lũy. Các tùy chọn cấu hình được liệt kê trong mục Tham số
RegionCounter().Truyền đối số
regiondưới dạng dictionary ánh xạ tên khu vực với danh sách điểm, như trong ví dụ chính: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)Mỗi khu vực được đặt tên sẽ được vẽ bằng một màu riêng và có số lượng độc lập.
Đối tượng được trả về từ mỗi lần gọi
regioncounter(im0)chứa dictionaryregion_countsánh xạ tên vùng với số lượng tương ứng, cùng vớiplot_im(khung hình đã chú thích) vàtotal_tracks(số lượng đối tượng được theo dõi). In đối tượng kết quả để xem tất cả các trường có sẵn.Có. Truyền đối số
classescùng các chỉ số lớp cần giữ, ví dụclasses=[0]để chỉ đếm người bằng model được huấn luyện trước trên COCO. Danh sách đầy đủ các đối số liên quan đến tracking nằm trong mục Đối sốRegionCounter().RegionCounterhiển thị số lượng đối tượng bên trong mỗi vùng đa giác ở khung hình hiện tại, trong khi ObjectCounter đếm tích lũy các đối tượng khi chúng đi qua đường hoặc ranh giới vùng, đồng thời theo dõi tổng số đối tượng đi vào và đi ra. DùngRegionCounterđể theo dõi lượng đối tượng hiện diện trực tiếp trong một hoặc nhiều vùng và dùngObjectCounterđể đếm lượt vào và lượt ra; chỉObjectCounterhỗ trợ các vùng có hình dạng đường thẳng.
Bình luận99
Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.
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(đã chỉnh sửa)
@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(đã chỉnh sửa)@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(đã chỉnh sửa)@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.

