错误:尝试将值 PIL 转换为张量

问题描述 投票:0回答:1

我尝试运行这段代码:

     import tensorflow as tf
     from tensorflow import keras
     from keras.models import  load_model
     import streamlit as st
     import numpy as np 

     st.header('Image Classification Model')
     model = load_model('C:\\Users\\ajit7\\OneDrive\\Documents\\Major Project\\Image_classify.keras')
     data_cat = ['WithMask', 'WithoutMask']
     img_height = 224
     img_width = 224
     image =st.text_input('Enter Image name','C:\\Users\\ajit7\\OneDrive\\Documents\\Major        Project\\gayatri-malhotra-26SGAduvONc-unsplash.png')

     image_load = tf.keras.utils.load_img(image, target_size=(img_height,img_width))
     img_arr = tf.keras.utils.array_to_img(image_load)
     img_bat=tf.expand_dims(img_arr,0)

     predict = model.predict(img_bat)

     score = tf.nn.softmax(predict)
     st.image(image, width=200)
     st.write(  data_cat[np.argmax(score)])
     st.write('With accuracy of ' + str(np.max(score)*100))`

我本来希望根据我使用的模型的预测获得信息,但我得到了这个:

    ValueError: Attempt to convert a value (<PIL.Image.Image image mode=RGB size=224x224 at 0x213D2F9E670>) with an unsupported type (<class 'PIL.Image.Image'>) to a Tensor.
    Traceback:
    File "C:\ProgramData\anaconda3\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 584, in _run_script
        exec(code, module.__dict__)
    File "C:\Users\ajit7\OneDrive\Documents\Major Project\app1.py", line 17, in <module>
        img_bat=tf.expand_dims(img_arr,0)
    File "C:\ProgramData\anaconda3\lib\site-packages\tensorflow\python\util\traceback_utils.py", line 153, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "C:\ProgramData\anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py", line 102, in convert_to_eager_tensor
        return ops.EagerTensor(value, ctx.device_name, dtype)
python tensorflow streamlit
1个回答
0
投票

这里因素太多,可能是路径不正确,图片格式不支持。但我建议也许尝试一下:

更换:

img_arr = tf.keras.utils.array_to_img(image_load)
img_bat = tf.expand_dims(img_arr, 0)

与:

img_arr = tf.keras.preprocessing.image.img_to_array(image_load)
img_bat = tf.expand_dims(img_arr, 0) / 255.0
© www.soinside.com 2019 - 2024. All rights reserved.