Python Forum
Video Streaming Python 3 adaptation failling
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Video Streaming Python 3 adaptation failling
#1
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()
Reply
#2
what error messages is python 3 giving you that python 2 is not giving?  or is this another error message guessing game?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#3
(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.
Reply
#4
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#5
(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.
Reply
#6
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)
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#7
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.
Reply
#8
Quote:while the internet browser writes "problem loading page" etc.

What verbatim does it say? This is important
Reply
#9
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Video recording with Raspberry Pi - What´s wrong with my python code? Montezuma1502 3 1,258 Feb-24-2023, 06:14 PM
Last Post: deanhystad
  How to output Python in Spout or any other video sharing network? buzzdarkyear 4 2,160 Jan-11-2022, 11:37 AM
Last Post: buzzdarkyear
  How to decrease latency while recording streaming video. unicorn2019 0 1,260 Nov-15-2021, 02:12 PM
Last Post: unicorn2019
  How to get Data-Taken For a Video file using Python ramprasad1211 1 1,906 Apr-28-2020, 08:48 AM
Last Post: ndc85430
  Get list of Video Device in python on Windows machine Michal 1 10,500 Apr-03-2020, 06:57 PM
Last Post: Mateusz
  How to check if video has been deleted or removed in youtube using python Prince_Bhatia 14 11,801 Feb-21-2020, 04:33 AM
Last Post: jehoshua
  Playing music from streaming ebolisa 1 1,889 Oct-08-2019, 06:50 PM
Last Post: snippsat
  Python 3.5 streaming output to the same log file that I write to cbj0517 2 2,755 Apr-23-2019, 04:38 PM
Last Post: cbj0517
  Streaming to website instead of Window OpenCV SDGRIFFUSW 1 1,924 Apr-19-2019, 09:59 PM
Last Post: SheeppOSU
  Position video in X Y in python sigmahokies 0 2,017 Feb-05-2019, 01:18 PM
Last Post: sigmahokies

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020