demo.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import gc
  2. import cv2
  3. import imutils
  4. import threading
  5. from AIDetector_pytorch import Detector
  6. def start_camera_detector(camera_id, detector):
  7. name = 'Demo Camera {}'.format(camera_id)
  8. cap = cv2.VideoCapture(camera_id, cv2.CAP_V4L2)
  9. if not cap.isOpened():
  10. print('Error: Unable to open camera {}.'.format(camera_id))
  11. return
  12. cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
  13. cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 640)
  14. fps = cap.get(cv2.CAP_PROP_FPS)
  15. if fps <= 0:
  16. fps = 30
  17. t = int(1000 / fps)
  18. print(f'{name} fps:', fps)
  19. frame_count = 0
  20. while True:
  21. ret, im = cap.read()
  22. if not ret or im is None:
  23. break
  24. if frame_count % 3 == 0:
  25. result = detector.feedCap(im)
  26. result = result['frame']
  27. result = imutils.resize(result, height=500)
  28. cv2.imshow(name, result)
  29. if cv2.waitKey(t) & 0xFF == ord('q'):
  30. break
  31. frame_count += 1
  32. if frame_count % 30 == 0:
  33. gc.collect()
  34. cap.release()
  35. cv2.destroyWindow(name)
  36. def main():
  37. detector = Detector()
  38. threads = []
  39. for i in range(6): # camera 数量
  40. thread = threading.Thread(target=start_camera_detector, args=(i, detector))
  41. thread.start()
  42. threads.append(thread)
  43. for thread in threads:
  44. thread.join()
  45. if __name__ == "__main__":
  46. main()