Last active
March 19, 2025 13:46
-
-
Save james4388/fa59f3e7c9d4bac238c06b4327b88b46 to your computer and use it in GitHub Desktop.
Revisions
-
james4388 revised this gist
Jun 30, 2018 . 1 changed file with 1 addition and 3 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -23,9 +23,7 @@ async def mjpeg_handler(request): mpwriter.append(data, { 'Content-Type': 'image/jpeg' }) await mpwriter.write(response, close_boundary=False) await response.drain() wc.shutdown() return response -
james4388 created this gist
Jun 24, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,54 @@ 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 with MultipartWriter('image/jpeg', boundary=boundary) as mpwriter: result, encimg = cv2.imencode('.jpg', frame, encode_param) data = encimg.tostring() mpwriter.append(data, { 'Content-Type': 'image/jpeg' }) await mpwriter.write(response) # Not working yet since MultipartWriter append closing boundary --boundary-- at the end # See https://gist.github.com/james4388/2cf7cb79d7ff4cb1c1da6b193d2ae60b for work around 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()