File size: 1,485 Bytes
9f320da 5cf4eea d97b868 9f320da db29817 fadf2ad db29817 fadf2ad d97b868 9f320da d97b868 9f320da d97b868 5cf4eea 9f320da db29817 5cf4eea 9f320da 53b38ec 9f320da 5cf4eea 9f320da |
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 |
import gradio as gr
import torch
from torch import nn
from torchvision import models, transforms
from PIL import Image
# Load the ResNet50 model
model = models.resnet50(pretrained=False) # Don't load pre-trained weights here
model.fc = nn.Linear(model.fc.in_features, 11) # Adjust the output layer to match your number of classes
# Load the saved model weights (food_classification_model.pth)
model.load_state_dict(torch.load('food_classification_model.pth')) # Load from the local file
model.eval() # Set the model to evaluation mode
# Define the same preprocessing used during training
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# Define the prediction function
def classify_image(img):
# Preprocess the image
img = transform(img).unsqueeze(0) # Add batch dimension
# Make prediction
with torch.no_grad():
outputs = model(img)
probs = torch.softmax(outputs, dim=-1)
# Get the label with the highest probability
top_label = probs.argmax().item() # Get the index of the highest probability
return top_label
# Create the Gradio interface
iface = gr.Interface(
fn=classify_image,
inputs=gr.Image(type="pil"),
outputs="text",
title="Food Image Classification",
description="Upload an image to classify if it’s an apple pie, etc."
)
# Launch the app
iface.launch()
|