Commencer

TrackZone avec Ultralytics YOLO26

Qu’est-ce que TrackZone ?#

Open TrackZone In Colab

TrackZone se spécialise dans la surveillance des objets à l’intérieur de zones définies d’une image, plutôt que dans toute l’image. Basé sur Ultralytics YOLO26, il intègre la détection d’objets et le suivi dans ces zones, pour les vidéos et les flux de caméra en direct. Comme YOLO26 effectue la détection et le suivi par apprentissage profond en temps réel, TrackZone convient à des applications comme la surveillance des foules et la vidéosurveillance.



Regarder : Comment suivre des objets dans une zone avec Ultralytics YOLO26 | TrackZone 🚀

Avantages du suivi d’objets dans des zones (TrackZone)#

  • Analyse ciblée : Le suivi des objets dans des zones précises permet d’obtenir des informations plus ciblées et de surveiller et d’analyser avec précision les zones d’intérêt, comme les entrées ou les zones réglementées.
  • Réduction de la charge de travail en aval : En ignorant les objets situés hors de la zone, TrackZone élimine les détections non pertinentes. La logique que tu construis par-dessus doit donc compter, enregistrer ou signaler moins d’objets. La détection s’effectue toujours sur une image masquée en pleine résolution, et non sur un recadrage serré de la zone : le résultat est donc plus propre et ciblé, mais l’inférence du modèle n’est pas plus rapide.
  • Sécurité renforcée : Le suivi par zone améliore la vidéosurveillance en surveillant les zones critiques et en facilitant la détection précoce d’activités inhabituelles ou d’intrusions.
  • Solutions évolutives : la possibilité de se concentrer sur des zones spécifiques rend TrackZone adaptable à divers scénarios, des commerces aux environnements industriels.

Applications concrètes#

AgricultureTransport
Suivi des plantes dans un champ avec Ultralytics YOLO26Suivi des véhicules sur une route avec Ultralytics YOLO26
Suivi des plantes dans un champ avec Ultralytics YOLO26Suivi des véhicules sur une route avec Ultralytics YOLO26
TrackZone avec Ultralytics YOLO
# Run a trackzone example
yolo solutions trackzone show=True

# Pass a source video
yolo solutions trackzone source="path/to/video.mp4" show=True

# Pass region coordinates
yolo solutions trackzone show=True region="[(150, 150), (1130, 150), (1130, 570), (150, 570)]"

TrackZone s’appuie sur la liste region pour déterminer quelle partie de l’image surveiller. Définis le polygone en fonction de la zone physique qui t’intéresse (portes, portails, etc.) et laisse show=True activé pendant la configuration afin de vérifier que la superposition correspond bien au flux vidéo.

Définir la zone de suivi
  • Chaque entrée de region correspond à une coordonnée en pixels (x, y) dans l’image vidéo. Énumère les points dans l’ordre où ils doivent être reliés autour du périmètre de la zone à surveiller.
  • Les coordonnées dépendent de la résolution de l’image : une région définie pour un flux de 1280×720 ne sera pas alignée sur un flux de 640×480. Laisse show=True activé pendant la configuration afin de vérifier que la superposition correspond bien à ton flux.
  • TrackZone réduit les points à leur enveloppe convexe : une forme concave est donc simplifiée en le plus petit polygone convexe contenant tous ses points. Pour les formes non convexes ou plusieurs zones distinctes, utilise plutôt la solution RegionCounter.
  • Si tu omets complètement region, une zone par défaut [(75, 75), (565, 75), (565, 285), (75, 285)] est utilisée.

Arguments de TrackZone#

Voici un tableau des arguments de TrackZone :

ArgumentTypeValeur par défautDescription
modelstrNoneChemin vers un fichier de modèle Ultralytics YOLO.
regionlist ou dictNonePoints définissant la région d'intérêt : une liste de tuples (x, y) ou un dictionnaire associant des noms de régions à des listes de points pour plusieurs régions (uniquement RegionCounter). Si None, les solutions qui nécessitent une région utilisent une région par défaut prédéfinie.
line_widthint2Épaisseur des lignes des boîtes, des points clés et des compteurs dessinés par la solution.
verboseboolTrueActive le journal de la solution pour chaque image, qui indique la forme de l'entrée, le nombre d'éléments par classe et la vitesse de traitement. L'appel de suivi reste toujours silencieux.

La solution TrackZone prend en charge les paramètres track :

ArgumentTypeValeur par défautDescription
trackerstr'tracktrack.yaml'Indique l'algorithme de suivi à utiliser. Options intégrées : botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml.
conffloat0.25Définit le seuil de confiance des détections ; des valeurs plus faibles permettent de suivre davantage d'objets, mais peuvent inclure des faux positifs.
ioufloat0.5Définit le seuil d'intersection sur l'union (IoU) utilisé pour filtrer les détections qui se chevauchent.
classeslistNoneFiltre les résultats selon l'indice de classe. Par exemple, classes=[0, 2, 3] ne suit que les classes spécifiées.
devicestrNoneIndique le périphérique utilisé pour l'inférence (par exemple, cpu, cuda:0 ou 0). Permet de choisir entre le CPU, un GPU spécifique ou d'autres périphériques de calcul pour l'exécution du modèle.
imgszint or tuple640Taille cible de l'image pour l'inférence : un entier pour une image carrée ou une paire (height, width). Les dimensions sont ajustées au stride du modèle.
max_detint300Nombre maximal de détections conservées par image avant le suivi, ce qui limite le nombre d'objets qu'une solution traite dans les scènes denses.
quantizeint or strNonePrécision d’inférence : 16 (FP16) ou 32/unset (FP32) pour les modèles PyTorch et TorchScript hors CPU ; les autres formats utilisent la précision définie par leur artefact et leur environnement d’exécution. Remplace l’argument half obsolète.

De plus, les options de visualisation suivantes sont disponibles :

ArgumentTypeValeur par défautDescription
showboolFalseSi True, affiche les images ou vidéos annotées dans une fenêtre. Utile pour obtenir un retour visuel immédiat pendant le développement ou les tests.
show_confboolTrueAffiche le score de confiance de chaque détection à côté de son étiquette. Donne une indication du degré de certitude du modèle pour chaque détection.
show_labelsboolTrueAffiche les étiquettes de chaque détection dans le résultat visuel. Permet d'identifier immédiatement les objets détectés.

Compter les objets à l’intérieur de la zone#

Chaque appel au système de suivi renvoie un objet SolutionResults dont l’attribut total_tracks contient le nombre d’objets actuellement suivis dans la zone. Lis cet attribut à chaque image pour surveiller l’occupation en temps réel, par exemple pour enregistrer l’affluence à une entrée ou dans une zone réglementée :

import cv2

from ultralytics import solutions

cap = cv2.VideoCapture("path/to/video.mp4")
assert cap.isOpened(), "Error reading video file"

region_points = [(150, 150), (1130, 150), (1130, 570), (150, 570)]
trackzone = solutions.TrackZone(show=False, region=region_points, model="yolo26n.pt")

while cap.isOpened():
    success, im0 = cap.read()
    if not success:
        break
    results = trackzone(im0)
    print(f"Objects currently in zone: {results.total_tracks}")  # live zone occupancy

cap.release()

FAQ#

  • Exécute la commande ci-dessous pour suivre les objets uniquement dans la zone et transmets region afin de définir les coordonnées de la zone. Cette méthode convient à des applications comme la vidéosurveillance, la gestion des foules ou tout scénario nécessitant un suivi par zone.

    yolo solutions trackzone source="path/to/video.mp4" show=True
  • Avec seulement quelques lignes de code, tu peux configurer le suivi d’objets dans des zones précises et l’intégrer facilement à tes projets.

    import cv2
    
    from ultralytics import solutions
    
    cap = cv2.VideoCapture("path/to/video.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 = cv2.VideoWriter("trackzone_output.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
    
    trackzone = solutions.TrackZone(
        show=True, region=[(150, 150), (1130, 150), (1130, 570), (150, 570)], model="yolo26n.pt"
    )
    
    while cap.isOpened():
        success, im0 = cap.read()
        if not success:
            break
        results = trackzone(im0)
        video_writer.write(results.plot_im)
    
    cap.release()
    video_writer.release()
    cv2.destroyAllWindows()
  • La configuration des points de zone pour le traitement vidéo avec Ultralytics TrackZone est simple et personnalisable. Tu peux définir et ajuster directement les zones dans un script Python, afin de contrôler précisément les zones à surveiller.

    from ultralytics import solutions
    
    # Définir les points de la région
    region_points = [(150, 150), (1130, 150), (1130, 570), (150, 570)]
    
    # Initialiser TrackZone
    trackzone = solutions.TrackZone(
        show=True,  # afficher le résultat
        region=region_points,  # transmettre les points de la région
    )

    N’oublie pas que TrackZone réduit les points à leur enveloppe convexe : un contour concave est donc simplifié en le plus petit polygone convexe contenant tous ses points.

  • Ces trois solutions fonctionnent avec des régions, mais répondent à des besoins différents :

    SolutionÀ utiliser pourRésultat type
    TrackZoneSuivre les objets et surveiller l’occupation en temps réel dans une seule zone convexeIdentifiants des objets suivis et total_tracks pour la zone
    ObjectCounterCompter les objets qui franchissent une ligne ou entrent dans une région et en sortentTotaux cumulés des entrées et des sorties
    RegionCounterCompter les objets dans une ou plusieurs régions de forme quelconque, y compris non convexesNombre d’objets par région

    Choisis TrackZone pour suivre en continu les objets dans une seule zone, et RegionCounter si tu as besoin de plusieurs zones ou d’une forme non convexe.

Commentaires40

Pose une question, partage tes résultats ou aide quelqu’un d’autre.

  1. Paul231200GitHub

    Hello, great development, but I had a question about the advantages of your solution in comparison with the regions of interest that can be done in Opencv, also the question is whether it is planned to add this development to such models as yolov8?

    1
    1. Glenn JocherUltralytics(modifié)

      @Paul231200 thank you for your question! TrackZone offers targeted and efficient region-based tracking, reducing computational overhead compared to general frame analysis in OpenCV. As for YOLOv8, TrackZone works with any Ultralytics model you pass via model=, including YOLOv8, though we recommend YOLO26 for new projects. For more details, you can explore TrackZone here: https://docs.ultralytics.com/guides/trackzone/.

  2. moshiourGitHub

    Hi, Its a nice feature to yolo! How do make it counting on top of it? Thank you in advance!

    1
    1. Glenn JocherUltralytics(modifié)

      @moshiour thank you for your kind words! TrackZone returns a results object with total_tracks, the number of objects currently tracked inside the zone: results = trackzone(im0) then results.total_tracks. For counting objects entering or leaving a region, see the Object Counting guide. Let us know if you have more questions!

      1
  3. biancalepeGitHub

    Thank you for this informative resource! I have a question - am I able to obtain the unique IDs of identified objects within 20 second windows? In this case, I'd like to know how many unique cars in total were in my zone for each 20 second time period of my video.

    Below is my starting code:

    def count_specific_classes(video_path, output_video_path, model_path, classes_to_count, region_points):

    """Count specific classes of objects in a video."""
    
    cap = cv2.VideoCapture(video_path)
    assert cap.isOpened(), "Error reading video file"
    
    # Video writer
    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))
    
    
    # Initiate TrackZone (object tracking in zones, not complete frame)
    trackzone = solutions.TrackZone(show=True, # Display the output
                                  region=region_points, # pass the region points
                                  model=model_path, # use any model that Ultralytics supports
                                  classes=classes_to_count) # which objects to track
    
    # Process video
    while cap.isOpened():
        success, im0 = cap.read()
        if not success:
            print("Video frame is empty or processing is complete.")
            break
            
        results = trackzone(im0)
        #print (results)  # access the output
        
        video_writer.write(results.plot_im) # write the video output
    
    cap.release()
    video_writer.release()
    cv2.destroyAllWindows() # destroy all open windows
    1. Glenn JocherUltralytics(modifié)

      @biancalepe you can access unique track IDs from trackzone.track_ids and implement time-based windowing for counting. Here's how to modify your code to count unique cars in 20-second intervals:

      def count_unique_cars_by_time_window(video_path, output_video_path, model_path, classes_to_count, region_points, window_seconds=20):
          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))
      
          trackzone = solutions.TrackZone(
              show=True,
              region=region_points,
              model=model_path,
              classes=classes_to_count
          )
      
          frame_count = 0
          window_frame_count = window_seconds * fps  # frames per 20-second window
          current_window = 1
          unique_ids_in_window = set()
          window_results = []
      
          while cap.isOpened():
              success, im0 = cap.read()
              if not success:
                  break
                  
              results = trackzone(im0)
              
              # Track IDs of the objects currently inside the zone
              unique_ids_in_window.update(trackzone.track_ids)
              
              frame_count += 1
              
              # Check if window is complete
              if frame_count >= window_frame_count:
                  unique_count = len(unique_ids_in_window)
                  window_results.append(f"Window {current_window} ({window_seconds - 20}-{window_seconds}s): {unique_count} unique cars")
                  print(f"Window {current_window}: {unique_count} unique cars detected")
                  
                  # Reset for next window
                  unique_ids_in_window.clear()
                  current_window += 1
                  frame_count = 0
                  window_seconds += 20
              
              video_writer.write(results.plot_im)
      
          # Handle final incomplete window
          if unique_ids_in_window:
              unique_count = len(unique_ids_in_window)
              print(f"Final window: {unique_count} unique cars detected")
      
          cap.release()
          video_writer.release()
          cv2.destroyAllWindows()
          
          return window_results

      This tracks unique car IDs within each 20-second window and provides counts for analysis.

    2. biancalepeGitHub

      Thank you!

      Running the code, I see that cars exist in the twenty second windows but the code returns back zero cars for all windows. As I was trying to parse out the code, I printed results.boxes and I get this error --> AttributeError: 'SolutionResults' object has no attribute 'boxes'. I get a similar error when I try to print out results.boxes.id. Printing results seems to get me a "total_tracks" and a "speed" option, but nothing else. Is there something I should be doing?

    3. RizwanMunawarGitHub(modifié)

      @biancalepe If you want to retrieve the IDs of tracked objects in a specific Zone (these will be unique), you can use the code mentioned below. Please note SolutionResults class includes the data highlighted here. Track IDs can be extracted directly by Solution Object, i.e, trackzone.track_ids. Thanks

      import cv2
      
      from ultralytics import solutions
      
      cap = cv2.VideoCapture("path/to/video.mp4")
      assert cap.isOpened(), "Error reading video file"
      
      # Define region points
      region_points = [(150, 150), (1130, 150), (1130, 570), (150, 570)]
      
      # Video writer
      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("trackzone_output.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
      
      # Init trackzone (object tracking in zones, not complete frame)
      trackzone = solutions.TrackZone(
          show=True,  # display the output
          region=region_points,  # pass region points
          model="yolo11n.pt",  # use any model that Ultralytics support, i.e. YOLOv9, YOLOv10
          # line_width=2,  # adjust the line width for bounding boxes and text display
      )
      
      # Process video
      while cap.isOpened():
          success, im0 = cap.read()
          if not success:
              print("Video frame is empty or processing is complete.")
              break
      
          results = trackzone(im0)
      
          print(trackzone.track_ids)  # access the track_ids
      
          video_writer.write(results.plot_im)  # write the video file
      
      cap.release()
      video_writer.release()
      cv2.destroyAllWindows()  # destroy all opened windows
    4. biancalepeGitHub

      Sorry @muhammadrizwanmunawar the reason I was doing the print statements is because I was trying to figure out why the first block of code written by @glenn-jocher wasn't working. I isolated the problem to the extract IDs from results part. Using your code and glenn's I updated that section to be the code below, which seems to have fixed the problem:

      Extract track IDs from results

      if trackzone.track_ids is not None:
          track_ids = trackzone.track_ids
          unique_ids_in_window.update(track_ids)
      1
    5. Glenn JocherUltralytics

      @biancalepe excellent troubleshooting! You've correctly identified that track IDs should be accessed via trackzone.track_ids rather than from the results object. This is the proper way to extract track IDs from TrackZone for time-windowed unique counting. Great job combining the solutions!

  4. Caio Passos

    Hi! I have a question. In the docs, it says TrackZone supports classes as parameters. I tried to limit TrackZone to only detect the class 0 (person).

    heres the code, almost like the example in docs:

    import cv2
    
    from ultralytics import solutions, YOLO
    
    cap = cv2.VideoCapture(
        "/path_to_video.mp4"
    )
    assert cap.isOpened(), "Error reading video file"
    
    # Define region points
    region_points = [(150, 150), (1130, 150), (1130, 570), (150, 570)]
    
    # Video writer
    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(
        "trackzone_output.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h)
    )
    # Init trackzone (object tracking in zones, not complete frame)
    trackzone = solutions.TrackZone(
        show=True,  # display the output
        region=region_points,  # pass region points
        model="yolo11n.pt",
        names=[0],
        # use any model that Ultralytics support, i.e. YOLOv9, YOLOv10
        line_width=1,  # adjust the line width for bounding boxes and text display
    )
    print(f" model class names: {trackzone.model.names}")
    # Process video
    while cap.isOpened():
        success, im0 = cap.read()
        if not success:
            print("Video frame is empty or processing is complete.")
            break
    
        results = trackzone(im0)
    
        # print(results)  # access the output
    
        video_writer.write(results.plot_im)  # write the video file
    
    cap.release()
    video_writer.release()
    cv2.destroyAllWindows()  # destroy all opened windows
    

    it runs without any issue, but still detecting other classes like backpacks, for example. Can you provide some extra details on how to limit detections for person class only?

    1. Caio Passos

      Thanks!! I've changed it in the code:

      trackzone = solutions.TrackZone(
          show=True,  # display the output
          region=region_points,  # pass region points
          model="yolo11n.pt",
          classes=[0],
          # use any model that Ultralytics support, i.e. YOLOv9, YOLOv10
          line_width=1,  # adjust the line width for bounding boxes and text display
      )

      But it led to this error, something related to the size of the mask or tensor:

      Traceback (most recent call last):
        File "/home/tarzan/Documents/programing/hive/aeroporto/track.py", line 38, in <module>
          results = trackzone(im0)
                    ^^^^^^^^^^^^^^
        File "/home/tarzan/Documents/programing/hive/aeroporto/.venv/lib/python3.12/site-packages/ultralytics/solutions/solutions.py", line 195, in __call__
          result = self.process(*args, **kwargs)  # Call the subclass-specific process method
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/home/tarzan/Documents/programing/hive/aeroporto/.venv/lib/python3.12/site-packages/ultralytics/solutions/trackzone.py", line 73, in process
          self.extract_tracks(masked_frame)
        File "/home/tarzan/Documents/programing/hive/aeroporto/.venv/lib/python3.12/site-packages/ultralytics/solutions/solutions.py", line 120, in extract_tracks
          self.tracks = self.model.track(source=im0, persist=True, classes=self.classes, **self.track_add_args)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/home/tarzan/Documents/programing/hive/aeroporto/.venv/lib/python3.12/site-packages/ultralytics/engine/model.py", line 593, in track
          return self.predict(source=source, stream=stream, **kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/home/tarzan/Documents/programing/hive/aeroporto/.venv/lib/python3.12/site-packages/ultralytics/engine/model.py", line 549, in predict
          return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream)
                                                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/home/tarzan/Documents/programing/hive/aeroporto/.venv/lib/python3.12/site-packages/ultralytics/engine/predictor.py", line 218, in __call__
          return list(self.stream_inference(source, model, *args, **kwargs))  # merge list of Result into one
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/home/tarzan/Documents/programing/hive/aeroporto/.venv/lib/python3.12/site-packages/torch/utils/_contextlib.py", line 36, in generator_context
          response = gen.send(None)
                     ^^^^^^^^^^^^^^
        File "/home/tarzan/Documents/programing/hive/aeroporto/.venv/lib/python3.12/site-packages/ultralytics/engine/predictor.py", line 336, in stream_inference
          self.results = self.postprocess(preds, im, im0s)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/home/tarzan/Documents/programing/hive/aeroporto/.venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/predict.py", line 55, in postprocess
          preds = ops.non_max_suppression(
                  ^^^^^^^^^^^^^^^^^^^^^^^^
        File "/home/tarzan/Documents/programing/hive/aeroporto/.venv/lib/python3.12/site-packages/ultralytics/utils/ops.py", line 304, in non_max_suppression
          x, xk = x[filt], xk[filt]
                  ~^^^^^^
      IndexError: The shape of the mask [64] at index 0 does not match the shape of the indexed tensor [62, 6] at index 0
      

      I had experienced something similar with QueueManager before, but I couldn't figure it out where or what went wrong

  5. Parthpatil0024GitHub

    Is there a way to use botsort without using the track method. how to do it if i am using a ncnn model format.

  6. skyceeeeGitHub

    import cv2 import gc from ultralytics import solutions

    Kamerayı başlat

    cap = cv2.VideoCapture(0) assert cap.isOpened(), "Kamera açılırken hata oluştu!"

    Kamera çözünürlüğünü belirle

    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

    Takip bölgesini tanımla (görüntü çözünürlüğüne uygun olmalı)

    region_points = [(50, 50), (590, 50), (590, 430), (50, 430)]

    TrackZone nesnesini başlat

    trackzone = solutions.TrackZone( show=True, region=region_points, model="C:/yazilim/staj/trackzone/yolov8n480.pt", # Daha küçük model kullanıldı imgsz=480, # Model giriş boyutu sınırlandırıldı )

    Canlı görüntü işleme döngüsü

    while cap.isOpened(): success, frame = cap.read() if not success: print("Kamera görüntüsü alınamadı!") break

    # Görüntüyü yeniden boyutlandır
    frame = cv2.resize(frame, (640, 480))
    
    # TrackZone ile işlem yap
    try:
        processed_frame = trackzone.trackzone(frame)
    except Exception as e:
        print(f"Takip sırasında bir hata oluştu: {e}")
        break
    
    # Görüntüyü göster
    cv2.imshow("TrackZone Canlı Takip", processed_frame)
    
    # Bellek temizliği yap
    gc.collect()
    
    # 'q' tuşuna basarak çıkış yapabilirsiniz
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

    Kamera ve pencereyi serbest bırak

    cap.release() cv2.destroyAllWindows()

    This is my code. I use my own trained yolov8n model. When the camera is turned on, the area I drew also appears. No problems until then. But the moment a person enters the rectangle, the kernel dies. What could be the reason for this?My model does human detection. Error: The Kernel crashed while executing code in the current cell or a previous cell. Please review the code in the cell(s) to identify a possible cause of the failure. Click here for more info. View Jupyter log for further details.

    1. Glenn JocherUltralytics

      The kernel crash could be due to insufficient memory or a compatibility issue with your custom YOLOv8 model. Ensure your system has enough resources available, and verify that the model file is correctly configured for the TrackZone solution. Additionally, try reducing the input resolution further (e.g., imgsz=320) to minimize memory usage. For further debugging, check the full error log and confirm that your model works with standard predict functionality outside of TrackZone.

  7. nichamond143GitHub

    Hi, I'm using TrackZone with a custom model, but it's not detecting the target object. However, when I crop the zone of interest from the example video and put it through the model it works fine. I also trained the model on zoomed in images of the object because the full-frame image is too noisey and the object is very small. Any advice on how to approach this?

    1. Glenn JocherUltralytics

      @nichamond143 it sounds like the model's training on zoomed-in images may limit its ability to generalize to full-frame inputs. You could try pre-processing the video frames to crop and resize the zone of interest before passing them to the model. Alternatively, consider retraining the model with multi-scale images, including both zoomed-in and contextual full-frame examples, to improve its detection robustness.

  8. UltralyticsAssistantGitHubUltralytics

    👋 Hello, thank you for your interest in Ultralytics 🚀! It sounds like you're exploring how TrackZone uses YOLO models for object tracking and analysis – fascinating topic!

    If this is a ❓ Question about custom implementations, feel free to share more details about your use case so our team or the community can better assist. If it's a 🐛 Bug Report or you need specific technical help, please provide a clear description, along with any code snippets, error messages, or logs. Including a minimum reproducible example (MRE) would greatly help us debug and offer guidance swiftly.

    For general inquiries or tips on achieving optimal results, consider reviewing our resources on model training and usage. Additionally, you can join the Ultralytics community on platforms like Discord, Reddit, or Discourse for deeper interactions and advice.

    Lastly, please ensure you're running the latest version of the ultralytics package and all required dependencies to avoid encountering previously resolved issues. You can upgrade using the pip install -U ultralytics command.

    Thank you for being part of the Ultralytics community! 😊 An Ultralytics engineer will be here to assist you further shortly.

    1. skyceeeeGitHub

      By converting the yolo model to tensorrt and setting coordinates in Jetson Nano, I track objects in a certain area with Jetson Nano. Can I use trackzone instead of adjusting coordinates myself? Is Jetson Nano supported?

    2. Glenn JocherUltralytics

      @skyceeee yes, you can use TrackZone with Jetson Nano for targeted object tracking within specific areas, eliminating the need to adjust coordinates manually. TrackZone is compatible with YOLO models, including TensorRT-exported ones. Ensure you optimize your model for Jetson Nano's limited resources for best performance. More details on TrackZone can be found here.

      1
  9. skyceeeeGitHub

    Thanks so much for this feature. Is it possible to use this feature with tensorrt format in Jetson nano?

    1. Glenn JocherUltralytics

      @skyceeee thank you for your question! Yes, you can use the TensorRT-exported YOLO models on the Jetson Nano, including for the TrackZone feature. First, export your YOLO11 model to TensorRT format using the yolo export command. Then, ensure your TensorRT runtime is properly set up on the Nano, and integrate the exported model into your tracking workflow. For more details, refer to the Export Documentation. Let us know if you encounter any issues!

      1