-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera.py
More file actions
79 lines (68 loc) · 2.6 KB
/
camera.py
File metadata and controls
79 lines (68 loc) · 2.6 KB
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
71
72
73
74
75
76
77
78
import subprocess
# Each preview frame is about 180 KB
READ_SIZE = 100 * 1024
SOI = b'\xff\xd8'
EOI = b'\xff\xd9'
# Kill existing gphoto2 processes to properly detect camera
def reset():
command = ['pkill', '-9', '-f', 'gphoto2']
subprocess.run(command)
def command(arg):
command = ['gphoto2', arg]
result = subprocess.run(command, stdout=subprocess.PIPE)
if result.returncode == 0:
return result.stdout.decode('utf-8');
def capture_image():
MjpegVideo.stop()
command = ['gphoto2', '--capture-image-and-download', '--stdout']
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode == 0:
return result.stdout;
else:
raise IOError(result.stderr.decode('utf-8'))
class MjpegVideo:
process = None
@staticmethod
def stop():
if MjpegVideo.process:
MjpegVideo.process.terminate()
MjpegVideo.process.wait()
MjpegVideo.process = None
def __init__(self, timeout=None):
# Start capturing video from gphoto2 and send it over pipe
command = ['gphoto2', '--capture-movie', '--stdout']
if timeout:
command[1] += f'={timeout}s'
MjpegVideo.stop()
self.process = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, bufsize=10**8)
try:
# collect errors occurred within 1 second
out, err = self.process.communicate(timeout=1)
if err:
raise IOError(err.decode('utf-8'))
if out:
raise Warning(out.decode('utf-8'))
except subprocess.TimeoutExpired:
# this implies video capture has started
MjpegVideo.process = self.process
pass
self.buf = b''
def get_frame(self):
while not self.process.stdout.closed:
# Read in larger chunks to avoid too many reads, but ensure full frames
chunk = self.process.stdout.read(READ_SIZE)
if not chunk:
break
self.buf += chunk
# Look for a complete JPEG frame (starting with FFD8 and ending with FFD9)
start = self.buf.find(SOI) # Start of JPEG frame
end = self.buf.find(EOI) # End of JPEG frame
if start != -1 and end != -1:
end += len(EOI)
frame = self.buf[start:end]
self.buf = self.buf[end:] # Remove the processed frame from the
return frame
def __del__(self):
self.process.terminate()
self.process.wait()