catandog / app.py
okeowo1014's picture
Update app.py
2b3b6cd verified
raw
history blame contribute delete
No virus
1.87 kB
import streamlit as st
import cv2
import numpy as np
from tensorflow.keras.preprocessing import image
import tensorflow as tf
from huggingface_hub import from_pretrained_keras
model = from_pretrained_keras("okeowo1014/catsanddogs")
# Load the saved model (replace with your model filename)
# model = tf.keras.models.load_model('cat_dog_classifier.keras')
# Image dimensions for the model
img_width, img_height = 224, 224
def preprocess_image(img):
"""Preprocesses an image for prediction."""
img = cv2.resize(img, (img_width, img_height))
img = img.astype('float32') / 255.0
img = np.expand_dims(img, axis=0)
return img
def predict_class(image):
"""Predicts image class and probabilities."""
preprocessed_img = preprocess_image(image)
prediction = model.predict(preprocessed_img)
class_names = ['cat', 'dog'] # Adjust class names according to your model
return class_names[np.argmax(prediction)], np.max(prediction)
def display_results(class_name, probability):
"""Displays prediction results in a progress bar style."""
st.write(f"**Predicted Class:** {class_name}")
# Create a progress bar using st.progress
progress = st.progress(0)
for i in range(100):
progress.progress(i + 1)
if i == int(probability * 100):
break
st.write(f"**Probability:** {probability:.2f}")
def main():
"""Main app function."""
st.title("Image Classifier")
st.write("Upload an image to classify it as cat or dog.")
uploaded_file = st.file_uploader("Choose an image...", type="jpg")
if uploaded_file is not None:
image = cv2.imdecode(np.frombuffer(uploaded_file.read(), np.uint8), cv2.IMREAD_COLOR)
st.image(image, caption="Uploaded Image", use_column_width=True)
predicted_class, probability = predict_class(image)
display_results(predicted_class, probability)
main()
# if __name__ == '__main__':
# main()