错误:无法编译片段着色器。而使用Tensorflow.js的slice()

时间:2020-05-26 16:10:00

标签: javascript tensorflow tensorflow.js

我正在使用 Tensorflow.js 开发用于图像分类的Web应用程序。我用我的网络摄像头拍摄了图像,并且想使用以前获得的边界框的坐标提取图像的一部分。边界框结构为:[x, y, width, height]。原始网络摄像头照片的形状为[ 480, 640, 1 ]

我使用以下代码使用Tensorflow.js提取边界框:

function cropImage(webcamElement, bbox){
    const webcamImage = tf.browser.fromPixels(webcamElement)
                                    .mean(2)
                                    .toFloat()
                                    .expandDims(-1);

    let crop_width = bbox[2];
    let crop_height = bbox[3];

    // Get valid bbox width in canvas
    if (bbox[2] > webcamImage.shape[1] - bbox[0]){
        crop_width =  webcamImage.shape[1] - bbox[0];
    }

    // Get valid bbox height in canvas
    if (bbox[3] > webcamImage.shape[0] - bbox[1]){
        crop_height =  webcamImage.shape[0] - bbox[1];
    }

    let crop = webcamImage.slice(
        [bbox[1], bbox[0], 0],
        [crop_height, crop_width, 1]
    );
    console.log(crop);

但是它在slice()的执行级别返回以下消息Error: Failed to compile fragment shader.

尽管进行了研究,但我还没有发现任何可以帮助我解决问题的方法。你有什么想法?预先谢谢你

2 个答案:

答案 0 :(得分:1)

如果要裁剪图像,为什么不直接使用“画布”而不是使用张量?

删除所有tf.browser.fromPixels内容,而是将canvas传递给保存绘制图像的函数,然后对其进行裁剪。例如:

将getImageData方法与边界框数据一起使用:

var imageData = ctx.getImageData(bbox[0], bbox[1], bbox[2], bbox[3]);

然后创建具有所需大小的第二个画布,并使用puImageData设置像素:

var canvas2 = document.createElement("canvas");
canvas2.width = bbox[2];
canvas2.height = bbox[3];
var ctx2 = canvas2.getContext("2d");
ctx2.putImageData(imageData, 0, 0);

如果要将其另存为图像,则可以执行以下操作:

dstImg.src = canvas1.toDataURL("image/png");

答案 1 :(得分:0)

传递给tf.slice的参数错误。应该是

tensor.slice([y, x], [h, w]) 

其中(y, x)是开始切片的坐标,(h, w)是切片的高度和高度。

const a = tf.ones([480, 640, 1]).slice([25, 60], [20, 30])
console.log(a.shape) // [20, 30, 1]
相关问题