vue2使用face-api.js实现,人脸识别

                由于开发需求要实现人脸识别,顺便在此记录一下,希望给各位前端爱好者带来帮助。

1、安装依赖

        首先,确保你已经安装了Vue.js,并且创建了一个Vue项目。然后,安装face-api.js及其相关依赖。由于face-api.js依赖于TensorFlow.js,你可能还需要安装这个库。可以通过npm或yarn来安装:

npm install face-api.js

这是我安装的版本

2、下载模型文件

face-api.js需要一些预先训练好的模型文件来执行人脸检测和识别。你需要从GitHub仓库中下载这些文件,并放置在项目的public目录下,或者配置一个正确的路径指向这些文件。可以从face-api.js的GitHub页面下载模型。

  1. 在这个页面上,你会看到多个模型文件,例如 ssd_mobilenetv1_model-weights_manifest.jsonface_landmark_68_model-weights_manifest.json 等。为了使用 face-api.js 的不同功能,如人脸检测、特征点定位、表情识别等,你需要下载相应的模型文件。

  2. 你可以手动下载,也可以直接克隆,你也可以私聊我一下我给你发。

    git clone https://github.com/justadudewhohacks/face-api.js.git

    3.克隆完之后你需要把模型文件放到 public下的models没有models自己创建,你也可以自己规定路径,只要路径正确就行。

到此准备工作就做完了,当然你需要配置好vue框架。

3、封装组件

        为了更好地组织代码并使其可复用,我们可以将人脸识别的功能封装成一个Vue组件。下面是一个更完善的示例,展示了如何创建一个名为FaceRecognition.vue的自定义组件,该组件负责处理视频流、人脸检测、以及展示检测结果。完整代码块在这

<template>
  <div class="face-recognition">
    <video ref="video" width="640" height="480" autoplay></video>
    <canvas ref="canvas" width="640" height="480"></canvas>
    <div>当前人流量:{{ peopleCount }}</div>
  </div>
</template>

<script>
import * as faceapi from 'face-api.js';

export default {
  name: 'FaceRecognition',
  data() {
    return {
      isLoaded: false,
      lastDetections: [], // 上一帧检测到的人脸
      peopleCount: 0, // 当前人流量计数
    };
  },
  mounted() {
    this.loadModels();
  },
  methods: {
    async loadModels() {
      try {
        await Promise.all([
          faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
          faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
          faceapi.nets.ssdMobilenetv1.loadFromUri('/models'),
        ]);
        this.isLoaded = true;
        this.startVideo();
      } catch (error) {
        console.error('Failed to load models:', error);
      }
    },
    startVideo() {
      if (navigator.mediaDevices && this.isLoaded) {
        navigator.mediaDevices.getUserMedia({ video: true })
          .then(stream => {
            this.$refs.video.srcObject = stream;
            this.$refs.video.onloadedmetadata = () => {
              this.detectFaces();
            };
          })
          .catch(error => console.error('getUserMedia error:', error));
      }
    },

    async detectFaces() {
      const video = this.$refs.video;
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext('2d');
      const detectionOptions = new faceapi.SsdMobilenetv1Options({ minConfidence: 0.9 });

      let recentDetections = [];
      const detectionHistoryLength = 5;

      setInterval(async () => {
        if (video.readyState === video.HAVE_ENOUGH_DATA) {
          ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
          const detections = await faceapi.detectAllFaces(video, detectionOptions).withFaceLandmarks();
          // console.log('查看获取帧',validDescriptors)
          // 确保只收集有效的面部描述符
          const validDescriptors = detections
          console.log('查看获取帧',validDescriptors)
          recentDetections.push(...validDescriptors.map(face => face.descriptor));

          // 限制历史长度并去重
          recentDetections = recentDetections.slice(-detectionHistoryLength);
          // console.log('查看获取帧',recentDetections)
          const uniqueDescriptors = Array.from(new Set(recentDetections));
          this.peopleCount = uniqueDescriptors.length; // 直接使用去重后的数组长度,因已排除undefined,无需JSON.stringify和parse

          faceapi.draw.drawDetections(canvas, detections);
          faceapi.draw.drawFaceLandmarks(canvas, detections);
        }
      }, 100);
    }
  },
  beforeDestroy() {
    // 清理视频流
    if (this.$refs.video.srcObject) {
      this.$refs.video.srcObject.getTracks().forEach(track => track.stop());
    }
  },
};
</script>

<style scoped>
.face-recognition {
  position: relative;
}
</style>

4、使用组件

创建文件直接引入组件然后注册使用即可

<template>
    <div id="app">
      <FaceDetection />
    </div>
  </template>
  
  <script>
  import FaceDetection from '@/components/FaceDetection/FaceDetection.vue';
  
  export default {
    name: 'App',
    components: {
      FaceDetection,
    },
  };
  </script>

5、实现逻辑

  • mounted()生命周期钩子中,首先加载模型,然后启动视频流。
  • 创建一个方法如detectFaces()来周期性地从视频流中捕获帧,使用faceapi.detectAllFaces()来检测人脸,并绘制检测结果到<canvas>上。
  • 根据需要,你可以扩展此逻辑来实现更复杂的人脸识别功能,比如与已知人脸匹配等。

6、注意事项

  • 确保你的应用有访问用户媒体设备的权限。
  • 处理好异步加载模型和获取视频流的错误情况。
  • 由于浏览器的安全策略,你可能需要在HTTPS环境下运行此应用,或者在localhost上进行开发。
  • 考虑性能优化,避免频繁的重绘导致的性能问题。

7、实现效果

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值