案例 :利用OpenCV,Python和Ubidots来构建行人计数器程序(附代码&解析)
本文将利用OpenCV,Python和Ubidots来编写一个行人计数器程序,并对代码进行了较为详细的讲解。
应用需求
编码 – 8个小节
测试
创造你自己的仪表板
结果展示
任何带有Ubuntu衍生版本的嵌入式Linux
操作系统中安装了Python 3或更高版本
OS中安装了OpenCV 3.0或更高版本。如果使用Ubuntu或其衍生产品,请按照官方安装教程或运行以下命令:
pip install opencv-contrib-python
按照官方操作指南来安装Numpy,或者运行下面的命令
安装imutils
安装requests
2、编码
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())
cv2.HOGDescriptor_getDefaultPeopleDetector()调用了预先训练的模型,用于OpenCV的行人检测,并提供支持向量机特征的评估功能。
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
图片转载自https://www.pyimagesearch.com
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
对于第7节,我们即将完成对代码的分析。函数 argsParser()简单地解析并通过终端将脚本的参数以字典的形式返回。在解析器中有两个参数:
· image:在你的系统中图片文件的路径
· camera:这个变量如果设置为‘true’,那么就会调用cameraDetect()方法
第8节:
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
UIS电子工程师,Ubuntu用户,布卡拉曼加人,程序员,有时很无聊,想要环游世界但却没太有希望完成这一梦想。 硬件和软件开发人员@Ubidots
原文标题:
People Counting with OpenCV, Python & Ubidots
原文链接:
译者简介:吴振东,法国洛林大学计算机与决策专业硕士。现从事人工智能和大数据相关工作,以成为数据科学家为终生奋斗目标。来自山东济南,不会开挖掘机,但写得了Java、Python和PPT。
北京外国语大学今年正式开设
“商业数据分析”方向在职研究生
毕业后
可获国家承认双一流高校硕士文凭
数据分析粉丝专属福利,扫码免费听课👇