platform_setup_detect.py 15 KB

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