Ultralytics YOLO26을 사용한 TrackZone

TrackZone이란 무엇인가요?#

Open TrackZone In Colab

TrackZone은 전체 프레임이 아니라 프레임에서 지정된 영역 안의 객체를 모니터링하는 데 특화되어 있습니다. Ultralytics YOLO26을 기반으로 하며 비디오와 라이브 카메라 피드에서 영역별 객체 감지와 추적을 통합합니다. YOLO26은 딥러닝 기반 감지와 추적을 실시간으로 수행하므로 TrackZone은 군중 모니터링 및 감시와 같은 애플리케이션에 적합합니다.



시청: Ultralytics YOLO26으로 영역 내 객체를 추적하는 방법 | TrackZone 🚀

영역 내 객체 추적(TrackZone)의 장점#

  • 집중 분석: 특정 영역 내에서 객체를 추적하면 출입구나 제한 구역과 같은 관심 영역을 정밀하게 모니터링하고 분석할 수 있어 더욱 집중적인 인사이트를 얻을 수 있습니다.
  • 후속 작업 부담 감소: TrackZone은 영역 밖의 객체를 무시하여 관련 없는 감지 결과를 제외하므로, 그 위에 구축하는 로직에서 카운트하거나 기록하거나 알림을 보낼 객체 수가 줄어듭니다. 감지는 영역을 촘촘하게 자른 이미지가 아니라 마스크를 적용한 전체 크기 프레임에서 계속 실행되므로, 이점은 모델 추론 속도 향상이 아니라 더 깔끔하고 집중된 결과를 얻는 것입니다.
  • 보안 강화: 영역별 추적은 중요 구역을 모니터링하여 감시 기능을 개선하고 비정상적인 활동이나 보안 침해를 조기에 감지하는 데 도움이 됩니다.
  • 확장 가능한 솔루션: 특정 영역에 집중할 수 있어 TrackZone은 소매 공간부터 산업 현장까지 다양한 시나리오에 적용할 수 있습니다.

실제 애플리케이션#

농업교통
Ultralytics YOLO26을 사용한 밭의 식물 추적Ultralytics YOLO26을 사용한 도로 위 차량 추적
Ultralytics YOLO26을 사용한 밭의 식물 추적Ultralytics YOLO26을 사용한 도로 위 차량 추적
Ultralytics YOLO를 사용한 TrackZone
# 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은 모니터링할 프레임 영역을 지정하기 위해 region 목록을 사용합니다. 관심 있는 물리적 영역(문, 게이트 등)에 맞게 다각형을 정의하고, 오버레이가 비디오 피드와 일치하는지 확인할 수 있도록 설정 중에 show=True을 활성화된 상태로 유지하세요.

추적 영역 정의하기
  • region의 각 항목은 비디오 프레임에서 (x, y) 픽셀 좌표입니다. 모니터링하려는 영역의 둘레를 따라 연결할 순서대로 포인트를 나열하세요.
  • 좌표는 프레임 해상도에 따라 달라지므로 1280×720 피드에 맞춘 영역은 640×480 피드에 맞지 않습니다. 오버레이가 피드와 일치하는지 확인할 수 있도록 설정 중에는 show=True을 유지하세요.
  • TrackZone은 포인트를 볼록 껍질로 줄이므로, 오목한 모양은 모든 포인트를 포함하는 가장 작은 볼록 다각형으로 단순화됩니다. 볼록하지 않은 모양이나 여러 개의 분리된 영역에는 대신 RegionCounter 솔루션을 사용하세요.
  • region을 생략하면 기본 영역인 [(75, 75), (565, 75), (565, 285), (75, 285)]이 사용됩니다.

TrackZone 인수#

다음은 TrackZone 인수 표입니다:

인수유형기본값설명
modelstrNoneUltralytics YOLO 모델 파일의 경로입니다.
regionlist 또는 dictNone관심 영역을 정의하는 점입니다. (x, y) 튜플 목록 또는 여러 영역에 대해 영역 이름을 점 목록에 매핑하는 사전(RegionCounter만 해당)으로 지정할 수 있습니다. None이면 영역이 필요한 Solutions는 사전 정의된 기본값을 사용합니다.
line_widthint2Solution에서 그리는 상자, 키포인트 및 개수 표시의 선 두께입니다.
verboseboolTrue프레임별 입력 형태, 클래스 개수 및 처리 속도 로그를 활성화합니다. 추적 호출 자체는 항상 로그를 출력하지 않습니다.

TrackZone 솔루션은 track 매개변수를 지원합니다:

인수유형기본값설명
trackerstr'tracktrack.yaml'사용할 추적 알고리즘을 지정합니다. 기본 제공 옵션: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml.
conffloat0.25탐지에 대한 신뢰도 임계값을 설정합니다. 값을 낮추면 추적할 수 있는 객체가 늘어나지만 오탐이 포함될 수 있습니다.
ioufloat0.5중복 탐지를 필터링하기 위한 교집합 대비 합집합 (IoU) 임계값을 설정합니다.
classeslistNone클래스 인덱스로 결과를 필터링합니다. 예를 들어 classes=[0, 2, 3]은 지정된 클래스만 추적합니다.
devicestrNone추론에 사용할 장치를 지정합니다(예: cpu, cuda:0 또는 0). 사용자는 모델 실행에 사용할 CPU, 특정 GPU 또는 기타 연산 장치를 선택할 수 있습니다.
imgszint or tuple640추론 대상 이미지 크기입니다. 정사각형을 나타내는 정수 또는 (height, width) 쌍을 지정합니다. 모델 stride에 맞춰 형태가 조정됩니다.
max_detint300추적 전에 프레임별로 유지할 최대 탐지 수를 지정하여 밀집된 장면에서 솔루션이 처리하는 객체 수를 제한합니다.
quantizeint or strNone추론 정밀도: CPU 이외의 환경에서 PyTorch 및 TorchScript 모델은 16(FP16) 또는 32/unset(FP32)을 사용하며, 다른 형식은 아티팩트와 런타임이 선택하는 정밀도를 사용합니다. 더 이상 사용되지 않는 half 인수를 대체합니다.

또한 다음 시각화 옵션을 사용할 수 있습니다:

인수유형기본값설명
showboolFalseTrue이면 주석이 추가된 이미지나 비디오를 창에 표시합니다. 개발 또는 테스트 중 즉각적인 시각적 피드백을 얻는 데 유용합니다.
show_confboolTrue각 감지 결과의 레이블 옆에 신뢰도 점수를 표시합니다. 각 감지 결과에 대한 모델의 확신도를 파악할 수 있습니다.
show_labelsboolTrue시각화 출력에 각 감지 결과의 레이블을 표시합니다. 감지된 객체를 즉시 파악할 수 있습니다.

영역 내 객체 수 세기#

추적기를 호출할 때마다 SolutionResults 객체가 반환되며, 이 객체의 total_tracks 속성에는 현재 영역 내에서 추적 중인 객체 수가 저장됩니다. 각 프레임에서 이 값을 읽어 실시간 점유 상태를 모니터링할 수 있습니다. 예를 들어 출입구나 제한 구역의 혼잡도를 기록할 수 있습니다:

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

자주 묻는 질문#

  • 아래 명령을 실행하면 영역 안의 객체만 추적할 수 있습니다. 영역 좌표를 설정하려면 region을 전달합니다. 이 방식은 감시, 군중 관리 또는 영역별 추적이 필요한 모든 시나리오에 적합합니다.

    yolo solutions trackzone source="path/to/video.mp4" show=True
  • 몇 줄의 코드만으로 특정 영역의 객체 추적을 설정할 수 있어 프로젝트에 쉽게 통합할 수 있습니다.

    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()
  • Ultralytics TrackZone을 사용한 비디오 처리의 영역 포인트는 간단하게 구성하고 사용자 지정할 수 있습니다. Python 스크립트에서 영역을 직접 정의하고 조정하여 모니터링하려는 영역을 정밀하게 제어할 수 있습니다.

    from ultralytics import solutions
    
    # 영역 포인트 정의
    region_points = [(150, 150), (1130, 150), (1130, 570), (150, 570)]
    
    # trackzone 초기화
    trackzone = solutions.TrackZone(
        show=True,  # 출력을 표시합니다.
        region=region_points,  # 영역 포인트를 전달합니다.
    )

    TrackZone은 포인트를 볼록 껍질로 줄이므로, 오목한 윤곽은 모든 포인트를 포함하는 가장 작은 볼록 다각형으로 단순화됩니다.

  • 세 솔루션 모두 영역을 다루지만, 각각 답하는 질문은 다릅니다:

    솔루션사용 목적일반적인 출력
    TrackZone하나의 볼록 영역 내에서 객체를 추적하고 실시간 점유 상태를 모니터링합니다추적된 ID와 해당 영역의 total_tracks
    ObjectCounter선을 통과하거나 영역에 들어오고 나가는 객체의 수를 셉니다누적 유입 및 유출 수
    RegionCounter하나 이상의 임의 영역(볼록하지 않은 영역 포함) 내 객체 수를 셉니다영역별 객체 수

    한 영역 내에서 지속적인 추적이 필요하면 TrackZone을 선택하고, 여러 영역이나 볼록하지 않은 모양이 필요하면 RegionCounter를 선택하세요.

댓글40

질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.

  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(수정됨)

      @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/.

    1. Glenn JocherUltralytics(수정됨)

      @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
  2. 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(수정됨)

      @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(수정됨)

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

  3. 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

  4. 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.

  5. 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.

  6. 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
  7. 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