Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import torch
|
3 |
+
from torchvision import models, transforms
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
# Load a pre-trained ResNet model
|
7 |
+
model = models.resnet50(pretrained=True)
|
8 |
+
model.eval()
|
9 |
+
|
10 |
+
# Define the transformations for the input image
|
11 |
+
transform = transforms.Compose([
|
12 |
+
transforms.Resize((224, 224)),
|
13 |
+
transforms.ToTensor(),
|
14 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
15 |
+
])
|
16 |
+
|
17 |
+
def classify_image(image):
|
18 |
+
# Preprocess the input image
|
19 |
+
image = transform(image)
|
20 |
+
image = image.unsqueeze(0) # Add batch dimension
|
21 |
+
|
22 |
+
# Make a prediction
|
23 |
+
with torch.no_grad():
|
24 |
+
output = model(image)
|
25 |
+
|
26 |
+
# Get the predicted class
|
27 |
+
_, predicted_class = torch.max(output, 1)
|
28 |
+
|
29 |
+
return predicted_class.item()
|
30 |
+
|
31 |
+
def main():
|
32 |
+
st.title("Image Classification with PyTorch and Streamlit")
|
33 |
+
|
34 |
+
uploaded_file = st.file_uploader("Choose a file", type=["jpg", "jpeg", "png"])
|
35 |
+
|
36 |
+
if uploaded_file is not None:
|
37 |
+
# Display the uploaded image
|
38 |
+
image = Image.open(uploaded_file)
|
39 |
+
st.image(image, caption="Uploaded Image.", use_column_width=True)
|
40 |
+
|
41 |
+
# Make a prediction
|
42 |
+
class_idx = classify_image(image)
|
43 |
+
|
44 |
+
# Display the result
|
45 |
+
class_label = str(class_idx)
|
46 |
+
st.write("Class Prediction: ", class_label)
|
47 |
+
|
48 |
+
if __name__ == "__main__":
|
49 |
+
main()
|