|
|
import os |
|
|
import numpy as np |
|
|
from ultralytics import YOLO |
|
|
from PIL import Image |
|
|
import torch |
|
|
import yaml |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
MODEL_PATH = "best.pt" |
|
|
DATA_YAML = "data.yaml" |
|
|
IMG_SIZE = 512 |
|
|
IMG_PATH = "chroms.jpeg" |
|
|
USE_GPU = True |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if USE_GPU and torch.cuda.is_available(): |
|
|
torch.cuda.set_per_process_memory_fraction(0.5, device=0) |
|
|
else: |
|
|
torch.device('cpu') |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with open(DATA_YAML, "r") as f: |
|
|
data = yaml.safe_load(f) |
|
|
|
|
|
class_names = data["names"] |
|
|
num_classes = len(class_names) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model = YOLO(MODEL_PATH) |
|
|
print(f"Loaded model: {MODEL_PATH}") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
yolo_names = model.names |
|
|
|
|
|
|
|
|
mapping = {yolo_idx: int(name_str) for yolo_idx, name_str in yolo_names.items()} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
img = Image.open(IMG_PATH).convert('RGB') |
|
|
img = img.resize((IMG_SIZE, IMG_SIZE)) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
results = model.predict(source=img, imgsz=IMG_SIZE, verbose=False) |
|
|
probs = results[0].probs.data.cpu().numpy() |
|
|
|
|
|
|
|
|
|
|
|
top5_yolo_idx = np.argsort(probs)[-5:][::-1] |
|
|
top5_probs = probs[top5_yolo_idx] * 100 |
|
|
|
|
|
print("\nπ£ Top-5 Predictions:") |
|
|
for rank, yolo_idx in enumerate(top5_yolo_idx, 1): |
|
|
species_idx = mapping[yolo_idx] |
|
|
species_name = class_names[species_idx] |
|
|
print(f"{rank}. {species_name} β {top5_probs[rank-1]:.2f}%") |
|
|
|
|
|
|