Spaces:
Runtime error
Runtime error
Commit ·
c3ffa98
1
Parent(s): 4d7b775
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
# Load pre-trained model
|
| 7 |
+
model = tf.keras.applications.ResNet50(weights='imagenet')
|
| 8 |
+
|
| 9 |
+
# Set Streamlit configurations
|
| 10 |
+
st.set_page_config(page_title="Image Classifier App", layout="wide")
|
| 11 |
+
|
| 12 |
+
# Define labels for ImageNet classes
|
| 13 |
+
LABELS_PATH = 'https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json'
|
| 14 |
+
labels = tf.keras.utils.get_file('ImageNetLabels.json', LABELS_PATH)
|
| 15 |
+
with open(labels) as f:
|
| 16 |
+
classes = eval(f.read())
|
| 17 |
+
|
| 18 |
+
# Function to preprocess the input image
|
| 19 |
+
def preprocess_image(image):
|
| 20 |
+
image = image.resize((224, 224)) # Resize image to match model input size
|
| 21 |
+
image = tf.keras.preprocessing.image.img_to_array(image)
|
| 22 |
+
image = np.expand_dims(image, axis=0)
|
| 23 |
+
image = tf.keras.applications.resnet50.preprocess_input(image)
|
| 24 |
+
return image
|
| 25 |
+
|
| 26 |
+
# Function to make predictions on the input image
|
| 27 |
+
def predict(image):
|
| 28 |
+
image = preprocess_image(image)
|
| 29 |
+
preds = model.predict(image)
|
| 30 |
+
top_predictions = tf.keras.applications.resnet50.decode_predictions(preds, top=5)[0]
|
| 31 |
+
return top_predictions
|
| 32 |
+
|
| 33 |
+
# Streamlit app
|
| 34 |
+
def main():
|
| 35 |
+
st.title("Image Classifier App")
|
| 36 |
+
st.write("Upload an image and the app will predict its class.")
|
| 37 |
+
|
| 38 |
+
uploaded_image = st.file_uploader("Choose an image", type=["jpg", "jpeg", "png"])
|
| 39 |
+
|
| 40 |
+
if uploaded_image is not None:
|
| 41 |
+
image = Image.open(uploaded_image)
|
| 42 |
+
st.image(image, caption='Uploaded Image', use_column_width=True)
|
| 43 |
+
st.write("")
|
| 44 |
+
|
| 45 |
+
if st.button("Predict"):
|
| 46 |
+
with st.spinner("Predicting..."):
|
| 47 |
+
predictions = predict(image)
|
| 48 |
+
|
| 49 |
+
st.write("Top predictions:")
|
| 50 |
+
for _, label, confidence in predictions:
|
| 51 |
+
st.write(f"{label}: {round(confidence * 100, 2)}%")
|
| 52 |
+
|
| 53 |
+
# Run the app
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
main()
|