Forked from n3wtron/simple_mjpeg_streamer_http_server
Created
February 6, 2022 03:45
-
-
Save ekapujiw2002/1db8594e5e2fc5b605545b29daedeefd to your computer and use it in GitHub Desktop.
Simple Python Motion Jpeg (mjpeg server) from webcam. Using: OpenCV,BaseHTTPServer
This file contains 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 characters
#!/usr/bin/python | |
''' | |
Author: Igor Maculan - [email protected] | |
A Simple mjpg stream http server | |
''' | |
import cv2 | |
import Image | |
import threading | |
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer | |
from SocketServer import ThreadingMixIn | |
import StringIO | |
import time | |
capture=None | |
class CamHandler(BaseHTTPRequestHandler): | |
def do_GET(self): | |
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) | |
tmpFile = StringIO.StringIO() | |
jpg.save(tmpFile,'JPEG') | |
self.wfile.write("--jpgboundary") | |
self.send_header('Content-type','image/jpeg') | |
self.send_header('Content-length',str(tmpFile.len)) | |
self.end_headers() | |
jpg.save(self.wfile,'JPEG') | |
time.sleep(0.05) | |
except KeyboardInterrupt: | |
break | |
return | |
if self.path.endswith('.html'): | |
self.send_response(200) | |
self.send_header('Content-type','text/html') | |
self.end_headers() | |
self.wfile.write('<html><head></head><body>') | |
self.wfile.write('<img src="http://127.0.0.1:8080/cam.mjpg"/>') | |
self.wfile.write('</body></html>') | |
return | |
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): | |
"""Handle requests in a separate thread.""" | |
def main(): | |
global capture | |
capture = cv2.VideoCapture(0) | |
capture.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 320); | |
capture.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 240); | |
capture.set(cv2.cv.CV_CAP_PROP_SATURATION,0.2); | |
global img | |
try: | |
server = ThreadedHTTPServer(('localhost', 8080), CamHandler) | |
print "server started" | |
server.serve_forever() | |
except KeyboardInterrupt: | |
capture.release() | |
server.socket.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment