Bắt đầu

Phân đoạn đối tượng và tracking bằng Ultralytics YOLO26

Phân đoạn đối tượng là gì?#

Phân đoạn đối tượng là tác vụ thị giác máy tính nhằm xác định và phác họa từng đối tượng riêng lẻ trong ảnh ở cấp độ pixel. Khác với phân đoạn ngữ nghĩa, vốn chỉ phân loại pixel theo danh mục, phân đoạn đối tượng gán nhãn riêng biệt và phân định chính xác từng instance đối tượng, nhờ đó đóng vai trò thiết yếu trong các ứng dụng cần hiểu biết không gian chi tiết như chẩn đoán hình ảnh y khoa, xe tự hành và tự động hóa công nghiệp.

Ultralytics YOLO26 xác định chính xác ranh giới đối tượng, đồng thời duy trì tốc độ và hiệu quả vốn có của các model YOLO.

Gói Ultralytics cung cấp hai kiểu tracking phân đoạn đối tượng:

  • Phân đoạn đối tượng theo lớp: Mỗi đối tượng thuộc lớp được gán một màu riêng để dễ phân biệt bằng hình ảnh.

  • Phân đoạn đối tượng theo track: Mỗi track được biểu thị bằng một màu riêng biệt, giúp dễ dàng nhận diện và theo dõi qua các khung hình video.



Xem: Phân đoạn instance kết hợp theo dõi đối tượng bằng Ultralytics YOLO26

Mẫu#

Phân đoạn đối tượngPhân đoạn đối tượng + tracking đối tượng
Phân đoạn đối tượng UltralyticsPhân đoạn đối tượng Ultralytics với tracking đối tượng
Phân đoạn đối tượng theo instance của UltralyticsPhân đoạn đối tượng theo instance của Ultralytics kết hợp theo dõi đối tượng

Phân đoạn và tracking bằng YOLO26#

Giải pháp InstanceSegmentation chạy model phân đoạn YOLO26 trên từng khung hình, vẽ mask riêng cho từng đối tượng và tô màu từng instance riêng biệt để bạn có thể theo dõi từng đối tượng xuyên suốt video. Tải model -seg như YOLO26n-seg, sau đó chạy model trên nguồn dữ liệu bằng Python API hoặc CLI.

Phân đoạn đối tượng bằng Ultralytics YOLO
# Instance segmentation using Ultralytics YOLO26
yolo solutions isegment show=True

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

# Monitor the specific classes
yolo solutions isegment classes="[0, 5]"

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

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

Đối sốKiểuMặc địnhMô tả
modelstrNoneĐường dẫn đến tệp model Ultralytics YOLO.
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ý.

Bạn cũng có thể sử dụng các đối số track trong giải pháp InstanceSegmentation:

Đố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, có thể sử dụng các đối 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.
show_boxesboolTrueVẽ bounding box quanh các đối tượng được phát hiện. Cần thiết để nhận diện trực quan và xác định vị trí đối tượng trong ảnh hoặc frame video.

Các ứng dụng của phân đoạn đối tượng#

Phân đoạn đối tượng bằng YOLO26 có nhiều ứng dụng thực tế trong các ngành công nghiệp khác nhau:

Quản lý và tái chế chất thải#

YOLO26 có thể được sử dụng tại các cơ sở quản lý chất thải để nhận diện và phân loại nhiều loại vật liệu. Model có thể phân đoạn rác thải nhựa, bìa carton, kim loại và các vật liệu có thể tái chế khác với độ chính xác cao, giúp hệ thống phân loại tự động xử lý chất thải hiệu quả hơn. Điều này đặc biệt có giá trị khi chỉ khoảng 10% trong số 7 tỷ tấn rác thải nhựa được tạo ra trên toàn cầu được tái chế.

Xe tự hành#

Trong xe tự lái, phân đoạn đối tượng theo instance giúp xác định và theo dõi người đi bộ, phương tiện, biển báo giao thông cùng các yếu tố đường bộ khác ở cấp độ pixel. Khả năng hiểu môi trường chính xác này rất quan trọng đối với các quyết định điều hướng và an toàn. Hiệu suất thời gian thực của YOLO26 khiến model này rất phù hợp với các ứng dụng đòi hỏi phản hồi nhanh.

Chẩn đoán hình ảnh y khoa#

Phân đoạn đối tượng có thể xác định và phác họa khối u, cơ quan hoặc cấu trúc tế bào trong ảnh chụp y khoa. Khả năng phân định chính xác ranh giới đối tượng của YOLO26 rất hữu ích cho chẩn đoán y khoa và lập kế hoạch điều trị.

Giám sát công trường xây dựng#

Tại công trường xây dựng, phân đoạn đối tượng theo instance có thể theo dõi máy móc hạng nặng, công nhân và vật liệu. Điều này giúp đảm bảo an toàn bằng cách giám sát vị trí thiết bị và phát hiện khi công nhân đi vào khu vực nguy hiểm, đồng thời tối ưu hóa quy trình làm việc và phân bổ tài nguyên.

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

  • Để phân đoạn đối tượng theo instance bằng Ultralytics YOLO26, hãy khởi tạo giải pháp InstanceSegmentation với một model phân đoạn YOLO26 rồi xử lý các khung hình video bằng model đó. Sau đây là ví dụ mã đơn giản:

    import cv2
    
    from ultralytics import solutions
    
    cap = cv2.VideoCapture("path/to/video.mp4")
    assert cap.isOpened(), "Error reading video file"
    
    # Bộ ghi video
    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("instance-segmentation.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
    
    # Khởi tạo InstanceSegmentation
    isegment = solutions.InstanceSegmentation(
        show=True,  # hiển thị đầu ra
        model="yolo26n-seg.pt",  # model="yolo26n-seg.pt" để phân đoạn đối tượng bằng YOLO26.
    )
    
    # Xử lý video
    while cap.isOpened():
        success, im0 = cap.read()
        if not success:
            print("Video frame is empty or processing is complete.")
            break
        results = isegment(im0)
        video_writer.write(results.plot_im)
    
    cap.release()
    video_writer.release()
    cv2.destroyAllWindows()
  • Phân đoạn đối tượng theo instance xác định và phác họa từng đối tượng riêng lẻ trong ảnh, gán cho mỗi đối tượng một nhãn và mask duy nhất. Theo dõi đối tượng mở rộng chức năng này bằng cách gán ID nhất quán cho các đối tượng qua các khung hình video, hỗ trợ theo dõi liên tục cùng một đối tượng theo thời gian. Khi kết hợp hai chức năng như trong cách triển khai của YOLO26, bạn có thể phân tích chuyển động và hành vi của đối tượng trong video mà vẫn giữ được thông tin ranh giới chính xác.

  • So với các model hai giai đoạn như Mask R-CNN hoặc Faster R-CNN, Ultralytics YOLO26 mang lại hiệu suất thời gian thực, độ chính xác cạnh tranh và tính dễ sử dụng. YOLO26 xử lý ảnh trong một lượt (phát hiện một giai đoạn), nhờ đó nhanh hơn nhiều mà vẫn duy trì độ chính xác cao. Model này cũng tích hợp với Ultralytics Platform để quản lý model, dataset và pipeline huấn luyện. YOLO26 mang đến sự cân bằng hiệu quả cho các ứng dụng cần cả tốc độ lẫn độ chính xác.

  • Có, Ultralytics cung cấp một số dataset phù hợp để huấn luyện model YOLO26 cho phân đoạn đối tượng, bao gồm COCO-Seg, COCO8-Seg (tập con nhỏ hơn để kiểm thử nhanh), Package-Seg và Crack-Seg. Các dataset này có chú thích ở cấp độ pixel cần thiết cho tác vụ phân đoạn đối tượng. Với các ứng dụng chuyên biệt hơn, bạn cũng có thể tạo dataset tùy chỉnh theo định dạng Ultralytics. Thông tin đầy đủ về dataset và hướng dẫn sử dụng có trong tài liệu Ultralytics Datasets.

Bình luận99

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

  1. CatFatOwGitHub

    Hello, I am trying to analyze a video and see if features grow/shrink over time. I am currently trying to use instance segmentation with object tracking; however, specifying save_txt=True parameter in model.track saves every single prediction into a single huge txt file. Trying to count the frames by going through this large txt apparently doesn't work as the class ID are not in order and sorting it would lose all information.

    Is there any way for Ultralytics to save the txt files by frame number? For example, frame1.txt only contains the predictions of the first frame.

    Any help would be greatly appreciated!

    1
    1. Glenn JocherUltralytics

      For per-frame TXT saving with tracking, you'll need to process results in your video loop and write custom frame-specific files. Here's a minimal adaptation of the Instance Segmentation and Tracking example:

      frame_count = 0
      while cap.isOpened():
          ret, im0 = cap.read()
          if not ret: break
          
          results = model.track(im0, persist=True)
          
          # Save current frame's tracked objects
          with open(f'frame{frame_count}.txt', 'w') as f:
              for box, mask, track_id in zip(results[0].boxes, results[0].masks, results[0].boxes.id.int().cpu().tolist()):
                  f.write(f"{track_id} {box.cls.item()} {box.xywhn.tolist()} {mask.xy[0].tolist()}\n")
          
          frame_count += 1

      This creates individual frameX.txt files with tracking IDs, class IDs, normalized boxes, and mask coordinates. The official documentation shows similar frame processing in the Instance Segmentation with Object Tracking examples.

    2. Glenn JocherUltralytics

      For per-frame TXT saving during tracking, you'll need to process each frame individually in your video loop as shown in the Instance Segmentation with Object Tracking example. Here's a minimal adaptation that creates frame-specific files:

      frame_count = 0
      while cap.isOpened():
          ret, im0 = cap.read()
          if not ret: break
          
          results = model.track(im0, persist=True)
          
          with open(f'frame{frame_count}.txt', 'w') as f:
              for box, mask, track_id in zip(results[0].boxes, results[0].masks, results[0].boxes.id.int().cpu().tolist()):
                  f.write(f"{track_id} {box.cls.item()} {box.xywhn.tolist()} {mask.xy[0].tolist()}\n")
          
          frame_count += 1

      This creates individual frameX.txt files with tracking IDs, class IDs, normalized boxes, and mask coordinates per frame. The approach mirrors the frame processing shown in our official tracking documentation.

  2. pedmindsetGitHub

    Been trying to figure this out for a while now. I want to ask, can I use object counting in regions with instance sementation and tracking? You want to count vehicles that cross two specific regions, like so Object 001 crossed region A and region B. Is this possible to do

    1
    1. Glenn JocherUltralytics

      @pedmindset yes, it is possible to combine object counting in regions with instance segmentation and tracking using Ultralytics YOLO11. You can use the track method to assign consistent IDs to objects across frames and define regions to monitor their crossings. For guidance, refer to the segmentation and tracking examples in the Instance Segmentation and Tracking Guide. Let us know if you need further clarification!

  3. DP1701GitHub

    Cool, but I can't define an imgsz via solutions.InstanceSegmentation(…). Is there another option for this?

    1. Glenn JocherUltralytics

      solutions.InstanceSegmentation is a higher-level wrapper and doesn’t currently expose imgsz directly; if you need to control input size, run segmentation+tracking via the core YOLO(...).track() API (supports imgsz) as shown in the Tracking mode docs and keep using the Instance Segmentation and Tracking guide for solution-level usage.

      from ultralytics import YOLO
      
      model = YOLO("yolo26n-seg.pt")
      results = model.track(source="path/to/video.mp4", imgsz=640, show=True, tracker="botsort.yaml")
  4. CatFatOwGitHub

    Hello, I noticed that when using tracking mode compared to normal segmentation prediction, the number of features predicted decreased by quite a lot for feature dense videos even if I use the same parameters of confidence and maximum detection?

    1. Glenn JocherUltralytics

      @CatFatOw great observation! This is actually expected behavior when using tracking mode compared to plain segmentation. Tracking algorithms apply additional filtering beyond confidence thresholds to maintain stable tracks, which can reduce the total number of detections.

      Here are a few things that might help increase detections while maintaining tracking:

      # Try adjusting these tracking-specific parameters
      results = model.track(
          frame, 
          persist=True,
          conf=0.3,  # Lower confidence threshold
          iou=0.5,   # Adjust IoU threshold for NMS
          max_det=1000,  # Increase max detections
          tracker="bytetrack.yaml"  # Try different trackers
      )

      You can also experiment with different tracking algorithms - ByteTrack tends to be more permissive with new track creation compared to BoTSORT. The trade-off is between detection sensitivity and tracking stability, where tracking prioritizes consistent object IDs over detecting every possible instance.

      If you need maximum detection sensitivity, consider running both modes and using tracking results only when you need the temporal consistency.

  5. Mauricio566GitHub

    Hello. Please, I need your help. I know exactly what segmenting an object is and how to do it. But I don't know what to do with an already segmented object or pixel mask. You can find a lot of information online about "how to segment a model or fit it to your dataset," but they don't tell you what to do with those masks in real projects. Can you give me some ideas or help, please? for r in results:
    if r.masks is not None: mask = r.masks.data[0].cpu().numpy() there is the mask but honestly I don't know what to do. thanks

  6. e-roeGitHub

    Hello Glenn, thanks for the example! Actually, I had already figured it out—it was more of a suggestion for the documentation examples. []´s

    1. Glenn JocherUltralytics

      Thank you for the suggestion! We always welcome community contributions to improve our documentation through GitHub Pull Requests. Feel free to submit any specific improvements you'd like to see in the Instance Segmentation with Object Tracking guide.

      1
  7. e-roeGitHub

    Hello, Wouldn't it be good to have a complete example showing how to extract the track ID, contour points, class, and confidence? These methods that handle everything automatically end up being of little practical use, and finding this information in the documentation is quite challenging—it's often easier to find from third-party sources. []´s

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

      @e-roe thanks for your feedback! You can access track IDs, classes, masks, and confidence scores directly from the results object. Here's a concise example showing how to extract these details:

      results = isegment(im0)
      for i in range(len(isegment.clss)):
          track_id = isegment.track_ids[i]
          class_name = isegment.names[isegment.clss[i]]
          confidence = isegment.confs[i]
          mask = isegment.masks[i].data[0].numpy()  # Binary mask array
          contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

      For full implementation details, see the InstanceSegmentation reference in our documentation. Let us know if you need further clarification!

  8. expen6veGitHub

    Hi! I tried training a pretrained yolov8m-seg model on our custom 1 class dataset consisting of 1,307 images with 5 augmentations like:

    Flip: Horizontal, Vertical Rotation: Between -15° and +15° Saturation: Between -25% and +25% Blur: Up to 1.4px Noise: Up to 1.49% of pixels

    with these training configurations:

    # Train the model
    results = model.train(
        data="data6.yaml",
        epochs=250,
        imgsz=320,
        batch=8,
        workers=4,
        device=device,
        patience=18,
        copy_paste=0.1  # Add this line to enable copy-paste augmentation
    )

    this is my 16th model training as i tried testing out from 200+ images that and so on. In my val plots, i always get bad results. What can i further do to make a good model? it stopped training at 128 with the results below:

    epoch,time,train/box_loss,train/seg_loss,train/cls_loss,train/dfl_loss,metrics/precision(B),metrics/recall(B),metrics/mAP50(B),metrics/mAP50-95(B),metrics/precision(M),metrics/recall(M),metrics/mAP50(M),metrics/mAP50-95(M),val/box_loss,val/seg_loss,val/cls_loss,val/dfl_loss,lr/pg0,lr/pg1,lr/pg2

    126,4123.96,0.47628,0.76702,0.30532,0.85667,0.9862,0.96565,0.98972,0.94445,0.9775,0.97566,0.98923,0.83189,0.35178,0.67432,0.26286,0.89191,0.00101,0.00101,0.00101 127,4156.45,0.47613,0.76458,0.30439,0.85872,0.96877,0.98339,0.98913,0.94227,0.98701,0.96962,0.99053,0.83626,0.34228,0.67744,0.25083,0.88958,0.00100208,0.00100208,0.00100208

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

      @expen6ve thank you for sharing your training details. For improved segmentation results with YOLO26, consider these adjustments:

      1. Dataset Size: 1.3k images may be insufficient for robust segmentation. Aim for ≥5k high-quality annotated images.
      2. Augmentation Tuning: Reduce rotation range (try ±5°) and remove noise augmentation, which can degrade mask precision.
      3. Hyperparameters: Increase imgsz to 640 (standard for segmentation tasks) and lower learning rate to 0.0001 with cosine scheduler.
      4. Model Selection: Try YOLO26s-seg instead of medium-sized models for better generalization on limited data.

      For detailed guidance, see the Segmentation Training Tips in our documentation.

  9. ShreyasChhetriGitHub

    Hi can we implement a Reinforcement Learning function up above the Yolo training function for more accuracy can it happen ?

    1. Glenn JocherUltralytics

      @ShreyasChhetri integrating reinforcement learning (RL) with YOLO training is an interesting idea, but YOLO models are not inherently designed for RL workflows. While it is theoretically possible, it would require substantial custom development outside the scope of the provided Ultralytics framework. You might consider exploring hybrid approaches combining RL and computer vision if your use case demands it. For standard training, refer to the existing YOLO training documentation: https://docs.ultralytics.com/modes/train.

  10. ZhangAiyiGitHub

    I have a question when run the code for Instance Segmentation with Object Tracking. The pycharm said UnicodeEncodeError: 'gbk' codec can't encode character '\u274c' in position 401: illegal multibyte sequence. Does anyone have the similar question? Thank you.

    1. Glenn JocherUltralytics

      @ZhangAiyi it seems like you're encountering a Unicode encoding issue. You can try setting your environment's encoding to UTF-8 in PyCharm to resolve this. If the problem persists, please check the PyCharm settings or your system's locale configuration.