【问题标题】:How can solve random_rotation error in tensorflow?如何解决张量流中的随机旋转错误?
【发布时间】:2021-06-19 16:51:04
【问题描述】:

我有一些图像,每个图像都有 [128, 128, 60] 大小。我想使用tf.keras.preprocessing.image.random_rotation 函数对它们进行一些扩充。

对于随机旋转我有这个功能:

def augment_rotate_tf(x):
    x = tf.keras.preprocessing.image.random_rotation(x,
                                                      50, 
                                                      row_axis=0,
                                                      col_axis=1,
                                                      channel_axis=2)

    return x

当我将 numpy 数组传递给此函数时,它可以正常工作,但是当我在 tensorflow 图中使用它时,会出现此错误:

AttributeError: in user code:

    <ipython-input-99-790177542fdb>:15 augmentation  *
        img = tf.cond(cond, lambda: augment_rotate_tf_(img), lambda:  img)
    <ipython-input-124-28f8f87fa48b>:4 augment_rotate_tf_  *
        x = tf.keras.preprocessing.image.random_rotation(x,
    C:\Users\user\AppData\Roaming\Python\Python38\site-packages\keras_preprocessing\image\affine_transformations.py:56 random_rotation  *
        x = apply_affine_transform(x, theta=theta, channel_axis=channel_axis,
    C:\Users\user\AppData\Roaming\Python\Python38\site-packages\keras_preprocessing\image\affine_transformations.py:323 apply_affine_transform  *
        x = np.rollaxis(x, channel_axis, 0)
    <__array_function__ internals>:5 rollaxis  **
        
    C:\Users\user\anaconda3\envs\tf2.3\lib\site-packages\numpy\core\numeric.py:1259 rollaxis
        n = a.ndim

    AttributeError: 'Tensor' object has no attribute 'ndim'

如何解决这个问题?

【问题讨论】:

  • 您使用的是什么版本的 Tensorflow?还有为什么你的图片有 60 个通道?
  • 我使用 2.3。我想要处理 ct 图像。
  • 您可以尝试使用pip install tensorflow==2.4.1 升级Tensorflow 吗?或者,如果这不起作用,请尝试使用ImageDataGenerator 来增强图像。
  • 他们没有工作。有没有办法使用 tensrflow 进行旋转而不是 keras?
  • 您是否尝试过使用apply_transform 方法?我们可以对图像应用任何所需的转换。您可以尝试使用apply_transform(x=img,transform_parameters={'theta':50}),其中 theta 是以度为单位的旋转角度。更多详情可以参考this SO answer。谢谢!

标签: python tensorflow rotation


【解决方案1】:

我在这里A possible workaround is to incorporate the layers into the input pipeline. 找到了一个优雅的knuckles hack:

random_rotator=tf.keras.layer.experimental.preprocessing.RandomRotation(factor=0.055, fill_mode='constant',fill_value=0.)
<....>
ds= ds.batch(batch_size).prefetch(1)
ds = ds.map(lambda d,l: (random_rotator.call(d,training=True), l), num_parallel_calls=AUTO)

这是我对 hack 的使用。如果您之前应用批处理,它会起作用,因为输入需要 rank=4,其中第一个维度是批处理大小 > 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-15
    • 2020-06-17
    • 2018-07-31
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多