关于在 tensorflow.js 的 posenet 中记录姿势对象的问题

Issue regarding logging the pose object in posenet of tensorflow.js

当我运行上面的代码时,只有最后一张图像的姿势对象被记录了5次。

我想记录每张图片的姿势对象。 我正在使用 node.js

的 http 服务器

以下代码没有错误,如有任何帮助,我们将不胜感激,并在此先致谢。

<html>

<head>
    <meta charset="UTF-8">
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
    <!-- Load Posenet -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/posenet"></script>
</head>

<body>
    <img id='cat' crossorigin="anonymous" />
    <button onclick="myfun()">button</button>
    <script>
        function myfun() {
            arr = ["http://127.0.0.1:8080/pic1.jpeg", "http://127.0.0.1:8080/pic2.jpeg", "http:  //127.0.0.1:8080/pic3.jpeg", "http://127.0.0.1:8080/pic4.jpeg", "http://127.0.0.1:8080/pic5.jpeg"]
            var x;
            for (x of arr) {
                document.getElementById("cat").src = x;
                var flipHorizontal = false;
                var imageElement = document.getElementById('cat');
                imageElement.crossOrigin = "Anonymous";
                posenet.load({
                    architecture: 'MobileNetV1',
                    outputStride: 16
                }).then(function(net) {
                    const pose = net.estimateSinglePose(imageElement, {
                        flipHorizontal: true
                    });
                    return pose;
                }).then(function(pose) {
                    console.log(pose);
                })
            }
        }
    </script>
</body>

</html>

将循环从 for (x of arr) { 更改为 for (var x = 0; x < arr.length; x++) { x = arr[x]; ... ... }

它会正常工作。

for 循环是运行 异步操作。当两个 posenet 调用都已解决时,图像已设置为 for 循环的最后一项。

使用 async ... await 将防止仅对循环的最后一项进行 posenet 估计。

async function myfun() {
        arr = ["http://127.0.0.1:8080/pic1.jpeg", "http://127.0.0.1:8080/pic2.jpeg", "http:  //127.0.0.1:8080/pic3.jpeg", "http://127.0.0.1:8080/pic4.jpeg", "http://127.0.0.1:8080/pic5.jpeg"]
        var x;
        for (x of arr) {
            document.getElementById("cat").src = x;
            var flipHorizontal = false;
            var imageElement = document.getElementById('cat');
            imageElement.crossOrigin = "Anonymous";
            const p = new Promise((resolve, reject) => {
                imageElement.onload = _ => {
                    resolve(imageElement)
                }
            })
            const net = await posenet.load({
                architecture: 'MobileNetV1',
                outputStride: 16
            })

            const pose = await net.estimateSinglePose(await p, {
                flipHorizontal: true
            });

            console.log(pose);
        }

此外,模型可以在 运行 循环之前加载。模型的单个实例可用于所有估计。