runthr.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. from datetime import datetime
  29. import matplotlib.path as mat
  30. import requests
  31. import argparse
  32. import os
  33. import platform
  34. import sqlite3
  35. import sys
  36. import threading
  37. import time
  38. from pathlib import Path
  39. import signal
  40. import torch
  41. from concurrent.futures import ThreadPoolExecutor
  42. from concurrent.futures import ProcessPoolExecutor
  43. from multiprocessing import Process,Manager,Value
  44. from multiprocessing import Queue
  45. from multiprocessing import set_start_method
  46. import multiprocessing
  47. import multiprocessing as mp
  48. import numpy as np
  49. import platform
  50. import pathlib
  51. from collections import defaultdict, deque
  52. #import websockets
  53. import asyncio
  54. FILE = Path(__file__).resolve()
  55. ROOT = FILE.parents[0] # YOLOv5 root directory
  56. if str(ROOT) not in sys.path:
  57. sys.path.append(str(ROOT)) # add ROOT to PATH
  58. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  59. import math
  60. from models.common import DetectMultiBackend
  61. from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages,LoadStreams, LoadStreamsSQLNEWN,LoadStreamsSQL,LoadStreamsSQLNRERT,LoadStreamsVEight,LoadStreamsSQLTN
  62. from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
  63. increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh,strtolst,strtolstl,apply_classifier1,task)
  64. from utils.plots import Annotator, colors, save_one_box
  65. from utils.torch_utils import select_device, smart_inference_mode
  66. #from testpool import func1,TestA
  67. from ultralytics import YOLO
  68. from ultralytics.trackers.bot_sort import BOTSORT
  69. from ultralytics.utils.checks import check_yaml
  70. from ultralytics.utils import IterableSimpleNamespace, yaml_load, ops
  71. from ultralytics.nn.autobackend import AutoBackend
  72. from ultralytics.utils.ops import non_max_suppression
  73. from ultralytics.engine.results import Results
  74. # def my_handler(signum, frame):
  75. # exit(0)
  76. #url = "http://36.7.84.146:18802/ai-service/open/api/operate/upload"
  77. plt = platform.system()
  78. if plt != 'Windows':
  79. pathlib.WindowsPath = pathlib.PosixPath
  80. urlhead = "http://172.19.152.231"
  81. url = f"{urlhead}/open/api/operate/upload"
  82. urlele = f"{urlhead}/open/api/operate/fence"
  83. urlperson = f"{urlhead}/open/api/operate/getPersonLimitNum"
  84. urlt = f"{urlhead}/open/api/operate/taskList"
  85. urla = f"{urlhead}/open/api/operate/algorithmList"
  86. weburl = f"ws://36.7.84.146:28801/websocket/device"
  87. urlrtsp = f"{urlhead}/open/api/operate/previewURLs"
  88. personcountdir = {}
  89. 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'}
  90. 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'}
  91. 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'}
  92. algmodel = {}
  93. for key,value in algdir.items():
  94. algmodel[value] = key
  95. def map_to_ellipse(position):
  96. x, y = position
  97. center_x = 640
  98. center_y = 360
  99. a = 580
  100. b = 280
  101. x_norm = x / 1280
  102. y_norm = y / 720
  103. d_norm = math.sqrt((x_norm - 0.5) ** 2 + (y_norm - 0.5) ** 2)
  104. theta_norm = math.atan2(y_norm - 0.5, x_norm - 0.5)
  105. f = d_norm
  106. a_new = a * f
  107. b_new = b * f
  108. bias_x = center_x + a_new * math.cos(theta_norm)
  109. bias_y = center_y + b_new * math.sin(theta_norm)
  110. return np.array([bias_x, bias_y])
  111. def parse_opt():
  112. parser = argparse.ArgumentParser()
  113. parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path or triton URL')
  114. opt = parser.parse_args()
  115. return opt
  116. def runtracker(modelname,source,channel):
  117. track_history = defaultdict(lambda: [])
  118. # 用于存储每个 track_id 最近的时间戳
  119. time_stamps = defaultdict(lambda: deque(maxlen=50)) # 固定长度为 50
  120. # 用于存储瞬时速度
  121. instantaneous_velocities = defaultdict(lambda: deque(maxlen=10))
  122. speed_threshold = 40 # 速度阈值
  123. high_velocity_count_threshold = 6 # 高速度计数阈值
  124. dirmodel = {"channel":channel,"postpretime":0,"classIndex":'',"VideoUrl":source}
  125. cap = cv2.VideoCapture(source)
  126. model = YOLO(modelname)
  127. while cap.isOpened():
  128. # 记录当前时间
  129. flag = False
  130. current_time = time.time()
  131. # Read a frame from the video
  132. success, frame = cap.read()
  133. oriimg = frame.copy()
  134. if success:
  135. # Run YOLO11 tracking on the frame, persisting tracks between frames
  136. results = model.track(frame, persist=True, classes=0, conf=0.6)
  137. if results[0].boxes and results[0].boxes.id is not None:
  138. # Get the boxes and track IDs
  139. boxes = results[0].boxes.xywh.cpu()
  140. track_ids = results[0].boxes.id.int().cpu().tolist()
  141. for box, track_id in zip(boxes, track_ids):
  142. x, y, w, h = box
  143. # 绘制边界框
  144. cv2.rectangle(frame, (int(x - w / 2), int(y - h / 2)), (int(x + w / 2), int(y + h / 2)),
  145. (0, 255, 0), 2)
  146. # 计算左下角坐标
  147. bottom_left_x = int(x - w / 2)
  148. bottom_left_y = int(y + h / 2)
  149. # 计算中心点
  150. center_x = int(x)
  151. center_y = int(y)
  152. # 绘制中心点
  153. cv2.circle(frame, (center_x, center_y), 5, (255, 0, 0), -1) # 红色中心点,半径为 5
  154. # 记录位置
  155. track_history[track_id].append((bottom_left_x, bottom_left_y))
  156. if len(track_history[track_id]) > 100:
  157. del track_history[track_id][:-50] # 维持历史长度
  158. # 记录每一帧的时间
  159. time_stamps[track_id].append(current_time)
  160. # 计算时间间隔
  161. if len(time_stamps[track_id]) > 1:
  162. delta_time = time_stamps[track_id][-1] - time_stamps[track_id][-2] # 最近两帧的时间差
  163. else:
  164. delta_time = 0
  165. instantaneous_velocity = 0
  166. # 计算二维瞬时速度
  167. if len(track_history[track_id]) >= 2:
  168. pos1 = np.array(track_history[track_id][-1]) # 最新位置
  169. pos2 = np.array(track_history[track_id][-2]) # 前一个位置
  170. pos1 = map_to_ellipse(pos1)
  171. pos2 = map_to_ellipse(pos2)
  172. distance = np.linalg.norm(pos1 - pos2)
  173. # 使用时间间隔进行速度计算
  174. instantaneous_velocity = distance / delta_time if delta_time > 0 else np.zeros(2)
  175. instantaneous_velocity_magnitude = round(np.linalg.norm(instantaneous_velocity), 1)
  176. instantaneous_velocities[track_id].append(instantaneous_velocity_magnitude)
  177. else:
  178. instantaneous_velocity_magnitude = 0
  179. # 判断是否有足够数量的高速度
  180. high_velocity_count = sum(
  181. 1 for velocity in instantaneous_velocities[track_id] if velocity > speed_threshold)
  182. if high_velocity_count >= high_velocity_count_threshold:
  183. cv2.putText(frame, str(instantaneous_velocity_magnitude), (int(x), int(y)),
  184. cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
  185. flag = True
  186. if flag and time.time()-dirmodel["postpretime"]>30:
  187. timesave = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
  188. year = time.strftime('%Y', time.localtime(time.time()))
  189. month = time.strftime('%m', time.localtime(time.time()))
  190. day = time.strftime('%d', time.localtime(time.time()))
  191. savefold = f'/mnt/project/images/run/{year}/{month}/{day}'
  192. savefold = Path(savefold)
  193. savefold.mkdir(parents=True, exist_ok=True)
  194. detsavefold = f'/mnt/project/detimages/run/{year}/{month}/{day}'
  195. detsavefold = Path(detsavefold)
  196. detsavefold.mkdir(parents=True, exist_ok=True)
  197. cv2.imwrite(f'{savefold}/{timesave}.jpg', oriimg)
  198. cv2.imwrite(f'{detsavefold}/{timesave}det.jpg', frame)
  199. success, encoded_image = cv2.imencode('.jpg', frame)
  200. content = encoded_image.tobytes()
  201. successori, encoded_imageori = cv2.imencode('.jpg', oriimg)
  202. contentori = encoded_imageori.tobytes()
  203. filename = f'{channel}_{int(time.time())}.jpg'
  204. filenameori = f'ori{channel}_{int(time.time())}.jpg'
  205. payload = {'channel': dirmodel['channel'],
  206. 'classIndex': dirmodel['classindex'],
  207. 'ip': dirmodel['algip'],
  208. 'videoTime': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),
  209. 'videoUrl': dirmodel["VideoUrl"]}
  210. files = [
  211. ('file', (filename, content, 'image/jpeg')),
  212. ('oldFile', (filenameori, contentori, 'image/jpeg')),
  213. ]
  214. try:
  215. result = requests.post(url, data=payload, files=files)
  216. print(result)
  217. except Exception:
  218. print('posterror')
  219. if __name__ == '__main__':
  220. torch.multiprocessing.set_start_method('spawn')
  221. #set_start_method('spawn')
  222. #multiprocessing.set_start_method('spawn')
  223. torch.cuda.set_per_process_memory_fraction(0.6)
  224. opt = parse_opt()
  225. dbpath = 'project.db'
  226. conn = sqlite3.connect(dbpath)
  227. #
  228. # print ("数据库打开成功")
  229. c = conn.cursor()
  230. task(c,conn,urlt,urla)
  231. cursor = c.execute('select channel,algip from stream where modelname = "run"')
  232. result = cursor.fetchall()
  233. for channel ,algip in result:
  234. data = {
  235. "channel": channel,
  236. "ip":algip
  237. }
  238. #personcountdir[channel] = num
  239. address = requests.post(url=urlrtsp,data=data).json()['msg']
  240. c.execute('UPDATE STREAM set address= (?) where channel =(?)',(address,channel))
  241. conn.commit()
  242. cursor = c.execute("SELECT modelname from CHANGESTREAM where modelname = 'run'")
  243. #cursor = c.execute("SELECT modelname from CHANGESTREAM where modelname = 'helmet'")
  244. content = cursor.fetchall()
  245. contentlist = []
  246. for con in content:
  247. contentlist.append(con[0])
  248. #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'")
  249. cursor = c.execute("SELECT address,modelname,channel from STREAM where modelname = 'run'")
  250. contenta = cursor.fetchall()
  251. source = []
  252. modellist = []
  253. addcha = []
  254. channellist = []
  255. for i in contenta:
  256. addcha.append((i[0],i[2]))
  257. modellist.append(i[1])
  258. addcha = set(addcha)
  259. addcha = sorted(addcha,key=lambda x:x[1])
  260. for a,cha in addcha:
  261. source.append(a)
  262. channellist.append(cha)
  263. print(addcha)
  264. #source = set(source)
  265. source = list(source)
  266. #source.sort()
  267. modellist = set(modellist)
  268. n = len(content)
  269. print(f'modelname={n}')
  270. print(content)
  271. #content.reverse()
  272. print(content)
  273. # main(opt)
  274. #processes = []
  275. streamqueue = Queue(maxsize=4)
  276. numworkv = Value('i', 0)
  277. manager = Manager()
  278. lock = multiprocessing.Lock()
  279. streamlist = manager.list()
  280. numworks = 2
  281. #queuelist = getmutpro(channellist,source, streamlist, numworkv, lock, numworks)
  282. #thread.start()
  283. #videoqueue = Queue(maxsize=20)
  284. #thread1 = threading.Thread(target=postvideo, args=(videoqueue,))
  285. #thread1.start()
  286. #pool = ThreadPoolExecutor(max_workers=n)
  287. #runmodel = manager.dict()
  288. modeladir = {}
  289. for modelname in modellist:
  290. if modelname in contentlist:
  291. #if modelname not in runmodel:
  292. #print(i)
  293. #detectdemo=Detect(weights=f'/mnt/project/yolodemo/yolov5-master/{i[0]}.pt')
  294. #if modelname in ['fall','helmet','bag','arm']:
  295. print(f'weights ={modelname}.pt')
  296. c.execute('select conf,cla from changestream where modelname = (?)',(modelname,))
  297. rea = c.fetchall()
  298. #print(f'rea')
  299. modeladir.setdefault(modelname,{})
  300. modeladir[modelname]['conf'] = rea[0][0]
  301. modeladir[modelname]['cla'] = rea[0][1]
  302. tracker_threads = []
  303. for channel,address in zip(channellist,source):
  304. thread = threading.Thread(target=runtracker,args=("run.pt",channel,address))
  305. tracker_threads.append(thread)
  306. thread.start()
  307. for thread in tracker_threads:
  308. thread.join()