Help needed with Python Code

Soldato
Joined
18 Oct 2002
Posts
2,912
Location
Stoke-on-Trent
Ive copied and altered some code i found on the web to enable me to take the stream from my IP Camera (video.cgi) and display it in a window.
The program is working fine and displaying the video from the camera apart from im getting errors in python.
The errors are:-

Corrupt JPEG data: X extraneous bytes before marker 0xd9

The 'X' is either '1' or '2' and i get loads of these errors even though the
video picture is not corrupt.

Here's the code below (missing ip address etc)
Im sure the error is occurring in the line:-
img = wx.ImageFromStream(stream)

Can anyone help me out with what the problem is and fix the code ????


Code:
import httplib
import base64
import StringIO
import threading
import time
import wx

class Trendnet():
  
  def __init__(self, ip='1.1.1.1', username='admin', password='admin'):
    self.IP = ip
    self.Username = username
    self.Password = password
    self.Connected = False

  def Connect(self):
    if self.Connected == False:
      try:
        print 'Atempting to connect to camera', self.IP, self.Username, self.Password
        h = httplib.HTTP(self.IP)
        h.putrequest('GET','/video.cgi')
        h.putheader('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (self.Username, self.Password))[:-1])
        h.endheaders()
        errcode, errmsg, headers = h.getreply()
        self.File = h.getfile()
        print 'Connected!'
        self.Connected = True
      except:
        print 'Unable to connect!'
        self.Connected = False
      
  def Disconnect(self):
    self.Connected = False
    print 'Camera Disconnected!' 

  def Update(self):
    if self.Connected:
      
      s = self.File.readline()    # '--myboundry'
      s = self.File.readline()    # 'Content-Length: #####'
      framesize = int(s[16:])
      s = self.File.read(framesize)  # jpeg data
      while s[0] != chr(0xff):       # stripp off some junk in front
        s = s[1:]                    # of the jpeg
      return StringIO.StringIO(s)
      
      
class CameraPanel(wx.Panel):
  
  def __init__(self, parent, camera):
    wx.Panel.__init__(self, parent, id=wx.ID_ANY, style=wx.SIMPLE_BORDER)
    self.Camera = camera
    self.Bind(wx.EVT_PAINT, self.OnPaint)
    self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
  
  def OnEraseBackground(self, event):
    pass
  
  def OnPaint(self, event):
   dc = wx.BufferedPaintDC(self)
    
   if self.Camera.Connected == True:
     try:
       stream = self.Camera.Update()
       if stream != None:
         img = wx.ImageFromStream(stream)
         bmp = wx.BitmapFromImage(img)
         dc.DrawBitmap(bmp, 0, 0, True)
     except:
       pass
   else:
	   pass
 
Last edited:
Back
Top Bottom