简体   繁体   中英

How to create tensor with shape(?,) and dtype=string from image with tensorflow in python

I have a trained model with input layer specified below:

Model input:  [<tf.Tensor 'encoded_image_string_tensor:0' shape=(None,) dtype=string>, <tf.Tensor 'key:0' shape=(None,) dtype=string>]

I have problem to create a tensor with these properties. Either i get right dtype but then i get shape() . Or i get a nonempty shape but dtype=uint8 or similar. Any tip on how to read, create and input my image to right format. The images that I want to input are grayscale , jpg , 3232x583 pixels.

You can do

import tensorflow as tf

a = tf.placeholder(dtype=tf.string, shape=[None, ], name="encoder_image_string_tensor")
print(a)

which prints

Tensor("encoder_image_string_tensor:0", shape=(?,), dtype=string)

For feeding value into this Tensor you can use sess.run and the feed_dict parameter inside this function.

To get the image in the right dimension you can do:

import cv2
im = cv2.imread("abc.jpg")
my_img = np.squeeze(np.reshape(im, [-1, 1]))
sess.run([], feed_dict={a: my_img})

I am sourcing my answer from here .

I was able to solve it with help of this anwser ( link ) I read it as a image with OpenCV. Encode it to jpg. Transform it to byte array. And make it to tensorflow with tf.constant(). Feels like the convertion from file to byte array could be made in a better way but i leave it with this for now.

code:

img = cv2.imread('IMAGEPATH')
flag, bts = cv2.imencode('.jpg', img) 
byte_arr = [bts[:,0].tobytes()]
tensor_string = tf.constant(byte_arr)

gives this which works:

Tensor("Const_14:0", shape=(1,), dtype=string)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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