繁体   English   中英

我收到错误 [IndexError: list index out of range] 但请帮我解决这个问题

[英]I am getting error [ IndexError: list index out of range ] but please help me to resolve this

上传图片后出现此错误:- IndexError:列表索引超出范围

在此处输入图像描述

这是回溯:

追溯:

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

这是我的代码:

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()

我正在尝试获取水果和蔬菜的营养价值,我使用 Streamlit 作为用户界面,当我尝试上传时出现此错误。

def preprocess_image(image_file):函数中,您正在处理图像并预测那里的标签。 无需调用label = predict_label(image)因为预测已经在预处理中完成。

您的代码中还有其他错误。

if image in labels:我想你是想查蔬菜

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM