File size: 1,910 Bytes
77368f6
 
 
 
 
11a9b7f
77368f6
 
11a9b7f
77368f6
f85dff3
11a9b7f
 
 
6386a8e
11a9b7f
2185839
6386a8e
 
 
 
77368f6
 
 
 
f85dff3
 
77368f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6386a8e
 
 
 
77368f6
 
 
 
 
 
 
2185839
 
f85dff3
2185839
 
 
77368f6
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import streamlit as st
import numpy as np
import cv2
from PIL import Image
import tensorflow as tf
import os

# Function to load the model
@st.cache_resource
def load_model():
    model_path = 'models/my_model.h5'  # Path relative to the script
    if not os.path.isfile(model_path):
        st.error(f"Model file not found: {model_path}")
        return None
    try:
        model = tf.keras.models.load_model(model_path)
        st.success("Model loaded successfully!")
        return model
    except Exception as e:
        st.error(f"Error loading model: {e}")
        return None

# Function to preprocess the image
def preprocess_image(image):
    image = np.array(image.convert('RGB'))
    image = cv2.resize(image, (224, 224))
    image = image / 255.0
    image = np.expand_dims(image, axis=0)
    return image

# Function to predict the class
def predict(image, model):
    processed_image = preprocess_image(image)
    prediction = model.predict(processed_image)
    return prediction

# Main app
def main():
    st.title("Food Item Recognition and Estimation")
    st.write("Upload an image of a food item and the model will recognize the food item and estimate its calories.")

    model = load_model()

    if model is None:
        st.write("Model could not be loaded.")
        return

    uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
    if uploaded_file is not None:
        image = Image.open(uploaded_file)
        st.image(image, caption='Uploaded Image.', use_column_width=True)
        
        st.write("")
        st.write("Classifying...")
        try:
            prediction = predict(image, model)
            predicted_class = np.argmax(prediction, axis=1)[0]
            st.write(f"Predicted class: {predicted_class}")
        except Exception as e:
            st.error(f"Error in prediction: {e}")

if __name__ == "__main__":
    main()