I am new to python. I am trying to write a motion detection app. Currently, I am trying to get the webcam video to display on the screen. Current code right now has no flicker at first, but after any resizing, the flicker will come back. Any clue? Also, why doesn't it work without self.Refresh() in the timer event, isn't paint event always happening unless the frame is minimized? Thanks in advance.
import wx
import cv
class LiveFrame(wx.Frame):
fps = 30
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, title="Live Camera Feed")
self.SetDoubleBuffered(True)
self.capture = None
self.bmp = None
#self.displayPanel = wx.Panel(self,-1)
#set up camaera init
self.capture = cv.CaptureFromCAM(0)
frame = cv.QueryFrame(self.capture)
if frame:
cv.CvtColor(frame,frame,cv.CV_BGR2RGB)
self.bmp = wx.BitmapFromBuffer(frame.width,frame.height,frame.tostring())
self.SetSize((frame.width,frame.height))
self.displayPanel = wx.Panel(self,-1)
self.fpstimer = wx.Timer(self)
self.fpstimer.Start(1000/self.fps)
self.Bind(wx.EVT_TIMER, self.onNextFrame, self.fpstimer)
self.Bind(wx.EVT_PAINT, self.onPaint)
self.Show(True)
def updateVideo(self):
frame = cv.QueryFrame(self.capture)
if frame:
cv.CvtColor(frame,frame,cv.CV_BGR2RGB)
self.bmp.CopyFromBuffer(frame.tostring())
self.Refresh()
def onNextFrame(self,evt):
self.updateVideo()
#self.Refresh()
evt.Skip()
def onPaint(self,evt):
#if self.bmp:
wx.BufferedPaintDC(self.displayPanel, self.bmp)
evt.Skip()
if __name__=="__main__":
app = wx.App()
app.RestoreStdio()
LiveFrame(None)
app.MainLoop()
I have found the solution to this problem. The flickering came from the panel clearing its background. I had to create a panel instance and have its EVT_ERASE_BACKGROUND bypass. Another thing is that I had to put the webcam routine inside that panel and have BufferPaintedDC drawing on the panel itself. For some reason, flicker still persist if wx.BufferedPaintedDC is drawing from the frame to self.displaypanel .
When you're drawing, you just have to call Refresh. It's a requirement. I don't remember why. To get rid of flicker, you'll probably want to read up on DoubleBuffering: http://wiki.wxpython.org/DoubleBufferedDrawing
Or maybe you could use the mplayer control. There's an example here: http://www.blog.pythonlibrary.org/2010/07/24/wxpython-creating-a-simple-media-player/
Related
I am writing a custom button control in wxPython 4.1.1 on Python 3.9.12 using MacOS 12.2. The custom button uses a bitmap background with text written on it. The bitmap is transparent so parts of underlying controls can be seen through it. This worked in 4.0.7-Pre2, but no longer. I have reduced the problem to the use of MemoryDC to create a a buffered copy of the background image.When BufferedPaintDC or MemoryDC are used, the alpha channel disappears and the transparent region is black. However, if I don't use a buffered DC and draw directly on the control, everything still works. Why is this?
The minimum code to reproduce looks like:
import wx
class MyButton(wx.Control):
def __init__(self, parent, id, text, **kwargs):
wx.Control.__init__(self,parent, id, **kwargs)
self.Bind(wx.EVT_PAINT,self._onPaint)
self.myBG = self.MakeBG()
def MakeBG(self):
newBG = wx.Bitmap(50,50)
mdc = wx.MemoryDC()
mdc.SelectObject(newBG)
mdc.SetBackground(wx.Brush(wx.Colour(0,0,255, wx.ALPHA_TRANSPARENT)))
mdc.Clear()
mdc.DrawText("HELLO", 0,0)
return newBG
def _onPaint(self, event):
dc = wx.PaintDC(self)
dc.DrawBitmap(self.myBG, 0,0, True)
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(200,100))
button = MyButton(self, -1 , "TEST BUTTON")
self.BackgroundColour = wx.Colour(255,0,0)
self.Show(True)
self.Refresh()
if __name__ == "__main__":
app = wx.App(False) # Create a new app, don't redirect stdout/stderr to a window.
frame = MyFrame(None, "Hello World") # A Frame is a top-level window.
app.MainLoop()
However, if I change the paint event to not use the bitmap and draw directly with the PaintDC, it works.
def _onPaint(self, event):
dc = wx.PaintDC(self)
dc.SetBackground(wx.Brush(wx.Colour(0,0,255, wx.ALPHA_TRANSPARENT)))
dc.Clear()
dc.DrawText("HELLO", 0,0)
I think the problem is with retaining the alpha channel, but I think something deeper is wrong because a BufferedPaintDC also has the same problem.
Database Loading Panel Screen StaticText is Blurred Out when Shown
Hello,
I have an odd issue with a loading screen. The problem is this: When I start with a main screen, then when you click on the 'next' button,
it goes to the database loading screen, when it is done, it prints on the screen that the Database Loading is complete.
The problem is that the loading screen text is blurred out for some reason. Also, something I discovered is that if you pop up a message dialog
box, the loading text is shown...
In this example, I am not actually loading into an actual database. Instead, I am just sleeping for seven seconds.
If you are confused as to what I am saying, just run the example, and you will see that the loading screen is all messed up...
Here is the code:
import wx
import time
class TextPanel(wx.Panel):
def __init__(self, parent, label):
self.__myParent = parent
wx.Panel.__init__(self, self.__myParent, size = (800, 800))
staticText = wx.StaticText(self, label = label)
class MainPanel(wx.Panel):
def __init__(self, parent):
self.__myParent = parent
wx.Panel.__init__(self, self.__myParent, size = (800, 800))
nextButton = wx.Button(self, label = 'Next')
nextButton.Bind(wx.EVT_BUTTON, self.__onNext)
def __onNext(self, event):
self.__myParent.onNextScreen()
class MainFrame(wx.Frame):
def __init__(self):
# Base contsructor.
wx.Frame.__init__(self, None, id = -1, title = 'Testing...', size = (800, 800))
self.__myMainPanel = MainPanel(self)
self.__myMainPanel.Show()
self.__myDatabase = TextPanel(self, 'Loading Data...')
self.__myDatabase.Hide()
self.__myFinalPanel = TextPanel(self, 'Database Loading Complete!')
self.__myFinalPanel.Hide()
def onNextScreen(self):
self.__myMainPanel.Hide()
self.__myDatabase.Show()
self.doDatabaseLoad()
self.__myDatabase.Hide()
self.__myFinalPanel.Show()
def doDatabaseLoad(self):
time.sleep(7) # before, this method would load data into a database...
if __name__ == '__main__':
app = wx.App()
frame = MainFrame()
frame.Show(True)
app.MainLoop()
print 'Exiting...'
Thanks all for your help,
I found an easy solution to this issue.
I first found out that wx.Panel.Update() gets called to repaint the screen when ever the event handler method returns. So, the loading panel seems to look like it needed to be repainted, as the static text box is all grayed out. I then just called self.__myDatabase.Update() after self.__myDatabase.Show().
Here is the new version of onNextScreen(self):
def onNextScreen(self):
self.__myMainPanel.Hide()
self.__myDatabase.Show()
self.__myDatabase.Update() # Fixes the bug...
self.doDatabaseLoad()
self.__myDatabase.Hide()
self.__myFinalPanel.Show()
Also, another way to fix it is to call SetLabel on the static text, but the above solution is better. It just seems that Update was not being called automatically, because it was in the middle of an event...
I need to bind the EVT_CHAR event for a GUI application I am developing using wxPython. I tried the following and I cann understand the beahviour of the code.
import wx
import wx.lib.agw.flatnotebook as fnb
class DemoApp(wx.App):
def __init__(self):
wx.App.__init__(self, redirect=False)
self.mainFrame = DemoFrame()
self.mainFrame.Show()
def OnInit(self):
return True
class DemoFrame(wx.Frame):
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, wx.ID_ANY,
"FlatNotebook Tutorial",
size=(600,400)
)
panel = wx.Panel(self)
button = wx.Button(panel, label="Close", pos=(125, 10), size=(50, 50))
self.Bind(wx.EVT_CHAR, self.character)
def character(self, event):
print "Char keycode : {0}".format(event.GetKeyCode())
if __name__ == "__main__":
app = DemoApp()
app.MainLoop()
The character function never gets called. However, when I comment out the two lines call to the Frame constructor, I character function is called. Adding a panel to the frame seems to interfere with the binding of the frame's EVT_CHAR.
How do I address this problem? Am I doing something wrong in my code?
The problem is that you are catching events that happen to the frame, but the frame is not in focus. The button is. In wxPython, events are sent to the widget in focus. If you add this to the end of your init, it works:
self.SetFocus()
However, if you change the focus to the button, then it will stop working again. See also:
wxpython capture keyboard events in a wx.Frame
http://www.blog.pythonlibrary.org/2009/08/29/wxpython-catching-key-and-char-events/
http://wxpython-users.1045709.n5.nabble.com/Catching-key-events-from-a-panel-and-follow-up-to-stacked-panels-td2360109.html
I appreciate that this question was answered 2 years ago but this issue catches us all out at some point or other.
It is the classic binding to wx.Event or wx.CommandEvent problem.
In this case simply changing the self.Bind(wx.EVT_CHAR, self.character) line to read button.Bind(wx.EVT_CHAR, self.character) will solve the problem, detailed above.
The issue of wx.Event - wx.CommandEvent is covered in full here:
http://wiki.wxpython.org/EventPropagation
and here:
http://wiki.wxpython.org/self.Bind%20vs.%20self.button.Bind
Here's some sample code:
import wx
class MainPanel(wx.Panel):
p1 = None
p2 = None
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
self.frame = parent
#self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
#self.bg = wx.Bitmap("2.jpg")
self.Bind(wx.EVT_MOTION, self.OnMouseMove)
self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))
def OnMouseMove(self, event):
if event.Dragging() and event.LeftIsDown():
self.p2 = event.GetPosition()
self.Refresh()
def OnMouseDown(self, event):
self.p1 = event.GetPosition()
def OnPaint(self, event):
if self.p1 is None or self.p2 is None: return
dc = wx.PaintDC(self)
dc.SetPen(wx.Pen('red', 3, wx.LONG_DASH))
dc.SetBrush(wx.Brush(wx.Color(0, 0, 0), wx.SOLID))
dc.DrawRectangle(self.p1.x, self.p1.y, self.p2.x - self.p1.x, self.p2.y - self.p1.y)
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, size=(600,450))
panel = MainPanel(self)
self.Center()
class Main(wx.App):
def __init__(self, redirect=False, filename=None):
wx.App.__init__(self, redirect, filename)
dlg = MainFrame()
dlg.Show()
if __name__ == "__main__":
app = Main()
app.MainLoop()
The two offending lines are:
#self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
#self.bg = wx.Bitmap("2.jpg")
If you run the code like that, you're able to draw a rectangle on the panel. If you start a new rectangle, the old one disappears, because the panel is refreshing.
However, if you uncomment those two lines, when you draw a rectangle, it stays there. You can have infinite number of rectangles. If I use dc.Clear(), the background disappears and reloading the background makes the application slow and it flickers.
How do I make the panel fully refresh while using a custom background?
By the way, the background image doesn't load with this code, but the behavior is the same.
EDIT: I found a workaround to the flickering caused by using dc.Clear() and reloading the background. Setting double buffering on the panel to true solves the flickering:
self.SetDoubleBuffered(True)
I will use that, but I'll leave the question open in case someone knows the answer to the initial problem.
When using the wx.BG_STYLE_CUSTOM background style it assumes that you will paint (or clear) the entire window in the EVT_PAINT event handler. The easiest way to do that without flicker is to only push pixels to the screen one time per paint event.
Using SetDoubleBuffered does that at the system level, although that has been known to have side-effects in some cases. Another easy way is to use a wx.BufferedPaintDC instead of wx.PaintDC. It will create a bitmap that is the target of all the drawing operations and then at the end the contents of the bitmap will be flushed to the screen.
I want to start playing a .wmv file as soon as it is loaded in wxPython. I wrote a small code for it. The code does not give any error, but it does not show any video as well, but the sound does play in the background. It just shows a gray screen. Following is the code I wrote for my program.
import wx
import wx.media
class TestPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1, style=wx.TAB_TRAVERSAL|wx.CLIP_CHILDREN)
# Create some controls
try:
self.mc = wx.media.MediaCtrl(self, style=wx.SIMPLE_BORDER)
except NotImplementedError:
self.Destroy()
raise
self.mc.Load(r"C:\Documents and Settings\N1002401B\Desktop\test1.wmv")
#self.slider.SetRange(0, self.mc.Length())
#folder, filename = os.path.split("C:\Documents and Settings\N1002401B\Desktop\test1.wmv")
self.Bind(wx.media.EVT_MEDIA_LOADED, self.OnPlay)
def OnPlay(self,evt):
self.mc.Play()
app = wx.App(0)
frame = wx.Frame(None)
panel = TestPanel(frame)
frame.Show()
app.MainLoop()
I am using Python 2.7 and windows XP.
Can anyone please help me on this one. I would be really grateful for your help.