2017-02-12 94 views
1

我需要調整到特定尺寸的圖像,並將其保存到文件,所以我選擇了tf.image.resize_image_with_crop_or_pad功能:無法保存tensorflow圖像文件

import tensorflow as tf 

image_decoded = tf.image.decode_jpeg(tf.read_file('1.jpg'), channels=3) 
cropped  = tf.image.resize_image_with_crop_or_pad(image_decoded, 200, 200) 
tf.write_file('2.jpg', cropped) 

失敗與錯誤:

Traceback (most recent call last): 
    File "/home/test/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 490, in apply_op 
    preferred_dtype=default_dtype) 
    File "/home/test/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 669, in convert_to_tensor 
    ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) 
    File "/home/test/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 583, in _TensorTensorConversionFunction 
    % (dtype.name, t.dtype.name, str(t))) 
ValueError: Tensor conversion requested dtype string for Tensor with dtype uint8: 'Tensor("control_dependency_3:0", shape=(200, 200, 3), dtype=uint8)' 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "train.py", line 15, in <module> 
    tf.write_file('2.jpg', cropped) 
    File "/home/test/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/gen_io_ops.py", line 694, in write_file 
    contents=contents, name=name) 
    File "/home/test/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 508, in apply_op 
    (prefix, dtypes.as_dtype(input_arg.type).name)) 
TypeError: Input 'contents' of 'WriteFile' Op has type uint8 that does not match expected type of string. 

我試着張量轉換爲使用tf.as_string()字符串,但與崩潰:

TypeError: DataType uint8 for attr 'T' not in list of allowed values: int32, int64, complex64, float32, float64, bool, int8 

我用Tensorflow v0.12.0-RC0對Linux Mint的

+0

我不確定該函數是否存在。它不在圖片大小調整頁面,而是類似的[在這裏](https://www.tensorflow.org/api_docs/python/image/cropping)。 –

+0

如果您發現我的答案有用,請接受它 – yuval

回答

3

您首先需要將圖像從張量編碼爲JPEG,然後將其保存。此外,您應該執行會話以評估您的代碼:

import tensorflow as tf 

image_decoded = tf.image.decode_jpeg(tf.read_file('1.jpg'), channels=3) 
cropped  = tf.image.resize_image_with_crop_or_pad(image_decoded, 200, 200) 
enc = tf.image.encode_jpeg(cropped) 
fname = tf.constant('2.jpg') 
fwrite = tf.write_file(fname, enc) 

sess = tf.Session() 
result = sess.run(fwrite) 
+0

非常感謝! –