将 tf.Tensor 转换为 numpy 数组,然后将其另存为图像而不需要eager_execution

Ymk*_*mka 5 python keras tensorflow

我的 OC 很适合苹果 M1,因此我的 tensorflow 版本是 2.4,它是从官方苹果 github 仓库(https://github.com/apple/tensorflow_macos)安装的。当我使用下面的代码时,我得到 tensor(<tf.Tensor 'StatefulPartitionedCall:0' shape=(1, 2880, 4320, 3) dtype=float32>)

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>
Run Code Online (Sandbox Code Playgroud)

如何从 sr Tensor 获取图像?

ral*_*htp 0

要从张量流张量创建 numpy 数组,您可以使用 `make_ndarray' :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/

在 Tensorflow 中将张量转换为 numpy 数组?

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

要从 numpy 数组生成图像,您可以使用PIL(Python 成像库):How do I conversion a numpy array to (and display) an image?

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()
Run Code Online (Sandbox Code Playgroud)

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