0%
YOLOv8: دليل شامل لاكتشاف الكائنات

YOLOv8: دليل شامل لاكتشاف الكائنات

تعرّف على كيفية استخدام YOLOv8 لاكتشاف الكائنات في الوقت الفعلي من خلال أمثلة عملية.

I

InSkillCoach

· دقيقة

YOLOv8: دليل شامل لاكتشاف الكائنات

YOLOv8 هو أحدث إصدار من خوارزمية YOLO (You Only Look Once)، طورته شركة Ultralytics. ويقدّم أداءً محسّنًا وواجهة برمجية (API) أكثر سهولة وبداهة.

1. التثبيت والإعداد

# Installation des dépendances
pip install ultralytics opencv-python numpy

# Import des bibliothèques nécessaires
from ultralytics import YOLO
import cv2
import numpy as np

2. النماذج المتاحة

2.1 تحميل النماذج

# Chargement des différents modèles
model_nano = YOLO('yolov8n.pt')  # Nano
model_small = YOLO('yolov8s.pt')  # Small
model_medium = YOLO('yolov8m.pt')  # Medium
model_large = YOLO('yolov8l.pt')  # Large
model_xlarge = YOLO('yolov8x.pt')  # XLarge

2.2 مقارنة النماذج

def compare_models():
    # Configuration de base
    test_image = "path/to/test/image.jpg"
    
    # Test des différents modèles
    models = {
        'nano': model_nano,
        'small': model_small,
        'medium': model_medium,
        'large': model_large,
        'xlarge': model_xlarge
    }
    
    results = {}
    for name, model in models.items():
        # Mesure du temps d'inférence
        start_time = time.time()
        results[name] = model(test_image)
        inference_time = time.time() - start_time
        
        print(f"Modèle {name}:")
        print(f"Temps d'inférence: {inference_time:.2f}s")
        print(f"Nombre de détections: {len(results[name][0].boxes)}")

3. اكتشاف الكائنات

3.1 الاكتشاف البسيط

def detect_objects(image_path):
    # Chargement du modèle
    model = YOLO('yolov8n.pt')
    
    # Détection
    results = model(image_path)
    
    # Traitement des résultats
    for result in results:
        boxes = result.boxes
        for box in boxes:
            # Coordonnées de la boîte
            x1, y1, x2, y2 = box.xyxy[0]
            x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
            
            # Confiance
            confidence = float(box.conf[0])
            
            # Classe
            class_id = int(box.cls[0])
            class_name = model.names[class_id]
            
            # Dessiner la boîte
            cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
            
            # Ajouter le texte
            label = f"{class_name} {confidence:.2f}"
            cv2.putText(image, label, (x1, y1 - 10),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
    
    return image

3.2 الاكتشاف في الوقت الفعلي

def real_time_detection():
    # Initialisation de la caméra
    cap = cv2.VideoCapture(0)
    
    # Chargement du modèle
    model = YOLO('yolov8n.pt')
    
    while cap.isOpened():
        success, frame = cap.read()
        if not success:
            continue
        
        # Détection
        results = model(frame)
        
        # Visualisation
        annotated_frame = results[0].plot()
        
        # Affichage
        cv2.imshow('YOLOv8 Detection', annotated_frame)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()

4. التجزئة (Segmentation)

4.1 تجزئة النسخ (Instance Segmentation)

def instance_segmentation():
    # Chargement du modèle de segmentation
    model = YOLO('yolov8n-seg.pt')
    
    # Segmentation
    results = model('path/to/image.jpg')
    
    # Visualisation
    for result in results:
        # Masques de segmentation
        masks = result.masks
        if masks is not None:
            for mask in masks:
                # Conversion du masque en image
                mask_array = mask.data.cpu().numpy()
                
                # Application du masque
                masked_image = cv2.bitwise_and(
                    image, image, mask=mask_array.astype(np.uint8)
                )
                
                # Affichage
                cv2.imshow('Segmentation', masked_image)

4.2 التجزئة في الوقت الفعلي

def real_time_segmentation():
    # Initialisation
    cap = cv2.VideoCapture(0)
    model = YOLO('yolov8n-seg.pt')
    
    while cap.isOpened():
        success, frame = cap.read()
        if not success:
            continue
        
        # Segmentation
        results = model(frame)
        
        # Visualisation
        annotated_frame = results[0].plot()
        
        # Affichage
        cv2.imshow('YOLOv8 Segmentation', annotated_frame)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()

5. التصنيف (Classification)

5.1 تصنيف الصور

def image_classification():
    # Chargement du modèle de classification
    model = YOLO('yolov8n-cls.pt')
    
    # Classification
    results = model('path/to/image.jpg')
    
    # Traitement des résultats
    for result in results:
        # Probabilités des classes
        probs = result.probs
        
        # Classe prédite
        predicted_class = probs.top1
        confidence = probs.top1conf
        
        print(f"Classe prédite: {model.names[predicted_class]}")
        print(f"Confiance: {confidence:.2f}")

5.2 التصنيف في الوقت الفعلي

def real_time_classification():
    # Initialisation
    cap = cv2.VideoCapture(0)
    model = YOLO('yolov8n-cls.pt')
    
    while cap.isOpened():
        success, frame = cap.read()
        if not success:
            continue
        
        # Classification
        results = model(frame)
        
        # Visualisation
        annotated_frame = results[0].plot()
        
        # Affichage
        cv2.imshow('YOLOv8 Classification', annotated_frame)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()

6. التدريب المخصص

6.1 إعداد البيانات

def prepare_training():
    # Configuration du dataset
    data_yaml = """
    path: dataset  # Chemin vers le dataset
    train: images/train  # Images d'entraînement
    val: images/val  # Images de validation
    
    # Classes
    names:
      0: person
      1: car
      2: truck
      # ... autres classes
    """
    
    # Sauvegarde de la configuration
    with open('data.yaml', 'w') as f:
        f.write(data_yaml)

6.2 تدريب النموذج

def train_model():
    # Chargement du modèle
    model = YOLO('yolov8n.pt')
    
    # Configuration de l'entraînement
    results = model.train(
        data='data.yaml',
        epochs=100,
        imgsz=640,
        batch=16,
        device='0',  # GPU
        workers=8,
        project='runs/train',
        name='exp'
    )

7. التحسين والنشر

7.1 تصدير النموذج

def export_model():
    # Chargement du modèle
    model = YOLO('yolov8n.pt')
    
    # Export dans différents formats
    model.export(format='onnx')  # ONNX
    model.export(format='engine')  # TensorRT
    model.export(format='coreml')  # CoreML
    model.export(format='tflite')  # TFLite

7.2 تحسين الأداء

def optimize_performance():
    # Configuration pour de meilleures performances
    model = YOLO('yolov8n.pt')
    
    # Optimisation des paramètres
    results = model.predict(
        source='0',  # Caméra
        conf=0.25,  # Seuil de confiance
        iou=0.45,  # Seuil IoU
        agnostic_nms=True,  # NMS agnostique aux classes
        max_det=300,  # Nombre maximum de détections
        half=True  # Utilisation de la précision FP16
    )

8. أفضل الممارسات

  1. اختيار النموذج

    • Nano للأجهزة المحمولة
    • Small/Medium للتطبيقات العامة
    • Large/XLarge لتحقيق أقصى دقة
  2. التحسين

    • استخدام دقة FP16 مع وحدات GPU
    • ضبط عتبات الثقة وIoU
    • تحسين حجم الدفعة (batch)
  3. النشر

    • التصدير بالصيغة المناسبة
    • استخدام التسريع العتادي
    • تنفيذ نظام للتخزين المؤقت (cache)

الخاتمة

النقاط الرئيسية:

  • أداء محسّن
  • واجهة برمجية (API) سهلة وبديهية
  • دعم متعدد المنصات
  • التصدير إلى صيغ مختلفة

التوصيات:

  • اختيار النموذج المناسب بحسب الاحتياجات
  • تحسين الأداء
  • استخدام التسريع العتادي
  • تنفيذ إدارة قوية للأخطاء
InSkillCoach

نبذة عن InSkillCoach

خبير في التدريب والتقنيات

مدرّب متخصص في التقنيات المتقدمة والذكاء الاصطناعي، تدعمه شركة GNeurone Inc.

الشهادات:

  • AWS Certified Solutions Architect – Professional
  • شهادات Google Cloud
  • Microsoft Certified: DevOps Engineer Expert
  • Certified Kubernetes Administrator (CKA)
  • CompTIA Security+
1.9k
167

التعليقات

التعليقات مدعومة عبر GitHub Discussions

سجّل الدخول باستخدام GitHub للمشاركة في النقاش

تم نسخ الرابط!