资讯专栏INFORMATION COLUMN

树莓派+阿里云IoT人脸识别场景实战

BicycleWarrior / 1920人阅读

摘要:整体架构基于阿里云的架构运行效果阿里云产品平台函数计算表格存储存储人脸识别设备采购名称图片购买摄像头淘宝树莓派淘宝树莓派设备端开发目录结构在目录下创建文件夹,在创建文件夹,配置文件文件程序安装依赖

1.整体架构

基于阿里云的Serverless架构

运行效果

2.阿里云产品

IoT平台:https://www.aliyun.com/product/iot

函数计算:https://www.aliyun.com/product/fc

表格存储:https://www.aliyun.com/product/ots

OSS存储:https://www.aliyun.com/product/oss

人脸识别:https://data.aliyun.com/product/face

3.设备采购
名称 图片 购买
摄像头 ![image.png left 155x144.9410029498525](https://cdn.nlark.com/yuque/0... "") 淘宝
树莓派 ![image.png left 155x144.82939632545933](https://cdn.nlark.com/yuque/0... "") 淘宝
4.树莓派设备端开发 4.1 Enable Camera

4.2 目录结构

在/home/pi目录下创建 iot文件夹,

在/home/pi/iot创建 photos文件夹,iot.cfg配置文件,iot.py文件

4.3 Python3程序 4.3.1 安装依赖
pip3 install oss2
pip3 install picamera
pip3 install aliyun-python-sdk-iot-client
4.3.2 iot.cfg配置文件
[IOT]
productKey = xxx
deviceName = xxx
deviceSecret = xxx

[OSS]
ossAccessKey = xxx
ossAccessKeySecret = xxx
ossEndpoint = xxx
ossBucketId = xxx
4.3.3 iot.py应用程序
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import oss2
from picamera import PiCamera
import time
import aliyunsdkiotclient.AliyunIotMqttClient as AliyunIot
import configparser

config = configparser.ConfigParser()
config.read("iot.cfg")

# IoT
PRODUCE_KEY = config["IOT"]["productKey"]
DEVICE_NAME = config["IOT"]["deviceName"]
DEVICE_SECRET = config["IOT"]["deviceSecret"]

HOST = PRODUCE_KEY + ".iot-as-mqtt.cn-shanghai.aliyuncs.com"
SUBSCRIBE_TOPIC = "/" + PRODUCE_KEY + "/" + DEVICE_NAME + "/control";
# oss
OSS_AK = config["OSS"]["ossAccessKey"]
OSS_AK_SECRET = config["OSS"]["ossAccessKeySecret"]
OSS_ENDPOINT = config["OSS"]["ossEndpoint"]
OSS_BUCKET_ID = config["OSS"]["ossBucketId"]

auth = oss2.Auth(OSS_AK, OSS_AK_SECRET)
bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUCKET_ID)

camera = PiCamera()
camera.resolution = (720,480)

# Take a photo first, then upload photo to oss
def take_photo():
    ticks = int(time.time())
    fileName = "raspi%s.jpg" % ticks
    filePath = "/home/pi/iot/photos/%s" % fileName
    # take a photo
    camera.capture(filePath)
    # upload to oss
    bucket.put_object_from_file("piPhotos/"+fileName, filePath)


def on_connect(client, userdata, flags, rc):
    print("subscribe "+SUBSCRIBE_TOPIC)
    client.subscribe(topic=SUBSCRIBE_TOPIC)


def on_message(client, userdata, msg):
    print("receive message topic :"+ msg.topic)
    print(str(msg.payload))
    take_photo()


if __name__ == "__main__":
    client = AliyunIot.getAliyunIotMqttClient(PRODUCE_KEY,DEVICE_NAME, DEVICE_SECRET, secure_mode=3)
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(host=HOST, port=1883, keepalive=60)
    # loop
    client.loop_forever()
5.函数计算开发 5.1 index.js应用程序
const request = require("request");
const url = require("url");
const crypto = require("crypto");
const TableStore = require("tablestore");
const co = require("co");
const RPCClient = require("@alicloud/pop-core").RPCClient;

const config = require("./config");

//iot client
const iotClient = new RPCClient({
    accessKeyId: config.accessKeyId,
    secretAccessKey: config.secretAccessKey,
    endpoint: config.iotEndpoint,
    apiVersion: config.iotApiVersion
});
//ots client
const otsClient = new TableStore.Client({
    accessKeyId: config.accessKeyId,
    secretAccessKey: config.secretAccessKey,
    endpoint: config.otsEndpoint,
    instancename: config.otsInstance,
    maxRetries: 20
});

const options = {
    url: config.dtplusUrl,
    method: "POST",
    headers: {
        "Accept": "application/json",
        "Content-type": "application/json"
    }
};

module.exports.handler = function(event, context, callback) {

    var eventJson = JSON.parse(event.toString());

    try {
        var imgUrl = config.ossEndpoint + eventJson.events[0].oss.object.key;

        options.body = JSON.stringify({ type: 0, image_url: imgUrl });
        options.headers.Date = new Date().toUTCString();
        options.headers.Authorization = makeDataplusSignature(options);

        request.post(options, function(error, response, body) {

            console.log("face/attribute response body" + body)
            const msg = parseBody(imgUrl, body)
            //
            saveToOTS(msg, callback);

        });
    } catch (err) {
        callback(null, err);
    }
};

parseBody = function(imgUrl, body) {

    body = JSON.parse(body);
    //face_rect [left, top, width, height],
    const idx = parseInt(10 * Math.random() % 4);
    const age = (parseInt(body.age[0])) + "岁";
    const expression = (body.expression[0] == "1") ? config.happy[idx] : config.normal[idx];
    const gender = (body.gender[0] == "1") ? "帅哥" : "靓女";
    const glass = (body.glass[0] == "1") ? "戴眼镜" : "火眼金睛";

    return {
        "imgUrl": imgUrl,
        "gender": gender,
        "faceRect": body.face_rect.join(","),
        "glass": glass,
        "age": age,
        "expression": expression
    };
}

//pub msg to WebApp by IoT
iotPubToWeb = function(payload, cb) {
    co(function*() {
        try {
            //创建设备
            var iotResponse = yield iotClient.request("Pub", {
                ProductKey: config.productKey,
                TopicFullName: config.topicFullName,
                MessageContent: new Buffer(JSON.stringify(payload)).toString("base64"),
                Qos: 0
            });
        } catch (err) {
            console.log("iotPubToWeb err" + JSON.stringify(err))
        }

        cb(null, payload);
    });
}

saveToOTS = function(msg, cb) {

    var ots_data = {
        tableName: config.tableName,
        condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),

        primaryKey: [{ deviceId: "androidPhoto" }, { id: TableStore.PK_AUTO_INCR }],

        attributeColumns: [
            { "imgUrl": msg.imgUrl },
            { "gender": msg.gender },
            { "faceRect": msg.faceRect },
            { "glass": msg.glass },
            { "age": msg.age },
            { "expression": msg.expression }
        ],

        returnContent: { returnType: TableStore.ReturnType.Primarykey }
    }

    otsClient.putRow(ots_data, function(err, data) {

        iotPubToWeb(msg, cb);
    });
}

makeDataplusSignature = function(options) {

    const md5Body = crypto.createHash("md5").update(new Buffer(options.body)).digest("base64");

    const stringToSign = "POST
application/json
" + md5Body + "
application/json
" + options.headers.Date + "
/face/attribute"
    // step2: 加密 [Signature = Base64( HMAC-SHA1( AccessSecret, UTF-8-Encoding-Of(StringToSign) ) )]
    const signature = crypto.createHmac("sha1", config.secretAccessKey).update(stringToSign).digest("base64");

    return "Dataplus " + config.accessKeyId + ":" + signature;
}
5.2 config.js配置文件
module.exports = {
    accessKeyId: "账号ak",
    secretAccessKey: "账号ak secret",
    iotEndpoint: "https://iot.cn-shanghai.aliyuncs.com",
    iotApiVersion: "2018-01-20",
    productKey: "web大屏产品pk",
    topicFullName: "web大屏订阅识别结果的topic",

//可选,如果不保存结果,不需要ots
    otsEndpoint: "ots接入点",
    otsInstance: "ots实例",
    tableName: "ots结果存储表",
}
6. Web端App开发




    
    阿里云IoT
    



    
7. 拍照指令触发器
/**
 * package.json 添加依赖:"@alicloud/pop-core": "1.5.2"
 */
const co = require("co");
const RPCClient = require("@alicloud/pop-core").RPCClient;

const options = {
    accessKey: "替换ak",
    accessKeySecret: "替换ak Secret",
};

//1.初始化client
const client = new RPCClient({
    accessKeyId: options.accessKey,
    secretAccessKey: options.accessKeySecret,
    endpoint: "https://iot.cn-shanghai.aliyuncs.com",
    apiVersion: "2018-01-20"
});

const params = {
    ProductKey: "a1p35XsaOS7",
    TopicFullName: "相机指令topic",
    MessageContent: new Buffer("{"action":"takephoto"}").toString("base64"),
    Qos: "0"
};

co(function*() {
    try {
        //3.发起API调用
        const response = yield client.request("Pub", params);
        console.log(JSON.stringify(response));
    } catch (err) {
        console.log(err);
    }
});

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/42595.html

相关文章

  • 边缘运算,一股方兴未艾的风潮

    摘要:近几年行动通讯人工智能物联网及相关是热门应用,而且未来也展现出万物皆智能的趋势。这其中边缘运算也称边缘计算是一股即将兴起的风潮。甚至应用于物联网非实时性小型传感器网络的智能边缘运算的普通单芯片如系列也可都算是边缘运算。近几年行动通讯、人工智能、物联网及相关是热门应用,而且未来也展现出「万物皆智能(AIoT = AI + IoT)」的趋势。不论是家电、交通、零售、虚拟扩增实境(AR/VR/XR...

    terasum 评论0 收藏0
  • 人脸实时签到(three.js+tracking.js)基于浏览器

    摘要:识别出人脸后,要算宽度,要在一定的宽度才算人脸,可以裁剪出正方形发送检索人脸。 人脸签到 花了一个星期做了人脸签到的demo,github地址欢迎star,在线预览大屏幕demo 先说些废话,以前做年会的抽奖,感觉好傻,现在正好在学threejs,就想做个这样的场景来抽奖的方式,又在学人脸识别的知识,就想做人脸识别签到,就想都做在浏览器中 体验完整过程 1.微信扫描注册上传头像 s...

    notebin 评论0 收藏0
  • “旧城改造”的背后——银泰新零售阿里解决方案(下)

    摘要:同时通过云摄像头的图像采集,图像分析,结合人脸识别,以及阿里沉淀的人脸底库,我们目前正在做银泰场内的智能客流系统。文/阿里云MVP 银泰技术高级经理 贾爽 相关免费课程《银泰新零售上云解决方案精讲》上线中立足实战 讲透经典案例 助你快速理解新零售 第一节学习地址第二节学习地址 安全策略的部署和风险防控先来说一下边界安全,下图是银泰边界安全所接入的所有阿里云产品: 我们结合了阿里云安全产...

    wenhai.he 评论0 收藏0

发表评论

0条评论

BicycleWarrior

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<