【发布时间】:2019-01-21 03:15:15
【问题描述】:
我已经训练了一个 keras 模型,现在我想在网络上运行它。我认为这可能是尝试测试 Tensorflow.js 的好方法。我下载了 Tesnroflow.js “Webcam-transfer-learning”教程,然后对其进行了修改以获得我目前拥有的内容。工作中的 keras 模型在将图像尺寸减小到 48x48 后执行情感分类。现在在 keras 模型中,我拍摄网络摄像头的快照,复制它,然后绘制我的框和标签。我试图在 tf.js 中做同样的事情,所以我设置了一个画布,获取了对它的引用,并在转换为灰度后尝试在画布上绘图。
我看到一个奇怪的行为,它正确显示了灰度图像,但它显示了 3 次,并且不确定我做错了什么。我已经包括了我认为问题可能存在于下面的区域。如果需要更多信息,我可以分享更多。我希望已经尝试过执行类似操作的人可以立即看到我明显做错了什么。任何信息都会有帮助。谢谢!
修改webcam.js,增加函数
preProc() {
return tf.tidy(() => {
// Reads the image as a Tensor from the webcam <video> element.
const webcamImage = tf.fromPixels(this.webcamElement);
//Resize to our image and get back single channel for greyscale
const croppedImage = this.cropImage(webcamImage, 1);
// Expand the outer most dimension so we have a batch size of 1.
const batchedImage = croppedImage.expandDims(0);
// Normalize the image between -1 and 1. The image comes in between 0-255,
// so we divide by 127 and subtract 1.
return batchedImage.toFloat().div(tf.scalar(127)).sub(tf.scalar(1));
});
}
/**
* Crops an image tensor so we get a square image with no white space.
* @param {Tensor4D} img An input image Tensor to crop.
*/
cropImage(img, dim=3) {
const size = Math.min(img.shape[0], img.shape[1]);
const centerHeight = img.shape[0] / 2;
const beginHeight = centerHeight - (size / 2);
const centerWidth = img.shape[1] / 2;
const beginWidth = centerWidth - (size / 2);
return img.slice([beginHeight, beginWidth, 0], [size, size, dim]);
}
来自 ui.js 我正在使用 drawFrame
export function drawFrame(image, canvas) {
const [width, height] = [300, 165];
const ctx = canvas.getContext('2d');
const imageData = new ImageData(width, height);
const data = image.dataSync();
for (let i = 0; i < height * width; ++i) {
const j = i * 4;
imageData.data[j + 0] = (data[i * 3 + 0] + 1) * 127;
imageData.data[j + 1] = (data[i * 3 + 1] + 1) * 127;
imageData.data[j + 2] = (data[i * 3 + 2] + 1) * 127;
imageData.data[j + 3] = 255;
}
ctx.putImageData(imageData, 0, 0);
}
最后在 index.js 中,当按下预测按钮时,会执行下面的处理程序
async function predict() {
while (isPredicting) {
const predictedClass = tf.tidy(() => {
// Capture the frame from the webcam.
const imgmod = webcam.preProc();
ui.drawFrame(imgmod, grayframe);
// Returns the index with the maximum probability. This number corresponds
// to the class the model thinks is the most probable given the input.
//return predictions.as1D().argMax();
return imgmod;
});
const classId = (await predictedClass.data())[0];
predictedClass.dispose();
//ui.predictClass(classId);
await tf.nextFrame();
}
ui.donePredicting();
}
【问题讨论】:
标签: python-3.x tensorflow keras tensorflow.js