◆
精彩推荐
◆
倒计时!由易观携手CSDN联合主办的第三届易观算法大赛还剩 5 天,冠军团队将获得3万元!
本次比赛主要预测访问平台的相关事件的PV,UV流量(包括Web端,移动端等),大赛将会提供相应事件的流量数据,以及对应时间段内的所有事件明细表和用户属性表等数据,进行模型训练,并用训练好的模型预测规定日期范围内的事件流量。
推荐阅读
作者 | Jose Garcia
译者 | 吴振东
校对 | 张一豪、林亦霖,编辑 | 于腾凯
来源 | 数据派(ID:datapi)
导读:本文将利用OpenCV,Python和Ubidots来编写一个行人计数器程序,并对代码进行了较为详细的讲解。
pip install opencv-contrib-python
import cv2 cv2.__version__
pip install numpy
pip install imutils
pip install requests
from imutils.object_detectionimport non_max_suppressionimport numpy as npimport imutilsimport cv2import requestsimport timeimport argparseURL_EDUCATIONAL = "http://things.ubidots.com"URL_INDUSTRIAL = "http://industrial.api.ubidots.com"INDUSTRIAL_USER = True # Set this to False if you are an educational userTOKEN = "...." # Put here your Ubidots TOKENDEVICE = "detector" # Device where will be stored the resultVARIABLE = "people" # Variable where will be stored the result# Opencv pre-trained SVM with HOG people featuresHOGCV = 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# boxesrects = 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 resultprint("[INFO] Detecting people")result = detector(image)# shows the resultfor (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/secondif sample_time < 1:sample_time = 1while(True):# Capture frame-by-frameret, frame = cap.read()frame = imutils.resize(frame, width=min(400, frame.shape[1]))result = detector(frame.copy())# shows the resultfor (xA, yA, xB, yB) in result:cv2.rectangle(frame, (xA, yA), (xB, yB), (0, 255, 0), 2)cv2.imshow('frame', frame)# Sends resultsif time.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.time()if cv2.waitKey(1) & 0xFF == ord('q'):break# When everything done, release the capturecap.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 imageif 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 contextb64 = convert_to_base64(image)context = {"image": b64}# Sends the resultreq = 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 webcamif 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 endpointurl = URL_INDUSTRIAL if industrial else URL_EDUCATIONALurl = "{}/api/v1.6/devices/{}".format(url, device)payload = buildPayload(variable, value, context)headers = {"X-Auth-Token": token, "Content-Type": "application/json"}attempts = 0status = 400while status >= 400 and attempts <= 5:req = requests.post(url=url, headers=headers, json=payload)status = req.status_codeattempts += 1time.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()
python peopleCounter.py PATH_TO_IMAGE_FILE
python peopleCounter.py -i dataset/image_1.png
python peopleCounter.py -c true
HTML<img id="img" width="400px" height="auto"/>JSvar socket;var srv = "industrial.ubidots.com:443";// var srv = "app.ubidots.com:443" // Uncomment this line if you are an educational uservar VAR_ID = "5ab402dabbddbd3476d85967"; // Put here your var Idvar 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 oncefunction 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 serversocket = io.connect("https://"+ srv, {path: '/notifications'});var subscribedVars = [];// Function to publish the variable IDvar subscribeVariable = 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 listeningvar 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 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){var parsedValue = JSON.parse(value);console.log(parsedValue);//$('#img').attr('src', 'data:image/png;base64, ' + parsedValue.context.image);renderImage(parsedValue.context.image);})});
原文标题: People Counting with OpenCV, Python & Ubidots 原文链接: https://ubidots.com/blog/people-counting-with-opencv-python-and-ubidots/
◆
精彩推荐
◆
倒计时!由易观携手CSDN联合主办的第三届易观算法大赛还剩 5 天,冠军团队将获得3万元!
本次比赛主要预测访问平台的相关事件的PV,UV流量(包括Web端,移动端等),大赛将会提供相应事件的流量数据,以及对应时间段内的所有事件明细表和用户属性表等数据,进行模型训练,并用训练好的模型预测规定日期范围内的事件流量。
推荐阅读