-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMjpgServer.py
62 lines (58 loc) · 2.28 KB
/
MjpgServer.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
#!/usr/bin/python3
'''
Author: Igor Maculan - [email protected]
A Simple mjpg stream http server
'''
import cv2
import time
import threading
import http
from socketserver import ThreadingMixIn
from http.server import BaseHTTPRequestHandler, HTTPServer,ThreadingHTTPServer
img_show = None
quality = (int(cv2.IMWRITE_JPEG_QUALITY), 70)
class MJPG_Handler(BaseHTTPRequestHandler):
def do_GET(self):
global img_show
if self.path == '/?action=snapshot':
if img_show is not None:
try:
l_quality = (int(cv2.IMWRITE_JPEG_QUALITY), 100)
ret, jpg = cv2.imencode('.jpg', img_show, l_quality)
jpg_bytes = jpg.tobytes()
self.send_response(200)
self.send_header('Content-type','image/jpeg')
self.send_header('Content-length', len(jpg_bytes))
self.end_headers()
self.wfile.write(jpg_bytes)
except Exception as e:
print('error1', e)
else:
img_show = None
self.send_response(200)
self.send_header('Content-type', 'multipart/x-mixed-replace; boundary=--boundarydonotcross')
self.end_headers()
while True:
try:
if img_show is not None:
ret, jpg = cv2.imencode('.jpg', img_show, quality)
jpg_bytes = jpg.tobytes()
self.send_header('Content-type', 'image/jpeg')
self.send_header('Content-length', len(jpg_bytes))
#self.send_header('X-Timestamp:', time.time())
self.wfile.write('--boundarydonotcross\r\n'.encode())
self.end_headers()
self.wfile.write(jpg_bytes)
time.sleep(0.05)
except Exception as e:
print("error2", e)
break
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
def startMjpgServer():
try:
server = ThreadedHTTPServer(('', 8080), MJPG_Handler)
print("server started")
server.serve_forever()
except KeyboardInterrupt:
pass