You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

webcam.py 2.1 kB

10 months ago
10 months ago
10 months ago
1 year ago
10 months ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import os
  2. import time
  3. import cv2
  4. import numpy as np
  5. import pyarrow as pa
  6. from dora import DoraStatus
  7. CAMERA_WIDTH = 640
  8. CAMERA_HEIGHT = 480
  9. CAMERA_INDEX = int(os.getenv("CAMERA_INDEX", 0))
  10. CI = os.environ.get("CI")
  11. font = cv2.FONT_HERSHEY_SIMPLEX
  12. class Operator:
  13. """Sending image from webcam to the dataflow
  14. """
  15. def __init__(self):
  16. self.video_capture = cv2.VideoCapture(CAMERA_INDEX)
  17. self.start_time = time.time()
  18. self.video_capture.set(cv2.CAP_PROP_FRAME_WIDTH, CAMERA_WIDTH)
  19. self.video_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, CAMERA_HEIGHT)
  20. self.failure_count = 0
  21. def on_event(
  22. self,
  23. dora_event: str,
  24. send_output,
  25. ) -> DoraStatus:
  26. event_type = dora_event["type"]
  27. if event_type == "INPUT":
  28. ret, frame = self.video_capture.read()
  29. if ret:
  30. frame = cv2.resize(frame, (CAMERA_WIDTH, CAMERA_HEIGHT))
  31. self.failure_count = 0
  32. ## Push an error image in case the camera is not available.
  33. elif self.failure_count > 10:
  34. frame = np.zeros((CAMERA_HEIGHT, CAMERA_WIDTH, 3), dtype=np.uint8)
  35. cv2.putText(
  36. frame,
  37. "No Webcam was found at index %d" % (CAMERA_INDEX),
  38. (30, 30),
  39. font,
  40. 0.75,
  41. (255, 255, 255),
  42. 2,
  43. 1,
  44. )
  45. else:
  46. self.failure_count += 1
  47. return DoraStatus.CONTINUE
  48. send_output(
  49. "image",
  50. pa.array(frame.ravel()),
  51. dora_event["metadata"],
  52. )
  53. elif event_type == "STOP":
  54. print("received stop")
  55. else:
  56. print("received unexpected event:", event_type)
  57. if time.time() - self.start_time < 20 or CI != "true":
  58. return DoraStatus.CONTINUE
  59. return DoraStatus.STOP
  60. def __del__(self):
  61. self.video_capture.release()