functionR=imnoise2(type,M,N,a,b)%IMNOISE2GeneratesanarrayofrandomnumberswithspecifiedPDF.%R=IMNOISE2(TYPE,M,N,A,B)generatesanarray,R,ofsize%M-by-N,whoseelementsarerandomnumbersofthespecifiedTYPE%withparametersAandB.IfonlyTYPEisincludedinthe%inputargumentlist,asinglerandomnumberofthespecified%TYPEanddefaultparametersshownbelowisgenerated.Ifonly%TYPE,M,andNareprovided,thedefaultparametersshownbelow%areused.IfM=N=1,IMNOISE2generatesasinglerandom%numberofthespecifiedTYPEandparametersAandB.%%ValidvaluesforTYPEandparametersAandBare:%%'uniform'Uniformrandomnumbersintheinterval(A,B).%Thedefaultvaluesare(0,1).%'gaussian'GaussianrandomnumberswithmeanAandstandard%deviationB.ThedefaultvaluesareA=0,B=1.%'salt&pepper'Saltandpeppernumbersofamplitude0with%probabilityPa=A,andamplitude1with%probabilityPb=B.ThedefaultvaluesarePa=%Pb=A=B=0.05.Notethatthenoisehas%values0(withprobabilityPa=A)and1(with%probabilityPb=B),soscalingisnecessaryif%valuesotherthan0and1arerequired.Thenoise%matrixRisassignedthreevalues.IfR(x,y)=%0,thenoiseat(x,y)ispepper(black).If%R(x,y)=1,thenoiseat(x,y)issalt%(white).IfR(x,y)=0.5,thereisnonoise%assignedtocoordinates(x,y).%'lognormal'LognormalnumberswithoffsetAandshape%parameterB.ThedefaultsareA=1andB=%0.25.%'rayleigh'RayleighnoisewithparametersAandB.The%defaultvaluesareA=0andB=1.%'exponential'ExponentialrandomnumberswithparameterA.The%defaultisA=1.%'erlang'Erlang(gamma)randomnumberswithparametersA%andB.Bmustbeapositiveinteger.The%defaultsareA=2andB=5.Erlangrandom%numbersareapproximatedasthesumofB%exponentialrandomnumbers.%Copyright2002-2006R.C.Gonzalez,R.E.Woods,&S.L.Eddins%DigitalImageProcessingUsingMATLAB,Prentice-Hall,2004%$Revision:1.6$$Date:2006/07/1520:44:52$%Setdefaultvalues.ifnargin==1a=0;b=1;M=1;N=1;elseifnargin==3a=0;b=1;end%Beginprocessing.Uselower(type)toprotectagainstinputbeing%capitalized.switchlower(type)case'uniform'R=a+(b-a)*rand(M,N);case'gaussian'R=a+b*randn(M,N);case'salt&pepper'ifnargin=3a=0.05;b=0.05;end%ChecktomakesurethatPa+Pbisnot1.if(a+b)1error('ThesumPa+Pbmustnotexceed1.')endR(1:M,1:N)=0.5;%GenerateanM-by-Narrayofuniformly-distributedrandomnumbers%intherange(0,1).Then,Pa*(M*N)ofthemwillhavevalues=%a.Thecoordinatesofthesepointswecall0(pepper%noise).Similarly,Pb*(M*N)pointswillhavevaluesintherange%a&=(a+b).Thesewecall1(saltnoise).X=rand(M,N);c=find(X=a);R(c)=0;u=a+b;c=find(Xa&X=u);R(c)=1;case'lognormal'ifnargin=3a=1;b=0.25;endR=exp(b*randn(M,N)+a);case'rayleigh'R=a+(-b*log(1-rand(M,N))).^0.5;case'exponential'ifnargin=3a=1;endifa=0error('Parameteramustbepositiveforexponentialtype.')endk=-1/a;R=k*log(1-rand(M,N));case'erlang'ifnargin=3a=2;b=5;endif(b~=round(b)|b=0)error('ParambmustbeapositiveintegerforErlang.')endk=-1/a;R=zeros(M,N);forj=1:bR=R+k*log(1-rand(M,N));endotherwiseerror('Unknowndistributiontype.')end