开始使用

使用 Ultralytics YOLO26 裁剪目标

什么是目标裁剪?#

使用 Ultralytics YOLO26裁剪对象,是指从图像或视频中分离并提取特定的检测对象。YOLO26 使用边界框定位每个对象,裁剪器会将该区域另存为单独的图像,以供进一步分析或处理。



观看: 使用 Ultralytics YOLO 裁剪目标

目标裁剪的优势#

  • 聚焦分析:YOLO26 支持针对性地裁剪对象,让你能够深入检查或处理场景中的单个项目。
  • 减少数据量:对象裁剪只提取相关对象,从而减小数据量,让存储、传输和后续计算任务更高效。
  • 提升精度:YOLO26 的目标检测准确率能够生成紧致裁剪区域,保留进一步分析所需的视觉细节。

可视化效果#

机场行李
使用 Ultralytics YOLO26 裁剪机场传送带上的行李箱
使用 Ultralytics YOLO26 裁剪机场传送带上的行李箱

使用 YOLO26 裁剪目标#

将视频传入 ObjectCropper 解决方案后,它会逐帧检测目标,并将每个检测结果保存为单独的图像。将裁剪范围限制为特定的 classes,调高 conf 以仅保留置信度高的检测结果,并设置 crop_dir 以选择裁剪图像的保存位置。

使用 Ultralytics YOLO 裁剪目标
# Crop the objects
yolo solutions crop

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

# Crop specific classes
yolo solutions crop classes="[0, 2]"

ObjectCropper 参数#

下面是 ObjectCropper 参数表:

参数类型默认值说明
modelstrNoneUltralytics YOLO 模型文件的路径。
crop_dirstr'cropped-detections'用于存储裁剪后检测结果的目录名称。
verboseboolTrue启用逐帧日志,记录输入形状、类别计数和处理速度。跟踪调用本身始终不会输出日志。

ObjectCropper 运行的是 predict,而不是 track,因此支持以下推理参数,但 tracker 除外:

参数类型默认值说明
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) 对。图像尺寸会调整为模型步幅的整数倍。
max_detint300跟踪前每帧保留的最大检测数量,用于限制解决方案在密集场景中处理的物体数量。
quantizeint or strNone推理精度:对于非 CPU 上运行的 PyTorch 和 TorchScript 模型,使用 16 (FP16) 或 32/unset (FP32) 进行选择;其他格式使用其模型文件和运行时所选的精度。此参数替代已弃用的 half 参数。

常见问题#

  • 使用 Ultralytics YOLO26裁剪目标,是指根据 YOLO26 的检测能力,从图像或视频中分离并提取特定目标。这个过程利用 YOLO26 准确识别目标,再相应地裁剪目标,从而实现针对性分析并减少数据量。

  • Ultralytics YOLO26 结合了准确检测、快速推理和简洁的 API,因此只需几行代码即可完成裁剪,并支持针对性分析。YOLO26 还可导出为 OpenVINO 和 TensorRT 等格式,以便在多种硬件上进行实时部署。

  • 使用 Ultralytics YOLO26 仅裁剪图像或视频中的相关对象,可以显著减小数据量,让存储和处理更加高效。你可以使用预训练模型,或训练模型来检测所需对象,然后只裁剪并保存这些区域。

  • 可以,Ultralytics YOLO26 能够处理实时视频流,动态检测并裁剪目标。其快速推理适用于监控、体育分析和自动化检测系统等实时应用。

  • Ultralytics YOLO26 针对 CPU 和 GPU 环境进行了优化,但若要获得最佳性能,尤其是在实时或高吞吐量推理场景下,建议使用专用 GPU(例如 NVIDIA RTX 或数据中心 GPU)。如需部署到轻量级设备,iOS 可考虑使用 CoreML,Android 可考虑使用 LiteRT。

评论15

提出问题、分享结果,或帮助其他人。

  1. NOSPAA21GitHub

    Can i use it so as to train a model especially for printed circuit board defect detection to find defects in certain regions of a pcb?Would this be helpful?

    1. RizwanMunawarGitHub

      @NOSPAA21 Yes, you can train the Ultralytics YOLO11 model on the circuit board defect detection dataset by following the training documentation. Once the model is trained, you can use the object-cropping solution to crop the different defects that the model detects.

    1. Glenn JocherUltralytics

      @AdityaJaiswal99 thank you for your question! If you're looking to avoid capturing the same objects multiple times within a frame, you can leverage the Non-Maximum Suppression (NMS) feature of YOLOv8. NMS helps in eliminating redundant bounding boxes by keeping only the highest confidence detections and discarding others that overlap significantly.

      Here's a brief example of how you can adjust the iou threshold to refine your detections and reduce duplicates:

      from ultralytics import YOLO
      
      # Load the model
      model = YOLO("yolov8n.pt")
      
      # Set the IoU threshold to a lower value to reduce overlapping detections
      results = model.predict("path/to/your/image_or_video", iou=0.5)
      
      # Process the results as needed
      for result in results:
          boxes = result.boxes.xyxy.cpu().tolist()
          clss = result.boxes.cls.cpu().tolist()
          # Further processing...

      In this example, setting the iou parameter to a lower value (e.g., 0.5) helps in reducing the number of overlapping boxes, thus minimizing the chances of capturing the same object multiple times.

      For a more comprehensive guide on object cropping and additional tips, please visit our Object Cropping Guide.

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

      Happy coding!

    1. Paula DerrengerUltralytics

      @AdityaJaiswal99 hi there!

      To change the frame height, width, and FPS of a video using OpenCV, you can set these properties directly on the cv2.VideoCapture and cv2.VideoWriter objects. Below is an example of how you can achieve this:

      import cv2
      
      # Load the video
      cap = cv2.VideoCapture("path/to/video/file.mp4")
      assert cap.isOpened(), "Error reading video file"
      
      # Set the desired frame width, height, and FPS
      frame_width = 640  # Set your desired width
      frame_height = 480  # Set your desired height
      fps = 30  # Set your desired FPS
      
      # Create a VideoWriter object to save the modified video
      video_writer = cv2.VideoWriter("modified_video.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (frame_width, frame_height))
      
      while cap.isOpened():
          success, frame = cap.read()
          if not success:
              break
      
          # Resize the frame to the desired dimensions
          resized_frame = cv2.resize(frame, (frame_width, frame_height))
      
          # Write the resized frame to the output video
          video_writer.write(resized_frame)
      
          # Display the frame (optional)
          cv2.imshow("Resized Video", resized_frame)
          if cv2.waitKey(1) & 0xFF == ord("q"):
              break
      
      # Release resources
      cap.release()
      video_writer.release()
      cv2.destroyAllWindows()

      This script reads a video, resizes each frame to the specified width and height, and writes the modified frames to a new video file with the desired FPS.

      For more detailed information on object cropping using YOLOv8, you can refer to our Object Cropping Guide.

      Feel free to reach out if you have any more questions! 😊

      1
    1. Glenn JocherUltralytics(已编辑)

      Hello! To crop only people from your video, filter the detections by class. In COCO-trained models 'person' is class 0, so the simplest way is the classes argument of predict:

      import os
      
      import cv2
      
      from ultralytics import YOLO
      
      model = YOLO("yolo26n.pt")
      
      cap = cv2.VideoCapture("path/to/video/file.mp4")
      assert cap.isOpened(), "Error reading video file"
      
      crop_dir_name = "ultralytics_crop"
      os.makedirs(crop_dir_name, exist_ok=True)
      
      idx = 0
      while cap.isOpened():
          success, im0 = cap.read()
          if not success:
              break
      
          results = model.predict(im0, classes=[0])  # 0 = 'person' in COCO
          boxes = results[0].boxes.xyxy.cpu().tolist()
      
          for box in boxes:
              idx += 1
              crop_obj = im0[int(box[1]) : int(box[3]), int(box[0]) : int(box[2])]
              cv2.imwrite(os.path.join(crop_dir_name, f"person_{idx}.png"), crop_obj)
      
      cap.release()
      cv2.destroyAllWindows()

      This will crop and save images only for detected persons. Note that model.names is a dictionary mapping class IDs to names, so to look up an ID by name use next(k for k, v in model.names.items() if v == "person"). Adjust according to your specific classes and needs! 👍

    2. Glenn JocherUltralytics(已编辑)

      Hello! We're really glad you found the materials helpful! If you ever need to crop specific classes, such as 'people', filter the detections by class ID. Here's a quick example:

      import cv2
      
      from ultralytics import YOLO
      
      model = YOLO("yolo26n.pt")  # Load your model
      person_class_id = next(k for k, v in model.names.items() if v == "person")  # model.names maps class ID -> name
      
      cap = cv2.VideoCapture("path/to/video.mp4")
      assert cap.isOpened(), "Error reading video file"
      
      while cap.isOpened():
          ret, frame = cap.read()
          if not ret:
              break
          results = model.predict(frame, classes=[person_class_id])  # only 'person' detections
          boxes = results[0].boxes.xyxy.cpu().tolist()
      
          for idx, box in enumerate(boxes):
              x1, y1, x2, y2 = map(int, box[:4])
              crop_img = frame[y1:y2, x1:x2]
              cv2.imwrite(f"cropped_person_{idx}.jpg", crop_img)

      Feel free to replace 'person' with any class you're interested in, and make sure the class name matches what's defined in your model's class names. Let us know if you need further assistance! 🚀

      1
    3. umairrkhnGitHub

      Hey Glenn, I am getting this error using your implementation:

      person_class_id = model.names.index('person') # Ensure 'person' is in the model's class names ^^^^^^^^^^^^^^^^^ AttributeError: 'dict' object has no attribute 'index'

    4. Glenn JocherUltralytics(已编辑)

      Hey there!

      It looks like you're trying to use the .index() method on a dictionary, which isn't supported. model.names is a dictionary mapping class IDs to class names, not a list. Here's how to find the ID for a class name:

      model = YOLO("yolo26n.pt")
      person_class_id = next(k for k, v in model.names.items() if v == "person")

      For COCO-trained models this is simply 0. If the issue persists, could you share more of your code context? That might help diagnose the issue better. 😊

    5. Glenn JocherUltralytics(已编辑)

      Hey there! It looks like you're trying to use the index() method on a dictionary, which isn't supported. model.names is a dictionary mapping class IDs to class names, so you need to look up the ID by name:

      person_class_id = next(k for k, v in model.names.items() if v == "person")

      Make sure that 'person' is indeed the name of the class you're interested in. Let me know if this helps or if you need further assistance! 😊

    6. zakirhGitHub

      To those who are facing issue on finding person class:

      person_class_id = None for class_id, class_name in model.names.items(): if class_name =='person': person_class_id = class_id break

      if person_class_id is None: print("The 'person' class was not found.") else: print(f"'person' class ID: {person_class_id}")

    7. Glenn JocherUltralytics(已编辑)

      @zakirh thank you for sharing this helpful approach to finding the class ID for 'person.' For others who might encounter similar issues, note that model.names is a dictionary mapping class IDs to class names, so finding an ID by name requires searching the values. If any further clarification is needed, feel free to ask!

      1