user2253546
user2253546

Reputation: 595

TensorFlow.js Resize 3D Tensor

I have a 3D tensor with the the following dimensions : Width x Height x Depth. I need to resize variable sized volumes to a specific shape say 256 x 256 x 256. Unfortunately, in TensorFlow.js the set of methods they have for resizing such as tf.image.resizeBilinear & tf.image.resizeNearestNeighbor only work for 2D images. Is there a workaround to get these methods to work in 3D space?

Upvotes: 3

Views: 1546

Answers (1)

edkeveked
edkeveked

Reputation: 18371

To resize a tensor, one can use tf.reshape if the input size matches the output size

const x = tf.tensor(Array.from({length :64}, (_, i) => i), [4, 4]);
x.reshape([1, 16])

One application of reshape is when creating batches from an initial dataset

If the input and the output size does not match, one can use tf.slice

const x = tf.tensor(Array.from({length :64}, (_, i) => i), [4, 4, 4]);
x.slice([1, 1, 1], [2, 2, 2]) // we are taking the 8 values at the center of the cube

The latter can be used to crop an image with the shape [ height, width, channels]

// t is a tensor
// edge is the size of an edge of the cube
const cropImage = (t, edge) => {
 shape = t.shape;
 startCoord = shape.map(i => (i - edge) / 2)
 return t.slice(startCoord, [edge, edge, edge])
 // to keep the number of channels 
 return t.slice([...startCoord.slice(0, shape.length - 1), 0], [edge, edge, channels])
 }

Upvotes: 3

Related Questions