streaming http server from inside opencv2 python script?

asked 2015-05-02 09:54:58 -0500

reggie gravatar image

updated 2015-05-15 08:46:17 -0500

Is it possible to implement a streaming http server whilst working in image processing in opencv2?

eg

#!/usr/bin/env python

    import numpy as np
    import cv2


    runtime_frame_count = 0

    vid = cv2.VideoCapture(0)
    vid.set(3,800)
    vid.set(4,600)

    while True:
        ret, img = vid.read()

        #-----send contents of img to a streaming http server, for access from browser------

        runtime_frame_count = runtime_frame_count + 1
        print (runtime_frame_count)

        # ------ do some other stuff on img in opencv2------------            

        cv2.imshow("input",img)

        key = cv2.waitKey(10)
        key = cv2.waitKey(10)
        key = cv2.waitKey(10)

        if (key == 27) or (runtime_frame_count == 100):
            break

    cv2.destroyAllWindows()

    vid.release()

=================edit===========================================

Following Berak's kind suggestion, Iv'e managed to process an opencv image and serve it to a webpage.

    class CamHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            print (self.path)
            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):# infinite loop with no exit condition
                        rc,img = capture.read()
                        if not rc:
                            continue 
                        if rc:
                            #========send img to  the cv_frame() function for CV2 operations======
                            imgRGB = cv_frame(img) # contains all the opencv stuff i want to perform
                            #=============================================================

                            #imgRGB = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                            r, buf = cv2.imencode(".jpg",imgRGB) 

                            self.wfile.write("--jpgboundary\r\n")
                            self.send_header('Content-type','image/jpeg')
                            self.send_header('Content-length',str(len(buf)))
                            self.end_headers()
                            self.wfile.write(bytearray(buf))
                            self.wfile.write('\r\n')
                            time.sleep(0.01)

                            k = cv2.waitKey(20)
                            if k == 27: 
                                break



                cv2.destroyAllWindows()
                capture.release()   

                return

            if self.path.endswith('.html') or self.path=="/":
                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://'+socket.gethostbyname(socket.gethostname())+':'+ str(port) +'/cam.mjpg"/>')
                self.wfile.write('</body></html>')
                return





def main():

    global capture, average
    capture = cv2.VideoCapture(0)

    capture.set(3,800)
    capture.set(4,600)


    while(1):

        server = HTTPServer(('',port),CamHandler)
        print ("server started on: ")
        print(socket.gethostbyname(socket.gethostname()))
        CamHandler.BaseHTTPServer.BaseHTTPRequestHandler("GET", (internalipaddress ,portnumber), CamHandler)
        server.handle_request()
        k = cv2.waitKey(20)

        if k == ord('q'):

            capture.release()
            server.socket.close() 
            print("server stopped")

            cv2.destroyAllWindows()
            break

    return



main()

However, to get the code to run, I have to go to my web browser and request the webpage "localhost:port\" or "localhost:port.html"

Is there a way to call the method "def do_GET()" using python, so the cv_frame(img) function runs all the time?

I cannot work out how to run the function 'cv_frame(img)' all the time, regardless of the server situation.

edit retag flag offensive close merge delete

Comments

1

just saying, you want: vid.release() in your last line, not open another one

berak gravatar imageberak ( 2015-05-02 10:01:21 -0500 )edit

like the above edit?

reggie gravatar imagereggie ( 2015-05-02 10:20:53 -0500 )edit
1

just vid, (the variable / instance), not cv2.vid.

you could try, if this toy works for you (single client only)

berak gravatar imageberak ( 2015-05-02 10:28:09 -0500 )edit

What a toy, thanks!

reggie gravatar imagereggie ( 2015-05-03 02:09:25 -0500 )edit