TENSORFLOW:A implementation of rotation OPS (rotation function implementation method)

Source: Internet
Author: User
The function realization method of TensorFlow rotation matrix

Keywords: rot90, tensorflow

1. Background

In the process of data enhancement, it is necessary to operate the image rotation and movement, for some special convolution (Garbo conv) operation, and also to rotate the convolution core.
The rotation of the 4D tensor does not appear to be implemented in the TensorFlow.
Strictly speaking: TensorFlow to the tensor of the flip operation is not implemented, only for the 3D tensor Tf.image.rot ()
In most cases, the use of a 4D form of tensor, [b,w,h,c] or a 3D image composed of Batchs.

By looking at the code in this article, you know that 1 can be rotated using NumPy's rot90 () function, but the Rot90 object is Ndarray, which is obviously unusable for tensorflow.tensor objects and throws something like: 无法找到m.dim属性 exception.
This means that the function cannot be used numpy.rot90() .

Also known, TensorFlow provides a function to flip, transpose, slice operations of the matrix, but does not provide rotation 90 °, 180°,270° operation.
So you can refer numpy.rot90(m, k=1, axes=(0,1)) to the program fragments to do their own implementation.
The first parameter m in Rot90 is the operand, K is the number of rotations, k=1 is rotated 90 degrees counterclockwise, k=2 is rotated 180 degrees counterclockwise, and so on
Axes is a plane that represents the two dimensions of the rotation operation.

The source code for ROT90 is as follows:

def rot90(m, k=1, axes=(0,1)):    '''    ......    '''    # 省略检测参数的操作    k %= 4    if k == 0:        return m[:]    if k == 2:        return flip(flip(m, axes[0]), axes[1])    axes_list = arange(0, m.ndim)    (axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]],                                                axes_list[axes[0]])    if k == 1:        return transpose(flip(m,axes[1]), axes_list)    else:        # k == 3        return flip(transpose(m, axes_list), axes[1])

PS: By reading the above code, you can also find that the exception thrown by the direct use of rot90 in TensorFlow is shown here

if axes[0] == axes[1] or absolute(axes[0] - axes[1]) == m.ndim

The reason is that the program treats the tensor object np.ndarray as an action, and the tensor object has no m.dim attributes

2. Implement the ROT90 Operation 2.1 carding procedure

By viewing the source code, you can comb out the program flowchart:

2.2 TensorFlow for rotational operation

According to the flowchart above, the rot90 operation of TensorFlow can be realized.

def rot90 (tensor,k=1,axes=[1,2],name=none): ' Autor:lizh tensor:a tensor 4 or more dimensions K:integer, N    Umber of times the array is rotated by degrees.        Axes: (2,) array_like the array is rotated in the plane defined by the axes.        Axes must be different.    -----Returns-------Tensor:tf.tensor A rotated view of ' tensor '. See also:www.tensorflow.org/api_docs/python/tf/image/rot90 "axes = tuple (axes) if Len (axes)! = 2:rai            Se valueerror ("len (axes) must be 2.")  Tenor_shape = (Tensor.get_shape (). As_list ()) Dim = Len (Tenor_shape) if axes[0] = = Axes[1] or Np.absolute (Axes[0]            -axes[1]) = = Dim:raise ValueError ("axes must be different.") if (Axes[0] >= Dim or axes[0] <-dim or axes[1] >= Dim or axes[1] <-dim): Raise Valuee            Rror ("axes={} out of range for tensor of ndim={}." . Format (axes, dim)) k%=4 If K==0:retUrn tensor if k==2:img180 = Tf.reverse (Tf.reverse (tensor, axis=[axes[0]]), axis=[axes[1]],name=name) Retu RN img180 axes_list = Np.arange (0, Dim) (Axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]],axes_list [Axes[0]]) # Replace print (axes_list) if K==1:img90=tf.transpose (Tf.reverse (Tensor,axis=[axes[1]]), perm=axes_list, name =name) return IMG90 if K==3:img270=tf.reverse (Tf.transpose (tensor, perm=axes_list), axis=[axes[1]],name= Name) return img270
2.3 Code Testing
# 加载库import numpy as npimport matplotlib.pyplot as pltimport tensorflow as tf# 手写体数据集 加载from tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("/home/lizhen/data/MNIST/", one_hot=True)sess=tf.Session()#选取数据 4Dimages = mnist.train.imagesimg_raw = images[0,:] # [0,784]img=tf.reshape(img_raw,[-1,28,28,1]) # img 现在是tensor# 绘图def fig_2D_tensor(tensor):# 绘图    #plt.matshow(tensor, cmap=plt.get_cmap('gray'))    plt.matshow(tensor) # 彩色图像    # plt.colorbar() # 颜色条    plt.show()# 显 显示 待旋转的图片fig_2D_tensor(sess.run(img)[0,:,:,0]) # 提取ndarray

Simply test the code:
img11_rot=rot90(img,2) # 旋转两次90fig_2D_tensor(sess.run(img11_rot)[0,:,:,0]) # 打印图像img12_rot=rot90(img,1,[1,1]) # 抛出异常,  测试 Axes must be different.img13_rot=rot90(img,1,[0,6]) # 抛出异常,  测试 Axes must be different.img14_rot=rot90(img,axes=[1,5])# 抛出异常,测试out of range.img14_rot=rot90(img,axes=[-1,2]) # -1的下标是倒数第二个,测试out of range.
Test results:

3 Summary

Okey, now it's ready to use.
.....

,,,,, recently found the latest version of TensorFlow, about the new version released a few days ago (14 days ago, 1.10.1) has added the operation of the 2d,3d image, support the [B,W,H,C] format tensor make rotation 2

Friday, 07. September 2018 02:49 pm

Reference documents
  1. Understanding 2D Dilated convolution operation with Examples in Numpy and TensorFlow with Interactive Code

  2. Tensorflow/python/ops/image_ops#rot90

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.