繁体   English   中英

Tensorflow:打开 PIL.Image?

[英]Tensorflow: open a 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.

使用img_to_array函数:

from PIL import Image

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

'DecodeJpeg:0/contents:0' 是一种用于将 base64 字符串解码为原始图像数据的操作。 您正在尝试输入原始图像数据。 因此,您应该将其输入到 'DecodeJpeg:0' 中,即 'DecodeJpeg:0/contents:0' 的输出,或者输入到作为图形输入的 'Mul:0' 中。 不要忘记调整大小,因为输入的形状应该是 (299,299,3) Mul 接受 (1,299,299,3)

像这样尝试:

image = Image.open("example.jepg")
image.resize((299,299), Image.ANTIALIAS)
image_array = np.array(image)[:, :, 0:3]  # Select RGB channels only.

prediction = sess.run(softmax_tensor, {'DecodeJpeg:0': image_array})
or
prediction = sess.run(softmax_tensor, {'Mul:0': [image_array]})

在这个 stackoverflow question 中也有讨论

要可视化操作:

 for i in sess.graph.get_operations():
            print (i.values())

希望这可以帮助

不知道为什么马克西米利安的答案不起作用,但以下是对我有用的:

from io import BytesIO

def predict(image, labels, sess):
    imageBuf = BytesIO()
    image.save(imageBuf, format="JPEG")
    image = imageBuf.getvalue()

    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[top_k[0]], labels[top_k[0]] # Return the raw value of tag matching and the matching tag.

制作了一个字节缓冲区,将 PIL Image 保存到其中,获取其值并将其传入。对这个答案做一个很好的补充。

您可以使用 PIL 的getdata()

将图像的内容作为包含像素值的序列对象返回。 序列对象被展平,因此第 1 行的值紧跟在第 0 行的值之后,依此类推。

或 Tensorflow 的gfile

from tensorflow.python.platform import gfile
image_data = gfile.FastGFile(image_filename, 'rb').read()

我试过这个,对我来说效果很好。 随意更改参数以调整您的解决方案。 该图像是作为输入的 PIL 图像。

def read_tensor_from_image(image, input_height=224, input_width=224,
            input_mean=0, input_std=255):

  float_caster = tf.cast(image, tf.float32)
  dims_expander = tf.expand_dims(float_caster, 0);
  resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
  normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
  sess = tf.Session()
  result = sess.run(normalized)

  return result

暂无
暂无

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

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