🚫为了防止狗上沙发,写了一个浏览器实时识别目标功能📷

324 天前
 xiaowoli

网页调用摄像头识别物体后做成行为

背景

家里有一条狗🐶,很喜欢乘人不备睡沙发🛋️,恰好最近刚搬家 + 狗迎来了掉毛期 不想让沙发上很多毛。所以希望能识别到狗,然后播放“gun 下去”的音频📣。

需求分析

技术要点

  1. 利用浏览器 API 调用手机摄像头,将视频流推给 video

    const stream = await navigator.mediaDevices.getUserMedia({
      // video: { facingMode: "environment" },  // 摄像头后置
      video: { facingMode: "user" },
    });
    
    const videoElement = document.getElementById("camera-stream");
    videoElement.srcObject = stream;
    
  2. 加载模型,实现识别

    let dogDetector;
    
    async function loadDogDetector() {
      // 加载预训练的 SSD MobileNet V2 模型
      const model = await cocoSsd.load();
      dogDetector = model; // 将加载好的模型赋值给 dogDetector 变量
    }
    
  3. 监听 video 的播放,将视频流转换成图像传入模型检测

    videoElement.addEventListener("play", async () => {
      requestAnimationFrame(processVideoFrame);
    });
    
    async function processVideoFrame() {
      if (!videoElement.paused && !videoElement.ended) {
        canvas.width = videoElement.videoWidth;
        canvas.height = videoElement.videoHeight;
        ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
    
        // 获取当前帧图像数据
        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    
        // 对帧执行预测
        let predictionClasses = "";
        const predictions = await dogDetector.detect(imageData);
        // 处理预测结果,比如检查是否有狗被检测到
        for (const prediction of predictions) {
          predictionClasses += `${prediction.class}\n`; // 组装识别的物体名称
          if (prediction.class === "dog") {
            // 播放声音
            playDogBarkSound();
          }
        }
        nameContainer.innerText = predictionClasses.trim(); // 移除末尾的换行符
    
        requestAnimationFrame(processVideoFrame);
      }
    }
    
  4. 播放音频

    async function playDogBarkSound() {
      if (playing) return;
      playing = true;
      const audio = new Audio(dogBarkSound);
      audio.addEventListener("ended", () => {
        playing = false;
      });
      audio.volume = 0.5; // 调整音量大小
      await audio.play();
    }
    
  5. 手机开启本地 http 服务

    • 安装 termux
    • 安装 python3
    • 运行 python3 -m http.server 8000
  6. 将项目上传到 termux 的目录

    • 直接用 termux 打开文件
    • 访问 http://localhost:8000

项目代码(改为 html 文件后)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Mobile Dog Detector</title>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.17.0/dist/tf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd@2.2.3/dist/coco-ssd.min.js"></script>
    <style>
      #camera-stream {
        width: 200px;
        height: auto;
      }
      #name {
        height: 200px;
        overflow-y: auto;
        font-family: Arial, sans-serif;
      }
    </style>
  </head>
  <body>
    <video id="camera-stream" autoplay playsinline></video>
    <div id="name" style="height: 200px"></div>

    <script>
      let playing = false;
      let dogDetector;

      async function loadDogDetector() {
        // 加载预训练的 SSD MobileNet V2 模型
        const model = await cocoSsd.load();
        dogDetector = model; // 将加载好的模型赋值给 dogDetector 变量
        console.log("dogDetector", dogDetector);
        startCamera();
      }
      // 调用函数加载模型
      loadDogDetector();

      async function startCamera() {
        const stream = await navigator.mediaDevices.getUserMedia({
          // video: { facingMode: "environment" },  // 摄像头后置
          video: { facingMode: "user" },
        });
        const nameContainer = document.getElementById("name");
        const videoElement = document.getElementById("camera-stream");
        videoElement.srcObject = stream;

        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");

        videoElement.addEventListener("play", async () => {
          requestAnimationFrame(processVideoFrame);
        });
        async function processVideoFrame() {
          if (!videoElement.paused && !videoElement.ended) {
            canvas.width = videoElement.videoWidth;
            canvas.height = videoElement.videoHeight;
            ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);

            const imageData = ctx.getImageData(
              0,
              0,
              canvas.width,
              canvas.height
            );

            let predictionClasses = "";
            const predictions = await dogDetector.detect(imageData);
            for (const prediction of predictions) {
              predictionClasses += `${prediction.class}\n`;
              if (prediction.class === "dog") {
                // 修改为检测到狗时播放声音
                playDogBarkSound();
              }
            }
            nameContainer.innerText = predictionClasses.trim();

            requestAnimationFrame(processVideoFrame);
          }
        }

        async function playDogBarkSound() {
          if (playing) return;
          playing = true;
          const audio = new Audio("./getout.mp3");
          audio.addEventListener("ended", () => {
            playing = false;
          });
          audio.volume = 0.5; // 调整音量大小
          await audio.play();
        }
      }
    </script>
  </body>
</html>

实现效果

效果很好👍,用旧手机开启摄像头后,检测到狗就播放声音了。

但是,家里夫人直接做了一个围栏晚上给狗圈起来了🚫

实现总结

该方案通过以下步骤实现了一个基于网页的实时物体检测系统,专门用于识别画面中的狗并播放特定音频以驱赶它离开沙发。具体实现过程包括以下几个核心部分:

使用浏览器提供的 navigator.mediaDevices.getUserMedia API 获取用户授权后调用手机摄像头,并将视频流设置给 video 元素展示。

使用 TensorFlow.js 和预训练的 COCO-SSD MobileNet V2 模型进行对象检测,加载模型后赋值给 dogDetector 变量。 处理视频流与图像识别:

监听 video 元素的播放事件,通过 requestAnimationFrame 循环逐帧处理视频。 将当前视频帧绘制到 canvas 上,然后从 canvas 中提取图像数据传入模型进行预测。 在模型返回的预测结果中,如果检测到“dog”,则触发播放音频函数。

定义一个异步函数 playDogBarkSound 来播放指定的音频文件,确保音频只在前一次播放结束后才开始新的播放。

使用旧 Android 手机安装 Termux ,创建本地 HTTP 服务器运行项目代码。 上传项目文件至 Termux 目录下并通过访问 localhost:8000 启动应用。

通过以上技术整合,最终实现了在旧手机上部署一个能够实时检测画面中狗的网页应用,并在检测到狗时播放指定音频。

6261 次点击
所在节点    分享创造
41 条回复
aitianci
323 天前
可以给狗加个放电脖圈,接近沙发一米内就电一下
wonderfulcxm
323 天前
结局略显意外
Atma
323 天前
你是真的🐶,哈哈哈
dyv9
323 天前
活在你家,做狗也不开心,既然都是不开心下辈子还是做人吧,至少想结婚或想嫖总有一个可以,做狗就没机会。
keepRun
323 天前
angry41
323 天前
@qsgy123456 #17 我记得房产销售大厅的摄像头都带这个功能,还上过 315 ,大数据会识别你之前在哪家看过哪家房子,心里价位大概多少
hanguofu
323 天前
厉害~~ 请问 ”使用 TensorFlow.js 和预训练的 COCO-SSD MobileNet V2 模型进行对象检测“ 这个拿来就可以用了吗 ?具体怎样训练才能识别 狗 啊?
ohayoo
323 天前
程序员的欢乐世界
lxcForPHP
323 天前
@qsgy123456 今年老回家过年,遇到很多能喊出我名字来(小时候的邻居和家族的人),但是我却没有多少印象,愣在那里也不知道喊人家啥,场面尴尬的很。所以就萌生了一个想法,能不能自己维护一个资料库,然后能通过啥智能设备来自动查询相关资料
fenglangjuxu
321 天前
高阶程序员 我等只能望洋兴叹
uyoungco
321 天前
@hanguofu 别人训练好的,你输入图形他会给你图像中的信息,比如 人、狗之类的
huangz003
321 天前
圈起来,小狗怎么上厕所😂
xiaowoli
321 天前
@huangz003 只有晚上关起来 我家狗一天就出去尿一次 够了
xiaowoli
321 天前
@netnetuser 老哥,最新消息,我家狗看了你的回复已经学会越狱了。。。
xiaowoli
321 天前
@hanguofu 直接用我那个代码就已经可以识别了 现成的模型库
netnetuser
321 天前
@xiaowoli 我觉得可以记录下狗狗越狱整个过程(偷 拍),然后让大家一起欢乐。
LavaC
320 天前
突然想起那个买了体重秤放床垫下的玩法
jiandandkl
320 天前
太好玩了,想知道狗听到播放的 gun 下去会听话的 gun 下去吗?
janda
320 天前
有意思
DavidA
320 天前
幽默

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://tanronggui.xyz/t/1024038

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX