我正在尝试进行不同类型的(图像)数据增强来训练我的神经网络。
我知道 tf.image 提供了一些增强功能,但它们太简单了 - 例如,我只能将图像旋转 90 度,而不是任何度数。
我还知道 tf.keras.preprocessing.image 提供随机旋转、随机剪切、随机移位和随机缩放。然而,这些方法只能应用于 numpy 数组,而不是张量。
我知道我可以先读取图像,使用 tf.keras.preprocessing.image 中的函数进行增强,然后将这些增强的 numpy 数组转换为张量。
但是,我只是想知道是否有一种方法可以实现张量方面的增强,这样我就不需要为“图像文件 -> 张量 -> numpy 数组 -> 张量”过程而烦恼。
更新给那些想知道如何应用你的转换的人:
详细源码可以查看tf.contrib.image.transform和 tf.contrib.image.matrices_to_flat_transforms .
这是我的代码:
def transformImg(imgIn,forward_transform):
t = tf.contrib.image.matrices_to_flat_transforms(tf.linalg.inv(forward_transform))
# please notice that forward_transform must be a float matrix,
# e.g. [[2.0,0,0],[0,1.0,0],[0,0,1]] will work
# but [[2,0,0],[0,1,0],[0,0,1]] will not
imgOut = tf.contrib.image.transform(imgIn, t, interpolation="BILINEAR",name=None)
return imgOut
基本上,上面的代码是在做
A shear transform平行于 x 轴,例如 ,是
因此,我们可以像这样实现剪切变换(使用上面定义的transformImg()
):
def shear_transform_example(filename,shear_lambda):
image_string = tf.read_file(filename)
image_decoded = tf.image.decode_jpeg(image_string, channels=3)
img = transformImg(image_decoded, [[1.0,shear_lambda,0],[0,1.0,0],[0,0,1.0]])
return img
img = shear_transform_example("white_square.jpg",0.1)
(请注意,img
是张量,不包括将张量转换为图像文件的代码。)
附言
以上代码适用于 tensorflow 1.10.1,可能不适用于 future 的版本。
老实说,我真的不知道为什么他们将 tf.contrib.image.transform 设计成我们必须使用另一个函数 (tf.linalg.inv) 来获得我们想要的东西的方式。我真的希望他们可以更改 tf.contrib.image.transform 以在 a more intuitive way 中工作.
最佳答案
看看tf.contrib.image.transform
.它可以将一般投影变换应用于图像。
您还需要查看 tf.contrib.image.matrices_to_flat_transforms
将仿射矩阵转换为 tf.contrib.image.transform
接受的投影格式。
关于python - Tensorflow - 有没有办法实现张量图像剪切/旋转/平移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52214953/