detectopencvthrjump.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
  2. """
  3. Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
  4. Usage - sources:
  5. $ python detect.py --weights yolov5s.pt --source 0 # webcam
  6. img.jpg # image
  7. vid.mp4 # video
  8. screen # screenshot
  9. path/ # directory
  10. list.txt # list of images
  11. list.streams # list of streams
  12. 'path/*.jpg' # glob
  13. 'https://youtu.be/Zgi9g1ksQHc' # YouTube
  14. 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
  15. Usage - formats:
  16. $ python detect.py --weights yolov5s.pt # PyTorch
  17. yolov5s.torchscript # TorchScript
  18. yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
  19. yolov5s_openvino_model # OpenVINO
  20. yolov5s.engine # TensorRT
  21. yolov5s.mlmodel # CoreML (macOS-only)
  22. yolov5s_saved_model # TensorFlow SavedModel
  23. yolov5s.pb # TensorFlow GraphDef
  24. yolov5s.tflite # TensorFlow Lite
  25. yolov5s_edgetpu.tflite # TensorFlow Edge TPU
  26. yolov5s_paddle_model # PaddlePaddle
  27. """
  28. import matplotlib.path as mat
  29. import requests
  30. import argparse
  31. import os
  32. import platform
  33. import sqlite3
  34. import sys
  35. import threading
  36. import time
  37. from pathlib import Path
  38. import signal
  39. import torch
  40. from concurrent.futures import ThreadPoolExecutor
  41. from concurrent.futures import ProcessPoolExecutor
  42. from multiprocessing import Process,Manager,Value
  43. from multiprocessing import Queue
  44. from multiprocessing import set_start_method
  45. import multiprocessing
  46. import multiprocessing as mp
  47. import numpy as np
  48. import platform
  49. import pathlib
  50. from collections import defaultdict, deque
  51. #import websockets
  52. import asyncio
  53. FILE = Path(__file__).resolve()
  54. ROOT = FILE.parents[0] # YOLOv5 root directory
  55. if str(ROOT) not in sys.path:
  56. sys.path.append(str(ROOT)) # add ROOT to PATH
  57. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  58. import math
  59. from models.common import DetectMultiBackend
  60. from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages,LoadStreams, LoadStreamsSQLNEWN,LoadStreamsSQL,LoadStreamsSQLNRERT,LoadStreamsVEight,LoadStreamsSQLTN
  61. from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
  62. increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh,strtolst,strtolstl,apply_classifier1,task)
  63. from utils.plots import Annotator, colors, save_one_box
  64. from utils.torch_utils import select_device, smart_inference_mode
  65. #from testpool import func1,TestA
  66. from ultralytics import YOLO
  67. from person_jump_check import personJump
  68. # def my_handler(signum, frame):
  69. # exit(0)
  70. #url = "http://36.7.84.146:18802/ai-service/open/api/operate/upload"
  71. plt = platform.system()
  72. if plt != 'Windows':
  73. pathlib.WindowsPath = pathlib.PosixPath
  74. urlhead = "http://172.19.152.231"
  75. url = f"{urlhead}/open/api/operate/upload"
  76. urlele = f"{urlhead}/open/api/operate/fence"
  77. urlperson = f"{urlhead}/open/api/operate/getPersonLimitNum"
  78. urlt = f"{urlhead}/open/api/operate/taskList"
  79. urla = f"{urlhead}/open/api/operate/algorithmList"
  80. weburl = f"ws://36.7.84.146:28801/websocket/device"
  81. personcountdir = {}
  82. algdir = {'0':'helmet','8':'danager','10':'uniform','14':'smoke','16':'fire','21':'cross','25':'fall','29':'occupancy','30':'liquid','31':'pressure','32':'sleep','33':'conveyor','34':'personcount','35':'gloves','36':'sit','37':'other','38':'duty','98':'face','51':'run','64':'jump'}
  83. modellabeldir = {'0':'head','8':'person','10':'other','14':'smoke','16':'fire','21':'cross','25':'fall','29':'car','30':'liquid','31':'pressure','32':'sleep','33':'conveyor','34':'personcount','35':'gloves','36':'sit','37':'other','38':'person','98':'face','51':'person','64':'person'}
  84. modelalgdir = {'helmet': '0','danager': '8','uniform': '10','smoke': '14','fire': '16','cross': '21','fall': '25','occupancy': '29','liquid': '30','pressure': '31','sleep': '32','conveyor': '33','personcount': '34','gloves': '35','sit': '36','other': '37','duty': '38','face': '98','run': '51','jump':'64'}
  85. algmodel = {}
  86. for key,value in algdir.items():
  87. algmodel[value] = key
  88. def map_to_ellipse(position):
  89. x, y = position
  90. center_x = 640
  91. center_y = 360
  92. a = 640
  93. b = 360
  94. x_norm = x / 1280
  95. y_norm = y / 720
  96. d_norm = math.sqrt((x_norm - 0.5) ** 2 + (y_norm - 0.5) ** 2)
  97. theta_norm = math.atan2(y_norm - 0.5, x_norm - 0.5)
  98. f = d_norm
  99. a_new = a * f
  100. b_new = b * f
  101. bias_x = center_x + a_new * math.cos(theta_norm)
  102. bias_y = center_y + b_new * math.sin(theta_norm)
  103. return np.array([bias_x, bias_y])
  104. class YoloOpt:
  105. def __init__(self, weights=ROOT / 'yolov5s.pt',source=ROOT / 'data/images',data=ROOT / 'data/coco128.yaml',
  106. imgsz=(640,640),
  107. conf_thres=0.80,
  108. iou_thres=0.45,
  109. max_det=1000,
  110. device='',
  111. view_img=False,
  112. save_txt=False,
  113. save_conf=False,
  114. save_crop=False,
  115. nosave=True,
  116. classes=None,
  117. agnostic_nms=False,
  118. augment=False,
  119. visualize=False,
  120. update=False,
  121. project=ROOT / 'runs/detect',
  122. name='exp',
  123. exist_ok=False,
  124. line_thickness=1,
  125. hide_labels=False,
  126. hide_conf=False,
  127. half=False,
  128. dnn=False,
  129. vid_stride=10,
  130. classify=False):
  131. self.weights = weights # 权重文件地址
  132. self.source = source # 待识别的图像
  133. self.data = data
  134. if imgsz is None:
  135. self.imgsz = (640, 640)
  136. self.imgsz = imgsz # 输入图片的大小,默认 (640,640)
  137. self.conf_thres = conf_thres # object置信度阈值 默认0.25 用在nms中
  138. self.iou_thres = iou_thres # 做nms的iou阈值 默认0.45 用在nms中
  139. self.device = device # 执行代码的设备,由于项目只能用 CPU,这里只封装了 CPU 的方法
  140. self.view_img = view_img # 是否展示预测之后的图片或视频 默认False
  141. self.classes = classes # 只保留一部分的类别,默认是全部保留
  142. self.agnostic_nms = agnostic_nms # 进行NMS去除不同类别之间的框, 默认False
  143. self.augment = augment # augmented inference TTA测试时增强/多尺度预测,可以提分
  144. self.update = update # 如果为True,则对所有模型进行strip_optimizer操作,去除pt文件中的优化器等信息,默认为False
  145. self.exist_ok = exist_ok # 如果为True,则对所有模型进行strip_optimizer操作,去除pt文件中的优化器等信息,默认为False
  146. self.project = project # 保存测试日志的参数,本程序没有用到
  147. self.name = name # 每次实验的名称,本程序也没有用到
  148. self.max_det = max_det
  149. self.save_txt = save_txt
  150. self.save_conf= save_conf
  151. self.save_crop= save_crop
  152. self.nosave = nosave
  153. self.visualize = visualize
  154. self.line_thickness = line_thickness
  155. self.hide_labels = hide_labels
  156. self.hide_conf = hide_conf
  157. self.half = half
  158. self.dnn = dnn
  159. self.vid_stride = vid_stride
  160. self.classify = classify
  161. class Detect:
  162. def __init__(self, weights = ROOT / 'yolov5s.pt' , imgsz=(640,640),source="changshusql1103.db",classify=False,conf_thres=0.80,device='',channelsl=''):
  163. print(f'detectweights = {weights}')
  164. self.opt = YoloOpt(weights=weights, imgsz=imgsz,source=source,classify=classify,conf_thres=conf_thres,device=device)
  165. self.source = str(self.opt.source)
  166. self.save_img = not self.opt.nosave and not source.endswith('.txt') # save inference images
  167. is_file = Path(self.source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
  168. is_url = self.source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
  169. self.webcam = True
  170. screenshot = self.source.lower().startswith('screen')
  171. if is_url and is_file:
  172. self.source = check_file(self.source) # download
  173. self.save_dir = increment_path(Path(self.opt.project) / self.opt.name, exist_ok=self.opt.exist_ok) # increment run
  174. #self.save_dir = self.save_dir / Path(self.opt.weights).stem
  175. #self.save_dir.mkdir(parents=True, exist_ok=True)
  176. (self.save_dir / 'labels' if self.opt.save_txt else self.save_dir).mkdir(parents=True, exist_ok=True) # make dir
  177. #self.imgsz = check_img_size(self.opt.imgsz, s=self.stride)
  178. # self.readchannel = self.readpoint()
  179. #print(self.imgsz)
  180. self.updatetime = time.time()
  181. #self.filetime = os.path.getmtime(self.opt.weights)
  182. bs = 1 # batch_size
  183. if self.webcam:
  184. #self.view_img = check_imshow(warn=True)
  185. self.view_img = False
  186. # dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
  187. tt= 0
  188. numworks = 1
  189. self.dataset = LoadStreamsSQLTN(channelsl, source, img_size=640,
  190. auto=True, vid_stride=1, tt=tt, numworks=numworks)
  191. # bs = len(dataset)
  192. elif screenshot:
  193. dataset = LoadScreenshots(self.source, img_size=self.imgsz, stride=self.stride, auto=self.pt)
  194. else:
  195. self.dataset = LoadImages(self.source, img_size=self.imgsz, stride=self.stride, auto=self.pt, vid_stride=self.opt.vid_stride)
  196. self.speed_threshold = 40
  197. self.high_velocity_count_threshold = 6
  198. # t1 = threading.Thread(target=self.load,daemon=True)
  199. # t1.start()
  200. @smart_inference_mode()
  201. def infer(self,weights,classify,conf_thres,device,runmodel):
  202. device = select_device(device)
  203. print("loadmodel device{device}")
  204. #region_points = [(820, 200), (1600, 200), (1600, 530), (820, 530)]
  205. #region_points = [[259, 200], [2258, 200], [2258, 943], [259, 943]]
  206. #region_points = [[374,1224],[380,1237],[426,1237],[435,1237],[479,1230],[527,1201],[552,1187],[575,1166],[583,1155],[585,1136],[583,1126],[558,1124],[485,1178],[374,1210]]
  207. region_points = [(214, 519),(235, 512),(251, 503),(269, 496),(283, 486),(296, 482),(302, 493),(296, 507),(283, 517),(275, 526),(247, 533),(227, 538),(209, 538),(207, 529),(203, 521)]
  208. counter = personJump(
  209. # show_in = False,
  210. # show_out = False,
  211. show=False,
  212. region=region_points,
  213. model=weights,
  214. classes=[0],
  215. conf=0.4,
  216. )
  217. # stride, names, pt = model.stride, model.names, model.pt
  218. if classify:
  219. classifier_model = torch.load(f"{Path(weights).stem}cls.pt")
  220. classifier_model = classifier_model.to(device)
  221. classifier_model.eval()
  222. print('classify--------------------------------------------------------------------')
  223. #imgsz = check_img_size(self.opt.imgsz, s=stride)
  224. #model.warmup(imgsz=(1, 3, *imgsz))
  225. readchannel,dirmodel = self.readpoint(weights)
  226. #print(imgsz)
  227. updatetime = time.time()
  228. filetime = os.path.getmtime(weights)
  229. #selfreadpoint();
  230. pretime = time.time()
  231. seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
  232. #
  233. # print ("数据库打开成功")
  234. #async with websockets.connect(uri) as websocket:
  235. # for key in dirmodel.keys():
  236. # dirmodel[key]['websoc'] = await websockets.connect(dirmodel[key]['web'])
  237. for path, im, im0s, vid_cap, s, videotime,channels in self.dataset:
  238. hour = time.localtime(time.time()).tm_hour
  239. if hour not in range(7,18):
  240. time.sleep(30)
  241. continue
  242. i = 0
  243. ima = im0s[i].copy()
  244. imc = ima.copy()
  245. flag = False
  246. #print('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
  247. #if len(queue) == 0:
  248. # print('queuezero')
  249. # time.sleep(0.01)
  250. #print(123)
  251. im0 = counter.count(ima)
  252. #print(456)
  253. if counter.in_count > 0:
  254. flag = True
  255. counter.in_count = 0
  256. #print(f'timee = {time.time()-timee}')
  257. #flag = True
  258. if flag:
  259. #if self.dirmodel[path[i]]['imgtime'] != videotime[i]:
  260. dirmodel[channels[i]]['detframe'].pop(0)
  261. dirmodel[channels[i]]['detframe'].append(1)
  262. dirmodel[channels[i]]['preim'] = im0
  263. dirmodel[channels[i]]['oripreim'] = imc
  264. dirmodel[channels[i]]['posttime'] = videotime[i]
  265. print(dirmodel[channels[i]]['detframe'])
  266. #self.dirmodel[channels[i]]['imgtime'] = videotime[i]
  267. else:
  268. #print(f'deti= {i}')
  269. #print(detframe[i])
  270. #if self.dirmodel[channels[i]]['imgtime'] != videotime[i]:
  271. dirmodel[channels[i]]['detframe'].pop(0)
  272. dirmodel[channels[i]]['detframe'].append(0)
  273. print(dirmodel[channels[i]]['detframe'])
  274. #self.dirmodel[channels[i]]['imgtime'] = videotime[i]
  275. #print(detframe[i])
  276. # Stream results
  277. #im0 = annotator.result()
  278. #print(f'i = {i}')
  279. #print(channels[i])
  280. #print(postpretime[i])
  281. #print(detframe[i])
  282. if not dirmodel[channels[i]]['detflag'] and dirmodel[channels[i]]['detframe'].count(1)>=1:
  283. dirmodel[channels[i]]['detflag'] = True
  284. dirmodel[channels[i]]['detpretime'] = time.time()
  285. elif dirmodel[channels[i]]['detframe'].count(1)==0 :
  286. dirmodel[channels[i]]['detflag'] = False
  287. dirmodel[channels[i]]['detpretime'] = float('inf')
  288. # Stream results
  289. #im0 = annotator.result()
  290. if time.time() - dirmodel[channels[i]]['postpretime'] >30 and time.time() - dirmodel[channels[i]]['detpretime'] > dirmodel[channels[i]]['durtime'] and dirmodel[channels[i]]['detflag']:
  291. #print()
  292. #if time.time() - self.dirmodel[channels[i]]['postpretime'] >30 and self.dirmodel[channels[i]]['detflag']:
  293. #print(time.time() - self.dirmodel[channels[i]]['detpretime'])
  294. #print(self.dirmodel[channels[i]]['detflag'])
  295. #print(f'{Path(self.opt.weights).stem}post----{time.strftime("%Y-%m-%d %H:%M:%S", time.time()}')
  296. #time.sleep(30)
  297. #print(time.time() - postpretime[i])
  298. #print('111111111111111111111111111111111111111111111111')
  299. #print(dirmodel[channels[i]]['preim'].shape)
  300. success, encoded_image = cv2.imencode('.jpg', dirmodel[channels[i]]['preim'])
  301. content = encoded_image.tobytes()
  302. successori, encoded_imageori = cv2.imencode('.jpg', dirmodel[channels[i]]['oripreim'])
  303. contentori = encoded_imageori.tobytes()
  304. filename = f'0_{int(time.time())}.jpg'
  305. filenameori = f'0_{int(time.time())}.jpg'
  306. #print(f'str(p) {p.name}')
  307. print(channels[i])
  308. payload = {'channel': dirmodel[channels[i]]['channel'],
  309. 'classIndex': dirmodel[channels[i]]['classindex'],
  310. 'ip': dirmodel[channels[i]]['algip'],
  311. 'videoTime': time.strftime('%Y-%m-%d %H:%M:%S', dirmodel[channels[i]]['posttime']),
  312. 'videoUrl': channels[i]}
  313. fourcc = cv2.VideoWriter_fourcc(*'MP4V')
  314. fps = 6
  315. height,width,_ = dirmodel[channels[i]]['preim'].shape
  316. year=time.strftime('%Y',time.localtime(time.time()))
  317. month=time.strftime('%m',time.localtime(time.time()))
  318. day=time.strftime('%d',time.localtime(time.time()))
  319. vidsavefold = f'/mnt/yolo/videos/{Path(weights).stem}/{year}/{month}/{day}'
  320. vidsaveflod = Path(vidsavefold)
  321. vidsaveflod.mkdir(parents=True, exist_ok=True)
  322. timesave = time.strftime('%Y-%m-%d-%H:%M:%S', dirmodel[channels[i]]['posttime'])
  323. #out = cv2.VideoWriter(f'{vidsaveflod}/{timesave}.mp4', fourcc, fps, (width, height))
  324. #for imgframe in self.dirmodel[channels[i]]['framelist']:
  325. #success, encoded_image = cv2.imencode('.jpg', self.dirmodel[channels[i]]['preim'])
  326. #content = encoded_image.tobytes()
  327. # out.write(imgframe)
  328. #out.release()
  329. files = [
  330. ('file', (filename, content, 'image/jpeg')),
  331. ('oldFile',(filenameori, contentori, 'image/jpeg')),
  332. #('videoFile',open(f'{vidsaveflod}/{timesave}.mp4','rb'))
  333. ]
  334. print(f'{Path(weights).stem}post----{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))}')
  335. try:
  336. # if self.dirmodel[channels[i]]['postvidpretime'] != self.dirmodel[channels[i]]['posttime'] and not self.dirmodel[channels[i]]['postvideo']:
  337. resulttext = requests.post(url, data=payload, files=files)
  338. # self.dirmodel[channels[i]]['postvidpretime'] = self.dirmodel[channels[i]]['posttime']
  339. # self.dirmodel[channels[i]]['postid'] = resulttext.json()['data']
  340. # self.dirmodel[channels[i]]['postframe'] = 0
  341. # self.dirmodel[channels[i]]['postvideo'] = True
  342. # self.dirmodel[channels[i]]['videoname'] = f'{vidsaveflod}/{timesave}.mp4'
  343. #videoqueuea.append(resulttext,f'{vidsaveflod}/{timesave}.mp4',)
  344. print(f'resulttext = {resulttext.json()["data"]}')
  345. except Exception:
  346. print("posterror")
  347. #if self.dirmodel[channels[i]]['postvideo']:
  348. #print(f'resulttext = {resulttext}')
  349. #time.sleep(3000)
  350. dirmodel[channels[i]]['postpretime'] = time.time()
  351. dirmodel[channels[i]]['detflag'] = False
  352. #timesave = time.strftime('%Y-%m-%d-%H:%M:%S', self.dirmodel[channels[i]]['posttime'])
  353. #year=time.strftime('%Y',time.localtime(time.time()))
  354. #month=time.strftime('%m',time.localtime(time.time()))
  355. #day=time.strftime('%d',time.localtime(time.time()))
  356. savefold = f'/mnt/yolo/images/{Path(weights).stem}/{year}/{month}/{day}'
  357. saveflod = Path(savefold)
  358. detsavefold = f'/mnt/yolo/detimages/{Path(weights).stem}/{year}/{month}/{day}'
  359. detsavefold = Path(detsavefold)
  360. saveflod.mkdir(parents=True, exist_ok=True)
  361. detsavefold.mkdir(parents=True, exist_ok=True)
  362. cv2.imwrite(f'{savefold}/{timesave}.jpg',dirmodel[channels[i]]['oripreim'])
  363. cv2.imwrite(f'{detsavefold}/{timesave}det.jpg',dirmodel[channels[i]]['preim'])
  364. self.view_img = False
  365. if self.view_img:
  366. if platform.system() == 'Linux' and p not in windows:
  367. windows.append(p)
  368. cv2.namedWindow(f'{str(p)}-{Path(weights).stem}',
  369. cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
  370. cv2.resizeWindow(f'{str(p)}-{Path(weights).stem}', im0.shape[1], im0.shape[0])
  371. im1 = cv2.resize(im0, (1280, 720))
  372. cv2.imshow(f'{str(p)}-{Path(weights).stem}', im1)
  373. cv2.waitKey(1) # 1 millisecond
  374. # Save results (image with detections)
  375. # Print time (inference-only)
  376. print(f'channels[i]={channels[i]}')
  377. #LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms {time.strftime('%Y-%m-%d-%H:%M:%S',time.localtime(time.time()))} {Path(weights).stem}")
  378. # def load(self):
  379. # conn = sqlite3.connect(self.source)
  380. # c = conn.cursor()
  381. # while True:
  382. # #
  383. # # print ("数据库打开成功")
  384. #
  385. # cursor = c.execute(
  386. # "SELECT modelname, addstream,delstream,streaming from CHANGESTREAM WHERE modelname= (?)",(Path(self.opt.weights).stem,))
  387. # # content = cursor.fetchall()
  388. # # if content[0][1] ==1 or content[0][2] ==1:
  389. # # c.execute("UPDATE CHANGESTREAM set streamimg = 1 where modelname='yolov5s'")
  390. # # print("updata changestream")
  391. # # conn.commit()
  392. # # cursor = c.execute(
  393. # # "SELECT modelname, addstream,delstream,streamimg from CHANGESTREAM WHERE modelname='yolov5s'")
  394. # self.contentid = cursor.fetchall()
  395. # #global tag
  396. # #tag = Value('i', self.contentid[0][3])
  397. # #print(tag.value==1)
  398. # print(f'loadcontent={self.contentid[0][3]}')
  399. # time.sleep(3)
  400. # c.close()
  401. # conn.close()
  402. def readpoint(self,weights):
  403. #conn = sqlite3.connect(self.source)
  404. #c = conn.cursor()
  405. #cursor = c.execute(
  406. # "SELECT address,fence,point,channel,classindex,ip ,algip,label, durtime from STREAM WHERE modelname= (?)",
  407. # (Path(self.opt.weights).stem,))
  408. data = {
  409. "algorithmCode": algmodel[Path(weights).stem],
  410. "deviceIp":None
  411. }
  412. dirmodel = {}
  413. result = requests.post(url=urlt,data=data).json()['data']
  414. channell=[]
  415. for info in result:
  416. #content = cursor.fetchall()
  417. #self.dirmodel = {}
  418. #for address,fence,point,channel,classindex,ip ,algip,label,durtime in content:
  419. #address = f'{address[:-1]}0'
  420. channel = info["deviceChannel"]
  421. channell.append(channel)
  422. dirmodel[channel] = {}
  423. dirmodel[channel]['fence'] = 1 if len(info["electricFence"])>0 else 0
  424. #self.dirmodel[channel]['point'] = point
  425. dirmodel[channel]['channel'] = info['deviceChannel']
  426. dirmodel[channel]['classindex'] = info['algorithmCode']
  427. dirmodel[channel]['ip'] = info['deviceIp']
  428. dirmodel[channel]['algip'] = info['deviceAlgorithmIp']
  429. dataele = {
  430. "algorithmCode": dirmodel[channel]['classindex'],
  431. "algorithmIp":dirmodel[channel]['algip'],
  432. "channel":dirmodel[channel]['channel']
  433. }
  434. resultele = requests.post(url=urlele,data=dataele).json()['data']['pointCollections']
  435. resultele = resultele.split(',||')
  436. resultele = tuple(resultele)
  437. point = '%s:'*len(resultele) %resultele
  438. if Path(weights).stem == 'personcount':
  439. resultper = requests.post(url=urlperson,data=dataele).json()['data']
  440. personcountdir[channel] = resultper
  441. dirmodel[channel]['point'] = point[:-2]
  442. dirmodel[channel]['preim'] = None
  443. dirmodel[channel]['oripreim'] = None
  444. dirmodel[channel]['detframe'] = [0 for _ in range(2)]
  445. dirmodel[channel]['postpretime'] = 0
  446. dirmodel[channel]['detflag'] = False
  447. dirmodel[channel]['detpretime'] = float('inf')
  448. dirmodel[channel]['label'] = modellabeldir[data['algorithmCode']]
  449. dirmodel[channel]['durtime'] = 0
  450. dirmodel[channel]['posttime'] = 0
  451. dirmodel[channel]['track_history'] = defaultdict(lambda: [])
  452. dirmodel[channel]['time_stamps'] = defaultdict(lambda: deque(maxlen=50))
  453. dirmodel[channel]['instantaneous_velocities'] = defaultdict(lambda: deque(maxlen=10))
  454. #tmp = f'{weburl}/{channel}/{info["deviceAlgorithmIp"]}'
  455. #dirmodel[channel]['web'] = f'{weburl}/{info["deviceId"]}/{info["algorithmCode"]}'
  456. print(dirmodel)
  457. return sorted(channell),dirmodel
  458. #def strtolst(self,str):
  459. # str = str.split(":")
  460. # lista = []
  461. # for liststr in str:
  462. # if len(liststr) > 0:
  463. # li = liststr.split(',')
  464. # listpoint = []
  465. # for i, j in zip(li[::2], li[1::2]):
  466. # listpoint.append((i, j))
  467. # lista.append(listpoint)
  468. # return listpoint
  469. #def preprocess():
  470. # print('preprocess-----------------------------------------------')
  471. # def getframe(queue,channelsl,source,tt,numworks,lock,numworkv):
  472. # while True:
  473. # print("dataloader")
  474. # imgsz = [640, 640]
  475. # print(f'source = {source}')
  476. # print(f'inchannel ={channelsl}')
  477. #
  478. # bs = len(dataset)
  479. # vid_path, vid_writer = [None] * bs, [None] * bs
  480. # # self.detframe = [[0 for _ in range(8)] for i in range(bs)]
  481. # # self.postpretime = [0]*bs
  482. # # Run inference
  483. #
  484. # #imgsz = (1 , 3, *self.imgsz)
  485. # print(imgsz)
  486. # #self.model.warmup(imgsz=(1 , 3, *imgsz)) # warmup
  487. # seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
  488. # sourcebase = 'project.db'
  489. # #
  490. # # print ("数据库打开成功")
  491. # pretime = time.time()
  492. # tag = 0
  493. # for path, im, im0s, vid_cap, s, videotime,channels in dataset:
  494. # # print('*'*21)
  495. # # global tag
  496. # if time.time()-pretime > 30:
  497. # channellist = []
  498. # pretime = time.time()
  499. # data = {
  500. # "algorithmCode": None,
  501. # "deviceIp":None
  502. # }
  503. # result = requests.post(url=urlt,data=data).json()['data']
  504. # for info in result:
  505. # channellist.append((info['deviceChannel'],info['playbackAddress']))
  506. # channelsa = []
  507. # sourcea = []
  508. # channellist = set(channellist)
  509. # channellist = sorted(channellist,key=lambda x:x[0])
  510. # #channellist = set(channellist)
  511. # for cha,add in channellist:
  512. # channelsa.append(cha)
  513. # sourcea.append(add)
  514. # channelsl = sorted(channelsl)
  515. # #channelsa = sorted(channelsa)
  516. # if channelsa!=channelsl:
  517. # print(f'channelsa = {channelsa}')
  518. # print(f'channelsl = {channelsl}')
  519. # dataset.close()
  520. # channelsl = channelsa
  521. # source = sourcea
  522. # break;
  523. #
  524. # #conn = sqlite3.connect(sourcebase)
  525. # #c = conn.cursor()
  526. # #cursor = c.execute("SELECT modelname, addstream,delstream,streaming from CHANGESTREAM WHERE modelname = 'stream'")
  527. # #contentid = cursor.fetchall()
  528. # #tag = contentid[0][3]
  529. # #if tag == 1:
  530. # # lock.acquire()
  531. # # numworkv.value += 1
  532. # # dataset.close()
  533. # # if numworkv.value==3:
  534. # # print('newstreaming=', tag)
  535. # # conn = sqlite3.connect(source)
  536. # # c = conn.cursor()
  537. # # c.execute("UPDATE CHANGESTREAM set streaming = 0 , addstream=0,delstream=0 where modelname= 'helmet'")
  538. # # print(123)
  539. # # conn.commit()
  540. # # c.close()
  541. # # conn.close()
  542. # # lock.release()
  543. # # print('opencv1')
  544. # # cv2.destroyAllWindows()
  545. # # print('opencv')
  546. # # break
  547. # #else:
  548. # # print('nonewstreaming=', tag)
  549. # queue.put((path, im, im0s, vid_cap, s, videotime,channels))
  550. # queue.get() if queue.qsize() > 3 else time.sleep(0.001)
  551. #
  552. # def getmutpro(channels,source,streamlist,numworkv,lock,numworks=1):
  553. # processlist = []
  554. # queuelist = []
  555. # for i in range(numworks):
  556. # queue = Queue(maxsize=4)
  557. # process = Process(target=getframe,
  558. # args=(queue, channels,source, i,numworks,lock,numworkv))
  559. # processlist.append(process)
  560. # process.start()
  561. # queuelist.append(queue)
  562. # return queuelist
  563. # #path = []
  564. # #im0s = []
  565. # #vid_cap = None
  566. # #s = ''
  567. # #videotime = []
  568. # #while True:
  569. # # imlist = []
  570. # # pathlist = []
  571. # # im0slist = []
  572. # # channelslist = []
  573. # # vid_cap = None
  574. # # s = ''
  575. # # videotimelist = []
  576. # # for q in queuelist:
  577. # # if q.qsize()>0:
  578. # # setframe = q.get()
  579. # # path, im, im0s, vid_cap, s, videotime,channels = setframe
  580. # # channelslist += channels
  581. # # pathlist += path
  582. # # im0slist += im0s
  583. # # videotimelist += videotime
  584. # # imlist.append(im)
  585. # # if len(imlist)>0:
  586. # # im = np.concatenate(imlist)
  587. # # if len(pathlist)>0:
  588. # # print(len(path),im.shape,len(im0s))
  589. # # streamlist.append((pathlist, im, im0slist, vid_cap, s, videotimelist,channelslist))
  590. # #print(f'streamlist = {len(streamlist)}')
  591. # # streamlist.pop(0) if len(streamlist) > 3 else time.sleep(0.001)
  592. def modelfun(detectdemo,weights,classify=False,conf_thres=0.80,device='',runmodel=None):
  593. print(weights)
  594. #detectdemo=Detect(weights=weights,source=sourcedb,classify=classify,conf_thres=conf_thres,device=device)
  595. detectdemo.infer(weights,classify,conf_thres,device,runmodel)
  596. #detectdemo.infer(weights, classify, conf_thres, device, runmodel)
  597. def detectmut(channellist,source,modellist,contentlist,modeladir,runmodel={},deviceid=''):
  598. detectdemo = Detect(channelsl=channellist,source=source)
  599. # while True:
  600. for modelname in modellist:
  601. if modelname in contentlist:
  602. #if modelname not in runmodel:
  603. #print(i)
  604. #detectdemo=Detect(weights=f'/mnt/project/yolodemo/yolov5-master/{i[0]}.pt')
  605. #if modelname in ['fall','helmet','bag','arm']:
  606. print(f'weights ={modelname}.pt deviceid {deviceid}')
  607. #c.execute('select conf,cla from changestream where modelname = (?)',(modelname,))
  608. #rea = c.fetchall()
  609. process = threading.Thread(target=modelfun,args=(detectdemo,f'{modelname}.pt',modeladir[modelname]['cla'],modeladir[modelname]['conf'],deviceid,runmodel))
  610. #elif modelname in ['personcount','persontre']:
  611. # process = Process(target=modelfun,args=(streamlist,videoqueue,f'{modelname}.pt',dbpath,False,0.50,'',runmodel))
  612. #elif modelname in ['uniform']:
  613. # process = Process(target=modelfun,args=(streamlist,videoqueue,f'{modelname}.pt',dbpath,True,0.50,'',runmodel))
  614. #else:
  615. # process = Process(target=modelfun,args=(streamlist,f'{modelname}.pt',dbpath))
  616. #runmodel[modelname] = 1
  617. #processes.append(process)
  618. #process.start()
  619. #detectobj = Process(target=detectdemo.infer,args=(queue,))
  620. # Detect(weights=f'{i[0]}.pt')
  621. time.sleep(3)
  622. process.start()
  623. def parse_opt():
  624. parser = argparse.ArgumentParser()
  625. parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path or triton URL')
  626. opt = parser.parse_args()
  627. return opt
  628. def main(opt):
  629. check_requirements(ROOT / 'requirements.txt', exclude=('tensorboard', 'thop'))
  630. run(**vars(opt))
  631. if __name__ == '__main__':
  632. torch.multiprocessing.set_start_method('spawn')
  633. #set_start_method('spawn')
  634. #multiprocessing.set_start_method('spawn')
  635. torch.cuda.set_per_process_memory_fraction(0.6)
  636. opt = parse_opt()
  637. dbpath = 'projectnew.db'
  638. conn = sqlite3.connect(dbpath)
  639. #
  640. # print ("数据库打开成功")
  641. c = conn.cursor()
  642. task(c,conn,urlt,urla)
  643. cursor = c.execute("SELECT modelname from CHANGESTREAM where modelname = 'jump'")
  644. #cursor = c.execute("SELECT modelname from CHANGESTREAM where modelname = 'helmet'")
  645. content = cursor.fetchall()
  646. contentlist = []
  647. for con in content:
  648. contentlist.append(con[0])
  649. #cursor = c.execute("SELECT address,modelname,channel from STREAM where modelname='helmet' or modelname = 'sleep' or modelname = 'smoke' or modelname = 'danager'or modelname = 'gloves' or modelname = 'other'")
  650. cursor = c.execute("SELECT address,modelname,channel from STREAM where modelname = 'jump'")
  651. contenta = cursor.fetchall()
  652. source = []
  653. modellist = []
  654. addcha = []
  655. channellist = []
  656. for i in contenta:
  657. addcha.append((i[0],i[2]))
  658. modellist.append(i[1])
  659. addcha = set(addcha)
  660. addcha = sorted(addcha,key=lambda x:x[1])
  661. for a,cha in addcha:
  662. source.append(a)
  663. channellist.append(cha)
  664. print(addcha)
  665. #source = set(source)
  666. source = list(source)
  667. #source.sort()
  668. modellist = set(modellist)
  669. n = len(content)
  670. print(f'modelname={n}')
  671. print(content)
  672. #content.reverse()
  673. print(content)
  674. # main(opt)
  675. #processes = []
  676. streamqueue = Queue(maxsize=4)
  677. numworkv = Value('i', 0)
  678. manager = Manager()
  679. lock = multiprocessing.Lock()
  680. streamlist = manager.list()
  681. numworks = 1
  682. #queuelist = getmutpro(channellist,source, streamlist, numworkv, lock, numworks)
  683. #thread.start()
  684. #videoqueue = Queue(maxsize=20)
  685. #thread1 = threading.Thread(target=postvideo, args=(videoqueue,))
  686. #thread1.start()
  687. #pool = ThreadPoolExecutor(max_workers=n)
  688. #runmodel = manager.dict()
  689. modeladir = {}
  690. for modelname in modellist:
  691. if modelname in contentlist:
  692. #if modelname not in runmodel:
  693. #print(i)
  694. #detectdemo=Detect(weights=f'/mnt/project/yolodemo/yolov5-master/{i[0]}.pt')
  695. #if modelname in ['fall','helmet','bag','arm']:
  696. print(f'weights ={modelname}.pt')
  697. c.execute('select conf,cla from changestream where modelname = (?)',(modelname,))
  698. rea = c.fetchall()
  699. #print(f'rea')
  700. modeladir.setdefault(modelname,{})
  701. modeladir[modelname]['conf'] = rea[0][0]
  702. modeladir[modelname]['cla'] = rea[0][1]
  703. runmodel = {}
  704. for deviceid,num in enumerate(range(0,len(channellist),13)):
  705. process = Process(target=detectmut,args=(channellist[num:num+13],source[num:num+13],modellist,contentlist,modeladir,{},deviceid%2))
  706. time.sleep(3)
  707. process.start()
  708. #deviceid = deviceid+1
  709. # detectdemo = Detect(channelsl=channellist[0:num],source=source[0:num])
  710. # # while True:
  711. # for modelname in modellist:
  712. # if modelname in contentlist:
  713. # if modelname not in runmodel:
  714. # #print(i)
  715. # #detectdemo=Detect(weights=f'/mnt/project/yolodemo/yolov5-master/{i[0]}.pt')
  716. # #if modelname in ['fall','helmet','bag','arm']:
  717. # print(f'weights ={modelname}.pt')
  718. # c.execute('select conf,cla from changestream where modelname = (?)',(modelname,))
  719. # rea = c.fetchall()
  720. # process = threading.Thread(target=modelfun,args=(detectdemo,f'{modelname}.pt',rea[0][1],rea[0][0],'',runmodel))
  721. # #elif modelname in ['personcount','persontre']:
  722. # # process = Process(target=modelfun,args=(streamlist,videoqueue,f'{modelname}.pt',dbpath,False,0.50,'',runmodel))
  723. # #elif modelname in ['uniform']:
  724. # # process = Process(target=modelfun,args=(streamlist,videoqueue,f'{modelname}.pt',dbpath,True,0.50,'',runmodel))
  725. # #else:
  726. # # process = Process(target=modelfun,args=(streamlist,f'{modelname}.pt',dbpath))
  727. # runmodel[modelname] = 1
  728. # #processes.append(process)
  729. # #process.start()
  730. # #detectobj = Process(target=detectdemo.infer,args=(queue,))
  731. # # Detect(weights=f'{i[0]}.pt')
  732. # time.sleep(3)
  733. # process.start()
  734. # time.sleep(900)
  735. # task(c,conn,urlt,urla)
  736. # cursor = c.execute("SELECT modelname from CHANGESTREAM where modelname = 'helmet' or modelname = 'fall' or modelname = 'uniform' or modelname = 'personcount' or modelname = 'arm' or modelname = 'bag'")
  737. # #cursor = c.execute("SELECT modelname from CHANGESTREAM where modelname = 'helmet'")
  738. # content = cursor.fetchall()
  739. # contentlist = []
  740. # for con in content:
  741. # contentlist.append(con[0])
  742. # #cursor = c.execute("SELECT address,modelname,channel from STREAM where modelname='helmet' or modelname = 'sleep' or modelname = 'smoke' or modelname = 'danager'or modelname = 'gloves' or modelname = 'other'")
  743. # cursor = c.execute("SELECT address,modelname,channel from STREAM ")
  744. # contenta = cursor.fetchall()
  745. # source = []
  746. # modellist = []
  747. # addcha = []
  748. # channellist = []
  749. # for i in contenta:
  750. # addcha.append((i[0],i[2]))
  751. # modellist.append(i[1])
  752. # addcha = set(addcha)
  753. # addcha = sorted(addcha)
  754. # for a,cha in addcha:
  755. # source.append(a)
  756. # channellist.append(cha)
  757. # print(addcha)
  758. # #source = set(source)
  759. # source = list(source)
  760. # #source.sort()
  761. # modellist = set(modellist)
  762. # n = len(content)
  763. # print(f'modelname={n}')
  764. # print(content)
  765. # #content.reverse()
  766. # print(content)
  767. #pool.submit(detectobj.infer)
  768. #cursor = c.execute("SELECT modelname from CHANGESTREAM where modelname = 'fall'")
  769. #content = cursor.fetchall()
  770. #n = len(content)
  771. #print(f'modelname={n}')
  772. #print(content)
  773. #content.reverse()
  774. #print(content)
  775. # main(opt)
  776. #processes = []
  777. #pool = ProcessPoolExecutor(max_workers=n)
  778. #for i in content:
  779. #print(i)
  780. #detectdemo=Detect(weights=f'{i[0]}.pt')
  781. #process = Process(target=detectdemo.infer)
  782. #processes.append(process)
  783. #process.start()
  784. #detectobj = Detect(weights=f'{i[0]}.pt')
  785. # time.sleep(3)
  786. #pool.submit(detectobj.infer)
  787. # print('111111111111111111111111111111111111111111111111111111111')
  788. #pool.submit(TestA().func1, '张三', i)
  789. #print('----------------------------------------------------------------')
  790. #time.sleep(3000)
  791. # 等待所有进程执行完毕
  792. #for process in processes:
  793. # process.join()
  794. #pool.submit(Detect(weights=f'{i[0]}.pt').infer)
  795. # if isinstance(opt.weights,list):
  796. # opt.weights = opt.weights[0]
  797. #signal.signal(signal.SIGINT, my_handler)
  798. #detectdemo1 = Detect(weights=f'{content[0][0]}.pt')
  799. #detectdemo1.infer()
  800. #a = Test
  801. #with ProcessPoolExecutor(3) as ppool:
  802. #for i in range(3):
  803. # print('hello')
  804. #ppool.submit(self.postprocess,pred[i::3],path[i::3],im0s[i::3],dataset,im[i::3],s)
  805. #ppool.submit(TestA().func1, '张三', i)
  806. #ta = TestA()
  807. #with ProcessPoolExecutor(5) as ppool: # 创建一个5个进程的进程池
  808. # for i in range(1, 4):
  809. # ppool.submit(func1, '张三', i)
  810. #f1= pool.submit(detectdemo1.infer)
  811. # print("线程1-----------------------------------------------------------------------------------")
  812. #detectdemo2 = Detect(weights=r"helmet.pt")
  813. #f2=pool.submit(detectdemo2.infer)
  814. # print("线程2-------------------------------------------------------------------------------------")
  815. #detectdemo3 = threading.Thread(target=detectdemo3.infer)
  816. #detectdemo3 = Detect(weights=r"fall.pt")
  817. #f3=pool.submit(detectdemo3.infer)