|
import streamlit as st |
|
from transformers import ViTForImageClassification, ViTFeatureExtractor |
|
from PIL import Image |
|
import torch |
|
import matplotlib.pyplot as plt |
|
|
|
|
|
repo_id = "Hammad712/5-Flower-Types-Classification-VIT-Model" |
|
|
|
|
|
model = ViTForImageClassification.from_pretrained(repo_id) |
|
feature_extractor = ViTFeatureExtractor.from_pretrained(repo_id) |
|
|
|
|
|
class_names = {0: 'Lilly', 1: 'Lotus', 2: 'Orchid', 3: 'Sunflower', 4: 'Tulip'} |
|
|
|
|
|
def predict(image): |
|
inputs = feature_extractor(images=image, return_tensors="pt") |
|
with torch.no_grad(): |
|
outputs = model(**inputs) |
|
logits = outputs.logits |
|
probabilities = torch.nn.functional.softmax(logits, dim=-1).squeeze().tolist() |
|
predicted_class_idx = logits.argmax(-1).item() |
|
predicted_class_name = class_names[predicted_class_idx] |
|
return probabilities, predicted_class_name |
|
|
|
|
|
st.title("Flower Type Classification") |
|
st.write("Upload an image of a flower to classify its type.") |
|
|
|
|
|
uploaded_file = st.sidebar.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"]) |
|
|
|
if uploaded_file is not None: |
|
|
|
image = Image.open(uploaded_file).convert("RGB") |
|
st.image(image, caption='Uploaded Image.', use_column_width=True) |
|
|
|
|
|
probabilities, predicted_class = predict(image) |
|
|
|
|
|
fig, ax = plt.subplots() |
|
ax.bar(class_names.values(), probabilities) |
|
ax.set_ylabel('Probability') |
|
ax.set_xlabel('Class') |
|
ax.set_title('Class Probabilities') |
|
st.pyplot(fig) |
|
|
|
|
|
st.write(f"Predicted class: **{predicted_class}**") |
|
|