python - Tensorflow - 有没有办法实现张量图像剪切/旋转/平移?

标签 python tensorflow keras

我正在尝试进行不同类型的(图像)数据增强来训练我的神经网络。

我知道 tf.image 提供了一些增强功能,但它们太简单了 - 例如,我只能将图像旋转 90 度,而不是任何度数。

我还知道 tf.keras.preprocessing.image 提供随机旋转、随机剪切、随机移位和随机缩放。然而,这些方法只能应用于 numpy 数组,而不是张量。

我知道我可以先读取图像,使用 tf.keras.preprocessing.image 中的函数进行增强,然后将这些增强的 numpy 数组转换为张量。

但是,我只是想知道是否有一种方法可以实现张量方面的增强,这样我就不需要为“图像文件 -> 张量 -> numpy 数组 -> 张量”过程而烦恼。


更新给那些想知道如何应用你的转换的人:

详细源码可以查看tf.contrib.image.transformtf.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

基本上,上面的代码是在做

enter image description here对于 imgIn 中的每个点 (x,y)。

A shear transform平行于 x 轴,例如 ,是

enter image description here

因此,我们可以像这样实现剪切变换(使用上面定义的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)

原图: enter image description here

转换后:enter image description here

(请注意,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/

相关文章:

python - 在没有 For 循环的 Python 中从 MySQL 中选择数组

python: lambda、yield-statement/expression 和循环(澄清)

Python:使用列表列表进行列表理解

python - 如何在测试集中找到错误的预测案例(使用 Keras 的 CNN)

Windows XP 中的 Python Cx_Freeze 错误

c++ - 为什么 Tensorflow 找不到我自定义 Op 的 GPU 内核?

python - RNN 从哪里获取批量大小?

machine-learning - 如何在 Keras 中使用其他 GPU 和 TensorFlow 后端?

python - Keras 中 Adam 优化器的衰减参数

python - tensorflow MNIST : terminate called after throwing an instance of 'std::bad_alloc'