超简单的借助face-api.js、webcamjs实现人脸拍照、图片上传

import React, { Component } from 'react';
import * as faceapi from 'face-api.js';
import * as webcamjs from 'webcamjs';
import config from '@/services/config.js';
import { Button } from 'antd';
class TakePicture extends Component {
  // 初始化摄像机
  _initCamera = async () => {
    await faceapi.nets.ssdMobilenetv1.loadFromUri(
      'http://localhost:8004/faceapi-weights/',
    );

    await faceapi.nets.faceLandmark68Net.loadFromUri(
      'http://localhost:8004/faceapi-weights/',
    );
    await faceapi.nets.faceRecognitionNet.loadFromUri(
      'http://localhost:8004/faceapi-weights/',
    );
    // 设置好打开摄像机
    this.openCamara()
  };

  componentDidMount(){
    // 初始化摄像环境
    this._initCamera()
  }

  componentWillUnmount() {
    // 关闭摄像头
    webcamjs.reset()
  }

  // 打开摄像头
  openCamara = () => {
    webcamjs.attach('#camera');
    // 与后端约定:上传文件接口约定name为file
    webcamjs.set('upload_name', 'file');
    // 设置摄像头范围
    webcamjs.set({
      width: 246,
      height: 185,
      image_format: 'jpeg',
      jpeg_quality: 90
    });
    // 摄像头错误捕获
    webcamjs.on('error', (err)=> {
      message.error('摄像头调起失败!')
    });
  };

  // 上传图片到后台
  uploadPhoto =  (imgUrl)=> {
    // 拍照的图片上传地址:config.uploadUrl,可以自行定义
    webcamjs.upload(imgUrl, config.uploadUrl, (code, text)=> {
      /*
        图片的url地址在text中 (JSON.parse(text))
        将对应后台返回的url地址传入需要的接口里...
      */
      console.log(JSON.parse(text));
    });
  }

  // 进行拍照
  takePicture = () => {
    webcamjs.snap( (imgUrl)=> {
      this.uploadPhoto(imgUrl)
    });
  };

  render() {
    return (
       <>
         <h1>人脸拍照</h1>
         <div id="camera" style={{width: 638, height: 359, background : '#000'}}></div>
         <Button type="primary" onClick={this.takePicture} style={{margin: '0 auto',width : 120}}>采集人脸</Button>
       </>
     );
  }
}

export default TakePicture;

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值