版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
PsychtooboxLihanChen2015.4.28MATLAB图像刺激
图像处理图像基础图像的变换与操纵计算生成图像图像基础像素、颜色、索引图像图像基础——像素数字图像离散的坐标:像素离散的强度:0~255(黑~白)图像基础——颜色RGB颜色系统每个像素的红、绿、蓝均由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]);%将这个组合复制5遍a2=xor(a1,a1’);%将这个黑白条纹与自己的转置做异或逻辑运算imshow(a2)%棋盘格就生成了实例:红蓝3D与双眼竞争im1=imread('Koala.jpg');im2=imread('Penguins.jpg');%用第二幅图替代第一幅图的红色通道im1(:,:,1)=im2(:,:,1);%把绿色通道清零im1(:,:,2)=0;imshow(im1)image与colormapimage函数是MATLAB最基本的图像显示函数,可以绘制索引图像,即每个像素的值对应颜色查找表中的索引colormap:定义图像显示用的颜色查找表imagesc将数据scale后绘制成图(例如绘制相关矩阵)image与imshowImshow仅用于显示由RGB或灰度值定义的图像(image也可以)无论是哪个函数,若图像是以uint8表示的,则取值范围为0~255,若以double表示,则取值范围是0~1将face.jpg与house.jpg融合成一张图片,face占用红色通道,house占用绿色通道,蓝色通道取值0.由于两张图片不一样大,最后结果保留两张图片重叠部分即可,如示例mix.jpg(imread读出的数据是uint8,取值范围是0-255,imshow图片的取值范围是0-1,中间需要除以255这个系数)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绘制数据imagesc&colormap绘制相关矩阵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数据,数据里记录了V1,V2,V3,V4,V5,ips6个脑区100个时间点的值,请画出其6x6的相关矩阵。loaddata.matfdata=[V1,V2,V3,V4,V5,ips];imagesc(corr(fdata))马赫带效应clearall%清除变量,MEX等,如果有需要的变量还不想清除,需要小心closeall%关闭各种figure窗口img=1:10;%图片的值,即是选择colormap第1-10的值figure(1)%打开figure编号为1的窗口paintpots=ones(10,3);%自己创建的一个颜色查找表colormap(paintpots)%将定义好的对应关系输入系统image(img);%呈现图片axisoff;%取消在这个任务中没有意义的轴fori=1:10paintpots(i,:)=(i/10);%令查找表的第i位的值为i/10,即是最大亮度的i/10倍colormap(paintpots);%将更新的查找表输入系统pause%等待按键,注意看figure中图片的变化endPsychtoolbox-1-listing-lst3.mclearallcloseallcolormap(gray(256))%将颜色查找表设置为灰度图img=reshape(1:256,16,16);image(img);axissquare%将长宽设置为等长axisoffpausefori=1:200paintpots=rand(256,3);%将颜色查找表设为随机,图片的像素颜色也变成随机colormap(paintpots);drawnow%立刻呈现end图像的变换与处理调整曲线、窗口化像素亮度的变换操作(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图像的“窗口”操纵每个像素的亮度:乘以一个系数生成高斯窗口
窗口化图像imagesc(GaWindow)tmp=double(im).*GaWindow;Windowed=uint8(tmp);imshow(Windowed)Psychtoolbox-1-listing-lst6.m先生成一个200x200的高斯滤波器,sigma=50,读取Simpson.jpg,使得二维高斯覆盖在图像上,高斯覆盖范围外值为0,(如3.jpg)。并且将这个过程做成动态。通过鼠标控制高斯覆盖的位置,刷新的频率定为25Hz(既每次呈现一帧图像要pause0.04s),点击鼠标右键退出循环。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)将该矩阵覆盖在每个像素点上对所有被覆盖的点将原图像矩阵和该矩阵的对应点相乘求和变成新图像的点由邻居决定新的像素点的强度
我们对下幅图片用3x3的平均滤波,即滤波的算子是一个3x3的平均矩阵。设原矩阵名为x(图),x(3,3)的值为74,则经过平均滤波之后,这个点的值变为(20+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对原图进行滤波 imf=imfilter(im,GaFilter);
imshow(imf)高斯模糊的图片边缘检测原始图像grayedge(gray)imfilter(gray,fspecial('sobel'))更多的滤波器用fspecial生成二维的特殊滤波器average简单平均gaussian高斯滤波motion模拟摄像机抖动sobel检测边缘算子docfspecial(1)将face进行高斯滤波,高斯算子的边长是100个pixel,sigma为30。clearallface=imread('face.jpg');op=fspecial('Gaussian',100,30);filface=imfilter(face,op);imshow(filface);
(2)对house进行边缘检测。clearallhouse=imread('house.jpg');ghouse=rgb2gray(house);imshow(edge(ghouse,'canny'))
(3)制作一个200x200竖直朝向顺时针偏转15度的gabor,其他参数可自己定,并解释各个参数的含义。
clearall[X,Y]=meshgrid(1:200,1:200);grating=sin((tan(75/180*pi)*X+Y)/25);%(tan(75/180*pi)表示竖直朝向顺时偏转15度,%gabor一个周期是25*2*pi/sqrt(tan(75/180*pi)^2+1)个pixel,%(分母是为了标准化)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);%制作坐标网格x1=sin(x/10);%值域为[-1,1];y1=sin(y/10);c=x1.*y1;%负负得正pic=c>0;
%最后逻辑判断,得到棋盘格imshow(pic)
Psychtoolbox函数介绍(图像刺激的实现)
SCREEN函数与视觉刺激被试眼睛到屏幕的距离为d,刺激的长度是l,那么视角就是θ,有tan(θ)=l/d,写成matlab语句就是tand(θ)=l/d,则θ=atand(l/d)deg2pix.m如果屏幕的分辨率是axb,屏幕宽度是w,则pixel数=tand(θ)*d*a/w假设屏幕的分辨率为1024x768,我们测得屏幕的宽为40cm,可以得出每cm的长度中有1024/40=25.6个pixel。实际报告刺激大小的时候往往用的是视角θ,而我们操作matlab用的pixel的数目。如果已知θ求pixel数,则有pixel数=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...产生视觉刺激的三种方式导入图片(jpg,.tif,…)在PTB里画图文本图片(textfigures)Screen函数Screen是PTB与视频显示有关的函数的集合都有哪些子函数?Commandwindow输入ScreenScreen(‘函数字符串‘,参数列表)/ScreenPsychtoolbox-2-listing9.1-9.10[windowPtr,rect]=Screen(‘Openwindow’,windowPtrOrScreenNumber,[,color],[,rect],[,pixelSize],[,numberOfBuffers][,stereomode][,multisample][,imagingmode][,specialFlags],[,clientRect]);使用Screen函数常用的子函数、使用顺序及功能查询有多少屏幕Screens开窗口(创建主页面)OpenWindow绘制视觉刺激画线DrawLine,画点DrawDots,贴图DrawTexture页面切换Flip关闭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函数:Screens子函数Screens子函数:查询有多少屏幕FAQ:有多少屏幕?若有多个显示器,一般主屏幕用来控制,编号最大的屏幕用来呈现刺激此步可省略,可以直接开0号窗口screens=Screen('Screens');screenNumber=max(screens);Screen函数:OpenWindow子函数OpenWindow用来打开一个窗口(“画布”)[w,rect]=Screen('OpenWindow',screenNumber);返回值w:该窗口的“句柄值”,类似于“指针”以后对这个窗口进行任何操作都要用这个指针rect:该窗口的“矩形”,由左上、右下两个点的座标定义,比如[001024768]更多参数背景颜色、窗口大小?ScreenOpenWindow?绘制视觉刺激画什么?线条? DrawLine点? DrawDots多边形? FillPoly/FramePoly椭圆? FillOval/FrameOval文字? DrawText照片? MakeTexture+DrawTexture效果?位置?透明?Screen函数:DrawDots子函数画点:DrawDotsScreen('DrawDots',w,xy,size,color,center,type);用来画一个或一堆点,它的参数们:w:窗口的“指针”xy:两行的行向量,每个点的x、y座标各占一行size:点的宽度,以像素计color:(每个)点的颜色([RGB]或[RGBA])center:点座标的相对中心type:方点,圆点,还是抗锯齿的圆点Screen函数:DrawLine子函数画线:DrawLineScreen(‘DrawLine’,w,color,fromH,fromV,toH,toV,penWidth);用来画一条线,它的参数们:w:窗口的“指针”color:线的颜色from/toH/V:起点/终点的x/y座标penWidth:线条的粗细Screen函数:MakeTexture子函数Texture-由图片转换而来的“纹理”,便于快速贴图怎么把图片转成纹理?image=imread(‘photo.jpg’);textureIndex=Screen('MakeTexture',w,image);返回值textureIndex就是这个纹理的“指针”DrawTexture子函数把纹理(即照片)画到屏幕上Screen(‘DrawTexture’,w,textureIndex);把照片画到哪里?源矩阵src_rect=Screen('Rect',tex);画纹理的哪部分(默认全画)?摆在中心ctr_rect=CenterRect(src_rect,wRect);偏移dst_rect=OffsetRect(dst_rect,-150,150);画到偏移完的目标上Screen(‘DrawTexture’,w,tex,src_rect,dst_rect);Screen函数:Flip子函数Psychtoolbox有两个缓冲区(“画板”)屏幕上显示的只是其中一面显示的同时可以在下面的画板中继续画需要更新的时候,直接切换,速度快把画板切换上去马上就翻:Screen('Flip',w);T时刻(或之后)再翻:vbl=Screen('Flip',w,T);返回值vbl是真正刷屏时刻的时间戳(GetSecs)Screen函数:CloseAll子函数为了避免程序运行时出错,而无法执行到CloseAll就卡在中间关不了全屏窗口tryscreens=Screen('Screens');screenNumber=max(screens);[w,rect]=Screen('OpenWindow',screenNumber);……Screen(‘CloseAll');catchScreen(‘CloseAll');rethrow(lasterror);end呈现透明刺激Alpha通道[RGBA]中第四个通道0为完全不透明,255为完全透明设置BlendFunctionScreen('BlendFunction',w,GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);“去掉图片中不要的部分”?Psychtoolbox-声音刺激
与反应录入
声音基础与产生声音采样率、位数声音基础音频信号的表示1或2行(列)采样得到的行(列)向量时间上的离散:采样率存储上的离散:位数(在MATLAB中是double)声道:单声道和立体声采样率:每秒离散信号的采样个数44100Hz位数:用多少位的数字表示信号对正弦波的4位采样用MATLAB存取并播放声音读取并播放声音[wav,sf,nbits]=wavread('sound.wav');size(wav)t=size(wav,1)/sf%时长=采样点个数/采样率wavplay(wav,sf)写入声音wavwrite(wav,sf,nbits,'sound.wav');Sound65.m播放声音:wavplay改变采样率改变播放时长,并变调wavplay(wav,8000)wavplay(wav,80000)“异步”播放指定async参数可以使声音在“后台”播放否则wavplay会等待播完,然后才执行下一句利用async可以“叠加”两个声音wavplay(wav,44100,'async')List5.9,5.10Sound4.mSound42.mwavplay与sound类似imshow和image,MATLAB中这两个函数都可以播放一段声音,用法类似只有wavplay可以“异步”播放soundsc将数据scale到-1~+1区间后播放(如果有意更改声音的音量,不要用这个函数)Sound3.m生成噪音生成一段单声道噪音就是生成一列随机数sf=44100;%采样率t=1.5;%持续时长noise=rand(sf*t,1);wavplay(noise,sf)%listing5.1
Sound6.mplot(noise(1:200))生成纯音生成一段单声道纯音就是生成一列正弦波sf=44100;%采样率t=1.5;%持续时长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))和声频谱示意图生成复合音叠加若干纯音sf=44100;%采样率t=1.5;%持续时长f=261.6;%基准频率(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;%持续时长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请编出欢乐颂的第一小节的声音刺激,一拍的时间间隔可以自定,推荐参数是0.5s
3345|5432|1123|3.22-|
这个小点代表半拍中音的音符1234567对应的声音频率是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)声音处理的几个一般函数纯音:MakeBeep[beep,samplingRate1]=MakeBeep(freq,duration,[samplingRate])freq-音调duration-音频长度(秒)
samplingRate-采样频率Beep-音频数据返回值
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’)音频数据播放:soundSound(y,Fs)Sound(y,Fs,bits)Fs-采样频率bits-比特数音频播放器:audioplayerplayer=audioplayer(Y,Fs,nBits)player=audioplayer(recorder,ID)创建录音机对象: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);产生其他波形chirp:产生信号的频率随时间的增长而变化t=0:0.005:2;%2secs@5000HzSFy=chirp(t,220,2,440);wavplay(y,5000)sawtooth:锯齿波fliplr,flipud:把矩阵左右或上下颠倒repmat:重复矩阵频谱图“通过按键音还原手机号码”
频谱图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之间的数表示ITD(两耳时间差)和ILD(两耳强度差)是人进行声源定位的两个线索HRTF(头相关传输函数)刻画人耳接收空间中某一点传来的声音的特征/projects/HRIRrepository声音的操纵包络与滤波音量控制数字音频中,0dB是最大的音量,在此基础上可以减小音量,如-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声音的包络(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;获取音频设备信息: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)技术,可以减少系统对音频流信号的延迟,增强声卡硬件的处理能力。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);使用前装载声卡驱动程序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;(反应时)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.
优先级BasiccommandsforsystemcontrolandtimingT=GetSecs(获取时间值)
Querytimewithmicrosecondresolution.Useshighestresolutionsystemclockformeasurementoftime.WaitSecs(duration)Waitforaspecifiedamountoftime'duration'.OnMacOS/X:Accurateto<0.3millisecondsonaverage.OnMS-Windows:Accurateto<2millisecondsonaverageonamodernmachine.按键Keypress对话框鼠标并口输入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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024年度可再生能源项目开发合同
- 2024年旅游服务与导游合同
- 2024年度车牌租赁合同范本模板
- 2024年度食堂食品安全保障合同
- 二零二四年度重载叉车进口销售合同
- 房地产房产广告合同
- 股权释放协议书
- 二零二四年度公园景区排水设施改造合同
- 二零二四年度宁伊网络安全保障合同
- 公司股份转让协议书
- 医院药房二维码溯源管理
- 四川省凉山州2023-2024学年七年级上学期期末检测历史试卷
- 《简述公平理论》课件
- 打地鼠游戏的设计与实现实验报告
- 物流管理专业人才需求分析与预测调研报告(2020年)
- 人是如何学习的II:学习者、境脉与文化
- 手术室利用PDCA循环提高患者手术室健康教育知晓率品管圈QCC成果汇报
- 妊娠易栓症查房课件
- 精神科住培入科教育
- 播音主持专业职业生涯规划书
- 人教版六年级上册数学期末看图列式计算专题训练
评论
0/150
提交评论