import cv2
from ultralytics import YOLO

# Load YOLO model
model = YOLO("yolov8m.pt")

# Read an image (change the path as needed)
img = cv2.imread("test.jpg")
if img is None:
    print("Error: Cannot read image."); exit()

all_detected = set()

# Run detection
for r in model(img, stream=True):
    for box in r.boxes:
        cls, conf = int(box.cls[0]), float(box.conf[0])
        x1, y1, x2, y2 = map(int, box.xyxy[0])
        name = model.names[cls]
        all_detected.add(name)
        cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
        cv2.putText(img, f"{name} {conf:.2f}", (x1, y1 - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

# Show result
cv2.imshow("YOLOv8 Image Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

print("\nDetected objects:", ", ".join(sorted(all_detected)) or "None")
