Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import argparse
- import cv2
- import time
- import mysql.connector
- import json
- from datetime import datetime
- from influxdb import InfluxDBClient
- import ast
- import os
- import logging
- from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
- import threading
- # ---------------------
- # TELEGRAM Handlers
- def people_total(update, context):
- update.message.reply_text('Total number of people present in store:' + str(total))
- def zone_risk(update, context):
- update.message.reply_text('Risky zones due to people presence'+ label2)
- def echo(update, context):
- """Echo the user message."""
- update.message.reply_text('Total number of people is:'+ label)
- # update.message.reply_text(update.message.text)
- def pic(update, context):
- chat_id = update.message.chat_id # get the recipient´s ID
- #context.bot.sendPhoto(chat_id=chat_id, photo=open(path, 'rb'))
- context.bot.sendPhoto(chat_id=chat_id, photo=open('./hall.jpg', 'rb'))
- def main_telegram():
- """Start the bot."""
- # Create the Updater and pass it your bot's token.
- # Make sure to set use_context=True to use the new context based callbacks
- # Post version 12 this will no longer be necessary
- updater = Updater("xxxxxx", use_context=True)
- # Get the dispatcher to register handlers
- dp = updater.dispatcher
- # on different commands - answer in Telegram
- dp.add_handler(CommandHandler("people", people_total))
- dp.add_handler(CommandHandler("risk", zone_risk))
- dp.add_handler(CommandHandler("picture", pic))
- # on noncommand i.e message - echo the message on Telegram
- dp.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
- # Start the Bot
- updater.start_polling()
- # Run the bot until you press Ctrl-C or the process receives SIGINT,
- # SIGTERM or SIGABRT. This should be used most of the time, since
- # start_polling() is non-blocking and will stop the bot gracefully.
- updater.idle()
- # ---------------------
- # TELEGRAM Enable logging
- logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
- level=logging.INFO)
- logger = logging.getLogger(__name__)
- # ---------------------
- # THREADING
- # threading.Thread(target=main_telegram).start()
- x = threading.Thread(target=main_telegram, args=())
- x.start()
- # ---------------------
- # import pandas as pd
- # INFLUXDB
- # client = InfluxDBClient('xxxxx', 3306, 'xxxx', 'xxxx', 'TRIALDB')
- # client.create_database('TRIALDB') # Problems with DB creation
- # ---------------------
- # SUB-DIRECTORY CREATION
- working_path = os.getcwd()
- # sub_directory = "Image"
- # path = os.path.join(working_path, sub_directory)
- path = working_path
- os.makedirs(path, exist_ok = True)
- print(path)
- # ---------------------
- # CAFFE construct the argument parse and parse the arguments
- ap = argparse.ArgumentParser()
- ap.add_argument("-i", "--image", required=True,
- help="path to input image")
- ap.add_argument("-p", "--prototxt", required=True,
- help="path to Caffe 'deploy' prototxt file")
- ap.add_argument("-m", "--model", required=True,
- help="path to Caffe pre-trained model")
- ap.add_argument("-c", "--confidence", type=float, default=0.2,
- help="minimum probability to filter weak detections")
- args = vars(ap.parse_args())
- CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
- "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
- "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
- "sofa", "train", "tvmonitor"]
- COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
- print("[INFO] loading model…")
- image = cv2.imread(args["image"])
- net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
- (h, w) = image.shape[:2]
- blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5)
- print("[INFO] computing object detections…")
- print(blob.shape)
- net.setInput(blob)
- detections = net.forward()
- # ---------------------
- # RECTANGLE LISTS DEFINITION BASED ON APPLE.JPG + ZONE COUNTER CREATION
- StartXlist = [1,230,580,30,275,460,155,295,415,200,300,390]
- StartYlist = [265,265,265,120,120,120,68,68,68,40,40,40]
- EndXlist = [90,430,640,210,380,620,240,355,510,255,355,465]
- EndYlist = [420,420,420,220,220,220,110,110,110,65,65,65]
- PeopleinZone=[0,0,0,0,0,0,0,0,0,0,0,0]
- LimitpeopleZone= [3,3,3,3,3,3,3,3,3,3,3,3]
- Risk = ["NO","NO","NO","NO","NO","NO","NO","NO","NO","NO","NO","NO"]
- # ---------------------
- for r in range(0,12):
- cv2.rectangle(image, (StartXlist[r], StartYlist[r]), (EndXlist[r], EndYlist[r]), (0,255,255), 2) # Black color in BGR
- y = StartYlist[r] - 15 if StartYlist[r] - 15 > 15 else StartYlist[r] + 15
- cv2.putText(image,'Zone'+str(r+1), (StartXlist[r], y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,255), 2)
- for i in np.arange(0, detections.shape[2]):
- confidence = detections[0, 0, i, 2]
- if confidence > args["confidence"]:
- idx = int(detections[0, 0, i, 1])
- box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
- (startX, startY, endX, endY) = box.astype("int")
- # label = '{}"class": {}, "confidence": {:.4f}, "startX": {}, "startY": {}, "EndX": {}, "EndY": {}, "Timestamp": {}{}'.format(chr(123),chr(34)+CLASSES[idx]+chr(34), confidence,startX,startY,endX,endY,chr(34)+str(datetime.now())+chr(34),chr(125))
- # label = json.dumps({'class': CLASSES[idx],"confidence": str(round(confidence * 100, 1)) + "%","startX": str(startX),"startY": str(startY),"EndX": str(endX),"EndY": str(endY),"Timestamp": datetime.now().strftime("%d/%m/%Y, %H:%M")})
- # print("[INFO] {}".format(label))
- # print(label3)
- # var person = { "name": "John", "age": 31, "city": "New York" }; JSON FORMAT FOUND
- ## Create table
- # val1 = json.loads(label3)
- # print(*val1)
- # df = pd.DataFrame(val1, index=list(range(1)))
- # print(df)
- ##
- if CLASSES[idx] == "person":
- for j in range(0,12):
- dx= min(EndXlist[j],endX)-max(StartXlist[j],startX)
- dy= min(EndYlist[j],endY)-max(StartYlist[j],startY)
- if (dx>=0) and (dy>=0):
- PeopleinZone[j]+= 1
- # print("Zone"+str(j+1)+" dx: "+str(dx)+"dy: "+str(dy))
- # print(PeopleinZone)
- print(PeopleinZone)
- # ---------------------
- # MYSQL
- mydb = mysql.connector.connect( host="xxxxx", user="xxxx", password="xxxx")
- # Check if connection was successful
- if (mydb):
- # Carry out normal procedure
- print ("Connection successful")
- else:
- # Terminate
- print ("Connection unsuccessful")
- mycursor = mydb.cursor()
- dbname="TFM40"
- mySql_Create_db = "CREATE DATABASE IF NOT EXISTS "+dbname
- mycursor.execute(mySql_Create_db)
- mysql_use_db = "USE "+dbname
- mycursor.execute(mysql_use_db)
- x = datetime.now()
- tablename="T"+str(x.year)+str(x.month)+str(x.day)
- # mySql_Create_Table = "CREATE TABLE IF NOT EXISTS "+tablename +"(id int AUTO_INCREMENT PRIMARY KEY, Classification varchar(250), Confidence varchar(250), StartX varchar(250), StartY varchar(250), EndX varchar(250), EndY varchar(250), Timestamp varchar(250))"
- mySql_Create_Table2 = "CREATE TABLE IF NOT EXISTS "+tablename +"(id int AUTO_INCREMENT PRIMARY KEY, Camera varchar(250), Zone1 float, Zone2 float, Zone3 float, Zone4 float, Zone5 float, Zone6 float, Zone7 float, Zone8 float, Zone9 float, Zone10 float, Zone11 float, Zone12 float, Timestamp timestamp)"
- print(mySql_Create_Table2)
- mycursor.execute (mySql_Create_Table2)
- # sql_insert = "INSERT INTO "+dbname+"."+tablename+" (Classification,Confidence,startX,startY,EndX,EndY,Timestamp) VALUES (%s,%s,%s,%s,%s,%s,%s)"
- sql_insert2 = "INSERT INTO "+dbname+"."+tablename+" (Camera, Zone1, Zone2, Zone3, Zone4, Zone5, Zone6, Zone7, Zone8, Zone9, Zone10, Zone11, Zone12, Timestamp) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
- # val = (str(CLASSES[idx]),str(round(confidence * 100, 1)),str(startX),str(startY),str(endX),str(endY),str(x))
- val2 = ('hall',PeopleinZone[0],PeopleinZone[1],PeopleinZone[2],PeopleinZone[3],PeopleinZone[4],PeopleinZone[5],PeopleinZone[6],PeopleinZone[7],PeopleinZone[8],PeopleinZone[9],PeopleinZone[10],PeopleinZone[11],str(x))
- # mycursor.execute(sql_insert,(val))
- mycursor.execute(sql_insert2,(val2))
- # mycursor.execute(sql_insert,(val,)) WORKS BUT IT IS FOR TUPLES
- mydb.commit()
- # python main.py --prototxt MobileNetSSD_deploy.prototxt --model MobileNetSSD_deploy.caffemodel --image EXECUTION
- # cursor.close()
- # mydb.close()
- # INFLUXDB
- # client = InfluxDBClient(host, port, user, password, dbname)
- # client = InfluxDBClient('xxx', xxx, 'xxx', 'xxxx', 'TRIALDB')
- # client.create_database('TRIALDB')
- #DRAW SQUARE
- #cv2.rectangle(image, (startX, startY), (endX, endY), COLORS[idx], 2) DEFINE OBJECTS DETECTED SQUARE
- #y = startY - 15 if startY - 15 > 15 else startY + 15 VERTICAL POSITION OF CLASS TITLE
- #cv2.putText(image, label, (startX, y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2) TITLE INSERTION INTO IMAGE
- cv2.imshow("Output", image)
- cv2.imwrite(os.path.join(path, '\hall.jpg'), image)
- print(os.path.join(path, 'hall.jpg'))
- cv2.waitKey(20000) # video (cambiamos un 0 por un 1)
- # --------------------------------------------------------------------------------------------------------------------------
- # TELEGRAM
- # label = '{}"Camera": {}, "Zone1": {}, "Zone2": {}, "Zone3": {}, "Zone4": {}, "Zone5": {}, "Zone6": {}, "Zone7": {}, "Zone8": {}, "Zone9": {}, "Zone10": {},"Zone11": {},"Zone12": {}, "Timestamp": {}{}'.format(chr(123),chr(34)+'hall'+chr(34), PeopleinZone[0],PeopleinZone[1],PeopleinZone[2],PeopleinZone[3],PeopleinZone[4],PeopleinZone[5],PeopleinZone[6],PeopleinZone[7],PeopleinZone[8],PeopleinZone[9],PeopleinZone[10],PeopleinZone[11],chr(34)+str(datetime.now())+chr(34),chr(125))
- # QUESTION & ANSWER 1
- total=0
- maximum=0
- for z in range(0,12):
- total += PeopleinZone[z]
- maximum += LimitpeopleZone[z]
- if PeopleinZone[z]>= LimitpeopleZone[z]:
- Risk[z] ='YES'
- else:
- Risk[z] ='NO'
- label = json.dumps({"Total people" : total, "Remaining people to reach limit" : (maximum - total),"Timestamp": datetime.now().strftime("%d/%m/%Y, %H:%M")})
- print(label)
- # ---------------------
- # QUESTION & ANSWER 2
- # label2 = json.dumps({"Camera": "hall", "Zone1": PeopleinZone[0],"Zone2": PeopleinZone[1],"Zone3": PeopleinZone[2],"Zone4": PeopleinZone[3],"Zone5": PeopleinZone[4],"Zone6": PeopleinZone[5],"Zone7": PeopleinZone[6],"Zone8": PeopleinZone[7],"Zone9": PeopleinZone[8],"Zone10": PeopleinZone[9],"Zone11": PeopleinZone[10],"Zone12": PeopleinZone[11],"Timestamp": datetime.now().strftime("%d/%m/%Y, %H:%M")})
- label2 = json.dumps({"Camera": "hall", "Zone1 Risk": Risk[0],"Zone2 Risk": Risk[1],"Zone3 Risk": Risk[2],"Zone4 Risk": Risk[3],"Zone5 Risk": Risk[4],"Zone6 Risk": Risk[5],"Zone7 Risk": Risk[6],"Zone8 Risk": Risk[7],"Zone9 Risk": Risk[8],"Zone10 Risk": Risk[9],"Zone11 Risk": Risk[10],"Zone12 Risk": Risk[11],"Timestamp": datetime.now().strftime("%d/%m/%Y, %H:%M")})
- print(label2)
- # ---------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement