Tensorflow:打开 PIL.Image?

新手上路,请多包涵

我有一个脚本可以遮盖图像的一部分并通过预测网络运行它以查看图像的哪些部分对标签预测的影响最大。为此,我使用 PIL 打开本地图像并调整其大小,同时在不同的时间间隔添加一个黑框。我使用 Tensorflow 打开我的模型,我想将图像传递给模型,但它不期望具有这种特定形状的值:

 Traceback (most recent call last):
  File "obscureImage.py", line 55, in <module>
    originalPrediction, originalTag = predict(originalImage, labels)
  File "obscureImage.py", line 23, in predict
    {'DecodeJpeg/contents:0': image})
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 766, in run
    run_metadata_ptr)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 943, in _run
    % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (224, 224, 3) for Tensor 'DecodeJpeg/contents:0', which has shape '()'

这是我的代码:

 def predict(image, labels):
    with tf.Session() as sess:
        #image_data = tf.gfile.FastGFile(image, 'rb').read() # What I used to use.

        softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
        predictions = sess.run(softmax_tensor,
                               {'DecodeJpeg/contents:0': image})
        predictions = np.squeeze(predictions)

        top_k = predictions.argsort()[-5:][::-1]  # Getting top 5 predictions

        return predictions[0], labels[top_k[0]] # Return the raw value of tag matching and the matching tag.

originalImage = Image.open(args.input).resize((args.imgsz,args.imgsz)).convert('RGB')
originalPrediction, originalTag = predict(originalImage, labels)

打开并使用磁盘中的图像工作正常,但当然这不是我修改过的图像。我尝试使用 tf.image.decode_jpeg(image,0) 作为 softmax 张量的参数,但这给了我 TypeError: Expected string passed to parameter 'contents' of op 'DecodeJpeg', got <PIL.Image.Image image mode=RGB size=224x224 at 0x2592F883358> of type 'Image' instead.

原文由 IronWaffleMan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 506
1 个回答

使用来自 Keras 的 img_to_array 函数:

 import tensorflow as tf
from PIL import Image

pil_img = Image.new(3, (200, 200))
image_array  = tf.keras.utils.img_to_array(pil_img)

原文由 NielsSchneider 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题