Ultralytics YOLO26 ile Bölgelerde Nesne Sayımı
Ultralytics YOLO26 içindeki RegionCounter çözümü, nesneleri video kareleri boyunca izler ve tanımladığın her bölgenin içinde sınırlayıcı kutusunun merkezi bulunan nesneleri her karede sayar. Her bölge, canlı sayımıyla birlikte kare üzerine çizilir; böylece mağaza koridorları, yol şeritleri veya üretim alanları gibi birden fazla bölgeyi tek bir Python çağrısı ya da CLI komutuyla izleyebilirsin.
İzle: Ultralytics YOLO ile Farklı Bölgelerde Nesne Sayımı | Ultralytics Çözümleri
Neden Bölge Sayımı Kullanmalısın?#
- Tek geçişte birden fazla bölge: Adlandırılmış çokgenlerden oluşan bir sözlük aktar; her bölgenin bağımsız sayımı kareye çizilsin, böylece tek bir video akışı ilgilendiğin tüm alanları kapsasın.
- Yerleşik izleme: Çözüm, YOLO26 algılamasını ve nesne izlemeyi kendi içinde çalıştırır; dolayısıyla ayrıca bir izleme hattı kurman gerekmez.
- Programatik olarak erişebileceğin sayımlar: İşlenen her kare, panolar, uyarılar veya günlük kaydı için hazır, bölge sayımlarını içeren bir sözlükle birlikte bir sonuç nesnesi döndürür.
Gerçek Dünya Uygulamaları#
| Perakende | Pazar Sokakları |
|---|---|
![]() | ![]() |
| Ultralytics YOLO ile Bölgelerde İnsan Sayımı | Ultralytics YOLO ile Bölgelerde Kalabalık Sayımı |
Ultralytics YOLO ile Bölgelerdeki Nesneleri Sayma#
RegionCounter çözümünü CLI veya Python üzerinden bir video kaynağında çalıştır. Bölge, noktalardan oluşan bir liste (tek bir bölge) ya da bölge adlarını nokta listeleriyle eşleştiren bir sözlük olabilir. Aşağıdaki Python örneği, adlandırılmış iki bölgede nesneleri sayar ve işlenen kareleri bir çıktı video dosyasına yazar:
# 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() Bağımsız Değişkenleri#
Aşağıda RegionCounter bağımsız değişkenlerini içeren bir tablo bulabilirsin:
| Bağımsız değişken | Tür | Varsayılan | Açıklama |
|---|---|---|---|
model | str | None | Ultralytics YOLO model dosyasının yolu. |
region | list veya dict | None | İlgi bölgesini tanımlayan noktalar; (x, y) demetlerinin listesi veya birden fazla bölge için bölge adlarını nokta listelerine eşleyen bir sözlük (yalnızca RegionCounter). None olduğunda, bölge gerektiren çözümler önceden tanımlanmış varsayılan bölgeye döner. |
line_width | int | 2 | Çözümün çizdiği kutular, anahtar noktalar ve sayılar için çizgi kalınlığı. |
verbose | bool | True | Çözümün her kare için girdi şekli, sınıf sayıları ve işleme hızına ilişkin günlüğünü etkinleştirir. İzleme çağrısının kendisi her zaman sessizdir. |
RegionCounter çözümü, nesne izleme parametrelerinin kullanılmasını sağlar:
| Bağımsız değişken | Tür | Varsayılan | Açıklama |
|---|---|---|---|
tracker | str | 'tracktrack.yaml' | Kullanılacak izleme algoritmasını belirtir. Yerleşik seçenekler: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml. |
conf | float | 0.25 | Algılamalar için güven eşiğini belirler; düşük değerler daha fazla nesnenin izlenmesine olanak tanır ancak yanlış pozitifleri de içerebilir. |
iou | float | 0.5 | Çakışan algılamaları filtrelemek için Kesişim-Birleşim Oranı (IoU) eşiğini belirler. |
classes | list | None | Sonuçları sınıf dizinine göre filtreler. Örneğin, classes=[0, 2, 3] yalnızca belirtilen sınıfları izler. |
device | str | None | Çıkarım için kullanılacak cihazı belirtir (ör. cpu, cuda:0 veya 0). Kullanıcıların model yürütme için CPU, belirli bir GPU veya başka hesaplama cihazları arasında seçim yapmasına olanak tanır. |
imgsz | int or tuple | 640 | Hedef çıkarım görüntü boyutu: kare görüntüler için bir tam sayı veya bir (height, width) çifti. Boyutlar model adım değerine göre ayarlanır. |
max_det | int | 300 | Yoğun sahnelerde bir çözümün işleyeceği nesne sayısını sınırlamak için izleme öncesinde kare başına tutulan en yüksek algılama sayısı. |
quantize | int or str | None | Çıkarım hassasiyeti: CPU dışında PyTorch ve TorchScript modelleri için 16 (FP16) veya 32/unset (FP32); diğer biçimler, model yapıtının ve çalışma zamanının seçtiği hassasiyeti kullanır. Kullanımdan kaldırılan half argümanının yerini alır. |
Ayrıca aşağıdaki görselleştirme ayarları da desteklenir:
| Bağımsız değişken | Tür | Varsayılan | Açıklama |
|---|---|---|---|
show | bool | False | True ise açıklama eklenmiş görüntüleri veya videoları bir pencerede gösterir. Geliştirme veya test sırasında anında görsel geri bildirim almak için kullanışlıdır. |
show_conf | bool | True | Her algılamanın güven puanını etiketinin yanında gösterir. Modelin her algılamaya ne kadar güvendiğini görmeni sağlar. |
show_labels | bool | True | Görsel çıktıda her algılama için etiketleri gösterir. Algılanan nesnelerin hemen anlaşılmasını sağlar. |
Bölge Sayımı Nasıl Çalışır?#
RegionCounter çözümü, aktardığın her bölgeyi en az üç nokta içeren bir çokgene dönüştürür. Düz bir nokta listesi Region#01 adlı tek bir bölgeye dönüşürken sözlük, kendi bölge adlarını korur; her bölge Ultralytics paletinden farklı bir renkle çizilir. Ardından her kare üç adımda işlenir:
- YOLO26 tracking, karedeki her nesneyi algılar ve izler
- İzlenen her nesne için çözüm, sınırlayıcı kutunun merkezini hesaplar ve bu merkezin hangi bölge çokgenlerinin içinde olduğunu kontrol eder
- Her bölgenin sayımı merkezine çizilir ve sonraki kareden önce sayımlar sıfırlanır
Sayımlar her karede yeniden başladığından, bir bölgede gösterilen sayı kümülatif toplamı değil, o anki doluluğu, yani o anda bölgenin içindeki nesne sayısını belirtir. Bir sınırı geçen nesneleri kümülatif olarak saymak için bunun yerine ObjectCounter çözümünü kullan.
Her çağrı ayrıca plot_im özniteliğinde açıklama eklenmiş kareyi, region_counts sözlüğünde ise bölge adlarını sayımlarla eşleştiren bir sonuç nesnesi döndürür; böylece sayıları kendi uygulama mantığına aktarabilirsin.
Sonuç#
Ultralytics YOLO26 RegionCounter çözümü, birkaç satır kodla istediğin sayıda adlandırılmış bölgedeki canlı nesne sayılarını izler. Daha ileri gitmek için nesne sayımı ile sınır geçişlerini say, TrackZone ile tek bir bölgedeki nesneleri izle veya diğer Ultralytics Çözümlerini keşfet.
Sık Sorulan Sorular#
Ultralytics YOLO26, karedeki her nesneyi izleyerek ve sınırlayıcı kutusunun merkezinin kullanıcı tarafından tanımlanan her çokgenin içinde olup olmadığını kontrol ederek bölgelerdeki nesneleri sayar. Bir bölgede gösterilen sayı, kümülatif toplamı değil, o karedeki mevcut doluluğu belirtir. Yapılandırma seçenekleri
RegionCounter()Bağımsız Değişkenler bölümünde listelenmiştir.regionbağımsız değişkenini bölge adlarını nokta listeleriyle eşleştiren bir sözlük olarak aktar; ana örnekte olduğu gibi: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)Her adlandırılmış bölge farklı bir renkle çizilir ve bağımsız bir sayım gösterir.
Her
regioncounter(im0)çağrısının döndürdüğü nesne; bölge adlarını sayımlarla eşleştiren birregion_countssözlüğünü,plot_im(açıklama eklenmiş kare) vetotal_tracks(izlenen nesne sayısı) ile birlikte içerir. Kullanılabilir tüm alanları incelemek için sonuç nesnesini yazdır.Evet. Tutulacak sınıf indeksleriyle
classesbağımsız değişkenini geçir; örneğin COCO ile önceden eğitilmiş bir modelle yalnızca kişileri saymak içinclasses=[0]kullan. İzlemeyle ilgili bağımsız değişkenlerin tam listesiRegionCounter()Bağımsız Değişkenler bölümünde.RegionCounter, geçerli karede her çokgen bölgenin içindeki nesne sayısını gösterirken ObjectCounter, nesneleri bir çizgiyi veya bölge sınırını geçerken kümülatif olarak sayar ve giriş-çıkış toplamlarını izler. Bir veya daha fazla bölgenin anlık doluluk durumunu görmek içinRegionCounter, giriş ve çıkışları saymak içinObjectCounterkullan; çizgi biçimindeki bölgeler yalnızcaObjectCountertarafından desteklenir.
Yorumlar99
Bir soru sor, sonuçlarını paylaş veya başka birine yardım et.
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(düzenlendi)
@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(düzenlendi)@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(düzenlendi)@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.

