北大心理學(xué)系.Psychtoolbox2_第1頁
北大心理學(xué)系.Psychtoolbox2_第2頁
北大心理學(xué)系.Psychtoolbox2_第3頁
北大心理學(xué)系.Psychtoolbox2_第4頁
北大心理學(xué)系.Psychtoolbox2_第5頁
已閱讀5頁,還剩185頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

PsychtooboxLihanChen2015.4.28MATLAB圖像刺激

圖像處理圖像基礎(chǔ)圖像的變換與操縱計算生成圖像圖像基礎(chǔ)像素、顏色、索引圖像圖像基礎(chǔ)——像素數(shù)字圖像離散的坐標(biāo):像素離散的強(qiáng)度:0~255(黑~白)圖像基礎(chǔ)——顏色RGB顏色系統(tǒng)每個像素的紅、綠、藍(lán)均由uint8表示(0~255)alpha通道:透明度24位/32位真彩色imtool('photo.jpg');用MATLAB存取并顯示圖片讀取并顯示圖片im=imread('tmp.png');size(im)imshow(im)寫入圖片imwrite(im,'tmp.jpg');a=[ones(400,40),zeros(400,40)];%先生成一根白條和一根黑條a1=repmat(a,[1,5]);%將這個組合復(fù)制5遍a2=xor(a1,a1’);%將這個黑白條紋與自己的轉(zhuǎn)置做異或邏輯運(yùn)算imshow(a2)%棋盤格就生成了實例:紅藍(lán)3D與雙眼競爭im1=imread('Koala.jpg');im2=imread('Penguins.jpg');%用第二幅圖替代第一幅圖的紅色通道im1(:,:,1)=im2(:,:,1);%把綠色通道清零im1(:,:,2)=0;imshow(im1)image與colormapimage函數(shù)是MATLAB最基本的圖像顯示函數(shù),可以繪制索引圖像,即每個像素的值對應(yīng)顏色查找表中的索引colormap:定義圖像顯示用的顏色查找表imagesc將數(shù)據(jù)scale后繪制成圖(例如繪制相關(guān)矩陣)image與imshowImshow僅用于顯示由RGB或灰度值定義的圖像(image也可以)無論是哪個函數(shù),若圖像是以uint8表示的,則取值范圍為0~255,若以double表示,則取值范圍是0~1將face.jpg與house.jpg融合成一張圖片,face占用紅色通道,house占用綠色通道,藍(lán)色通道取值0.由于兩張圖片不一樣大,最后結(jié)果保留兩張圖片重疊部分即可,如示例mix.jpg(imread讀出的數(shù)據(jù)是uint8,取值范圍是0-255,imshow圖片的取值范圍是0-1,中間需要除以255這個系數(shù))clearallface=imread('face.jpg');house=imread('house.jpg');mix(:,:,1)=face(1:680,1:550,1);mix(:,:,2)=house(1:680,221:770,2);mix(:,:,3)=0;imshow(mix);image繪制數(shù)據(jù)imagesc&colormap繪制相關(guān)矩陣a=rand(10);fori=2:10a(:,i)=a(:,i-1)+rand(10,1)*0.5;endimagesc(corr(a))

colorbarcolormapautumnPsychtoolbox-1-listing-lst4.mdata.mat中保存了一組虛擬的fMRI數(shù)據(jù),數(shù)據(jù)里記錄了V1,V2,V3,V4,V5,ips6個腦區(qū)100個時間點的值,請畫出其6x6的相關(guān)矩陣。loaddata.matfdata=[V1,V2,V3,V4,V5,ips];imagesc(corr(fdata))馬赫帶效應(yīng)clearall%清除變量,MEX等,如果有需要的變量還不想清除,需要小心closeall%關(guān)閉各種figure窗口img=1:10;%圖片的值,即是選擇colormap第1-10的值figure(1)%打開figure編號為1的窗口paintpots=ones(10,3);%自己創(chuàng)建的一個顏色查找表colormap(paintpots)%將定義好的對應(yīng)關(guān)系輸入系統(tǒng)image(img);%呈現(xiàn)圖片axisoff;%取消在這個任務(wù)中沒有意義的軸fori=1:10paintpots(i,:)=(i/10);%令查找表的第i位的值為i/10,即是最大亮度的i/10倍colormap(paintpots);%將更新的查找表輸入系統(tǒng)pause%等待按鍵,注意看figure中圖片的變化endPsychtoolbox-1-listing-lst3.mclearallcloseallcolormap(gray(256))%將顏色查找表設(shè)置為灰度圖img=reshape(1:256,16,16);image(img);axissquare%將長寬設(shè)置為等長axisoffpausefori=1:200paintpots=rand(256,3);%將顏色查找表設(shè)為隨機(jī),圖片的像素顏色也變成隨機(jī)colormap(paintpots);drawnow%立刻呈現(xiàn)end圖像的變換與處理調(diào)整曲線、窗口化像素亮度的變換操作(PS中的“曲線”)實例:去除掃描時背面透過來的影im=imread('book-000123.png');g=rgb2gray(im);d=double(g);y=uint8(d*1.7-85);imshow(y);imwrite(y,'out.png');Psychtoolbox-1-listing-lst5.m圖像的“窗口”操縱每個像素的亮度:乘以一個系數(shù)生成高斯窗口

窗口化圖像imagesc(GaWindow)tmp=double(im).*GaWindow;Windowed=uint8(tmp);imshow(Windowed)Psychtoolbox-1-listing-lst6.m先生成一個200x200的高斯濾波器,sigma=50,讀取Simpson.jpg,使得二維高斯覆蓋在圖像上,高斯覆蓋范圍外值為0,(如3.jpg)。并且將這個過程做成動態(tài)。通過鼠標(biāo)控制高斯覆蓋的位置,刷新的頻率定為25Hz(既每次呈現(xiàn)一幀圖像要pause0.04s),點擊鼠標(biāo)右鍵退出循環(huán)。clearallcdata=imread('Simpson.jpg');[y,x]=size(cdata);[X,Y]=meshgrid(1:x,1:y);while1

[x0,y0,button]=GetMouse;ifbutton(3)~=0closeallbreakendga=exp((-1/2/50^2)*((X-x0).^2+(Y-y0).^2));%ga=ga./max(max(ga));tmp=double(cdata).*ga;imshow(tmp/255)pause(0.04)end鄰居處理高斯模糊、邊緣檢測空間濾波定義一個矩陣(稱為濾波器filter)將該矩陣覆蓋在每個像素點上對所有被覆蓋的點將原圖像矩陣和該矩陣的對應(yīng)點相乘求和變成新圖像的點由鄰居決定新的像素點的強(qiáng)度

我們對下幅圖片用3x3的平均濾波,即濾波的算子是一個3x3的平均矩陣。設(shè)原矩陣名為x(圖),x(3,3)的值為74,則經(jīng)過平均濾波之后,這個點的值變?yōu)椋?0+65+1+102+74+54+58+98+50)/9=58。濾波的過程就是對所有點都做這個計算,得到一個新的值。

Psychtoolbox-1-listing-lst7.m高斯模糊改變窗口大小,令x=y=10,stdev=5,生成一個“高斯窗口”讓窗口矩陣的和等于1

GaFilter=GaWindow/sum(sum(GaWindow));用imfilter或filter2或conv2對原圖進(jìn)行濾波 imf=imfilter(im,GaFilter);

imshow(imf)高斯模糊的圖片邊緣檢測原始圖像grayedge(gray)imfilter(gray,fspecial('sobel'))更多的濾波器用fspecial生成二維的特殊濾波器average簡單平均gaussian高斯濾波motion模擬攝像機(jī)抖動sobel檢測邊緣算子docfspecial(1)將face進(jìn)行高斯濾波,高斯算子的邊長是100個pixel,sigma為30。clearallface=imread('face.jpg');op=fspecial('Gaussian',100,30);filface=imfilter(face,op);imshow(filface);

(2)對house進(jìn)行邊緣檢測。clearallhouse=imread('house.jpg');ghouse=rgb2gray(house);imshow(edge(ghouse,'canny'))

(3)制作一個200x200豎直朝向順時針偏轉(zhuǎn)15度的gabor,其他參數(shù)可自己定,并解釋各個參數(shù)的含義。

clearall[X,Y]=meshgrid(1:200,1:200);grating=sin((tan(75/180*pi)*X+Y)/25);%(tan(75/180*pi)表示豎直朝向順時偏轉(zhuǎn)15度,%gabor一個周期是25*2*pi/sqrt(tan(75/180*pi)^2+1)個pixel,%(分母是為了標(biāo)準(zhǔn)化)grating=(grating+1)/2;%imshow(grating);op=fspecial('Gaussian',200,50);%高斯算子的邊長是200個pixel,sigma為50個pixelop=op/max(max(op));gabor=op.*grating;imshow(gabor)計算生成圖像正弦光柵,Gabor

Patch,…生成正弦光柵[X,Y]=meshgrid(1:50,1:100);imshow(sin(X))imshow(sin(X+Y))imshow(sin((X+Y)/2))imshow(sin((X+2*Y)/2))imshow(0.5+0.5*sin((3*X+4*Y)/6))Psychtoolbox-1-listing-lst8.m生成Gabor%先生成正弦光柵[X,Y]=meshgrid(-50:50,-50:50);im=sin((X+2*Y)/3);imshow(im)%生成窗口“蓋住”光柵Ga=exp(-((X/20).^2)-((Y/20).^2));imshow(Ga.*im)

生成棋盤格clearallcloseall[x,y]=meshgrid(1:400,1:400);%制作坐標(biāo)網(wǎng)格x1=sin(x/10);%值域為[-1,1];y1=sin(y/10);c=x1.*y1;%負(fù)負(fù)得正pic=c>0;

%最后邏輯判斷,得到棋盤格imshow(pic)

Psychtoolbox函數(shù)介紹(圖像刺激的實現(xiàn))

SCREEN函數(shù)與視覺刺激被試眼睛到屏幕的距離為d,刺激的長度是l,那么視角就是θ,有tan(θ)=l/d,寫成matlab語句就是tand(θ)=l/d,則θ=atand(l/d)deg2pix.m如果屏幕的分辨率是axb,屏幕寬度是w,則pixel數(shù)=tand(θ)*d*a/w假設(shè)屏幕的分辨率為1024x768,我們測得屏幕的寬為40cm,可以得出每cm的長度中有1024/40=25.6個pixel。實際報告刺激大小的時候往往用的是視角θ,而我們操作matlab用的pixel的數(shù)目。如果已知θ求pixel數(shù),則有pixel數(shù)=lx25.6=tand(θ)*d*25.6視角掃頻Supportformultipledisplaysmyscreens=Screen(‘Screens’);Windows:0=“Virtualdisplay”,spanningthemaindisplayanditsrightneighbour.1=Realmaindisplay,2=Realdisplay2.StereodisplaysupportforeasybinocularstimulationScreen(‘OpenWindow’,…,stereoMode);Demos:StereoDemo,ImagingStereoDemoOnecommandinyourstimulusdrawinglooptoswitchbetweendrawingofleft-(bufferid=0)andright-eye(bufferid=1)view:

Screen(‘SelectStereoDrawBuffer’,myWindow,bufferid)Psychtoolbox-2StereoDemo.mStereodisplayfordual-displaysetups:SlightlydifferentapproachonWindowsvs.MacOS/X:Windows:%Openonscreen0,withstereomode4:win=Screen('OpenWindow',0,....,4);MacOS/X:

%Openleft-eyewindowfirston'lefteyedisplay',withstereomode10:win=Screen('OpenWindow',lefteyedisplay,....,10);

%Openright-eyewindow'righteyedisplay',withstereomode10.%Don'tcareaboutwindowhandle,thiswindowisjustapassive%receiver:Screen('OpenWindow',righteyedisplay,....,10);Use'win'windowhandleforallfurthercommands...Demos:StereoDemo,ImagingStereoDemoPTB-3Doublebuffereddrawingmodel-ConceptScreen:StimulusonsettimestampsScreen(‘Flip’)-Example1:Fix->Prime->TargetPsychtoolbox2-prime.mScreen(‘Flip’)-Example1:FixPrimeTarget1%Drawfixationspottobackbuffer:winRect=Screen('Rect',win);slack=Screen('GetFlipInterval',win)/2;Screen('FillOval',win,255,CenterRectInRect([002020],winRect));2.%Showfixationspotonnextretrace,takeonsettimestamp:tfixation_onset=Screen('Flip',win);3.%Drawprimestimulusimagetobackbuffer:Screen('DrawTexture',win,primeImage);4.%Showprimeexactly500msecsafteronsetoffixationspot:tprime_onset=Screen('Flip',win,tfixation_onset+0.500-slack);5.%Drawtargetstimulusimagetobackbuffer:Screen('DrawTexture',win,targetImage);6.%Showtargetexactly100msecsafteronsetofprimeimage:ttarget_onset=Screen('Flip',win,tprime_onset+0.100-slack);7.%Showtargetexactlyfor200msecs,thenblankscreen.ttarget_offset=Screen('Flip',win,ttarget_onset+0.200-slack);?Chooseyourpresentationtimesasamultipleofthevideorefreshduration!100Hzisagoodrefreshsettingfor10mstiminggranularityScreen(‘Flip’)-Example2:Animationwithconst.fps.1.%Getbasictiminginfo:Durationofasinglevideorefreshinterval:refresh=Screen('GetFlipInterval',win);2.%Synchronizetoretraceatstartoftrial/animationloop:vbl=Screen('Flip',win);3.%Loop:Cyclethrough300images:fori=1:3004.%Drawi'thimagetobackbuffer:Screen('DrawTexture',win,myImage(i));5.%Showimagesexactly2refreshcyclesapartofeachother:vbl=Screen('Flip',win,vbl+(2–0.5)*refresh);6.%Keyboardchecks,whatever...Nextloopiteration.end;7.%Endofanimationloop,blankscreen,recordoffsettime:toffset=Screen('Flip',win,vbl+(2–0.5)*refresh);?Chooseyourmonitorsvideorefreshrateasmultipleofwantedanimationframerate!For25fps->75Hzor100Hzisagoodrefreshsetting.For30fps->60Hz,90Hz,120Hz...產(chǎn)生視覺刺激的三種方式導(dǎo)入圖片(jpg,.tif,…)在PTB里畫圖文本圖片(textfigures)Screen函數(shù)Screen是PTB與視頻顯示有關(guān)的函數(shù)的集合都有哪些子函數(shù)?Commandwindow輸入ScreenScreen(‘函數(shù)字符串‘,參數(shù)列表)/ScreenPsychtoolbox-2-listing9.1-9.10[windowPtr,rect]=Screen(‘Openwindow’,windowPtrOrScreenNumber,[,color],[,rect],[,pixelSize],[,numberOfBuffers][,stereomode][,multisample][,imagingmode][,specialFlags],[,clientRect]);使用Screen函數(shù)常用的子函數(shù)、使用順序及功能查詢有多少屏幕Screens開窗口(創(chuàng)建主頁面)OpenWindow繪制視覺刺激畫線DrawLine,畫點DrawDots,貼圖DrawTexture頁面切換Flip關(guān)閉CloseAll附注ShowCursor;HideCursor;Basic2Ddrawingcommands(Filled)Circlesandellipses:Screen('FrameOval',window,color,boundingrect[,penWidth]);Screen('FillOval',window,color,boundingrect);(Filled)Rectangles:Screen('FrameRect',window,color,boundingrect[,penWidth]);Screen('FillRect',window,color,boundingrect);Linesofdifferentthicknessandstipplepatterns:Screen('DrawLine',window,color,fromH,fromV,toH,toV[,penWidth]);(Filled)Arcs:Screen('DrawArc',window,color,boundingrect,startAngle,arcAngle);Screen('FrameArc',window,color,boundingrect,startAngle,arcAngle);Screen('FillArc',window,color,boundingrect,startAngle,arcAngle);(Filled)convexandconcavePolygons:Screen('FillPoly',window,color,xy)批處理-

Fast2DbatchdrawingandparallelismInsteadofdrawingoneprimitiveatatime,definehundredsofsimilarprimitivesanddrawthemwith1call:

Insteadof:Screen('FillRect',win,[red1green1blue1],[left1top1right1bot1]);Screen('FillRect',win,[red2green2blue2],[left2top2right2bot2]);...Screen('FillRect',win,[redngreennbluen],[leftntopnrightnbotn]);Write:mycolors=[red1green1blue1;red2green2blue2;...;redngreennbluen];myrects=[left1top1right1bot1;left2top2right2bot2;...;leftntopnrightnbotn];Screen('FillRect',win,mycolors,myrects);screenNum=0;res=[12801024];clrdepth=32;[wPtr,rect]=Screen('OpenWindow',screenNum,0,...[00res(1)res(2)],clrdepth);black=BlackIndex(wPtr);white=WhiteIndex(wPtr);Screen('FillRect',wPtr,black);Screen(wPtr,'Flip');HideCursor;ticwhiletoc<3;endScreen('FillRect',wPtr,white);Screen(wPtr,'Flip');HideCursor;ticwhiletoc<3;endScreen('CloseAll');ShowCursorscreenNum=0;flipSpd=13;%aflipevery13frames[wPtr,rect]=Screen('OpenWindow',screenNum);monitorFlipInterval=Screen('GetFlipInterval',wPtr);%1/monitorFlipIntervalistheframerateofthemonitorblack=BlackIndex(wPtr);white=WhiteIndex(wPtr);%blanktheScreenandwaitasecondScreen('FillRect',wPtr,black);Screen(wPtr,'Flip');HideCursor;ticwhiletoc<1;end%makearectangleinthemiddleofthescreen;flipcolorsandsizeScreen('FillRect',wPtr,black);vbl=Screen(wPtr,'Flip');%collectthetimeforthefirstflipwithvblfori=1:10Screen('FillRect',wPtr,[00255],[100150200250]);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));%flip13framesaftervblScreen('FillRect',wPtr,[25500],[100150400450]);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));end%blankthescreenandwaitasecondScreen('FillRect',wPtr,black);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));ticwhiletoc<1;end%makecirclesflipcolors&sizeScreen('FillRect',wPtr,black);vbl=Screen(wPtr,'Flip');fori=1:10Screen('FillOval',wPtr,[0180255],[500500600600]);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));Screen('FillOval',wPtr,[02550],[400400900700]);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));end%blanktheScreenandwaitasecondScreen('FillRect',wPtr,black);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));ticwhiletoc<1;end%makelinesthatflipcolorssize&positionScreen('FillRect',wPtr,black);vbl=Screen(wPtr,'Flip');fori=1:10Screen('DrawLine',wPtr,[0255255],500,200,700,600,5);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));Screen('DrawLine',wPtr,[2552550],100,600,600,100,5);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));end%blanktheScreenandwaitasecondScreen('FillRect',wPtr,black);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));ticwhiletoc<1;end%combinethestimuliScreen('FillRect',wPtr,black);vbl=Screen(wPtr,'Flip');fori=1:10Screen('FillRect',wPtr,[00255],[100150200250]);Screen('DrawLine',wPtr,[0255255],500,200,700,600,5);Screen('FillOval',wPtr,[0180255],[500500600600]);Screen('TextSize',wPtr,150);Screen('DrawText',wPtr,'FUNKY!!',200,20,[25550255]);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));Screen('FillRect',wPtr,[25500],[100150400450]);Screen('FillOval',wPtr,[02550],[400400900700]);Screen('DrawLine',wPtr,[2552550],100,600,600,100,5);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));end%blankthescreenandwaitasecondScreen('FillRect',wPtr,black);vbl=Screen(wPtr,'Flip',vbl+(flipSpd*monitorFlipInterval));ticwhiletoc<1;endScreen('CloseAll');ShowCursor/wiki/MATLAB_Programming/Psychtoolbox/Screen_CommandsContents1BlitImage2552BringMATLABToFront3BringWindowToFront4ClearScreen5Close6CloseAll7CloseScreen8Computer9CopyWindow10CopyWindows11DrawLine12DrawOval13DrawPoly14DrawRect15DrawText16FillArc17FillOval18FillPoly19FillRect20FrameArc

21FrameOval22FrameRate23FrameRect24Gamma25GetClut26GetFrontWindow27GetImage28GetImage25529GetMATLABWindow30GetWindowByTitle31GlobalRect32IsOffscreen33MATLABToFront34MoveWindow35OpenOffscreenWindow36OpenWindow37PixelSize38PixelSizes39Preference40PutColorImage41PutImage42Rect43Screens44SelectMATLAB45SetClut46SetClutQ47SetDrawingRegion48SetGamma49TextFace50TextFont51TextMode52TextSize53TextStyle54TextWidth55UsageWarnings56VideoCard57WaitBlanking58WaitVBL59WindowKind60Windows61WindowScreenNumber62WindowTitle63WindowToBack64WindowToFront

Screen函數(shù):Screens子函數(shù)Screens子函數(shù):查詢有多少屏幕FAQ:有多少屏幕?若有多個顯示器,一般主屏幕用來控制,編號最大的屏幕用來呈現(xiàn)刺激此步可省略,可以直接開0號窗口screens=Screen('Screens');screenNumber=max(screens);Screen函數(shù):OpenWindow子函數(shù)OpenWindow用來打開一個窗口(“畫布”)[w,rect]=Screen('OpenWindow',screenNumber);返回值w:該窗口的“句柄值”,類似于“指針”以后對這個窗口進(jìn)行任何操作都要用這個指針rect:該窗口的“矩形”,由左上、右下兩個點的座標(biāo)定義,比如[001024768]更多參數(shù)背景顏色、窗口大小?ScreenOpenWindow?繪制視覺刺激畫什么?線條? DrawLine點? DrawDots多邊形? FillPoly/FramePoly橢圓? FillOval/FrameOval文字? DrawText照片? MakeTexture+DrawTexture效果?位置?透明?Screen函數(shù):DrawDots子函數(shù)畫點:DrawDotsScreen('DrawDots',w,xy,size,color,center,type);用來畫一個或一堆點,它的參數(shù)們:w:窗口的“指針”xy:兩行的行向量,每個點的x、y座標(biāo)各占一行size:點的寬度,以像素計color:(每個)點的顏色([RGB]或[RGBA])center:點座標(biāo)的相對中心type:方點,圓點,還是抗鋸齒的圓點Screen函數(shù):DrawLine子函數(shù)畫線:DrawLineScreen(‘DrawLine’,w,color,fromH,fromV,toH,toV,penWidth);用來畫一條線,它的參數(shù)們:w:窗口的“指針”color:線的顏色from/toH/V:起點/終點的x/y座標(biāo)penWidth:線條的粗細(xì)Screen函數(shù):MakeTexture子函數(shù)Texture-由圖片轉(zhuǎn)換而來的“紋理”,便于快速貼圖怎么把圖片轉(zhuǎn)成紋理?image=imread(‘photo.jpg’);textureIndex=Screen('MakeTexture',w,image);返回值textureIndex就是這個紋理的“指針”DrawTexture子函數(shù)把紋理(即照片)畫到屏幕上Screen(‘DrawTexture’,w,textureIndex);把照片畫到哪里?源矩陣src_rect=Screen('Rect',tex);畫紋理的哪部分(默認(rèn)全畫)?擺在中心ctr_rect=CenterRect(src_rect,wRect);偏移dst_rect=OffsetRect(dst_rect,-150,150);畫到偏移完的目標(biāo)上Screen(‘DrawTexture’,w,tex,src_rect,dst_rect);Screen函數(shù):Flip子函數(shù)Psychtoolbox有兩個緩沖區(qū)(“畫板”)屏幕上顯示的只是其中一面顯示的同時可以在下面的畫板中繼續(xù)畫需要更新的時候,直接切換,速度快把畫板切換上去馬上就翻:Screen('Flip',w);T時刻(或之后)再翻:vbl=Screen('Flip',w,T);返回值vbl是真正刷屏?xí)r刻的時間戳(GetSecs)Screen函數(shù):CloseAll子函數(shù)為了避免程序運(yùn)行時出錯,而無法執(zhí)行到CloseAll就卡在中間關(guān)不了全屏窗口tryscreens=Screen('Screens');screenNumber=max(screens);[w,rect]=Screen('OpenWindow',screenNumber);……Screen(‘CloseAll');catchScreen(‘CloseAll');rethrow(lasterror);end呈現(xiàn)透明刺激Alpha通道[RGBA]中第四個通道0為完全不透明,255為完全透明設(shè)置BlendFunctionScreen('BlendFunction',w,GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);“去掉圖片中不要的部分”?Psychtoolbox-聲音刺激

與反應(yīng)錄入

聲音基礎(chǔ)與產(chǎn)生聲音采樣率、位數(shù)聲音基礎(chǔ)音頻信號的表示1或2行(列)采樣得到的行(列)向量時間上的離散:采樣率存儲上的離散:位數(shù)(在MATLAB中是double)聲道:單聲道和立體聲采樣率:每秒離散信號的采樣個數(shù)44100Hz位數(shù):用多少位的數(shù)字表示信號對正弦波的4位采樣用MATLAB存取并播放聲音讀取并播放聲音[wav,sf,nbits]=wavread('sound.wav');size(wav)t=size(wav,1)/sf%時長=采樣點個數(shù)/采樣率wavplay(wav,sf)寫入聲音wavwrite(wav,sf,nbits,'sound.wav');Sound65.m播放聲音:wavplay改變采樣率改變播放時長,并變調(diào)wavplay(wav,8000)wavplay(wav,80000)“異步”播放指定async參數(shù)可以使聲音在“后臺”播放否則wavplay會等待播完,然后才執(zhí)行下一句利用async可以“疊加”兩個聲音wavplay(wav,44100,'async')List5.9,5.10Sound4.mSound42.mwavplay與sound類似imshow和image,MATLAB中這兩個函數(shù)都可以播放一段聲音,用法類似只有wavplay可以“異步”播放soundsc將數(shù)據(jù)scale到-1~+1區(qū)間后播放(如果有意更改聲音的音量,不要用這個函數(shù))Sound3.m生成噪音生成一段單聲道噪音就是生成一列隨機(jī)數(shù)sf=44100;%采樣率t=1.5;%持續(xù)時長noise=rand(sf*t,1);wavplay(noise,sf)%listing5.1

Sound6.mplot(noise(1:200))生成純音生成一段單聲道純音就是生成一列正弦波sf=44100;%采樣率t=1.5;%持續(xù)時長f=261.6;%純音頻率(C4=261.6Hz)tmp=linspace(0,t,sf*t);%計算正弦用的采樣矩陣tone=sin(2*pi*f*tmp);wavplay(tone,sf)List5.2plot(tone(1:200))和聲頻譜示意圖生成復(fù)合音疊加若干純音sf=44100;%采樣率t=1.5;%持續(xù)時長f=261.6;%基準(zhǔn)頻率(C4=261.6Hz)tmp=linspace(0,t,sf*t);tone1=sin(2*pi*f*tmp);tone2=sin(2*pi*2*f*tmp);tone3=sin(2*pi*4*f*tmp);harmonic=tone1+tone2+tone3;%疊加并歸一化harmonic=harmonic/max(abs(harmonic));wavplay(harmonic,sf)List5.3,List5.4,List5_567plot(harmonic(1:200))生成一段聲音拼接若干純音sf=44100;%采樣率t=0.5;%持續(xù)時長f1=261.6;f2=293.6;f3=329.6;%(C4,D4,E4)tmp=linspace(0,t,sf*t);do=sin(2*pi*f1*tmp);re=sin(2*pi*f2*tmp);mi=sin(2*pi*f3*tmp);silence=zeros(1,sf*t);%靜音wavplay([doremisilencedoremiredo],sf)List5.8Sound64.m請編出歡樂頌的第一小節(jié)的聲音刺激,一拍的時間間隔可以自定,推薦參數(shù)是0.5s

3345|5432|1123|3.22-|

這個小點代表半拍中音的音符1234567對應(yīng)的聲音頻率是523,578,659,698,784,880,988clearallsf=44100;%t50=0.5;%t25=0.25;t75=0.75;t100=1;frq=[523,578,659,698,784,880,988,392];f=261.6;tmp50=linspace(0,t50,sf*t50);tmp25=linspace(0,t25,sf*t25);tmp75=linspace(0,t75,sf*t75);tmp100=linspace(0,t100,sf*t100);fori=1:7tone25(i,:)=sin(2*pi*frq(i)*tmp25);tone50(i,:)=sin(2*pi*frq(i)*tmp50);tone75(i,:)=sin(2*pi*frq(i)*tmp75);tone100(i,:)=sin(2*pi*frq(i)*tmp100);endtoned5=sin(2*pi*frq(8)*tmp100);order=[5035035045055055045035025015015025037532521002503503504505505504,…5035025015015025037522511001502502503501,50225325450350150225325450350250150210057532535045055055045035025015015025037522511001];ge=0;fori=1:length(order)%temp=sum{order(i)}; eval(['temp=tone',num2str(fix(order(i)/10)),'(mod(order(i),10),:);']);

iforder(i)==1005temp=toned5;endge=[ge,temp];

endwavplay(ge,sf)聲音處理的幾個一般函數(shù)純音:MakeBeep[beep,samplingRate1]=MakeBeep(freq,duration,[samplingRate])freq-音調(diào)duration-音頻長度(秒)

samplingRate-采樣頻率Beep-音頻數(shù)據(jù)返回值

samplingRate1-返回采樣頻率Beeper格式Beeper(frequency,loudness,duration)loudness–“0~1”

Snd(command,[signal],[rate],[samplesize])command集成-Open,Play,Close,Wait,Quiet,DefaultRate,IsPlayingsignal-單、雙通道rate-播放頻率samplesize-比特率(8或16)Snd('Play',sin(0:5000))Snd('Close')

freq=44100;tone(1,:)=0.9*MakeBeep(1000,0.04,44100);tone(2,:)=tone(1,:);toneb(1,:)=0.9*MakeBeep(500,0.04,44100);toneb(2,:)=toneb(1,:);Snd('Play',tone,freq,16);Snd('Quiet')Snd(‘Close’)音頻數(shù)據(jù)播放:soundSound(y,Fs)Sound(y,Fs,bits)Fs-采樣頻率bits-比特數(shù)音頻播放器:audioplayerplayer=audioplayer(Y,Fs,nBits)player=audioplayer(recorder,ID)創(chuàng)建錄音機(jī)對象:audiorecorderrecorder=audiorecorder(Fs,nBits,nChannels,ID)錄制一段聲音recorder=audiorecorder(44100,8,1,0);disp('StartRecording…');Recordblocking(recorder,6);%record6secsdisp('EndofRecording');play(recorder);audiodata=getaudiodata(recorder);plot(audiodata);產(chǎn)生其他波形chirp:產(chǎn)生信號的頻率隨時間的增長而變化t=0:0.005:2;%2secs@5000HzSFy=chirp(t,220,2,440);wavplay(y,5000)sawtooth:鋸齒波fliplr,flipud:把矩陣左右或上下顛倒repmat:重復(fù)矩陣頻譜圖“通過按鍵音還原手機(jī)號碼”

頻譜圖t=0:0.0001:2;%2secs@10000Hzy=chirp(t,220,2,4400);wavplay(y,10000)spectrogram(y,128,120,128,1e5)立體聲、ITD和ILD立體聲由兩列-1/+1之間的數(shù)表示ITD(兩耳時間差)和ILD(兩耳強(qiáng)度差)是人進(jìn)行聲源定位的兩個線索HRTF(頭相關(guān)傳輸函數(shù))刻畫人耳接收空間中某一點傳來的聲音的特征/projects/HRIRrepository聲音的操縱包絡(luò)與濾波音量控制數(shù)字音頻中,0dB是最大的音量,在此基礎(chǔ)上可以減小音量,如-10dBwav*10^(db/20)可將wav音量降低為db分貝,db<0聲音的淡入和淡出在聲音前后一小段加上“門控”gatedur=.01;gate=cos(linspace(pi,2*pi,fs*gatedur));gate=(gate+1)/2;offsetgate=fliplr(gate);sustain=ones(1,(length(tone)-2*length(gate)));envelope=[gate,sustain,offsetgate];smoothed_tone=envelope.*tone;List5.13,Soundenvelope.m聲音的包絡(luò)(envelope)生成500ms,1000Hz,采樣率為44100的純音,其中,該聲音的起始30ms和末尾30ms需要ramp,用余弦變換。sf=44100;t=0.5;f=1000;tmp=linspace(0,t,sf*t);tone=sin(2*pi*f*tmp);wavplay(tone,sf)gatedur=.01;gate=cos(linspace(pi,2*pi,sf*gatedur));gate=(gate+1)/2;offsetgate=fliplr(gate);sustain=ones(1,(length(tone)-2*length(gate)));envelope=[gate,sustain,offsetgate];smoothed_tone=envelope.*tone;獲取音頻設(shè)備信息:audiodevinfodevinfo=audiodevinfoName=audiodevinfo(IO,ID);ID=audiodevinfo(IO,rate,bits,chans)Lowlatency,preciselytimedsoundwithPsychPortAudioBasedonPortAudio,afree,open-source,cross-platformaudiolibraryforrealtimeaudio:Features:Multi-channelplayback,recordingandfull-duplexfeedbackoperationLow-latencysoundoutputonMacOS/X,andMS-Windows(ASIO-required)PreciselytimedsoundonsetonMacOS/X,andMS-Windows(ASIOrequried)LowlatencysoundonWindowsneedsThestandardsoundsubsystemofMicrosoftWindowsisnotcapableofreliablytimedsoundplaybackandcapturewithlowlatencyIfyouwantlowlatencysoundwithhightimingprecisiononMicrosoftWindows,you’llneedasoundcardwithnativeASIOdriversupportandaspecialpluginforPsychtoolbox采用ASIO(AudioStreamInputOutput)技術(shù),可以減少系統(tǒng)對音頻流信號的延遲,增強(qiáng)聲卡硬件的處理能力。Delta1010聲卡Lowlatency,timedsoundwithPsychPortAudioSimpleinterface,allowsforasynchronoussoundoutputatascheduledsystemtime,e.g.,timetvisualonset:1.Padevice=PsychPortAudio('Open',[deviceid],[mode],2,96000);2.Mysound=0.9*MakeBeep(1000,0.1,96000);3.PsychPortAudio('FillBuffer',Padevice,Mysound);4.PsychPortAudio('Start',Padevice,5,tvisualonset);5.Visonset=Screen('Flip',window,tvisualonset–0.004);6....whatever...7.Audioonset=PsychPortAudio('Stop',Padevice);8.PsychPortAudio('Close'[,Padevice]);Auto-selectssettingsforlowlatency,butoverridespossible.Highprecision,lowlatencywithstandardhardwareonOS/X.PsychPortAudio-ASIOdriverInitializePsychSound(1);freq=96000;ISOI=0.12;%120msStimdur=0.03;%%auditorydurationlatbias=(64/freq);%hardwaredelaypahandle=PsychPortAudio('Open',[],[],2,freq);%Telldriverabouthardwaresinherentlatencyprelat=PsychPortAudio('LatencyBias',pahandle,latbias);postlat=PsychPortAudio('LatencyBias',pahandle);%1:singlesound;2:twosounds;3:multiplesoundstone20=0.9*MakeBeep(500,0.02,freq);%tonewith20mstone(1,:)=0.9*MakeBeep(500,ISOI+Stimdur,freq);tone(2,1:length(tone20))=tone20;tone(2,end-length(tone20)+1:end)=tone20;fori=0:2:6range=1+i*length(tone20):length(tone20)*(i+1);tone(3,range)=tone20;endPsychPortAudio('FillBuffer',pahandle,repmat(tone(1,:),2,1));PsychPortAudio('Start',pahandle,1,

0);

%PsychPortAudio('Stop',pahandle);使用前裝載聲卡驅(qū)動程序List10.4,psyaudioTimingtryw=Screen('OpenWindow',0);

WaitSecs(10);%等待時間,以秒為單位Screen('CloseAll');catchScreen('Close',w)rethrow(lasterror)endtryScreen('OpenWindow',0);t0=GetSecs;WaitSecs(5);t1=GetSecs;Screen('CloseAll');

t_elapsed=t1-t0;(反應(yīng)時)catchScreen('Close',w);rethrow(lasterror)endtry

screenNum=0;res=[12801024];clrdepth=32;[wPtr,rect]=Screen('OpenWindow',screenNum,0,[00res(1)res(2)],clrdepth);black=BlackIndex(wPtr);white=WhiteIndex(wPtr);Screen('FillRect',wPtr,black);priorityLevel=MaxPriority(wPtr);Priority(priorityLevel);Screen(wPtr,'Flip');Priority(0);Screen('CloseAll');catchScreen('Close',wPtr)rethrow(lasterror)EndPriority()-SwitchMatlabprocesstorealtime-schedulingmode.

優(yōu)先級BasiccommandsforsystemcontrolandtimingT=GetSecs(獲取時間值)

Querytimewithmicrosecondresolution.Useshighestresolutionsystemclockformeasurementoftime.WaitSecs(duration)Waitforaspecifiedamountoftime'duration'.OnMacOS/X:Accurateto<0.3millisecondsonaverage.OnMS-Windows:Accurateto<2millisecondsonaverageonamodernmachine.按鍵Keypress對話框鼠標(biāo)并口輸入KbName('UnifyKeyNames')[keyIsDown,secs,keyCode]=KbCheck;>KbDemoKbWait[keyIsDown,~,keyCode]=KbCheck;disp('TestingKbWait:hitanykey.Justonce.');startSecs=GetSecs;timeSecs=KbWait;[keyIsDown,t,keyCode]=KbCheck;str=[KbName(keyCode),'typedattime',num2str(timeSecs-startSecs),'seconds']disp(str);KeyPressesCollectingkeypressesusingpauseandinputInputdlg

promptParameters={'SubjectName','Age','Gender(ForM?)','Handedness(LorR)'};defaultParameters={'','','','R'};Subinfo=inputdlg(promptParameters,'SubjectInfo',1,defaultParameters);Inputresp_num=input(‘pressanumberkey…’);resp_char=input(‘pressanumberkey…’);disp('Usinginputcommand')resp='x';whileresp~='a'&resp~='b'resp=input('pressaorb...','s');endrespBearinmindthatthecommandwindowneedstobeinfrontforthekey-presstobeavailabletoMatlab,soinputdoesn’tworkwellify

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論