Views
No views yet
1import cv2
2import torch
3import torchvision.transforms as transforms
4from transformers import AutoModelForImageClassification
5from PIL import Image
6
7# Load the saved model and tokenizer
8model = AutoModelForImageClassification.from_pretrained("jazzmacedo/fruits-and-vegetables-detector-36")
9
10# Get the list of labels from the model's configuration
11labels = list(model.config.id2label.values())
12
13# Define the preprocessing transformation
14preprocess = transforms.Compose([
15 transforms.Resize((224, 224)),
16 transforms.ToTensor(),
17 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
18])
19
20image_path = "path/to/your/image.jpg"
21image = cv2.imread(image_path)
22image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
23pil_image = Image.fromarray(image) # Convert NumPy array to PIL image
24input_tensor = preprocess(pil_image).unsqueeze(0)
25
26# Run the image through the model
27outputs = model(input_tensor)
28
29# Get the predicted label index
30predicted_idx = torch.argmax(outputs.logits, dim=1).item()
31
32# Get the predicted label text
33predicted_label = labels[predicted_idx]
34
35# Print the predicted label
36print("Detected label:", predicted_label)