编写计数器程序python_利用OpenCV、Python和Ubidots构建行人计数器程序(附完整代码)...

URL_EDUCATIONAL= "http://things.ubidots.com"URL_INDUSTRIAL= "http://industrial.api.ubidots.com"INDUSTRIAL_USER= True# Setthis to Falseifyou are an educational userTOKEN= "...."# Puthere your UbidotsTOKENDEVICE= "detector"# Devicewherewill be stored the resultVARIABLE= "people"# Variablewherewill be stored the result# Opencvpre-trained SVMwith HOGpeople featuresHOGCV= cv2.HOGDeorHOGCV.setSVMDetector(cv2.HOGDeor_getDefaultPeopleDetector)

在第1节中,我们导入必要的库来实现我们的探测器,imutils是一个有用的DIP库工具,让我们从结果中执行不同的转换,cv2是我们的OpenCV Python包装器,requests 可以通过HTTP发送数据/结果到Ubidots,argparse让我们从脚本中的命令终端来读取命令。

重要提示:不要忘记使用您的Ubidots帐户TOKEN更改这段代码,如果是学生用户,请务必将INDUSTRIAL_USER设置为FALSE。

导入库后,我们将对方向梯度直方图(Histogram of Oriented Gradient)进行初始化。方向梯度直方图的简称是HOG,它是最受欢迎的对象检测技术之一,已经在多个应用程序中实现并取得成功。OpenCV已经以高效的方式将HOG算法与支持向量机这种用于预测目的的经典机器学习技术(SVM)相结合,成为了一笔我们可以利用的财富。

这项声明:

cv2.HOGDeor_getDefaultPeopleDetector调用了预先训练的模型,用于OpenCV的行人检测,并提供支持向量机特征的评估功能。

第2节

defdetector(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# boxesrects = np.array([[x, y, x + w, y + h] for(x, y, w, h) inrects])result = non_max_suppression(rects, probs=None, overlapThresh=0.65)returnresult

detector函数是“神奇”诞生的地方,它可以接收分成三个颜色通道的RGB图像。为了避免出现性能问题,我们用imutils来调整图像大小,再从HOG对象调用detectMultiScale方法。然后,检测多尺度方法可以让我们使用SVM的分类结果去分析图像并知晓人是否存在。关于此方法的参数介绍超出了本教程的范围,但如果你想了解更多信息,请参阅官方OpenCV文档或查看Adrian Rosebrock的精彩解释。

HOG分析将会生成一些捕获框(针对检测到的对象),但有时这些框的重叠会导致误报或检测错误。为了避免这种混淆,我们将使用imutils库中的非最大值抑制实用程序来删除重叠的框 - 如下所示:

图片转载自

https://www.pyimagesearch.com

第3节

deflocalDetect(image_path):result = []image = cv2.imread(image_path)iflen(image) <= 0:print("[ERROR] could not read your local image")returnresultprint("[INFO] Detecting people")result = detector(image)# shows the resultfor(xA, yA, xB, yB) inresult:cv2.rectangle(image, (xA, yA), (xB, yB), (0, 255, 0), 2)cv2.imshow("result", image)cv2.waitKey(0)cv2.destroyAllWindowsreturn(result, image)

现在,在这一部分代码中,我们必须定义一个函数来从本地文件中读取图像并检测其中是否有人存在。为了实现这一点,我只是简单地调用了detector函数并添加了一个简单的循环来绘制探测器的圆框。它会返回检测到的框的数量和带有绘制检测的图像。然后,只需在新的OS窗口中重新创建结果即可。

第4节

defcameraDetect(token, device, variable, sample_time=5):cap = cv2.VideoCapture(0)init = time.time# Allowed sample time for Ubidots is 1 dot/secondifsample_time < 1:sample_time = 1while(True):# Capture frame-by-frameret, frame = cap.readframe = imutils.resize(frame, width=min(400, frame.shape[1]))result = detector(frame.copy)# shows the resultfor(xA, yA, xB, yB) inresult:cv2.rectangle(frame, (xA, yA), (xB, yB), (0, 255, 0), 2)cv2.imshow('frame', frame)# Sends resultsiftime.time - init >= sample_time:print("[INFO] Sending actual frame results")# Converts the image to base 64 and adds it to the contextb64 = convert_to_base64(frame)context = {"image": b64}sendToUbidots(token, device, variable,len(result), context=context)init = time.timeifcv2.waitKey(1) & 0xFF== ord('q'):break# When everything done, release the capturecap.releasecv2.destroyAllWindowsdefconvert_to_base64(image):image = imutils.resize(image, width=400)img_str = cv2.imencode('.png', image)[1].tostringb64 = base64.b64encode(img_str)returnb64.decode('utf-8')

与第3节的函数类似,第4节的函数将调用detector方法和绘图框,并使用OpenCV中的VideoCapture方法直接从网络摄像头检索图像。我们还稍微修改了officialOpenCV,从而在相机中获取图像,并且每隔“n”秒将结果发送到一个Ubidots帐户(sendToUbidots函数将在本教程的后面部分进行回顾)。 函数convert_to_base64会将图像转换为基本的64位字符串,这个字符串对于在HTML Canvas widget中使用Java代码查看Ubidots中的结果非常重要。

第5节

defdetectPeople(args):image_path = args["image"]camera = Trueifstr(args["camera"]) == 'true'elseFalse# Routine to read local imageifimage_path != Noneandnotcamera: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 contextb64 = convert_to_base64(image)context = {"image": b64}# Sends the resultreq = sendToUbidots(TOKEN, DEVICE, VARIABLE,len(result), context=context)ifreq.status_code >= 400:print("[ERROR] Could not send data to Ubidots")returnreq# Routine to read images from webcamifcamera:print("[INFO] reading camera images")cameraDetect(TOKEN, DEVICE, VARIABLE)

这个方法旨在通过终端插入参数并触发例程,对本地存储的图像文件或通过网络摄像来搜索行人。

第6节

defbuildPayload(variable, value, context):return{variable: {"value": value, "context": context}}defsendToUbidots(token, device, variable, value, context={}, industrial=True):# Builds the endpointurl = URL_INDUSTRIAL ifindustrial elseURL_EDUCATIONALurl = "{}/api/v1.6/devices/{}".format(url, device)payload = buildPayload(variable, value, context)headers = {"X-Auth-Token": token, "Content-Type": "application/json"}attempts = 0status = 400whilestatus >= 400andattempts <= 5:req = requests.post(url=url, headers=headers, json=payload)status = req.status_codeattempts += 1time.sleep(1)returnreq

第6节的这两个函数是把结果发送给Ubidots从而理解和对数据进行可视化的两条主干道。第一个函数 def buildPayload是在请求中构建有效的负载,而第二个函数 def sendToUbidots则接收你的Ubidots参数(TOKEN,变量和设备标签)用于存储结果。在这种情况下,OpenCV可以检测到圆盒的长度。作为备选,也可以发送上下文来将结果存储为base64图像,以便稍后进行检索。

第7节

defargsParser:ap = argparse.ArgumentParserap.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)returnargs

对于第7节,我们即将完成对代码的分析。函数 argsParser简单地解析并通过终端将脚本的参数以字典的形式返回。在解析器中有两个参数:

· image:在你的系统中图片文件的路径

· camera:这个变量如果设置为‘true’,那么就会调用cameraDetect方法

第8节

defmain:args = argsParserdetectPeople(args)if__name__ == '__main__':main

第8节是我们主函数代码中的最终部分,只是用来获取console中的参数,然后发起指定的程序。

别忘了,全部的代码都可以从Github上下载。

3、测试

打开你最喜爱的代码编辑器(sublime-text,notepad,nano等),然后复制并粘贴此处所提供的完整代码。使用你特定的Ubidots TOKEN更新代码并将文件另存为“peopleCounter.py”。

正确保存代码后,让我们从Caltech Dataset和Pexels公共数据集中随机选择的下面四个图像来进行测试:

为了对这些图像进行分析,首先你必须将图像存储在笔记本电脑或PC中,并记录好要分析图像的存放路径。

pythonpeopleCounter.pyPATH_TO_IMAGE_FILE

在我的例子中,我将图像存储在标记为“dataset”的路径中。要执行一项有效的命令,请运行以下命令,但请更换为你个人的文件存放路径。

pythonpeopleCounter.py -i dataset/image_1.png

如果你希望是从相机而不是本地文件中获取图像,只需运行以下命令:

pythonpeopleCounter.py -c true

测试结果:

除了这种查看测试结果的方式之外,你还可以实时查看存储在Ubidots帐户中的测试的结果:

4、创造你自己的仪表板

我们将使用HTML Canvas来实时观察所取得的结果,本教程不对HTML canvas widget做讲解,如果你不了解如何使用它们,请参阅以下文章:

Canvas Widget Examples

Canvas Widget Introductory Demo

Canvas Creating a Real Time Widget

我们将使用基本的实时示例加上微小的修改,便于观看我们的图像。 你可以在下面看到关于widget的代码。

HTMLJSvarsocket;varsrv = "industrial.ubidots.com:443";// var srv = "app.ubidots.com:443" // Uncomment this line if you are an educational uservarVAR_ID = "5ab402dabbddbd3476d85967"; // Put here your var IdvarTOKEN = ""// Put here your token$( document).ready(function(){functionrenderImage(imageBase64){if(!imageBase64) return;$('#img').attr('src', 'data:image/png;base64, '+ imageBase64);}// Function to retrieve the last value, it runs only oncefunctiongetDataFromVariable(variable, token, callback){varurl = 'https://things.ubidots.com/api/v1.6/variables/'+ variable + '/values';varheaders = {'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 serversocket = io.connect("https://"+ srv, {path: '/notifications'});varsubscribedVars = [];// Function to publish the variable IDvarsubscribeVariable = function(variable, callback){// Publishes the variable ID that wishes to listensocket.emit('rt/variables/id/last_value', {variable: variable});// Listens for changessocket.on('rt/variables/'+ variable + '/last_value', callback);subscribedVars.push(variable);};// Function to unsubscribed for listeningvarunSubscribeVariable = function(variable){socket.emit('unsub/rt/variables/id/last_value', {variable: variable});varpst = subscribedVars.indexOf(variable);if(pst !== -1){subscribedVars.splice(pst, 1);}};varconnectSocket = function(){// Implements the socket connectionsocket.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){varparsedValue = JSON.parse(value);console.log(parsedValue);//$('#img').attr('src', 'data:image/png;base64, ' + parsedValue.context.image);renderImage(parsedValue.context.image);})});

不要忘记把你的帐户TOKEN和变量ID放在代码段的开头。

第三部分的LIBRARIES

增加下面第三部分的libraries:

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、结果展示

在此链接中你可以看到带有结果的仪表板。

在本文中,我们探讨了如何使用DIP(图像处理),OpenCV和Ubidots来创建物联网人员计数器。通过这些服务,在对人物、场景或事物的检测与识别问题上,你的DIP应用程序会比PIR或其他光学传感器更加准确 – 这套程序提供了高效的行人计数器,而且不需要对早期数据的静态进行任何操作。

做一个快乐的码农!

关于作者Jose García:

UIS电子工程师,Ubuntu用户,布卡拉曼加人,程序员,有时很无聊,想要环游世界但却没太有希望完成这一梦想。 硬件和软件开发人员@Ubidots

译者介绍:

法国洛林大学计算机与决策专业硕士。现从事人工智能和大数据相关工作,以成为数据科学家为终生奋斗目标。来自山东济南,不会开挖掘机,但写得了Java、Python和PPT。

原文标题:

People Counting with OpenCV, Python & Ubidots

https://ubidots.com/blog/people-counting-with-opencv-python-and-ubidots/

(*本文为AI科技大本营转载文章,转载请联系作者)

倒计时!由易观携手CSDN联合主办的第三届易观算法大赛还剩 5 天,冠军团队将获得3万元!返回搜狐,查看更多

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值