Tensorflow: open a PIL.Image?

2024/9/16 23:13:35

I have a script that obscures part of an image and runs it through a prediction net to see which parts of the image most strongly influence the tag prediction. To do this, I open a local image with PIL and resize it, along with adding a black box at various intervals. I use Tensorflow to open my model and I want to pass the image to the model, but it's not expecting a value with this specific shape:

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

This is my code:

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

Opening and using the image from the disk works fine, but of course then it's not my modified image. I tried using tf.image.decode_jpeg(image,0) as the parameter for the softmax tensor, but that gives me 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.

Answer

Use the img_to_array function from Keras:

import tensorflow as tf 
from PIL import Imagepil_img = Image.new(3, (200, 200))
image_array  = tf.keras.utils.img_to_array(pil_img)
https://en.xdnf.cn/q/72663.html

Related Q&A

Django: Saving to DB from form example

It seems I had difficulty finding a good source/tutorial about saving data to the DB from a form. And as it progresses, I am slowly getting lost. I am new to Django, and please guide me. I am getting e…

eval(input()) in python 2to3

From the Python 2to3 doc:input:Converts input(prompt) to eval(input(prompt))I am currently trying to learn Python 3 after a few years working with Python 2. Can anybody please explain why the tool inse…

Post XML file using Python

Im new to Python and in need of some help. My aim is to send some XML with a post request to a URL, which is going to trigger a SMS being sent. I have a small XML document that I want to post to the UR…

Python TypeError: __init__() got multiple values for argument master

Trying to build a GUI in Python at the moment, and Im stuck at this part in particular. Every time I try to run my code it just throws the error TypeError: __init__() got multiple values for argument m…

How to suppress all warnings in window of executable file generated by pyinstaller

I have generated an executable file from a python file using pyinstaller. The program works how it is supposed to work but there is this warning message it appears in the window that I would like to hi…

Python requests gives me bad handshake error

Using Python requests like thisimport requests; requests.get(https://internal.site.no)gives me an error many have had;SSLError: ("bad handshake: Error([(SSL routines, SSL23_GET_SERVER_HELLO, sslv3…

PyCharm: Storing variables in memory to be able to run code from a checkpoint

Ive been searching everywhere for an answer to this but to no avail. I want to be able to run my code and have the variables stored in memory so that I can perhaps set a "checkpoint" which I …

Execute bash script from Python on Windows

I am trying to write a python script that will execute a bash script I have on my Windows machine. Up until now I have been using the Cygwin terminal so executing the bash script RunModels.scr has been…

Python regex convert youtube url to youtube video

Im making a regex so I can find youtube links (can be multiple) in a piece of HTML text posted by an user.Currently Im using the following regex to change http://www.youtube.com/watch?v=-JyZLS2IhkQ in…

Python / Kivy: conditional design in .kv file

Would an approach similar to the example below be possible in Kivy? The code posted obviously doesnt work, and again its only an example: I will need different layouts to be drawn depending on a certa…