Spaces:
Build error
Build error
Commit ·
432a20d
1
Parent(s): c448a39
Add application file
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import torch
|
| 3 |
+
from torchvision import models, transforms
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import json
|
| 6 |
+
|
| 7 |
+
# Load pretrained ResNet50 model
|
| 8 |
+
model = models.resnet50(pretrained=True)
|
| 9 |
+
model.eval()
|
| 10 |
+
|
| 11 |
+
# Image preprocessing
|
| 12 |
+
def process_image(image):
|
| 13 |
+
transform = transforms.Compose([
|
| 14 |
+
transforms.Resize(256),
|
| 15 |
+
transforms.CenterCrop(224),
|
| 16 |
+
transforms.ToTensor(),
|
| 17 |
+
transforms.Normalize(
|
| 18 |
+
mean=[0.485, 0.456, 0.406],
|
| 19 |
+
std=[0.229, 0.224, 0.225]
|
| 20 |
+
)
|
| 21 |
+
])
|
| 22 |
+
return transform(image).unsqueeze(0)
|
| 23 |
+
|
| 24 |
+
# Load ImageNet class labels
|
| 25 |
+
with open('imagenet_classes.json', 'r') as f:
|
| 26 |
+
class_labels = json.load(f)
|
| 27 |
+
|
| 28 |
+
# Streamlit UI
|
| 29 |
+
st.title("Image Classification with ResNet50")
|
| 30 |
+
st.write("Upload an image and the model will classify it!")
|
| 31 |
+
|
| 32 |
+
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
|
| 33 |
+
|
| 34 |
+
if uploaded_file is not None:
|
| 35 |
+
# Display uploaded image
|
| 36 |
+
image = Image.open(uploaded_file).convert('RGB')
|
| 37 |
+
st.image(image, caption='Uploaded Image', use_container_width=True)
|
| 38 |
+
|
| 39 |
+
# Make prediction
|
| 40 |
+
input_tensor = process_image(image)
|
| 41 |
+
|
| 42 |
+
with torch.no_grad():
|
| 43 |
+
output = model(input_tensor)
|
| 44 |
+
probabilities = torch.nn.functional.softmax(output[0], dim=0)
|
| 45 |
+
|
| 46 |
+
# Get top 5 predictions
|
| 47 |
+
top5_prob, top5_idx = torch.topk(probabilities, 5)
|
| 48 |
+
|
| 49 |
+
# Display results
|
| 50 |
+
st.write("Top 5 Predictions:")
|
| 51 |
+
for i in range(5):
|
| 52 |
+
st.write(f"{class_labels[str(top5_idx[i].item())]}: {top5_prob[i].item()*100:.2f}%")
|