WebcamVideoStream.py 1.21 KB
Newer Older
1
from threading import Thread
Arne Gerdes's avatar
Arne Gerdes committed
2

3
4
5
6
import cv2

class WebcamVideoStream:
    def __init__(self, src=0):
7
8

        # Initialize webcam stream and read the first frame from the stream
9
        self.stream = cv2.VideoCapture(src)
10
        (self.ret, self.frame) = self.stream.read()
11

12
        # Variable indicating whether the thread should be stopped
13
14
15
        self.stopped = False

    def start(self):
16
17

        # start the thread to read frames from the webcam stream
18
19
20
21
        Thread(target=self.update, args=()).start()
        return self

    def update(self):
22
23

        # Endless loop until the thread stops
24
        while True:
25
26

            # If the thread indicator variable is set, it stops the thread
27
28
29
            if self.stopped:
                return

30
            # Otherwise, the next frame is read from the stream
31
            self.ret, self.frame = self.stream.read()
32
33

    def read(self):
34
35

        # returns the last frame
36
37
38
        return self.frame

    def stop(self):
39
40

        # indicates that the thread should be stopped
Arne Gerdes's avatar
Arne Gerdes committed
41
        self.stopped = True
42
43
44
45

    def size(self):
        # returns the width and height of the video stream
        return int(self.stream.get(cv2.CAP_PROP_FRAME_WIDTH)), int(self.stream.get(cv2.CAP_PROP_FRAME_HEIGHT))