我正在嘗試在 Keras 頁面上編輯此代碼:https ://keras.io/examples/vision/deeplabv3_plus/ 。我想做的一件事是為資料集添加一個增強功能。這是我寫的:
def image_augmentation(img):
img = tf.image.random_flip_left_right(img)
img = tf.image.random_flip_up_down(img)
img = tf.image.random_brightness(img, 0.2)
img = tf.image.random_crop(value = img, size=(2, 2))
img = tf.keras.preprocessing.image.random_rotation(img, 90, row_axis=0, col_axis=1,channel_axis=2)
但是,最后兩行會引發我遇到問題的錯誤。
此行img = tf.image.random_crop(value = img, size=(2, 2))引發此錯誤:
ValueError: Dimensions must be equal, but are 3 and 2 for '{{node random_crop/GreaterEqual}} = GreaterEqual[T=DT_INT32](random_crop/Shape, random_crop/size)' with input shapes: [3], [2].
此行img = tf.keras.preprocessing.image.random_rotation(img, 90, row_axis=0, col_axis=1,channel_axis=2)引發此錯誤:
AttributeError: in user code:
File "<ipython-input-3-8db8a894e0d0>", line 41, in data_loader *
mask = image_process(mask_list, mask=True)
File "<ipython-input-3-8db8a894e0d0>", line 28, in image_process *
img = image_augmentation(img)
File "<ipython-input-7-037af66af3d3>", line 18, in image_augmentation *
img = tf.keras.preprocessing.image.random_rotation(img, 90, row_axis=0, col_axis=1,channel_axis=2)
File "/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/affine_transformations.py", line 56, in random_rotation *
x = apply_affine_transform(x, theta=theta, channel_axis=channel_axis,
File "/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/affine_transformations.py", line 323, in apply_affine_transform *
x = np.rollaxis(x, channel_axis, 0)
File "<__array_function__ internals>", line 6, in rollaxis **
File "/usr/local/lib/python3.7/dist-packages/numpy/core/numeric.py", line 1290, in rollaxis
n = a.ndim
AttributeError: 'Tensor' object has no attribute 'ndim'
uj5u.com熱心網友回復:
對于該行中的第一個錯誤,
img = tf.image.random_crop(value = img, size=(2, 2))
在該方法的檔案tf.image.random_crop中明確提到,
如果不應裁剪尺寸,請傳遞該尺寸的完整尺寸。例如,可以使用 size = [crop_height,crop_width, 3] 裁剪 RGB?? 影像。
因此,為了修復錯誤,
img = tf.image.random_crop(value = img, size=(2, 2, 3))
對于該行中的第二個錯誤,
img = tf.keras.preprocessing.image.random_rotation(img, 90, row_axis=0, col_axis=1,channel_axis=2)
此方法要求它img是 NumPy 陣列(張量)而不是Tensor物件。此外,該方法以 NumPy 陣列的形式回傳旋轉后的影像。
如果函式的所需輸出image_augmentation是 andarray那么您只需要進行以下更改,
img = tf.keras.preprocessing.image.random_rotation(img.numpy(), 90, row_axis=0, col_axis=1,channel_axis=2)
或者,如果所需的輸出型別是 a Tensor,我們可以使用tfa.image.rotate來自 TensorFlow Addons 包的方法,
import math
import random
upper = 90 * (math.pi/180.0) # degrees -> radian
lower = 0 * (math.pi/180.0)
def rand_degree():
return random.uniform( lower , upper )
def image_augmentation(img):
...
img = tfa.image.rotate( img , rand_degree() )
# img is a Tensor
return img
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/419551.html
標籤:
