转换tf.张量到numpy数组,然后保存为图像,不需要eager_execution



我的OC是apple M1的大sur,因此我的tensorflow版本是2.4,已经从官方apple github repo(https://github.com/apple/tensorflow_macos)安装。当我使用下面的代码时,我得到张量(<tf)。张量'>)

import tensorflow as tf
import tensorflow_hub as hub
from PIL import Image
import numpy as np
from tensorflow.python.compiler.mlcompute import mlcompute
from tensorflow.python.framework.ops import disable_eager_execution
disable_eager_execution()
mlcompute.set_mlc_device(device_name='gpu') # Available options are 'cpu', 'gpu', and 'any'.
tf.config.run_functions_eagerly(False)
print(tf.executing_eagerly())
image = np.asarray(Image.open('/Users/alex26/Downloads/face.jpg'))
image = tf.cast(image, tf.float32)
image = tf.expand_dims(image, 0)
model = hub.load("https://tfhub.dev/captain-pool/esrgan-tf2/1")
sr = model(image) #<tf.Tensor 'StatefulPartitionedCall:0' shape=(1, 2880, 4320, 3)dtype=float32>

如何从sr张量中获取图像?

如果你急切执行,它可以工作:

import tensorflow as tf
import numpy as np
import tensorflow_hub as hub
model = hub.load("https://tfhub.dev/captain-pool/esrgan-tf2/1")
x = np.random.rand(1, 224, 224, 3).astype(np.float32)
image = model(x)

然后可以使用tf.keras.preprocessing.image.save_img保存生成的图像。您可能必须将结果乘以255并转换为np.uint8才能使该函数工作,我不确定。

要从tensorflow张量创建numpy数组,可以使用' make_narray ': https://www.tensorflow.org/api_docs/python/tf/make_ndarray

make_ndarray以原张量为参数,所以必须先将张量转化为原张量

proto_tensor = tf.make_tensor_proto(a) # convert tensor a to a proto tensor

(https://www.geeksforgeeks.org/tensorflow-how-to-create-a-tensorproto/)

转换张量到numpy数组在Tensorflow?

张量必须是(img_height, img_width, 3)形状,3如果你想生成RGB图像(3通道),请参阅下面的代码,使用PIL将numpy图像转换为图像

从numpy数组生成图像,然后你可以使用PIL(Python成像库):我如何将numpy数组转换为(并显示)图像?

from PIL import Image
import numpy as np
img_w, img_h = 200, 200
data = np.zeros((img_h, img_w, 3), dtype=np.uint8)  <- zero np_array depth 3 for RGB
data[100, 100] = [255, 0, 0]    <- fille array with 255,0,0 in RGB
img = Image.fromarray(data, 'RGB')    <- array to image (all black then)
img.save('test.png')
img.show()

来源:https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-109.php

这是你所追求的老式方式吗?

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(sr)