Tensorflow.js中的图像大小调整方法(resizeBilinear和resizeNearestNeighbor



问题

  1. resizeBiliner(*1(和resizeNearestNeighbor(*2(之间有什么区别?特别是,resizeNearestNeighbor不会返回正确的图像(一半图像为黑色(。(图像的一半是黑色的。(
  2. ResizeBiliner不会返回正确的分割结果。(图像的一半为灰色。(为什么?这与resizeNearestNeighbor的结果非常相似

背景

我想开发一个在Tensorflow.js中进行分段的应用程序。幸运的是,我在Python中找到了一些用于分段的示例代码。(*3(我相信我可以在Tensorflow.js中通过将那里获得的Keras模型转换为TFJS模型来进行分割。我试过在Tensorflow.js中调整图像的大小,但无法得到正确的结果。有人有什么好主意吗?

代码

这是我写的源代码。(我不习惯写JavaScript。(

<!DOCTYPE html>
<html>
<head></head>
<meta charset="utf-8"/>
<body>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<canvas id="canvas1" width="256" height="256" style="border: 2px solid;"></canvas>
<canvas id='canvas2' width="128" height="128" style="border: 2px solid;"></canvas>
<canvas id='canvas3' width="128" height="128" style="border: 2px solid;"></canvas>
<canvas id='canvas4' width="128" height="128" style="border: 2px solid;"></canvas>
<canvas id='canvas5' width="128" height="128" style="border: 2px solid;"></canvas>
<script>
var inputImg = new Image();inputImg.src = "../00_resources/woman172.jpg";
const canvas1 = document.getElementById('canvas1');
const canvas2 = document.getElementById('canvas2');
const canvas3 = document.getElementById('canvas3');
const canvas4 = document.getElementById('canvas4');
const canvas5 = document.getElementById('canvas5');
const SIZE = 128;
const COL_CHANNEL = 3;
const BIN_CHANNEL = 1;
inputImg.onload = () => {
const inCtx = canvas1.getContext('2d');
inCtx.drawImage(inputImg, 0, 0, canvas1.width, canvas1.height);
};

(async() => {
// load model
let model = await tf.loadGraphModel('/tfjsdoc/Portrait-Segmentation/model/deconv_bnoptimized_munet_to_tfjs_graph_model/model.json');
// image1 (original image)
let img1 = tf.browser.fromPixels(canvas1, COL_CHANNEL);
tf.browser.toPixels(img1, canvas2);// OK
// image2 (resized image - using 'resizeNearestNeighbor')
let img2 = img1.resizeNearestNeighbor([SIZE, SIZE]).toFloat().div(tf.scalar(255));
tf.browser.toPixels(img2, canvas3);// NG
// image3 (resized image - using 'resizeBilinear')
let img3 = img1.resizeBilinear([SIZE, SIZE]).toFloat().div(tf.scalar(255));
tf.browser.toPixels(img3, canvas4);// OK?
// predict (image3 is used to make predictions, but the same problem occurs as in image2)
let pred = await model.predict(tf.reshape(img3, [-1,SIZE,SIZE,COL_CHANNEL])).data();
tf.browser.toPixels(tf.tensor(pred, [SIZE,SIZE, BIN_CHANNEL]), canvas5);// NG
})();
</script>
</body>
</html>

获取执行结果

从左到右。

  • 原始图像
  • 原始图像是在画布上拍摄和绘制的
  • 使用resizeNearestNeighbor调整大小并在画布上绘制的原始图像(图像的一半为黑色(
  • 使用resizeBiliner调整大小并在画布上绘制的原始图像(看起来是正确的(
  • 使用resizeBilinear调整大小并在画布上绘制的原始图像的分割(图像的一半是灰色的(

参考

(*1(https://js.tensorflow.org/api/latest/#image.resizeBilinear

(*2(https://js.tensorflow.org/api/latest/#image.resizeNearestNeighbor

(*3(https://github.com/anilsathyan7/Portrait-Segmentation

根据我的经验,两者似乎都完成了类似的输入图像大小调整。ResizeBilinear对图像执行双线性插值。

相关内容

最新更新