Recorte de objetos con Ultralytics YOLO26
¿Qué es el recorte de objetos?#
El recorte de objetos con Ultralytics YOLO26 consiste en aislar y extraer objetos detectados específicos de una imagen o un vídeo. YOLO26 localiza cada objeto mediante un cuadro delimitador, y la herramienta de recorte guarda esa región como una imagen independiente para analizarla o procesarla posteriormente.
Ver: Recorte de objetos con Ultralytics YOLO
Ventajas del recorte de objetos#
- Análisis específico: YOLO26 permite recortar objetos concretos para examinar o procesar en profundidad elementos individuales de una escena.
- Menor volumen de datos: Al extraer solo los objetos relevantes, el recorte de objetos reduce el tamaño de los datos y hace más eficientes el almacenamiento, la transmisión y las tareas de cálculo posteriores.
- Mayor precisión: La precisión de la detección de objetos de YOLO26 produce recortes ajustados que conservan los detalles visuales necesarios para el análisis posterior.
Elementos visuales#
| Equipaje en el aeropuerto |
|---|
![]() |
| Recorte de maletas en la cinta transportadora de un aeropuerto con Ultralytics YOLO26 |
Recorta objetos con YOLO26#
Pasa tu vídeo a la solución ObjectCropper: detectará objetos en cada fotograma y guardará cada detección como una imagen independiente. Limita el recorte a clases específicas con classes, aumenta conf para conservar solo las detecciones con suficiente confianza y establece crop_dir para elegir dónde se guardan los recortes.
# 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]"Argumentos de ObjectCropper#
Aquí tienes una tabla con los argumentos de ObjectCropper:
| Argumento | Tipo | Predeterminado | Descripción |
|---|---|---|---|
model | str | None | Ruta a un archivo de modelo Ultralytics YOLO. |
crop_dir | str | 'cropped-detections' | Nombre del directorio donde se guardan las detecciones recortadas. |
verbose | bool | True | Activa el registro por fotograma de la forma de entrada, los recuentos por clase y la velocidad de procesamiento de la solución. La llamada de seguimiento en sí siempre es silenciosa. |
ObjectCropper ejecuta predict en lugar de track, por lo que admite los siguientes parámetros de inferencia, excepto tracker:
| Argumento | Tipo | Predeterminado | Descripción |
|---|---|---|---|
tracker | str | 'tracktrack.yaml' | Especifica el algoritmo de seguimiento que se va a usar. Opciones integradas: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml. |
conf | float | 0.25 | Establece el umbral de confianza de las detecciones; los valores más bajos permiten seguir más objetos, pero pueden incluir falsos positivos. |
iou | float | 0.5 | Establece el umbral de intersección sobre unión (IoU) para filtrar las detecciones solapadas. |
classes | list | None | Filtra los resultados por índice de clase. Por ejemplo, classes=[0, 2, 3] solo sigue las clases especificadas. |
device | str | None | Especifica el dispositivo para la inferencia (p. ej., cpu, cuda:0 o 0). Permite elegir entre CPU, una GPU concreta u otros dispositivos de cálculo para ejecutar el modelo. |
imgsz | int or tuple | 640 | Tamaño de imagen de destino para la inferencia: un entero para una imagen cuadrada o una pareja (height, width). Las dimensiones se ajustan al stride del modelo. |
max_det | int | 300 | Número máximo de detecciones que se conservan por fotograma antes del seguimiento, lo que limita los objetos que procesa una solución en escenas densas. |
quantize | int or str | None | Precisión de inferencia: 16 (FP16) o 32/unset (FP32) para los modelos PyTorch y TorchScript fuera de CPU; los demás formatos usan la precisión que seleccionen el artefacto y el entorno de ejecución. Sustituye al argumento obsoleto half. |
Preguntas frecuentes#
El recorte de objetos con Ultralytics YOLO26 consiste en aislar y extraer objetos concretos de una imagen o un vídeo a partir de las capacidades de detección de YOLO26. Este proceso permite centrar el análisis y reducir el volumen de datos: YOLO26 identifica los objetos con precisión y los recorta según corresponda.
Ultralytics YOLO26 combina una detección precisa, una inferencia rápida y una API sencilla, por lo que recortar objetos requiere solo unas pocas líneas de código y permite realizar un análisis focalizado. YOLO26 también se exporta a formatos como OpenVINO y TensorRT para su implementación en tiempo real en distintos tipos de hardware.
Al usar Ultralytics YOLO26 para recortar solo los objetos relevantes de tus imágenes o vídeos, puedes reducir considerablemente el tamaño de los datos y mejorar la eficiencia del almacenamiento y el procesamiento. Usa un modelo preentrenado o entrena uno para detectar los objetos que necesitas y, después, recorta y guarda solo esas regiones.
Sí, Ultralytics YOLO26 puede procesar secuencias de vídeo en tiempo real para detectar y recortar objetos de forma dinámica. Su rápida inferencia es adecuada para aplicaciones en tiempo real como la videovigilancia, el análisis deportivo y los sistemas de inspección automatizados.
Ultralytics YOLO26 está optimizado para entornos con CPU y GPU, pero se recomienda una GPU dedicada —por ejemplo, una NVIDIA RTX o una GPU de centro de datos— para obtener un rendimiento óptimo, especialmente en inferencias en tiempo real o de gran volumen. Para la implementación en dispositivos ligeros, considera usar CoreML en iOS o LiteRT en Android.
Comentarios15
Haz una pregunta, comparte tus resultados o ayuda a otra persona.
NOSPAA21
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?
RizwanMunawar
@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.
AdityaJaiswal99
Can we make the model, so it does not take the same pictures in the frame again?
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
iouthreshold 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
iouparameter 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!
AdityaJaiswal99
How can we change the frame height and width to a specific pixel and change FPS?
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.VideoCaptureandcv2.VideoWriterobjects. 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
HsnKmlMt
Hi! How can i specify classed to be cropped like for my case i just want people.
Glenn JocherUltralytics(editado)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
classesargument ofpredict: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.namesis a dictionary mapping class IDs to names, so to look up an ID by name usenext(k for k, v in model.names.items() if v == "person"). Adjust according to your specific classes and needs! 👍HsnKmlMt
Thank you, I really appreciate it!
Glenn JocherUltralytics(editado)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! 🚀
1umairrkhn
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'
Glenn JocherUltralytics(editado)Hey there!
It looks like you're trying to use the
.index()method on a dictionary, which isn't supported.model.namesis 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. 😊
Glenn JocherUltralytics(editado)Hey there! It looks like you're trying to use the
index()method on a dictionary, which isn't supported.model.namesis 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! 😊
zakirh
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}")
Glenn JocherUltralytics(editado)@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.namesis 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
