demo1.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import os
  2. import gc
  3. import cv2
  4. import imutils
  5. import threading
  6. import time # 导入时间模块
  7. from AIDetector_pytorch import Detector
  8. import logging
  9. import argparse # 导入argparse库
  10. # 用于控制检测线程退出的事件
  11. stop_event = threading.Event()
  12. def start_camera_detector(camera_id, width, height, detector, output_directory):
  13. name = 'Demo Camera {}'.format(camera_id)
  14. cap = cv2.VideoCapture(camera_id, cv2.CAP_V4L2)
  15. if not cap.isOpened():
  16. print('Error: Unable to open camera {}.'.format(camera_id))
  17. return
  18. cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
  19. cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
  20. fps = cap.get(cv2.CAP_PROP_FPS)
  21. if fps <= 0:
  22. fps = 30
  23. print(f'{name} fps:', fps)
  24. frame_count = 0
  25. while not stop_event.is_set(): # 检查停止事件
  26. ret, im = cap.read()
  27. if not ret or im is None:
  28. break
  29. if frame_count % 3 == 0:
  30. start_time = time.time()
  31. result = detector.feedCap(im)
  32. result_frame = result['frame']
  33. elapsed_time = time.time() - start_time
  34. result_frame = imutils.resize(result_frame, height=500)
  35. # Save the result image
  36. filename = os.path.join(output_directory, f'camera_{camera_id}_frame_{frame_count}.jpg')
  37. cv2.imwrite(filename, result_frame)
  38. print(f'Saved image: {filename}')
  39. logging.info(f'Frame {frame_count} processed in {elapsed_time:.4f} seconds.')
  40. frame_count += 1
  41. if frame_count % 30 == 0:
  42. gc.collect()
  43. cap.release()
  44. def main():
  45. parser = argparse.ArgumentParser(description='Camera Detection with ONNX.')
  46. parser.add_argument('--camera_id', type=int, default=1, help='Camera ID to use.')
  47. parser.add_argument('--width', type=int, default=1280, help='Input the wight of the video image(default=1280)')
  48. parser.add_argument('--height', type=int, default=720, help='Input the height of the video image(default=720)')
  49. args = parser.parse_args()
  50. detector = Detector()
  51. output_directory = 'output_images'
  52. os.makedirs(output_directory, exist_ok=True) # Create output directory if not exists
  53. threads = []
  54. thread = threading.Thread(target=start_camera_detector, args=(args.camera_id, args.width, args.height, detector, output_directory))
  55. thread.start()
  56. threads.append(thread)
  57. # 等待用户输入停止程序
  58. input("Press Enter to stop the camera detection...\n")
  59. # 设置停止事件
  60. stop_event.set()
  61. # 等待所有线程结束
  62. for thread in threads:
  63. thread.join()
  64. if __name__ == "__main__":
  65. main()