File: video_capture.py

package info (click to toggle)
camitk 6.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 389,496 kB
  • sloc: cpp: 103,476; sh: 2,448; python: 1,618; xml: 984; makefile: 128; perl: 84; sed: 20
file content (70 lines) | stat: -rw-r--r-- 2,313 bytes parent folder | download
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
# This is a CamiTK python action
#
# Video acquisition using OpenCV. It continuously replaces the image data of the selected
# component using the video feed.
# This action uses a timer to refresh the image.
# Note that you need to run the "Acquire Image" action first in order to get an image
# component with the proper dimensions.

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)

    self.setParameterValue("Video Frame", self.getParameterValue("Video Frame")+1)
    
    # uncomment the next line to update the GUI
    self.saveState()
    self.updateWidget()

def init(self:camitk.Action):
    self.timer = None
    self.camera_index = 0

def process(self:camitk.Action):  
    # create the timer
    if not self.timer:
        self.timer = QTimer()
        connected = self.timer.timeout.connect(lambda: capture_loop(self))
        self.image_component = self.getTargets()[-1]
    
    # if the acquisition is paused
    if not self.timer.isActive():
        self.setParameterValue("Video Frame", 0)
        
        # open the camera
        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
        
        camitk.info("Starting Image Acquisition")
        self.timer.start(10)
    else:
        camitk.info("Stopping Image acquisition")
        self.timer.stop()
        # Release the camera
        self.capture_device.release()

    # Note: if camitk.refresh() or self.refreshApplication() is called before the
    # end of the method (e.g. just before the "self.timer.start(10)"), the python objects are
    # lost → self.timer is NoneType...
    #
    # → call refresh only when everything is in place
    # self.refreshApplication()
    # camitk.refresh()