【微信小程序】基于百度大脑人体检测、人脸识别以及调用阿里垃圾分类识别小程序利用canvas完成人脸画图、分割手部部分图片算法

本文涉及的产品
图像搜索,7款服务类型 1个月
简介: 【微信小程序】基于百度大脑人体检测、人脸识别垃圾分类人体出现在镜头里用红色框将人脸圈出来、用黄色框将手部圈出来,定时器触发后,通过百度返回的top+、left+、width+、height+将拍照的截图用canvas画出来,最后保存上传到阿里云垃圾分类识别检测博主用的是手部关键点识别,手部截取包括手肘部分,当出现手肘没有手掌时会出现截取不到目标的问题,目前解决办法:定时器设置时间长一点供演示员做好调整,另外就是出现手掌,可以尽量把掌心打开方便识别这样手肘部分就不会被检测到了在截取的时候canvas用不了..

演示

好久没发了,最近在做比赛看下成品演示:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
说明:人体出现在镜头里用红色框将人脸圈出来、用黄色框将手部圈出来,定时器触发后,通过百度返回的top+、left+、width+、height+将拍照的截图用canvas画出来,最后保存上传到阿里云垃圾分类识别检测

完整视频演示,等路演发出来

遇到的问题

博主用的是手部关键点识别,手部截取包括手肘部分,当出现手肘没有手掌时会出现截取不到目标的问题,目前解决办法:定时器设置时间长一点供演示员做好调整,另外就是出现手掌,可以尽量把掌心打开方便识别
在这里插入图片描述
这样手肘部分就不会被检测到了
在截取的时候canvas用不了了,网上找了很多办法,都是基础版本不支持,都是淘汰废弃代码,在这里卡了几天,最后看到一篇文章,
canvas的drawImage方法参数详解

最后我做了总结

ctx.drawImage(that.data.src,that.data.left-80,that.data.top-80,161,169,0,0,161,169);

                //原图片;坐标left、top;剪裁的宽度、高度;在新的图像上显示比例

下面的注释为:百度检测到返回的localtion坐标

项目完整流程:通过单片机超声波检测人体靠近,打开小程序摄像头,检测人脸和手部,检测到以后记录人脸以及手部分割,手部分割的图片最后用阿里识别接口完成调用,识别后发送自定义参数从而使垃圾桶完成开盖,人脸用于记录绿色能量值,整个流程就是这样

百度返回的人体手部大小不能使手上的东西完整截取出来

所以我加了以下东西,帮助识别检测

that.data.left-80,that.data.top-80

另外由于图片大小 还没做调整,宽度、高度不够会用白色图片补全
在这里插入图片描述

手部识别代码(包含canvas截图):
index.js

var app = getApp();


// 规定
// access_token1为:人脸识别
// access_token2为:手部检测的


// 
Page({
  data: {
    src:"",
    fengmian:"",
    videoSrc:"",
    who:"",
    openid: "",
    token: "",
    windowWidth: 0,
    trackshow: "进行人脸追踪",
    canvasshow:true,
    access_token1:'',
    access_token2:''
  },
  ceshi() {
    console.log("点击");
    let that = this
    setTimeout(() => {
      wx.canvasToTempFilePath({
        // x:100,
        // y:20,
        width: 170,
        heght: 170,
        canvasId: 'canvasresult',
        fileType: 'jpg',
        quality: 1,
        success: (res) => {
          console.log(res);
          console.log(res.tempFilePath);
        },
        fail: function (res) {
          console.log(res);
        },
      })
    }, 1000);
    // wx.downloadFile({
    //  url: that.data.src,
    //  success: function (res) {
    //   wx.saveImageToPhotosAlbum({
    //    filePath: res.tempFilePath,
    //    success(res) {
    //     wx.showToast({
    //      title: '保存成功',
    //      icon: "success",
    //      duration: 1000
    //     })
    //    }
    //   })
    //  }
    // })
   },
  onLoad() {
    var that = this
    wx.showLoading({
      title: '开始监测人脸',
      mask: true
    })
    //屏幕宽度
    var sysInfo = wx.getSystemInfoSync()
    that.setData({
      windowWidth: sysInfo.windowWidth,
    })
    that.ctx = wx.createCameraContext()
    console.log("onLoad"),
    
      // that.setData({
      //   openid: app.globalData.openid,
      //   token: app.globalData.token
      // });
    


    wx.request({
      url: "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=pkTx***o&client_secret=LXw1****6P0lR1",
      method: 'POST',
      dataType: "json",
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        // console.log(res.data.access_token1);
        // app.globalData.access_token1 = res.data.access_token1;
        that.setData({
          access_token2: res.data.access_token
        });
      }
    })
    // https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Va5yQRHlA4Fq5eR3LT0vuXV4&client_secret=0rDSjzQ20XUj5itV6WRtznPQSzr5pVw2&

    // 更新手部2
    // wx.request({
    //   url: "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=XbQ******pkTxo&client_secret=Lyw1o******lR1",
    //   method: 'POST',
    //   dataType: "json",
    //   header: {
    //     'content-type': 'application/json'
    //   },
    //   success: function (res) {
    //     // console.log(res.data.access_token1);
    //     // app.globalData.access_token1 = res.data.access_token1;
    //     that.setData({
    //       access_token1: res.data.access_token
    //     });
    //   }
    // })
    wx.hideLoading()
    that.track();
  },

  onReady: function () {
  },

  track (e){
    var that =this
    if (that.data.trackshow =="进行人脸追踪"){
      //运行
      that.setData({
        trackshow: "停止人脸追踪",
        canvasshow: true
      })
      that.takePhoto()
      that.interval = setInterval(this.takePhoto, 500)
    }else{
      //停止
      clearInterval(that.interval)
      that.setData({
        trackshow: "进行人脸追踪",
        canvasshow: false
      })
    }
  },


  takePhoto() {
    //
    console.log("takePhoto")
    var that = this
    var takephonewidth
    var takephoneheight
    that.ctx.takePhoto({
      quality: 'hight',
      success: (res) => {
        that.setData({
          src: res.tempImagePath
        })
        // console.log(res.tempImagePath),
        // 获取图片真实宽高
        wx.getImageInfo({
          src: res.tempImagePath,
          success: function (res) {
            takephonewidth= res.width,
            takephoneheight = res.height
          }
        })
        // console.log(takephonewidth, takephoneheight)
        wx.getFileSystemManager().readFile({
          filePath: res.tempImagePath, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            // console.log('data:image/png;base64,' + res.data),
            wx.request({
              url: "https://aip.baidubce.com/rest/2.0/image-classify/v1/hand_analysis?access_token=" + that.data.access_token2,
              data: {
                image:res.data
              },
              method: 'POST',
              dataType: "json",
              header: {
                'content-type': 'application/x-www-form-urlencoded' },
              success: function (res) {
                console.log(res.data);
                if (res.data.hand_num) { 
                  var ctx = wx.createContext()
                
                  ctx.setStrokeStyle('red')
                  ctx.lineWidth = 4
                  for (let j = 0; j < res.data.hand_num; j++){
                    var cavansl = res.data.hand_info[j].location.left / takephonewidth * that.data.windowWidth
                    var cavanst = res.data.hand_info[j].location.top / takephoneheight * that.data.windowWidth
                    var cavansw = res.data.hand_info[j].location.width / takephonewidth * that.data.windowWidth
                    var cavansh = res.data.hand_info[j].location.height / takephoneheight * that.data.windowWidth
                    ctx.strokeRect(cavansl, cavanst, cavansw, cavansh)
                    that.setData({
                      left:res.data.hand_info[j].location.left, 
                      top:res.data.hand_info[j].location.top,
                      bd_w:res.data.hand_info[j].location.width,
                      bd_h:res.data.hand_info[j].location.height ,
                      cavansw:cavansw,
                      cavansh:cavansh

                    })
                   
                    // ctx.setFontSize(14);
                    // ctx.fillText(cavanstext, cavansl, cavanst-2)
                    // ctx.strokeRect(cavansl, cavanst, cavansw, cavansh)
                    
                  
                   
                  }
                  // that.search();
                    //绘制
                    ctx.drawImage(that.data.src,that.data.left-80,that.data.top-80,161,169,0,0,161,169);
                    //原图片;坐标left、top;剪裁的宽度、高度;在新的图像上显示比例
                  wx.drawCanvas({
                    canvasId: 'canvasresult',
                    actions: ctx.getActions()
                  })
                  wx.drawCanvas({
                    canvasId: 'canvass',
                    actions: ctx.getActions()
                  })
                  setTimeout(() => {
                    //检测到人脸则搜索用户识别码
                    // that.search();
                    //执行完一遍关闭调用检测
                   //执行完一遍关闭调用检测
                clearInterval(that.interval)
                that.setData({
                  trackshow: "进行人脸追踪",
                  canvasshow: false
                })
                  }, 1000);
                   
                // 
                } else{
                var ctx = wx.createContext()
                ctx.setStrokeStyle('#31859c')
                ctx.lineWidth = 3
                wx.drawCanvas({
                  canvasId: 'canvas',
                  actions: ctx.getActions()
                })
              }
              },
            })

          }
        })
      }
    })
  },

  search(){
    var that = this
    that.setData({
      who: ""
    })
    var takephonewidth
    var takephoneheight
    that.ctx.takePhoto({
      quality: 'low',
      success: (res) => {
        // console.log(res.tempImagePath),
        // 获取图片真实宽高
        wx.getImageInfo({
          src: res.tempImagePath,
          success: function (res) {
            takephonewidth = res.width,
              takephoneheight = res.height
          }
        })
        that.setData({
          src: res.tempImagePath
        }),
        wx.getFileSystemManager().readFile({
          filePath: that.data.src, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => {
            // var ctx = wx.createContext()
            //       ctx.drawImage(that.data.src, 0, 0, takephonewidth, takephoneheight);
            //         ctx.setStrokeStyle('#31859c')
            //         ctx.setFillStyle('#31859c');
            //         ctx.lineWidth = 4
            //           ctx.setFontSize(14);
                  
            //           wx.canvasToTempFilePath({

            //             x: 0,
                    
            //             y: 0,
                    
            //             width: 300,
                    
            //             height: 500,
                    
            //             canvasId: 'canvasresult',
                    
            //             success: function (res) {
                    
            //                 console.log(res.tempFilePath);
                    
            //             }
                    
            //         })
            //         wx.drawCanvas({
            //           canvasId: 'canvasresult',
            //           actions: ctx.getActions()
            //         })
          }
        })
      }
    })

  },


  startRecord() {
    this.ctx.startRecord({
      success: (res) => {
        console.log('startRecord')
      },   
    })
  },
  stopRecord() {
    this.ctx.stopRecord({
      success: (res) => {
        console.log(res)
        this.setData({
          fengmian: res.tempThumbPath,
          videoSrc: res.tempVideoPath
        })
        console.log('startOver')
      }
    })
  },
  uploadRecord() {
    var that = this;
    wx.showLoading({
      title: '上传中',
    })
    //获取摄像头信息
    wx.request({
      url: app.globalData.urlHeader + '/login/cameralist',
      data: {
        openid: app.globalData.openid,
        token: app.globalData.token
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.code === 0) {
          if (res.data.data.cameras == null) {
            wx.request({
              url: app.globalData.urlHeader + '/login/addcamera',
              data: {
                openid: app.globalData.openid,
                token: app.globalData.token,
                camera: "phone",
              },
              method: 'POST',
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                if (res.data.code === 0) {
                  console.log('添加成功')
                } else {
                  console.log(res.data.error)
                }
              }
            })
          } else {
            var cameras = res.data.data.cameras
            if (cameras.includes("phone")) {
              return false
            } else {
              wx.request({
                url: app.globalData.urlHeader + '/login/addcamera',
                data: {
                  openid: app.globalData.openid,
                  token: app.globalData.token,
                  camera: "phone"
                },
                method: 'POST',
                header: {
                  'content-type': 'application/json'
                },
                success: function (res) {
                  if (res.data.code === 0) {
                    console.log('添加成功')
                  } else {
                    console.log(res.data.error)
                  }
                }
              })
            }
          }
        }
        else {
          wx.hideLoading()
          console.log('获取摄像头列表失败!' + res.data.error)
          wx.showToast({
            title: '获取摄像头列表失败!',
            image: '../../img/about.png',
            duration: 1000
          })

        }
      }
    })

    wx.uploadFile({
      url: app.globalData.urlHeader + '/upload',
      filePath: that.data.videoSrc,
      name: 'file',
      formData: {
        'cameraid':'phone',
        'openid': app.globalData.openid,
        'token': app.globalData.token,
        'tag': 2
      },
      success: function (res) {
        console.log(res.data);
        var result = JSON.parse(res.data).data.filename
        console.log(result);
        wx.uploadFile({
          url: app.globalData.urlHeader + '/upload/fengmian',
          filePath: that.data.fengmian,
          name: 'file',
          formData: {
            'openid': app.globalData.openid,
            'token': app.globalData.token,
            'name': result
          },
          success(res) {
            console.log( res.data);
            that.setData({
              fengmian: "",
              videoSrc:""
            }),
            wx.hideLoading()
            wx.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 2000
            })
            setTimeout(function () {
              wx.switchTab({
                url: '../index/index'
              })
            }, 2000)
            
          },
          fail(res) {
            wx.hideLoading()
            wx.showToast({
              title: '上传失败',
              image: '../../img/about.png',
              duration: 2000
            })

          }
        })
      },
      fail(res) {
        wx.hideLoading()
        wx.showToast({
          title: '上传失败',
          image: '../../img/about.png',
          duration: 2000
        })

      }
      
    })
  },

  onUnload: function () {
    var that=this
    clearInterval(that.interval)
  },

  error(e) {
    console.log(e.detail)
  }

})

wxml

<view class="page-body">
  <view class="page-body-wrapper">
    <camera device-position="{{qiehuan}}" flash="off" binderror="error" style="width:100%;height:{{windowWidth}}px;"></camera>
    <canvas wx:if="{{canvasshow}}" style="width: 100%;height:{{windowWidth}}px;position:absolute;" canvas-id="canvas"></canvas>
    <!-- <canvas type="2d" id="myCanvas"></canvas> -->
    <!-- <view class="btn-area">
      <button type="primary" bindtap="track" style='background-color:#31859c;' data-trackshow="{{trackshow}}">{{trackshow}}</button>
    </view> -->
    <view class="btn-area">
      <button type="primary" bindtap="qiehuan" data-qie="{{qiehuan}}" style='background-color:#31859c;'>切换镜头</button>
    </view>
    <view class="btn-area">
      <button type="primary" bindtap="search" style='background-color:#31859c;'>确定</button>
    </view>

    <view class="btn-area">
      <button type="primary" bindtap="ceshi" style='background-color:#31859c;'>测试</button>
    </view>
    <!-- <view class="btn-area">
      <button type="primary" bindtap="startRecord" style='background-color:#31859c;'>开始录像</button>
    </view>
    <view class="btn-area">
      <button type="primary" bindtap="stopRecord" style='background-color:#31859c;'>结束录像</button>
    </view> -->
    <view  wx:if="{{src}}" class="preview-tips">识别结果:{{who}}</view>
    <view wx:if="{{src}}" style='display:flex;width:100%;justify-content:center;'>
      <image  mode="aspectFit" src="{{src}}"  style='width:50%;height:{{windowWidth/2}}px;'></image>
      <canvas  style="width: 50%;height:{{windowWidth/2}}px;position:absolute;" canvas-id="canvasresult"></canvas>
    </view>
    <view wx:if="{{videoSrc}}" class="preview-tips">视频预览</view>
    <video wx:if="{{videoSrc}}" poster="{{fengmian}}" class="video" src="{{videoSrc}}"></video>
    <!-- <view wx:if="{{videoSrc}}" class="btn-area">
      <button type="primary" bindtap="uploadRecord" style='background-color:#31859c;'>上传该录像</button>
    </view> -->
  </view>
</view>

wss:

.preview-tips {
  margin: 50rpx 0  30rpx;  
}

.video {
  margin: 20rpx auto;
  width: 100%;
  height: 300px;
}

page {
  background-color: #F8F8F8;
  height: 100%;
  font-size: 32rpx;
  line-height: 1.6;
}

.page-body {
  padding: 20rpx 0;
}

.page-body-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.btn-area {
  margin-top: 40rpx;
  box-sizing: border-box;
  width: 100%;
  padding: 0 30rpx;
}

完整的代码包上传后发出来

相关文章
|
5月前
|
算法 小程序 TensorFlow
垃圾分类算法
垃圾分类算法
147 0
|
5月前
|
传感器 算法 计算机视觉
基于肤色模型和中值滤波的手部检测算法FPGA实现,包括tb测试文件和MATLAB辅助验证
该内容是关于一个基于肤色模型和中值滤波的手部检测算法的描述,包括算法的运行效果图和所使用的软件版本(matlab2022a, vivado2019.2)。算法分为肤色分割和中值滤波两步,其中肤色模型在YCbCr色彩空间定义,中值滤波用于去除噪声。提供了一段核心程序代码,用于处理图像数据并在FPGA上实现。最终,检测结果输出到&quot;hand.txt&quot;文件。
|
5月前
|
机器学习/深度学习 算法 计算机视觉
基于yolov2深度学习网络的视频手部检测算法matlab仿真
基于yolov2深度学习网络的视频手部检测算法matlab仿真
|
8天前
|
缓存 算法 Java
JVM知识体系学习六:JVM垃圾是什么、GC常用垃圾清除算法、堆内存逻辑分区、栈上分配、对象何时进入老年代、有关老年代新生代的两个问题、常见的垃圾回收器、CMS
这篇文章详细介绍了Java虚拟机(JVM)中的垃圾回收机制,包括垃圾的定义、垃圾回收算法、堆内存的逻辑分区、对象的内存分配和回收过程,以及不同垃圾回收器的工作原理和参数设置。
29 4
JVM知识体系学习六:JVM垃圾是什么、GC常用垃圾清除算法、堆内存逻辑分区、栈上分配、对象何时进入老年代、有关老年代新生代的两个问题、常见的垃圾回收器、CMS
|
16天前
|
存储 算法 Java
【JVM】垃圾释放方式:标记-清除、复制算法、标记-整理、分代回收
【JVM】垃圾释放方式:标记-清除、复制算法、标记-整理、分代回收
39 2
|
5月前
|
机器学习/深度学习 数据采集 算法
基于贝叶斯算法的手机垃圾短信过滤
基于贝叶斯算法的手机垃圾短信过滤
|
3月前
|
算法 安全 数据安全/隐私保护
支付系统---微信支付09------数字签名,现在Bob想要给Pink写一封信,信件的内容不需要加密,怎样能够保证信息的完整性,使用信息完整性的主要手段是摘要算法,散列函数,哈希函数,H称为数据指纹
支付系统---微信支付09------数字签名,现在Bob想要给Pink写一封信,信件的内容不需要加密,怎样能够保证信息的完整性,使用信息完整性的主要手段是摘要算法,散列函数,哈希函数,H称为数据指纹
|
4月前
|
机器学习/深度学习 存储 算法
心得经验总结:微信红包随机算法转载
心得经验总结:微信红包随机算法转载
45 0
|
4月前
|
存储 运维 算法
社交软件红包技术解密(十三):微信团队首次揭秘微信红包算法,为何你抢到的是0.01元
本文中,我们将介绍几种主流的IM红包分配算法,相信聪明的你一定能从中窥见微信红包技术实现的一些奥秘。
84 0
|
5月前
|
小程序 JavaScript Java
基于微信小程序的垃圾分类小程序的设计与实现(源码+lw+部署文档+讲解等)
基于微信小程序的垃圾分类小程序的设计与实现(源码+lw+部署文档+讲解等)