Erste Schritte

Objekte ausschneiden mit Ultralytics YOLO26

Was bedeutet das Ausschneiden von Objekten?#

Beim Ausschneiden von Objekten mit Ultralytics YOLO26 werden bestimmte erkannte Objekte aus einem Bild oder Video isoliert und extrahiert. YOLO26 lokalisiert jedes Objekt mit einer Begrenzungsbox. Das Ausschneidewerkzeug speichert den jeweiligen Bereich als separates Bild zur weiteren Analyse oder Verarbeitung.



Ansehen: Objekte mit Ultralytics YOLO zuschneiden

Vorteile des Ausschneidens von Objekten#

  • Gezielte Analyse: Mit YOLO26 kannst du gezielt Objekte ausschneiden und einzelne Elemente in einer Szene eingehend untersuchen oder verarbeiten.
  • Weniger Datenvolumen: Beim Ausschneiden von Objekten werden nur relevante Objekte extrahiert. Dadurch sinkt die Datenmenge und Speicherung, Übertragung sowie nachfolgende Berechnungen werden effizienter.
  • Höhere Präzision: Die Objekterkennung von YOLO26 liefert eine hohe Genauigkeit und erzeugt präzise Ausschnitte, die die für weitere Analysen erforderlichen visuellen Details bewahren.

Visualisierungen#

Flughafengepäck
Koffer auf dem Flughafen-Förderband, ausgeschnitten mit Ultralytics YOLO26
Koffer auf einem Flughafen-Förderband, ausgeschnitten mit Ultralytics YOLO26

Objekte mit YOLO26 ausschneiden#

Übergib dein Video an die Lösung ObjectCropper. Sie erkennt in jedem Frame Objekte und speichert jede Erkennung als separates Bild. Beschränke das Ausschneiden auf bestimmte classes, erhöhe conf, damit nur Erkennungen mit hoher Konfidenz beibehalten werden, und lege mit crop_dir fest, wo die Ausschnitte gespeichert werden.

Objekte ausschneiden mit 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]"

Argumente für ObjectCropper#

Hier ist eine Tabelle mit den Argumenten für ObjectCropper:

ArgumentTypStandardBeschreibung
modelstrNonePfad zu einer Ultralytics-YOLO-Modelldatei.
crop_dirstr'cropped-detections'Verzeichnisname zum Speichern zugeschnittener Erkennungen.
verboseboolTrueAktiviert das Protokoll der Lösung für jedes Bild, das Eingabeform, Klassenanzahlen und Verarbeitungsgeschwindigkeit enthält. Der Tracking-Aufruf selbst gibt grundsätzlich keine Meldungen aus.

ObjectCropper führt predict statt track aus und unterstützt daher die folgenden Inferenzparameter, außer tracker:

ArgumentTypStandardBeschreibung
trackerstr'tracktrack.yaml'Legt den zu verwendenden Verfolgungsalgorithmus fest. Integrierte Optionen: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml.
conffloat0.25Legt den Konfidenzschwellenwert für Erkennungen fest. Niedrigere Werte ermöglichen die Verfolgung weiterer Objekte, können aber auch falsch positive Ergebnisse einschließen.
ioufloat0.5Legt den Schwellenwert für die Schnittmenge über Vereinigung (IoU) fest, um überlappende Erkennungen herauszufiltern.
classeslistNoneFiltert die Ergebnisse nach Klassenindex. Beispielsweise verfolgt classes=[0, 2, 3] nur die angegebenen Klassen.
devicestrNoneLegt das Gerät für die Inferenz fest (z. B. cpu, cuda:0 oder 0). So kannst du für die Modellausführung zwischen CPU, einer bestimmten GPU oder anderen Rechengeräten wählen.
imgszint or tuple640Zielbildgröße für die Inferenz: eine Ganzzahl für ein quadratisches Bild oder ein (height, width)-Paar. Die Formen werden an den Modellschritt angepasst.
max_detint300Maximale Anzahl der Erkennungen, die pro Bild vor der Verfolgung beibehalten werden. Dadurch wird die Anzahl der Objekte begrenzt, die eine Lösung in dichten Szenen verarbeitet.
quantizeint or strNoneInferenzpräzision: 16 (FP16) oder 32/unset (FP32) für PyTorch- und TorchScript-Modelle außerhalb der CPU; andere Formate verwenden die Präzision, die ihr Artefakt und ihre Laufzeitumgebung vorgeben. Ersetzt das veraltete Argument half.

Häufig gestellte Fragen#

  • Beim Zuschneiden von Objekten mit Ultralytics YOLO26 werden anhand der Erkennungsfunktionen von YOLO26 bestimmte Objekte aus einem Bild oder Video isoliert und extrahiert. So kannst du gezielte Analysen durchführen und das Datenvolumen verringern, indem YOLO26 Objekte präzise erkennt und entsprechend zuschneidet.

  • Ultralytics YOLO26 kombiniert präzise Erkennung, schnelle Inferenz und eine einfache API. Dadurch reichen zum Zuschneiden wenige Codezeilen aus, und eine gezielte Analyse wird unterstützt. YOLO26 lässt sich außerdem in Formate wie OpenVINO und TensorRT exportieren, um Echtzeitbereitstellungen auf verschiedenen Hardwareplattformen zu ermöglichen.

  • Wenn du mit Ultralytics YOLO26 nur relevante Objekte aus deinen Bildern oder Videos ausschneidest, kannst du die Datenmenge deutlich reduzieren und die Speicherung und Verarbeitung effizienter gestalten. Verwende ein vortrainiertes Modell oder trainiere ein Modell, um die benötigten Objekte zu erkennen, und schneide dann nur diese Bereiche aus und speichere sie.

  • Ja, Ultralytics YOLO26 kann Videostreams in Echtzeit verarbeiten, um Objekte dynamisch zu erkennen und zuzuschneiden. Dank der schnellen Inferenz eignet sich das Modell für Echtzeitanwendungen wie die Videoüberwachung, Sportanalysen und automatisierte Prüfsysteme.

  • Ultralytics YOLO26 ist sowohl für CPU- als auch für GPU-Umgebungen optimiert. Für optimale Leistung, insbesondere bei Echtzeit- oder umfangreicher Inferenz, wird jedoch eine dedizierte GPU empfohlen, zum Beispiel eine NVIDIA RTX oder eine GPU für Rechenzentren. Für die Bereitstellung auf leichten Geräten kannst du CoreML für iOS oder LiteRT für Android verwenden.

Kommentare15

Stell eine Frage, teile deine Ergebnisse oder hilf jemand anderem.

  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
  2. HsnKmlMtGitHub

    Hi! How can i specify classed to be cropped like for my case i just want people.

    1. Glenn JocherUltralytics(bearbeitet)

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

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

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

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

      @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