Calculate Z Rotation of a face in Tensorflow.js

Viewed 370

Note: This question has NOTHING to do with Three.js, it's only Tensorflow.js and Trigonometry.

I am trying to rotate a 3D object in Three.js by rotating my face. I have used this code by akhirai560 for rotating in X and Y axis.:

function normal(vec) {
  let norm = 0;
  for (const v of vec) {
    norm += v * v;
  }
  return Math.sqrt(norm);
}

function getHeadAnglesCos(keypoints) {
  // Vertical (Y-Axis) Rotation
  const faceVerticalCentralPoint = [
    0,
    (keypoints[10][1] + keypoints[152][1]) * 0.5,
    (keypoints[10][2] + keypoints[152][2]) * 0.5,
  ];
  const verticalAdjacent = keypoints[10][2] - faceVerticalCentralPoint[2];
  const verticalOpposite = keypoints[10][1] - faceVerticalCentralPoint[1];
  const verticalHypotenuse = normal([verticalAdjacent, verticalOpposite]);
  const verticalCos = verticalAdjacent / verticalHypotenuse;

  // Horizontal (X-Axis) Rotation
  const faceHorizontalCentralPoint = [
    (keypoints[226][0] + keypoints[446][0]) * 0.5,
    0,
    (keypoints[226][2] + keypoints[446][2]) * 0.5,
  ];
  const horizontalAdjacent = keypoints[226][2] - faceHorizontalCentralPoint[2];
  const horizontalOpposite = keypoints[226][0] - faceHorizontalCentralPoint[0];
  const horizontalHypotenuse = normal([horizontalAdjacent, horizontalOpposite]);
  const horizontalCos = horizontalAdjacent / horizontalHypotenuse;

  return [horizontalCos, verticalCos];
}

It calculates the rotation by finding the cos of these points (original image source):

Vertical and Horizontal Landmarks

I also want to calculate the cos of Z axis rotation. Thanks!

1 Answers

Am not fully clear of the end goal of the question, but if simply looking to rotate about the Z axis, the following snippet will assist.

center = { x: 50, y: 50 };

points = [
  { x: 60, y:  60 },
  { x: 50, y: 100 }
]

function rotateAboutZ( xyRotationPoint, points, zRotation ) {

  let result = points.map( p => {
    // Adjust the point based on the center of rotation.
    let x = p.x - xyRotationPoint.x;
    let y = p.y - xyRotationPoint.y;
    // Calculate the radius and angle in preparation for rotation
    // about the Z axis.
    let radius = Math.sqrt( x * x + y * y );
    let angle = Math.atan2( y, x );
    // Adjust the angle by the requested rotation.
    let angleRotated = angle + zRotation;
    // Finally, calculate the new XY coordinates, and re-adjust 
    // based on the center of rotation.
    let xRotated = radius * Math.cos( angleRotated ) + xyRotationPoint.x;
    let yRotated = radius * Math.sin( angleRotated ) + xyRotationPoint.y;
    return { x: xRotated, y: yRotated };
  } );
  
  return result;

}

// Let's rotate the points by 180 degrees around the
// center point of (50,50).
let result = rotateAboutZ( center, points, Math.PI );
console.log( result );

Related