قصّ العناصر باستخدام Ultralytics YOLO26
ما المقصود بقصّ العناصر؟#
يتضمن قص الكائنات باستخدام Ultralytics YOLO26 عزل كائنات مكتشفة محددة واستخراجها من صورة أو فيديو. يحدد YOLO26 موقع كل كائن باستخدام صندوق إحاطة، ويحفظ أداة القص تلك المنطقة كصورة منفصلة لمزيد من التحليل أو المعالجة.
شاهد: اقتصاص الكائنات باستخدام Ultralytics YOLO
مزايا قصّ العناصر#
- تحليل مركّز: يتيح YOLO26 قص كائنات محددة، ما يسمح بفحص العناصر الفردية داخل المشهد أو معالجتها بعمق.
- تقليل حجم البيانات: من خلال استخراج الكائنات ذات الصلة فقط، يقلل قص الكائنات حجم البيانات، ما يجعل التخزين والنقل والمهام الحاسوبية اللاحقة أكثر كفاءة.
- دقة محسّنة: تؤدي دقة اكتشاف الكائنات في YOLO26 إلى قص دقيق يحافظ على التفاصيل المرئية اللازمة لمزيد من التحليل.
المرئيات#
| أمتعة المطار |
|---|
![]() |
| قصّ حقائب السفر على سير ناقل في المطار باستخدام Ultralytics YOLO26 |
قصّ العناصر باستخدام YOLO26#
مرّر مقطع الفيديو إلى حل ObjectCropper، وسيكتشف العناصر في كل إطار ويحفظ كل عملية كشف في صورة منفصلة. قصّر القصّ على classes محددة، وارفع conf للاحتفاظ بعمليات الكشف عالية الثقة فقط، وحدد crop_dir لاختيار مكان حفظ الصور المقصوصة.
# 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:
| المعامل | النوع | الافتراضي | الوصف |
|---|---|---|---|
model | str | None | مسار ملف نموذج Ultralytics YOLO. |
crop_dir | str | 'cropped-detections' | اسم الدليل الذي تُحفظ فيه الاكتشافات المقصوصة. |
verbose | bool | True | يفعّل سجل الحل لكل إطار، ويشمل شكل المدخل وعدد الفئات وسرعة المعالجة. يظل استدعاء التتبع نفسه صامتًا دائمًا. |
يشغّل ObjectCropper predict بدلًا من track، لذا فهو يدعم معلمات الاستدلال التالية باستثناء tracker:
| المعامل | النوع | الافتراضي | الوصف |
|---|---|---|---|
tracker | str | 'tracktrack.yaml' | يحدد خوارزمية التتبع المطلوب استخدامها. الخيارات المضمنة: botsort.yaml، bytetrack.yaml، ocsort.yaml، deepocsort.yaml، fasttrack.yaml، tracktrack.yaml. |
conf | float | 0.25 | يضبط عتبة الثقة للكشوفات؛ إذ تسمح القيم الأقل بتتبع مزيد من الكائنات، لكنها قد تتضمن إيجابيات كاذبة. |
iou | float | 0.5 | يضبط عتبة التقاطع على الاتحاد (IoU) لتصفية الكشوفات المتداخلة. |
classes | list | None | يصفّي النتائج حسب فهرس الفئة. على سبيل المثال، لا يتتبع classes=[0, 2, 3] إلا الفئات المحددة. |
device | str | None | يحدد الجهاز المستخدم للاستدلال (مثل cpu أو cuda:0 أو 0). ويتيح للمستخدمين الاختيار بين CPU أو GPU محددة أو أجهزة حوسبة أخرى لتنفيذ النموذج. |
imgsz | int or tuple | 640 | حجم صورة الاستدلال المستهدف: عدد صحيح لصورة مربعة، أو زوج (height, width). تُعدّل الأبعاد وفقًا لخطوة النموذج. |
max_det | int | 300 | الحد الأقصى لعدد الكشوفات التي يُحتفظ بها لكل إطار قبل التتبع، ما يحد من عدد الكائنات التي يعالجها الحل في المشاهد الكثيفة. |
quantize | int or str | None | دقة الاستدلال: 16 (FP16) أو 32/unset (FP32) لنماذج PyTorch وTorchScript خارج CPU؛ أما التنسيقات الأخرى فتستخدم الدقة التي يحددها الملف الاصطناعي وبيئة التشغيل. يحل هذا الوسيط محل الوسيطة half المهملة. |
الأسئلة الشائعة#
يتضمن قص الكائنات باستخدام Ultralytics YOLO26 عزل كائنات محددة واستخراجها من صورة أو فيديو بالاستناد إلى قدرات YOLO26 على الاكتشاف. تتيح هذه العملية إجراء تحليل مركّز وتقليل حجم البيانات، إذ يستخدم YOLO26 لتحديد الكائنات بدقة ثم قصّها وفقًا لذلك.
يجمع Ultralytics YOLO26 بين دقة الاكتشاف وسرعة الاستدلال وبساطة API، لذا لا يتطلب القص سوى بضعة أسطر من التعليمات البرمجية، ويدعم التحليل المركّز. كما يتيح YOLO26 التصدير إلى تنسيقات مثل OpenVINO وTensorRT للنشر في الزمن الحقيقي على أجهزة متنوعة.
باستخدام Ultralytics YOLO26 لقص الكائنات ذات الصلة فقط من صورك أو مقاطع الفيديو، يمكنك تقليل حجم البيانات بشكل ملحوظ، ما يجعل التخزين والمعالجة أكثر كفاءة. استخدم نموذجًا مدرّبًا مسبقًا، أو درّب نموذجًا لاكتشاف الكائنات التي تحتاج إليها، ثم قص تلك المناطق وحدها واحفظها.
تم تحسين Ultralytics YOLO26 للعمل على كل من CPU وGPU، لكن يُوصى باستخدام GPU مخصص (مثل NVIDIA RTX أو GPU لمركز بيانات) لتحقيق الأداء الأمثل، ولا سيما للاستدلال الآني أو عالي الحجم. أما النشر على الأجهزة خفيفة الوزن، فيمكن استخدام CoreML لنظام iOS أو LiteRT لنظام Android.
التعليقات15
اطرح سؤالًا، وشارك نتائجك، أو ساعد شخصًا آخر.
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(تم التعديل)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(تم التعديل)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(تم التعديل)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(تم التعديل)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(تم التعديل)@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
