【发布时间】:2021-06-25 03:51:41
【问题描述】:
我是 javascript 和异步函数的新手,我正在尝试使用 Express 在 NodeJs 中编写一个 API,该 API 从 Postman 获取 JPG 图像并将其放入我的图像分类机器学习模型(改编自 MobileNet)用于预测。图像需要经过预处理才能通过模型。我使用包 resize-optimize-images get-image-data 来调整图像大小并将其更改为适合我的模型的格式。
const app = express();
const multer = require('multer');
const tf = require('@tensorflow/tfjs-node');
const image = require('get-image-data');
const resizeOptimizeImages = require('resize-optimize-images');
let model;
(async function () {
model = await tf.loadLayersModel("http://localhost:5000/model/model.json");
})();
app.post('/classify', upload.single('file'), (req, res) => {
//call methods to resize and preprocess the image
resize();
var input = preprocess();
//have model predict
console.log(input);
let prediction = model.predict(input);
});
这是我的 resize 函数代码。
function resize() {
(async () => {
// Set the options.
const options = {
images: [imagePath],
width: 224,
height: 224,
quality: 90
};
// Run the module.
await resizeOptimizeImages(options);
console.log("resized");
})();
}
这是我的预处理函数代码。
function preprocess() {
image(imagePath, async (err, imageData) => {
// pre-process image
const numChannels = 3;
const numPixels = imageData.width * imageData.height;
const values = new Int32Array(numPixels * numChannels);
const pixels = imageData.data;
for (let i = 0; i < numPixels; i++) {
for (let channel = 0; channel < numChannels; ++channel) {
values[i * numChannels + channel] = pixels[i * 4 + channel];
}
}
const outShape = [imageData.height, imageData.width, numChannels];
const input = tf.tensor3d(values, outShape, 'float32');
console.log(input);
return input;
});
当我运行程序时,我在调用 predict 的行收到错误“TypeError: Cannot read property 'length' of undefined”。 resize 和 preprocess 函数没有完全执行,导致要预测的输入未定义。我认为通过 resizeImageOptimizer() 放置 await,程序将等待该过程完成后再继续。然而,它似乎在最后才这样做,即使它是首先被调用的。 对此问题的任何帮助将不胜感激。
【问题讨论】:
-
包含
model = await tf.loadLayersModel(...)的 IIFE 没有异步运行,您也没有等待它。所以它不会等待它。 -
将异步函数放入 IIFE 不会让包含的代码等待它。
标签: javascript node.js asynchronous async-await