图像识别垃圾分类app的制作

7,600 阅读2分钟

随着6月结束,7月开始,最近上海最火的话题是垃圾分类无疑了。。上海人民是每天早晚俩小时定时定点扔垃圾。

干湿垃圾要分开,把湿垃圾从垃圾袋里倒进桶里,再把垃圾袋扔进干垃圾桶 😂

龙虾🦞壳是干垃圾,龙虾🦞肉是湿垃圾,请你分开扔,谢谢😂

猪🐷能吃的是湿垃圾,不能吃的是干垃圾,吃了会死的是有毒垃圾,卖了能买猪🐷的是可回收垃圾

佩琦识垃圾

看完是不是要崩溃了?!别担心,本人周末花一下午精心制作的看图识垃圾app,主要依赖 tensorflow coco-ssd 来识别照片中的多物体,然后找了个不知名的api,返回垃圾的分类。例如:

screenshot

制作过程简述

首先,网上已经有很多可以输入文字查询垃圾分类的网站了,我灵光一闪:要是可以直接通过图像垃圾分类岂不更好。然后找到了tensorflow.js 的官方指南:

<!-- Load TensorFlow.js. This is required to use coco-ssd model. -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"> </script>
<!-- Load the coco-ssd model. -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd"> </script>
<img id="img" src="cat.jpg"/>
<script>
  // Notice there is no 'import' statement. 'cocoSsd' and 'tf' is
  // available on the index-page because of the script tag above.

  const img = document.getElementById('img');

  // Load the model. 在浏览器里fetch和加载模型到内存可能要花1分钟以上
  cocoSsd.load().then(model => {
    // detect objects in the image.
    model.detect(img).then(predictions => {
      console.log('Predictions: ', predictions);
    });
  });
</script>

可见,Google tensorflow 已经把常用的机器学习模型做到开箱即用的水平,非常方便。当然,这个多物体检测的函数返回的是个数组,包含了对象在图中的bbox,而且里面的分类标签都是英文的:

[{
  bbox: [x, y, width, height],
  class: "person",
  score: 0.8380282521247864
}, {
  bbox: [x, y, width, height],
  class: "kite",
  score: 0.74644153267145157
}]

那么问题来了:网上的垃圾分类api 都是要求输入中文的!!我第一时间想到了 Bing Translate API 把英文翻译成中文再去查询分类。所以又去申请了个Azure 的免费账号,还好我有master card,付了一美金才搞定。具体的可以参考最后的官方文档链接

经过一顿折腾,终于搞定,就是识别率很低。毕竟没有专门训练垃圾分类的模型,只是用现成的物体检测模型。

所以有很多搞笑的结果 😂:

哭笑不得

在线体验

建议用电脑在线体验地址,加载模型就得花一分钟:

感兴趣的可以看github 项目地址

也欢迎扫码体验:

二维码

参考资料

tensorflowjs-models

Bing 翻译官方文档

Bing 翻译官方例子