import cv2
from ultralytics import YOLO
import matplotlib.pyplot as plt

# Load YOLOv8 model
model = YOLO('yolo11x.pt') 

def detect_multiple_objects_yolov8(image_path, confidence_threshold=0.04):
    # Load the image
    image = cv2.imread(image_path)
    
    # Run object detection
    results = model(image)
    
    # List to store detected objects
    detected_objects = []
    
    # Extract detections
    for result in results[0].boxes:
        confidence = result.conf[0].item()  # confidence score
        if confidence >= confidence_threshold:  # Apply confidence threshold
            x1, y1, x2, y2 = map(int, result.xyxy[0])  # bounding box coordinates
            class_id = int(result.cls[0].item())       # class ID
            class_name = model.names[class_id]         # get class name
            
            # Append class name to the list of detected objects
            detected_objects.append((class_name, confidence))
            
            # Draw bounding box and label on image
            label = f"{class_name} {confidence:.2f}"
            cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)

    # Show the annotated image
    plt.figure(figsize=(10, 8))
    plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    plt.axis("off")
    plt.show()
    
    # Print list of detected objects
    print("Detected objects:")
    for obj, conf in detected_objects:
        print(f"{obj}: {conf:.2f}")

# Run detection with a lower confidence threshold
image_path = 'lost_and_found.jpg'
detect_multiple_objects_yolov8(image_path, confidence_threshold=0.2)
