node.js - 如何使用 Clarifai 检测本地镜像的人脸

标签 node.js reactjs api face-detection clarifai

我正在尝试使用 Clarifai API 从本地文件夹中获取的图像中检测面部。 但我无法这样做并获得一个对象作为响应。 然后“网络”选项卡显示为待处理并给出空对象 {} 我也在index.html中使用了sdk脚本

<script type="text/javascript" src="https://sdk.clarifai.com/js/clarifai-latest.js"></script>

前端

import React, { Component } from 'react';

class App extends Component {
      constructor(){
        super();
        this.state = {
              input:'',
              imageUrl: '',
              box:{}
        }
      }

      calculateFaceLocation = (data) =>{
        const clarifaiFace= data.outputs[0].data.regions[0].region_info.bounding_box;
        const image = document.getElementById('preview');
        const width = Number(image.width);
        const height = Number(image.height);
        return {
          leftCol: clarifaiFace.left_col * width,
          topRow: clarifaiFace.top_row * height,
          rightCol: width - (clarifaiFace.right_col * width),
         bottomRow: height - (clarifaiFace.bottom_row * height)
        }
      }

      displayFaceBox = (box) =>{
        this.setState({ box :box});
      }


       previewFiles = ()=> {

        var preview = document.querySelector('#preview');
        var files   = document.querySelector('input[type=file]').files;

        function readAndPreview(file) {

          // Make sure `file.name` matches our extensions criteria
          if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
            var reader = new FileReader();

            reader.addEventListener("load", function () {
              var image = new Image();
              image.height = 300;
              image.title = file.name;
              image.src = this.result;
              preview.appendChild( image );

            }, false);

            reader.readAsDataURL(file);
          }

        }

        if (files) {
          [].forEach.call(files, readAndPreview);
        }
        this.setState({input: this.result })
      }


      onButtonSubmit = () =>{
        this.setState({
          imageUrl: this.state.input
        });
        fetch('http://localhost:3000/imageurl',{
          method:'post',
          headers:{'Content-Type':'application/json'},
          body:JSON.stringify({
              input : this.state.input
          })
        })
        .then(response => response.json())
        .then(response =>  this.displayFaceBox(this.calculateFaceLocation(this.response)))

      }



  render(){
    const {  imageUrl, box } = this.state;
    return (
      <div className="App">

        <input id="browse" type="file" onChange={this.previewFiles} />
        <div id="preview" box={box} imageUrl = { imageUrl} style={{top: box.topRow , right: box.rightCol , 
                             bottom: box.bottomRow , left: box.leftCol}}></div>
        <button onClick= { this.onButtonSubmit } > DETECT</button>



      </div>
    );


  }


}

export default App;

后端:

const Clarifai = require ('clarifai')

const app = new Clarifai.App({
    apiKey: 'Changed API KEY' 
   });

   const handleApiCall = (req,res)=>{
    app.models.predict(Clarifai.FACE_DETECT_MODEL, req.body.input)
    .then(data =>{
        res.json(data);
    })
    .catch(err =>response.status(400).json("UNABLE TO HANDLE API "))
 }

 module.exports ={ 
    handleApiCall
}

最佳答案

不使用 PreviewFile 函数, OnInputChange ,使用 e.target.files 从输入标记获取文件,并使用 const formData = new FormData() 从表单数据获取图像。

就这样

 onInputChange = (event) => {
    if (event.target.files) {

      const files = Array.from(event.target.files);
      const formData = new FormData();
      files.forEach((file, i) => {
        formData.append(i, file)
      })
      fetch(`${url}/image-upload`, {
        method: 'POST',
        body: formData
      })
        .then(res => res.json())
        .then(images => {
          this.setState({ input: images[0].url});
        })
    } else {
      this.setState({ input: event.target.value});
    }

Refer This Github Project这会给你更清晰的想法。

关于node.js - 如何使用 Clarifai 检测本地镜像的人脸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61996835/

相关文章:

ajax - ExpressJS 后端挂起太多请求

javascript - 类型错误 : unable to create data property ~ React ~ ESLint

python - 我如何通过 telethon API 向我的联系人发送消息 python telegram

c# - mysql c# 无法连接到主机 (0x800004005)

javascript - 重定向到不同域页面后,Excel Javascript API 不可用

javascript - express.js 多文件上传回调

node.js - 如何维护 Google 的 OpenID Connect 发现文档中的公钥缓存

reactjs - 用 Cypress 移动 slider

reactjs - 我无法将 Next.js 部署到 Netlify。由于@netlify/plugin-nextjs 插件错误导致部署失败

javascript - JISON 中的错误处理