首页 > 解决方案 > Azure 认知服务,在未检测到人脸时需要帮助处理错误

问题描述

链接到完整的回购

所以在我的应用程序中,它会分析上传照片的面部并返回结果。但是当它没有检测到任何面孔时,应用程序就会崩溃。我在控制台中收到“TypeError:无法读取未定义的属性'faceAttributes'”。现在我只是重定向回'/',但宁愿在 EJS 中显示一条消息。这是发布请求:

app.post("/", upload.single("file-to-upload"), async (req, res) => {
  try {
    // Upload image to cloudinary
    const result = await cloudinary.uploader.upload(req.file.path);
    const imageUrl = result.secure_url;
    axios({
      method: "post",
      url: faceEndpoint,
      params: {
        returnFaceId: true,
        returnFaceAttributes:
          "age,gender,headPose,smile,facialHair,glasses," +
          "emotion,hair,makeup,occlusion,accessories,blur,exposure,noise",
      },
      data: {
        url: imageUrl,
      },
      headers: { "Ocp-Apim-Subscription-Key": subscriptionKey },
    })
      .then(function (response) {
        console.log("Status text: " + response.status);
        console.log("Status text: " + response.statusText);
        console.log(response.data[0]);
        res.render("result.ejs", {
          data: response.data[0].faceAttributes.emotion,
          img: imageUrl,
        });
      })
      .catch(function (error) {
        res.redirect('/')
        console.log(error);
      });
  } catch (err) {

    console.log(err);
  }
})

在我的 EJS 中,我只有一个 UL:

<ul>
  <li>Anger: <%= (data.anger * 100).toFixed(1) %>%</li>
  <li>Contempt: <%= (data.contempt * 100).toFixed(1) %>%</li>
  <li>Disgust: <%= (data.disgust * 100).toFixed(1) %>%</li>
  <li>Fear: <%= (data.fear * 100).toFixed(1) %>%</li>
  <li>Happiness: <%= (data.happiness *100).toFixed(1) %>%</li>
  <li>Neutral: <%= (data.neutral * 100).toFixed(1) %>%</li>
  <li>Sadness: <%= (data.sadness * 100).toFixed(1) %>%</li>
  <li>Surprise: <%= (data.surprise * 100).toFixed(1) %>%  </li>
</ul>

我在 ul.. 之前尝试了许多 if 语句的变体。

<% if(data.length == 0) { %>
 <h2> no faces detected </h2>
<% } else { %>
// ul goes here
<% } %> 

也分别尝试了所有这些.. if(data[0].faceAttributes) if (data[0].faceAttributes.emotion) if(!data) if(typeof faceAttributes == 'undefined'

我对 EJS 很陌生,并且仍在尝试掌握一些概念,所以我只是不理解某些部分。

标签: javascriptejsmicrosoft-cognitive

解决方案


推荐阅读