Skip to content

Object Counting using Ultralytics YOLO11

Qu'est-ce que le comptage d'objets ?

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.


Regarde : Object Counting using Ultralytics YOLO11

Regarde : Class-wise Object Counting using Ultralytics YOLO11

Avantages du comptage d'objets ?

  • Optimisation des ressources : Le comptage d'objets facilite la gestion efficace des ressources en fournissant des comptages prĂ©cis et en optimisant l'allocation des ressources dans des applications telles que la gestion des stocks.
  • SĂ©curitĂ© renforcĂ©e : Le comptage d'objets amĂ©liore la sĂ©curitĂ© et la surveillance en suivant et en comptant avec prĂ©cision les entitĂ©s, ce qui permet une dĂ©tection proactive des menaces.
  • Prise de dĂ©cision Ă©clairĂ©e : Le comptage d'objets offre des informations prĂ©cieuses pour la prise de dĂ©cision, l'optimisation des processus dans le commerce de dĂ©tail, la gestion du trafic et divers autres domaines.

Applications dans le monde réel

Logistique Aquaculture
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()

Argument ObjectCounter

Voici un tableau avec les ObjectCounter arguments :

Nom Type DĂ©faut Description
model str None Path to Ultralytics YOLO Model File
region list [(20, 400), (1260, 400)] Liste des points définissant la région de comptage.
line_width int 2 Épaisseur du trait pour les boîtes de délimitation.
show bool False Drapeau permettant de contrôler l'affichage ou non du flux vidéo.
show_in bool True Indicateur permettant de contrôler l'affichage du nombre d'entrées sur le flux vidéo.
show_out bool True Indicateur permettant de contrôler l'affichage ou non des décomptes de sortie sur le flux vidéo.

Arguments model.track

Argument Type DĂ©faut Description
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 ou 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.

FAQ

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. Importe les bibliothèques nécessaires (cv2, ultralytics).
  2. Définis la région de comptage (par exemple, un polygone, une ligne, etc.).
  3. Configure la capture vidéo et initialise le compteur d'objets.
  4. Traite chaque image pour suivre les objets et les compter dans la région définie.

Voici un exemple simple pour compter dans une région :

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")

Explore d'autres configurations et options dans la section Comptage d'objets.

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

Using Ultralytics YOLO11 for object counting offers several advantages:

  1. Optimisation des ressources : Il facilite la gestion efficace des ressources en fournissant des comptages précis, ce qui permet d'optimiser l'affectation des ressources dans des secteurs tels que la gestion des stocks.
  2. Sécurité renforcée : Il améliore la sécurité et la surveillance en suivant et en comptant les entités avec précision, ce qui facilite la détection proactive des menaces.
  3. Prise de décision éclairée : Il offre des informations précieuses pour la prise de décision, l'optimisation des processus dans des domaines tels que la vente au détail, la gestion du trafic, et plus encore.

Pour des applications concrètes et des exemples de code, visite la section Avantages du comptage d'objets.

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])

Dans cet exemple, classes_to_count=[0, 2]ce qui signifie qu'il compte les objets de la classe 0 et 2 (par exemple, personne et voiture).

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. Flexibilité : Prend en charge diverses tâches telles que la détection, la segmentation et le suivi d'objets avec des modèles configurables pour répondre aux exigences de cas d'utilisation spécifiques.

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:

  • Analyse des foules : Surveille et gère les grands rassemblements, en assurant la sĂ©curitĂ© et en optimisant le flux de la foule.
  • Gestion du trafic : Suit et compte les vĂ©hicules, analyse les schĂ©mas de circulation et gère les embouteillages en temps rĂ©el.

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


📅 Created 10 months ago ✏️ Updated 8 days ago

Commentaires