利用OpenCV、Python和Ubidots构建行人计数器程序(附完整代码)
作者 | Jose Garcia
译者 | 吴振东
校对 | 张一豪、林亦霖,编辑 | 于腾凯
来源 | 数据派(ID:datapi)
导读:本文将利用OpenCV,Python和Ubidots来编写一个行人计数器程序,并对代码进行了较为详细的讲解。
- 应用需求
- 编码 – 8个小节
- 测试
- 创造你自己的仪表板
- 结果展示
- 任何带有Ubuntu衍生版本的嵌入式Linux
- 操作系统中安装了Python 3或更高版本
- OS中安装了OpenCV 3.0或更高版本。如果使用Ubuntu或其衍生产品,请按照官方安装教程或运行以下命令:
pip install opencv-contrib-python
import cv2 cv2.__version__
pip install numpy
pip install imutils
pip install requests
from imutils.object_detection
import non_max_suppression
import numpy as np
import imutils
import cv2
import requests
import time
import argparse URL_EDUCATIONAL = "http://things.ubidots.com"
URL_INDUSTRIAL = "http://industrial.api.ubidots.com"
INDUSTRIAL_USER = True # Set this to False if you are an educational user
TOKEN = "...." # Put here your Ubidots TOKEN
DEVICE = "detector" # Device where will be stored the result
VARIABLE = "people" # Variable where will be stored the result # Opencv pre-trained SVM with HOG people features
HOGCV = cv2.HOGDescriptor()
HOGCV.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
def detector(image): ''' @image is a numpy array ''' image = imutils.resize(image, width=min(400, image.shape[1])) clone = image.copy() (rects, weights) = HOGCV.detectMultiScale(image, winStride=(8, 8), padding=(32, 32), scale=1.05) # Applies non-max supression from imutils package to kick-off overlapped # boxes rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects]) result = non_max_suppression(rects, probs=None, overlapThresh=0.65) return result
def localDetect(image_path): result = [] image = cv2.imread(image_path) if len(image) <= 0: print("[ERROR] could not read your local image") return result print("[INFO] Detecting people") result = detector(image) # shows the result for (xA, yA, xB, yB) in result: cv2.rectangle(image, (xA, yA), (xB, yB), (0, 255, 0), 2) cv2.imshow("result", image) cv2.waitKey(0) cv2.destroyAllWindows() return (result, image)
def cameraDetect(token, device, variable, sample_time=5): cap = cv2.VideoCapture(0) init = time.time() # Allowed sample time for Ubidots is 1 dot/second if sample_time < 1: sample_time = 1 while(True): # Capture frame-by-frame ret, frame = cap.read() frame = imutils.resize(frame, width=min(400, frame.shape[1])) result = detector(frame.copy()) # shows the result for (xA, yA, xB, yB) in result: cv2.rectangle(frame, (xA, yA), (xB, yB), (0, 255, 0), 2) cv2.imshow('frame', frame) # Sends results if time.time() - init >= sample_time: print("[INFO] Sending actual frame results") # Converts the image to base 64 and adds it to the context b64 = convert_to_base64(frame) context = {"image": b64} sendToUbidots(token, device, variable, len(result), context=context) init = time.time() if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows() def convert_to_base64(image): image = imutils.resize(image, width=400) img_str = cv2.imencode('.png', image)[1].tostring() b64 = base64.b64encode(img_str) return b64.decode('utf-8')
def detectPeople(args): image_path = args["image"] camera = True if str(args["camera"]) == 'true' else False # Routine to read local image if image_path != None and not camera: print("[INFO] Image path provided, attempting to read image") (result, image) = localDetect(image_path) print("[INFO] sending results") # Converts the image to base 64 and adds it to the context b64 = convert_to_base64(image) context = {"image": b64} # Sends the result req = sendToUbidots(TOKEN, DEVICE, VARIABLE, len(result), context=context) if req.status_code >= 400: print("[ERROR] Could not send data to Ubidots") return req # Routine to read images from webcam if camera: print("[INFO] reading camera images") cameraDetect(TOKEN, DEVICE, VARIABLE)
def buildPayload(variable, value, context): return {variable: {"value": value, "context": context}} def sendToUbidots(token, device, variable, value, context={}, industrial=True): # Builds the endpoint url = URL_INDUSTRIAL if industrial else URL_EDUCATIONAL url = "{}/api/v1.6/devices/{}".format(url, device) payload = buildPayload(variable, value, context) headers = {"X-Auth-Token": token, "Content-Type": "application/json"} attempts = 0 status = 400 while status >= 400 and attempts <= 5: req = requests.post(url=url, headers=headers, json=payload) status = req.status_code attempts += 1 time.sleep(1) return req
def argsParser(): ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", default=None, help="path to image test file directory") ap.add_argument("-c", "--camera", default=False, help="Set as true if you wish to use the camera") args = vars(ap.parse_args()) return args
def main(): args = argsParser() detectPeople(args) if __name__ == '__main__': main()
3、测试
python peopleCounter.py PATH_TO_IMAGE_FILE
python peopleCounter.py -i dataset/image_1.png
python peopleCounter.py -c true
4、创造你自己的仪表板
- Canvas Widget Examples
- Canvas Widget Introductory Demo
- Canvas Creating a Real Time Widget
HTML
<img id="img" width="400px" height="auto"/>
JS
var socket;
var srv = "industrial.ubidots.com:443";
// var srv = "app.ubidots.com:443" // Uncomment this line if you are an educational user
var VAR_ID = "5ab402dabbddbd3476d85967"; // Put here your var Id
var TOKEN = "" // Put here your token
$( document ).ready(function() { function renderImage(imageBase64){ if (!imageBase64) return; $('#img').attr('src', 'data:image/png;base64, ' + imageBase64);
} // Function to retrieve the last value, it runs only once
function getDataFromVariable(variable, token, callback) { var url = 'https://things.ubidots.com/api/v1.6/variables/' + variable + '/values'; var headers = { 'X-Auth-Token': token, 'Content-Type': 'application/json' }; $.ajax({ url: url, method: 'GET', headers: headers, data : { page_size: 1 }, success: function (res) { if (res.results.length > 0){ renderImage(res.results[0].context.image); } callback(); } });
} // Implements the connection to the server
socket = io.connect("https://"+ srv, {path: '/notifications'});
var subscribedVars = []; // Function to publish the variable ID
var subscribeVariable = function (variable, callback) { // Publishes the variable ID that wishes to listen socket.emit('rt/variables/id/last_value', { variable: variable }); // Listens for changes socket.on('rt/variables/' + variable + '/last_value', callback); subscribedVars.push(variable);
}; // Function to unsubscribed for listening
var unSubscribeVariable = function (variable) { socket.emit('unsub/rt/variables/id/last_value', { variable: variable }); var pst = subscribedVars.indexOf(variable); if (pst !== -1){ subscribedVars.splice(pst, 1); }
}; var connectSocket = function (){ // Implements the socket connection socket.on('connect', function(){ console.log('connect'); socket.emit('authentication', {token: TOKEN}); }); window.addEventListener('online', function () { console.log('online'); socket.emit('authentication', {token: TOKEN}); }); socket.on('authenticated', function () { console.log('authenticated'); subscribedVars.forEach(function (variable_id) { socket.emit('rt/variables/id/last_value', { variable: variable_id }); }); });
} /* Main Routine */
getDataFromVariable(VAR_ID, TOKEN, function(){ connectSocket();
}); connectSocket(); //connectSocket();
// Subscribe Variable with your own code.
subscribeVariable(VAR_ID, function(value){ var parsedValue = JSON.parse(value); console.log(parsedValue); //$('#img').attr('src', 'data:image/png;base64, ' + parsedValue.context.image); renderImage(parsedValue.context.image); })
});
- https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
- https://iot.cdnedge.bluemix.net/ind/static/js/libs/socket.io/socket.io.min.js
- 当你保存你的widget,你可以获得类似于下面的结果:
5、结果展示
关于作者Jose García:
原文标题:People Counting with OpenCV, Python & Ubidots原文链接:https://ubidots.com/blog/people-counting-with-opencv-python-and-ubidots/
◆
精彩推荐
◆
倒计时!由易观携手CSDN联合主办的第三届易观算法大赛还剩 5 天,冠军团队将获得3万元!
本次比赛主要预测访问平台的相关事件的PV,UV流量(包括Web端,移动端等),大赛将会提供相应事件的流量数据,以及对应时间段内的所有事件明细表和用户属性表等数据,进行模型训练,并用训练好的模型预测规定日期范围内的事件流量。
推荐阅读
知乎算法团队负责人孙付伟:Graph Embedding在知乎的应用实践
大数据工程师手册:全面系统的掌握必备知识与工具
经典再读 | NASNet:神经架构搜索网络在图像分类中的表现
激光雷达,马斯克看不上,却又无可替代?
卷积神经网络中十大拍案叫绝的操作
Docker是啥?容器变革的火花?
5大必知的图算法,附Python代码实现
阿里云弹性计算负责人蒋林泉:亿级场景驱动的技术自研之路
利用OpenCV、Python和Ubidots构建行人计数器程序(附完整代码)相关推荐
- OpenCV输出版本和构建配置的实例(附完整代码)
OpenCV输出版本和构建配置的实例 OpenCV输出版本和构建配置的实例 OpenCV输出版本和构建配置的实例 #include <opencv2/core/utility.hpp> # ...
- Py之pygame:有趣好玩—利用pygame库实现鱼儿自动实时目标跟踪(附完整代码)
Py之pygame:有趣好玩-利用pygame库实现鱼儿自动实时目标跟踪(附完整代码) 目录 输出结果 实现代码 输出结果 实现代码 #Py之pygame:利用pygame库实现鱼儿自动实时目标跟踪i ...
- c++代码好玩_Py之pygame:有趣好玩—利用pygame库实现鱼儿自动实时目标跟踪(附完整代码)...
Py之pygame:有趣好玩-利用pygame库实现鱼儿自动实时目标跟踪(附完整代码) 目录 输出结果 实现代码 输出结果 实现代码 #Py之pygame:利用pygame库实现鱼儿自动实时目标跟 ...
- python中import cv2遇到的错误及安装方法_独家利用OpenCV,Python和Ubidots来构建行人计数器程序(附代码amp;解析)...
作者:Jose Garcia 翻译:吴振东 校对:张一豪 本文约4000字,建议阅读14分钟. 本文将利用OpenCV,Python和Ubidots来编写一个行人计数器程序,并对代码进行了较为详细的讲 ...
- 干货 | 利用OpenCV,Python和Ubidots来构建行人计数器程序(附代码解析)
作者 | Jose Garcia 翻译 | 吴振东 校对 | 张一豪 来源 | 数据派THU(DatapiTHU ) 数字图像处理(DIP)技术目前发展非常迅速,这在很大程度上要归功于开发人员可以访问 ...
- opengl实现三维动画简单代码_使用Python简单实现马赛克拼图!内附完整代码
今天小编带大家使用python简单实现马赛克拼图,内容比以往会稍长一些,各位看官老爷可以慢慢细读,若有不足之处还望请斧正,闲话不多说,请看文章. 先看原图: 效果图: 思路: 拼图的原理其实很简单,就 ...
- 基于python nlp PyTorch智能对联生成系统 附完整代码 毕业设计
软件标题:智能对联生成系统 b 系统概述 使用项目:智能对联生成系统 软件用途:通过网页端可以获取到根据已有上联只能生成的下联. 开发历史:本项目未曾有前置版本.但在服务器搭建,Tensorflow ...
- python firmata协议利用arduino操控麦克纳姆轮小车(附完整代码)
python firmata协议利用arduino操控麦克纳姆轮小车 前言 一.python中pyfirmata的环境 材料 二.使用步骤 1.小车的安装方式 我在这采用的是X型安装方式 总结 前言 ...
- 利用pyecharts绘制新浪微博传播图(文末附完整代码地址)
文章目录 任务 来龙去脉 过程 绘图代码 绘图参数分析 结点参数格式 联系参数格式 类别参数格式 总览 获取转发关系 构造数据结构 集成json文件 代码地址 任务 延续之前的爬虫任务,最初同学提出的 ...
最新文章
- nodejs 转换long到unsigned long(NXT)
- 【Android】RxJava的使用(一)基本用法
- 加强数据中心安全的六条措施
- 水利水电工程管理与实务电子版习题_水利水电工程管理与实务复习题集
- (六)docker-compose使用教程
- webpack简单修改版本号(单页面)
- 详解一个自己原创的正则匹配IP的表达式
- 史上最全Java多线程面试60题,含答案大赠送!
- java查询数据库的方式_Java连接各种数据库方式速查表
- webmin账户重置密码
- C++调用编译好的darknet来进行物体监测
- Delphi基础教程图文版之数组
- 关于微PE的那些事和重装系统
- Shiro面试题总结
- 那些年 用过的经典App
- 码云推送代码后不显示贡献度
- webstorm 使用技巧
- 【饭谈】为什么总有人劝你用mac来办公?
- Baxer双臂机器人Ubuntu20.04+ROS noetic开发环境配置
- 【MySQL·水滴计划】第三话- SQL的基本概念
热门文章
- tomcat中server.xml文件详解
- ARM 位置无关代码(PIC)的分析理解
- JavaBean规范
- ESX上ORACLE 10.2RAC(4.在REHAT4.7中安装ORACLE RAC)
- SpringDataJpa根据多个id物品清单id查询房源编号
- 待解决--LaTex为什么其他符号可以用,插入大于等于,或者小于等于就报错?
- spring中实现自己的初始化逻辑
- codeforce843B Interactive LowerBound
- Python之路-python(Queue队列、进程、Gevent协程、Select\Poll\Epoll异步IO与事件驱动)
- java中文乱码解决之道(二)—–字符编码详解:基础知识 + ASCII + GB**