Previous topic

TextStim

Next topic

psychopy.visual.windowframepack - Pack multiple monochrome images into RGB frame

This Page

Quick links

Window

class psychopy.visual.Window(size=(800, 600), pos=None, color=(0, 0, 0), colorSpace='rgb', rgb=None, dkl=None, lms=None, fullscr=None, allowGUI=None, monitor=None, bitsMode=None, winType=None, units=None, gamma=None, blendMode='avg', screen=0, viewScale=None, viewPos=None, viewOri=0.0, waitBlanking=True, allowStencil=False, multiSample=False, numSamples=2, stereo=False, name='window1', checkTiming=True, useFBO=False, useRetina=False, autoLog=True)

Used to set up a context in which to draw objects, using either pyglet or pygame

The pyglet backend allows multiple windows to be created, allows the user to specify which screen to use (if more than one is available, duh!) and allows movies to be rendered.

Pygame may still work for you but it’s officially deprecated in this project (we won’t be fixing pygame-specific bugs).

These attributes can only be set at initialization. See further down for a list of attributes which can be changed after initialization of the Window, e.g. color, colorSpace, gamma etc.

Parameters:
size
: (800,600)

Size of the window in pixels (X,Y)

pos
: None or (x,y)

Location of the window on the screen

color
: [0,0,0]

Color of background as [r,g,b] list or single value. Each gun can take values between -1 and 1

fullscr
: None, True or False

Better timing can be achieved in full-screen mode

allowGUI
: None, True or False (if None prefs are used)

If set to False, window will be drawn with no frame and no buttons to close etc...

winType
: None, ‘pyglet’, ‘pygame’

If None then PsychoPy will revert to user/site preferences

monitor
: None, string or a ~psychopy.monitors.Monitor object

The monitor to be used during the experiment

units
: None, ‘height’ (of the window), ‘norm’ (normalised),

‘deg’, ‘cm’, ‘pix’ Defines the default units of stimuli drawn in the window (can be overridden by each stimulus) See Units for the window and stimuli for explanation of options.

screen
: 0, 1 (or higher if you have many screens)

Specifies the physical screen that stimuli will appear on (pyglet winType only)

viewScale
: None or [x,y]

Can be used to apply a custom scaling to the current units of the Window.

viewPos
: None, or [x,y]

If not None, redefines the origin within the window, in the ref:units of the window. Values outside the borders will be clamped to lie on the border.

viewOri
: 0 or any numeric value

A single value determining the orientation of the view in degs

waitBlanking
: None, True or False.

After a call to flip() should we wait for the blank before the script continues

bitsMode :

DEPRECATED in 1.80.02. Use BitsSharp class from pycrsltd instead.

checkTiming: True of False

Whether to calculate frame duration on initialization. Estimated duration is saved in [Window].monitorFramePeriod.

allowStencil
: True or False

When set to True, this allows operations that use the OpenGL stencil buffer (notably, allowing the class:~psychopy.visual.Aperture to be used).

multiSample
: True or False

If True and your graphics driver supports multisample buffers, multiple color samples will be taken per-pixel, providing an anti-aliased image through spatial filtering. (Cannot be changed after opening a window, pyglet only)

numSamples
: 2 or integer >2

A single value specifying the number of samples per pixel if multisample is enabled. The higher the number, the better the image quality, but can delay frame flipping. (The largest number of samples is determined by GL_MAX_SAMPLES, usually 16 or 32 on newer hardware, will crash if number is invalid)

stereo
: True or False

If True and your graphics card supports quad buffers then this will be enabled. You can switch between left and right-eye scenes for drawing operations using setBuffer()

useRetina
: True or False

Try to use the full resolution of the Retina display (only on certain Macs). By default the display’s reduced resolution will be used. NB when you use Retina display the initial win size request will be in the larger pixels but subsequent use of units=’pix’ should refer to the tiny Retina pixels. Window.size will give the actual size of the screen in Retina pixels

note:Preferences. Some parameters (e.g. units) can now be given default values in the user/site preferences and these will be used if None is given here. If you do specify a value here it will take precedence over preferences.
blendMode
callOnFlip(function, *args, **kwargs)

Call a function immediately after the next .flip() command.

The first argument should be the function to call, the following args should be used exactly as you would for your normal call to the function (can use ordered arguments or keyword arguments as normal).

e.g. If you have a function that you would normally call like this:

pingMyDevice(portToPing, channel=2, level=0)

then you could call callOnFlip() to have the function call synchronized with the frame flip like this:

win.callOnFlip(pingMyDevice, portToPing, channel=2, level=0)
clearBuffer()

Clear the back buffer (to which you are currently drawing) without flipping the window. Useful if you want to generate movie sequences from the back buffer without actually taking the time to flip the window.

close()

Close the window (and reset the Bits++ if necess).

color

Set the color of the window.

NB This command sets the color that the blank screen will have on the next clear operation. As a result it effectively takes TWO flip() operations to become visible (the first uses the color to create the new screen, the second presents that screen to the viewer). For this reason, if you want to changed background color of the window “on the fly”, it might be a better idea to draw a visual.Rect that fills the whole window with the desired Rect.fillColor attribute. That’ll show up on first flip.

See other stimuli (e.g. GratingStim.color) for more info on the color attribute which essentially works the same on all PsychoPy stimuli.

See Color spaces for further information about the ways to specify colors and their various implications.

colorSpace

string. (Documentation for colorSpace is in the stimuli.)

e.g. GratingStim.colorSpace.

Usually used in conjunction with color like this:

win.colorSpace = 'rgb255'  # changes colorSpace but not
                           # the value of win.color
win.color = [0, 0, 255]    # clear blue in rgb255

See Color spaces for further information about the ways to specify colors and their various implications.

classmethod dispatchAllWindowEvents()

Dispatches events for all pyglet windows. Used by iohub 2.0 psychopy kb event integration.

flip(clearBuffer=True)

Flip the front and back buffers after drawing everything for your frame. (This replaces the win.update() method, better reflecting what is happening underneath).

win.flip(clearBuffer=True) # results in a clear screen after flipping win.flip(clearBuffer=False) # the screen is not cleared (so represent

# the previous screen)
fps()

Report the frames per second since the last call to this function (or since the window was created if this is first call)

gamma

Set the monitor gamma for linearization

(don’t use this if using a Bits++ or Bits#) Overrides monitor settings.

gammaRamp
getActualFrameRate(nIdentical=10, nMaxFrames=100, nWarmUpFrames=10, threshold=1)

Measures the actual fps for the screen.

This is done by waiting (for a max of nMaxFrames) until [nIdentical] frames in a row have identical frame times (std dev below [threshold] ms).

If there is no such sequence of identical frames a warning is logged and None will be returned.

Parameters:
nIdentical:

the number of consecutive frames that will be evaluated. Higher –> greater precision. Lower –> faster.

nMaxFrames:

the maximum number of frames to wait for a matching set of nIdentical

nWarmUpFrames:

the number of frames to display before starting the test (this is in place to allow the system to settle after opening the Window for the first time.

threshold:

the threshold for the std deviation (in ms) before the set are considered a match

getMovieFrame(buffer='front')

Capture the current Window as an image.

Saves to stack for saveMovieFrames(). As of v1.81.00 this also returns the frame as a PIL image

This can be done at any time (usually after a .flip() command).

Frames are stored in memory until a .saveMovieFrames(filename) command is issued. You can issue getMovieFrame() as often as you like and then save them all in one go when finished.

The back buffer will return the frame that hasn’t yet been ‘flipped’ to be visible on screen but has the advantage that the mouse and any other overlapping windows won’t get in the way.

The default front buffer is to be called immediately after a win.flip() and gives a complete copy of the screen at the window’s coordinates.

getMsPerFrame(nFrames=60, showVisual=False, msg='', msDelay=0.0)

Assesses the monitor refresh rate (average, median, SD) under current conditions, over at least 60 frames.

Records time for each refresh (frame) for n frames (at least 60), while displaying an optional visual. The visual is just eye-candy to show that something is happening when assessing many frames. You can also give it text to display instead of a visual, e.g., msg=’(testing refresh rate...)’; setting msg implies showVisual == False.

To simulate refresh rate under cpu load, you can specify a time to wait within the loop prior to doing the win.flip(). If 0 < msDelay < 100, wait for that long in ms.

Returns timing stats (in ms) of:

  • average time per frame, for all frames
  • standard deviation of all frames
  • median, as the average of 12 frame times around the median (~monitor refresh rate)
Author:
  • 2010 written by Jeremy Gray
logOnFlip(msg, level, obj=None)

Send a log message that should be time-stamped at the next .flip() command.

Parameters:
  • msg: the message to be logged
  • level: the level of importance for the message
  • obj (optional): the python object that might be associated with this message if desired
mouseVisible

Sets the visibility of the mouse cursor.

If Window was initialized with noGUI=True then the mouse is initially set to invisible, otherwise it will initially be visible.

Usage:

``win.mouseVisible = False``
``win.mouseVisible = True``
recordFrameIntervals

To provide accurate measures of frame intervals, to determine whether frames are being dropped. The intervals are the times between calls to .flip(). Set to True only during the time-critical parts of the script. Set this to False while the screen is not being updated, i.e., during any slow, non-frame-time-critical sections of your code, including inter-trial-intervals, event.waitkeys(), core.wait(), or image.setImage().

see also:
Window.saveFrameIntervals()
saveFrameIntervals(fileName=None, clear=True)

Save recorded screen frame intervals to disk, as comma-separated values.

Parameters:
fileName
: None or the filename (including path if necessary) in
which to store the data. If None then ‘lastFrameIntervals.log’ will be used.
saveMovieFrames(fileName, codec='libx264', fps=30, clearFrames=True)

Writes any captured frames to disk.

Will write any format that is understood by PIL (tif, jpg, png, ...)

Parameters:
filename: name of file, including path (required)

The extension at the end of the file determines the type of file(s) created. If an image type (e.g. .png) is given, then multiple static frames are created. If it is .gif then an animated GIF image is created (although you will get higher quality GIF by saving PNG files and then combining them in dedicated image manipulation software, such as GIMP). On Windows and Linux .mpeg files can be created if pymedia is installed. On OS X .mov files can be created if the pyobjc-frameworks-QTKit is installed.

Unfortunately the libs used for movie generation can be flaky and poor quality. As for animated GIFs, better results can be achieved by saving as individual .png frames and then combining them into a movie using software like ffmpeg.

codec: the codec to be used by moviepy for mp4/mpg/mov files.

If None then the default will depend on file extension. Can be one of ‘libx264’,’mpeg4’ for mp4/mov files. Can be ‘rawvideo’,’png’ for avi files (not recommended). Can be ‘libvorbis’ for ogv files.

fps: the frame rate to be used throughout the movie

only for quicktime (.mov) movies

clearFrames: set this to False if you want the frames to be kept

for additional calls to saveMovieFrames

Examples:

# writes a series of static frames as frame001.tif,
# frame002.tif etc...
myWin.saveMovieFrames('frame.tif')

#as of PsychoPy 1.84.1 the following are written with moviepy
myWin.saveMovieFrames('stimuli.mp4') # codec = 'libx264' or 'mpeg4'
myWin.saveMovieFrames('stimuli.mov')
myWin.saveMovieFrames('stimuli.gif')
setBlendMode(blendMode, log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.

setBuffer(buffer, clear=True)

Choose which buffer to draw to (‘left’ or ‘right’).

Requires the Window to be initialised with stereo=True and requires a graphics card that supports quad buffering (e,g nVidia Quadro series)

PsychoPy always draws to the back buffers, so ‘left’ will use GL_BACK_LEFT This then needs to be flipped once both eye’s buffers have been rendered.

Typical usage:

win = visual.Window(...., stereo=True)
while True:
    # clear may not actually be needed
    win.setBuffer('left', clear=True)
    # do drawing for left eye
    win.setBuffer('right', clear=True)
    # do drawing for right eye
    win.flip()
setColor(color, colorSpace=None, operation='', log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you want to set color and colorSpace simultaneously. See Window.color for documentation on colors.

setGamma(gamma, log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.

setMouseVisible(visibility, log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.

setRGB(newRGB)

Deprecated: As of v1.61.00 please use setColor() instead

setRecordFrameIntervals(value=True, log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.

setScale(units, font='dummyFont', prevScale=(1.0, 1.0))

DEPRECATED: this method used to be used to switch between units for stimulus drawing but this is now handled by the stimuli themselves and the window should aways be left in units of ‘pix’

setUnits(value, log=True)
setViewPos(value, log=True)
units

None, ‘height’ (of the window), ‘norm’, ‘deg’, ‘cm’, ‘pix’ Defines the default units of stimuli initialized in the window. I.e. if you change units, already initialized stimuli won’t change their units.

Can be overridden by each stimulus, if units is specified on initialization. See Units for the window and stimuli for explanation of options.

viewPos

The origin of the window onto which stimulus-objects are drawn.

The value should be given in the units defined for the window. NB: Never change a single component (x or y) of the origin, instead replace the viewPos-attribute in one shot, e.g.:

win.viewPos = [new_xval, new_yval] # This is the way to do it win.viewPos[0] = new_xval # DO NOT DO THIS! Errors will result.
waitBlanking

None, True or False. After a call to flip() should we wait for the blank before the script continues