-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
68 lines (51 loc) · 1.73 KB
/
app.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
66
67
68
import sys
import time
import json
import pygame
import pygame.camera
from io import BytesIO
from PIL import Image as pil_image
from is_wire.core import Channel, Message, Logger
from is_msgs.image_pb2 import Image
log = Logger(name="CameraGateway")
options_file = "options.json" if len(sys.argv) < 2 else sys.argv[1]
with open(options_file, 'r') as f:
options = json.load(f)
log.info("Options loaded from '{}'\n{}", options_file, json.dumps(options))
pygame.camera.init()
devices = pygame.camera.list_cameras()
if options['device'] not in devices:
log.critical("Device '{}' not found.", options['device'])
cam = pygame.camera.Camera(options['device'], options['resolution'])
cam.start()
def run():
channel = Channel(options['broker_uri'])
log.info("Connected to {}", options['broker_uri'])
while True:
t0 = time.time()
img = cam.get_image()
data = pygame.image.tostring(img, 'RGB')
pil_img = pil_image.frombytes('RGB', options['resolution'], data)
if options['flip_v']:
pil_img = pil_img.transpose(pil_image.FLIP_TOP_BOTTOM)
if options['flip_h']:
pil_img = pil_img.transpose(pil_image.FLIP_LEFT_RIGHT)
bdata = BytesIO()
pil_img.save(bdata, 'jpeg')
pb_image = Image()
pb_image.data = bdata.getvalue()
msg = Message(content=pb_image)
channel.publish(msg, topic="CameraGateway.{}.Frame".format(options['camera_id']))
dt = time.time() - t0
log.debug("took_ms={:.1f}", dt * 1e3)
interval = max(0.0, 1.0 / options['fps'] - dt)
time.sleep(interval)
if options['broker_reconnection']:
while True:
try:
run()
except:
pass
else:
run()
cam.stop()