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
|
# This is a CamiTK python action
#
# Video acquisition using OpenCV.
#
# Creates a new RGB image component and continuously replaces its image data using the video feed.
# This action uses a timer to refresh the image.
import camitk
from PySide2.QtCore import QTimer
import cv2
def capture(self):
ret, frame = self.capture_device.read()
if not ret:
camitk.warning("Error: Could not read frame.")
return None
else:
# Convert the image from BGR to RGB
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
return rgb_frame
def capture_loop(self):
rgb_frame = capture(self)
if rgb_frame is not None and self.image_component:
self.image_component.replaceImageData(rgb_frame)
def init(self:camitk.Action):
self.timer:QTimer = None
self.camera_index:int = 0
self.image_component:camitk.ImageComponent = None
self.setApplyButtonText("Start")
def process(self:camitk.Action):
if not self.timer:
self.timer = QTimer()
connected = self.timer.timeout.connect(lambda: capture_loop(self))
if not self.timer.isActive():
self.capture_device = cv2.VideoCapture(self.camera_index)
if not self.capture_device.isOpened():
camitk.warning(f"Error: Could not open capturing device #{self.camera_index}.")
return
rgb_frame = capture(self)
if rgb_frame is not None and not self.image_component:
self.image_component = camitk.newImageComponentFromNumpy(rgb_frame, "Webcam Video")
self.refreshApplication()
self.setApplyButtonText("Stop")
self.timer.start(10)
else:
self.setApplyButtonText("Restart")
self.timer.stop()
# Release the camera
self.capture_device.release()
|