使用Telegrambot的Python多线程OpenCV

问题描述

我试图在代码的opencv部分启动之前使用多线程启动电报机器人。以前的问题是,当程序完成opencv部分时,它就完成了,我们希望让它等待与Telegram的交互。我们收到的错误消息就像其他机器人实例正在运行一样。

您能帮我实现多线程吗?

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')

def zone_risk(update,context):
    update.message.reply_text('Risky zones due to people presence')

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'))

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("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",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()
# ---------------------
# THREADING
# threading.Thread(target=main_telegram).start()
x = threading.Thread(target=main_telegram,args=())
x.start()
# ---------------------
# import pandas as pd

# INFLUXDB
# client = InfluxDBClient('vps656540.ovh.net',3306,'master26','master26_','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) 
os.makedirs(path,exist_ok = True) 
# ---------------------
# 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",help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m","--model",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),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,120,68,40,40]
EndXlist = [90,430,640,210,380,620,240,355,510,465]
EndYlist = [420,420,220,110,65,65]
PeopleinZone=[0,0]
LimitpeopleZone= [3,3,3]
Risk = ["NO","NO","NO"]
# ---------------------
for r in range(0,12):
      cv2.rectangle(image,(StartXlist[r],StartYlist[r]),(EndXlist[r],EndYlist[r]),(0,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),y),cv2.FONT_HERShey_SIMPLEX,0.5,2)

for i in np.arange(0,detections.shape[2]):
     confidence = detections[0,i,2]
         
     if confidence > args["confidence"]:
            idx = int(detections[0,1])
            Box = detections[0,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,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="localhost",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,EndX,EndY,Timestamp) VALUES (%s,%s,%s)"
sql_insert2 = "INSERT INTO "+dbname+"."+tablename+" (Camera,Zone1,Zone2,Zone3,Zone4,Zone5,Zone6,Zone7,Zone8,Zone9,Zone10,Zone11,Zone12,%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('vps656540.ovh.net',xxxx,'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,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(5000) # video (cambiamos un 0 por un 1)
# --------------------------------------------------------------------------------------------------------------------------
# TELEGRAM
# label = '{}"Camera": {},"Zone1": {},"Zone2": {},"Zone3": {},"Zone4": {},"Zone5": {},"Zone6": {},"Zone7": {},"Zone8": {},"Zone9": {},"Zone10": {},"Zone11": {},"Zone12": {},chr(34)+'hall'+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),%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],%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],%H:%M")})
print(label2)
# ---------------------
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)

logger = logging.getLogger(__name__)
# ---------------------
if __name__ == '__main__':
    main_telegram()
# --------------------------------------------------------------------------------------------------------------------------

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)