Skip to content

Instantly share code, notes, and snippets.

@james4388
Created June 24, 2018 05:10
Show Gist options
  • Save james4388/2cf7cb79d7ff4cb1c1da6b193d2ae60b to your computer and use it in GitHub Desktop.
Save james4388/2cf7cb79d7ff4cb1c1da6b193d2ae60b to your computer and use it in GitHub Desktop.
mjpeg streaming using aiohttp and opencv
import asyncio
import cv2
from aiohttp import web, MultipartWriter
async def mjpeg_handler(request):
boundary = "boundarydonotcross"
response = web.StreamResponse(status=200, reason='OK', headers={
'Content-Type': 'multipart/x-mixed-replace; '
'boundary=--%s' % boundary,
})
await response.prepare(request)
wc = cv2.VideoCapture(0)
encode_param = (int(cv2.IMWRITE_JPEG_QUALITY), 90)
while True:
_, frame = wc.read()
if frame is None:
continue
result, encimg = cv2.imencode('.jpg', frame, encode_param)
data = encimg.tostring()
await response.write(
'--{}\r\n'.format(boundary).encode('utf-8'))
await response.write(b'Content-Type: image/jpeg\r\n')
await response.write('Content-Length: {}\r\n'.format(
len(data)).encode('utf-8'))
await response.write(b"\r\n")
# Write data
await response.write(data)
await response.write(b"\r\n")
await response.drain()
wc.shutdown()
return response
async def index(request):
return web.Response(text='<img src="/image"/>', content_type='text/html')
async def start_server(loop, address, port):
app = web.Application(loop=loop)
app.router.add_route('GET', "/", index)
app.router.add_route('GET', "/image", mjpeg_handler)
return await loop.create_server(app.make_handler(), address, port)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(start_server(loop, '0.0.0.0', 8888))
print("Server ready!")
try:
loop.run_forever()
except KeyboardInterrupt:
print("Shutting Down!")
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment