Advertisement
Cesar_Leiton

Untitled

Sep 23rd, 2020 (edited)
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.39 KB | None | 0 0
  1. import numpy as np
  2. import argparse
  3. import cv2
  4. import time
  5. import mysql.connector
  6. import json
  7. from datetime import datetime
  8. from influxdb import InfluxDBClient
  9. import ast
  10. import os
  11. import logging
  12. from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
  13. import threading
  14.  
  15. # ---------------------
  16. # TELEGRAM Handlers
  17. def people_total(update, context):
  18.     update.message.reply_text('Total number of people present in store:' + str(total))
  19.  
  20. def zone_risk(update, context):
  21.     update.message.reply_text('Risky zones due to people presence'+ label2)
  22.  
  23. def echo(update, context):
  24.     """Echo the user message."""
  25.     update.message.reply_text('Total number of people is:'+ label)
  26.     # update.message.reply_text(update.message.text)
  27.  
  28. def pic(update, context):
  29.     chat_id = update.message.chat_id        # get the recipient´s ID
  30.     #context.bot.sendPhoto(chat_id=chat_id, photo=open(path, 'rb'))
  31.     context.bot.sendPhoto(chat_id=chat_id, photo=open('./hall.jpg', 'rb'))
  32.  
  33. def main_telegram():
  34.     """Start the bot."""
  35.     # Create the Updater and pass it your bot's token.
  36.     # Make sure to set use_context=True to use the new context based callbacks
  37.     # Post version 12 this will no longer be necessary
  38.     updater = Updater("xxxxxx", use_context=True)
  39.  
  40.     # Get the dispatcher to register handlers
  41.     dp = updater.dispatcher
  42.  
  43.     # on different commands - answer in Telegram
  44.     dp.add_handler(CommandHandler("people", people_total))
  45.     dp.add_handler(CommandHandler("risk", zone_risk))
  46.     dp.add_handler(CommandHandler("picture", pic))
  47.  
  48.     # on noncommand i.e message - echo the message on Telegram
  49.     dp.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
  50.  
  51.    
  52.     # Start the Bot
  53.     updater.start_polling()
  54.  
  55.     # Run the bot until you press Ctrl-C or the process receives SIGINT,
  56.     # SIGTERM or SIGABRT. This should be used most of the time, since
  57.     # start_polling() is non-blocking and will stop the bot gracefully.
  58.     updater.idle()
  59. # ---------------------
  60. # TELEGRAM Enable logging
  61. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  62.                     level=logging.INFO)
  63.  
  64. logger = logging.getLogger(__name__)
  65. # ---------------------
  66. # THREADING
  67. # threading.Thread(target=main_telegram).start()
  68. x = threading.Thread(target=main_telegram, args=())
  69. x.start()
  70. # ---------------------
  71.  
  72. # import pandas as pd
  73.  
  74. # INFLUXDB
  75. # client = InfluxDBClient('xxxxx', 3306, 'xxxx', 'xxxx', 'TRIALDB')
  76. # client.create_database('TRIALDB') # Problems with DB creation
  77. # ---------------------
  78. # SUB-DIRECTORY CREATION
  79. working_path = os.getcwd()
  80. # sub_directory = "Image"
  81. # path = os.path.join(working_path, sub_directory)
  82. path = working_path
  83. os.makedirs(path, exist_ok = True)
  84. print(path)
  85. # ---------------------
  86. # CAFFE construct the argument parse and parse the arguments
  87. ap = argparse.ArgumentParser()
  88. ap.add_argument("-i", "--image", required=True,
  89.      help="path to input image")
  90. ap.add_argument("-p", "--prototxt", required=True,
  91.      help="path to Caffe 'deploy' prototxt file")
  92. ap.add_argument("-m", "--model", required=True,
  93.      help="path to Caffe pre-trained model")
  94. ap.add_argument("-c", "--confidence", type=float, default=0.2,
  95.      help="minimum probability to filter weak detections")
  96. args = vars(ap.parse_args())
  97. CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
  98.      "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
  99.      "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
  100.      "sofa", "train", "tvmonitor"]
  101. COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
  102. print("[INFO] loading model…")
  103. image = cv2.imread(args["image"])
  104. net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
  105. (h, w) = image.shape[:2]
  106. blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5)
  107. print("[INFO] computing object detections…")
  108. print(blob.shape)
  109. net.setInput(blob)
  110. detections = net.forward()
  111. # ---------------------
  112. # RECTANGLE LISTS DEFINITION BASED ON APPLE.JPG + ZONE COUNTER CREATION
  113. StartXlist = [1,230,580,30,275,460,155,295,415,200,300,390]
  114. StartYlist = [265,265,265,120,120,120,68,68,68,40,40,40]
  115. EndXlist = [90,430,640,210,380,620,240,355,510,255,355,465]
  116. EndYlist = [420,420,420,220,220,220,110,110,110,65,65,65]
  117. PeopleinZone=[0,0,0,0,0,0,0,0,0,0,0,0]
  118. LimitpeopleZone= [3,3,3,3,3,3,3,3,3,3,3,3]
  119. Risk = ["NO","NO","NO","NO","NO","NO","NO","NO","NO","NO","NO","NO"]
  120. # ---------------------
  121. for r in range(0,12):
  122.       cv2.rectangle(image, (StartXlist[r], StartYlist[r]), (EndXlist[r], EndYlist[r]),         (0,255,255), 2) # Black color in BGR
  123.       y = StartYlist[r] - 15 if StartYlist[r] - 15 > 15 else StartYlist[r] + 15    
  124.       cv2.putText(image,'Zone'+str(r+1), (StartXlist[r], y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,255), 2)
  125.  
  126. for i in np.arange(0, detections.shape[2]):
  127.      confidence = detections[0, 0, i, 2]
  128.          
  129.      if confidence > args["confidence"]:
  130.             idx = int(detections[0, 0, i, 1])
  131.             box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
  132.             (startX, startY, endX, endY) = box.astype("int")      
  133.             # 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))
  134.             # 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")})
  135.             # print("[INFO] {}".format(label))
  136.             # print(label3)
  137.             # var person = { "name": "John", "age": 31, "city": "New York" }; JSON FORMAT FOUND
  138.            
  139.             ## Create table
  140.             # val1 = json.loads(label3)
  141.             # print(*val1)
  142.          
  143.             # df = pd.DataFrame(val1, index=list(range(1)))
  144.             # print(df)
  145.             ##
  146.             if CLASSES[idx] == "person":
  147.                for j in range(0,12):
  148.                      dx= min(EndXlist[j],endX)-max(StartXlist[j],startX)
  149.                      dy= min(EndYlist[j],endY)-max(StartYlist[j],startY)
  150.                      if (dx>=0) and (dy>=0):
  151.                           PeopleinZone[j]+= 1
  152.                      # print("Zone"+str(j+1)+" dx: "+str(dx)+"dy: "+str(dy))
  153.                      # print(PeopleinZone)
  154.                      
  155. print(PeopleinZone)            
  156. # ---------------------
  157. # MYSQL
  158. mydb = mysql.connector.connect( host="xxxxx", user="xxxx", password="xxxx")
  159. # Check if connection was successful
  160. if (mydb):
  161.      # Carry out normal procedure
  162.      print ("Connection successful")
  163. else:
  164.      # Terminate
  165.      print ("Connection unsuccessful")
  166. mycursor = mydb.cursor()
  167. dbname="TFM40"
  168. mySql_Create_db = "CREATE DATABASE IF NOT EXISTS "+dbname
  169. mycursor.execute(mySql_Create_db)
  170. mysql_use_db = "USE "+dbname
  171. mycursor.execute(mysql_use_db)
  172. x = datetime.now()
  173. tablename="T"+str(x.year)+str(x.month)+str(x.day)
  174. # 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))"
  175. 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)"
  176. print(mySql_Create_Table2)
  177. mycursor.execute (mySql_Create_Table2)
  178. # sql_insert = "INSERT INTO "+dbname+"."+tablename+" (Classification,Confidence,startX,startY,EndX,EndY,Timestamp) VALUES (%s,%s,%s,%s,%s,%s,%s)"
  179. 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)"
  180. # val = (str(CLASSES[idx]),str(round(confidence * 100, 1)),str(startX),str(startY),str(endX),str(endY),str(x))
  181. 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))
  182. # mycursor.execute(sql_insert,(val))
  183. mycursor.execute(sql_insert2,(val2))
  184. # mycursor.execute(sql_insert,(val,)) WORKS BUT IT IS FOR TUPLES
  185. mydb.commit()
  186.            
  187.            
  188.            
  189.            # python main.py --prototxt MobileNetSSD_deploy.prototxt --model MobileNetSSD_deploy.caffemodel --image EXECUTION
  190.            
  191.            # cursor.close()
  192.  
  193.  
  194.  
  195.             # mydb.close()
  196.            
  197.             # INFLUXDB
  198.  
  199.             # client = InfluxDBClient(host, port, user, password, dbname)
  200.             # client = InfluxDBClient('xxx', xxx, 'xxx', 'xxxx', 'TRIALDB')
  201.             # client.create_database('TRIALDB')
  202.             #DRAW SQUARE
  203.             #cv2.rectangle(image, (startX, startY), (endX, endY),         COLORS[idx], 2)  DEFINE OBJECTS DETECTED SQUARE  
  204.            
  205.             #y = startY - 15 if startY - 15 > 15 else startY + 15  VERTICAL POSITION OF CLASS TITLE    
  206.             #cv2.putText(image, label, (startX, y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2) TITLE INSERTION INTO IMAGE
  207. cv2.imshow("Output", image)
  208. cv2.imwrite(os.path.join(path, '\hall.jpg'), image)
  209. print(os.path.join(path, 'hall.jpg'))
  210. cv2.waitKey(20000) # video (cambiamos un 0 por un 1)
  211. # --------------------------------------------------------------------------------------------------------------------------
  212. # TELEGRAM
  213. # 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))
  214. # QUESTION & ANSWER 1
  215. total=0
  216. maximum=0
  217. for z in range(0,12):
  218.      total += PeopleinZone[z]
  219.      maximum += LimitpeopleZone[z]
  220.      if PeopleinZone[z]>= LimitpeopleZone[z]:
  221.           Risk[z] ='YES'
  222.      else:
  223.           Risk[z] ='NO'
  224. label = json.dumps({"Total people" : total, "Remaining people to reach limit" : (maximum - total),"Timestamp": datetime.now().strftime("%d/%m/%Y, %H:%M")})
  225. print(label)
  226. # ---------------------
  227. # QUESTION & ANSWER 2
  228. # 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")})
  229. 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")})
  230. print(label2)
  231. # ---------------------
  232.  
  233.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement