47

当微信小程序遇上 TensorFlow:小程序实现

 5 years ago
source link: https://mp.weixin.qq.com/s/d2OR5Yn8hOneiTKhyUfWXg?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

ZvIVJj2.jpg!web

首先要吐槽一下微信小程序开发工具没有Linux版本,为了开发微信小程序,我不得不搬出我的娱乐机iMac。对着硕大的屏幕,看着如蚂蚁般的文字,真心想问一下,那些使用iMac做开发机的朋友们不会肩周发炎,双眼发涩么?

言归正传,在前面的两篇文章《 当微信小程序遇上TensorFlow:Server端实现 》和《 当微信小程序遇上TensorFlow:Server端实现补充 》中,谈到了服务端的实现,本文将继续探讨小程序的实现。

我之前一直从事浏览器引擎的开发工作,对于HTML、CSS、Javascript并不陌生,但没有过多使用前端技术。好在微信小程序在很多地方借鉴了HTML、CSS,也用到了JS,上手起来很快。在浏览了一下入门手册之后,就在微信小程序模板的基础上开发出了一个简单的原型程序。

本微信小程序的主要实现功能点在于:

  1. 调用相机拍照或选择相册中的图片;

  2. 图片缩放,获取图像的RGB数据,;

  3. 组成JSON数据,通过HTTP POST发送到服务器端,并接收返回的响应数据

调用相机拍照或选择相册

由于微信为小程序封装了拍照和选择相册功能,提供了 wx.chooseImage API,所以这个功能实现起来非常简单:

 // 拍照
  doTakePhoto: function () {
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: function (res) {
        ...
      },
      fail: e => {
        console.error(e);
      }
    })
  }

图片缩放

网上有相关的资料,具体说来其方法是在小程序page中放一个Canvas,然后调用Canvas Context的 drawImage 绘制图像,最后调用 wx.canvasGetImageData 得到图片的像素信息,代码如下:

// 获取图像RGB数据
var getImageRGB = function (canvasId, imgUrl, callback, imgWidth, imgHeight) {
  const ctx = wx.createCanvasContext(canvasId);
  ctx.drawImage(imgUrl, 0, 0, imgWidth || 299, imgHeight || 299);
  ctx.draw(false, () => {
    // API 1.9.0 获取图像数据
    wx.canvasGetImageData({
      canvasId: canvasId,
      x: 0,
      y: 0,
      width: imgWidth || 299,
      height: imgHeight || 299,
      success(res) {
        var result = res;
        console.log([result.data.buffer]);

        var i, j;
        rows = [];
        for (i = 0; i < result.width; i++) {
          cols = [];
          for (j = 0; j < result.height; j++) {
            rgb = [];
            index = i * result.width + j * 4;         // 每个点包含RGBA 4个分量
            rgb.push(result.data[index] / 255);       // r
            rgb.push(result.data[index + 1] / 255);   // g
            rgb.push(result.data[index + 2] / 255);   // b
            // 忽略alpha值

            cols.push(rgb);
          }
          rows.push(cols);
        }

        callback(rows);
      },
      fail: e => {
        console.error(e);
      },
    })
  })
};

这段代码很容易理解,获取到图像的RGB数据后,将其存放入JSON数组中。

HTTP POST

微信为小程序原生提供了 wx.request API,所以在功能实现上不费吹灰之力:

getImageRGB('dogCanvas', filePath, function (rgbData) {
  //  在此处得到的RGB数据
  json_data = {
    "model_name": "default", "data": { "image": [] }
  }
  json_data["data"]["image"] = [rgbData];

  wx.request({
    url: "https://ilego.club:8500",
    method: "POST",
    data: json_data,
    success: function (respose) {
      prediction = respose.data["prediction"];
      console.log(prediction);
    }
  });
});

小结

微信小程序开发起来还是比较简单的,原生提供的功能组件能够极大的简化开发工作,微信小程序开发工具提供了很好的模拟调试环境。如果有过前端开发经验,入手会更加简单。当然,这只是针对入门而言,如果要开发一个产品,需要设计更加复杂的界面,考虑更多的用户交互,那并不是一件简单的事情。

目前这个微信小程序仍然只是一个雏形,后续会持续进行完善,有兴趣的可以访问:https://github.com/mogoweb/aiexamples/ ,同时敬请关注我的微信公众号:云水木石。

VBreEnM.jpg!web

参考

  1. 微信小程序图片压缩及base64化上传

  2. javascript加载图片查看具体某一点RGB值

  3. 微信小程序API: https://developers.weixin.qq.com/miniprogram/dev/api/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK