【问题标题】:How to convert tensor from 2D to 4D如何将张量从 2D 转换为 4D
【发布时间】:2021-02-19 07:12:02
【问题描述】:

我目前正在使用 DICOM 文件,而用于 DICOM 文件的 TensorFlow IO 库似乎会引发一些错误。所以我最初做的是这样的:

    # read file bytes
    image_bytes = tf.io.read_file(image_path)

    # Convert to a tensor
    image_as_tensor = tfio.image.decode_dicom_image(image_bytes, dtype=IMAGE_TYPE)

    print(image_as_tensor.get_shape())
(1, 519, 519, 1)

无论如何,我决定用pydicom 加载DICOM 文件,这似乎可以将数据加载到numpy 数组中。然而,当我create a tensor from the data 时,我似乎无法获得正确的尺寸:

        # read into dicom file
        ds = pydicom.dcmread(image_path)
        print(ds.pixel_array.shape)

        # take pixel array, and lets create a tensor
        image_as_tensor = tf.convert_to_tensor(ds.pixel_array, dtype=IMAGE_TYPE)
        print(image_as_tensor.get_shape())
(519, 519)

最终,我确实希望程序的某些后续部分使用 (Z, X, Y, D) 格式,但不确定如何将 2D 张量放入该版本。

谢谢!

【问题讨论】:

  • X.reshape(1, x_shape, y_shape, 1)

标签: python numpy tensorflow


【解决方案1】:

你可以直接使用numpy.reshape(),例如:

import numpy as np

arr = np.zeros((20, 30))
shape = arr.shape

print(shape)
# (20, 30)

arr = arr.reshape(1, *shape, 1)
print(arr.shape)
# (1, 20, 30, 1)

【讨论】:

    【解决方案2】:

    你可以从numpy使用expand_dims

    X = np.zeros((519, 519))
    X.shape # (519, 519)
    X_ = np.expand_dims(X, [0, 3])
    X_.shape # (1, 519, 519, 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      相关资源
      最近更新 更多