Python Forum
Video Streaming Python 3 adaptation failling - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Video Streaming Python 3 adaptation failling (/thread-1267.html)



Video Streaming Python 3 adaptation failling - maimonid - Dec-19-2016

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()



RE: Video Streaming Python 3 adaptation failling - Skaperen - Dec-19-2016

what error messages is python 3 giving you that python 2 is not giving?  or is this another error message guessing game?


RE: Video Streaming Python 3 adaptation failling - maimonid - Dec-19-2016

(Dec-19-2016, 09:17 AM)Skaperen Wrote: what error messages is python 3 giving you that python 2 is not giving?  or is this another error message guessing game?

I've taken this code from the web. It was written for python 2 and people said it works, but I've not tested it with Python 2 (not installed in my computer). Regarding the error message, there is none: the code is running, until I type in my internet browser "http://127.0.0.1:8080/try.mjpg", and then the Ipython kernel dies (the console from where I'm running the code), while the internet browser writes "problem loading page" etc.


RE: Video Streaming Python 3 adaptation failling - Skaperen - Dec-24-2016

so basically it just dies before delivering content to the browser.

how do you know that it is the part of the code you marked with "#This is the fragment of code that does not work for Python 3:" that is where the failure is happening?  can whatever test was done to narrow it down this far be used to narrow it any further, such as testing smaller code parts?  have you tried tracing?


RE: Video Streaming Python 3 adaptation failling - maimonid - Dec-25-2016

(Dec-24-2016, 04:49 AM)Skaperen Wrote: so basically it just dies before delivering content to the browser.

how do you know that it is the part of the code you marked with "#This is the fragment of code that does not work for Python 3:" that is where the failure is happening?  can whatever test was done to narrow it down this far be used to narrow it any further, such as testing smaller code parts?  have you tried tracing?

Skaperen, thank you for answering me.
I know this is the fragment of code that does not work, because I've tried to remove all or a part of it and no crashes occur (all the other things works as desired).  If the line "jpg.save(self.wfile, 'JPEG')" is removed, this does not crash, but, of course nothing is shown. The problem here is that there is something to know (how to write this correctly for Python 3): I'm trying to replace the code in a blind way and this does not work.


RE: Video Streaming Python 3 adaptation failling - Skaperen - Dec-26-2016

if you can narrow down one line of code that when removed (or commented out) avoids an exception, it would be nice to know:
1. which line and what has
2. the exception and what line it happened on, including full traceback
3. the value, as explained by repr(), of every variable referenced by all lines involved (both if the exception happens at a different line than the one put back in)


RE: Video Streaming Python 3 adaptation failling - maimonid - Dec-26-2016

Thank you Skaperen. I'm not able to obtain the information you think is needed. I think if someone experienced in this part of the Python language hit my question, he will catch the problem in a glance, so ... let me wait.


RE: Video Streaming Python 3 adaptation failling - Larz60+ - Dec-26-2016

Quote:while the internet browser writes "problem loading page" etc.

What verbatim does it say? This is important


RE: Video Streaming Python 3 adaptation failling - maimonid - Dec-28-2016

(Dec-26-2016, 09:44 AM)Larz60+ Wrote:
Quote:while the internet browser writes "problem loading page" etc.

What verbatim does it say? This is important

Thank you for answering me Larz60+.
If I put the line "jpg.save(self.wfile, 'JPEG')" into comments, the browser says "the image "http://127.0.0.1:8080/try.mjpg" cannot be displayed because it contains errors."
And after I stop the execution of the program, the console displays the message:
127.0.0.1 - - [28/Dec/2016 11:16:23] "GET /try.mjpg HTTP/1.1" 200 -

If I don't put the above line into comment, the browser displays:
"The connection to the server was reset while the page was loading.
*The site could be temporarily unavailable or too busy. Try again in a few moments.
*If you are unable to load any pages, check your computer’s network connection.
*If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web."
and the kernel of the console dies.