我正在使用tensorflow的cocoSsd模型。但是,我希望能够查看多张图片并将结果动态打印到页面上,因此我决定使用PHP并仅回显整个脚本。除了一件事,这完美无瑕。在每个循环(遍历所有图像)到达最后一个图像之前,cocoSsd.load()命令似乎不会完成。这将导致所有结果不正确。我的代码如下
<?php
echo "<script src='https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js'></script>";
echo "<script src='https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd@latest'></script>";
echo "<script> cocoSsd.load(); </script>";
sleep(5);
$a = 0;
$files = scandir('/var/www/html/pics');
echo "'$files[2]'";
foreach($files as $file) {
if($file !== "." && $file !== "..") {
echo "<img id='$a' src=/pics/$file>";
echo "<script> cocoSsd.load(); </script>";
echo "<script>";
echo "console.log('$a');";
echo "var imag = document.getElementById('$a');";
echo "cocoSsd.load().then(model => {";
sleep(6);
echo "model.detect(imag).then(predictions => {";
echo "predictions.forEach(function (prediction){";
echo "document.write(prediction.class+'<br>');";
echo "console.log(prediction.class);";
echo "console.log('$file');";
echo "});";
echo "});";
echo "});";
echo "</script>";
$a++;
}
}
?>
这仅在控制台中产生
person
'one of the three images'.jpeg
只有最后一个图像由人组成,这就是为什么我导致相信只有在处理了最后一个图像后才加载模型,导致列出的唯一结果是人。