def memory_task(all_bubbles, loaded_bubbles, bubble_image, memory_image, surf): correct = 'No valid answer yet' #positions for bubble display positions = [(-150, 0), (150, 0)] pos_same = random.choice(positions) positions.remove(pos_same) pos_other = positions[0] #load bubble from shown image all_bubbles_same = os.listdir(path_to_fixdur_files + 'stimuli/single_bubble_images/' + bubble_image) same_mem = random.choice(all_bubbles_same) same_mem_loc = [ int(same_mem.split('_', 1)[1].split('_')[0]), int(same_mem.split('_', 1)[1].split('_')[1].split('.')[0]) ] same_mem_loaded = visual.SimpleImageStim(surf, image=path_to_fixdur_files + 'stimuli/single_bubble_images/' + bubble_image + '/' + bubble, pos=pos_same) #bubble from other image bubble_mat = np.load(path_to_fixdur_code + 'all_bubble_mat.npy') other_mem_loc = random.choice(bubble_mat) #make sure it"s from another image while other_mem_loc[0] == bubble_image: other_mem_loc = random.choice(bubble_mat) #load bubble other_mem_loaded = visual.SimpleImageStim( surf, path_to_fixdur_files + 'stimuli/single_bubble_images/' + other_mem_loc[0] + '/' + other_mem_loc[1], pos=pos_other) memory_image.draw(surf) same_mem_loaded.draw(surf) other_mem_loaded.draw(surf) surf.flip() key = event.waitKeys(keyList=['left', 'right']) #if left bubble is correct and left bubble was choosen if (((pos_same == (-150,0)) and (key == ['left'])) or \ #if right bubble is correct and right bubble was choosen ((pos_same == (150,0)) and (key == ['right']))): correct = True else: correct = False if pos_same == (-150, 0): left_bubble = same_mem_loc right_bubble = other_mem_loc if pos_same == (150, 0): left_bubble = other_mem_loc right_bubble = same_mem_loc return [correct, left_bubble, right_bubble]
def loadFilesOld(directory, extension, fileType, win='', whichFiles='*', stimList=[]): """ Load all the pics and sounds""" path = os.getcwd() #set path to current directory if type(extension).__name__ == 'list': fileList = [] for curExtension in extension: fileList.extend( glob.glob( os.path.join(path, directory, whichFiles + curExtension))) else: fileList = glob.glob( os.path.join(path, directory, whichFiles + extension)) fileMatrix = { } #initialize fileMatrix as a dict because it'll be accessed by picture names, cound names, whatver for i in range(len(fileList)): fullPath = fileList[i] fullFileName = os.path.basename(fullPath) stimFile = fullFileName[:len(fullFileName) - 4] #chops off the extension if fileType == "image": try: surface = pygame.image.load( fullPath) #this is just to get heigh/width of the image #stim = visual.PatchStim(win, tex=fullPath) stim = visual.SimpleImageStim(win, image=fullPath) fileMatrix[stimFile] = ((stim, fullFileName, i, surface.get_width(), surface.get_height(), stimFile)) except: #no pygame, so don't store the image dims stim = visual.SimpleImageStim(win, image=fullPath) fileMatrix[stimFile] = ((stim, fullFileName, i, '', '', stimFile)) elif fileType == "sound": soundRef = sound.Sound(fullPath) fileMatrix[stimFile] = ((soundRef)) elif fileType == "winSound": soundRef = highPitch = open(fullPath, "rb").read() fileMatrix[stimFile] = ((soundRef)) #check if stimList and set( fileMatrix.keys()).intersection(stimList) != set(stimList): #print stimList, fileMatrix.keys(),set(stimList).difference(fileMatrix.keys()) popupError( str(set(stimList).difference(fileMatrix.keys())) + " does not exist in " + path + '\\' + directory) return fileMatrix
def loadFiles(self, directory,extension,fileType,win='',whichFiles='*',stimList=[]): """ Load all the pics and sounds""" self.dir = directory self.extension = extension self.fileType = fileType self.wi = win self.whichFiles = whichFiles self.stimList=stimList if isinstance(self.extension,list): fileList = [] for curExtension in self.ext: print self.whichFiles fileList.extend(glob.glob( os.path.join(self.path, self.directory, self.whichFiles+curExtension))) else: fileList = glob.glob(os.path.join(self.path,directory,self.whichFiles+self.extension)) fileMatrix = {} #initialize fileMatrix as a dict because it'll be accessed by picture names, cound names, whatver for num,curFile in enumerate(fileList): fullPath = curFile fullFileName = os.path.basename(fullPath) stimFile = os.path.splitext(fullFileName)[0] if fileType=="image": from psychopy import visual try: surface = pygame.image.load(fullPath) #gets height/width of the image stim = visual.SimpleImageStim(win, image=fullPath) fileMatrix[stimFile] = ((stim,fullFileName,num,surface.get_width(),surface.get_height(),stimFile)) except: #no pygame, so don't store the image dims stim = visual.SimpleImageStim(win, image=fullPath) fileMatrix[stimFile] = ((stim,fullFileName,num,'','',stimFile)) elif fileType=="sound": soundRef = sound.Sound(fullPath) fileMatrix[stimFile] = ((soundRef)) elif fileType=='text': from psychopy import visual import codecs with codecs.open(fullPath, 'r', encoding='utf8') as f: textRef = visual.TextStim(win, text=f.read(), wrapWidth=1.2, alignHoriz='center', alignVert='center', height=0.06) fileMatrix[stimFile] = ((textRef)) #check if stimList and set(fileMatrix.keys()).intersection(stimList) != set(stimList): popupError(str(set(self.stimList).difference(fileMatrix.keys())) + " does not exist in " + self.path+'\\'+directory) return fileMatrix
def __init__(self, win, mouse, imageFileName, thickness=3, lineColor='green', dotColor='blue'): '''Set up the gauge figure ellipse + normal''' # raw stuff self.win = win self.mouse = mouse self.thickness = thickness self.lineColor = lineColor self.dotColor = dotColor self.drawDots = True # image self.image = visual.SimpleImageStim(self.win, image=imageFileName) # line stim self.lines = visual.ShapeStim(self.win, lineColor=self.lineColor, lineWidth=self.thickness, fillColor=None, closeShape=False, opacity=0.75, autoLog=True) # self.points = []
def createStim(self): from psychopy import visual stimuli = {} stimuli['number'] = visual.TextStim( self.win, text='', color=self.textCol, height=0.2) stimuli['mask'] = visual.SimpleImageStim( self.win, image='stim/MaskCircle125.png') stimuli['fb_correct'] = visual.TextStim( self.win, text='+', color='Green', height=0.2, pos=[0.0, -0.2]) stimuli['fb_incorrect'] = visual.TextStim( self.win, text='x', color='Red', height=0.2, pos=[0.0, -0.2]) return stimuli
def prepare(self): im = self._to_pil() x, y = self.to_xy(self.x, self.y) if not self.center: x += im.width // 2 y -= im.height // 2 self._stim = visual.SimpleImageStim(self.win, im, pos=(x, y))
def test_simpleimage(self): win = self.win fileName = os.path.join(utils.TESTS_DATA_PATH, 'testimage.jpg') if not os.path.isfile(fileName): raise IOError('Could not find image file: %s' % os.path.abspath(fileName)) image = visual.SimpleImageStim(win, image=fileName, flipHoriz=True, flipVert=True) image.draw() utils.compareScreenshot('simpleimage1_%s.png' %(self.contextName), win, crit=5.0) # Should be exact replication
def loadFiles(directory, extension, fileType, win, whichFiles='*', stimList=[]): path = os.getcwd() #set path to current directory if isinstance(extension, list): fileList = [] for curExtension in extension: fileList.extend( glob.glob( os.path.join(path, directory, whichFiles + curExtension))) else: fileList = glob.glob( os.path.join(path, directory, whichFiles + extension)) fileMatrix = { } #initialize fileMatrix as a dict because it'll be accessed by picture names, sound names, whatever for num, curFile in enumerate(fileList): fullPath = curFile fullFileName = os.path.basename(fullPath) stimFile = os.path.splitext(fullFileName)[0] if fileType == "image": try: surface = pygame.image.load( fullPath) #gets height/width of the image stim = visual.SimpleImageStim(win, image=fullPath) fileMatrix[stimFile] = ((stim, fullFileName, num, surface.get_width(), surface.get_height(), stimFile)) except: #no pygame, so don't store the image dims stim = visual.SimpleImageStim(win, image=fullPath) fileMatrix[stimFile] = ((stim, fullFileName, num, '', '', stimFile)) elif fileType == "sound": soundRef = sound.Sound(fullPath) fileMatrix[stimFile] = ((soundRef)) #check if stimList and set( fileMatrix.keys()).intersection(stimList) != set(stimList): #print stimList, fileMatrix.keys(),set(stimList).difference(fileMatrix.keys()) popupError( str(set(stimList).difference(fileMatrix.keys())) + " does not exist in " + path + '\\' + directory) return fileMatrix
def doOne(fname, outfname): '''handle a stimulus''' fileName, fileExtension = os.path.splitext(fname) outPts = [] im = visual.SimpleImageStim(myWin, image=fname) lines = visual.ShapeStim( myWin, lineColor='red', lineWidth=3.0, # in pixels fillColor=None, closeShape=False, pos=[0, 0], interpolate=True, opacity=0.5, autoLog=False) # event loop oldpos = (0, 0) while True: if myMouse.getPressed()[0] is 1: newpos = myMouse.getPos() if not np.array_equal(newpos, oldpos): outPts.append(newpos) event.clearEvents() lines.setVertices(list(outPts)) oldpos = newpos for key in event.getKeys(): print key if key in ['escape', 'q']: print(str(outPts)) core.quit() elif key in ['space', 'return']: print(str(outPts)) ofile = open(fileName + outfname, 'wb') writer = csv.writer(ofile, dialect='excel') for row in outPts: writer.writerow(row) ofile.close() return outPts elif key in ['backspace']: print(outPts.pop()) lines.setVertices(list(outPts)) im.draw() lines.draw() myWin.flip()
def test_simpleimage(self): win = self.win if win.useRetina: pytest.skip("Rendering pixel-for-pixel is not identical on retina") fileName = os.path.join(utils.TESTS_DATA_PATH, 'testimage.jpg') if not os.path.isfile(fileName): raise IOError('Could not find image file: %s' % os.path.abspath(fileName)) image = visual.SimpleImageStim(win, image=fileName, flipHoriz=True, flipVert=True) "{}".format(image) #check that str(xxx) is working image.draw() utils.compareScreenshot('simpleimage1_%s.png' %(self.contextName), win, crit=5.0) # Should be exact replication
def show_instruction(): global win instr = visual.SimpleImageStim(win, image='instruction.png', units='', pos=(0.0, 0.0), flipHoriz=False, flipVert=False, name=None, autoLog=None) instrStim = visual.BufferImageStim(win, stim=[instr]) instrStim.draw() win.flip() while True: if len(event.getKeys()) > 0: break event.clearEvents()
def SimGlP(self, path, picType, window=None, Position=[0, 0]): # used to obtain all pictures beginning with a certain path and append them to a list for later use. """Takes the idea that you have images named something akin to "F1.jpg, F2.jpg, F3.jpg..." and runs with it. In path you write the path to the directory with the images, with a \F or whatever at the end. In picType you add '.jpg' for jpegs and so on. The Size and Position are variables that can be altered to suit your purposes, but by default are the natural image size and the center of the screen. This function then fills a list with psychopy ImageStims of all those images, using the psychopy visual.Window given by the window argument. Feel free to alter the window, image function, and so on.""" List = [] # You don't have to make empty lists for this function to fill in the script itself stims = glob.glob( path + '*' + picType) # basically this searches for anything starting with the path and ending in the picType. While it's possible to specify a path as part of this function, it removes the location flexibility. PsychoPyVersion = pkg_resources.get_distribution("psychopy").version if float(PsychoPyVersion[0:4]) >= 1.75: for stim in stims: # for all the files found List.append(visual.SimpleImageStim(window, image=stim, pos=Position)) # add to the list the ImageStim object, meaning it can be drawn and we don't have to do this within any other function. else: for stim in stims: # for all the files found List.append(visual.PatchStim(window, tex=stim, pos=Position)) # add to the list the PatchStim object, meaning it can be drawn and we don't have to do this within any other function. return List
def slideshow(surf, ims): ims = [visual.SimpleImageStim(surf, im.tostring()) for im in ims] i = 0 while True: ims[i].draw() surf.flip() #key = wait_for_key(keylist = [276, 275]) key = event.waitKeys(keyList=['left', 'right']) if key == ['right']: if (i == len(ims) - 1): return else: i += 1 elif (key == ['left'] and i > 0): i -= 1
def _show_calibration_result(self): img = Image.new('RGBA', tuple(self.win.size)) img_draw = ImageDraw.Draw(img) result_img = visual.SimpleImageStim(self.win, img, autoLog=False) img_draw.rectangle(((0, 0), tuple(self.win.size)), fill=(0, 0, 0, 0)) if self.calibration_result.status == tr.CALIBRATION_STATUS_FAILURE: #computeCalibration failed. pass else: if len(self.calibration_result.calibration_points) == 0: pass else: for calibration_point in self.calibration_result.calibration_points: p = calibration_point.position_on_display_area for calibration_sample in calibration_point.calibration_samples: lp = calibration_sample.left_eye.position_on_display_area rp = calibration_sample.right_eye.position_on_display_area if calibration_sample.left_eye.validity == tr.VALIDITY_VALID_AND_USED: img_draw.line(((p[0] * self.win.size[0], p[1] * self.win.size[1]), (lp[0] * self.win.size[0], lp[1] * self.win.size[1])), fill=(0, 255, 0, 255)) if calibration_sample.right_eye.validity == tr.VALIDITY_VALID_AND_USED: img_draw.line(((p[0] * self.win.size[0], p[1] * self.win.size[1]), (rp[0] * self.win.size[0], rp[1] * self.win.size[1])), fill=(255, 0, 0, 255)) img_draw.ellipse(((p[0] * self.win.size[0] - 3, p[1] * self.win.size[1] - 3), (p[0] * self.win.size[0] + 3, p[1] * self.win.size[1] + 3)), outline=(0, 0, 0, 255)) result_img.setImage(img) return result_img
#=============================== # Creation of window and stimuli #=============================== # Open a window win = visual.Window(size=scrsize, color='white', units='pix', fullscr=True) # Create the start message start_message = visual.TextStim(win, text="Press space to start the experiment", color='red', height=20) # Create the bitmap object; its contents can still change bitmap = visual.SimpleImageStim(win, image=os.path.join(impath, imlist[0]+asfx)) trialImgList = [asfx,blank,bsfx,blank]*60 #========================= # Creation of TrialHandler #========================= stim_order = [] for im, ori in zip(imlist, orilist): stim_order.append({'im': im, 'ori': ori}) trials = data.TrialHandler(stim_order, nReps=1, extraInfo=exp_info, method='sequential', originPath=datapath)
Read each item and then mark the appropriate answer. Indicate to what extent you agree with each statement right now. Press any key to continue.''', height=1, alignHoriz="center", color="#000000") imagestart = visual.TextStim( win, text= "You will now view a series of images. Each image will appear for 20 seconds. Try to visualize yourself actually being in each scene.", height=1, color="#000000", alignHoriz="center") players = visual.SimpleImageStim(win, image='images/start.bmp') round_fix = visual.TextStim(win, text="", height=1, color="#000000") fixation = visual.TextStim(win, text="Please wait...", height=2, color="#000000") goodbye = visual.TextStim(win, text="", color="#000000") p1name = visual.TextStim(win, text=player1_name, color="#000000", pos=(-6, 2), height=0.5)
def __init__ (self): positionX = np.linspace(-23.5, 23.5, num=10, endpoint=True, retstep=False) positionY = np.linspace(-14.1, 14.1, num=6, endpoint=True, retstep=False) xys = np.transpose([np.tile(positionX, len(positionY)), np.repeat(positionY, len(positionX))]) self.positions = xys self.counter = 0 self.waitForKeys = True mon = monitors.Monitor('myMonitor1') self.window = visual.Window(size=mon.getSizePix(), color=(1,1,1), colorSpace='rgb', fullscr=True, monitor=mon, units='cm') self.window.mouseVisible = False self.resultData = np.zeros(shape = (360,7),dtype=np.float64) fixationX = visual.Line(win=self.window, lineColor=(-1,-1,-1), lineColorSpace='rgb', start=(-0.5,0), end=(0.5,0),lineWidth = 2.5, interpolate=False) fixationY = visual.Line(win=self.window, lineColor=(-1,-1,-1), lineColorSpace='rgb', start=(0,-0.5), end=(0,0.5),lineWidth = 2.5, interpolate=False) self.fixation = [fixationX, fixationY] self.text1 = visual.TextStim(win=self.window, text='Ist', color=(-1,-1,-1), colorSpace='rgb', height=2, bold=True, wrapWidth=50, pos=(0.0, 2)) self.text3 = visual.TextStim(win=self.window, text='im folgenden Bild enthalten?', color=(-1,-1,-1), colorSpace='rgb', height=2, bold=True, wrapWidth=50, pos=(0.0, -2.0)) imgStart1 = visual.SimpleImageStim(win=self.window, image="..\\img\\auftrag1.png") imgStart2 = visual.SimpleImageStim(win=self.window, image="..\\img\\aufgabe2.png") imgPractice1 = visual.SimpleImageStim(win=self.window, image="..\\img\\training1.png") imgExperiment = visual.SimpleImageStim(win=self.window, image="..\\img\\Versuch.jpg") thankyou = visual.SimpleImageStim(win=self.window, image="..\\img\\danke.jpg") # block slides block1 = visual.SimpleImageStim(win=self.window, image="..\\img\\Block_1.jpg") block2 = visual.SimpleImageStim(win=self.window, image="..\\img\\Block_2.jpg") block3 = visual.SimpleImageStim(win=self.window, image="..\\img\\Block_3.jpg") block4 = visual.SimpleImageStim(win=self.window, image="..\\img\\Block_4.jpg") block5 = visual.SimpleImageStim(win=self.window, image="..\\img\\Block_5.jpg") block6 = visual.SimpleImageStim(win=self.window, image="..\\img\\Block_6.jpg") 'creating the stimulus' self.redCircle = visual.ImageStim(win=self.window, image="..\\img\\shapes_13.jpg", units = "cm", pos=(0,0), size = 3.4, contrast=1.0) self.greenCircle = visual.ImageStim(win=self.window, image="..\\img\\shapes_11.jpg", units = "cm", pos=(0,0), size = 3.4, contrast=1.0) self.redTriangle = visual.ImageStim(win=self.window, image="..\\img\\shapes_15.jpg", units = "cm", pos=(0,0), size = 3.4, ori = -90, contrast=1.0) self.greenTriangle = visual.ImageStim(win=self.window, image="..\\img\\shapes_17.png", units = "cm", pos=(0,0), size = 3.4, contrast=1.0) self.redSquare = visual.ImageStim(win=self.window, image="..\\img\\shapes_03.jpg", units = "cm", pos=(0,0), size = 3.4, contrast=1.0) self.greenSquare = visual.ImageStim(win=self.window, image="..\\img\\shapes_05.jpg", units = "cm", pos=(0,0), size = 3.4, contrast=1.0) self.greenRhombus = visual.ImageStim(win=self.window, image="..\\img\\shapes_07.jpg", units = "cm", pos=(0,0), size = 3.4, contrast=1.0) self.greenSquareOpen = visual.ImageStim(win=self.window, image="..\\img\\shapes_09.jpg", units = "cm", pos=(0,0), size = 3.4, contrast=1.0) self.star4 = visual.ImageStim(win=self.window, image="..\\img\\shapes_25.jpg", units = "cm", pos=(0,0), size = 3.4, contrast=1.0) self.star5 = visual.ImageStim(win=self.window, image="..\\img\\shapes_20.jpg", units = "cm", pos=(0,0), size = 3.4, contrast=1.0) self.instructions = {'start1': imgStart1, 'start2': imgStart2, 'practice1': imgPractice1, 'experiment': imgExperiment, 'danke': thankyou, 'block1': block1, 'block2': block2, 'block3': block3, 'block4': block4, 'block5': block5, 'block6': block6 } '''generating a dict with keys 1 to 60 of all the necessary images''' self.images = {} for x in range(1,17): self.images[x] = self.redCircle x += 1 self.images[x] = self.greenCircle for x in range (18,29): self.images[x] = self.redSquare for x in range (29,40): self.images[x] = self.greenSquare x += 1 self.images[x] = self.greenSquareOpen x += 1 self.images[x] = self.greenRhombus x += 1 self.images[x] = self.redTriangle for x in range (43,59): self.images[x] = self.star4 x += 1 self.images[x] = self.star5 x += 1 self.images[x] = self.greenTriangle '''creating the constellation using the code for six time: constellation = random.sample(xrange(1, 61), 60)''' constellation1 = [7, 43, 46, 16, 27, 5, 31, 36, 44, 52, 22, 25, 59, 24, 17, 48, 8, 32, 40, 20, 29, 21, 57, 15, 26, 13, 10, 35, 53, 2, 51, 30, 33, 38, 47, 34, 3, 55, 4, 6, 50, 23, 28, 12, 54, 1, 9, 60, 18, 37, 42, 39, 11, 19, 14, 41, 45, 58, 56, 49] constellation2 = [29, 9, 1, 4, 45, 3, 35, 16, 13, 22, 57, 25, 24, 37, 19, 26, 60, 32, 59, 36, 2, 18, 46, 58, 14, 48, 49, 44, 12, 39, 38, 40, 56, 8, 51, 28, 47, 43, 50, 34, 41, 21, 55, 31, 33, 17, 53, 42, 30, 15, 23, 11, 7, 52, 20, 54, 10, 6, 27, 5] constellation3 = [57, 19, 53, 47, 13, 55, 14, 52, 29, 39, 9, 1, 25, 38, 18, 56, 49, 31, 28, 15, 3, 5, 4, 54, 58, 41, 27, 2, 44, 59, 35, 60, 24, 16, 40, 23, 43, 34, 32, 20, 17, 37, 6, 26, 33, 45, 51, 11, 50, 46, 30, 8, 36, 22, 48, 12, 21, 7, 42, 10] constellation4 = [13, 27, 32, 49, 2, 57, 35, 60, 11, 25, 19, 5, 59, 24, 34, 6, 54, 21, 3, 51, 52, 23, 18, 31, 42, 45, 9, 10, 15, 38, 16, 53, 47, 8, 22, 37, 4, 40, 44, 17, 58, 7, 29, 46, 12, 20, 39, 26, 50, 56, 14, 1, 43, 33, 36, 30, 41, 55, 48, 28] constellation5 = [51, 27, 15, 48, 59, 20, 9, 19, 53, 13, 43, 39, 37, 58, 38, 45, 47, 40, 31, 17, 18, 26, 30, 8, 32, 4, 55, 54, 56, 25, 14, 50, 1, 12, 28, 16, 10, 44, 52, 24, 3, 34, 6, 5, 42, 35, 46, 36, 57, 7, 23, 11, 21, 22, 60, 2, 41, 49, 29, 33] constellation6 = [20, 60, 35, 54, 26, 7, 4, 29, 30, 59, 34, 37, 42, 1, 46, 48, 9, 31, 21, 36, 32, 45, 5, 33, 53, 14, 22, 11, 55, 23, 18, 28, 52, 2, 25, 41, 51, 47, 43, 27, 10, 57, 6, 40, 50, 49, 19, 39, 56, 13, 8, 12, 16, 3, 17, 38, 15, 24, 44, 58] constellationPrac = [19, 43, 39, 13, 12, 46, 25, 41, 16, 60, 20, 49, 8, 33, 36, 35, 9, 37, 21, 42, 31, 55, 23, 24, 34, 57, 53, 5, 18, 14, 32, 1, 26, 11, 3, 50, 15, 4, 30, 58, 22, 54, 56, 45, 28, 47, 38, 40, 29, 44, 10, 59, 7, 6, 52, 27, 51, 17, 48, 2] '''a dict to access the constellation block wise''' self.constellation = { 1 : constellation1, 2 : constellation2, 3 : constellation3, 4 : constellation4, 5 : constellation5, 6 : constellation6, 7 : constellationPrac }
def newTextureObject(win, image, position=[0, 0]): return visual.SimpleImageStim(win, image=image, units='', pos=position)
precision=10, skipKeys=None, marker='glow', markerExpansion=10, showValue=False, pos=[0, -200], name='Example2') # using a list is handy if you have a lot of items to rate on the same scale, eg personality adjectives or images: imageList = ['beach.jpg', 'face.jpg'] data = [] for image in imageList: x, y = myRatingScale.win.size myItem = visual.SimpleImageStim(win=win, image=image, units='pix', pos=[0, y // 7]) # rate each image on two dimensions for dimension in [ '0=very negative . . . 50=very positive', '0=very boring . . . 50=very energizing' ]: myRatingScale.reset() # reset between repeated uses of the same scale myRatingScale.setDescription(dimension) # reset the instructions event.clearEvents() while myRatingScale.noResponse: myItem.draw() myRatingScale.draw() win.flip() if event.getKeys(['escape']):
scalebg.draw() picq.draw() picscale.draw() win.flip() thepause() #--------------- # instruction slide title1.draw() instr1.draw() picscale.reset() picq.draw() picscale.draw() win.flip() thepause() # pics for trial in range(8): picpath = stimpath + thepictures[trial] thepic = visual.SimpleImageStim(win=win, image=picpath, units='pix', pos=[0, 0]) picloop(thepic) instr2.draw() win.flip() thepause() #-------------- # clean up thequit()
name='Cue', text= " You are now playing \nthe PRISONER'S DILEMMA \n game with your partner", font='Arial', pos=[0, 0], height=0.1, wrapWidth=None, color='white', colorSpace='rgb', opacity=1, autoLog=True) game = visual.SimpleImageStim(win=win, image='Screenshot.png', pos=[0.0, 0.0], units=None, opacity=1.0, name='game', autoLog=True) choose = visual.TextStim(win=win, ori=0, name='choose', text='Do you cooperate or default?', font='Arial', pos=[0, 0], height=0.1, wrapWidth=None, color='white', colorSpace='rgb', opacity=1,
path_to_fixdur_code + 'data/' + str(subject) + '/' + str(subject), 'w') else: subject_file = open( path_to_fixdur_code + 'data/' + str(subject) + '/' + str(subject) + str(START_TRIAL), 'w') #monitor information # set up the window rectXY = (1920, 1080) surf = visual.Window(size=rectXY, fullscr=True, winType='pygame') #surf.setMouseVisible(False) #surf.waitBlanking = False #load images memory_image = visual.SimpleImageStim( surf, image=path_to_fixdur_code + 'images/memory.png') #,pos=(rectXY[0]/2,rectXY[1]/2)) fix_cross = visual.SimpleImageStim(surf, image=path_to_fixdur_code + 'images/fixationcross.png') # set up eyetracker #pylink.openGraphics() openGraphicsEx(EyeLinkCoreGraphicsOpenGL(surf)) rand_filename = ''.join( random.choice(string.ascii_uppercase + string.digits) for x in range(8)) print rand_filename #el = tracker.Tracker(surf,rand_filename+'.EDF') #track = PsychoTracker(surf, rand_filename) #track.set_calibration(13) #el.setup()
def _show_calibration_result(self): global calib_auto_status img = Image.new("RGBA", tuple(self.win.size)) img_draw = ImageDraw.Draw(img) img_draw1 = ImageDraw.Draw(img) result_img = visual.SimpleImageStim(self.win, img, autoLog=False) img_draw.rectangle(((0, 0), tuple(self.win.size)), fill=(0, 0, 0, 0)) r = '0' l = '0' calib_auto_status_l = [] self.calib_auto_status = calib_auto_status_l if self.calibration_result.status == tr.CALIBRATION_STATUS_FAILURE: # computeCalibration failed. pass else: if len(self.calibration_result.calibration_points) == 0: pass else: for calibration_point in self.calibration_result.calibration_points: p = calibration_point.position_on_display_area for calibration_sample in calibration_point.calibration_samples: lp = calibration_sample.left_eye.position_on_display_area rp = calibration_sample.right_eye.position_on_display_area distancel = math.sqrt(((p[0] - lp[0])**2) + ((p[1] - lp[1])**2)) distancer = math.sqrt(((p[0] - lp[0])**2) + ((p[1] - lp[1])**2)) if distancel <= 1.36: if distancer <= 1.36: calib_auto_status_l.append('1') r = '1' print('dl:', distancel) print('dr:', distancer) print('r:', r) print('p:', p[0]) print('lp:', lp[0]) print('rp:', rp[0]) print('status:', calib_auto_status_l) else: calib_auto_status_l.append('0') r = '0' print('r:', r) print('status:', calib_auto_status_l) #elif distancel > 0.04: # r='0' #3 l='0' # print('r:', r) # print('l:', l) # print('dl:',distancel) # print('dr:',distancer) # print('r:', r) # print('p:',p[0]) # print('lp:',lp[0]) # print('rp:',rp[0]) if (calibration_sample.left_eye.validity == tr.VALIDITY_VALID_AND_USED): img_draw.line( ( (p[0] * self.win.size[0], p[1] * self.win.size[1]), ( lp[0] * self.win.size[0], lp[1] * self.win.size[1], ), ), fill=(0, 255, 0, 255), ) if (calibration_sample.right_eye.validity == tr.VALIDITY_VALID_AND_USED): img_draw.line( ( (p[0] * self.win.size[0], p[1] * self.win.size[1]), ( rp[0] * self.win.size[0], rp[1] * self.win.size[1], ), ), fill=(255, 0, 0, 255), ) img_draw.ellipse( ( (p[0] * self.win.size[0] - 3, p[1] * self.win.size[1] - 3), (p[0] * self.win.size[0] + 3, p[1] * self.win.size[1] + 3), ), outline=(0, 0, 0, 255), ) #changing size of the accuracy circle #cir = visual.Circle(self.win,radius=1.136,lineColor="white") #psychopy.visual.Polygon(win, edges=3, radius=0.5, **kwargs) img_draw1.ellipse( ( (p[0] * self.win.size[0] - 76.8, p[1] * self.win.size[1] - 76.8), (p[0] * self.win.size[0] + 76.8, p[1] * self.win.size[1] + 76.8), ), outline=(255, 255, 255, 255), ) #cir.draw() result_img.setImage(img) return result_img
situationStim = visual.TextStim(win, text='', height=1.4, pos=(0, 2), alignHoriz='center', wrapWidth=15) thinkStim = visual.TextStim(win, text='Think of a situation', pos=(0, -2)) restStim = visual.TextStim(win, text='REST', height=2.5) # instrcution screen instruction_image = visual.SimpleImageStim(win, image="buttonpad.png", pos=(-1, -3.5)) instruction_text = visual.TextStim( win, height=1.3, color="#FFFFFF", text="Use the buttons to indicate how important each statement is to you", pos=(0, +5)) anchor1 = visual.TextStim(win, text='Not very\nimportant', pos=(-8, -6)) anchor4 = visual.TextStim(win, text='Very\nimportant', pos=(8, -6)) ratingStim = []
conditionBG = visual.Rect(win, width=16, height=2, pos=(0, 5)) stem = visual.TextStim(win, text="People should", pos=(-5.5, 2.5), height=1.3) word = visual.TextStim(win, text="kind", pos=(0, -0.5), height=1.8, wrapWidth=30) resp1 = visual.TextStim(win, text="yes", pos=(-4, -4)) resp2 = visual.TextStim(win, text="no", pos=(4, -4)) resp3 = visual.TextStim(win, text="Press for each reason", pos=(0, -4)) # instrcution screen instruction_image = visual.SimpleImageStim(win, image="img/instruct1.png", pos=(-2, 0)) instruction_text = visual.TextStim( win, height=1.3, color="#000000", text= "In the AGREE condition use buttons 1 and 2 to indicate whether you agree or disagree ", pos=(0, +5)) # ------------- timer = core.Clock() current_run = 1 ######################## # SHOW READY SCREEN #
IMSIZE = 100 QUITKEY = 'escape' win = visual.Window(WINSIZE, units='pix', allowGUI=False, color=BACKGROUND, monitor='monitor1') text_item = visual.TextStim(win, color=FOREGROUND, height=50, wrapWidth=1000) prompt = visual.TextStim(win, color=BACKGROUND, height=20, wrapWidth=100, pos=[0, 60]) fixation = visual.SimpleImageStim(win, image='images/island.png', pos=[0, 0]) object_im = visual.SimpleImageStim(win, image='images/island.png') study_area = visual.Circle(win, radius=500, edges=64, fillColor=CIRCCOL, lineColor=CIRCCOL) object_list_main = [ each for each in os.listdir('images/') if each.endswith('.png') and each != 'island.png' and not each.startswith(".") ] object_list = [object_list_main[i] for i in range(108)] object_list_prac = [object_list_main[i] for i in range(108, 108 + 9, 1)] conf_scale = visual.RatingScale(win,
""" from __future__ import division from __future__ import print_function from builtins import str from builtins import range from psychopy import visual, event, core # need a window and clock: win = visual.Window(fullscr=False, monitor='testMonitor') clock = core.Clock() # first define a list of various slow, static stim imageList = ['face.jpg', 'beach.jpg'] imageStim = visual.SimpleImageStim(win, imageList[0]) imageStim2 = visual.SimpleImageStim(win, imageList[1], pos=(.300, .20)) wordStim = visual.TextStim( win, text= 'Press < escape > to quit.\n\nThere should be no change after 3 seconds.\n\n' + 'This is a text stim that is kinda verbose and long, so if it ' + 'were actually really long it would take a while to render completely.', pos=(0, -.2)) stimlist = [imageStim, imageStim2, wordStim] # Get and save a "screen shot" of everything in stimlist: rect = (-1, 1, 1, -1) t0 = clock.getTime() screenshot = visual.BufferImageStim(win, stim=stimlist, rect=rect) # rect is the screen rectangle to grab, (-1, 1, 1, -1) is whole-screen
Unfortunately it is slower to draw than PatchStim and can lead to dropped frames. (to test this on your system try commenting out the beach.draw() command) """ #create a window to draw in myWin = visual.Window((800, 800), monitor='testMonitor', allowGUI=False, color=(-1, -1, -1)) myWin._haveShaders = False #INITIALISE SOME STIMULI beach = visual.SimpleImageStim(myWin, 'beach.jpg', flipHoriz=True, pos=(0, 1.50), units='deg') faceRGB = visual.PatchStim( myWin, tex='face.jpg', mask=None, pos=(50, -20), size=None, #will be the size of the original image in pixels units='pix', interpolate=True, autoLog=False) #this stim changes too much for autologging to be useful print "original image size:", faceRGB.origSize faceALPHA = visual.PatchStim( myWin, pos=(-0.7, -0.2),
color='black', height=.05) midText = visual.TextStim(win, text='Middle value!', color='black', height=.05) rating = ratingScale.getRating() history = ratingScale.getHistory() ratingText = visual.TextStim(win, text=print(rating), color='black', height=.05) hisText = visual.TextStim(win, text=history, color='black', height=.05) # make your loop for image in imageList: x, y = ratingScale.win.size text = visual.SimpleImageStim(win=win, image=image, units='pix', pos=[0, y // 7]) ratingScale.reset() event.clearEvents() while ratingScale.noResponse: text.draw() ratingScale.draw() win.flip() if event.getKeys(['escape']): core.quit() data.append([ratingScale.getRating()]) alldata.append([image, ratingScale.getRating(), ratingScale.getRT()]) win.flip() if data[-1][0] == 'cutest': bigText.draw() elif data[-1][0] == 'cute':
from psychopy import visual, event, core import os # need a win, as always: myWin = visual.Window(fullscr=False, monitor='testMonitor') # first compose your screen-shot: draw as many slow, static "still-life" stim # as you want to the back buffer myWin.clearBuffer() # clear the back buffer for drawing # find a couple images in the demo directory, and display imageList = [ f for f in os.listdir('.') if len(f) > 4 and f[-4:] in ['.jpg', '.png'] ] imageList = imageList[:2] imageStim = visual.SimpleImageStim(myWin, imageList[0]) imageStim.draw() imageStim2 = visual.SimpleImageStim(myWin, imageList[1], pos=(300, 20)) imageStim2.draw() wordStim = visual.TextStim( myWin, text='This is a text stim that is kinda verbose and long, so if it ' + 'were actually really long it would take a while to render completely.', pos=(0, -.5)) wordStim.draw() rect = [-1, 1, 1, -1] # rect is what rectangle to grab, here whole-screen (same as default). # rect is a list of the edges: Left Top Right Bottom, norm units; try [-.5,.5,.5,-.5] # No need to be symmetrical, but it works better for the demo. # NB. If you change the rect and there was flickering on screen during the demo,