1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
# This is a script independent from CamiTK used to demonstrate
# how a CamiTK Python extension can use external code.
# This code is used by the action acquire_video_using_script
#
# Note:
# This script can be used independently from CamiTK (see __main__ below for an example)
# just run it using the extension virtual environment:
# .venv/bin/python video_capture_device
import cv2
class VideoCaptureDevice:
max_camera_test_index:int = 10
def __init__(self, camera_index, format=cv2.COLOR_BGR2RGB):
self.capture_device:cv2.VideoCapture = None
self.camera_index:int = camera_index
self.format = format
@staticmethod
def list_available_cameras():
available_cameras = []
for index in range(VideoCaptureDevice.max_camera_test_index):
cap = cv2.VideoCapture(index)
if cap.isOpened():
available_cameras.append(index)
cap.release()
return available_cameras
def is_started(self):
return self.capture_device != None
def start(self):
self.capture_device = cv2.VideoCapture(self.camera_index)
if not self.capture_device.isOpened():
print(f"Error: Could not open capturing device #{self.camera_index}.")
return
def stop(self):
self.capture_device.release()
self.capture_device = None
def capture(self):
ret, frame = self.capture_device.read()
if not ret:
print("Error: Could not read frame.")
return None
else:
# Convert the image from BGR
if self.format is not None:
converted_frame = cv2.cvtColor(frame, self.format)
else:
converted_frame = frame
return converted_frame
if __name__ == "__main__":
available_cameras = VideoCaptureDevice.list_available_cameras()
if (len(available_cameras)>1):
camera = VideoCaptureDevice(available_cameras[0],None)
camera.start()
userInterruption = False
cameraInterruption = False
print("\nPress any key to stop video acquisition\n")
while cv2.waitKey(1) == -1: # check if any key was pressed during 1 ms
frame = camera.capture()
if frame is None:
print("Error: Could not read frame.")
cv2.imshow('Camera Feed', frame)
camera.stop()
cv2.destroyAllWindows()
else:
print("No camera available. Exiting")
|