|
|
|
import streamlit as st |
|
from fastai.vision.all import * |
|
import matplotlib.pyplot as plt |
|
import matplotlib.image as mpimg |
|
|
|
|
|
def GetLabel(fileName): |
|
return fileName.split('-')[0] |
|
|
|
|
|
def prepare_data(food_path, label_a, label_b): |
|
for img in get_image_files(food_path): |
|
if label_a in str(img): |
|
img.rename(f"{img.parent}/{label_a}-{img.name}") |
|
elif label_b in str(img): |
|
img.rename(f"{img.parent}/{label_b}-{img.name}") |
|
else: |
|
os.remove(img) |
|
|
|
|
|
def load_pretrained_model(): |
|
model_path = "export.pkl" |
|
return load_learner(model_path) |
|
|
|
|
|
def main(): |
|
st.title("Food Classifier Streamlit App") |
|
|
|
|
|
options = ["Upload Image", "Test Random Images", "Confusion Matrix"] |
|
choice = st.sidebar.selectbox("Choose an option", options) |
|
|
|
if choice == "Upload Image": |
|
st.subheader("Upload Your Own Images") |
|
model = load_pretrained_model() |
|
|
|
uploaded_files = st.file_uploader("Choose images", type=["jpg", "jpeg", "png"], accept_multiple_files=True) |
|
|
|
if uploaded_files: |
|
for img in uploaded_files: |
|
img = PILImage.create(img) |
|
label, _, probs = model.predict(img) |
|
|
|
st.image(img, caption=f"This is a {label}.") |
|
st.write(f"{label}: {probs[1].item():.6f}") |
|
st.write(f"{label}: {probs[0].item():.6f}") |
|
|
|
elif choice == "Test Random Images": |
|
st.subheader("Test Using Images in Dataset") |
|
model = load_pretrained_model() |
|
food_path = Path("~/.fastai/data/food-101/food-101").expanduser() |
|
|
|
for i in range(0, 5): |
|
random_index = random.randint(0, len(get_image_files(food_path)) - 1) |
|
img_path = get_image_files(food_path)[random_index] |
|
img = mpimg.imread(img_path) |
|
label, _, probs = model.predict(img) |
|
|
|
st.image(img, caption=f"Predicted label: {label}") |
|
|
|
elif choice == "Confusion Matrix": |
|
st.subheader("Confusion Matrix") |
|
model = load_pretrained_model() |
|
interp = ClassificationInterpretation.from_learner(model) |
|
st.pyplot(interp.plot_confusion_matrix()) |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |
|
|