Getting this error after uploading the image:- IndexError: list index out of range
here are the tracebacks:
Traceback:
File "E:\pythonsoft\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 565, in _run_script
exec(code, module.__dict__)File "D:\Python_Projects\Fruit_vegetable_nutrients\main.py", line 97, in <module>
main()File "D:\Python_Projects\Fruit_vegetable_nutrients\main.py", line 82, in main
label = predict_label(image)File "D:\Python_Projects\Fruit_vegetable_nutrients\main.py", line 53, in predict_label
prediction = model.predict(image_array)File "E:\pythonsoft\lib\site-packages\keras\engine\training.py", line 1720, in predict
data_handler = data_adapter.get_data_handler(File "E:\pythonsoft\lib\site-packages\keras\engine\data_adapter.py", line 1383, in get_data_handler
return DataHandler(*args, **kwargs)File "E:\pythonsoft\lib\site-packages\keras\engine\data_adapter.py", line 1138, in __init__
self._adapter = adapter_cls(File "E:\pythonsoft\lib\site-packages\keras\engine\data_adapter.py", line 658, in __init__
self._internal_adapter = TensorLikeDataAdapter(File "E:\pythonsoft\lib\site-packages\keras\engine\data_adapter.py", line 240, in __init__
num_samples = set(int(i.shape[0]) for i in tf.nest.flatten(inputs)).pop()File "E:\pythonsoft\lib\site-packages\keras\engine\data_adapter.py", line 240, in <genexpr>
num_samples = set(int(i.shape[0]) for i in tf.nest.flatten(inputs)).pop()File "E:\pythonsoft\lib\site-packages\tensorflow\python\framework\tensor_shape.py", line 896, in __getitem__
return self._dims[key].value
And here is my code:
import numpy as np
import streamlit as st
from keras.models import load_model
from keras.preprocessing.image import load_img, img_to_array
from PIL import Image
# Load the trained CNN model
model = load_model('FV.h5')
# Dictionary of labels and corresponding fruit/vegetable names
labels = {0: 'apple', 1: 'banana', 2: 'beetroot', 3: 'bell pepper', 4: 'cabbage', 5: 'capsicum', 6: 'carrot',
7: 'cauliflower', 8: 'chilli pepper', 9: 'corn', 10: 'cucumber', 11: 'eggplant', 12: 'garlic', 13: 'ginger',
14: 'grapes', 15: 'jalepeno', 16: 'kiwi', 17: 'lemon', 18: 'lettuce',
19: 'mango', 20: 'onion', 21: 'orange', 22: 'paprika', 23: 'pear', 24: 'peas', 25: 'pineapple',
26: 'pomegranate', 27: 'potato', 28: 'raddish', 29: 'soy beans', 30: 'spinach', 31: 'sweetcorn',
32: 'sweetpotato', 33: 'tomato', 34: 'turnip', 35: 'watermelon'}
fruits = ['Apple', 'Banana', 'Bello Pepper', 'Chilli Pepper', 'Grapes', 'Jalepeno', 'Kiwi', 'Lemon', 'Mango', 'Orange',
'Paprika', 'Pear', 'Pineapple', 'Pomegranate', 'Watermelon']
vegetables = ['Beetroot', 'Cabbage', 'Capsicum', 'Carrot', 'Cauliflower', 'Corn', 'Cucumber', 'Eggplant', 'Ginger',
'Lettuce', 'Onion', 'Peas', 'Potato', 'Raddish', 'Soy Beans', 'Spinach', 'Sweetcorn', 'Sweetpotato',
'Tomato', 'Turnip']
# Dictionary of nutritional information for different types of fruits and vegetables
nutrition_info = {
'apple': {'calories': 95, 'vitamins': ['Vitamin C', 'Vitamin K'], 'fat': 0.3, 'protein': 1},
'banana': {'calories': 105, 'vitamins': ['Vitamin C', 'Vitamin B6'], 'fat': 0.4, 'protein': 1.3},
'bell pepper': {'calories': 20, 'vitamins': ['Vitamin C', 'Vitamin A'], 'fat': 0.2, 'protein': 0.9},
# ...
}
def preprocess_image(image_file):
# Read the image file and resize it to the required input size for the model
image = load_img(image_file, target_size=(224, 224))
# Convert the image to a numpy array
image = img_to_array(image)
# Normalize the pixel values
image = image / 255
image = np.expand_dims(image, [0])
# Make a prediction using the CNN model
prediction = model.predict(image)
# Get the index of the highest prediction
label_index = np.argmax(prediction)
# Get the corresponding label from the labels list
label = labels[label_index]
return label
def predict_label(image_array):
# Make a prediction using the CNN model
prediction = model.predict(image_array)
# Get the index of the highest prediction
label_index = np.argmax(prediction)
# Get the corresponding label from the labels list
label = labels[label_index]
return label
def get_nutrition_info(label):
# Get the nutrition information for the label
info = nutrition_info[label]
return info
# Define the main function
def main():
# Use Streamlit to create a file uploader widget
uploaded_file = st.file_uploader("Choose an image...", type="jpg")
if uploaded_file is not None:
# Preprocess the image
image = Image.open(uploaded_file).resize((250, 250))
st.image(image, use_column_width=False)
uploaded_file_path = './upload_images/' + uploaded_file.name
with open(uploaded_file_path, "wb") as f:
f.write(uploaded_file.getbuffer())
image = preprocess_image(uploaded_file_path)
# Get the predicted label
label = predict_label(image)
if image in labels:
st.info('**Category: Vegetables**')
else:
st.info('**Category : Fruits**')
# Get the nutrition information for the label
info = get_nutrition_info(label)
# Display the predicted label and nutrition information
st.write("Predicted label: ", label)
st.write("Calories: ", info['calories'])
st.write("Vitamins: ", info['vitamins'])
st.write("Fat: ", info['fat'])
st.write("Protein: ", info['protein'])
main()
I am trying to fetch the Nutritional values of fruits and vegetables, I am using Streamlit as user interface and When I'm trying to upload I am getting this error.
In def preprocess_image(image_file): function you are processing the image and predicting the labels there. There is no need to call label = predict_label(image) since prections is already done in preprocess.
There are other errors in you code.
if image in labels: I think you meant to look up vegetables .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.