dtracers
dtracers

Reputation: 1648

How to create a Rotation Matrix in Tensorflow

I want to create a rotation matrix in tensorflow where all parts of it are tensors.

What I have:

def rotate(tf, points, theta):
    rotation_matrix = [[tf.cos(theta), -tf.sin(theta)],
                       [tf.sin(theta), tf.cos(theta)]]
    return tf.matmul(points, rotation_matrix)

But this says that rotation_matrix is a list of tensors instead of a tensor itself. theta is also a tensor object that is passed in at run time.

Upvotes: 9

Views: 5968

Answers (4)

P-Gn
P-Gn

Reputation: 24581

You may want to have a look at Tensorflow Graphics, which has some nice helper functions regarding representation of 2D and 3D rotations.

import tensorflow_graphics.geometry.transformation as tfgt
tfgt.rotation_matrix_2d.from_euler([0.1])

# <tf.Tensor: id=48, shape=(2, 2), dtype=float32, numpy=
# array([[ 0.9950042 , -0.09983342],
#        [ 0.09983342,  0.9950042 ]], dtype=float32)>

Upvotes: 1

eqzx
eqzx

Reputation: 5559

To answer the question of 'How to build a Rotation Matrix', the following is cleaner than requiring a multiple pack (stack) calls:

tf.stack([(tf.cos(angle), -tf.sin(angle)), (tf.sin(angle), tf.cos(angle))], axis=0)

Upvotes: 4

fabmilo
fabmilo

Reputation: 48310

with two operations:

def rotate(tf, points, theta):
    rotation_matrix = tf.pack([tf.cos(theta),
                              -tf.sin(theta),  
                               tf.sin(theta),
                               tf.cos(theta)])
    rotation_matrix = tf.reshape(rotation_matrix, (2,2))
    return tf.matmul(points, rotation_matrix)

Upvotes: 10

dtracers
dtracers

Reputation: 1648

An Option I found that works is to use pack but if there is a better way please post an answer:

def rotate(tf, points, theta):
    top = tf.pack([tf.cos(theta), -tf.sin(theta)])
    bottom = tf.pack([tf.sin(theta), tf.cos(theta)])
    rotation_matrix = tf.pack([top, bottom])
    return tf.matmul(points, rotation_matrix)

Upvotes: 1

Related Questions