# Apply YOLO object detection algorithm for real world problem

# Install required packages
# !pip install ultralytics opencv-python matplotlib --quiet

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

model = YOLO("yolov8n.pt")

img_path = '/content/yoloimg.png'

if not os.path.isfile(img_path):
    raise FileNotFoundError(f"Image not found at {img_path}. Please upload the image to Colab.")

results = model(img_path, verbose=False)

img = cv2.imread(img_path)
if img is None:
    raise ValueError(f"Failed to load image at {img_path}. Check the file path or format.")

for r in results:
    for box in r.boxes:
        x1, y1, x2, y2 = map(int, box.xyxy[0])
        conf = float(box.conf[0])
        cls_id = int(box.cls[0])
        label = f"{r.names[cls_id]} {conf:.2f}"

        cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)

        (w, h), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)
        cv2.rectangle(img, (x1, y1 - 20), (x1 + w, y1), (0, 255, 0), -1)

        cv2.putText(img, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2)

output_path = '/content/annotated_OIP.jpeg'
cv2.imwrite(output_path, img)
print(f"Annotated image saved to {output_path}")

plt.figure(figsize=(12, 8))
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.title('YOLO Object Detection Results')
plt.show()

