-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRecordWebcam.py
65 lines (56 loc) · 2.05 KB
/
RecordWebcam.py
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
'''
For use in recording a usb camera mounted in a car
'''
import os
import time
import cv2
class RecordWebCam(object):
def __init__(self,outPath,captureFrequency=5.0,camId=0,show=False):
'''
outPath: path where the images are to be stored
Images will be stored as <epoch in milliseconds>.jpeg
captureFrequency: the frequency in hertz to save a frame
camId: the index of the usb camera to use, defaults to 1 but may need to change for multi camera machines
show: bool, if the images should be shown as they are taken
'''
self.outPath = outPath
self._checkOutPath()
self.timeBetweenFrames = 1.0/captureFrequency
self.show = show
self.lastCapture = 0
# create the video stream
self.camId = camId
self.cap = cv2.VideoCapture(camId)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT,720)
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH,1280)
if show:
self.windowName = "Captured Image"
cv2.namedWindow("Captured Image",cv2.WINDOW_NORMAL)
print("Finished setting up camera {}!".format(self.camId))
def _checkOutPath(self):
'''
Verify that self.outPath is a directory
'''
if not os.path.isdir(self.outPath):
os.makedirs(self.outPath)
def __call__(self):
'''
when called cature and save a frame
'''
currentTime = time.time()
if currentTime - self.timeBetweenFrames > self.lastCapture:
self.lastCapture = currentTime
ret,frame = self.cap.read()
assert ret, "Lost connection with camera {}!".format(self.camId)
frame = cv2.flip(frame,-1)
cv2.imwrite("{}/{:0.3f}.jpeg".format(self.outPath,currentTime),frame)
if self.show:
cv2.waitKey(1)
cv2.imshow(self.windowName,frame)
def shutDown(self):
'''
Shut down the recorder
'''
self.cap.release()
if self.show:
cv2.destroyAllWindows()