如何解决将 tf.Tensor 转换为 numpy 数组,然后将其保存为图像而不需要eager_execution
我的 OC 是苹果 M1 的大 sur,因此我的 tensorflow 版本是 2.4,已从官方苹果 github repo(https://github.com/apple/tensorflow_macos) 安装。当我使用下面的代码时,我得到 tensor(
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 Tensor 获取图像?
解决方法
要从 tensorflow 张量创建一个 numpy 数组,您可以使用 `make_ndarray':https://www.tensorflow.org/api_docs/python/tf/make_ndarray
34 00 * * 2 test "$(($(date +%W)%4))" -eq 2 && echo "yes2" > /u/crmprod/test
以原始张量作为参数,因此您必须先将张量转换为原始张量
make_ndarray
( https://www.geeksforgeeks.org/tensorflow-how-to-create-a-tensorproto/ )
Convert a tensor to numpy array in Tensorflow?
张量必须是形状 proto_tensor = tf.make_tensor_proto(a) # convert tensor a to a proto tensor
,如果要生成 RGB 图像(3 个通道),则为 (img_height,img_width,3)
,请参阅以下代码以使用 {{ 将 numpy aaray 转换为图像1}}
要从 numpy 数组生成图像,您可以使用 3
(Python 图像库):How do I convert a numpy array to (and display) an image?
PIL
来源:https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-109.php
,如果你急切地执行它是有效的:
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,3).astype(np.float32)
image = model(x)
然后您可以使用 tf.keras.preprocessing.image.save_img
保存生成的图像。您可能需要将结果乘以 255
并转换为 np.uint8
才能使该函数起作用,我不确定。
这是您正在照顾的老式方法吗?
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(sr)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。