2017-10-05 129 views
0

我有一個返回我叫變量的函數 - 圖像格式:保存張量與tf.map_fn JPEG圖像 - 的Python/TensorFlow

<tf.Tensor 'Conv2D_1:0' shape=(?, 16, 16, 1) dtype=float32> 

我需要將這些圖像保存。 JPEG。

到目前爲止,我認爲這樣做的:

# Reshape into tf.image.encode_jpeg format 
images = tf.image.convert_image_dtype(layer, tf.uint8) 

train_batch_size = 300 

而且在會話= tf.Session()

images_encode = tf.map_fn(lambda x: tf.image.encode_jpeg(x), images, dtype=tf.uint8) # There was no error in this line, is it right? 

我懷疑現在是如何配置它來拯救他們?

我已經試過這樣:

# That means it will only scroll through my 300 images 
# And it's these 300 images that I want to save 
x_batch, y_true_batch = next_batch_size(train_batch_size) 

feed_dict_train = {x: x_batch, y_true: y_true_batch} 

result = session.run(images_encode, feed_dict=feed_dict_train) 

format_str = ('%s.jpeg') 
fr = format_str % datetime.now() 
f = open(fr, "wb+") 
f.write(result.eval()) 
f.close() 

但我發現了以下錯誤:

InvalidArgumentError (see above for traceback): TensorArray dtype is uint8 but Op is trying to write dtype string. 
    [[Node: map_5/while/TensorArrayWrite/TensorArrayWriteV3 = TensorArrayWriteV3[T=DT_STRING, _class=["loc:@map_5/TensorArray_1"], _device="/job:localhost/replica:0/task:0/cpu:0"](map_5/while/TensorArrayWrite/TensorArrayWriteV3/Enter, map_5/while/Identity, map_5/while/EncodeJpeg, map_5/while/Identity_1)]] 

我的佔位符:

# Placeholder variable for the input images 
x = tf.placeholder(tf.float32, shape=[None, img_size_flat], name='x') 

# Reshape 'x' 
x_image = tf.reshape(x, [-1, img_size, img_size, num_channels]) 

# Placeholder variable for the true labels associated with the images 
y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true') 
+0

請讓我知道如果你還需要幫助,或者如果答案解決您的問題。 – Patwie

+0

@Patwie,我很抱歉拖延,我這些日子一直很忙! – QuestionsStackOverflow

回答

1

你幾乎完成。該類型必須是一個tf.string: 這給出了一個嘈雜的圖像:

import tensorflow as tf 
import numpy as np 

noise = np.random.randn(3, 128, 128, 1).astype(np.float32) * 255 
# your data 
layer = tf.convert_to_tensor(noise) 

images = tf.image.convert_image_dtype(layer, tf.uint8) 
images_encode = tf.map_fn(lambda x: tf.image.encode_jpeg(x), 
          images, dtype=tf.string) 


def write_jpg(buf, fn): 
    with open(fn, 'wb') as f: 
     f.write(encoded_jpegs[0]) 

with tf.Session() as sess: 
    encoded_jpegs = sess.run(images_encode) 

    for k, jpg in enumerate(encoded_jpegs): 
     with open("test%03i.jpg" % k, 'wb') as f: 
      f.write(jpg) 
+0

這非常有幫助。但它仍然不是我所需要的,我需要單獨保存300個圖像中的每一個,例如:'test1.jpg,test2.jpg,...,test300.jpg'。我需要它們的原始形式,沒有噪音。因爲這個想法是稍後生成這些圖像的直方圖。 – QuestionsStackOverflow

+0

你總是可以連接這些圖像或使用tf.py_func – Patwie

+0

我添加了循環來編寫所有圖像,它們都是**沒有**噪音。我只是以噪音爲例。 '圖層'可以是任何圖像! – Patwie