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

3
4
import cv2

Arne Gerdes's avatar
Arne Gerdes committed
5

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

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

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

    def start(self):
17
18

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

    def update(self):
23
24

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

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

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

    def read(self):
35
36

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

    def stop(self):
40
41

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

    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))