首页 > 解决方案 > TensorFlow.js 调整 3D 张量大小

问题描述

我有一个具有以下尺寸的 3D 张量:宽度 x 高度 x 深度。我需要将可变大小的体积调整为特定的形状,比如 256 x 256 x 256。不幸的是,在 TensorFlow.js 中,它们用于调整大小的一组方法,例如tf.image.resizeBilineartf.image.resizeNearestNeighbor仅适用于 2D 图像. 有没有一种解决方法可以让这些方法在 3D 空间中工作?

标签: tensorflowimage-processingtensorflow.js

解决方案


要调整张量的大小,如果输入大小与输出大小匹配,可以使用tf.reshape

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

reshape 的一种应用是从初始数据集创建批次时

如果输入和输出大小不匹配,可以使用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

后者可用于裁剪具有形状的图像[ 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])
 }

推荐阅读