Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,29 +1,14 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
from PIL import Image
|
| 3 |
-
import
|
| 4 |
-
import torchvision.transforms as transforms
|
| 5 |
-
from torchvision import models
|
| 6 |
-
|
| 7 |
-
# Check if CUDA (GPU) is available, otherwise use CPU
|
| 8 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 9 |
-
|
| 10 |
-
# Load the pre-trained model (ResNet-50)
|
| 11 |
-
model = models.resnet50(pretrained=True)
|
| 12 |
-
model = model.to(device)
|
| 13 |
-
model.eval()
|
| 14 |
-
|
| 15 |
-
# Define a function to preprocess the image
|
| 16 |
-
def preprocess_image(image):
|
| 17 |
-
transform = transforms.Compose([
|
| 18 |
-
transforms.Resize((224, 224)),
|
| 19 |
-
transforms.ToTensor(),
|
| 20 |
-
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 21 |
-
])
|
| 22 |
-
return transform(image).unsqueeze(0).to(device)
|
| 23 |
|
| 24 |
# Set up a title for the app
|
| 25 |
st.title("Image Recognition App")
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
# Upload an image
|
| 28 |
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"])
|
| 29 |
|
|
@@ -32,15 +17,9 @@ if uploaded_file is not None:
|
|
| 32 |
image = Image.open(uploaded_file).convert("RGB")
|
| 33 |
st.image(image, caption='Uploaded Image.', use_column_width=True)
|
| 34 |
|
| 35 |
-
#
|
| 36 |
st.write("Classifying...")
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
top5_prob, top5_classes = torch.topk(probabilities, 5)
|
| 42 |
-
|
| 43 |
-
# Display the top 5 predictions
|
| 44 |
-
st.write("Predictions:")
|
| 45 |
-
for i in range(5):
|
| 46 |
-
st.write(f"Label: {top5_classes[i].item()}, Confidence: {top5_prob[i].item():.2f}")
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
from PIL import Image
|
| 3 |
+
from fastai.vision.all import load_learner, PILImage, Path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
# Set up a title for the app
|
| 6 |
st.title("Image Recognition App")
|
| 7 |
|
| 8 |
+
# Load the pre-trained model (make sure it's stored in the same directory as 'app.py')
|
| 9 |
+
model_path = Path("model.pkl") # Adjust the path if needed
|
| 10 |
+
learn = load_learner(model_path)
|
| 11 |
+
|
| 12 |
# Upload an image
|
| 13 |
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"])
|
| 14 |
|
|
|
|
| 17 |
image = Image.open(uploaded_file).convert("RGB")
|
| 18 |
st.image(image, caption='Uploaded Image.', use_column_width=True)
|
| 19 |
|
| 20 |
+
# Run the model to make predictions
|
| 21 |
st.write("Classifying...")
|
| 22 |
+
pred, pred_idx, probs = learn.predict(PILImage.create(uploaded_file))
|
| 23 |
+
|
| 24 |
+
# Display the predictions
|
| 25 |
+
st.write(f"Prediction: {pred} with probability {probs[pred_idx]:.2f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|