-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjpeg_streaming.py
More file actions
94 lines (72 loc) · 2.86 KB
/
jpeg_streaming.py
File metadata and controls
94 lines (72 loc) · 2.86 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env python3
"""
JPEG Video Streaming Example
Demonstrates real-time JPEG frame streaming and video recording
with proper resource management using context managers.
"""
import serial
import time
from pydiplink import JpegVideoWriter, receive_and_show_jpeg
def main():
# Configuration
PORT = "/dev/ttyUSB0"
BAUD = 500000
OUTPUT_VIDEO = "output.avi"
FPS = 30
RESOLUTION = (640, 480)
NUM_FRAMES = 300 # Record 10 seconds at 30 FPS
print(f"Connecting to {PORT}...")
try:
ser = serial.Serial(PORT, BAUD, timeout=5)
print("Connected!")
print(f"\nRecording {NUM_FRAMES} frames ({NUM_FRAMES/FPS:.1f} seconds)")
print(f"Resolution: {RESOLUTION[0]}x{RESOLUTION[1]} at {FPS} FPS")
print(f"Output: {OUTPUT_VIDEO}\n")
# Use context manager for automatic cleanup
with JpegVideoWriter(OUTPUT_VIDEO, fps=FPS, resolution=RESOLUTION) as writer:
frames_received = 0
start_time = time.time()
for i in range(NUM_FRAMES):
try:
# Receive JPEG frame
frame = receive_and_show_jpeg(ser, resolution=RESOLUTION)
if frame is None:
print(f"Frame {i+1}: failed to receive, skipping...")
continue
writer.write_frame(frame)
frames_received += 1
# Progress indicator
if (i + 1) % 30 == 0:
elapsed = time.time() - start_time
fps_actual = frames_received / elapsed
print(
f"Frame {i+1}/{NUM_FRAMES} "
f"({fps_actual:.1f} FPS, {elapsed:.1f}s elapsed)"
)
except TimeoutError:
print(f"Frame {i+1}: timeout, skipping...")
continue
except KeyboardInterrupt:
print("\nInterrupted by user")
break
except Exception as e:
print(f"Frame {i+1}: error - {e}")
continue
# Video writer automatically closed by context manager
elapsed_total = time.time() - start_time
avg_fps = frames_received / elapsed_total
print(f"\n=== Recording Complete ===")
print(f"Frames received: {frames_received}/{NUM_FRAMES}")
print(f"Total time: {elapsed_total:.1f}s")
print(f"Average FPS: {avg_fps:.1f}")
print(f"Video saved to: {OUTPUT_VIDEO}")
except serial.SerialException as e:
print(f"Serial error: {e}")
except KeyboardInterrupt:
print("\nRecording interrupted by user")
finally:
if 'ser' in locals():
ser.close()
print("Serial port closed")
if __name__ == "__main__":
main()