|
|
|
|
|
import torch |
|
import cv2 |
|
import numpy as np |
|
from PIL import Image |
|
from transformers import AutoImageProcessor, AutoModelForObjectDetection |
|
|
|
|
|
model = AutoModelForObjectDetection.from_pretrained("lkk688/yolov8l-model") |
|
processor = AutoImageProcessor.from_pretrained("lkk688/yolov8l-model") |
|
|
|
|
|
def detect_objects(image_path, confidence_threshold=0.25): |
|
|
|
image = Image.open(image_path).convert("RGB") |
|
|
|
|
|
inputs = processor(images=image, return_tensors="pt") |
|
|
|
|
|
with torch.no_grad(): |
|
outputs = model(**inputs) |
|
|
|
|
|
target_sizes = torch.tensor([image.size[::-1]]) |
|
results = processor.post_process_object_detection( |
|
outputs, |
|
threshold=confidence_threshold, |
|
target_sizes=target_sizes |
|
)[0] |
|
|
|
|
|
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): |
|
box = [round(i, 2) for i in box.tolist()] |
|
print( |
|
f"Detected {model.config.id2label[label.item()]} with confidence " |
|
f"{round(score.item(), 3)} at location {box}" |
|
) |
|
|
|
return results |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
image_path = "path/to/your/image.jpg" |
|
detect_objects(image_path) |
|
|