微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 numpy.ndarray 或列表初始化时,Tensorflow tf.ragged.constant 卡住

如何解决从 numpy.ndarray 或列表初始化时,Tensorflow tf.ragged.constant 卡住

我正在尝试将图像目录加载到张量数组并将其嵌套在包含这些文件夹的数组中。对于这个任务,tf.ragged.constant 似乎是合适的,因为它可以接受不同大小的输入维度。

我有 30 个目录,每个目录大约有 50-100 张图片

出于某种原因,我无法初始化 tf.ragged.constant。当我尝试时,它永远不会通过初始化。我尝试在初始化之前将数组转换为 NumPy 数组或列表,但无济于事。

import numpy as np
from PIL import Image
import glob
import os
import tensorflow as tf

# Points to folders with images that needs to be converted
filelist2 = glob.glob('dataset_videoes\\train\\01April_2010_Thursday_heute-6695\\*.png')

train_dir = "dataset_videoes\\train"
path,dirs,files = next(os.walk(train_dir))

np_array_imgs_all_dirs = []

# Converts each image to a numpy array and stores it in the np_array_imgs_all_dirs list
for dir_path in dirs:
    filelist = glob.glob('dataset_videoes\\train\\' + dir_path + '\\*.png')
    x = np.array([np.array(Image.open(fname)) for fname in filelist])
    np_array_imgs_all_dirs.append(x)

print(x.shape) # (53,224,3)

# Creates a second array with the images in a folder
x2 = np.array([np.array(Image.open(fname)) for fname in filelist2])

# Adds x1 and x2 to the same array. This tests that the errors are still present with only two directories,and also that it is not due to a error from casting to np.array from list.
two_directories_as_numpy = np.array([x,x2])

# Converts a single directory of numpy image arrays to a tensor. This works.
tf.convert_to_tensor(x) 

# Tries to converts two of the image folders that were stored in a array to a tensor. 
# This does not work,due to the tensor having varying input size in the first dimensionm,i SUSPECT
# Gives following errors when passed list or numpy array:
# Can't convert non-rectangular Python sequence to Tensor.
# Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).

#tf.convert_to_tensor(two_directories_as_numpy) 
print(two_directories_as_numpy.shape) # (2,) 

# To solve this I convert them to tf.ragged.constant,but initalizing makes 
# it stuck regardless of the datatype i test with.
print("Before initalization")
data_tensor = tf.ragged.constant(two_directories_as_numpy)
print("Initalization completed")
data_tensor = tf.ragged.constant(np_array_imgs_all_dirs)
data_tensor = tf.ragged.constant(x)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。