Bắt đầu

Quản lý hàng đợi bằng Ultralytics YOLO26

Quản lý hàng đợi là gì?#

Open Queue Management In Colab

Quản lý hàng đợi bằng Ultralytics YOLO26 là giám sát hàng người hoặc phương tiện để giảm thời gian chờ và nâng cao hiệu quả. YOLO26 phát hiện và theo dõi mọi người trong khu vực chờ, đồng thời báo cáo độ dài hàng đợi trực tiếp, giúp cải thiện mức độ hài lòng của khách hàng và hoạt động tại các địa điểm như cửa hàng bán lẻ, ngân hàng, sân bay và cơ sở y tế.



Xem: Cách xây dựng hệ thống quản lý hàng đợi bằng Ultralytics YOLO26 | Phân tích hàng đợi theo thời gian thực 🚀

Ưu điểm của quản lý hàng đợi#

  • Giảm thời gian chờ: Hệ thống quản lý hàng đợi tổ chức hàng đợi hiệu quả, giảm thiểu thời gian chờ của khách hàng. Nhờ đó, mức độ hài lòng được cải thiện vì khách hàng dành ít thời gian chờ đợi hơn và có nhiều thời gian tương tác với sản phẩm hoặc dịch vụ hơn.
  • Tăng hiệu quả: Việc triển khai quản lý hàng đợi giúp doanh nghiệp phân bổ nguồn lực hiệu quả hơn. Bằng cách phân tích dữ liệu hàng đợi và tối ưu hóa việc bố trí nhân viên, doanh nghiệp có thể hợp lý hóa hoạt động, giảm chi phí và nâng cao năng suất tổng thể.
  • Thông tin chuyên sâu theo thời gian thực: Giải pháp quản lý hàng đợi sử dụng YOLO26 cung cấp dữ liệu tức thì về độ dài hàng đợi và thời gian chờ, giúp quản lý nhanh chóng đưa ra quyết định dựa trên thông tin.
  • Nâng cao trải nghiệm khách hàng: Bằng cách giảm sự khó chịu do phải chờ lâu, doanh nghiệp có thể cải thiện mức độ hài lòng và lòng trung thành của khách hàng.

Ứng dụng thực tế#

LogisticsBán lẻ
Quản lý hàng đợi tại quầy bán vé sân bay bằng Ultralytics YOLO26Giám sát hàng đợi trong đám đông bằng Ultralytics YOLO26
Quản lý hàng đợi tại quầy bán vé sân bay bằng Ultralytics YOLO26Giám sát hàng đợi trong đám đông bằng Ultralytics YOLO26

Quản lý hàng đợi bằng YOLO26#

Giải pháp QueueManager đếm các đối tượng được theo dõi bên trong một vùng đã xác định ở mỗi khung hình, cung cấp độ dài hàng đợi trực tiếp để bạn có thể ghi vào video đầu ra. Truyền vào một vùng đa giác bao phủ khu vực chờ, sau đó chạy giải pháp trên nguồn video bằng Python API hoặc CLI.

Quản lý hàng đợi bằng Ultralytics YOLO
# Run a queue example
yolo solutions queue show=True

# Pass a source video
yolo solutions queue source="path/to/video.mp4"

# Pass queue coordinates
yolo solutions queue region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]"

Các đối số của QueueManager#

Dưới đây là bảng các đối số của QueueManager:

Đối sốKiểuMặc địnhMô tả
modelstrNoneĐường dẫn đến tệp model Ultralytics YOLO.
regionlist hoặc dictNoneCác điểm xác định vùng quan tâm, dưới dạng danh sách tuple (x, y) hoặc từ điển ánh xạ tên vùng với danh sách điểm cho nhiều vùng (chỉ dùng RegionCounter). Khi là None, các giải pháp cần vùng sẽ dùng vùng mặc định được xác định trước.
line_widthint2Độ dày đường viền của box, keypoint và số đếm mà giải pháp vẽ.
verboseboolTrueBật nhật ký theo từng frame của giải pháp, gồm shape đầu vào, số lượng class và tốc độ xử lý. Bản thân lệnh gọi tracking luôn không ghi nhật ký.

Giải pháp QueueManager cũng hỗ trợ các đối số track:

Đối sốKiểuMặc địnhMô tả
trackerstr'tracktrack.yaml'Chỉ định thuật toán theo dõi cần sử dụng. Các tùy chọn tích hợp sẵn: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml.
conffloat0.25Đặt ngưỡng confidence cho các đối tượng được phát hiện; giá trị thấp hơn cho phép theo dõi nhiều đối tượng hơn nhưng có thể bao gồm cả kết quả dương tính giả.
ioufloat0.5Đặt ngưỡng Intersection over Union (IoU) để lọc các đối tượng phát hiện bị chồng lấn.
classeslistNoneLọc kết quả theo chỉ mục class. Ví dụ: classes=[0, 2, 3] chỉ theo dõi các class được chỉ định.
devicestrNoneChỉ định thiết bị dùng để suy luận (ví dụ: cpu, cuda:0 hoặc 0). Cho phép người dùng chọn CPU, một GPU cụ thể hoặc thiết bị tính toán khác để chạy model.
imgszint or tuple640Kích thước ảnh suy luận mục tiêu: số nguyên cho ảnh vuông hoặc cặp (height, width). Kích thước sẽ được điều chỉnh theo stride của model.
max_detint300Số lượng đối tượng phát hiện tối đa được giữ lại trong mỗi khung hình trước khi theo dõi, giới hạn số đối tượng mà một giải pháp xử lý trong các cảnh dày đặc.
quantizeint or strNoneĐộ chính xác suy luận: 16 (FP16) hoặc 32/unset (FP32) cho model PyTorch và TorchScript khi chạy ngoài CPU; các định dạng khác sử dụng độ chính xác do artifact và runtime của chúng lựa chọn. Thay thế đối số half đã lỗi thời.

Ngoài ra, bạn có thể sử dụng các tham số trực quan hóa sau:

Đối sốKiểuMặc địnhMô tả
showboolFalseNếu True, hiển thị ảnh hoặc video đã được chú thích trong một cửa sổ. Hữu ích để nhận phản hồi trực quan ngay lập tức trong quá trình phát triển hoặc kiểm thử.
show_confboolTrueHiển thị điểm confidence bên cạnh nhãn của mỗi detection. Cho biết mức độ chắc chắn của model đối với từng detection.
show_labelsboolTrueHiển thị nhãn cho mỗi detection trong đầu ra trực quan. Giúp nhận biết ngay các đối tượng được phát hiện.

Chiến lược triển khai#

Khi triển khai quản lý hàng đợi bằng YOLO26, hãy cân nhắc các phương pháp tốt nhất sau:

  1. Bố trí camera hợp lý: Đặt camera sao cho ghi hình được toàn bộ khu vực hàng đợi mà không bị vật cản che khuất.
  2. Xác định vùng hàng đợi phù hợp: Thiết lập ranh giới hàng đợi cẩn thận dựa trên bố cục thực tế của không gian.
  3. Điều chỉnh độ tin cậy phát hiện: Tinh chỉnh ngưỡng độ tin cậy dựa trên điều kiện ánh sáng và mật độ đám đông.
  4. Tích hợp với các hệ thống hiện có: Kết nối giải pháp quản lý hàng đợi với hệ thống bảng hiệu kỹ thuật số hoặc thông báo cho nhân viên để tự động phản hồi.

Câu hỏi thường gặp#

  • Để sử dụng Ultralytics YOLO26 quản lý hàng đợi theo thời gian thực, bạn có thể thực hiện các bước sau:

    1. Thu nhận luồng video bằng cv2.VideoCapture.
    2. Xác định vùng quan tâm (ROI) để quản lý hàng đợi.
    3. Khởi tạo solutions.QueueManager bằng model YOLO26, chẳng hạn như yolo26n.pt, cùng với vùng đã xác định.
    4. Xử lý các khung hình để phát hiện đối tượng và quản lý hàng đợi.

    Dưới đây là ví dụ tối giản:

    import cv2
    
    from ultralytics import solutions
    
    cap = cv2.VideoCapture("path/to/video.mp4")
    queue_region = [(20, 400), (1080, 400), (1080, 360), (20, 360)]
    
    queuemanager = solutions.QueueManager(
        model="yolo26n.pt",
        region=queue_region,
        line_width=3,
        show=True,
    )
    
    while cap.isOpened():
        success, im0 = cap.read()
        if not success:
            break
        results = queuemanager(im0)
    
    cap.release()
    cv2.destroyAllWindows()

    Bạn có thể huấn luyện và triển khai các model dùng trong giải pháp quản lý hàng đợi trên Ultralytics Platform.

  • Sử dụng Ultralytics YOLO26 để quản lý hàng đợi mang lại một số lợi ích:

    • Giảm thời gian chờ: Tổ chức hàng đợi hiệu quả, giảm thời gian chờ của khách hàng và nâng cao mức độ hài lòng.
    • Tăng hiệu quả: Phân tích dữ liệu hàng đợi để tối ưu hóa việc bố trí nhân viên và hoạt động, qua đó giảm chi phí.
    • Thông tin chuyên sâu theo thời gian thực: Cung cấp số lượng người trong hàng đợi trực tiếp ở từng khung hình, giúp can thiệp nhanh chóng khi hàng đợi kéo dài.
    • Khả năng mở rộng: Dễ dàng mở rộng quy mô để triển khai trong nhiều môi trường như cửa hàng bán lẻ, sân bay và cơ sở y tế.
  • Ultralytics YOLO26 có một số ưu điểm so với các bộ phát hiện dựa trên TensorFlow và Detectron2 trong việc quản lý hàng đợi:

    • Hiệu suất thời gian thực: YOLO26 được thiết kế để phát hiện theo thời gian thực và xử lý khung hình nhanh chóng.
    • Dễ sử dụng: Ultralytics hỗ trợ toàn bộ quy trình từ huấn luyện đến triển khai bằng Python hoặc trên Ultralytics Platform.
    • Model được huấn luyện trước: Truy cập nhiều model đã được huấn luyện trước, giảm thiểu thời gian cần thiết để thiết lập.
    • Hỗ trợ cộng đồng: Tài liệu phong phú và cộng đồng hỗ trợ tích cực giúp giải quyết vấn đề dễ dàng hơn.

    Tìm hiểu cách bắt đầu với Ultralytics YOLO.

  • Có, Ultralytics YOLO26 có thể quản lý nhiều loại hàng đợi, bao gồm cả hàng đợi tại sân bay và môi trường bán lẻ. Bằng cách cấu hình QueueManager với các vùng và thiết lập cụ thể, YOLO26 có thể thích ứng với nhiều cách bố trí và mật độ hàng đợi khác nhau.

    Ví dụ tại sân bay:

    queue_region_airport = [(50, 600), (1200, 600), (1200, 550), (50, 550)]
    queue_airport = solutions.QueueManager(
        model="yolo26n.pt",
        region=queue_region_airport,
        line_width=3,
    )
  • Ultralytics YOLO26 được sử dụng trong nhiều ứng dụng thực tế về quản lý hàng đợi:

    • Bán lẻ: Giám sát hàng tại quầy thanh toán để giảm thời gian chờ và cải thiện mức độ hài lòng của khách hàng.
    • Sân bay: Quản lý hàng đợi tại quầy bán vé và điểm kiểm tra an ninh để hành khách có trải nghiệm thuận tiện hơn.
    • Y tế: Tối ưu hóa luồng bệnh nhân tại phòng khám và bệnh viện.
    • Ngân hàng: Nâng cao chất lượng dịch vụ khách hàng bằng cách quản lý hàng đợi tại ngân hàng hiệu quả.

    Đọc blog về quản lý hàng đợi trong thực tế của chúng tôi để tìm hiểu thêm về cách thị giác máy tính đang chuyển đổi hoạt động giám sát hàng đợi trong nhiều ngành.

Bình luận18

Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.

  1. CharanPrasadKGitHub

    Like in_counts and out_counts methods in objectCounter class, I want get Queue Count in real time to print and use on out side but the method you provided 'counts' in QueueManager class is refreshing to 0, so I made some changes in code in my local system used private variable to get the count out side in real time. How can I make it better?

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      @TechWolf21 to get the real-time queue count, read it from the results returned for each frame (queue_count) instead of modifying QueueManager:

      results = queue(im0)
      print(results.queue_count)

      For details, please refer to the Queue Management documentation.

  2. Alexts166GitHub

    Have a nice day. I made several queue areas, but I can't find the code to get a separate counter to count the total number of people who passed through these areas.

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      @Alexts166 hello!

      Thank you for your question. QueueManager counts the people currently inside its region on each frame (results.queue_count or queue.counts), so with several queue areas you can create one QueueManager per region and sum their counts:

      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 = cv2.VideoWriter("queue_management.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
      
      # Define multiple queue regions
      queue_regions = [
          [(20, 400), (1080, 404), (1080, 360), (20, 360)],
          [(30, 300), (1070, 304), (1070, 260), (30, 260)],
      ]
      
      # Initialize a QueueManager for each region (person class only)
      queues = [solutions.QueueManager(model="yolo26n.pt", region=region, classes=[0], show=False) for region in queue_regions]
      
      while cap.isOpened():
          success, im0 = cap.read()
          if not success:
              print("Video frame is empty or video processing has been successfully completed.")
              break
      
          for queue in queues:
              queue(im0)  # draws on im0
          total_in_queues = sum(queue.counts for queue in queues)  # people currently inside all queue regions
          print(f"People currently in the queue areas: {total_in_queues}")
      
          video_writer.write(im0)
      
      cap.release()
      video_writer.release()
      cv2.destroyAllWindows()

      Note this is a per-frame count of people currently in the regions, not a running total of everyone who has passed through. For cumulative in/out crossing counts, use solutions.ObjectCounter instead.

      For more details on queue management and additional examples, you can refer to our Queue Management Guide.

      If you encounter any issues or have further questions, please provide a reproducible example, and ensure you are using the latest version of the packages. This will help us assist you more effectively.

    2. Alexts166GitHub

      Thanks for the code. I tweaked it a little to fit my needs. There is no summation of objects in queues. Maybe where is the error?

      import cv2
      from ultralytics import YOLO, solutions
      
      # Load the YOLOv8 model
      model = YOLO("best.pt")
      cap = cv2.VideoCapture("gf.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("queue_management.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
      
      # Define multiple queue regions
      queue_regions = [
          [(20, 200), (1200, 200), (1200, 150), (20, 150)],
          [(20, 600), (1200, 600), (1200, 550), (20, 550)]
      ]
      
      # Initialize QueueManager for each region
      queues = [solutions.QueueManager(
          classes_names=model.names,
          reg_pts=region,
          line_thickness=3,
          fontsize=1.0,
          region_color=(255, 144, 31)
      ) for region in queue_regions]
      
      total_count = 0
      
      while cap.isOpened():
          success, im0 = cap.read()
      
          if success:
              tracks = model.track(im0, show=False, persist=True, verbose=False)
              for queue in queues:
                  out = queue.process_queue(im0, tracks)
                  total_count += queue.counts # Accumulate the count from each queue region
      
      
                  color_black = (0, 0, 0)
                  cv2.rectangle(im0, (15, 25), (250, 110), (0, 255, 255), -15)
                  cv2.putText(im0, ('Summ - ') + str(total_count), (20, 50), cv2.FONT_HERSHEY_DUPLEX, 0.8, color_black, 2,
                              cv2.LINE_AA)
      
      
      
      
              video_writer.write(im0)
              if cv2.waitKey(1) & 0xFF == ord("q"):
                  break
              continue
      
          print("Video frame is empty or video processing has been successfully completed.")
          break
      
      cap.release()
      cv2.destroyAllWindows()
    3. Glenn JocherUltralytics

      Hi! It looks like the issue might be with how the counts are being accumulated. Ensure that queue.counts is correctly accessed and reset after each frame. Also, make sure you're using the latest version of the packages. If the problem persists, please provide more details. Happy coding!

  3. QuifaAbasGitHub

    Despite multiple attempts, I'm still facing the same problem. The code isn't generating the expected results. Even with the provided inputs, the results aren't found. Additionally, when trying to generate a video file, the output turns out to be empty. I input a 2.3 MB video file, and it is not an empty file. The code snippet I've been using is,

    Install required packages

    !pip install opencv-python torch

    Import necessary libraries

    from ultralytics import YOLO from ultralytics.solutions import distance_calculation import cv2

    Load YOLO model

    model = YOLO("/content/drive/MyDrive/YOLOv8_1/Distance/yolov8s.pt") # Update the path to yolov8s.pt names = model.model.names

    Load video file

    video_path = "/content/drive/MyDrive/YOLOv8_1/Distance/vid2.mp4" # Update the path to your video file 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

    output_video_path = "/content/drive/MyDrive/YOLOv8_1/Distance/distance_calculation.mp4" video_writer = cv2.VideoWriter(output_video_path, cv2.VideoWriter_fourcc(*'MP4V'), # Or try 'MP4V' for .mp4 files fps, (w, h))

    Init distance-calculation obj

    dist_obj = distance_calculation.DistanceCalculation() dist_obj.set_args(names=names, view_img=False) # Change view_img to False

    while cap.isOpened(): success, im0 = cap.read() if not success: print("End of video or read error encountered.") break

    tracks = model.track(im0, persist=True, show=False)
    
    # Check if any tracks were found
    if len(tracks) > 0:  # Using len() to get the count of elements
        im0 = dist_obj.start_process(im0, tracks)
        
        # Debugging: Save frame only if it's not empty
        if im0 is not None and im0.any():  
            cv2.imwrite('/content/drive/MyDrive/YOLOv8_1/Distance/Copy of Copy of DJI_0083.JPG', im0)  # Save a frame as an image for debugging
            video_writer.write(im0)
        else:
            print("Empty frame detected. Skipping saving to file.")
    else:
        print("No tracks found. Skipping frame processing.")

    Release resources

    video_writer.release() cap.release()

    output_video_path

    The specific error message I'm receiving is "Empty frame detected. Skipping saving to file. End of video or read error encountered.". Strangely, the resulting video file is only 258 bytes in size, indicating an issue with its generation.

    In my pursuit to find a solution, I came across your YouTube video [YouTube Video Link: "https://www.youtube.com/watch?v=LE8am1QoVn4&ab_channel=Ultralytics", where the results showcased are exactly what I'm aiming for. Specifically, I'm keen on measuring the distance between two bounded boxes in both photos and videos.

    Could you please provide a YOLOv8 Google Colab code for both video files and image files that addresses these issues and ensures error-free execution?Specifically, I would need two separate codes: one for processing video files and another for processing image files. Could you include instructions on what file paths I should replace in each code?

    I've made several attempts to correct and run the code, but unfortunately, I keep encountering the same issue. It seems to persist despite my efforts. I hope you understand my actual problem and can provide a solution that resolves the issue. Could you please provide the complete code along with a detailed explanation to help me better understand and address the problem?

    [ I want to attach your comment to my screenshot. How can I do that?I would like to include your comment in my screenshot for reference. Could you please provide guidance on how to attach your comment to the screenshot? ]

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      It looks like you're encountering a common issue with video processing where no tracks are found and your output frames are empty. Let's try a couple of things to resolve this:

      1. Check Video Input: Confirm the video path and contents to ensure it's being read correctly. You have already done this, but double-check if the path is accessible and the video is not corrupted.

      2. Model Loading: Verify the model path for loading the YOLO model. Ensure that yolov8s.pt is the correct model file and path.

      3. Debugging Output: Try increasing the verbosity of your video processing to get more details:

        tracks = model.track(im0, persist=True, show=True, verbose=True)
      4. Update Your Installation: Ensure your ultralytics package is up to date as fixes are frequently released. Use:

        pip install --upgrade ultralytics
      5. Modify Export Code: If the issue persists, simplify the frame processing code to check if any frames are being written to the file at all:

        while cap.isOpened():
            ret, frame = cap.read()
            if not ret:
                break
            video_writer.write(frame)  # write raw frames to see if writing is the issue
      6. Permissions and Path: Ensure that the output path for your video file is correct and your environment has write permissions for that directory.

      Try these steps and see if the issue persists. If it does, you might want to check out a Colab example: Ultralytics YOLO Example Colab.

      Regarding attaching a comment to a screenshot, if you're using screenshot tools like Snipping Tool or Snagit, you can usually add text directly on the image. Alternatively, you can use image editing software like Photoshop or free tools like GIMP to add text annotations.

      Please let me know if these suggestions help resolve your issues or if there’s anything else I can assist you with!

    2. QuifaAbasGitHub

      I've attempted to run the code multiple times, but I'm consistently encountering errors. I ran the code that you provided with the suggested changes, but unfortunately, the issue persists. The code I've been using is,

      Install required packages

      !pip install opencv-python torch !pip install --upgrade ultralytics

      Import necessary libraries

      from ultralytics import YOLO from ultralytics.solutions import distance_calculation import cv2

      Load YOLO model

      model = YOLO("/content/drive/MyDrive/YOLOv8_1/Distance/yolov8s.pt") # Update the path to yolov8s.pt names = model.model.names

      Load video file

      video_path = "/content/drive/MyDrive/YOLOv8_1/Distance/vid2.mp4" # Update the path to your video file 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

      output_video_path = "/content/drive/MyDrive/YOLOv8_1/Distance/distance_calculation.mp4" video_writer = cv2.VideoWriter(output_video_path, cv2.VideoWriter_fourcc(*'MP4V'), # Or try 'MP4V' for .mp4 files fps, (w, h))

      Init distance-calculation obj

      dist_obj = distance_calculation.DistanceCalculation() dist_obj.set_args(names=names, view_img=False) # Change view_img to False

      while cap.isOpened(): ret, frame = cap.read() if not ret: break video_writer.write(frame) # write raw frames to see if writing is the issue

      tracks = model.track(im0, persist=True, show=True, verbose=True)
      
      # Check if any tracks were found
      if len(tracks) > 0:  # Using len() to get the count of elements
          im0 = dist_obj.start_process(im0, tracks)
      
          # Debugging: Save frame only if it's not empty
          if im0 is not None and im0.any():
              cv2.imwrite('/content/drive/MyDrive/YOLOv8_1/Distance/Copy of Copy of DJI_0083.JPG', im0)  # Save a frame as an image for debugging
              video_writer.write(im0)
          else:
              print("Empty frame detected. Skipping saving to file.")
      else:
          print("No tracks found. Skipping frame processing.")

      Release resources

      video_writer.release() cap.release()

      output_video_path

      and the resulting output is,

      Requirement already satisfied: torchvision>=0.9.0 in /usr/local/lib/python3.10/dist-packages (from ultralytics) (0.17.1+cu121) Requirement already satisfied: tqdm>=4.64.0 in /usr/local/lib/python3.10/dist-packages (from ultralytics) (4.66.2) Requirement already satisfied: psutil in /usr/local/lib/python3.10/dist-packages (from ultralytics) (5.9.5) Requirement already satisfied: py-cpuinfo in /usr/local/lib/python3.10/dist-packages (from ultralytics) (9.0.0) Requirement already satisfied: thop>=0.1.1 in /usr/local/lib/python3.10/dist-packages (from ultralytics) (0.1.1.post2209072238) Requirement already satisfied: pandas>=1.1.4 in /usr/local/lib/python3.10/dist-packages (from ultralytics) (2.0.3) Requirement already satisfied: seaborn>=0.11.0 in /usr/local/lib/python3.10/dist-packages (from ultralytics) (0.13.1) Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.10/dist-packages (from matplotlib>=3.3.0->ultralytics) (1.2.1) Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.10/dist-packages (from matplotlib>=3.3.0->ultralytics) (0.12.1) Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.10/dist-packages (from matplotlib>=3.3.0->ultralytics) (4.51.0) Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.10/dist-packages (from matplotlib>=3.3.0->ultralytics) (1.4.5) Requirement already satisfied: numpy>=1.20 in /usr/local/lib/python3.10/dist-packages (from matplotlib>=3.3.0->ultralytics) (1.25.2) Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from matplotlib>=3.3.0->ultralytics) (24.0) Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.10/dist-packages (from matplotlib>=3.3.0->ultralytics) (3.1.2) Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.10/dist-packages (from matplotlib>=3.3.0->ultralytics) (2.8.2) Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.10/dist-packages (from pandas>=1.1.4->ultralytics) (2023.4) Requirement already satisfied: tzdata>=2022.1 in /usr/local/lib/python3.10/dist-packages (from pandas>=1.1.4->ultralytics) (2024.1) Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests>=2.23.0->ultralytics) (3.3.2) Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests>=2.23.0->ultralytics) (3.7) Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests>=2.23.0->ultralytics) (2.0.7) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests>=2.23.0->ultralytics) (2024.2.2) Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (3.14.0) Requirement already satisfied: typing-extensions>=4.8.0 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (4.11.0) Requirement already satisfied: sympy in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (1.12) Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (3.3) Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (3.1.3) Requirement already satisfied: fsspec in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (2023.6.0) Requirement already satisfied: nvidia-cuda-nvrtc-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (12.1.105) Requirement already satisfied: nvidia-cuda-runtime-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (12.1.105) Requirement already satisfied: nvidia-cuda-cupti-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (12.1.105) Requirement already satisfied: nvidia-cudnn-cu12==8.9.2.26 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (8.9.2.26) Requirement already satisfied: nvidia-cublas-cu12==12.1.3.1 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (12.1.3.1) Requirement already satisfied: nvidia-cufft-cu12==11.0.2.54 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (11.0.2.54) Requirement already satisfied: nvidia-curand-cu12==10.3.2.106 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (10.3.2.106) Requirement already satisfied: nvidia-cusolver-cu12==11.4.5.107 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (11.4.5.107) Requirement already satisfied: nvidia-cusparse-cu12==12.1.0.106 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (12.1.0.106) Requirement already satisfied: nvidia-nccl-cu12==2.19.3 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (2.19.3) Requirement already satisfied: nvidia-nvtx-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (12.1.105) Requirement already satisfied: triton==2.2.0 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8.0->ultralytics) (2.2.0) Requirement already satisfied: nvidia-nvjitlink-cu12 in /usr/local/lib/python3.10/dist-packages (from nvidia-cusolver-cu12==11.4.5.107->torch>=1.8.0->ultralytics) (12.4.127) Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.10/dist-packages (from python-dateutil>=2.7->matplotlib>=3.3.0->ultralytics) (1.16.0) Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch>=1.8.0->ultralytics) (2.1.5) Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.10/dist-packages (from sympy->torch>=1.8.0->ultralytics) (1.3.0) WARNING ⚠️ Environment does not support cv2.imshow() or PIL Image.show()


      NameError Traceback (most recent call last) in <cell line: 31>() 35 video_writer.write(frame) # write raw frames to see if writing is the issue 36 ---> 37 tracks = model.track(im0, persist=True, show=True, verbose=True) 38 39 # Check if any tracks were found

      NameError: name 'im0' is not defined

      Unfortunately, I'm unable to attach a screenshot directly. Could you please provide the complete code to resolve this issue?

      I did try my older code, which is,

      Install required packages

      !pip install opencv-python torch

      Import necessary libraries

      from ultralytics import YOLO from ultralytics.solutions import distance_calculation import cv2

      Load YOLO model

      model = YOLO("/content/drive/MyDrive/YOLOv8_1/Distance/yolov8s.pt") # Update the path to yolov8s.pt names = model.model.names

      Load video file

      video_path = "/content/drive/MyDrive/YOLOv8_1/Distance/vid2.mp4" # Update the path to your video file 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

      output_video_path = "/content/drive/MyDrive/YOLOv8_1/Distance/distance_calculation.mp4" video_writer = cv2.VideoWriter(output_video_path, cv2.VideoWriter_fourcc(*'MP4V'), # Or try 'MP4V' for .mp4 files fps, (w, h))

      Init distance-calculation obj

      dist_obj = distance_calculation.DistanceCalculation() dist_obj.set_args(names=names, view_img=False) # Change view_img to False

      while cap.isOpened(): success, im0 = cap.read() if not success: print("End of video or read error encountered.") break

      tracks = model.track(im0, persist=True, show=False)
      
      # Check if any tracks were found
      if len(tracks) > 0:  # Using len() to get the count of elements
          im0 = dist_obj.start_process(im0, tracks)
      
          # Debugging: Save frame only if it's not empty
          if im0 is not None and im0.any():
              cv2.imwrite('/content/drive/MyDrive/YOLOv8_1/Distance/Copy of Copy of DJI_0083.JPG', im0)  # Save a frame as an image for debugging
              video_writer.write(im0)
          else:
              print("Empty frame detected. Skipping saving to file.")
      else:
          print("No tracks found. Skipping frame processing.")

      Release resources

      video_writer.release() cap.release()

      output_video_path

      and the resulting output was ,

      Requirement already satisfied: nvidia-nccl-cu12==2.19.3 in /usr/local/lib/python3.10/dist-packages (from torch) (2.19.3) Requirement already satisfied: nvidia-nvtx-cu12==12.1.105 in /usr/local/lib/python3.10/dist-packages (from torch) (12.1.105) Requirement already satisfied: triton==2.2.0 in /usr/local/lib/python3.10/dist-packages (from torch) (2.2.0) Requirement already satisfied: nvidia-nvjitlink-cu12 in /usr/local/lib/python3.10/dist-packages (from nvidia-cusolver-cu12==11.4.5.107->torch) (12.4.127) Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch) (2.1.5) Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.10/dist-packages (from sympy->torch) (1.3.0) WARNING ⚠️ Environment does not support cv2.imshow() or PIL Image.show()

      requirements: Ultralytics requirement ['lapx>=0.5.2'] not found, attempting AutoUpdate... Collecting lapx>=0.5.2 Downloading lapx-0.5.8-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.7 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.7/1.7 MB 14.6 MB/s eta 0:00:00 Requirement already satisfied: Cython>=0.29.32 in /usr/local/lib/python3.10/dist-packages (from lapx>=0.5.2) (3.0.10) Requirement already satisfied: numpy>=1.21.6 in /usr/local/lib/python3.10/dist-packages (from lapx>=0.5.2) (1.25.2) Installing collected packages: lapx Successfully installed lapx-0.5.8

      requirements: AutoUpdate success ✅ 8.7s, installed 1 package: ['lapx>=0.5.2'] requirements: ⚠️ Restart runtime or rerun command for updates to take effect

      0: 384x640 (no detections), 566.5ms Speed: 29.6ms preprocess, 566.5ms inference, 4702.4ms postprocess per image at shape (1, 3, 384, 640) Empty frame detected. Skipping saving to file.

      0: 384x640 (no detections), 436.2ms Speed: 3.1ms preprocess, 436.2ms inference, 0.9ms postprocess per image at shape (1, 3, 384, 640) Empty frame detected. Skipping saving to file.

      0: 384x640 (no detections), 410.8ms Speed: 3.4ms preprocess, 410.8ms inference, 1.5ms postprocess per image at shape (1, 3, 384, 640) Empty frame detected. Skipping saving to file.

      0: 384x640 1 potted plant, 412.6ms Speed: 3.1ms preprocess, 412.6ms inference, 15.0ms postprocess per image at shape (1, 3, 384, 640) Empty frame detected. Skipping saving to file.

      0: 384x640 1 potted plant, 428.9ms Speed: 3.2ms preprocess, 428.9ms inference, 1.3ms postprocess per image at shape (1, 3, 384, 640) Empty frame detected. Skipping saving to file.

      0: 384x640 1 potted plant, 545.6ms Speed: 3.8ms preprocess, 545.6ms inference, 1.9ms postprocess per image at shape (1, 3, 384, 640) Empty frame detected. Skipping saving to file.

      0: 384x640 (no detections), 546.6ms Speed: 3.0ms preprocess, 546.6ms inference, 1.3ms postprocess per image at shape (1, 3, 384, 640) Empty frame detected. Skipping saving to file.

      0: 384x640 (no detections), 626.9ms Speed: 3.6ms preprocess, 626.9ms inference, 1.2ms postprocess per image at shape (1, 3, 384, 640) Empty frame detected. Skipping saving to file.

      0: 384x640 (no detections), 631.8ms Speed: 3.4ms preprocess, 631.8ms inference, 1.2ms postprocess per image at shape (1, 3, 384, 640) Empty frame detected. Skipping saving to file. End of video or read error encountered. /content/drive/MyDrive/YOLOv8_1/Distance/distance_calculation.mp4

      The specific error message I'm receiving is "Empty frame detected. Skipping saving to file. End of video or read error encountered.". Strangely, the resulting video file is only 258 bytes in size, indicating an issue with its generation.

    3. Glenn JocherUltralytics(đã chỉnh sửa)

      Hi there! 👋 It seems like you're encountering a persistent issue with detecting objects in your video file. Let's try a couple of adjustments:

      1. Ensure Correct Model Load: Double-check if the path to your model (yolov8s.pt) is correct and the model is appropriately loaded.

      2. Verify Video Content: Sometimes, if the video does not include the objects the model is trained to detect, it may not find any tracks. Confirm that the target objects are present in the video.

      3. Frame Handling: Right before calling the solution (distancecalculator(frame)), ensure that frame is your actual frame variable from ret, frame = cap.read().

      4. Debugging Output: Increase logging for each step and verify each component's output, such as the captured frames and the model's response.

      Here's a simplified snippet to recheck each part:

      from ultralytics import solutions
      
      distancecalculator = solutions.DistanceCalculation(model="yolo26n.pt", show=True)  # tracking is handled internally
      
      while cap.isOpened():
          ret, frame = cap.read()
          if not ret:
              print("Failed to read frame.")
              break
      
          # Debugging: Show frame dimension
          print(f"Frame dimensions: {frame.shape}")
      
          results = distancecalculator(frame)
          video_writer.write(results.plot_im)
      
      # Cleanup
      cap.release()
      video_writer.release()
      print("Released all resources.")

      Adjust the debugging prints as necessary to check the outputs directly. Let me know how it goes, and if there's anything else I can help with! 🚀

    4. QuifaAbasGitHub(đã chỉnh sửa)

      I have zero knowledge in YOLOv8, as I'm an undergraduate student in Electrical Engineering. My final year project topic is 'Unmanned Aerial Systems (UAS) for Enhanced Vegetation Management in Electric Distribution Networks'. Initially, I aimed to detect vegetation and power lines in single frames. I successfully achieved this using YOLOv8 in Google Colab for images. However, I encountered difficulties when applying the same approach to videos, particularly in detecting power lines accurately.

      To enhance the accuracy of power line detection, I plan to collect more photos using a drone. Additionally, I aim to measure the distance between vegetation and power lines. Despite my efforts, I've faced repeated challenges in implementing these tasks.

      I have shared a link to my Google Drive , which contains my files. Within this folder, I've included one of the best detection images, the detected video, the final output, and my code.

      I kindly request two separate complete codes—one for image tracking and another for video tracking. As I have minimal knowledge about where to make changes in the code, it would greatly assist me if you could run the code using my data and provide the necessary adjustments.

    5. Glenn JocherUltralytics(đã chỉnh sửa)

      Hello! 🚀 It's great to see you using YOLOv8 for your project on unmanned aerial systems for vegetation management. Since you're encountering issues with power line detection in videos, here are a few suggestions:

      1. Data Collection: Collecting more diverse images of power lines and vegetation at different times and conditions will definitely help in improving the model's accuracy.

      2. Annotation Quality: Ensure that your additional images are accurately annotated to improve learning during training.

      3. Model Training for Video: Although you've successfully used YOLOv8 for single frame detections, video processing can be trickier due to motion and different angles. Consider using techniques like temporal smoothing or frame-to-frame tracking to enhance accuracy.

      Here's a basic outline on how you could set up your code for video processing using your own data:

      import cv2
      from ultralytics import YOLO
      
      # Load your pre-trained model
      model = YOLO("/path/to/your/model.pt")
      
      # Setup the video capture
      cap = cv2.VideoCapture("/path/to/your/video.mp4")
      while cap.isOpened():
          ret, frame = cap.read()
          if not ret:
              break
          
          # Detect objects in the frame
          results = model.predict(frame)
      
          # Optionally, visualize the results
          annotated_frame = results[0].plot()  # frame with the detections drawn
          cv2.imshow('YOLO Detections', annotated_frame)
          if cv2.waitKey(1) & 0xFF == ord('q'):
              break
      
      cap.release()
      cv2.destroyAllWindows()

      For measuring distances between detected objects like vegetation and power lines, you'd have to post-process the detection bounding boxes from YOLOv8. Calculating distances could be based on known scales or additional sensors like LiDAR data if your drone setup permits.

      If you have any more questions or need further assistance with your code, feel free to ask. Best of luck with your exciting project! 🌿⚡

    6. QuifaAbasGitHub(đã chỉnh sửa)

      I've tried multiple times, but I haven't been successful in getting the distance calculation code to work properly.

      1. Could you please ensure that the distance calculation code is implemented correctly for both my image and video files? [I have asked multiple times for you in providing separate code for processing my image and video files. However, you have only provided code for the video file. As I have zero knowledge in YOLOv8 coding, it's challenging for me to adapt the provided code for my image files. I kindly request your understanding of my situation and would greatly appreciate separate code for both image and video files.]

      2. Once you've done so, Could you please provide the results for both my video and image files, which I have attached in the Google Drive folder?

      3. Can you share these results with me via your Google Drive link?

      I have a tight deadline to complete my project within this week, and your assistance would be immensely valuable. Thank you for understanding my situation. I am seeking results that accurately measure the distance between the vegetation bounded box and powerline bounded box in both my input image and input video. The desired outcome is to achieve results that closely resemble the accuracy and presentation demonstrated in your YouTube video (https://www.youtube.com/watch?v=LE8am1QoVn4&t=5s&ab_channel=Ultralytics). detection1

      detection2

      I have clearly articulated my problem and outlined my specific requests. I kindly request your attention to my three requests and urge you to help me resolve my problem. 🥰

    7. Glenn JocherUltralytics(đã chỉnh sửa)

      Hello! Thanks for sharing the details and your Google Drive link. It sounds like you're facing a challenge with adapting the distance calculation code specifically for images, along with your existing video processing.

      For processing images separately, you can follow a similar approach as with videos but adapted for single-frame use. Here is a simplified code snippet that processes individual images:

      from ultralytics import YOLO
      import cv2
      
      # Load the model
      model = YOLO('path/to/your/model.pt')
      
      # Load an image
      image_path = 'path/to/your/image.jpg'
      image = cv2.imread(image_path)
      
      # Predict using the model
      results = model.predict(image)
      
      # Display detected objects with bounding boxes
      results[0].show()

      For the videos, if the provided code doesn't meet expectations, it helps to first manually check a few frames to understand what's missing or incorrect. This could be due to various factors such as the model's sensitivity, training data, or the quality/resolution of the video frame.

      I've noticed your tight deadline and understand the importance of precise and timely responses. Please check the code above, and let's ensure it aligns with your project's requirements. If you need adjustments or further assistance, feel free to let me know! 🌟

    8. QuifaAbasGitHub(đã chỉnh sửa)

      Once again, I am encountering a problem. I have attached a screenshot of the error I'm facing, along with the image for which I want to measure the distance between the vegetation and powerline. Initially, could you please provide me with the tracked image? Subsequently, I will require the results image corresponding to the attached image. Following that, kindly provide the code necessary to achieve this task.

    9. Glenn JocherUltralytics(đã chỉnh sửa)

      @QuifaAbas hello! Thanks for reaching out and sharing the details and your screenshot. It seems like you're looking to measure distances between detected objects in an image, which is a great application of YOLOv8.

      For measuring distances, we would typically process the output of the detection model to obtain bounding boxes, and then calculate the distances based on these coordinates.

      Here's a simplified approach to get you started with the image processing:

      from ultralytics import YOLO
      import cv2
      
      # Load your pre-trained model
      model = YOLO('path/to/your/model.pt')
      
      # Load your image
      image = cv2.imread('path/to/your/image.jpg')
      
      # Perform detection
      results = model.predict(image)
      
      # Extract bounding boxes (for example, for vegetation and power lines)
      result = results[0]
      for box in result.boxes:
          name = result.names[int(box.cls)]
          if name == 'vegetation':  # replace with your actual class
              veg_box = box.xyxy[0].tolist()  # x1, y1, x2, y2
          elif name == 'power line':  # replace with your actual class
              pline_box = box.xyxy[0].tolist()  # x1, y1, x2, y2
      
      # Calculate distances between objects (simplified Euclidean distance)
      distance = ((veg_box[0] - pline_box[0])**2 + (veg_box[1] - pline_box[1])**2)**0.5
      
      # Draw results on image
      annotated_image = result.plot()
      
      # Save or display the annotated image
      cv2.imwrite('output.jpg', annotated_image)
      cv2.imshow('Distance Detection', annotated_image)
      cv2.waitKey(0)
      cv2.destroyAllWindows()

      For video files, you can follow a similar approach by processing each frame for detections and computing distances as outlined above.

      If you need further customization or assistance, we're here to help! 🚀

    10. QuifaAbasGitHub(đã chỉnh sửa)

      Once again, I am encountering a problem. I have attached a screenshot of the error I'm facing, along with the image for which I want to measure the distance between the vegetation and powerline. My objective is to detect and measure distances between power lines and vegetation. Initially, could you please provide me with the tracked image? Subsequently, I will require the results image corresponding to the attached image. Following that, kindly provide the code necessary to achieve this task.

    11. Glenn JocherUltralytics(đã chỉnh sửa)

      Hello! 🚀 It looks like you've run into some challenges with error handling and distance measurements between detected objects in your images. Let's tackle this step by step.

      To help you measure the distances between detected vegetation and power lines in the image, you can utilize the coordinates of the bounding boxes provided by the YOLOv8 detections. Here's a simple code snippet to get you started:

      from ultralytics import YOLO
      import cv2
      
      # Load your model
      model = YOLO('path/to/your/yolov8-model.pt')
      
      # Load your image
      image = cv2.imread('path/to/your/image.jpg')
      
      # Detect objects
      results = model.predict(image)
      
      # Draw boxes and labels on the image
      results[0].show()
      
      # Save or display the image
      cv2.imwrite('tracked_image.jpg', results[0].plot())
      
      # Extract bounding boxes for specific classes
      veg_boxes = [b.xyxy[0].tolist() for b in results[0].boxes if results[0].names[int(b.cls)] == 'Vegetation']
      pline_boxes = [b.xyxy[0].tolist() for b in results[0].boxes if results[0].names[int(b.cls)] == 'Power Line']
      
      # Assuming you want the distance between the closest points, calculate Euclidean distance
      from scipy.spatial import distance
      if veg_boxes and pline_boxes:
          veg_point = veg_boxes[0][:2]  # Example: top-left corner of the first vegetation box
          pline_point = pline_boxes[0][:2]  # Example: top-left corner of the first powerline box
          dist = distance.euclidean(veg_point, pline_point)
          print(f"Distance between closest points: {dist} pixels")

      Make sure to modify the path/to/your/yolov8-model.pt and path/to/your/image.jpg according to your files. This code will print the Euclidean distance between the top left corners of the first detected vegetation and power line boxes.

      I hope this helps! Start with this basic functionality and you can tune further based on your project needs. Let me know if there are specific aspects you want to adjust or if you encounter further issues! 🌿⚡