[英]How to read images in path If I have a tensorflow string tensor
我在下面有這個簡單的函數,它接受一個 tensorflow 字符串張量( filename
)並檢索圖像。
def get_image(filename):
filename = filename.numpy()
img = tf.io.read_file(f'images/{filename}')
return img
但我得到AttributeError: 'Tensor' object has no attribute 'numpy'
我在這里尋找解決方案,但沒有人有一個好的解決方案。 很多人就如何啟用 Eager Execution 提出了建議,但都沒有奏效。 從張量中檢索數據真的那么難嗎……?
或者在這種情況下是否有另一種方法可以在不轉換為 numpy 的情況下執行我想要的操作?
TL;DR首先,也許下面的示例可以幫助您,然后您可以閱讀解決方案並從路徑中讀取圖像。
生成錯誤示例(我們無法在此類函數中訪問 numpy)
# With @tf.function
@tf.function
def func(tns):
tf.print(tns.numpy())
func(tf.random.uniform(shape=(2,)))
# -> AttributeError: 'Tensor' object has no attribute 'numpy'
# Without @tf.function
def func(tns):
tf.print(tns.numpy())
func(tf.random.uniform(shape=(2,)))
# -> array([0.86797523, 0.10352373], dtype=float32)
解決方案:要從您的路徑讀取圖像,您需要考慮:
os.path.join
創建要從中讀取圖像的路徑列表。tf.image.decode_png
。import tensorflow as tf
import os
path = 'images'
path_images = [os.path.join(path, img) for img in os.listdir(path)]
img_dataset = tf.data.Dataset.from_tensor_slices(path_images)
def get_image(filename):
img = tf.io.read_file(filename)
img = tf.image.decode_png(img, channels=3)
return img
img_dataset = img_dataset.map(get_image, num_parallel_calls=tf.data.AUTOTUNE)
for img in img_dataset.take(1):
print(img.shape)
# (100, 100, 3)
在路徑/images/
中創建隨機圖像:
from PIL import Image
import numpy as np
for i in range(10):
imarray = np.random.rand(100,100,3) * 255
im = Image.fromarray(imarray.astype('uint8')).convert('RGB')
im.save(f'images/image_{i}.png')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.