随机3d图像切片tensorflow数据,NoneType形状的深度

Random 3d image slicing tensorflow data, depth of NoneType shape

我需要做的是随机切割 3D 二进制蒙版的一些切片(固定大小)。 数据存储在张量流数据集中 (tf.data)。确实必须是这种数据类型才能使用缓存来加速。

到目前为止我的源代码:

import tensorflow as tf      #version 2.2.0


mask.shape # (512,512,None,1), where (width, height, depth, channel), depth is NOT FIXED and depends on the image and therefore unknown

slice_number = 10
positive = tf.where(tf.equal(masks[:, :, :-slice_number,:],1))[:, 2] #slices with non zero values

# now we need to select slice id from positive mask slices randomly,
# which failes since the shape is always None due to the fact that image depth is unknown.

pos_id = random.randint(0, positive.shape[0])
mask = mask[:, :, positive[pos_id]:positive[pos_id] + slice_number]

如何获得形状?非常感谢任何想法

提前致谢!

假设你想从一个深度未知的张量维度中随机切出一个固定的slice_size,下面演示如何实现:

import tensorflow as tf

@tf.function
def random_slice(slice_size):
  # For demonstration purposes, generate your mask with random depth
  random_depth = tf.random.uniform(shape=[], dtype=tf.int32,
    minval=20, maxval=50)
  mask = tf.ones([512, 512, random_depth, 1], dtype=tf.int32)
  print(mask) # Mask with unknown depth: Tensor("ones:0", shape=(512, 512, None, 1), dtype=int32)
  depth = tf.shape(mask)[2]
  print(depth) # Unknown depth: Tensor("strided_slice:0", shape=(), dtype=int32)
  depth_begin = tf.random.uniform(shape=[], dtype=tf.int32,
    minval=0, maxval=depth-slice_size)
  print(depth_begin) # Random begin of slice based on unknown depth: Tensor("random_uniform_1:0", shape=(), dtype=int32)
  mask_sliced = tf.slice(mask,
    begin=[0, 0, depth_begin, 0],
    size=[512, 512, slice_size, 1])
  print(mask_sliced) # Random slice with known dimensions: Tensor("Slice:0", shape=(512, 512, 10, 1), dtype=int32)
  return mask_sliced

mask_sliced = random_slice(slice_size=10)
print(mask_sliced) # Resolved random slice