Dec-19-2016, 09:07 AM
I've almost been successful in adapting a Python 2 code for video and html streaming to Python 3 (actually, the streaming works fine for html files). Unfortunately, I was unsuccessful in adapting the central part marked inside the following code, related to image streaming (I do not master the streaming modules). For these 10 lines, I'll greatly appreciate some help and advises (I'm new in this forum, hope that this is a valid question).
import cv2 from PIL import Image from http.server import BaseHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn import time class CamHandler(BaseHTTPRequestHandler): def do_GET(self): #self.path handles the path of the request typed by the client in his browser or his other client program. #For example, the client may have typed //127.0.0.1:8080/cam.mjpg or //127.0.0.1:8080/file.html. #Here, we check only the suffix of the path to serve the client. if self.path.endswith('.mjpg'): self.send_response(200) self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary') self.end_headers() while True: try: rc, img = capture.read() if not rc: continue imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) jpg = Image.fromarray(imgRGB) #----------------------------------------------------- #This is the fragment of code that does not work for Python 3: #tmpFile = StringIO() #Python 2, don't work with Python3 #jpg.save(tmpFile, 'JPEG') #Python 2, replaced by next line (seems to work fine) self.wfile.write(bytes('--jpgboundary', 'utf8')) self.send_header('Content-type', 'image/jpeg') #this seems to work with python 3 #self.send_header('Content-length', str(tmpFile.len)) #Python 2, replaced by self.send_header('Content-length', str(jpg.size[0]*jpg.size[1])) #don't know if this is the right replacement of the previous line self.end_headers() jpg.save(self.wfile, 'JPEG') #makes Python3 crashes time.sleep(0.04) #end of not working fragment #----------------------------------------------------- except KeyboardInterrupt: break return if self.path.endswith('.html'): # The streaming here works for Python 3: self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(bytes('<html><head>Hello world</head><body>', 'utf8')) return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" def main(): global capture capture = cv2.VideoCapture(0) capture.set(cv2.CAP_PROP_FRAME_WIDTH, 320) capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 240) capture.set(cv2.CAP_PROP_SATURATION, 0.2) try: server = ThreadedHTTPServer(('localhost', 8080), CamHandler) print('server started', flush = True) server.serve_forever() except KeyboardInterrupt: capture.release() server.socket.close() #---------------------------------------------------------------------------- if __name__ == '__main__': main()