我们如何使用tf.image.encode_jpeg在TensorFlow中写出图像?

jks*_*hin 2 tensorflow

给定张量,我想使用此函数获取0D字符串,然后将其写为“ sample.jpg”。

这可以通过OpenCV或Python PIL轻松实现,但我希望尽可能将所有内容保留在TF中。

fab*_*ioM 5

在tensorflow中,函数如下所示:

 import tensorflow as tf


def write_jpeg(data, filepath):
    g = tf.Graph()
    with g.as_default():
        data_t = tf.placeholder(tf.uint8)
        op = tf.image.encode_jpeg(data_t, format='rgb', quality=100)
        init = tf.initialize_all_variables()

    with tf.Session(graph=g) as sess:
        sess.run(init)
        data_np = sess.run(op, feed_dict={ data_t: data })

    with open(filepath, 'w') as fd:
        fd.write(data_np)


import numpy as np

R = np.zeros([128 * 128])
G = np.ones([128 * 128]) * 100
B = np.ones([128 * 128]) * 200

data = np.array(list(zip(R, G, B)), dtype=np.uint8).reshape(128, 128, 3)

assert data.shape == (128, 128, 3)

write_jpeg(data, "./test.jpeg")
Run Code Online (Sandbox Code Playgroud)

numpy部分可以改进,但仅用于演示目的