platform_setup_detect.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import cv2
  2. import torch
  3. from shapely.geometry import box, Polygon
  4. import threading
  5. import numpy as np
  6. import math
  7. from datetime import datetime
  8. from ultralytics import YOLO
  9. from utils.tool import IoU
  10. from globals import stop_event,redis_client
  11. from config import SAVE_IMG_PATH,POST_IMG_PATH4,PLATFORM_SETUP_MODEL,PLATFORM_SETUP_VIDEO_SOURCES
  12. from globals import platform_setup_steps_detect_num,platform_setup_final_result,platform_setup_steps_img
  13. def init_platform_setup_detection():
  14. global platform_setup_steps_detect_num,platform_setup_final_result,platform_setup_steps_img
  15. platform_setup_final_result=[0]*14
  16. platform_setup_steps_detect_num=[0]*14
  17. platform_setup_steps_img=[False]*14
  18. redis_client.delete("platform_setup_order")
  19. for i in range(1, 14):
  20. redis_client.delete(f"platform_setup_{i}")
  21. redis_client.delete(f"platform_setup_{i}_img")
  22. def start_platform_setup_detection(start_events):
  23. threads = []
  24. for video_source in PLATFORM_SETUP_VIDEO_SOURCES:
  25. event = threading.Event()
  26. start_events.append(event)
  27. thread = threading.Thread(target=process_video, args=(PLATFORM_SETUP_MODEL,video_source,event))
  28. threads.append(thread)
  29. thread.daemon=True
  30. thread.start()
  31. # Wait for all threads to complete
  32. for thread in threads:
  33. thread.join()
  34. print("平台搭设子线程启动")
  35. # Function to process video with YOLO model
  36. def process_video(model_path, video_source,start_event):
  37. # Load YOLO model
  38. model = YOLO(model_path)
  39. cap = cv2.VideoCapture(video_source)
  40. while cap.isOpened():
  41. if stop_event.is_set():#控制停止推理
  42. #del model
  43. break
  44. # Read a frame from the video
  45. success, frame = cap.read()
  46. if success:
  47. # Run YOLOv8 inference on the frame
  48. if cap.get(cv2.CAP_PROP_POS_FRAMES) % 25 != 0:
  49. continue
  50. results = model.predict(frame,conf=0.6,verbose=False,task='obb')
  51. LEVLEL0_REGION = np.array([[1167, 908], [931, 1153], [1962, 1187], [2034, 936]], np.int32)
  52. LEVLEL1_REGION = np.array([[1163, 574], [859, 818], [1969, 828], [2060, 588]], np.int32)
  53. LEVLEL2_REGION = np.array([[1147, 263], [778, 438], [1953, 442], [2044, 248]], np.int32)
  54. LEVLEL3_REGION = np.array([[1142, 34], [793, 163], [1945, 112], [2050, 17]], np.int32)
  55. DIAGONAL_REGION = np.array([[838, 147], [845, 1145], [1935, 1147], [1943, 147]], np.int32)
  56. global platform_setup_steps_detect_num,platform_setup_final_result
  57. # 每十秒归零 platform_setup_steps_detect_num
  58. # current_time = time.time()
  59. # if not hasattr(process_video, 'last_reset_time'):
  60. # process_video.last_reset_time = current_time
  61. # if current_time - process_video.last_reset_time >= 10:
  62. # platform_setup_steps_detect_num = [0] * 14
  63. # process_video.last_reset_time = current_time
  64. for r in results:
  65. boxes=r.obb.xyxyxyxy
  66. boxes1=r.obb.xywhr
  67. confidences=r.obb.conf
  68. classes=r.obb.cls
  69. # 0: montant
  70. # 1: diagonal
  71. # 2: wheel
  72. # 3: vertical_bar
  73. # 4: horizontal_bar
  74. # 5: ladder
  75. # 6: toe_board
  76. # 7: scaffold
  77. # 1=轮子
  78. # 2=立杆
  79. # 3=纵向扫地杆
  80. # 4=横向扫地杆
  81. # 5=纵向水平杆1
  82. # 6=横向水平杆1
  83. # 7=纵向水平杆2
  84. # 8=横向水平杆2
  85. # 9=斜撑
  86. # 10=爬梯
  87. # 11=脚手板
  88. # 12=挡脚板
  89. # 13=纵向水平杆3
  90. # 14=横向水平杆3
  91. platform_setup_steps = [0] * 14
  92. hengxianggan=0
  93. zongxinaggan=0
  94. for i in range(len(boxes)):
  95. confidence = confidences[i].item()
  96. cls = int(classes[i].item())
  97. label = model.names[cls]
  98. #print(boxes[i].tolist())
  99. box_coords = boxes[i].tolist()
  100. x_center = (box_coords[0][0] + box_coords[1][0]+box_coords[2][0]+box_coords[3][0]) / 4
  101. y_center=(box_coords[0][1] + box_coords[1][1]+box_coords[2][1]+box_coords[3][1]) / 4
  102. center_point = (int(x_center), int(y_center))
  103. rotation= math.degrees(boxes1[i][4])
  104. if label=="wheel":#轮子
  105. # platform_setup_steps_detect_num[0]+=1
  106. # if platform_setup_steps_detect_num[0]>3:
  107. # platform_setup_steps[0]+=1
  108. platform_setup_steps[0]+=1
  109. #print(f"轮子{rotation}")
  110. elif label=="bar":#立杆
  111. # platform_setup_steps_detect_num[1]+=1
  112. # if platform_setup_steps_detect_num[1]>3:
  113. # platform_setup_steps[1]+=1
  114. if video_source == PLATFORM_SETUP_VIDEO_SOURCES[0]:
  115. if 70 < rotation < 110:
  116. platform_setup_steps[1] += 1 # 立杆
  117. elif rotation < 10 or rotation > 170:
  118. hengxianggan += 1 # 横向杆
  119. elif 135 < rotation < 150:
  120. platform_setup_steps[8] += 1 # 斜杆
  121. else:
  122. zongxinaggan += 1 # 纵向杆
  123. elif video_source == PLATFORM_SETUP_VIDEO_SOURCES[1]:
  124. if 70 < rotation < 110:
  125. platform_setup_steps[1] += 1 # 立杆
  126. elif 5 < rotation < 25:
  127. hengxianggan += 1 # 横向杆
  128. elif 40 < rotation < 60:
  129. platform_setup_steps[8] += 1 # 斜杆
  130. else:
  131. zongxinaggan += 1 # 纵向杆
  132. # elif label=="vertical_bar":#水平横杆,纵杆
  133. # is_inside0 = cv2.pointPolygonTest(LEVLEL0_REGION.reshape((-1, 1, 2)), center_point, False)
  134. # is_inside1 = cv2.pointPolygonTest(LEVLEL1_REGION.reshape((-1, 1, 2)), center_point, False)
  135. # is_inside2 = cv2.pointPolygonTest(LEVLEL2_REGION.reshape((-1, 1, 2)), center_point, False)
  136. # is_inside3 = cv2.pointPolygonTest(LEVLEL3_REGION.reshape((-1, 1, 2)), center_point, False)
  137. # #print(is_inside)
  138. # if is_inside0>=0 :
  139. # platform_setup_steps_detect_num[2]+=1
  140. # if platform_setup_steps_detect_num[2]>3:
  141. # platform_setup_steps[2]+=1 #表示纵向扫地杆
  142. # elif is_inside1>=0:
  143. # platform_setup_steps_detect_num[4]+=1
  144. # if platform_setup_steps_detect_num[4]>3:
  145. # platform_setup_steps[4]+=1#5=纵向水平杆1
  146. # elif is_inside2>=0:
  147. # platform_setup_steps_detect_num[6]+=1
  148. # if platform_setup_steps_detect_num[6]>3:
  149. # platform_setup_steps[6]+=1#7=纵向水平杆2
  150. # elif is_inside3>=0:
  151. # platform_setup_steps_detect_num[12]+=1
  152. # if platform_setup_steps_detect_num[12]>3:
  153. # platform_setup_steps[12]+=1#13=纵向水平杆3
  154. # elif label=="horizontal_bar":#水平纵杆
  155. # is_inside0 = cv2.pointPolygonTest(LEVLEL0_REGION.reshape((-1, 1, 2)), center_point, False)
  156. # is_inside1 = cv2.pointPolygonTest(LEVLEL1_REGION.reshape((-1, 1, 2)), center_point, False)
  157. # is_inside2 = cv2.pointPolygonTest(LEVLEL2_REGION.reshape((-1, 1, 2)), center_point, False)
  158. # is_inside3 = cv2.pointPolygonTest(LEVLEL3_REGION.reshape((-1, 1, 2)), center_point, False)
  159. # #print(is_inside)
  160. # if is_inside0>=0 :
  161. # platform_setup_steps_detect_num[3]+=1
  162. # if platform_setup_steps_detect_num[3]>3:
  163. # platform_setup_steps[3]+=1#4=横向扫地杆
  164. # elif is_inside1>=0:
  165. # platform_setup_steps_detect_num[5]+=1
  166. # if platform_setup_steps_detect_num[5]>3:
  167. # platform_setup_steps[5]+=1#6=横向水平杆1
  168. # elif is_inside2>=0:
  169. # platform_setup_steps_detect_num[7]+=1
  170. # if platform_setup_steps_detect_num[7]>3:
  171. # platform_setup_steps[7]+=1# 8=横向水平杆2
  172. # elif is_inside3>=0:
  173. # platform_setup_steps_detect_num[13]+=1
  174. # if platform_setup_steps_detect_num[13]>3:
  175. # platform_setup_steps[13]+=1#14=横向水平杆3
  176. # elif label=="diagonal":#斜撑
  177. # is_inside = cv2.pointPolygonTest(DIAGONAL_REGION.reshape((-1, 1, 2)), center_point, False)
  178. # if is_inside>=0:
  179. # platform_setup_steps_detect_num[8]+=1
  180. # if platform_setup_steps_detect_num[8]>3:
  181. # platform_setup_steps[8]+=1# 9=斜撑
  182. elif label=="ladder":#梯子
  183. #10=爬梯
  184. # platform_setup_steps_detect_num[9]+=1
  185. # if platform_setup_steps_detect_num[9]>3:
  186. platform_setup_steps[9]+=1
  187. elif label=="scaffold":#脚手板
  188. #11=脚手板
  189. # platform_setup_steps_detect_num[10]+=1
  190. # if platform_setup_steps_detect_num[10]>3:
  191. platform_setup_steps[10]+=1
  192. elif label=="toe_board":#档脚板
  193. #12=挡脚板
  194. # platform_setup_steps_detect_num[11]+=1
  195. # if platform_setup_steps_detect_num[11]>3:
  196. platform_setup_steps[11]+=1
  197. if hengxianggan >= 2:
  198. platform_setup_steps[3] = 2
  199. if hengxianggan >= 4:
  200. platform_setup_steps[5] = 2
  201. if hengxianggan >= 6:
  202. platform_setup_steps[7] = 2
  203. if hengxianggan >= 8:
  204. platform_setup_steps[13] = 2
  205. if zongxinaggan>=2:
  206. platform_setup_steps[2]=2
  207. if zongxinaggan>=4:
  208. platform_setup_steps[4]=2
  209. if zongxinaggan>=6:
  210. platform_setup_steps[6]=2
  211. if zongxinaggan>=8:
  212. platform_setup_steps[12]=2
  213. # print(hengxianggan)
  214. # print(zongxinaggan)
  215. #print(platform_setup_steps)
  216. #print('----------------------')
  217. # Print the platform setup steps
  218. for i, nums in enumerate(platform_setup_steps):
  219. label = ""
  220. if nums>0:
  221. if all(not redis_client.exists(f"platform_setup_{j}") for j in range(i+2, len(platform_setup_steps))):
  222. if redis_client.exists(f"platform_setup_{i+1}"):
  223. redis_client.set(f"platform_setup_{i+1}", str(nums))
  224. platform_setup_final_result[i] = nums
  225. else:
  226. redis_client.set(f"platform_setup_{i+1}", str(nums))
  227. platform_setup_final_result[i] = nums
  228. redis_client.rpush("platform_setup_order", f"platform_setup_{i+1}")
  229. if i==13:
  230. save_time=datetime.now().strftime('%Y%m%d_%H%M')
  231. imgpath = f"{SAVE_IMG_PATH}/platform_setup{i+1}_{save_time}.jpg"
  232. post_path= f"{POST_IMG_PATH4}/platform_setup{i+1}_{save_time}.jpg"
  233. annotated_frame = results[0].plot()
  234. cv2.imwrite(imgpath, annotated_frame)
  235. redis_client.set(f"platform_setup_{i+1}_img",post_path)
  236. elif not platform_setup_steps_img[i]:
  237. save_time=datetime.now().strftime('%Y%m%d_%H%M')
  238. imgpath = f"{SAVE_IMG_PATH}/platform_setup{i+1}_{save_time}.jpg"
  239. post_path= f"{POST_IMG_PATH4}/platform_setup{i+1}_{save_time}.jpg"
  240. annotated_frame = results[0].plot()
  241. cv2.imwrite(imgpath, annotated_frame)
  242. redis_client.set(f"platform_setup_{i+1}_img",post_path)
  243. platform_setup_steps_img[i]=True
  244. # if nums > 0 and not redis_client.exists(f"platform_setup_{i+2}"):
  245. # if redis_client.exists(f"platform_setup_{i+1}"):
  246. # if all(platform_setup_final_result[j] == 0 for j in range(i+1, len(platform_setup_final_result))):#当前步骤检测到,后面的步骤都没有检测到
  247. # redis_client.set(f"platform_setup_{i+1}", str(nums))
  248. # platform_setup_final_result[i] = nums
  249. # else:
  250. # save_time=datetime.now().strftime('%Y%m%d_%H%M')
  251. # imgpath = f"{SAVE_IMG_PATH}/platform_setup{i}_{save_time}.jpg"
  252. # post_path= f"{POST_IMG_PATH4}/platform_setup{i}_{save_time}.jpg"
  253. # annotated_frame = results[0].plot()
  254. # cv2.imwrite(imgpath, annotated_frame)
  255. # redis_client.set(f"platform_setup_{i}_img",post_path)
  256. # if i==13:
  257. # save_time=datetime.now().strftime('%Y%m%d_%H%M')
  258. # imgpath = f"{SAVE_IMG_PATH}/platform_setup{i}_{save_time}.jpg"
  259. # post_path= f"{POST_IMG_PATH4}/platform_setup{i}_{save_time}.jpg"
  260. # annotated_frame = results[0].plot()
  261. # cv2.imwrite(imgpath, annotated_frame)
  262. # redis_client.set(f"platform_setup_{i}_img",post_path)
  263. # else:
  264. # redis_client.set(f"platform_setup_{i+1}", str(nums))
  265. # platform_setup_final_result[i] = nums
  266. # redis_client.rpush("platform_setup_order", f"platform_setup_{i+1}")
  267. # if i != 0:
  268. # save_time=datetime.now().strftime('%Y%m%d_%H%M')
  269. # imgpath = f"{SAVE_IMG_PATH}/platform_setup{i}_{save_time}.jpg"
  270. # post_path= f"{POST_IMG_PATH4}/platform_setup{i}_{save_time}.jpg"
  271. # annotated_frame = results[0].plot()
  272. # # Draw the polygon on the frame
  273. # # cv2.polylines(annotated_frame, [LEVLEL3_REGION], True, (0, 255, 0), 5)
  274. # # cv2.polylines(annotated_frame, [LEVLEL2_REGION], True, (0, 255, 0), 5)
  275. # # cv2.polylines(annotated_frame, [LEVLEL1_REGION], True, (0, 255, 0), 5)
  276. # # cv2.polylines(annotated_frame, [LEVLEL0_REGION], True, (0, 255, 0), 5)
  277. # cv2.imwrite(imgpath, annotated_frame)
  278. # redis_client.set(f"platform_setup_{i}_img",post_path)
  279. start_event.set()
  280. else:
  281. # Break the loop if the end of the video is reached
  282. break
  283. # Release the video capture object and close the display window
  284. cap.release()
  285. if torch.cuda.is_available():
  286. torch.cuda.empty_cache()
  287. del model