File size: 1,456 Bytes
4bfd00b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

# Example script for using the yolov8_l model from Hugging Face
import torch
import cv2
import numpy as np
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForObjectDetection

# Load model and processor
model = AutoModelForObjectDetection.from_pretrained("lkk688/yolov8l-model")
processor = AutoImageProcessor.from_pretrained("lkk688/yolov8l-model")

# Function to run inference on an image
def detect_objects(image_path, confidence_threshold=0.25):
    # Load image
    image = Image.open(image_path).convert("RGB")
    
    # Process image
    inputs = processor(images=image, return_tensors="pt")
    
    # Run inference
    with torch.no_grad():
        outputs = model(**inputs)
    
    # Post-process outputs
    target_sizes = torch.tensor([image.size[::-1]])
    results = processor.post_process_object_detection(
        outputs, 
        threshold=confidence_threshold,
        target_sizes=target_sizes
    )[0]
    
    # Print results
    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

# Example usage
if __name__ == "__main__":
    # Replace with your image path
    image_path = "path/to/your/image.jpg"
    detect_objects(image_path)