[英]Convert tf.Tensor to numpy array and than save it as image in without eager_execution
我的 OC 對於蘋果 M1 來說是很大的,因此我的 tensorflow 版本是 2.4,它是從蘋果官方 github repo 安裝的( https://github.com ) 當我使用下面的代碼時,我得到 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>
如何從 sr Tensor 獲取圖像?
To create an numpy array from a tensorflow tensor you can use `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 數組?
張量必須是 if shape (img_height, img_width, 3)
3
如果要生成 RGB 圖像(3 個通道),則為 3,請參閱以下代碼以使用PIL
將 numpy aaray 轉換為圖像
要從 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
如果您急切地執行它,它會起作用:
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
才能使 function 工作,我不確定。
這是你正在照顧的老式方式嗎?
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(sr)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.