作者 | 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
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代码实现
-
阿里云弹性计算负责人蒋林泉:亿级场景驱动的技术自研之路