welding_wearing_detect.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import torch
  2. import cv2
  3. import threading
  4. from datetime import datetime
  5. from ultralytics import YOLO
  6. from globals import stop_event,redis_client
  7. from config import SAVE_IMG_PATH,POST_IMG_PATH1,VIDEO_SOURCE,MODEL_PATH
  8. def init_compressed_oxygen_detection():
  9. pass
  10. def start_compressed_oxygen_detection(start_events):
  11. event = threading.Event()
  12. start_events.append(event)
  13. thread = threading.Thread(target=process_video, args=(MODEL_PATH,VIDEO_SOURCE,event))
  14. thread.daemon=True
  15. thread.start()
  16. thread.join()
  17. def process_video(model_path, video_source, start_event):
  18. model = YOLO(model_path)
  19. cap = cv2.VideoCapture(video_source)
  20. while cap.isOpened():
  21. # Read a frame from the video
  22. success, frame = cap.read()
  23. if stop_event.is_set():#控制停止推理
  24. break
  25. if success:
  26. if cap.get(cv2.CAP_PROP_POS_FRAMES) % 10 != 0:#跳帧检测,
  27. continue
  28. results = model.predict(frame,conf=0.6,verbose=False)
  29. for r in results:
  30. boxes = r.boxes.xyxy # 提取所有检测到的边界框坐标
  31. confidences = r.boxes.conf # 提取所有检测到的置信度
  32. classes = r.boxes.cls # 提取所有检测到的类别索引
  33. for i in range(len(boxes)):
  34. x1, y1, x2, y2 = boxes[i].tolist()
  35. confidence = confidences[i].item()
  36. cls = int(classes[i].item())
  37. label = model.names[cls]
  38. pass
  39. start_event.set()
  40. else:
  41. # Break the loop if the end of the video is reached
  42. break
  43. # Release the video capture object and close the display window
  44. cap.release()
  45. if torch.cuda.is_available():
  46. torch.cuda.empty_cache()
  47. del model