Vai al contenuto

Object Counting using Ultralytics YOLO11

Che cos'è il conteggio degli oggetti?

Object counting with Ultralytics YOLO11 involves accurate identification and counting of specific objects in videos and camera streams. YOLO11 excels in real-time applications, providing efficient and precise object counting for various scenarios like crowd analysis and surveillance, thanks to its state-of-the-art algorithms and deep learning capabilities.


Guarda: Object Counting using Ultralytics YOLO11

Guarda: Class-wise Object Counting using Ultralytics YOLO11

Vantaggi del conteggio degli oggetti?

  • Ottimizzazione delle risorse: Il conteggio degli oggetti facilita una gestione efficiente delle risorse, fornendo conteggi accurati e ottimizzando l'allocazione delle risorse in applicazioni come la gestione dell'inventario.
  • Maggiore sicurezza: Il conteggio degli oggetti migliora la sicurezza e la sorveglianza grazie al tracciamento e al conteggio accurato delle entità, favorendo il rilevamento proattivo delle minacce.
  • Decisioni informate: Il conteggio degli oggetti offre spunti preziosi per il processo decisionale, ottimizzando i processi nella vendita al dettaglio, nella gestione del traffico e in vari altri settori.

Applicazioni nel mondo reale

Logistica Acquacoltura
Conveyor Belt Packets Counting Using Ultralytics YOLO11 Fish Counting in Sea using Ultralytics YOLO11
Conveyor Belt Packets Counting Using Ultralytics YOLO11 Fish Counting in Sea using Ultralytics YOLO11

Object Counting using YOLO11 Example

import cv2

from ultralytics import solutions

cap = cv2.VideoCapture("path/to/video/file.mp4")
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))

# Define region points
region_points = [(20, 400), (1080, 404), (1080, 360), (20, 360)]

# Video writer
video_writer = cv2.VideoWriter("object_counting_output.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))

# Init Object Counter
counter = solutions.ObjectCounter(
    show=True,
    region=region_points,
    model="yolo11n.pt",
)

# Process video
while cap.isOpened():
    success, im0 = cap.read()
    if not success:
        print("Video frame is empty or video processing has been successfully completed.")
        break
    im0 = counter.count(im0)
    video_writer.write(im0)

cap.release()
video_writer.release()
cv2.destroyAllWindows()
import cv2

from ultralytics import solutions

cap = cv2.VideoCapture("path/to/video/file.mp4")
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))

# line or region points
line_points = [(20, 400), (1080, 400)]

# Video writer
video_writer = cv2.VideoWriter("object_counting_output.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))

# Init Object Counter
counter = solutions.ObjectCounter(
    show=True,
    region=line_points,
    model="yolo11n-obb.pt",
)

# Process video
while cap.isOpened():
    success, im0 = cap.read()
    if not success:
        print("Video frame is empty or video processing has been successfully completed.")
        break
    im0 = counter.count(im0)
    video_writer.write(im0)

cap.release()
video_writer.release()
cv2.destroyAllWindows()
import cv2

from ultralytics import solutions

cap = cv2.VideoCapture("path/to/video/file.mp4")
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))

# Define region points
region_points = [(20, 400), (1080, 404), (1080, 360), (20, 360), (20, 400)]

# Video writer
video_writer = cv2.VideoWriter("object_counting_output.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))

# Init Object Counter
counter = solutions.ObjectCounter(
    show=True,
    region=region_points,
    model="yolo11n.pt",
)

# Process video
while cap.isOpened():
    success, im0 = cap.read()
    if not success:
        print("Video frame is empty or video processing has been successfully completed.")
        break
    im0 = counter.count(im0)
    video_writer.write(im0)

cap.release()
video_writer.release()
cv2.destroyAllWindows()
import cv2

from ultralytics import solutions

cap = cv2.VideoCapture("path/to/video/file.mp4")
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))

# Define region points
line_points = [(20, 400), (1080, 400)]

# Video writer
video_writer = cv2.VideoWriter("object_counting_output.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))

# Init Object Counter
counter = solutions.ObjectCounter(
    show=True,
    region=line_points,
    model="yolo11n.pt",
)

# Process video
while cap.isOpened():
    success, im0 = cap.read()
    if not success:
        print("Video frame is empty or video processing has been successfully completed.")
        break
    im0 = counter.count(im0)
    video_writer.write(im0)

cap.release()
video_writer.release()
cv2.destroyAllWindows()
import cv2

from ultralytics import solutions

cap = cv2.VideoCapture("path/to/video/file.mp4")
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))

# Video writer
video_writer = cv2.VideoWriter("object_counting_output.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))

# Init Object Counter
counter = solutions.ObjectCounter(
    show=True,
    model="yolo11n.pt",
    classes=[0, 1],
)

# Process video
while cap.isOpened():
    success, im0 = cap.read()
    if not success:
        print("Video frame is empty or video processing has been successfully completed.")
        break
    im0 = counter.count(im0)
    video_writer.write(im0)

cap.release()
video_writer.release()
cv2.destroyAllWindows()

Argomento ObjectCounter

Ecco una tabella con i dati ObjectCounter argomenti:

Nome Tipo Predefinito Descrizione
model str None Path to Ultralytics YOLO Model File
region list [(20, 400), (1260, 400)] Elenco dei punti che definiscono la regione di conteggio.
line_width int 2 Spessore delle linee per i riquadri di delimitazione.
show bool False Flag per controllare se visualizzare il flusso video.
show_in bool True Flag per controllare se visualizzare o meno i conteggi nel flusso video.
show_out bool True Flag per controllare se visualizzare i conteggi di uscita nel flusso video.

Argomenti model.track

Argomento Tipo Predefinito Descrizione
source str None Specifies the source directory for images or videos. Supports file paths and URLs.
persist bool False Enables persistent tracking of objects between frames, maintaining IDs across video sequences.
tracker str botsort.yaml Specifies the tracking algorithm to use, e.g., bytetrack.yaml o botsort.yaml.
conf float 0.3 Sets the confidence threshold for detections; lower values allow more objects to be tracked but may include false positives.
iou float 0.5 Sets the Intersection over Union (IoU) threshold for filtering overlapping detections.
classes list None Filters results by class index. For example, classes=[0, 2, 3] only tracks the specified classes.
verbose bool True Controls the display of tracking results, providing a visual output of tracked objects.

DOMANDE FREQUENTI

How do I count objects in a video using Ultralytics YOLO11?

To count objects in a video using Ultralytics YOLO11, you can follow these steps:

  1. Importa le librerie necessarie (cv2, ultralytics).
  2. Definisci la regione di conteggio (ad esempio, un poligono, una linea, ecc.).
  3. Imposta l'acquisizione video e inizializza il contatore degli oggetti.
  4. Elabora ogni fotogramma per tracciare gli oggetti e contarli all'interno della regione definita.

Ecco un semplice esempio di conteggio in una regione:

import cv2

from ultralytics import solutions


def count_objects_in_region(video_path, output_video_path, model_path):
    """Count objects in a specific region within a video."""
    cap = cv2.VideoCapture(video_path)
    assert cap.isOpened(), "Error reading video file"
    w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
    video_writer = cv2.VideoWriter(output_video_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))

    region_points = [(20, 400), (1080, 404), (1080, 360), (20, 360)]
    counter = solutions.ObjectCounter(show=True, region=region_points, model=model_path)

    while cap.isOpened():
        success, im0 = cap.read()
        if not success:
            print("Video frame is empty or video processing has been successfully completed.")
            break
        im0 = counter.count(im0)
        video_writer.write(im0)

    cap.release()
    video_writer.release()
    cv2.destroyAllWindows()


count_objects_in_region("path/to/video.mp4", "output_video.avi", "yolo11n.pt")

Esplora altre configurazioni e opzioni nella sezione Conteggio oggetti.

What are the advantages of using Ultralytics YOLO11 for object counting?

Using Ultralytics YOLO11 for object counting offers several advantages:

  1. Ottimizzazione delle risorse: Facilita una gestione efficiente delle risorse fornendo conteggi accurati, aiutando a ottimizzare l'allocazione delle risorse in settori come la gestione dell'inventario.
  2. Maggiore sicurezza: Migliora la sicurezza e la sorveglianza grazie al tracciamento e al conteggio accurato delle entità, favorendo il rilevamento proattivo delle minacce.
  3. Processo decisionale informato: Offre preziosi spunti per il processo decisionale, ottimizzando i processi in settori come la vendita al dettaglio, la gestione del traffico e altri ancora.

Per applicazioni reali ed esempi di codice, visita la sezione Vantaggi del conteggio degli oggetti.

How can I count specific classes of objects using Ultralytics YOLO11?

To count specific classes of objects using Ultralytics YOLO11, you need to specify the classes you are interested in during the tracking phase. Below is a Python example:

import cv2

from ultralytics import solutions


def count_specific_classes(video_path, output_video_path, model_path, classes_to_count):
    """Count specific classes of objects in a video."""
    cap = cv2.VideoCapture(video_path)
    assert cap.isOpened(), "Error reading video file"
    w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
    video_writer = cv2.VideoWriter(output_video_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))

    line_points = [(20, 400), (1080, 400)]
    counter = solutions.ObjectCounter(show=True, region=line_points, model=model_path, classes=classes_to_count)

    while cap.isOpened():
        success, im0 = cap.read()
        if not success:
            print("Video frame is empty or video processing has been successfully completed.")
            break
        im0 = counter.count(im0)
        video_writer.write(im0)

    cap.release()
    video_writer.release()
    cv2.destroyAllWindows()


count_specific_classes("path/to/video.mp4", "output_specific_classes.avi", "yolo11n.pt", [0, 2])

In questo esempio, classes_to_count=[0, 2], il che significa che conta gli oggetti della classe 0 e 2 (ad esempio, persona e auto).

Why should I use YOLO11 over other object detection models for real-time applications?

Ultralytics YOLO11 provides several advantages over other object detection models like Faster R-CNN, SSD, and previous YOLO versions:

  1. Speed and Efficiency: YOLO11 offers real-time processing capabilities, making it ideal for applications requiring high-speed inference, such as surveillance and autonomous driving.
  2. Accuracy: It provides state-of-the-art accuracy for object detection and tracking tasks, reducing the number of false positives and improving overall system reliability.
  3. Ease of Integration: YOLO11 offers seamless integration with various platforms and devices, including mobile and edge devices, which is crucial for modern AI applications.
  4. Flessibilità: Supporta diverse attività come il rilevamento, la segmentazione e il tracciamento degli oggetti con modelli configurabili per soddisfare i requisiti di casi d'uso specifici.

Check out Ultralytics YOLO11 Documentation for a deeper dive into its features and performance comparisons.

Can I use YOLO11 for advanced applications like crowd analysis and traffic management?

Yes, Ultralytics YOLO11 is perfectly suited for advanced applications like crowd analysis and traffic management due to its real-time detection capabilities, scalability, and integration flexibility. Its advanced features allow for high-accuracy object tracking, counting, and classification in dynamic environments. Example use cases include:

  • Analisi delle folle: Controlla e gestisce i grandi raduni, garantendo la sicurezza e ottimizzando il flusso della folla.
  • Gestione del traffico: Traccia e conta i veicoli, analizza i modelli di traffico e gestisce la congestione in tempo reale.

For more information and implementation details, refer to the guide on Real World Applications of object counting with YOLO11.


📅 Created 10 months ago ✏️ Updated 2 days ago

Commenti