image_specifier / app.py
sharjjel67's picture
Update app.py
6e99a18
Raw
History Blame Contribute Delete
2.21 kB
import os
import torch
import streamlit as st
from PIL import Image
from torchvision import transforms
torch.hub.download_url_to_file("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")
model = torch.hub.load('pytorch/vision:v0.9.0', 'densenet121', pretrained=True)
model.eval()
# Download ImageNet labels
os.system("wget https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt")
def inference(input_image):
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
input_tensor = preprocess(input_image)
input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model
# move the input and model to GPU for speed if available
if torch.cuda.is_available():
input_batch = input_batch.to('cuda')
model.to('cuda')
with torch.no_grad():
output = model(input_batch)
# Tensor of shape 1000, with confidence scores over Imagenet's 1000 classes
# The output has unnormalized scores. To get probabilities, you can run a softmax on it.
probabilities = torch.nn.functional.softmax(output[0], dim=0)
# Read the categories
with open("imagenet_classes.txt", "r") as f:
categories = [s.strip() for s in f.readlines()]
# Show top categories per image
top5_prob, top5_catid = torch.topk(probabilities, 5)
result = {}
for i in range(top5_prob.size(0)):
result[categories[top5_catid[i]]] = top5_prob[i].item()
return result
# Streamlit app
st.title("DenseNet Image Classification Demo")
st.sidebar.title("Upload Image")
# File upload
uploaded_file = st.sidebar.file_uploader("Choose an image...", type="jpg")
if uploaded_file is not None:
# Display the uploaded image
st.image(uploaded_file, caption="Uploaded Image.", use_column_width=True)
# Inference
result = inference(Image.open(uploaded_file))
# Display results
st.subheader("Top Predictions:")
for category, confidence in result.items():
st.write(f"{category}: {confidence:.2%}")