Başla

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ı#

PerakendePazar Sokakları
Ultralytics YOLO, perakende mağazasında çizilmiş çokgen bölgelerin içindeki insanları sayıyorUltralytics YOLO, kalabalık bir pazar sokağının üzerine bölge sayılarını yerleştiriyor
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:

Ultralytics YOLO ile bölge sayımı
# 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şkenTürVarsayılanAçıklama
modelstrNoneUltralytics YOLO model dosyasının yolu.
regionlist veya dictNoneİ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_widthint2Çözümün çizdiği kutular, anahtar noktalar ve sayılar için çizgi kalınlığı.
verboseboolTrueÇö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şkenTürVarsayılanAçıklama
trackerstr'tracktrack.yaml'Kullanılacak izleme algoritmasını belirtir. Yerleşik seçenekler: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml.
conffloat0.25Algı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.
ioufloat0.5Çakışan algılamaları filtrelemek için Kesişim-Birleşim Oranı (IoU) eşiğini belirler.
classeslistNoneSonuçları sınıf dizinine göre filtreler. Örneğin, classes=[0, 2, 3] yalnızca belirtilen sınıfları izler.
devicestrNoneÇı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.
imgszint or tuple640Hedef çı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_detint300Yoğ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ı.
quantizeint or strNoneÇı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şkenTürVarsayılanAçıklama
showboolFalseTrue 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_confboolTrueHer 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_labelsboolTrueGö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:

  1. YOLO26 tracking, karedeki her nesneyi algılar ve izler
  2. İ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
  3. 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.

  • region bağı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 bir region_counts sözlüğünü, plot_im (açıklama eklenmiş kare) ve total_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 classes bağımsız değişkenini geçir; örneğin COCO ile önceden eğitilmiş bir modelle yalnızca kişileri saymak için classes=[0] kullan. İzlemeyle ilgili bağımsız değişkenlerin tam listesi RegionCounter() 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çin RegionCounter, giriş ve çıkışları saymak için ObjectCounter kullan; çizgi biçimindeki bölgeler yalnızca ObjectCounter tarafından desteklenir.

Yorumlar99

Bir soru sor, sonuçlarını paylaş veya başka birine yardım et.

  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(düzenlendi)

      @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(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 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!

  9. MuhammedEnesGurkanGitHub

    Hello, I use object counter but ı want to count only sheeps how can ı set classes_names to sheeps. Please help me

    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.