WebcamVideoStream.py 1.04 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
11
12
        self.stream = cv2.VideoCapture(src)
        (self.grabbed, self.frame) = self.stream.read()

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
33
34
            (self.grabbed, self.frame) = self.stream.read()

    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