plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
jacksky64/imageProcessing-master
|
load_signal.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/toolbox/load_signal.m
| 12,338 |
utf_8
|
b70e4cb57d6b467ae9c90d4b3310a81f
|
function y = load_signal(name, n, options)
% load_signal - load a 1D signal
%
% y = load_signal(name, n, options);
%
% name is a string that can be :
% 'regular' (options.alpha gives regularity)
% 'step', 'rand',
% 'gaussiannoise' (options.sigma gives width of filtering in pixels),
% [natural signals]
% 'tiger', 'bell', 'bird'
% [WAVELAB signals]
% 'HeaviSine', 'Bumps', 'Blocks',
% 'Doppler', 'Ramp', 'Cusp', 'Sing', 'HiSine',
% 'LoSine', 'LinChirp', 'TwoChirp', 'QuadChirp',
% 'MishMash', 'WernerSorrows' (Heisenberg),
% 'Leopold' (Kronecker), 'Piece-Regular' (Piece-Wise Smooth),
% 'Riemann','HypChirps','LinChirps', 'Chirps', 'Gabor'
% 'sineoneoverx','Cusp2','SmoothCusp','Gaussian'
% 'Piece-Polynomial' (Piece-Wise 3rd degree polynomial)
if nargin<2
n = 1024;
end
options.null = 0;
if isfield(options, 'alpha')
alpha = options.alpha;
else
alpha = 2;
end
options.rep = '';
switch lower(name)
case 'regular'
y = gen_signal(n,alpha);
case 'step'
y = linspace(0,1,n)>0.5;
case 'stepregular'
y = linspace(0,1,n)>0.5; y=y(:);
a = gen_signal(n,2); a = a(:);
a = rescale(a,-0.1,0.1);
y = y+a;
case 'gaussiannoise'
% filtered gaussian noise
y = randn(n,1);
if isfield(options, 'sigma')
sigma = options.sigma; % variance in number of pixels
else
sigma = 20;
end
m = min(n, 6*round(sigma/2)+1);
h = compute_gaussian_filter(m,sigma/(4*n),n);
options.bound = 'per';
y = perform_convolution(y,h, options);
case 'rand'
if isfield(options, 'p1')
p1 = options.p1;
else
c = 10;
p1 = 1:c; p1 = p1/sum(p1);
end
p1 = p1(:); c = length(p1);
if isfield(options, 'p2')
p2 = options.p2;
else
if isfield(options, 'evol')
evol = options.evol;
else
evol = 0;
end
p2 = p1(:) + evol*(rand(c,1)-0.5);
p2 = max(p2,0); p2 = p2/sum(p2);
end
y = zeros(n,1);
for i=1:n
a = (i-1)/(n-1);
p = a*p1+(1-a)*p2; p = p/sum(p);
y(i) = rand_discr(p, 1);
end
case 'bird'
[y,fs] = load_sound([name '.wav'], n, options);
case 'tiger'
[y,fs] = load_sound([name '.au'], n, options);
case 'bell'
[y,fs] = load_sound([name '.wav'], n, options);
otherwise
y = MakeSignal(name,n);
end
y = y(:);
function y = gen_signal(n,alpha)
% gen_signal - generate a 1D C^\alpha signal of length n.
%
% y = gen_signal(n,alpha);
%
% The signal is scaled in [0,1].
%
% Copyright (c) 2003 Gabriel Peyr?
if nargin<2
alpha = 2;
end
y = randn(n,1);
fy = fft(y);
fy = fftshift(fy);
% filter with |omega|^{-\alpha}
h = (-n/2+1):(n/2);
h = (abs(h)+1).^(-alpha-0.5);
fy = fy.*h';
fy = fftshift(fy);
y = real( ifft(fy) );
y = (y-min(y))/(max(y)-min(y));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sig = MakeSignal(Name,n)
% MakeSignal -- Make artificial signal
% Usage
% sig = MakeSignal(Name,n)
% Inputs
% Name string: 'HeaviSine', 'Bumps', 'Blocks',
% 'Doppler', 'Ramp', 'Cusp', 'Sing', 'HiSine',
% 'LoSine', 'LinChirp', 'TwoChirp', 'QuadChirp',
% 'MishMash', 'WernerSorrows' (Heisenberg),
% 'Leopold' (Kronecker), 'Piece-Regular' (Piece-Wise Smooth),
% 'Riemann','HypChirps','LinChirps', 'Chirps', 'Gabor'
% 'sineoneoverx','Cusp2','SmoothCusp','Gaussian'
% 'Piece-Polynomial' (Piece-Wise 3rd degree polynomial)
% n desired signal length
% Outputs
% sig 1-d signal
%
% References
% Various articles of D.L. Donoho and I.M. Johnstone
%
if nargin > 1,
t = (1:n) ./n;
end
Name = lower(Name);
if strcmp(Name,'heavisine'),
sig = 4.*sin(4*pi.*t);
sig = sig - sign(t - .3) - sign(.72 - t);
elseif strcmp(Name,'bumps'),
pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];
hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2];
wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005];
sig = zeros(size(t));
for j =1:length(pos)
sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;
end
elseif strcmp(Name,'blocks'),
pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];
hgt = [4 (-5) 3 (-4) 5 (-4.2) 2.1 4.3 (-3.1) 2.1 (-4.2)];
sig = zeros(size(t));
for j=1:length(pos)
sig = sig + (1 + sign(t-pos(j))).*(hgt(j)/2) ;
end
elseif strcmp(Name,'doppler'),
sig = sqrt(t.*(1-t)).*sin((2*pi*1.05) ./(t+.05));
elseif strcmp(Name,'ramp'),
sig = t - (t >= .37);
elseif strcmp(Name,'cusp'),
sig = sqrt(abs(t - .37));
elseif strcmp(Name,'sing'),
k = floor(n * .37);
sig = 1 ./abs(t - (k+.5)/n);
elseif strcmp(Name,'hisine'),
sig = sin( pi * (n * .6902) .* t);
elseif strcmp(Name,'losine'),
sig = sin( pi * (n * .3333) .* t);
elseif strcmp(Name,'linchirp'),
sig = sin(pi .* t .* ((n .* .500) .* t));
elseif strcmp(Name,'twochirp'),
sig = sin(pi .* t .* (n .* t)) + sin((pi/3) .* t .* (n .* t));
elseif strcmp(Name,'quadchirp'),
sig = sin( (pi/3) .* t .* (n .* t.^2));
elseif strcmp(Name,'mishmash'), % QuadChirp + LinChirp + HiSine
sig = sin( (pi/3) .* t .* (n .* t.^2)) ;
sig = sig + sin( pi * (n * .6902) .* t);
sig = sig + sin(pi .* t .* (n .* .125 .* t));
elseif strcmp(Name,'wernersorrows'),
sig = sin( pi .* t .* (n/2 .* t.^2)) ;
sig = sig + sin( pi * (n * .6902) .* t);
sig = sig + sin(pi .* t .* (n .* t));
pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];
hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2];
wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005];
for j =1:length(pos)
sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;
end
elseif strcmp(Name,'leopold'),
sig = (t == floor(.37 * n)/n); % Kronecker
elseif strcmp(Name,'riemann'),
sqn = round(sqrt(n));
sig = t .* 0; % Riemann's Non-differentiable Function
sig((1:sqn).^2) = 1. ./ (1:sqn);
sig = real(ifft(sig));
elseif strcmp(Name,'hypchirps'), % Hyperbolic Chirps of Mallat's book
alpha = 15*n*pi/1024;
beta = 5*n*pi/1024;
t = (1.001:1:n+.001)./n;
f1 = zeros(1,n);
f2 = zeros(1,n);
f1 = sin(alpha./(.8-t)).*(0.1<t).*(t<0.68);
f2 = sin(beta./(.8-t)).*(0.1<t).*(t<0.75);
M = round(0.65*n);
P = floor(M/4);
enveloppe = ones(1,M); % the rising cutoff function
enveloppe(1:P) = (1+sin(-pi/2+((1:P)-ones(1,P))./(P-1)*pi))/2;
enveloppe(M-P+1:M) = reverse(enveloppe(1:P));
env = zeros(1,n);
env(ceil(n/10):M+ceil(n/10)-1) = enveloppe(1:M);
sig = (f1+f2).*env;
elseif strcmp(Name,'linchirps'), % Linear Chirps of Mallat's book
b = 100*n*pi/1024;
a = 250*n*pi/1024;
t = (1:n)./n;
A1 = sqrt((t-1/n).*(1-t));
sig = A1.*(cos((a*(t).^2)) + cos((b*t+a*(t).^2)));
elseif strcmp(Name,'chirps'), % Mixture of Chirps of Mallat's book
t = (1:n)./n.*10.*pi;
f1 = cos(t.^2*n/1024);
a = 30*n/1024;
t = (1:n)./n.*pi;
f2 = cos(a.*(t.^3));
f2 = reverse(f2);
ix = (-n:n)./n.*20;
g = exp(-ix.^2*4*n/1024);
i1 = (n/2+1:n/2+n);
i2 = (n/8+1:n/8+n);
j = (1:n)/n;
f3 = g(i1).*cos(50.*pi.*j*n/1024);
f4 = g(i2).*cos(350.*pi.*j*n/1024);
sig = f1+f2+f3+f4;
enveloppe = ones(1,n); % the rising cutoff function
enveloppe(1:n/8) = (1+sin(-pi/2+((1:n/8)-ones(1,n/8))./(n/8-1)*pi))/2;
enveloppe(7*n/8+1:n) = reverse(enveloppe(1:n/8));
sig = sig.*enveloppe;
elseif strcmp(Name,'gabor'), % two modulated Gabor functions in
% Mallat's book
N = 512;
t = (-N:N)*5/N;
j = (1:N)./N;
g = exp(-t.^2*20);
i1 = (2*N/4+1:2*N/4+N);
i2 = (N/4+1:N/4+N);
sig1 = 3*g(i1).*exp(i*N/16.*pi.*j);
sig2 = 3*g(i2).*exp(i*N/4.*pi.*j);
sig = sig1+sig2;
elseif strcmp(Name,'sineoneoverx'), % sin(1/x) in Mallat's book
N = 1024;
a = (-N+1:N);
a(N) = 1/100;
a = a./(N-1);
sig = sin(1.5./(i));
sig = sig(513:1536);
elseif strcmp(Name,'cusp2'),
N = 64;
a = (1:N)./N;
x = (1-sqrt(a)) + a/2 -.5;
M = 8*N;
sig = zeros(1,M);
sig(M-1.5.*N+1:M-.5*N) = x;
sig(M-2.5*N+2:M-1.5.*N+1) = reverse(x);
sig(3*N+1:3*N + N) = .5*ones(1,N);
elseif strcmp(Name,'smoothcusp'),
sig = MakeSignal('Cusp2');
N = 64;
M = 8*N;
t = (1:M)/M;
sigma = 0.01;
g = exp(-.5.*(abs(t-.5)./sigma).^2)./sigma./sqrt(2*pi);
g = fftshift(g);
sig2 = iconv(g',sig)'/M;
elseif strcmp(Name,'piece-regular'),
sig1=-15*MakeSignal('Bumps',n);
t = (1:fix(n/12)) ./fix(n/12);
sig2=-exp(4*t);
t = (1:fix(n/7)) ./fix(n/7);
sig5=exp(4*t)-exp(4);
t = (1:fix(n/3)) ./fix(n/3);
sigma=6/40;
sig6=-70*exp(-((t-1/2).*(t-1/2))/(2*sigma^2));
sig(1:fix(n/7))= sig6(1:fix(n/7));
sig((fix(n/7)+1):fix(n/5))=0.5*sig6((fix(n/7)+1):fix(n/5));
sig((fix(n/5)+1):fix(n/3))=sig6((fix(n/5)+1):fix(n/3));
sig((fix(n/3)+1):fix(n/2))=sig1((fix(n/3)+1):fix(n/2));
sig((fix(n/2)+1):(fix(n/2)+fix(n/12)))=sig2;
sig((fix(n/2)+2*fix(n/12)):-1:(fix(n/2)+fix(n/12)+1))=sig2;
sig(fix(n/2)+2*fix(n/12)+fix(n/20)+1:(fix(n/2)+2*fix(n/12)+3*fix(n/20)))=...
-ones(1,fix(n/2)+2*fix(n/12)+3*fix(n/20)-fix(n/2)-2*fix(n/12)-fix(n/20))*25;
k=fix(n/2)+2*fix(n/12)+3*fix(n/20);
sig((k+1):(k+fix(n/7)))=sig5;
diff=n-5*fix(n/5);
sig(5*fix(n/5)+1:n)=sig(diff:-1:1);
% zero-mean
bias=sum(sig)/n;
sig=bias-sig;
elseif strcmp(Name,'piece-polynomial'),
t = (1:fix(n/5)) ./fix(n/5);
sig1=20*(t.^3+t.^2+4);
sig3=40*(2.*t.^3+t) + 100;
sig2=10.*t.^3 + 45;
sig4=16*t.^2+8.*t+16;
sig5=20*(t+4);
sig6(1:fix(n/10))=ones(1,fix(n/10));
sig6=sig6*20;
sig(1:fix(n/5))=sig1;
sig(2*fix(n/5):-1:(fix(n/5)+1))=sig2;
sig((2*fix(n/5)+1):3*fix(n/5))=sig3;
sig((3*fix(n/5)+1):4*fix(n/5))=sig4;
sig((4*fix(n/5)+1):5*fix(n/5))=sig5(fix(n/5):-1:1);
diff=n-5*fix(n/5);
sig(5*fix(n/5)+1:n)=sig(diff:-1:1);
%sig((fix(n/20)+1):(fix(n/20)+fix(n/10)))=-ones(1,fix(n/10))*20;
sig((fix(n/20)+1):(fix(n/20)+fix(n/10)))=ones(1,fix(n/10))*10;
sig((n-fix(n/10)+1):(n+fix(n/20)-fix(n/10)))=ones(1,fix(n/20))*150;
% zero-mean
bias=sum(sig)/n;
sig=sig-bias;
elseif strcmp(Name,'gaussian'),
sig=GWN(n,beta);
g=zeros(1,n);
lim=alpha*n;
mult=pi/(2*alpha*n);
g(1:lim)=(cos(mult*(1:lim))).^2;
g((n/2+1):n)=g((n/2):-1:1);
g = rnshift(g,n/2);
g=g/norm(g);
sig=iconv(g,sig);
else
disp(sprintf('MakeSignal: I don*t recognize <<%s>>',Name))
disp('Allowable Names are:')
disp('HeaviSine'),
disp('Bumps'),
disp('Blocks'),
disp('Doppler'),
disp('Ramp'),
disp('Cusp'),
disp('Crease'),
disp('Sing'),
disp('HiSine'),
disp('LoSine'),
disp('LinChirp'),
disp('TwoChirp'),
disp('QuadChirp'),
disp('MishMash'),
disp('WernerSorrows'),
disp('Leopold'),
disp('Sing'),
disp('HiSine'),
disp('LoSine'),
disp('LinChirp'),
disp('TwoChirp'),
disp('QuadChirp'),
disp('MishMash'),
disp('WernerSorrows'),
disp('Leopold'),
disp('Riemann'),
disp('HypChirps'),
disp('LinChirps'),
disp('Chirps'),
disp('sineoneoverx'),
disp('Cusp2'),
disp('SmoothCusp'),
disp('Gabor'),
disp('Piece-Regular');
disp('Piece-Polynomial');
disp('Gaussian');
end
%
% Originally made by David L. Donoho.
% Function has been enhanced.
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
|
github
|
jacksky64/imageProcessing-master
|
load_image.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/toolbox/load_image.m
| 20,946 |
utf_8
|
f51ce8bb55fa19a67c87b6d1249cb2a5
|
function M = load_image(type, n, options)
% load_image - load benchmark images.
%
% M = load_image(name, n, options);
%
% name can be:
% Synthetic images:
% 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line',
% 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle',
% 'parabola', 'sin', 'phantom', 'circ_oscil',
% 'fnoise' (1/f^alpha noise).
% Natural images:
% 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
n = 512;
end
options.null = 0;
type = lower(type);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters for geometric objects
eta = getoptions(options, 'eta', .1);
gamma = getoptions(options, 'gamma', 1/sqrt(2));
radius = getoptions(options, 'radius', 10);
center = getoptions(options, 'center', [0 0]);
center1 = getoptions(options, 'center1', [0 0]);
w = getoptions(options, 'tube_width', 0.06);
nb_points = getoptions(options, 'nb_points', 9);
scaling = getoptions(options, 'scaling', 1);
theta = getoptions(options, 'theta', 30 * 2*pi/360);
eccentricity = getoptions(options, 'eccentricity', 1.3);
sigma = getoptions(options, 'sigma', 0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the line, can be vertical / horizontal / diagonal / any
if strcmp(type, 'line_vertical')
eta = 0.5; % translation
gamma = 0; % slope
elseif strcmp(type, 'line_horizontal')
eta = 0.5; % translation
gamma = Inf; % slope
elseif strcmp(type, 'line_diagonal')
eta = 0; % translation
gamma = 1; % slope
end
if strcmp(type(1:min(12,end)), 'square-tube-')
k = str2double(type(13:end));
c1 = [.22 .5]; c2 = [1-c1(1) .5];
eta = 1.5;
r1 = [c1 c1] + .21*[-1 -eta 1 eta];
r2 = [c2 c2] + .21*[-1 -eta 1 eta];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
if mod(k,2)==0
sel = n/2-k/2+1:n/2+k/2;
else
sel = n/2-(k-1)/2:n/2+(k-1)/2;
end
M( round(.25*n:.75*n), sel ) = 1;
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(type)
case 'constant'
M = ones(n);
case 'ramp'
x = linspace(0,1,n);
[Y,M] = meshgrid(x,x);
case 'bump'
s = getoptions(options, 'bump_size', .5);
c = getoptions(options, 'center', [0 0]);
if length(s)==1
s = [s s];
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
X = (X-c(1))/s(1); Y = (Y-c(2))/s(2);
M = exp( -(X.^2+Y.^2)/2 );
case 'periodic'
x = linspace(-pi,pi,n)/1.1;
[Y,X] = meshgrid(x,x);
f = getoptions(options, 'freq', 6);
M = (1+cos(f*X)).*(1+cos(f*Y));
case {'letter-x' 'letter-v' 'letter-z' 'letter-y'}
M = create_letter(type(8), radius, n);
case 'l'
r1 = [.1 .1 .3 .9];
r2 = [.1 .1 .9 .4];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
case 'ellipse'
c1 = [0.15 0.5];
c2 = [0.85 0.5];
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2);
M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) );
case 'ellipse-thin'
options.eccentricity = 1.06;
M = load_image('ellipse', n, options);
case 'ellipse-fat'
options.eccentricity = 1.3;
M = load_image('ellipse', n, options);
case 'square-tube'
c1 = [.25 .5];
c2 = [.75 .5];
r1 = [c1 c1] + .18*[-1 -1 1 1];
r2 = [c2 c2] + .18*[-1 -1 1 1];
r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) );
case 'square-tube-1'
options.tube_width = 0.03;
M = load_image('square-tube', n, options);
case 'square-tube-2'
options.tube_width = 0.06;
M = load_image('square-tube', n, options);
case 'square-tube-3'
options.im = 0.09;
M = load_image('square-tube', n, options);
case 'polygon'
theta = sort( rand(nb_points,1)*2*pi );
radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93);
points = [cos(theta) sin(theta)] .* repmat(radius, 1,2);
points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:);
M = draw_polygons(zeros(n),0.8,{points'});
[x,y] = ind2sub(size(M),find(M));
p = 100; m = length(x);
lambda = linspace(0,1,p);
X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]);
Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]);
I = round(X) + (round(Y)-1)*n;
M = zeros(n); M(I) = 1;
case 'polygon-8'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-10'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-12'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'pacman'
options.radius = 0.45;
options.center = [.5 .5];
M = load_image('disk', n, options);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
T =atan2(Y,X);
M = M .* (1-(abs(T-pi/2)<theta/2));
case 'square-hole'
options.radius = 0.45;
M = load_image('disk', n, options);
options.scaling = 0.5;
M = M - load_image('polygon-10', n, options);
case 'grid-circles'
if isempty(n)
n = 256;
end
f = getoptions(options, 'frequency', 30);
eta = getoptions(options, 'width', .3);
x = linspace(-n/2,n/2,n) - round(n*0.03);
y = linspace(0,n,n);
[Y,X] = meshgrid(y,x);
R = sqrt(X.^2+Y.^2);
theta = 0.05*pi/2;
X1 = cos(theta)*X+sin(theta)*Y;
Y1 = -sin(theta)*X+cos(theta)*Y;
A1 = abs(cos(2*pi*R/f))<eta;
A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta );
M = A1;
M(X1>0) = A2(X1>0);
case 'chessboard1'
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (2*(Y>=0)-1).*(2*(X>=0)-1);
case 'chessboard'
width = getoptions(width, round(n/16) );
[Y,X] = meshgrid(0:n-1,0:n-1);
M = mod( floor(X/width)+floor(Y/width), 2 ) == 0;
case 'square'
if ~isfield( options, 'radius' )
radius = 0.6;
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M = max( abs(X),abs(Y) )<radius;
case 'squareregular'
M = rescale(load_image('square',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'regular1'
options.alpha = 1;
M = load_image('fnoise',n,options);
case 'regular2'
options.alpha = 2;
M = load_image('fnoise',n,options);
case 'regular3'
options.alpha = 3;
M = load_image('fnoise',n,options);
case 'sparsecurves'
options.alpha = 3;
M = load_image('fnoise',n,options);
M = rescale(M);
ncurves = 3;
M = cos(2*pi*ncurves);
case 'geometrical'
J = getoptions(options, 'Jgeometrical', 4);
sgeom = 100*n/256;
options.bound = 'per';
A = ones(n);
for j=0:J-1
B = A;
for k=1:2^j
I = find(B==k);
U = perform_blurring(randn(n),sgeom,options);
s = median(U(I));
I1 = find( (B==k) & (U>s) );
I2 = find( (B==k) & (U<=s) );
A(I1) = 2*k-1;
A(I2) = 2*k;
end
end
M = A;
case 'lic-texture'
disp('Computing random tensor field.');
options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256);
T = compute_tensor_field_random(n,options);
Flow = perform_tensor_decomp(T); % extract eigenfield.
options.isoriented = 0; % no orientation in streamlines
% initial texture
lic_width = getoptions(options, 'lic_width', 0);
M0 = perform_blurring(randn(n),lic_width);
M0 = perform_histogram_equalization( M0, 'linear');
options.histogram = 'linear';
options.dt = 0.4;
options.M0 = M0;
options.verb = 1;
options.flow_correction = 1;
options.niter_lic = 3;
w = 30;
M = perform_lic(Flow, w, options);
case 'square_texture'
M = load_image('square',n);
M = rescale(M);
% make a texture patch
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta );
case 'tv-image'
M = rand(n);
tau = compute_total_variation(M);
options.niter = 400;
[M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options);
M = perform_histogram_equalization(M,'linear');
case 'oscillatory_texture'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M = sin( x * 2*pi / eta );
case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'}
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
if gamma~=Inf
M = (X-eta) - gamma*Y < 0;
else
M = (Y-eta) < 0;
end
case 'grating'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
theta = getoptions(options, 'theta', .2);
freq = getoptions(options, 'freq', .2);
X = cos(theta)*X + sin(theta)*Y;
M = sin(2*pi*X/freq);
case 'disk'
if ~isfield( options, 'radius' )
radius = 0.35;
end
if ~isfield( options, 'center' )
center = [0.5, 0.5]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'diskregular'
M = rescale(load_image('disk',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'quarterdisk'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'fading_contour'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
theta = 2/pi*atan2(Y,X);
h = 0.5;
M = exp(-(1-theta).^2/h^2).*M;
case '3contours'
radius = 1.3;
center = [-1, 1];
radius1 = 0.8;
center1 = [0, 0];
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2;
M = f1 + 0.5*f2.*(1-f1);
case 'line_circle'
gamma = 1/sqrt(2);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M1 = double( X>gamma*Y+0.25 );
M2 = X.^2 + Y.^2 < 0.6^2;
M = 20 + max(0.5*M1,M2) * 216;
case 'fnoise'
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
alpha = getoptions(options, 'alpha', 1);
M = gen_noisy_image(n,alpha);
case 'gaussiannoise'
% generate an image of filtered noise with gaussian
sigma = getoptions(options, 'sigma', 10);
M = randn(n);
m = 51;
h = compute_gaussian_filter([m m],sigma/(4*n),[n n]);
M = perform_convolution(M,h);
return;
case {'bwhorizontal','bwvertical','bwcircle'}
[Y,X] = meshgrid(0:n-1,0:n-1);
if strcmp(type, 'bwhorizontal')
d = X;
elseif strcmp(type, 'bwvertical')
d = Y;
elseif strcmp(type, 'bwcircle')
d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 );
end
if isfield(options, 'stripe_width')
stripe_width = options.stripe_width;
else
stripe_width = 5;
end
if isfield(options, 'black_prop')
black_prop = options.black_prop;
else
black_prop = 0.5;
end
M = double( mod( d/(2*stripe_width),1 )>=black_prop );
case 'parabola'
% curvature
c = getoptions(c, 'c', .1);
% angle
theta = getoptions(options, 'theta', pi/sqrt(2));
x = -0.5:1/(n-1):0.5;
[Y,X] = meshgrid(x,x);
Xs = X*cos(theta) + Y*sin(theta);
Y =-X*sin(theta) + Y*cos(theta); X = Xs;
M = Y>c*X.^2;
case 'sin'
[Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1);
M = Y >= 0.6*cos(pi*X);
M = double(M);
case 'circ_oscil'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
R = sqrt(X.^2+Y.^2);
M = cos(R.^3*50);
case 'phantom'
M = phantom(n);
case 'periodic_bumps'
nbr_periods = getoptions(options, 'nbr_periods', 8);
theta = getoptions(options, 'theta', 1/sqrt(2));
skew = getoptions(options, 'skew', 1/sqrt(2) );
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];
B = [1 skew; 0 1];
T = B*A;
x = (0:n-1)*2*pi*nbr_periods/(n-1);
[Y,X] = meshgrid(x,x);
pos = [X(:)'; Y(:)'];
pos = T*pos;
X = reshape(pos(1,:), n,n);
Y = reshape(pos(2,:), n,n);
M = cos(X).*sin(Y);
case 'noise'
sigma = getoptions(options, 'sigma', 1);
M = randn(n) * sigma;
case 'disk-corner'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
rho = .3; eta = .1;
M1 = rho*X+eta<Y;
c = [0 .2]; r = .85;
d = (X-c(1)).^2 + (Y-c(2)).^2;
M2 = d<r^2;
M = M1.*M2;
otherwise
ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'};
for i=1:length(ext)
name = [type '.' ext{i}];
if( exist(name) )
M = imread( name );
M = double(M);
if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2
M = image_resize(M,n,n);
end
if strcmp(type, 'peppers-bw')
M(:,1) = M(:,2);
M(1,:) = M(2,:);
end
if sigma>0
M = perform_blurring(M,sigma);
end
return;
end
end
error( ['Image ' type ' does not exists.'] );
end
M = double(M);
if sigma>0
M = perform_blurring(M,sigma);
end
M = rescale(M);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = create_letter(a, r, n)
c = 0.2;
p1 = [c;c];
p2 = [c; 1-c];
p3 = [1-c; 1-c];
p4 = [1-c; c];
p4 = [1-c; c];
pc = [0.5;0.5];
pu = [0.5; c];
switch a
case 'x'
point_list = { [p1 p3] [p2 p4] };
case 'z'
point_list = { [p2 p3 p1 p4] };
case 'v'
point_list = { [p2 pu p3] };
case 'y'
point_list = { [p2 pc pu] [pc p3] };
end
% fit image
for i=1:length(point_list)
a = point_list{i}(2:-1:1,:);
a(1,:) = 1-a(1,:);
point_list{i} = round( a*(n-1)+1 );
end
M = draw_polygons(zeros(n),r,point_list);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_polygons(mask,r,point_list)
sk = mask*0;
for i=1:length(point_list)
pl = point_list{i};
for k=2:length(pl)
sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_line(sk,x1,y1,x2,y2,r)
n = size(sk,1);
[Y,X] = meshgrid(1:n,1:n);
q = 100;
t = linspace(0,1,q);
x = x1*t+x2*(1-t); y = y1*t+y2*(1-t);
if r==0
x = round( x ); y = round( y );
sk( x+(y-1)*n ) = 1;
else
for k=1:q
I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 );
sk(I) = 1;
end
end
function M = gen_noisy_image(n,alpha)
% gen_noisy_image - generate a noisy cloud-like image.
%
% M = gen_noisy_image(n,alpha);
%
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin<1
n = 128;
end
if nargin<2
alpha = 1.5;
end
if mod(n(1),2)==0
x = -n/2:n/2-1;
else
x = -(n-1)/2:(n-1)/2;
end
[Y,X] = meshgrid(x,x);
d = sqrt(X.^2 + Y.^2) + 0.1;
f = rand(n)*2*pi;
M = (d.^(-alpha)) .* exp(f*1i);
% M = real(ifft2(fftshift(M)));
M = ifftshift(M);
M = real( ifft2(M) );
function y = gen_signal_2d(n,alpha)
% gen_signal_2d - generate a 2D C^\alpha signal of length n x n.
% gen_signal_2d(n,alpha) generate a 2D signal C^alpha.
%
% The signal is scale in [0,1].
%
% Copyright (c) 2003 Gabriel Peyr?
% new new method
[Y,X] = meshgrid(0:n-1, 0:n-1);
A = X+Y+1;
B = X-Y+n+1;
a = gen_signal(2*n+1, alpha);
b = gen_signal(2*n+1, alpha);
y = a(A).*b(B);
% M = a(1:n)*b(1:n)';
return;
% new method
h = (-n/2+1):(n/2); h(n/2)=1;
[X,Y] = meshgrid(h,h);
h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2);
h = h .* exp( 2i*pi*rand(n,n) );
h = fftshift(h);
y = real( ifft2(h) );
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
return;
%% old code
y = rand(n,n);
y = y - mean(mean(y));
for i=1:alpha
y = cumsum(cumsum(y)')';
y = y - mean(mean(y));
end
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
function newimg = image_resize(img,p1,q1,r1)
% image_resize - resize an image using bicubic interpolation
%
% newimg = image_resize(img,nx,ny,nz);
% or
% newimg = image_resize(img,newsize);
%
% Works for 2D, 2D 2 or 3 channels, 3D images.
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin==2
% size specified as an array
q1 = p1(2);
if length(p1)>2
r1 = p1(3);
else
r1 = size(img,3);
end
p1 = p1(1);
end
if nargin<4
r1 = size(img,3);
end
if ndims(img)<2 || ndims(img)>3
error('Works only for grayscale or color images');
end
if ndims(img)==3 && size(img,3)<4
% RVB image
newimg = zeros(p1,q1, size(img,3));
for m=1:size(img,3)
newimg(:,:,m) = image_resize(img(:,:,m), p1, q1);
end
return;
elseif ndims(img)==3
p = size(img,1);
q = size(img,2);
r = size(img,3);
[Y,X,Z] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1), (0:r-1)/(r-1) );
[YI,XI,ZI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1), (0:r1-1)/(r1-1) );
newimg = interp3( Y,X,Z, img, YI,XI,ZI ,'cubic');
return;
end
p = size(img,1);
q = size(img,2);
[Y,X] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1) );
[YI,XI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1) );
newimg = interp2( Y,X, img, YI,XI ,'cubic');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = draw_rectangle(r,n)
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
|
github
|
jacksky64/imageProcessing-master
|
perform_thresholding.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/toolbox/perform_thresholding.m
| 2,482 |
utf_8
|
0f3a43687bf3809b0789cace4871a1e6
|
function y = perform_thresholding(x, t, type)
% perform_thresholding - perform hard or soft thresholding
%
% y = perform_thresholding(x, t, type);
%
% type is either 'hard' or 'soft' or 'semisoft'
% t is the threshold
%
% works also for complex data, and for cell arrays.
%
% if type is 'strict' then it keeps the t largest entry in each
% column of x.
%
% Copyright (c) 2006 Gabriel Peyre
if nargin<3
type = 'hard';
end
if iscell(x)
% for cell arrays
for i=1:size(x,1)
for j=1:size(x,2)
y{i,j} = perform_thresholding(x{i,j},t, type);
end
end
return;
end
switch lower(type)
case {'hard', ''}
y = perform_hard_thresholding(x,t);
case 'soft'
y = perform_soft_thresholding(x,t);
case 'semisoft'
y = perform_semisoft_thresholding(x,t);
case 'strict'
y = perform_strict_thresholding(x,t);
otherwise
error('Unkwnown thresholding type.');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X = perform_strict_thresholding(X,s)
%% keep only the s largest coefficients in each column of X
v = sort(abs(X)); v = v(end:-1:1,:);
v = v(round(s),:);
v = repmat(v, [size(X,1) 1]);
X = X .* (abs(X)>=v);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_hard_thresholding(x,t)
t = t(1);
y = x .* (abs(x) > t);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_soft_thresholding(x,t)
if not(isreal(x))
% complex threshold
d = abs(x);
d(d<eps) = 1;
x = x./d .* perform_soft_thresholding(d,t);
end
t = t(1);
s = abs(x) - t;
s = (s + abs(s))/2;
y = sign(x).*s;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_semisoft_thresholding(x,t)
if length(t)==1
t = [t 2*t];
end
t = sort(t);
y = x;
y(abs(x)<t(1)) = 0;
I = find(abs(x)>=t(1) & abs(x)<t(2));
y( I ) = sign(x(I)) .* t(2)/(t(2)-t(1)) .* (abs(x(I))-t(1));
|
github
|
jacksky64/imageProcessing-master
|
histo.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/toolbox/histo.m
| 1,835 |
utf_8
|
e76d8956cd1d59f518a8146dc5145f9b
|
% [N,X] = histo(MTX, nbinsOrBinsize, binCenter);
%
% Compute a histogram of (all) elements of MTX. N contains the histogram
% counts, X is a vector containg the centers of the histogram bins.
%
% nbinsOrBinsize (optional, default = 101) specifies either
% the number of histogram bins, or the negative of the binsize.
%
% binCenter (optional, default = mean2(MTX)) specifies a center position
% for (any one of) the histogram bins.
%
% How does this differ from MatLab's HIST function? This function:
% - allows uniformly spaced bins only.
% +/- operates on all elements of MTX, instead of columnwise.
% + is much faster (approximately a factor of 80 on my machine).
% + allows specification of number of bins OR binsize. Default=101 bins.
% + allows (optional) specification of binCenter.
% Eero Simoncelli, 3/97.
function [N, X] = histo(mtx, nbins, binCtr)
%% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD)
fprintf(1,'WARNING: You should compile the MEX version of "histo.c",\n found in the MEX subdirectory of matlabPyrTools, and put it in your matlab path. It is MUCH faster.\n');
mtx = mtx(:);
%------------------------------------------------------------
%% OPTIONAL ARGS:
[mn,mx] = range2(mtx);
if (exist('binCtr') ~= 1)
binCtr = mean(mtx);
end
if (exist('nbins') == 1)
if (nbins < 0)
binSize = -nbins;
else
binSize = ((mx-mn)/nbins);
tmpNbins = round((mx-binCtr)/binSize) - round((mn-binCtr)/binSize);
if (tmpNbins ~= nbins)
warning('Using %d bins instead of requested number (%d)',tmpNbins,nbins);
end
end
else
binSize = ((mx-mn)/101);
end
firstBin = binCtr + binSize*round( (mn-binCtr)/binSize );
tmpNbins = round((mx-binCtr)/binSize) - round((mn-binCtr)/binSize);
bins = firstBin + binSize*[0:tmpNbins];
[N, X] = hist(mtx, bins);
|
github
|
jacksky64/imageProcessing-master
|
ltsa.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_dimreduc/ltsa.m
| 2,653 |
utf_8
|
39339d59acc8335882d3bf9aeeed65f0
|
% ltsa - local tangent planes alignement
%
% [T,NI] = ltsa(X,d,K);
%
% X is the (d,n) n data points in R^d.
% d is the output dimensionnality.
% K is the number of nearest neighbors.
%
% Written by Zhenyue Zhang & Hongyuan Zha, 2004.
% Reference: http://epubs.siam.org/sam-bin/dbq/article/41915
function [T,NI] = ltsa(X,d,K,NI)
[m,N] = size(X); % m is the dimensionality of the input sample points.
% Step 0: Neighborhood Index
if nargin<4
if length(K)==1
K = repmat(K,[1,N]);
end;
NI = cell(1,N);
if m>N
if 0
a = sum(X.*X);
dist2 = sqrt(repmat(a',[1 N]) + repmat(a,[N 1]) - 2*(X'*X));
for i=1:N
% Determine ki nearest neighbors of x_j
[dist_sort,J] = sort(dist2(:,i));
Ii = J(1:K(i));
NI{i} = Ii;
end;
else
% use fast code
options.exlude_self = 1;
[D1,nn_list] = compute_nn_distance(X,K(1), options);
for i=1:N
NI{i} = nn_list(i,:);
end
end
else
if 0
for i=1:N
% Determine ki nearest neighbors of x_j
x = X(:,i); ki = K(i);
dist2 = sum((X-repmat(x,[1 N])).^2,1);
[dist_sort,J] = sort(dist2);
Ii = J(1:ki);
NI{i} = Ii;
end;
else
% use fast code
options.exlude_self = 1;
[D1,nn_list] = compute_nn_distance(X,K(1), options);
for i=1:N
NI{i} = nn_list(i,:);
end
end
end;
else
K = zeros(1,N);
for i=1:N
K(i) = length(NI{i});
end;
end;
% Step 1: local information
BI = {};
Thera = {};
for i=1:N
% Compute the d largest right singular eigenvectors of the centered matrix
Ii = NI{i}; ki = K(i);
Xi = X(:,Ii)-repmat(mean(X(:,Ii),2),[1,ki]);
W = Xi'*Xi; W = (W+W')/2;
[Vi,Si] = schur(W);
[s,Ji] = sort(-diag(Si));
Vi = Vi(:,Ji(1:d));
% construct Gi
Gi = [repmat(1/sqrt(ki),[ki,1]) Vi];
% compute the local orthogonal projection Bi = I-Gi*Gi'
% that has the null space span([e,Theta_i^T]).
BI{i} = eye(ki)-Gi*Gi';
end;
B = speye(N);
for i=1:N
Ii = NI{i};
B(Ii,Ii) = B(Ii,Ii)+BI{i};
B(i,i) = B(i,i)-1;
end;
B = (B+B')/2;
options.disp = 0;
options.isreal = 1;
options.issym = 1;
[U,D] = eigs(B,d+2,0,options);
lambda = diag(D);
[lambda_s,J] = sort(abs(lambda));
U = U(:,J); lambda = lambda(J);
T = U(:,2:d+1)';
|
github
|
jacksky64/imageProcessing-master
|
hlle.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_dimreduc/hlle.m
| 5,717 |
utf_8
|
c4f0f3986f804846fe8c8137aed78dd8
|
function [Y, mse] = HLLE(X,k,d)
%HLLE Runs the standard Hessian LLE implementation of Hessian Eigenmaps
%
% X is the high-dimensional data to be processed
% k is the number of nearest neighbor points to be used
% if k is a scalar, same size used at all points. if k is a vector of
% length N, neighborhood N(i) will be assigned k(i) nearest neighbors
%
% d is the number of dimensions to embed X in
%
% Y is the output embedded data
% mse is the sum (at each neighborhood used) of the eigenvalues(d+2:end)
% of the local coordinate representation. used for adaptive neighborhood
% restructuring
% Example:
% N=1000; k=12; d=2;
% tt = (3*pi/2)*(1+2*rand(1,N)); height = 21*rand(1,N);
% X = [tt.*cos(tt); height; tt.*sin(tt)];
% [Y, mse] = HLLE(X,k,d);
% C. Grimes and D. Donoho, March 2003
% Last Revision:
% Version 1.0
%get data size
N = size(X,2);
%check for constant neighborhood size
if max(size(k)) ==1
kvec = repmat(k,N,1);
elseif max(size(k)) == N
kvec=k;
else
error('Neighborhood Vector Size does not match data');
end;
disp(['-->Running HLLE for ', num2str(N), ' points']);
disp('-->Computing HLLE neighbors');
%Compute Nearest neighbors
D1 = L2_distance(X,X,1);
dim = size(X,1);
nind = repmat(0, size(D1,1), size(D1,2));
%extra term count for quadratic form
dp = d*(d+1)/2;
W = repmat(0,dp*N,N);
if(mean(k)>d)
disp('[note: k>d; regularization will be used]');
tol=1e-3; % regularlizer in case constrained fits are ill conditioned
else
tol=0;
end;
for i=1:N
tmp = D1(:,i);
[ts, or] = sort(tmp);
%take k nearest neighbors
nind(or(2:kvec(i)+1),i) = 1;
thisx = X(:,or(2:kvec(i)+1));
%center using the mean
thisx = thisx - repmat(mean(thisx')',1,kvec(i));
%compute local coordinates
[U,D,Vpr] = svd(thisx);
V = Vpr(:,1:d);
%Neighborhood diagnostics
vals = diag(D);
mse(i) = sum(vals(d+1:end));
%build Hessian estimator
clear Yi; clear Pii;
ct = 0;
for mm=1:d
startp = V(:,mm);
for nn=1:length(mm:d)
indles = mm:d;
Yi(:,ct+nn) = startp.*(V(:,indles(nn)));
end;
ct = ct+length(mm:d);
end;
Yi = [repmat(1,kvec(i),1), V, Yi];
%orthogonalize linear and quadratic forms
[Yt, Orig] = mgs(Yi);
Pii = Yt(:,d+2:end)';
%double check weights sum to 1
for j=1:dp
if sum(Pii(j,:)) >0.0001
tpp = Pii(j,:)./sum(Pii(j,:));
else
tpp = Pii(j,:);
end;
%fill weight matrix
W((i-1)*dp+j, or(2:kvec(i)+1)) = tpp;
end;
end;
%%%%%%%%%%%%%%%%%%%%Compute eigenanalysis of W
disp('-->Computing HLLE embedding');
G=W'*W;
G = sparse(G);
options.disp = 0;
options.isreal = 1;
options.issym = 1;
%tol=1e-3; %sometimes useful for pathological fits
tol=0;
% [Yo,eigenvals] = eigs(G,d+1,tol,options); % old code
[Yo,eigenvals] = eigs(G,d+1,'SM',options);
Y = Yo(:,1:d)'*sqrt(N); % bottom evect is [1,1,1,1...] with eval 0
disp('-->Orienting Coordinates');
%compute final coordinate alignment
R = Y'*Y;
R2 = R^(-1/2);
Y = Y*R2;
function d = L2_distance(a,b,df)
% L2_DISTANCE - computes Euclidean distance matrix
%
% E = L2_distance(A,B)
%
% A - (DxM) matrix
% B - (DxN) matrix
% df = 1, force diagonals to be zero; 0 (default), do not force
%
% Returns:
% E - (MxN) Euclidean distances between vectors in A and B
%
%
% Description :
% This fully vectorized (VERY FAST!) m-file computes the
% Euclidean distance between two vectors by:
%
% ||A-B|| = sqrt ( ||A||^2 + ||B||^2 - 2*A.B )
%
% Example :
% A = rand(400,100); B = rand(400,200);
% d = distance(A,B);
% Author : Roland Bunschoten
% University of Amsterdam
% Intelligent Autonomous Systems (IAS) group
% Kruislaan 403 1098 SJ Amsterdam
% tel.(+31)20-5257524
% [email protected]
% Last Rev : Wed Oct 20 08:58:08 MET DST 1999
% Tested : PC Matlab v5.2 and Solaris Matlab v5.3
% Copyright notice: You are free to modify, extend and distribute
% this code granted that the author of the original code is
% mentioned as the original author of the code.
% Fixed by JBT (3/18/00) to work for 1-dimensional vectors
% and to warn for imaginary numbers. Also ensures that
% output is all real, and allows the option of forcing diagonals to
% be zero.
if (nargin < 2)
error('Not enough input arguments');
end
if (nargin < 3)
df = 0; % by default, do not force 0 on the diagonal
end
if (size(a,1) ~= size(b,1))
error('A and B should be of same dimensionality');
end
if ~(isreal(a)*isreal(b))
disp('Warning: running distance.m with imaginary numbers. Results may be off.');
end
if (size(a,1) == 1)
a = [a; zeros(1,size(a,2))];
b = [b; zeros(1,size(b,2))];
end
aa=sum(a.*a); bb=sum(b.*b); ab=a'*b;
d = sqrt(repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab);
% make sure result is all real
d = real(d);
% force 0 on the diagonal?
if (df==1)
d = d.*(1-eye(size(d)));
end
function [Q, R] = mgs(A);
%
% modified Gram-Schmidt. this is a more stable way to compute a
% qr factorization
%
[m, n] = size(A);
%
% we assume that m>= n.
%
V = A;
R = zeros(n,n);
for i=1:n
R(i,i) = norm(V(:,i));
V(:,i) = V(:,i)/R(i,i);
if (i < n)
for j = i+1:n
R(i,j) = V(:,i)' * V(:,j);
V(:,j) = V(:,j) - R(i,j) * V(:,i);
end
end
end
Q = V;
|
github
|
jacksky64/imageProcessing-master
|
qslim.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/qslim.m
| 13,152 |
utf_8
|
2ab54ac7408e720642cbe21d8b6927bd
|
function [NFV,smf_fname] = qslim(FV,varargin);
%QSLIM - Mesh simplification, wrapper function for Garland's QSLIM executable program
% function [NFV,smf_fname] = qslim(FV,varargin);
% varargin should be entered in pairs '<option>','<arg>'.
% Valid pairs used in this wrapper are:
%
% '-t', <n>
%
% Specify the desired number of faces in the simplified model. You are not
% guaranteed to get exactly the number you ask for, but it should generally
% be within 1-2 faces of the target.
%
% '-q',[]
%
% Run quietly. QSlim will not output the usual status information.
%
% '-O', <n> (capital O, order)
%
% Specify the policy for selecting the target position for edge
% contractions. The following levels of optimization are available:
%
% 3 -- Pick point which minimizes error [default].
% 2 -- Pick best point along edge.
% 1 -- Pick best of endpoints or midpoint.
% 0 -- Pick best of the two endpoints.
%
% '-m', <penalty>
%
% Set the penalty for bad meshes (default is 1)
%
% '-c', <ratio>
%
% Set the desired compactness ratio (default is 0)
%
% '-B', <weight>
%
% Specifies the weight assigned to boundary constraint planes. The default
% value is currently 1000. Specify a weight of 0 to disable boundary
% constraints entirely.
%
% '-W', <n>
%
% Select the quadric weighting policy. Available policies are:
%
% 0 -- Weight all quadrics uniformly
% 1 -- Weight by area of contributing triangle [default]
% 2 -- Weight by angle around vertex
%
% '-j',[]
%
% Only perform contractions that do not remove any faces. You can use this
% feature in conjunction with custom edge sets (see below) to effect a form
% of stitching. This is not terribly reliable, it's just an experimental
% feature.
%
% '-F',[]
%
% This will cause the simplification algorithm to use iterative face
% contraction rather than iterative edge contraction. Generally speaking,
% this has the following effects:
%
% - Simplification is faster
% - Less memory is consumed
% - Geometric quality of the results is reduced
%
% '-o',<fname>
%
% The output simplified file, default is temp_qslim_out.smf.
%
% Wrapper option:
%
% If FV is a string, then that smf file is read, rather than writing out FV to
% a file. Use the -save option below to write the structure FV to a file.
% Saves execution time on subsequent passes
%
% '-save', <fname>,
%
% The filename to which to write the structure FV. Default is temp_qslim.smf.
%
% Defaults are set to -t, 2000, -m, 1000, -o temp_qslime_out.smf
%
% See http://graphics.cs.uiuc.edu/~garland/software/qslim.html
% http://graphics.cs.uiuc.edu/~garland/research/thesis.html
% for details on QSLIM and dissertation with technical details.
%
% Examples
%
% reduce to 2000 faces, with mesh penalty of 1000
% NFV = qslim(FV);
%
% write the FV to the brain.smf file, return 10,000 faces
% NFV = qslim(FV,'-save','brain.smf','-t',10000);
%
% load the brain.smf file for the FV information, quiet mode, compactness ratio
% of 1
% NFV = qslim('brain.smf','-q',[],'-c',1);
%
%
% See also REDUCEPATCH
%<autobegin> ---------------------- 27-Jun-2005 10:45:28 -----------------------
% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------
%
% CATEGORY: Utility - General
%
% Alphabetical list of external functions (non-Matlab):
% toolbox\load_smf.m
% toolbox\save_smf.m
%
% At Check-in: $Author: Mosher $ $Revision: 7 $ $Date: 6/27/05 9:00a $
%
% This software is part of BrainStorm Toolbox Version 27-June-2005
%
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
% University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
% Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
% CNRS, Hopital de la Salpetriere, Paris, France
%
% See BrainStorm website at http://neuroimage.usc.edu for further information.
%
% Copyright (c) 2005 BrainStorm by the University of Southern California
% This software distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 27-Jun-2005 10:45:28 -----------------------
% QSLIM program by
%
% Michael Garland
% Department of Computer Science
% University of Illinois
% 201 North Goodwin Avenue
% Urbana, IL 61801-2302
%
% Wrapper author:
% John C. Mosher
% ----------------------------- Script History ---------------------------------
% JCM 24-May-2004 Creation
% ----------------------------- Script History ---------------------------------
DEFAULT_INPUT = 'temp_qslim.smf'; % unless the user specifies in FV
if isstr(FV),
% user specified an input file instead of a FV structure
InputFile = FV;
else
InputFile = DEFAULT_INPUT; % default
end
if ~ispc,
error(sprintf('Unable to run QSLIM from this %s computer.',computer));
end
% where is the QSLIM on this computer
QSLIM = which('qslim.exe');
if isempty(QSLIM),
error(sprintf('Cannot find qslim.exe in the public toolbox'));
end
OPERATION = varargin(1:2:end);
ARGUMENT = varargin(2:2:end);
if strmatch('-q',OPERATION),
VERBOSE = 0; % silent running requested
else
VERBOSE = 1;
end
% setup defaults
OutputStr = struct('option',[],'arg',[]);
OutputStr(1).option = '-t'; % wrapper argument
OutputStr(1).arg = 2000; % number of triangles generated
OutputStr(2).option = '-o'; % wrapper argument
OutputStr(2).arg = 'temp_qslim_out.smf'; % default
OutputStr(3).option = '-m';
OutputStr(3).arg = 1000; % helps prevent mesh badness
for i = 1:length(OPERATION),
% have we already set this output?
ndx = strmatch(OPERATION{i},{OutputStr.option});
if isempty(ndx),
% haven't defined
% is it valid?
switch OPERATION{i}
case {'-O','-B','-W','-t','-F','-o','-I','-m','-c','-r','-M','-q','-j','-h'}
% okay
OutputStr(end + 1).option = OPERATION{i};
OutputStr(end).arg = ARGUMENT{i};
case '-save'
InputFile = ARGUMENT{i}; % change the input file specification
otherwise
disp(sprintf('unknown qslim option %s',OPERATION{i}))
end
else
% already defined, replace
OutputStr(ndx).arg = ARGUMENT{i};
end
end
% now make command string
commandstr = sprintf('"%s"',QSLIM); % initiate the start
for i = 1:length(OutputStr),
switch OutputStr(i).option
case {'-o','-I'}
% string arg
commandstr = sprintf(' %s %s %s',commandstr,OutputStr(i).option,OutputStr(i).arg);
case {'-q','-j','-F','-r','-h'}
% empty argument
commandstr = sprintf(' %s %s',commandstr,OutputStr(i).option);
case {'-B','-W','-t','-m'}
% assume integer argument
commandstr = sprintf(' %s %s %.0f',commandstr,OutputStr(i).option,OutputStr(i).arg);
case {'-c'}
% floating point argument
commandstr = sprintf(' %s %s %f',commandstr,OutputStr(i).option,OutputStr(i).arg);
end
end
% where was the output?
ndx = strmatch('-o',{OutputStr.option});
OutputFile = OutputStr(ndx).arg;
commandstr = sprintf('%s %s',commandstr,InputFile); % the input file
if ~isstr(FV),
if VERBOSE
disp(sprintf('Writing out FV to SMF file %s. ..',InputFile))
end
save_smf(InputFile,FV);
end
if VERBOSE
disp('Executing . . .')
disp(commandstr)
end
dos(commandstr);
drawnow
if VERBOSE
disp(sprintf('Reading results from %s . . .',OutputFile))
end
NFV = load_smf(OutputFile);
function FV = load_smf(fname);
%LOAD_SMF - Load a simply written SMF file into the faces vertices structure
% function FV = load_smf(fname);
%
% Each line is one of
% # comment
% f <i> <j> <k>
% v <x> <y> <z>
% otherwise the line is ignored
%
% See also LOAD_SMF
%<autobegin> ---------------------- 27-Jun-2005 10:44:59 -----------------------
% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------
%
% CATEGORY: Data Processing
%
% At Check-in: $Author: Mosher $ $Revision: 7 $ $Date: 6/27/05 9:00a $
%
% This software is part of BrainStorm Toolbox Version 27-June-2005
%
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
% University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
% Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
% CNRS, Hopital de la Salpetriere, Paris, France
%
% See BrainStorm website at http://neuroimage.usc.edu for further information.
%
% Copyright (c) 2005 BrainStorm by the University of Southern California
% This software distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 27-Jun-2005 10:44:59 -----------------------
% Author: John C. Mosher, Ph.D.
% ----------------------------- Script History ---------------------------------
% JCM 24-May-2004 Creation
% ----------------------------- Script History ---------------------------------
fid = fopen(fname,'rt');
% preallocate
FV.faces = zeros(200000,3);
FV.vertices = zeros(100000,3);
iV = 0; % initialize vertices counter
iF = 0; % faces counter
while 1
tline = fgetl(fid);
if ~ischar(tline),
break
end
[OP,ARG] = strtok(tline);
switch OP
case {'begin','end'}
% ignore
case 'v'
iV = iV + 1;
FV.vertices(iV,:) = sscanf(ARG,'%g %g %g')';
case 'f'
iF = iF + 1;
FV.faces(iF,:) = sscanf(ARG,'%f %f %f')';
case '#'
% comment line
disp(tline);
otherwise
% do nothing
end
end
fclose(fid);
FV.vertices = FV.vertices(1:iV,:);
FV.faces = FV.faces(1:iF,:);
function save_smf(fname,FV);
%SAVE_SMF - Save out a file in a simple form of the SMF format
% function save_smf(fname,FV);
% Writes out one line per vertex or face:
% v <x> <y> <z>
% f <i> <j> <k>
%
% See also LOAD_SMF
%<autobegin> ---------------------- 27-Jun-2005 10:45:38 -----------------------
% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------
%
% CATEGORY: Data Processing
%
% At Check-in: $Author: Mosher $ $Revision: 7 $ $Date: 6/27/05 9:00a $
%
% This software is part of BrainStorm Toolbox Version 27-June-2005
%
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
% University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
% Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
% CNRS, Hopital de la Salpetriere, Paris, France
%
% See BrainStorm website at http://neuroimage.usc.edu for further information.
%
% Copyright (c) 2005 BrainStorm by the University of Southern California
% This software distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 27-Jun-2005 10:45:38 -----------------------
% Author: John C. Mosher, Ph.D.
% ----------------------------- Script History ---------------------------------
% JCM 24-May-2004 Creation
% ----------------------------- Script History ---------------------------------
fid = fopen(fname,'wt');
for i = 1:size(FV.vertices,1),
fprintf(fid,'v %.3f %.3f %.3f\n',FV.vertices(i,:));
end
for i = 1:size(FV.faces,1),
fprintf(fid,'f %.0f %.0f %.0f\n',FV.faces(i,:));
end
fclose(fid);
|
github
|
jacksky64/imageProcessing-master
|
perform_point_picking.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/perform_point_picking.m
| 4,121 |
utf_8
|
9c43a474845c0bc92e5d215f6eda9a88
|
function perform_point_picking( PointCloud, face )
% function perform_point_picking( PointCloud, face );
%
% This function shows a 3D point cloud or a mesh and lets the user click select one
% of the points by clicking on it. The selected point will be highlighted
% and its index in the point cloud will be printed.
%
% input:
% PointCloud: should be a 3*N matrix representing N 3D points
% (if it's M*N, M > 3, the higher dimensions are ignored)
%
% output:
% none
%
% To test this function, run these lines:
%
% PointCloud = rand(3,100)*100;
% perform_point_picking( PointCloud );
%
% now rotate or move the point cloud and try it again.
% (on the figure View menu, turn the Camera Toolbar on, ...)
%
% by Babak Taati
% http://qlink.queensu.ca/~3bt1/
% Queen's University
% May 4, 2005 (revised Oct 30, 2007)
if nargin==2
clf;
hold on;
plot_mesh(PointCloud,face);
end
plot3(PointCloud(1,:), PointCloud(2,:), PointCloud(3,:), 'c.'); % visualize the point cloud
hold on; % so we can highlight the clicked points without clearing the point cloud
cameramenu;
global PointCloudIndex;
set(gcf,'WindowButtonDownFcn',{@callbackClickA3DPoint,PointCloud}); % set the callbak
set(gcf,'WindowButtonUpFcn',{}); % set the callbak
% callbackClickA3DPoint.m
% by Babak Taati
% http://qlink.queensu.ca/~3bt1/
% Queen's University
% May 4, 2005
%
%
% this is the callback function for ClickA3DPoint
%
function callbackClickA3DPoint(src, eventdata, PointCloud);
global PointCloudIndex;
Point = get(gca,'CurrentPoint'); % get the mouse click position
CamPos = get(gca,'CameraPosition'); % camera position
CamTgt = get(gca,'CameraTarget'); % where the camera is pointing to
CamDir = CamPos - CamTgt; % Camera direction
CamUpVect = get(gca,'CameraUpVector'); % camera 'up' vector
% build a orthonormal frame based on the viewing direction and the up vector (the "view frame")
Z_axis = CamDir/norm(CamDir);
UP_axis = CamUpVect/norm(CamUpVect);
X_axis = cross(UP_axis,Z_axis);
Y_axis = cross(Z_axis, X_axis);
Rot = [ X_axis ; Y_axis ; Z_axis ]; % view rotation
RotatedPointCloud = Rot * PointCloud; % the point cloud represented in the view frame
RotatedPointFront = Rot * Point' ; % the clicked point represented in the view frame
% --- find the nearest neighbour to the clicked point
%
% project the 3D point cloud onto a plane (i.e. ignore the z coordinate)
% and find the point that is the closest to the clicked point in that 2D plane.
diff = [ RotatedPointCloud(1,:) - RotatedPointFront(1) ; RotatedPointCloud(2,:) - RotatedPointFront(2) ]; % the difference of all the 2D points from the clicked point (2D)
AllDistances = RowNorm(diff'); % the distance of all the 2D points from the clicked point (2D)
[dist, PointCloudIndex] = min(AllDistances); % find the point that is closest to the clicked point (2D)
% ---- delete the old nearest neighbour & display the new nearest neighbour
h = findobj(gca,'Tag','pt'); % try to find the old point
SelectedPoint = PointCloud(:,PointCloudIndex);
if isempty(h) % Check if it's the first click (i.e. no need to delete the previous point)
h = plot3(SelectedPoint(1,:), SelectedPoint(2,:), SelectedPoint(3,:), 'r.', 'MarkerSize', 20); % highlight the selected point
set(h,'Tag','pt'); % set its Tag property for later use
else % if Not the first click
delete(h); % delete the previously selected point
h = plot3(SelectedPoint(1,:), SelectedPoint(2,:), SelectedPoint(3,:), 'r.', 'MarkerSize', 20); % highlight the newly selected point
set(h,'Tag','pt'); % set its Tag property for later use
end
fprintf('you clicked on point number %d\n', PointCloudIndex);
% RowNorm.m
% Babak taati
%
% function N = RowNorm(A);
%
% returns a matrix with same number of rows as A and one column
% each element in N is the norm of the corresponding row in A
%
% input: A (an m*n matrix)
% output: N (an m*1 vector)
%
function N = RowNorm(A);
N = sqrt(sum(A.*A, 2));
|
github
|
jacksky64/imageProcessing-master
|
select3d.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/select3d.m
| 10,864 |
utf_8
|
64f6b58cf8db75c3508f68035be9892e
|
function [pout, vout, viout, facevout, faceiout] = select3d(obj)
%SELECT3D(H) Determines the selected point in 3-D data space.
% P = SELECT3D determines the point, P, in data space corresponding
% to the current selection position. P is a point on the first
% patch or surface face intersected along the selection ray. If no
% face is encountered along the selection ray, P returns empty.
%
% P = SELECT3D(H) constrains selection to graphics handle H and,
% if applicable, any of its children. H can be a figure, axes,
% patch, or surface object.
%
% [P V] = SELECT3D(...), V is the closest face or line vertex
% selected based on the figure's current object.
%
% [P V VI] = SELECT3D(...), VI is the index into the object's
% x,y,zdata properties corresponding to V, the closest face vertex
% selected.
%
% [P V VI FACEV] = SELECT3D(...), FACE is an array of vertices
% corresponding to the face polygon containing P and V.
%
% [P V VI FACEV FACEI] = SELECT3D(...), FACEI is the row index into
% the object's face array corresponding to FACE. For patch
% objects, the face array can be obtained by doing
% get(mypatch,'faces'). For surface objects, the face array
% can be obtained from the output of SURF2PATCH (see
% SURF2PATCH for more information).
%
% RESTRICTIONS:
% SELECT3D supports surface, patch, or line object primitives. For surface
% and patches, the algorithm assumes non-self-intersecting planar faces.
% For line objects, the algorithm always returns P as empty, and V will
% be the closest vertex relative to the selection point.
%
% Example:
%
% h = surf(peaks);
% zoom(10);
% disp('Click anywhere on the surface, then hit return')
% pause
% [p v vi face facei] = select3d;
% marker1 = line('xdata',p(1),'ydata',p(2),'zdata',p(3),'marker','o',...
% 'erasemode','xor','markerfacecolor','k');
% marker2 = line('xdata',v(1),'ydata',v(2),'zdata',v(3),'marker','o',...
% 'erasemode','xor','markerfacecolor','k');
% marker2 = line('erasemode','xor','xdata',face(1,:),'ydata',face(2,:),...
% 'zdata',face(3,:),'linewidth',10);
% disp(sprintf('\nYou clicked at\nX: %.2f\nY: %.2f\nZ: %.2f',p(1),p(2),p(3)'))
% disp(sprintf('\nThe nearest vertex is\nX: %.2f\nY: %.2f\nZ: %.2f',v(1),v(2),v(3)'))
%
% Version 1.3 11-11-04
% Copyright Joe Conti 2004
% Send comments to [email protected]
%
% See also GINPUT, GCO.
% Output variables
pout = [];
vout = [];
viout = [];
facevout = [];
faceiout = [];
% other variables
ERRMSG = 'Input argument must be a valid graphics handle';
isline = logical(0);
isperspective = logical(0);
% Parse input arguments
if nargin<1
obj = gco;
end
if isempty(obj) | ~ishandle(obj) | length(obj)~=1
error(ERRMSG);
end
% if obj is a figure
if strcmp(get(obj,'type'),'figure')
fig = obj;
ax = get(fig,'currentobject');
currobj = get(fig,'currentobject');
% bail out if not a child of the axes
if ~strcmp(get(get(currobj,'parent'),'type'),'axes')
return;
end
% if obj is an axes
elseif strcmp(get(obj,'type'),'axes')
ax = obj;
fig = get(ax,'parent');
currobj = get(fig,'currentobject');
currax = get(currobj,'parent');
% Bail out if current object is under an unspecified axes
if ~isequal(ax,currax)
return;
end
% if obj is child of axes
elseif strcmp(get(get(obj,'parent'),'type'),'axes')
currobj = obj;
ax = get(obj,'parent');
fig = get(ax,'parent');
% Bail out
else
return
end
axchild = currobj;
obj_type = get(axchild,'type');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Get vertex, face, and current point data %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cp = get(ax,'currentpoint')';
% If surface object
if strcmp(obj_type,'surface')
% Get surface face and vertices
fv = surf2patch(axchild);
vert = fv.vertices;
faces = fv.faces;
% If patch object
elseif strcmp(obj_type,'patch')
vert = get(axchild,'vertices');
faces = get(axchild,'faces');
% If line object
elseif strcmp(obj_type,'line')
xdata = get(axchild,'xdata');
ydata = get(axchild,'ydata');
zdata = get(axchild,'zdata');
vert = [xdata', ydata',zdata'];
faces = [];
isline = logical(1);
% Ignore all other objects
else
return;
end
% Add z if empty
if size(vert,2)==2
vert(:,3) = zeros(size(vert(:,2)));
if isline
zdata = vert(:,3);
end
end
% NaN and Inf check
nan_inf_test1 = isnan(faces) | isinf(faces);
nan_inf_test2 = isnan(vert) | isinf(vert);
if any(nan_inf_test1(:)) | any(nan_inf_test2(:))
warning(sprintf('%s does not support NaNs or Infs in face/vertex data.',mfilename));
end
% For debugging
% if 0
% ax1 = getappdata(ax,'testselect3d');
% if isempty(ax1) | ~ishandle(ax1)
% fig = figure;
% ax1 = axes;
% axis(ax1,'equal');
% setappdata(ax,'testselect3d',ax1);
% end
% cla(ax1);
% patch('parent',ax1,'faces',faces,'vertices',xvert','facecolor','none','edgecolor','k');
% line('parent',ax1,'xdata',xcp(1,2),'ydata',xcp(2,2),'zdata',0,'marker','o','markerfacecolor','r','erasemode','xor');
% end
% Transform vertices from data space to pixel space
xvert = local_Data2PixelTransform(ax,vert)';
xcp = local_Data2PixelTransform(ax,cp')';
% Translate vertices so that the selection point is at the origin.
xvert(1,:) = xvert(1,:) - xcp(1,2);
xvert(2,:) = xvert(2,:) - xcp(2,2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% simple algorithm (almost naive algorithm!) for line objects %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isline
% Ignoring line width and marker attributes, find closest
% vertex in 2-D view space.
d = xvert(1,:).*xvert(1,:) + xvert(2,:).*xvert(2,:);
[val i] = min(d);
i = i(1); % enforce only one output
% Assign output
vout = [ xdata(i) ydata(i) zdata(i)];
viout = i;
return % Bail out early
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Perform 2-D crossing test (Jordan Curve Theorem) %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Find all vertices that have y components less than zero
vert_with_negative_y = zeros(size(faces));
face_y_vert = xvert(2,faces);
ind_vert_with_negative_y = find(face_y_vert<0);
vert_with_negative_y(ind_vert_with_negative_y) = logical(1);
% Find all the line segments that span the x axis
is_line_segment_spanning_x = abs(diff([vert_with_negative_y, vert_with_negative_y(:,1)],1,2));
% Find all the faces that have line segments that span the x axis
ind_is_face_spanning_x = find(any(is_line_segment_spanning_x,2));
% Ignore data that doesn't span the x axis
candidate_faces = faces(ind_is_face_spanning_x,:);
vert_with_negative_y = vert_with_negative_y(ind_is_face_spanning_x,:);
is_line_segment_spanning_x = is_line_segment_spanning_x(ind_is_face_spanning_x,:);
% Create line segment arrays
pt1 = candidate_faces;
pt2 = [candidate_faces(:,2:end), candidate_faces(:,1)];
% Point 1
x1 = reshape(xvert(1,pt1),size(pt1));
y1 = reshape(xvert(2,pt1),size(pt1));
% Point 2
x2 = reshape(xvert(1,pt2),size(pt2));
y2 = reshape(xvert(2,pt2),size(pt2));
% Cross product of vector to origin with line segment
cross_product_test = -x1.*(y2-y1) > -y1.*(x2-x1);
% Find all line segments that cross the positive x axis
crossing_test = (cross_product_test==vert_with_negative_y) & is_line_segment_spanning_x;
% If the number of line segments is odd, then we intersected the polygon
s = sum(crossing_test,2);
s = mod(s,2);
ind_intersection_test = find(s~=0);
% Bail out early if no faces were hit
if isempty(ind_intersection_test)
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Plane/ray intersection test %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Perform plane/ray intersection with the faces that passed
% the polygon intersection tests. Grab the only the first
% three vertices since that is all we need to define a plane).
% assuming planar polygons.
candidate_faces = candidate_faces(ind_intersection_test,1:3);
candidate_faces = reshape(candidate_faces',1,prod(size(candidate_faces)));
vert = vert';
candidate_facev = vert(:,candidate_faces);
candidate_facev = reshape(candidate_facev,3,3,length(ind_intersection_test));
% Get three contiguous vertices along polygon
v1 = squeeze(candidate_facev(:,1,:));
v2 = squeeze(candidate_facev(:,2,:));
v3 = squeeze(candidate_facev(:,3,:));
% Get normal to face plane
vec1 = [v2-v1];
vec2 = [v3-v2];
crs = cross(vec1,vec2);
mag = sqrt(sum(crs.*crs));
nplane(1,:) = crs(1,:)./mag;
nplane(2,:) = crs(2,:)./mag;
nplane(3,:) = crs(3,:)./mag;
% Compute intersection between plane and ray
cp1 = cp(:,1);
cp2 = cp(:,2);
d = cp2-cp1;
dp = dot(-nplane,v1);
%A = dot(nplane,d);
A(1,:) = nplane(1,:).*d(1);
A(2,:) = nplane(2,:).*d(2);
A(3,:) = nplane(3,:).*d(3);
A = sum(A,1);
%B = dot(nplane,pt1)
B(1,:) = nplane(1,:).*cp1(1);
B(2,:) = nplane(2,:).*cp1(2);
B(3,:) = nplane(3,:).*cp1(3);
B = sum(B,1);
% Distance to intersection point
t = (-dp-B)./A;
% Find "best" distance (smallest)
[tbest ind_best] = min(t);
% Determine intersection point
pout = cp1 + tbest .* d;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Assign additional output variables %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargout>1
% Get face index and vertices
faceiout = ind_is_face_spanning_x(ind_intersection_test(ind_best));
facevout = vert(:,faces(faceiout,:));
% Determine index of closest face vertex intersected
facexv = xvert(:,faces(faceiout,:));
dist = sqrt(facexv(1,:).*facexv(1,:) + facexv(2,:).*facexv(2,:));
min_dist = min(dist);
min_index = find(dist==min_dist);
% Get closest vertex index and vertex
viout = faces(faceiout,min_index);
vout = vert(:,viout);
end
%--------------------------------------------------------%
function [p] = local_Data2PixelTransform(ax,vert)
% Transform vertices from data space to pixel space.
% Get needed transforms
xform = get(ax,'x_RenderTransform');
offset = get(ax,'x_RenderOffset');
scale = get(ax,'x_RenderScale');
% Equivalent: nvert = vert/scale - offset;
nvert(:,1) = vert(:,1)./scale(1) - offset(1);
nvert(:,2) = vert(:,2)./scale(2) - offset(2);
nvert(:,3) = vert(:,3)./scale(3) - offset(3);
% Equivalent xvert = xform*xvert;
w = xform(4,1) * nvert(:,1) + xform(4,2) * nvert(:,2) + xform(4,3) * nvert(:,3) + xform(4,4);
xvert(:,1) = xform(1,1) * nvert(:,1) + xform(1,2) * nvert(:,2) + xform(1,3) * nvert(:,3) + xform(1,4);
xvert(:,2) = xform(2,1) * nvert(:,1) + xform(2,2) * nvert(:,2) + xform(2,3) * nvert(:,3) + xform(2,4);
% w may be 0 for perspective plots
ind = find(w==0);
w(ind) = 1; % avoid divide by zero warning
xvert(ind,:) = 0; % set pixel to 0
p(:,1) = xvert(:,1) ./ w;
p(:,2) = xvert(:,2) ./ w;
|
github
|
jacksky64/imageProcessing-master
|
compute_parameterization.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/compute_parameterization.m
| 7,948 |
utf_8
|
ccbb3294b8723d824f8bfa35c4ea64dc
|
function vertex1 = compute_parameterization(vertex,face, options)
% compute_parameterization - compute a planar parameterization
%
% vertex1 = compute_parameterization(vertex,face, options);
%
% options.method can be:
% 'parameterization': solve classical parameterization, the boundary
% is specified by options.boundary which is either 'circle',
% 'square' or 'triangle'. The kind of laplacian used is specified
% by options.laplacian which is either 'combinatorial' or 'conformal'
% 'freeboundary': same be leave the boundary free.
% 'flattening': solve spectral embedding using a laplacian
% specified by options.laplacian.
% 'isomap': use Isomap approach.
% 'drawing': to draw a graph whose adjacency is options.A.
% Then leave vertex and face empty.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
method = getoptions(options, 'method', 'parameterization');
laplacian = getoptions(options, 'laplacian', 'conformal');
boundary = getoptions(options, 'boundary', 'square');
ndim = getoptions(options, 'ndim', 2);
[vertex,face] = check_face_vertex(vertex,face);
options.symmetrize=1;
options.normalize=0;
switch lower(method)
case 'parameterization'
vertex1 = compute_parametrization_boundary(vertex,face,laplacian,boundary, options);
case 'freeboundary'
vertex1 = compute_parameterization_free(vertex,face, laplacian, options);
case 'drawing'
if isfield(options, 'A')
A = options.A;
else
error('You must specify options.A.');
end
L = compute_mesh_laplacian(vertex,face,'combinatorial',options);
[U,S,V] = eigs(L, ndim+1, 'SM');
if abs(S(1))<eps
vertex1 = U(:,end-ndim+1:end);
elseif abs(S(ndim))<eps
vertex1 = U(:,1:ndim);
else
error('Problem with Laplacian matrix');
end
case 'flattening'
L = compute_mesh_laplacian(vertex,face,laplacian,options);
[U,S] = eig(full(L));
vertex1 = U(:,2:3);
if 0
[U,S,V] = eigs(L, ndim+1, 'SM');
if abs(S(1))<1e-9
vertex1 = U(:,end-ndim+1:end);
elseif abs(S(ndim))<eps
vertex1 = U(:,1:ndim);
else
error('Problem with Laplacian matrix');
end
end
case 'isomap'
A = triangulation2adjacency(face);
% build distance graph
D = build_euclidean_weight_matrix(A,vertex,Inf);
vertex1 = isomap(D,ndim, options);
otherwise
error('Unknown method.');
end
if size(vertex1,2)<size(vertex1,1)
vertex1 = vertex1';
end
if ndim==2
vertex1 = rectify_embedding(vertex(1:ndim,:),vertex1);
end
function xy_spec1 = rectify_embedding(xy,xy_spec)
% rectify_embedding - try to match the embeding
% with another one.
% Use the Y coord to select 2 base points.
%
% xy_spec = rectify_embedding(xy,xy_spec);
%
% Copyright (c) 2003 Gabriel Peyr?
I = find( xy(2,:)==max(xy(2,:)) );
n1 = I(1);
I = find( xy(2,:)==min(xy(2,:)) );
n2 = I(1);
v1 = xy(:,n1)-xy(:,n2);
v2 = xy_spec(:,n1)-xy_spec(:,n2);
theta = acos( dot(v1,v2)/sqrt(dot(v1,v1)*dot(v2,v2)) );
theta = theta * sign( det([v1 v2]) );
M = [cos(theta) sin(theta); -sin(theta) cos(theta)];
xy_spec1 = M*xy_spec;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xy = compute_parameterization_free(vertex,face, laplacian, options)
n = size(vertex,2);
% extract boundary
boundary = compute_boundary(face,options);
nbound = length(boundary);
options.symmetrize=1;
options.normalize=0;
% compute Laplacian
if ~isstr(laplacian)
L = laplacian;
laplacian = 'user';
else
L = compute_mesh_laplacian(vertex,face,laplacian,options);
end
A = sparse(2*n,2*n);
A(1:end/2,1:end/2) = L;
A(end/2+1:end,end/2+1:end) = L;
% set up boundary conditions
for s = 1:nbound
% neighboring values
s1 = mod(s-2,nbound)+1;
s2 = mod(s,nbound)+1;
i = boundary(s);
i1 = boundary(s1);
i2 = boundary(s2);
e = 1;
A(i,i1+n) = +e;
A(i,i2+n) = -e;
A(i+n,i1) = -e;
A(i+n,i2) = +e;
end
% set up pinned vertices
i1 = boundary(1);
i2 = boundary(round(end/2));
A(i1,:) = 0; A(i1+n,:) = 0;
A(i1,i1) = 1; A(i1+n,i1+n) = 1;
A(i2,:) = 0; A(i2+n,:) = 0;
A(i2,i2) = 1; A(i2+n,i2+n) = 1;
p1 = [0 0]; p2 = [1 0]; % position of pinned vertices
y = zeros(2*n,1);
y(i1) = p1(1); y(i1+n) = p1(2);
y(i2) = p2(1); y(i2+n) = p2(2);
% solve for the position
xy = A\y;
xy = reshape(xy, [n 2])';
function xy = compute_parametrization_boundary(vertex,face,laplacian,boundary_type,options)
% compute_parametrization - compute a planar parameterization
% of a given disk-like triangulated manifold.
%
% compute_parametrization(vertex,face,laplacian,boundary_type);
%
% 'laplacian' is either 'combinatorial', 'conformal' or 'authalic'
% 'boundary_type' is either 'circle', 'square' or 'triangle'
%
% Copyright (c) 2004 Gabriel Peyr?
if size(vertex,2)>size(vertex,1)
vertex = vertex';
end
if size(face,2)>size(face,1)
face = face';
end
nface = size(face,1);
nvert = max(max(face));
options.symmetrize=1;
options.normalize=0;
if nargin<2
error('Not enough arguments.');
end
if nargin<3
laplacian = 'conformal';
end
if nargin<4
boundary_type = 'circle';
end
if ~isstr(laplacian)
L = laplacian;
laplacian = 'user';
else
% compute Laplacian
L = compute_mesh_laplacian(vertex,face,laplacian,options);
end
% compute the boundary
boundary = compute_boundary(face, options);
% compute the position of the boundary vertex
nbound = length(boundary);
xy_boundary = zeros(nbound,2);
% compute total length
d = 0;
ii = boundary(end); % last index
for i=boundary
d = d + norme( vertex(i,:)-vertex(ii,:) );
ii = i;
end
% vertices along the boundary
vb = vertex(boundary,:);
% compute the length of the boundary
sel = [2:nbound 1];
D = cumsum( sqrt( sum( (vb(sel,:)-vb).^2, 2 ) ) );
d = D(end);
% curvilinear abscice
t = (D-D(1))/d; t = t(:);
switch lower(boundary_type)
case 'circle'
xy_boundary = [cos(2*pi*t),sin(2*pi*t)];
case 'square'
t = t*4;
[tmp,I] = min(abs(t-1)); t(I) = 1;
[tmp,I] = min(abs(t-2)); t(I) = 2;
[tmp,I] = min(abs(t-3)); t(I) = 3;
xy_boundary = [];
I = find(t<1); nI = length(I);
xy_boundary = [xy_boundary; [t(I),t(I)*0]];
I = find(t>=1 & t<2); nI = length(I);
xy_boundary = [xy_boundary; [t(I)*0+1,t(I)-1]];
I = find(t>=2 & t<3); nI = length(I);
xy_boundary = [xy_boundary; [3-t(I),t(I)*0+1]];
I = find(t>=3); nI = length(I);
xy_boundary = [xy_boundary; [t(I)*0,4-t(I)]];
case 'triangle'
t = t*3;
[tmp,I] = min(abs(t-1)); t(I) = 1;
[tmp,I] = min(abs(t-2)); t(I) = 2;
xy_boundary = [];
I = find(t<1); nI = length(I);
xy_boundary = [xy_boundary; [t(I),t(I)*0]];
I = find(t>=1 & t<2); nI = length(I);
xy_boundary = [xy_boundary; (t(I)-1)*[0.5,sqrt(2)/2] + (2-t(I))*[1,0] ];
I = find(t>=2 & t<3); nI = length(I);
xy_boundary = [xy_boundary; (3-t(I))*[0.5,sqrt(2)/2] ];
end
% set up the matrix
M = L;
for i=boundary
M(i,:) = zeros(1,nvert);
M(i,i) = 1;
end
% solve the system
xy = zeros(nvert,2);
for coord = 1:2
% compute right hand side
x = zeros(nvert,1);
x(boundary) = xy_boundary(:,coord);
xy(:,coord) = M\x;
end
function y = norme( x );
y = sqrt( sum(x(:).^2) );
|
github
|
jacksky64/imageProcessing-master
|
perform_dijkstra_propagation_old.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/perform_dijkstra_propagation_old.m
| 5,116 |
utf_8
|
28fc1b6f28ff90c69f6e7c7330aaa33f
|
function D = perform_dijkstra_propagation_old( G , S )
% dijkstra - Find shortest paths in graphs
%
% D = dijkstra_fast( G , S );
%
% use the full or sparse matrix G in which
% an entry (i,j) represents the arc length between nodes i and j in a
% graph. In a full matrix, the value INF represents the absence of an arc;
% in a sparse matrix, no entry at (i,j) naturally represents no arc.
%
% S is the one-dimensional matrix of source nodes for which the shortest
% to ALL other nodes in the graphs will be calculated. The output matrices
% D and P contain the shortest distances and predecessor indices respectively.
% An infinite distance is represented by INF. The predecessor indices contain
% the node indices of the node along the shortest path before the destination
% is reached. These indices are useful to construct the shortest path with the
% function pred2path (by Michael G. Kay).
%
% This function was implemented in C++. The source code can be compiled to a
% Matlab compatible mex file by the command "mex -O dijkstra.cpp" at the Matlab
% prompt. In this package, we provide a compiled .dll version that is
% compatible all Windows based machines. If you are not working on a
% Windows platform, delete the .dll version provided and recompile from
% the .cpp source file. If you do not have the Matlab compiler or a Windows
% platform, delete the .dll version and dijkstra will then call the
% Matlab function dijk.m (by Michael G. Kay). Note that this Matlab
% code is several orders of magnitude slower than the C based mex file.
%
% code taken from :
% Mark Steyvers, Stanford University, 12/19/00
N = size( G , 1 );
D = dijk( G , S , 1:N );
function D = dijk(A,s,t)
% dijk - shortest paths from nodes 's' to nodes 't' using Dijkstra algorithm.
%
% D = dijk(A,s,t);
%
% A = n x n node-node weighted adjacency matrix of arc lengths
% (Note: A(i,j) = 0 => Arc (i,j) does not exist;
% A(i,j) = NaN => Arc (i,j) exists with 0 weight)
% s = FROM node indices
% = [] (default), paths from all nodes
% t = TO node indices
% = [] (default), paths to all nodes
% D = |s| x |t| matrix of shortest path distances from 's' to 't'
% = [D(i,j)], where D(i,j) = distance from node 'i' to node 'j'
%
% (If A is a triangular matrix, then computationally intensive node
% selection step not needed since graph is acyclic (triangularity is a
% sufficient, but not a necessary, condition for a graph to be acyclic)
% and A can have non-negative elements)
%
% (If |s| >> |t|, then DIJK is faster if DIJK(A',t,s) used, where D is now
% transposed and P now represents successor indices)
%
% (Based on Fig. 4.6 in Ahuja, Magnanti, and Orlin, Network Flows,
% Prentice-Hall, 1993, p. 109.)
% Copyright (c) 1998-2000 by Michael G. Kay
% Matlog Version 1.3 29-Aug-2000
%
% Modified by JBT, Dec 2000, to delete paths
% Input Error Checking ******************************************************
error(nargchk(1,3,nargin));
[n,cA] = size(A);
if nargin < 2 | isempty(s), s = (1:n)'; else s = s(:); end
if nargin < 3 | isempty(t), t = (1:n)'; else t = t(:); end
if ~any(any(tril(A) ~= 0)) % A is upper triangular
isAcyclic = 1;
elseif ~any(any(triu(A) ~= 0)) % A is lower triangular
isAcyclic = 2;
else % Graph may not be acyclic
isAcyclic = 0;
end
if n ~= cA
error('A must be a square matrix');
elseif ~isAcyclic & any(any(A < 0))
error('A must be non-negative');
elseif any(s < 1 | s > n)
error(['''s'' must be an integer between 1 and ',num2str(n)]);
elseif any(t < 1 | t > n)
error(['''t'' must be an integer between 1 and ',num2str(n)]);
end
% End (Input Error Checking) ************************************************
A = A'; % Use transpose to speed-up FIND for sparse A
D = zeros(length(s),length(t));
P = zeros(length(s),n);
for i = 1:length(s)
j = s(i);
Di = Inf*ones(n,1); Di(j) = 0;
isLab = logical(zeros(length(t),1));
if isAcyclic == 1
nLab = j - 1;
elseif isAcyclic == 2
nLab = n - j;
else
nLab = 0;
UnLab = 1:n;
isUnLab = logical(ones(n,1));
end
while nLab < n & ~all(isLab)
if isAcyclic
Dj = Di(j);
else % Node selection
[Dj,jj] = min(Di(isUnLab));
j = UnLab(jj);
UnLab(jj) = [];
isUnLab(j) = 0;
end
nLab = nLab + 1;
if length(t) < n, isLab = isLab | (j == t); end
[jA,kA,Aj] = find(A(:,j));
Aj(isnan(Aj)) = 0;
if isempty(Aj), Dk = Inf; else Dk = Dj + Aj; end
P(i,jA(Dk < Di(jA))) = j;
Di(jA) = min(Di(jA),Dk);
if isAcyclic == 1 % Increment node index for upper triangular A
j = j + 1;
elseif isAcyclic == 2 % Decrement node index for lower triangular A
j = j - 1;
end
%disp( num2str( nLab ));
end
D(i,:) = Di(t)';
end
|
github
|
jacksky64/imageProcessing-master
|
compute_boundary.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/compute_boundary.m
| 1,951 |
utf_8
|
a1d4f16ccb164b5d4d3dded2507bbee2
|
function boundary=compute_boundary(face, options)
% compute_boundary - compute the vertices on the boundary of a 3D mesh
%
% boundary=compute_boundary(face);
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
verb = getoptions(options, 'verb', 1);
if size(face,1)<size(face,2)
face=face';
end
nvert=max(max(face));
nface=size(face,1);
A=sparse(nvert,nvert);
for i=1:nface
if verb
progressbar(i,nface);
end
f=face(i,:);
A(f(1),f(2))=A(f(1),f(2))+1;
A(f(1),f(3))=A(f(1),f(3))+1;
A(f(3),f(2))=A(f(3),f(2))+1;
end
A=A+A';
for i=1:nvert
u=find(A(i,:)==1);
if ~isempty(u)
boundary=[i u(1)];
break;
end
end
s=boundary(2);
i=2;
while(i<=nvert)
u=find(A(s,:)==1);
if length(u)~=2
warning('problem in boundary');
end
if u(1)==boundary(i-1)
s=u(2);
else
s=u(1);
end
if s~=boundary(1)
boundary=[boundary s];
else
break;
end
i=i+1;
end
if i>nvert
warning('problem in boundary');
end
%%% OLD %%%
function v = compute_boundary_old(faces)
nvert = max(face(:));
ring = compute_vertex_ring( face );
% compute boundary
v = -1;
for i=1:nvert % first find a starting vertex
f = ring{i};
if f(end)<0
v = i;
break;
end
end
if v<0
error('No boundary found.');
end
boundary = [v];
prev = -1;
while true
f = ring{v};
if f(end)>=0
error('Problem in boundary');
end
if f(1)~=prev
prev = v;
v = f(1);
else
prev = v;
v = f(end-1);
end
if ~isempty( find(boundary==v) )
% we have reach the begining of the boundary
if v~=boundary(1)
warning('Begining and end of boundary doesn''t match.');
else
break;
end
end
boundary = [boundary,v];
end
|
github
|
jacksky64/imageProcessing-master
|
compute_geometric_laplacian.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/compute_geometric_laplacian.m
| 5,760 |
utf_8
|
b6c0f7f8acdbb0c203c5f1a297957760
|
function L = compute_geometric_laplacian(vertex,face,type)
% compute_geometric_laplacian - return a laplacian
% of a given triangulation (can be combinatorial or geometric).
%
% L = compute_geometric_laplacian(vertex,face,type);
%
% Type is either :
% - 'combinatorial' : combinatorial laplacian, doesn't take into
% acount geometry.
% - 'conformal' : conformal (i.e. harmonic) weights,
% - 'authalic' : area-preserving weights (not implemented yet).
% - 'distance' : L(i,j) = 1/|xi-xj|^2
%
% Reference:
% M.S.Floater and K.Hormann
% Recent Advances in Surface Parameterization
% Multiresolution in geometric modelling
% <http://vcg.isti.cnr.it/~hormann/papers/survey.pdf>
%
% Copyright (c) 2003 Gabriel Peyre
error('Not used anymore');
[vertex,face] = check_face_vertex(vertex,face);
nface = size(face,1);
n = max(max(face));
if nargin<3
type = 'conformal';
end
if strcmp(lower(type),'combinatorial')
L = compute_combinatorial_laplacian( triangulation2adjacency(face) );
return;
end
if strcmp(lower(type),'distance')
D = build_euclidean_weight_matrix(triangulation2adjacency(face),vertex,0);
D(D>0) = 1/D(D>0).^2;
L = diag( sum(D) ) - D;
L = (L+L')/2;
return;
end
if strcmp(lower(type),'authalic')
error('Not implemented');
end
if not(strcmp(lower(type),'conformal'))
error('Unknown laplacian type.');
end
% conformal laplacian
L = sparse(n,n);
ring = compute_vertex_face_ring(face);
for i = 1:n
for b = ring{i}
% b is a face adjacent to a
bf = face(:,b);
% compute complementary vertices
if bf(1)==i
v = bf(2:3);
elseif bf(2)==i
v = bf([1 3]);
elseif bf(3)==i
v = bf(1:2);
else
error('Problem in face ring.');
end
j = v(1); k = v(2);
vi = vertex(:,i);
vj = vertex(:,j);
vk = vertex(:,k);
% angles
alpha = myangle(vk-vi,vk-vj);
beta = myangle(vj-vi,vj-vk);
% add weight
L(i,j) = L(i,j) + cot( alpha );
L(i,k) = L(i,k) + cot( beta );
end
end
L = L - diag(sum(L,2));
return;
%% old code
if strcmp(lower(type),'combinatorial')
L = compute_combinatorial_laplacian( triangulation2adjacency(face) );
elseif strcmp(lower(type),'conformal') || strcmp(lower(type),'authalic')
if nargin<4
disp('--> Computing 1-ring.');
ring = compute_vertex_ring( face );
end
disp('--> Computing laplacian.');
for i=1:n
vi = vertex(i,:);
r = ring{i};
if r(end)==-1
% no circularity
s = length(r)-1;
r = [r(1), r(1:(end-1)), r(end-1)];
else
% circularity
s = length(r);
r = [r(end), r, r(1)];
end
% circulate on the 1-ring
for x = 2:(s+1)
j = r(x);
if L(i,j)==0
gche = r(x-1);
drte = r(x+1);
vj = vertex(j,:);
v1 = vertex(gche,:);
v2 = vertex(drte,:);
% we use cot(acos(x))=x/sqrt(1-x^2)
if strcmp(lower(type),'conformal')
d1 = sqrt(dot(vi-v2,vi-v2));
d2 = sqrt(dot(vj-v2,vj-v2));
if d1>eps && d2>eps
z = dot(vi-v2,vj-v2)/( d1*d2 );
L(i,j) = L(i,j) + z/sqrt(1-z^2);
end
d1 = sqrt(dot(vi-v1,vi-v1));
d2 = sqrt(dot(vj-v1,vj-v1));
if d1>eps && d2>eps
z = dot(vi-v1,vj-v1)/( d1*d2 );
L(i,j) = L(i,j) + z/sqrt(1-z^2);
end
else
d1 = sqrt(dot(vi-vj,vi-vj));
d2 = sqrt(dot(v2-vj,v2-vj));
if d1>eps && d2>eps
z = dot(vi-vj,v2-vj)/( d1*d2 );
L(i,j) = L(i,j) + z/sqrt(1-z^2);
end
d1 = sqrt(dot(vi-vj,vi-vj));
d2 = sqrt(dot(v1-vj,v1-vj));
if d1>eps && d2>eps
z = dot(vi-vj,v1-vj)/( d1*d2 );
L(i,j) = L(i,j) + z/sqrt(1-z^2);
end
if d1>eps
L(i,j) = L(i,j) / (d1*d1);
end
end
if 0 % uncomment for symmeterization
if L(j,i)==0
L(j,i) = L(i,j);
else
L(j,i) = (L(j,i)+L(i,j))/2;
end
end
end
end
end
for i=1:n
L(i,i) = -sum( L(i,:) );
end
else
error('Unknown type.');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function beta = myangle(u,v);
du = sqrt( sum(u.^2) );
dv = sqrt( sum(v.^2) );
du = max(du,eps); dv = max(dv,eps);
beta = acos( sum(u.*v) / (du*dv) );
|
github
|
jacksky64/imageProcessing-master
|
check_face_vertex.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/check_face_vertex.m
| 646 |
utf_8
|
fe3c5da3b1ca8f15eb7eed61acfc2259
|
function [vertex,face] = check_face_vertex(vertex,face, options)
% check_face_vertex - check that vertices and faces have the correct size
%
% [vertex,face] = check_face_vertex(vertex,face);
%
% Copyright (c) 2007 Gabriel Peyre
vertex = check_size(vertex);
face = check_size(face);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function a = check_size(a)
if isempty(a)
return;
end
if size(a,1)>size(a,2)
a = a';
end
if size(a,1)<3 && size(a,2)==3
a = a';
end
if size(a,1)<=3 && size(a,2)>=3 && sum(abs(a(:,3)))==0
% for flat triangles
a = a';
end
if size(a,1)~=3 && size(a,1)~=4
error('face or vertex is not of correct size');
end
|
github
|
jacksky64/imageProcessing-master
|
plot_graph.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/plot_graph.m
| 2,140 |
utf_8
|
337033b66fe405903639bcac59c2b34d
|
function h = plot_graph(A,xy, options)
% plot_graph - display a 2D or 3D graph.
%
% plot_graph(A,xy, options);
%
% options.col set the display (e.g. 'k.-')
%
% Copyright (c) 2006 Gabriel Peyre
if size(xy,1)>size(xy,2)
xy = xy';
end
if nargin<3
options.null = 0;
end
if not(isstruct(options))
col = options; clear options;
options.null = 0;
else
if isfield(options, 'col')
col = options.col;
else
col = 'k.-';
end
end
lw = getoptions(options, 'lw', 2);
ps = getoptions(options, 'ps', 20);
B = full(A); B = B(:); B = B( B~=0 );
isvarying = std(B)>0;
if size(xy,1)==2
if ~isstr(col)
col = [];
end
% 2D display
h = gplotvarying(A,xy, col);
% h = gplot(A,xy', col);
axis tight; axis equal; axis off;
elseif size(xy,1)==3
% 3D display
if isstr(col)
if ~isvarying
h = gplot3(A,xy', col);
else
h = gplotvarying3(A,xy, col);
end
else
hold on;
if ~isvarying
h = gplot3(A,xy', col);
else
h = gplotvarying3(A,xy, col);
end
plot_scattered(xy, col);
hold off;
view(3);
end
axis off;
cameramenu;
else
error('Works only for 2D and 3D graphs');
end
set(h, 'LineWidth', lw);
set(h, 'MarkerSize', ps);
function h = gplotvarying(A,xy,col)
[i,j,s] = find(sparse(A));
I = find(i<=j);
i = i(I); j = j(I); s = s(I);
x = [xy(1,i);xy(1,j)];
y = [xy(2,i);xy(2,j)];
h = plot(x,y,col);
function h = gplotvarying3(A,xy,col)
[i,j,s] = find(sparse(A));
I = find(i<=j);
i = i(I); j = j(I); s = s(I);
x = [xy(1,i);xy(1,j)];
y = [xy(2,i);xy(2,j)];
y = [xy(3,i);xy(3,j)];
h = plot3(x,y,z,col);
function h = gplot3(A,xy,lc)
[i,j] = find(A);
[ignore, p] = sort(max(i,j));
i = i(p);
j = j(p);
% Create a long, NaN-separated list of line segments,
% rather than individual segments.
X = [ xy(i,1) xy(j,1) repmat(NaN,size(i))]';
Y = [ xy(i,2) xy(j,2) repmat(NaN,size(i))]';
Z = [ xy(i,3) xy(j,3) repmat(NaN,size(i))]';
X = X(:);
Y = Y(:);
Z = Z(:);
if nargin<3,
h = plot3(X, Y, Z)
else
h = plot3(X, Y, Z, lc);
end
|
github
|
jacksky64/imageProcessing-master
|
perform_faces_reorientation.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/perform_faces_reorientation.m
| 2,816 |
utf_8
|
2cf3d5c1ad6ea271b524352db5492c2c
|
function faces = perform_faces_reorientation(vertex,faces, options)
% perform_faces_reorientation - reorient the faces with respect to the center of the mesh
%
% faces = perform_faces_reorientation(vertex,faces, options);
%
% try to find a consistant reorientation for faces of a mesh.
%
% if options.method = 'fast', then use a fast non accurate method
% if options.method = 'slow', then use a slow exact method
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
method = getoptions(options, 'method', 'fast');
[vertex,faces] = check_face_vertex(vertex,faces);
n = size(vertex,2);
m = size(faces,2);
if strcmp(method, 'fast')
% compute the center of mass of the mesh
G = mean(vertex,2);
% center of faces
Cf = (vertex(:,faces(1,:)) + vertex(:,faces(2,:)) + vertex(:,faces(3,:)))/3;
Cf = Cf - repmat(G,[1 m]);
% normal to the faces
V1 = vertex(:,faces(2,:))-vertex(:,faces(1,:));
V2 = vertex(:,faces(3,:))-vertex(:,faces(1,:));
N = [V1(2,:).*V2(3,:) - V1(3,:).*V2(2,:) ; ...
-V1(1,:).*V2(3,:) + V1(3,:).*V2(1,:) ; ...
V1(1,:).*V2(2,:) - V1(2,:).*V2(1,:) ];
% dot product
s = sign(sum(N.*Cf));
% reverse faces
I = find(s>0);
faces(:,I) = faces(3:-1:1,I);
return
end
options.method = 'fast';
faces = perform_faces_reorientation(vertex,faces, options);
fring = compute_face_ring(faces);
tag = zeros(m,1)-1;
heap = 1;
for i=1:m
if m>100
progressbar(i,m);
end
if isempty(heap)
I = find(tag==-1);
if isempty(I)
error('Problem');
end
heap = I(1);
end
f = heap(end); heap(end) = [];
if tag(f)==1
warning('Problem');
end
tag(f) = 1; % computed
fr = fring{f};
fr = fr(tag(fr)==-1);
tag(fr)=0;
heap = [heap fr];
for k=fr(:)'
% see if re-orientation is needed
if check_orientation(faces(:,k), faces(:,f))==1
faces(1:2,k) = faces(2:-1:1,k);
end
end
end
if not(isempty(heap)) || not(isempty(find(tag<1)))
warning('Problem');
end
% try to see if face are facing in the correct direction
[normal,normalf] = compute_normal(vertex,faces);
a = mean(vertex,2);
a = repmat(a, [1 n]);
dp = sign(sum(normal.*a,1));
if sum(dp>0)<sum(dp<0)
faces(1:2,:) = faces(2:-1:1,:);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function o = check_orientation(f1,f2)
i1 = 0; j1 = 0;
for i=1:3
for j=1:3
if f1(i)==f2(j)
i1 = i; j1 = j;
break;
end
end
if i1~=0
break;
end
end
if i1==0
error('Problem.');
end
ia = mod(i1,3)+1;
ja = mod(j1,3)+1;
ib = mod(i1-2,3)+1;
jb = mod(j1-2,3)+1;
if f1(ia)==f2(ja) || f1(ib)==f2(jb)
o=1;
else
o = -1;
end
|
github
|
jacksky64/imageProcessing-master
|
plot_spherical_triangulation.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/plot_spherical_triangulation.m
| 1,397 |
utf_8
|
fde5d8ffb7898bb232257895ced3d53d
|
function plot_spherical_triangulation(svertex,face, options)
% plot_spherical_triangulation - display a nice spherical triangulation
%
% plot_spherical_triangulation(svertex,face,options);
%
% Copyright (c) 2008 Gabriel Peyre
options.null = 0;
hold on;
% draw a background sphere
[X,Y,Z] = sphere(30);
surf(X,Y,Z);
shading interp; lighting gouraud
camlight;
f = getoptions(options, 'target_face', []);
f = face(:,f);
edges = compute_edges(face);
ne = size(edges,2);
npoints = getoptions(options, 'npoints', 30); % number of point on each arc
lw = getoptions(options, 'lw', 3);
for k=1:ne
i = edges(1,k); j = edges(2,k);
a = svertex(:,i); b = svertex(:,j);
if not(ismember(i,f)) || not(ismember(j,f))
plot_arc(a, b, npoints, lw, 'b');
end
end
axis tight; axis equal; axis off;
rho = 1.02;
if not(isempty(f))
for i=1:3
j = mod(i,3)+1;
c = svertex(:,f(i)); d = svertex(:,f(j));
h = plot3(c(1)*rho, c(2)*rho, c(3)*rho, '.g');
set(h, 'MarkerSize', 40);
plot_arc(c, d, npoints, lw+1, 'r');
end
end
%%
function plot_arc(a, b, npoints, lw, col)
t = repmat(linspace(0,1,npoints), [3 1]);
% arc curve
c = t.*repmat(a, [1 npoints]) + (1-t).*repmat(b, [1 npoints]);
% project on sphere
d = sqrt(sum(c.^2)); d(d<1e-10) = 1;
c = 1.005 * c./repmat(d, [3 1]);
h = plot3(c(1,:), c(2,:), c(3,:), col);
set(h, 'LineWidth', lw);
|
github
|
jacksky64/imageProcessing-master
|
compute_mesh_weight.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/compute_mesh_weight.m
| 2,783 |
utf_8
|
435dabe64ab50ca5bf2c467bcbad6ab8
|
function W = compute_mesh_weight(vertex,face,type,options)
% compute_mesh_weight - compute a weight matrix
%
% W = compute_mesh_weight(vertex,face,type,options);
%
% W is sparse weight matrix and W(i,j)=0 is vertex i and vertex j are not
% connected in the mesh.
%
% type is either
% 'combinatorial': W(i,j)=1 is vertex i is conntected to vertex j.
% 'distance': W(i,j) = 1/d_ij^2 where d_ij is distance between vertex
% i and j.
% 'conformal': W(i,j) = cot(alpha_ij)+cot(beta_ij) where alpha_ij and
% beta_ij are the adjacent angle to edge (i,j)
%
% If options.normalize=1, the the rows of W are normalize to sum to 1.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
[vertex,face] = check_face_vertex(vertex,face);
nface = size(face,1);
n = max(max(face));
verb = getoptions(options, 'verb', n>5000);
if nargin<3
type = 'conformal';
end
switch lower(type)
case 'combinatorial'
W = triangulation2adjacency(face);
case 'distance'
W = my_euclidean_distance(triangulation2adjacency(face),vertex);
W(W>0) = 1./W(W>0);
W = (W+W')/2;
case 'conformal'
% conformal laplacian
W = sparse(n,n);
ring = compute_vertex_face_ring(face);
for i = 1:n
if verb
progressbar(i,n);
end
for b = ring{i}
% b is a face adjacent to a
bf = face(:,b);
% compute complementary vertices
if bf(1)==i
v = bf(2:3);
elseif bf(2)==i
v = bf([1 3]);
elseif bf(3)==i
v = bf(1:2);
else
error('Problem in face ring.');
end
j = v(1); k = v(2);
vi = vertex(:,i);
vj = vertex(:,j);
vk = vertex(:,k);
% angles
alpha = myangle(vk-vi,vk-vj);
beta = myangle(vj-vi,vj-vk);
% add weight
W(i,j) = W(i,j) + cot( alpha );
W(i,k) = W(i,k) + cot( beta );
end
end
otherwise
error('Unknown type.')
end
if isfield(options, 'normalize') && options.normalize==1
W = diag(sum(W,2).^(-1)) * W;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function beta = myangle(u,v);
du = sqrt( sum(u.^2) );
dv = sqrt( sum(v.^2) );
du = max(du,eps); dv = max(dv,eps);
beta = acos( sum(u.*v) / (du*dv) );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function W = my_euclidean_distance(A,vertex)
if size(vertex,1)<size(vertex,2)
vertex = vertex';
end
[i,j,s] = find(sparse(A));
d = sum( (vertex(i,:) - vertex(j,:)).^2, 2);
W = sparse(i,j,d);
|
github
|
jacksky64/imageProcessing-master
|
perform_analysis_regularization.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_graph/toolbox/perform_analysis_regularization.m
| 2,585 |
utf_8
|
c15e65a8b4b77823cd42e992ac708563
|
function [g,g_list,E] = perform_analysis_regularization(f, G, options)
% perform_analysis_regularization - perform a sparse regularization
%
% [g,g_list,E] = perform_analysis_regularization(f, A, options);
%
% Method solves, given f of length n, for
% min_g E(g) = 1/2*|f-g|^2 + lambda * |A*g|_1
% where A is an (m,n) operator and |x|_1=\sum_k |x(k)|
%
% A can be a (m,n) matrix or an operator
% y = A(x,dir,options);
% where dir=1 to computer y=A*x and y=A'*x when dir=-1.
%
% You have to set lambda in options.lambda.
% The number of iteration is options.niter.
% The regularization parameter is options.eta (should be small enough).
% You can use an increasing lambda by setting options.lambda_min and
% options.lambda_max. In that case, g_list contains the list of solutions
% for increasing values of lambda.
%
% It uses the projection algorithm described in
% A. Chambolle
% "An algorithm for Total variation Minimization and applications"
% Journal of Mathematical Imaging and Vision, 20(1), p. 89-97, 2004
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
if isfield(options, 'niter')
niter = options.niter;
else
niter = 100;
end
if isfield(options, 'eta')
eta = options.eta;
else
eta = 0.1;
end
if isfield(options, 'g')
h = options.h;
else
h = f*0;
end
if isfield(options, 'lambda')
lambda = options.lambda;
else
lambda = .3;
end
if isfield(options, 'lambda_min')
lambda_min = options.lambda_min;
else
lambda_min = lambda;
end
if isfield(options, 'lambda_max')
lambda_max = options.lambda_max;
else
lambda_max = lambda;
end
if isfield(options, 'verb')
verb = options.verb;
else
verb = 1;
end
lambda_list = linspace(lambda_min,lambda_max,niter);
f = f(:);
n = length(f);
if nargout>2
g_list = zeros(n,niter);
end
E = [];
p = appG(G,h,options);
for i=1:niter
if verb
progressbar(i,niter);
end
lambda = lambda_list(i);
h = lambda*appGT(G,p,options);
pp = -1/lambda * appG(G,h-f,options);
% update
p = ( p+eta*pp )./( 1+eta*abs(pp) );
if nargout>2
g = f-h;
pg = appG(G,g,options);
E(end+1) = .5*norm(h, 'fro')^2 + lambda_max * sum( abs(pg(:)) );
end
if nargout>1
g_list(:,i) = f - h;
end
end
g = f - h;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y=appG(G,x, options)
if isnumeric(G)
y = G*x;
else
y = feval( G,x, 1, options );
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y=appGT(G,x, options)
if isnumeric(G)
y = G'*x;
else
y = feval( G,x, -1, options );
end
|
github
|
jacksky64/imageProcessing-master
|
perform_synthesis_quilting.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_nlmeans/perform_synthesis_quilting.m
| 7,651 |
utf_8
|
8c411ddc2b26690849941b7d95f0b8ac
|
function Y = perform_synthesis_quilting(X, tilesize, n, overlap, err)
% perform_synthesis_quilting - perform image synthesis
%
% Y = perform_synthesis_quilting(X, tilesize, n, overlap, err);
%
% The method is described in
% ``Image Quilting for Texture Synthesis and Transfer''
% Alexei A. Efros and William T. Freeman
% Proceedings of SIGGRAPH '01, Los Angeles, California, August, 2001.
%
% The implementation is by Christopher DeCoro
% http://www.cs.princeton.edu/~cdecoro/imagequilting/
%
% X: The source image to be used in synthesis
% tilesize: the dimensions of each square tile. Should divide size(X) evenly
% n: The number of tiles to be placed in the output image, in each dimension
% overlap: The amount of overlap to allow between pixels (def: 1/6 tilesize)
% err: used when computing list of compatible tiles (def: 0.1)
X = double(X);
if( length(size(X)) == 2 )
X = repmat(X, [1 1 3]);
elseif( length(size(X)) ~= 3 )
error('Input image must be 2 or 3 dimensional');
end
simple = 0;
if( nargin < 5 )
err = 0.002;
end
if( nargin < 4 )
overlap = round(tilesize / 6);
end
use_draw = 1;
use_verb = 0;
if( overlap >= tilesize )
error('Overlap must be less than tilesize');
end
destsize = n * tilesize - (n-1) * overlap;
Y = zeros(destsize, destsize, 3);
for i=1:n,
for j=1:n,
progressbar(j+(i-1)*n, n^2);
startI = (i-1)*tilesize - (i-1) * overlap + 1;
startJ = (j-1)*tilesize - (j-1) * overlap + 1;
endI = startI + tilesize -1 ;
endJ = startJ + tilesize -1;
%Determine the distances from each tile to the overlap region
%This will eventually be replaced with convolutions
distances = zeros( size(X,1)-tilesize, size(X,2)-tilesize );
useconv = 1;
if( useconv == 0 )
%Compute the distances from the template to target for all i,j
for a = 1:size(distances,1)
v1 = Y(startI:endI, startJ:endJ, 1:3);
for b = 1:size(distances,2),
v2 = X(a:a+tilesize-1,b:b+tilesize-1, 1:3);
distances(a,b) = myssd( double((v1(:) > 0)) .* (v1(:) - v2(:)) );
%distances(a,b) = D;
end
end
else
%Compute the distances from the source to the left overlap region
if( j > 1 )
distances = ssd( X, Y(startI:endI, startJ:startJ+overlap-1, 1:3) );
distances = distances(1:end, 1:end-tilesize+overlap);
end
%Compute the distance from the source to top overlap region
if( i > 1 )
Z = ssd( X, Y(startI:startI+overlap-1, startJ:endJ, 1:3) );
Z = Z(1:end-tilesize+overlap, 1:end);
if( j > 1 ) distances = distances + Z;
else distances = Z;
end
end
%If both are greater, compute the distance of the overlap
if( i > 1 && j > 1 )
Z = ssd( X, Y(startI:startI+overlap-1, startJ:startJ+overlap-1, 1:3) );
Z = Z(1:end-tilesize+overlap, 1:end-tilesize+overlap);
distances = distances - Z;
end
end
%Find the best candidates for the match
best = max( min(distances(:)), 0 );
candidates = find(distances(:) <= (1+err)*best);
idx = candidates(ceil(rand(1)*length(candidates)));
[sub(1), sub(2)] = ind2sub(size(distances), idx);
if use_verb
fprintf( 'Picked tile (%d, %d) out of %d candidates. Best error=%.4f\n', sub(1), sub(2), length(candidates), best );
end
%If we do the simple quilting (no cut), just copy image
if( simple )
Y(startI:endI, startJ:endJ, 1:3) = X(sub(1):sub(1)+tilesize-1, sub(2):sub(2)+tilesize-1, 1:3);
else
%Initialize the mask to all ones
M = ones(tilesize, tilesize);
%We have a left overlap
if( j > 1 )
%Compute the SSD in the border region
E = ( X(sub(1):sub(1)+tilesize-1, sub(2):sub(2)+overlap-1) - Y(startI:endI, startJ:startJ+overlap-1) ).^2;
%Compute the mincut array
C = mincut(E, 0);
%Compute the mask and write to the destination
M(1:end, 1:overlap) = double(C >= 0);
end
%We have a top overlap
if( i > 1 )
%Compute the SSD in the border region
E = ( X(sub(1):sub(1)+overlap-1, sub(2):sub(2)+tilesize-1) - Y(startI:startI+overlap-1, startJ:endJ) ).^2;
%Compute the mincut array
C = mincut(E, 1);
%Compute the mask and write to the destination
M(1:overlap, 1:end) = M(1:overlap, 1:end) .* double(C >= 0);
end
if( i == 1 && j == 1 )
Y(startI:endI, startJ:endJ, 1:3) = X(sub(1):sub(1)+tilesize-1, sub(2):sub(2)+tilesize-1, 1:3);
else
%Write to the destination using the mask
Y(startI:endI, startJ:endJ, :) = filtered_write(Y(startI:endI, startJ:endJ, :), ...
X(sub(1):sub(1)+tilesize-1, sub(2):sub(2)+tilesize-1, :), M);
end
end
if use_draw
imageplot(Y);
drawnow;
end
end
end
if use_draw
imageplot(Y);
drawnow;
end
function y = myssd( x )
y = sum( x.^2 );
function A = filtered_write(A, B, M)
for i = 1:3,
A(:, :, i) = A(:,:,i) .* (M == 0) + B(:,:,i) .* (M == 1);
end
%function Y = mincut(X,dir)
%Computes the minimum cut from one edge of the matrix to the other
%
%Inputs:
% X: Evalutations of 2d function to be cut along local minima
% dir: 0 = vertical cut, 1 = horizontal cut
%
%Outputs:
% C: Matrix containing entries indicating side
% -1: left (or top) side of cut
% 0: along the cut
% 1: right (or bottom) side of cut
function C = mincut(X,dir)
if( nargin > 1 && dir == 1 )
X = X';
end
%Allocate the current cost array, and set first row to first row of X
E = zeros(size(X));
E(1:end,:) = X(1:end,:);
%Starting with the second array, compute the path costs until the end
for i=2:size(E,1),
E(i,1) = X(i,1) + min( E(i-1,1), E(i-1,2) );
for j=2:size(E,2)-1,
E(i,j) = X(i,j) + min( [E(i-1,j-1), E(i-1,j), E(i-1,j+1)] );
end
E(i,end) = X(i,end) + min( E(i-1,end-1), E(i-1,end) );
end
%Backtrace to find the cut
C = zeros(size(X));
[cost, idx] = min(E(end, 1:end));
C(i, 1:idx-1) = -1;
C(i, idx) = 0;
C(i, idx+1:end) = +1;
for i=size(E,1)-1:-1:1,
for j=1:size(E,2),
if( idx > 1 && E(i,idx-1) == min(E(i,idx-1:min(idx+1,size(E,2))) ) )
idx = idx-1;
elseif( idx < size(E,2) && E(i,idx+1) == min(E(i,max(idx-1,1):idx+1)) )
idx = idx+1;
end
C(i, 1:idx-1) = -1;
C(i, idx) = 0;
C(i, idx+1:end) = +1;
end
end
if( nargin > 1 && dir == 1 )
%E = E';
C = C';
end
%function Z = ssd(X, Y)
%Computes the sum of squared distances between X and Y for each possible
% overlap of Y on X. Y is thus smaller than X
%
%Inputs:
% X - larger image
% Y - smaller image
%
%Outputs:
% Each pixel of Z contains the ssd for Y overlaid on X at that pixel
function Z = ssd(X, Y)
K = ones(size(Y,1), size(Y,2));
for k=1:size(X,3),
A = X(:,:,k);
B = Y(:,:,k);
a2 = filter2(K, A.^2, 'valid');
b2 = sum(sum(B.^2));
ab = filter2(B, A, 'valid').*2;
if( k == 1 )
Z = ((a2 - ab) + b2);
else
Z = Z + ((a2 - ab) + b2);
end
end
|
github
|
jacksky64/imageProcessing-master
|
perform_wavelet_matching.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_nlmeans/toolbox/perform_wavelet_matching.m
| 4,232 |
utf_8
|
c08affe005c098a67fc7fbda0a77237e
|
function [M1,MW,MW1] = perform_wavelet_matching(M1,M,options)
% perform_wavelet_matching - match multiscale histograms
%
% M1 = perform_wavelet_matching(M1,M,options);
%
% M1 is the image to synthesize.
% M is the exemplar image.
%
% This function match the histogram of the image and the histogram
% of each sub-band of a wavelet-like pyramid.
%
% To do texture synthesis, one should apply several time this function.
% You can do it by setting the value of options.niter_synthesis.
% This leads to the synthesis as described in
%
% Pyramid-Based Texture Analysis/Synthesis
% D. Heeger, J. Bergen,
% Siggraph 1995
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
niter_synthesis = getoptions(options, 'niter_synthesis', 1);
if not(isfield(options, 'color_mode'))
options.color_mode = 'pca';
end
if isfield(options, 'color_mode') && strcmp(options.color_mode, 'pca') && ~isfield(options, 'ColorP') && size(M,3)==3
[tmp,options.ColorP] = change_color_mode(M,+1,options);
end
rgb_postmatching = getoptions(options, 'rgb_postmatching', 0);
if size(M,3)==3
options.niter_synthesis = 1;
for iter=1:niter_synthesis
% color images
M = change_color_mode(M, +1,options);
M1 = change_color_mode(M1,+1,options);
for i=1:size(M,3)
M1(:,:,i) = perform_wavelet_matching(M1(:,:,i),M(:,:,i), options);
end
M = change_color_mode(M, -1,options);
M1 = change_color_mode(M1,-1,options);
if rgb_postmatching
for i=1:size(M,3)
M1(:,:,i) = perform_histogram_equalization(M1(:,:,i),M(:,:,i));
end
end
end
return;
end
if size(M,3)>1
for i=1:size(M,3)
[M1(:,:,i),MW,MW1] = perform_wavelet_matching(M1(:,:,i),M(:,:,i),options);
end
return;
end
n = size(M,1);
n1 = size(M1,1);
synthesis_method = getoptions(options, 'synthesis_method', 'steerable');
m = 2^( ceil(log2(n)) );
m1 = 2^( ceil(log2(n1)) );
M = perform_image_extension(M,m);
M1 = perform_image_extension(M1,m1);
% precompute input
MW = my_transform(M, +1, options);
for iter=1:niter_synthesis
% spatial equalization
M1 = my_equalization(M1,M);
% forward transforms
MW1 = my_transform(M1, +1, options);
% wavelet domain equalization
MW1 = my_equalization(MW1,MW);
% backward transform
M1 = my_transform(MW1, -1, options);
% spatial equalization
M1 = my_equalization(M1,M);
end
M1 = M1(1:n1,1:n1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = my_equalization(M,M0)
options.absval = 0;
options.rows = 0;
options.cols = 0;
options.dim3 = 1;
if iscell(M)
for i=1:min(length(M),length(M0))
M{i} = my_equalization(M{i},M0{i});
end
return;
end
if size(M,3)>1
for i=1:min(size(M,3),size(M0,3))
M(:,:,i) = my_equalization(M(:,:,i),M0(:,:,i));
end
return;
end
M = perform_histogram_equalization(M,M0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = my_transform(M, dir, options)
n = size(M,1);
deltaJ = 5;
Jmax = log2(n)-1;
Jmin = max(Jmax-deltaJ+1,3);
synthesis_method = getoptions(options, 'synthesis_method', 'steerable');
% steerable options
if not(isfield(options, 'nb_orientations'))
options.nb_orientations = 4;
end
% wave ortho options
options.wavelet_type = 'biorthogonal_swapped';
options.wavelet_vm = 4;
switch synthesis_method
case 'steerable'
M = perform_steerable_transform(M, Jmin, options);
case 'wavelets-ortho'
if dir==-1
M = convert_wavelets2list(M, Jmin);
end
M = perform_wavelet_transform(M, Jmin, dir, options);
if dir==1
M = convert_wavelets2list(M, Jmin);
end
case 'quincunx-ti'
M = perform_quicunx_wavelet_transform_ti(M,Jmin,options);
case 'wavelets-ti'
options.wavelet_type = 'biorthogonal';
options.wavelet_vm = 3;
M = perform_atrou_transform(M,Jmin,options);
otherwise
error('Unknown transform.');
end
|
github
|
jacksky64/imageProcessing-master
|
load_image.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_nlmeans/toolbox/load_image.m
| 12,502 |
utf_8
|
4d9dcb12e956804ea88dbe11fb8b6912
|
function M = load_image(type, n, options)
% load_image - load benchmark images.
%
% M = load_image(name, n, options);
%
% name can be:
% Synthetic images:
% 'chessboard1', 'chessboard', 'square', 'disk', 'quaterdisk', '3contours', 'line',
% 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle',
% 'parabola', 'sin', 'phantom', 'circ_oscil',
% 'fnoise' (1/f^alpha noise).
% Natural images:
% 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own.
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin<2
n = 512;
end
options.null = 0;
type = lower(type);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters for geometric objects
eta = 0.1; % translation
gamma = 1/sqrt(2); % slope
if isfield( options, 'eta' )
eta = options.eta;
end
if isfield( options, 'gamma' )
eta = options.gamma;
end
if isfield( options, 'radius' )
radius = options.radius;
end
if isfield( options, 'center' )
center = options.center;
end
if isfield( options, 'center1' )
center1 = options.center1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the line, can be vertical / horizontal / diagonal / any
if strcmp(type, 'line_vertical')
eta = 0.5; % translation
gamma = 0; % slope
elseif strcmp(type, 'line_horizontal')
eta = 0.5; % translation
gamma = Inf; % slope
elseif strcmp(type, 'line_diagonal')
eta = 0; % translation
gamma = 1; % slope
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for some blurring
sigma = 0;
if isfield(options, 'sigma')
sigma = options.sigma;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch type
case 'chessboard1'
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (2*(Y>=0)-1).*(2*(X>=0)-1);
case 'chessboard'
if ~isfield( options, 'width' )
width = round(n/16);
else
width = options.width;
end
[Y,X] = meshgrid(0:n-1,0:n-1);
M = mod( floor(X/width)+floor(Y/width), 2 ) == 0;
case 'square'
if ~isfield( options, 'radius' )
radius = 0.6;
end
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = max( abs(X),abs(Y) )<radius;
case 'square_texture'
M = load_image('square',n);
M = rescale(M);
% make a texture patch
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta );
case 'oscillatory_texture'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M = sin( x * 2*pi / eta );
case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'}
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
if gamma~=Inf
M = (X-eta) - gamma*Y < 0;
else
M = (Y-eta) < 0;
end
case 'grating'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
if isfield(options, 'theta')
theta = options.theta;
else
theta = 0.2;
end
if isfield(options, 'freq')
freq = options.freq;
else
freq = 0.2;
end
X = cos(theta)*X + sin(theta)*Y;
M = sin(2*pi*X/freq);
case 'disk'
if ~isfield( options, 'radius' )
radius = 0.35;
end
if ~isfield( options, 'center' )
center = [0.5, 0.5]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'quarterdisk'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'fading_contour'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
theta = 2/pi*atan2(Y,X);
h = 0.5;
M = exp(-(1-theta).^2/h^2).*M;
case '3contours'
radius = 1.3;
center = [-1, 1];
radius1 = 0.8;
center1 = [0, 0];
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2;
M = f1 + 0.5*f2.*(1-f1);
case 'line_circle'
gamma = 1/sqrt(2);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M1 = double( X>gamma*Y+0.25 );
M2 = X.^2 + Y.^2 < 0.6^2;
M = 20 + max(0.5*M1,M2) * 216;
case 'fnoise'
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
if isfield(options, 'alpha')
alpha = options.alpha;
else
alpha = 1;
end
M = gen_noisy_image(n,alpha);
case 'gaussiannoise'
% generate an image of filtered noise with gaussian
if isfield(options, 'sigma')
sigma = options.sigma;
else
sigma = 10;
end
M = randn(n);
m = 51;
h = compute_gaussian_filter([m m],sigma/(4*n),[n n]);
M = perform_convolution(M,h);
return;
case {'bwhorizontal','bwvertical','bwcircle'}
[Y,X] = meshgrid(0:n-1,0:n-1);
if strcmp(type, 'bwhorizontal')
d = X;
elseif strcmp(type, 'bwvertical')
d = Y;
elseif strcmp(type, 'bwcircle')
d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 );
end
if isfield(options, 'stripe_width')
stripe_width = options.stripe_width;
else
stripe_width = 5;
end
if isfield(options, 'black_prop')
black_prop = options.black_prop;
else
black_prop = 0.5;
end
M = double( mod( d/(2*stripe_width),1 )>=black_prop );
case 'parabola'
% curvature
if isfield(options, 'c')
c = options.c;
else
c = 0.1;
end
% angle
if isfield(options, 'theta');
theta = options.theta;
else
theta = pi/sqrt(2);
end
x = -0.5:1/(n-1):0.5;
[Y,X] = meshgrid(x,x);
Xs = X*cos(theta) + Y*sin(theta);
Y =-X*sin(theta) + Y*cos(theta); X = Xs;
M = Y>c*X.^2;
case 'sin'
[Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1);
M = Y >= 0.6*cos(pi*X);
M = double(M);
case 'circ_oscil'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
R = sqrt(X.^2+Y.^2);
M = cos(R.^3*50);
case 'phantom'
M = phantom(n);
case 'periodic_bumps'
if isfield(options, 'nbr_periods')
nbr_periods = options.nbr_periods;
else
nbr_periods = 8;
end
if isfield(options, 'theta')
theta = options.theta;
else
theta = 1/sqrt(2);
end
if isfield(options, 'skew')
skew = options.skew;
else
skew = 1/sqrt(2);
end
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];
B = [1 skew; 0 1];
T = B*A;
x = (0:n-1)*2*pi*nbr_periods/(n-1);
[Y,X] = meshgrid(x,x);
pos = [X(:)'; Y(:)'];
pos = T*pos;
X = reshape(pos(1,:), n,n);
Y = reshape(pos(2,:), n,n);
M = cos(X).*sin(Y);
case 'noise'
if isfield(options, 'sigma')
sigma = options.sigma;
else
sigma = 1;
end
M = randn(n);
otherwise
ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm'};
for i=1:length(ext)
name = [type '.' ext{i}];
if( exist(name) )
M = imread( name );
M = double(M);
if not(isempty(n)) && n~=size(M, 1) && nargin>=2
M = image_resize(M,n,n);
end
return;
end
end
error( ['Image ' type ' does not exists.'] );
end
M = double(M);
if sigma>0
h = ones(sigma);
h = conv2(h,h);
h = h/sum(h(:));
M = conv2(M, h, 'same');
end
M = rescale(M) * 256;
function M = gen_noisy_image(n,alpha)
% gen_noisy_image - generate a noisy cloud-like image.
%
% M = gen_noisy_image(n,alpha);
%
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin<1
n = 128;
end
if nargin<2
alpha = 1.5;
end
if mod(n(1),2)==0
x = -n/2:n/2-1;
else
x = -(n-1)/2:(n-1)/2;
end
[Y,X] = meshgrid(x,x);
d = sqrt(X.^2 + Y.^2) + 0.1;
f = rand(n)*2*pi;
M = (d.^(-alpha)) .* exp(f*1i);
% M = real(ifft2(fftshift(M)));
M = ifftshift(M);
M = real( ifft2(M) );
function y = gen_signal_2d(n,alpha)
% gen_signal_2d - generate a 2D C^\alpha signal of length n x n.
% gen_signal_2d(n,alpha) generate a 2D signal C^alpha.
%
% The signal is scale in [0,1].
%
% Copyright (c) 2003 Gabriel Peyr?
% new new method
[Y,X] = meshgrid(0:n-1, 0:n-1);
A = X+Y+1;
B = X-Y+n+1;
a = gen_signal(2*n+1, alpha);
b = gen_signal(2*n+1, alpha);
y = a(A).*b(B);
% M = a(1:n)*b(1:n)';
return;
% new method
h = (-n/2+1):(n/2); h(n/2)=1;
[X,Y] = meshgrid(h,h);
h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2);
h = h .* exp( 2i*pi*rand(n,n) );
h = fftshift(h);
y = real( ifft2(h) );
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
return;
%% old code
y = rand(n,n);
y = y - mean(mean(y));
for i=1:alpha
y = cumsum(cumsum(y)')';
y = y - mean(mean(y));
end
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
function newimg = image_resize(img,p1,q1,r1)
% image_resize - resize an image using bicubic interpolation
%
% newimg = image_resize(img,nx,ny,nz);
% or
% newimg = image_resize(img,newsize);
%
% Works for 2D, 2D 2 or 3 channels, 3D images.
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin==2
% size specified as an array
q1 = p1(2);
if length(p1)>2
r1 = p1(3);
else
r1 = size(img,3);
end
p1 = p1(1);
end
if nargin<4
r1 = size(img,3);
end
if ndims(img)<2 || ndims(img)>3
error('Works only for grayscale or color images');
end
if ndims(img)==3 && size(img,3)<4
% RVB image
newimg = zeros(p1,q1, size(img,3));
for m=1:size(img,3)
newimg(:,:,m) = image_resize(img(:,:,m), p1, q1);
end
return;
elseif ndims(img)==3
p = size(img,1);
q = size(img,2);
r = size(img,3);
[Y,X,Z] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1), (0:r-1)/(r-1) );
[YI,XI,ZI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1), (0:r1-1)/(r1-1) );
newimg = interp3( Y,X,Z, img, YI,XI,ZI ,'cubic');
return;
end
p = size(img,1);
q = size(img,2);
[Y,X] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1) );
[YI,XI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1) );
newimg = interp2( Y,X, img, YI,XI ,'cubic');
|
github
|
jacksky64/imageProcessing-master
|
perform_histogram_equalization.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_nlmeans/toolbox/perform_histogram_equalization.m
| 7,968 |
utf_8
|
bcc84159668c38454a24a2574e13ac2b
|
function x = perform_histogram_equalization(x,y,options)
% perform_histogram_equalization - perform histogram equalization
%
% x = perform_histogram_equalization(x,y,options);
%
% Change the values of x so that its ordered values match
% the ordered values of y.
%
% You can set
% options.cols=1 to operate along columns
% options.rows=1 to operate along rows
% options.absval to operate only on absolute values.
%
% Copyright (c) 2006 Gabriel Peyr?
options.null = 0;
if isfield(options ,'absval')
absval = options.absval;
else
absval = 0;
end
if isfield(options ,'cols')
cols = options.cols;
else
cols = 0;
end
if isfield(options ,'rows')
rows = options.rows;
else
rows = 0;
end
if isfield(options, 'match_ycbcr')
match_ycbcr = options.match_ycbcr;
else
match_ycbcr = 1;
end
% for color images
if size(x,3)>1
if size(x,3)~=size(y,3)
error('x and y images must have the same number of components.');
end
if size(x,3)==3 && match_ycbcr
x = rgb2ycbcr(x);
y = rgb2ycbcr(y);
end
% match each color
for i=1:3
x(:,:,i) = perform_histogram_equalization(x(:,:,i), y(:,:,i), options);
end
if size(x,3)==3 && match_ycbcr
x = ycbcr2rgb(x);
end
return;
end
if cols && rows
error('You cannote specify both cols and rows');
end
if cols && size(x,2)>1
if not(size(x,2)==size(y,2))
error('x and y must have same number of columns');
end
for i=1:size(x,2)
x(:,i) = perform_histogram_equalization(x(:,i),y(:,i),options);
end
return;
end
if rows && size(x,1)>1
if not(size(x,1)==size(y,1))
error('x and y must have same number of rows');
end
for i=1:size(x,1)
x(i,:) = perform_histogram_equalization(x(i,:),y(i,:),options);
end
return;
end
sx = size(x);
x = x(:);
y = y(:);
if absval
s = sign(x);
x = abs(x);
y = abs(y);
end
[vx,Ix] = sort(x);
[vy,Iy] = sort(y);
nx = length(x);
ny = length(y);
ax = linspace(1,ny,nx);
ay = 1:ny;
vx = interp1(ay,vy,ax);
x(Ix) = vx;
if absval
x = x .* s;
end
x = reshape(x,sx);
function rgb = ycbcr2rgb(in)
%YCBCR2RGB Convert YCbCr values to RGB color space.
% RGBMAP = YCBCR2RGB(YCBCRMAP) converts the YCbCr values in the
% colormap YCBCRMAP to the RGB color space. If YCBCRMAP is M-by-3 and
% contains the YCbCr luminance (Y) and chrominance (Cb and Cr) color
% values as columns, then RGBMAP is an M-by-3 matrix that contains
% the red, green, and blue values equivalent to those colors.
%
% RGB = YCBCR2RGB(YCBCR) converts the YCbCr image to the equivalent
% truecolor image RGB.
%
% Class Support
% -------------
% If the input is a YCbCr image, it can be of class uint8, uint16,
% or double; the output image is of the same class as the input
% image. If the input is a colormap, the input and output
% colormaps are both of class double.
%
% Example
% -------
% Convert image from RGB space to YCbCr space and back.
%
% rgb = imread('board.tif');
% ycbcr = rgb2ycbcr(rgb);
% rgb2 = ycbcr2rgb(ycbcr);
%
% See also NTSC2RGB, RGB2NTSC, RGB2YCBCR.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 1.15.4.2 $ $Date: 2003/08/23 05:54:51 $
% Reference:
% Charles A. Poynton, "A Technical Introduction to Digital Video",
% John Wiley & Sons, Inc., 1996
%initialize variables
isColormap = false;
classin = class(in);
%must reshape colormap to be m x n x 3 for transformation
if (ndims(in)==2)
%colormap
isColormap=true;
colors = size(in,1);
in = reshape(in, [colors 1 3]);
end
%initialize output
rgb = in;
% set up constants for transformation. T alone will transform YCBCR in [0,255]
% to RGB in [0,1]. We must scale T and the offsets to get RGB in the appropriate
% range for uint8 and for uint16 arrays.
T = [65.481 128.553 24.966;...
-37.797 -74.203 112; ...
112 -93.786 -18.214];
Tinv = T^-1;
offset = [16;128;128];
Td = 255 * Tinv;
offsetd = Tinv * offset;
T8 = Td;
offset8 = T8 * offset;
T16 = (65535/257) * Tinv;
offset16 = 65535 * Tinv * offset;
switch classin
case 'double'
for p = 1:3
rgb(:,:,p) = Td(p,1) * in(:,:,1) + Td(p,2) * in(:,:,2) + ...
Td(p,3) * in(:,:,3) - offsetd(p);
end
case 'uint8'
for p = 1:3
rgb(:,:,p) = imlincomb(T8(p,1),in(:,:,1),T8(p,2),in(:,:,2), ...
T8(p,3),in(:,:,3),-offset8(p));
end
case 'uint16'
for p = 1:3
rgb(:,:,p) = imlincomb(T16(p,1),in(:,:,1),T16(p,2),in(:,:,2), ...
T16(p,3),in(:,:,3),-offset16(p));
end
end
if isColormap
rgb = reshape(rgb, [colors 3 1]);
end
if isa(rgb,'double')
rgb = min(max(rgb,0.0),1.0);
end
%%%
%Parse Inputs
%%%
function X = parse_inputs(varargin)
checknargin(1,1,nargin,mfilename);
X = varargin{1};
if ndims(X)==2
checkinput(X,{'uint8','uint16','double'},'real nonempty',mfilename,'MAP',1);
if (size(X,2) ~=3 || size(X,1) < 1)
eid = sprintf('Images:%s:invalidSizeForColormap',mfilename);
msg = 'MAP must be a m x 3 array.';
error(eid,'%s',msg);
end
elseif ndims(X)==3
checkinput(X,{'uint8','uint16','double'},'real',mfilename,'RGB',1);
if (size(X,3) ~=3)
eid = sprintf('Images:%s:invalidTruecolorImage',mfilename);
msg = 'RGB must a m x n x 3 array.';
error(eid,'%s',msg);
end
else
eid = sprintf('Images:%s:invalidInputSize',mfilename);
msg = ['RGB2GRAY only accepts two-dimensional or three-dimensional ' ...
'inputs.'];
error(eid,'%s',msg);
end
function out = rgb2ycbcr(in)
%RGB2YCBCR Convert RGB values to YCBCR color space.
% YCBCRMAP = RGB2YCBCR(MAP) converts the RGB values in MAP to
% the YCBCR color space. YCBCRMAP is a M-by-3 matrix that contains
% the YCBCR luminance (Y) and chrominance (Cb and Cr) color values as
% columns. Each row represents the equivalent color to the
% corresponding row in the RGB colormap.
%
% YCBCR = RGB2YCBCR(RGB) converts the truecolor image RGB to the
% equivalent image in the YCBCR color space.
%
% Class Support
% -------------
% If the input is an RGB image, it can be of class uint8, uint16,
% or double; the output image is of the same class as the input
% image. If the input is a colormap, the input and output colormaps
% are both of class double.
%
% Examples
% --------
% Convert RGB image to YCbCr.
%
% RGB = imread('board.tif');
% YCBCR = rgb2ycbcr(RGB);
%
% Convert RGB color space to YCbCr.
%
% map = jet(256);
% newmap = rgb2ycbcr(map);
% See also NTSC2RGB, RGB2NTSC, YCBCR2RGB.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 1.13.4.2 $ $Date: 2003/08/23 05:54:37 $
% Reference:
% C.A. Poynton, "A Technical Introduction to Digital Video", John Wiley
% & Sons, Inc., 1996, p. 175
%initialize variables
isColormap = false;
classin = class(in);
%must reshape colormap to be m x n x 3 for transformation
if (ndims(in)==2)
%colormap
isColormap=true;
colors = size(in,1);
in = reshape(in, [colors 1 3]);
end
% set up constants for transformation
T = [65.481 128.553 24.966;...
-37.797 -74.203 112; ...
112 -93.786 -18.214];
offset = [16;128;128];
offset16 = 257 * offset;
fac8 = 1/255;
fac16 = 257/65535;
%initialize output
out = in;
% do transformation
switch classin
case 'uint8'
for p=1:3
out(:,:,p) = imlincomb(T(p,1)*fac8,in(:,:,1),T(p,2)*fac8,in(:,:,2),...
T(p,3)*fac8,in(:,:,3),offset(p));
end
case 'uint16'
for p=1:3
out(:,:,p) = imlincomb(T(p,1)*fac16,in(:,:,1),T(p,2)*fac16,in(:,:,2),...
T(p,3)*fac16,in(:,:,3),offset16(p));
end
case 'double'
% These equations transform RGB in [0,1] to YCBCR in [0, 255]
for p=1:3
out(:,:,p) = T(p,1) * in(:,:,1) + T(p,2) * in(:,:,2) + T(p,3) * ...
in(:,:,3) + offset(p);
end
out = out / 255;
end
if isColormap
out = reshape(out, [colors 3 1]);
end
|
github
|
jacksky64/imageProcessing-master
|
perform_blsgsm_denoising.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_nlmeans/toolbox/perform_blsgsm_denoising.m
| 41,741 |
utf_8
|
d7adcb441f0d91f470957d7d1083332f
|
function y = perform_blsgsm_denoising(x, options)
% perform_blsgsm_denoising - denoise an image using BLS-GSM
%
% y = perform_blsgsm_denoising(x, options);
%
% BLS-GSM stands for "Bayesian Least Squares - Gaussian Scale Mixture".
%
% This function is a wrapper for the code of J.Portilla.
%
% You can change the following optional parameters
% options.Nor: Number of orientations (for X-Y separable wavelets it can
% only be 3)
% options.repres1: Type of pyramid ('uw': shift-invariant version of an orthogonal wavelet, in this case)
% options.repres2: Type of wavelet (daubechies wavelet, order 2N, for 'daubN'; in this case, 'Haar')
%
% Other parameter that should not be changed unless really needed.
% options.blSize n x n coefficient neighborhood (n must be odd):
% options.parent including or not (1/0) in the
% neighborhood a coefficient from the same spatial location
% options.boundary Boundary mirror extension, to avoid boundary artifacts
% options.covariance Full covariance matrix (1) or only diagonal elements (0).
% options.optim Bayes Least Squares solution (1), or MAP-Wiener solution in two steps (0)
%
% Default parameters favors speed.
% To get the optimal results, one should use:
% options.Nor = 8; 8 orientations
% options.repres1 = 'fs'; Full Steerable Pyramid, 5 scales for 512x512
% options.repres2 = ''; Dummy parameter when using repres1 = 'fs'
% options.parent = 1; Include a parent in the neighborhood
%
% J Portilla, V Strela, M Wainwright, E P Simoncelli,
% "Image Denoising using Scale Mixtures of Gaussians in the Wavelet Domain,"
% IEEE Transactions on Image Processing. vol 12, no. 11, pp. 1338-1351,
% November 2003
%
% Javier Portilla, Universidad de Granada, Spain
% Adapted by Gabriel Peyre in 2007
options.null = 0;
if isfield(options, 'sigma')
sig = options.sigma;
else
sig = perform_noise_estimation(x)
end
[Ny,Nx] = size(x);
% Pyramidal representation parameters
Nsc = ceil(log2(min(Ny,Nx)) - 4); % Number of scales (adapted to the image size)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters
if isfield(options, 'Nor')
Nor = options.Nor;
else
Nor = 3; % Number of orientations (for X-Y separable wavelets it can only be 3)
end
if isfield(options, 'repres1')
repres1 = options.repres1;
else
repres1 = 'uw'; % Type of pyramid (shift-invariant version of an orthogonal wavelet, in this case)
end
if isfield(options, 'repres2')
repres2 = options.repres2;
else
repres2 = 'daub1'; % Type of wavelet (daubechies wavelet, order 2N, for 'daubN'; in this case, 'Haar')
end
% Model parameters (optimized: do not change them unless you are an advanced user with a deep understanding of the theory)
if isfield(options, 'blSize')
blSize = options.blSize;
else
blSize = [3 3]; % n x n coefficient neighborhood of spatial neighbors within the same subband
end
if isfield(options, 'parent')
parent = options.parent;
else
parent = 0; % including or not (1/0) in the neighborhood a coefficient from the same spatial location
end
if isfield(options, 'boundary')
boundary = options.boundary;
else
boundary = 1; % Boundary mirror extension, to avoid boundary artifacts
end
if isfield(options, 'covariance')
covariance = options.covariance;
else
covariance = 1; % Full covariance matrix (1) or only diagonal elements (0).
end
if isfield(options, 'optim')
optim = options.optim;
else
optim = 1; % Bayes Least Squares solution (1), or MAP-Wiener solution in two steps (0)
end
PS = ones(size(x)); % power spectral density (in this case, flat, i.e., white noise)
seed = 0;
% Uncomment the following 4 code lines for reproducing the results of our IEEE Trans. on Im. Proc., Nov. 2003 paper
% This configuration is slower than the previous one, but it gives slightly better results (SNR)
% on average for the test images "lena", "barbara", and "boats" used in the
% cited article.
% Nor = 8; % 8 orientations
% repres1 = 'fs'; % Full Steerable Pyramid, 5 scales for 512x512
% repres2 = ''; % Dummy parameter when using repres1 = 'fs'
% parent = 1; % Include a parent in the neighborhood
% Call the denoising function
y = denoi_BLS_GSM(x, sig, PS, blSize, parent, boundary, Nsc, Nor, covariance, optim, repres1, repres2, seed);
function im_d = denoi_BLS_GSM(im, sig, PS, blSize, parent, boundary, Nsc, Nor, covariance, optim, repres1, repres2, seed);
% [im_d,im,SNR_N,SNR,PSNR] = denoi_BLS_GSM(im, sig, ft, PS, blSize, parent, boundary, Nsc, Nor, covariance, optim, repres1, repres2, seed);
%
% im: input noisy image
% sig: standard deviation of noise
% PS: Power Spectral Density of noise ( fft2(autocorrelation) )
% NOTE: scale factors do not matter. Default is white.
% blSize: 2x1 or 1x2 vector indicating local neighborhood
% ([sY sX], default is [3 3])
% parent: Use parent yes/no (1/0)
% Nsc: Number of scales
% Nor: Number of orientations. For separable wavelets this MUST be 3.
% covariance: Include / Not Include covariance in the GSM model (1/0)
% optim: BLS / MAP-Wiener(2-step) (1/0)
% repres1: Possible choices for representation:
% 'w': orthogonal wavelet
% (uses buildWpyr, reconWpyr)
% repres2 (optional):
% haar: - Haar wavelet.
% qmf8, qmf12, qmf16 - Symmetric Quadrature Mirror Filters [Johnston80]
% daub2,daub3,daub4 - Daubechies wavelet [Daubechies88] (#coef = 2N, para daubN).
% qmf5, qmf9, qmf13: - Symmetric Quadrature Mirror Filters [Simoncelli88,Simoncelli90]
% 'uw': undecimated orthogonal wavelet, Daubechies, pyramidal version
% (uses buildWUpyr, reconWUpyr).
% repres2 (optional): 'daub<N>', where <N> is a positive integer (e.g., 2)
% 's': steerable pyramid [Simoncelli&Freeman95].
% (uses buildSFpyr, reconSFpyr)
% 'fs': full steerable pyramid [Portilla&Simoncelli02].
% (uses buildFullSFpyr2, reconsFullSFpyr2)
% seed (optional): Seed used for generating the Gaussian noise (when ft == 0)
% By default is 0.
%
% im_d: denoising result
% Javier Portilla, Univ. de Granada, 5/02
% revision 31/03/2003
% revision 7/01/2004
% Last revision 15/11/2004
if ~exist('blSize'),
blSzX = 3; % Block size
blSzY = 3;
else
blSzY = blSize(1);
blSzX = blSize(2);
end
if (blSzY/2==floor(blSzY/2))|(blSzX/2==floor(blSzX/2)),
error('Spatial dimensions of neighborhood must be odd!');
end
if ~exist('PS'),
no_white = 0; % Power spectral density of noise. Default is white noise
else
no_white = 1;
end
if ~exist('parent'),
parent = 1;
end
if ~exist('boundary'),
boundary = 1;
end
if ~exist('Nsc'),
Nsc = 4;
end
if ~exist('Nor'),
Nor = 8;
end
if ~exist('covariance'),
covariance = 1;
end
if ~exist('optim'),
optim = 1;
end
if ~exist('repres1'),
repres1 = 'fs';
end
if ~exist('repres2'),
repres2 = '';
end
if (((repres1=='w') | (repres1=='uw')) & (Nor~=3)),
warning('For X-Y separable representations Nor must be 3. Nor = 3 assumed.');
Nor = 3;
end
if ~exist('seed'),
seed = 0;
end
[Ny Nx] = size(im);
% We ensure that the processed image has dimensions that are integer
% multiples of 2^(Nsc+1), so it will not crash when applying the
% pyramidal representation. The idea is padding with mirror reflected
% pixels (thanks to Jesus Malo for this idea).
Npy = ceil(Ny/2^(Nsc+1))*2^(Nsc+1);
Npx = ceil(Nx/2^(Nsc+1))*2^(Nsc+1);
if Npy~=Ny | Npx~=Nx,
Bpy = Npy-Ny;
Bpx = Npx-Nx;
im = bound_extension(im,Bpy,Bpx,'mirror');
im = im(Bpy+1:end,Bpx+1:end); % add stripes only up and right
end
% size of the extension for boundary handling
if (repres1 == 's') | (repres1 == 'fs'),
By = (blSzY-1)*2^(Nsc-2);
Bx = (blSzX-1)*2^(Nsc-2);
else
By = (blSzY-1)*2^(Nsc-1);
Bx = (blSzX-1)*2^(Nsc-1);
end
if ~no_white, % White noise
PS = ones(size(im));
end
% As the dimensions of the power spectral density (PS) support and that of the
% image (im) do not need to be the same, we have to adapt the first to the
% second (zero padding and/or cropping).
PS = fftshift(PS);
isoddPS_y = (size(PS,1)~=2*(floor(size(PS,1)/2)));
isoddPS_x = (size(PS,2)~=2*(floor(size(PS,2)/2)));
PS = PS(1:end-isoddPS_y, 1:end-isoddPS_x); % ensures even dimensions for the power spectrum
PS = fftshift(PS);
[Ndy,Ndx] = size(PS); % dimensions are even
delta = real(ifft2(sqrt(PS)));
delta = fftshift(delta);
aux = delta;
delta = zeros(Npy,Npx);
if (Ndy<=Npy)&(Ndx<=Npx),
delta(Npy/2+1-Ndy/2:Npy/2+Ndy/2,Npx/2+1-Ndx/2:Npx/2+Ndx/2) = aux;
elseif (Ndy>Npy)&(Ndx>Npx),
delta = aux(Ndy/2+1-Npy/2:Ndy/2+Npy/2,Ndx/2+1-Npx/2:Ndx/2+Npx/2);
elseif (Ndy<=Npy)&(Ndx>Npx),
delta(Npy/2+1-Ndy/2:Npy/2+1+Ndy/2-1,:) = aux(:,Ndx/2+1-Npx/2:Ndx/2+Npx/2);
elseif (Ndy>Npy)&(Ndx<=Npx),
delta(:,Npx/2+1-Ndx/2:Npx/2+1+Ndx/2-1) = aux(Ndy/2+1-Npy/2:Ndy/2+1+Npy/2-1,:);
end
if repres1 == 'w',
PS = abs(fft2(delta)).^2;
PS = fftshift(PS);
% noise, to be used only with translation variant transforms (such as orthogonal wavelet)
delta = real(ifft2(sqrt(PS).*exp(j*angle(fft2(randn(size(PS)))))));
end
%Boundary handling: it extends im and delta
if boundary,
im = bound_extension(im,By,Bx,'mirror');
if repres1 == 'w',
delta = bound_extension(delta,By,Bx,'mirror');
else
aux = delta;
delta = zeros(Npy + 2*By, Npx + 2*Bx);
delta(By+1:By+Npy,Bx+1:Bx+Npx) = aux;
end
else
By=0;Bx=0;
end
delta = delta/sqrt(mean2(delta.^2)); % Normalize the energy (the noise variance is given by "sig")
delta = sig*delta; % Impose the desired variance to the noise
% main
t1 = clock;
if repres1 == 's', % standard steerable pyramid
im_d = decomp_reconst(im, Nsc, Nor, [blSzX blSzY], delta, parent,covariance,optim,sig);
elseif repres1 == 'fs', % full steerable pyramid
im_d = decomp_reconst_full(im, Nsc, Nor, [blSzX blSzY], delta, parent, covariance, optim, sig);
elseif repres1 == 'w', % orthogonal wavelet
if ~exist('repres2'),
repres2 = 'daub1';
end
filter = repres2;
im_d = decomp_reconst_W(im, Nsc, filter, [blSzX blSzY], delta, parent, covariance, optim, sig);
elseif repres1 == 'uw', % undecimated daubechies wavelet
if ~exist('repres2'),
repres2 = 'daub1';
end
if repres2(1:4) == 'haar',
daub_order = 2;
else
daub_order = 2*str2num(repres2(5));
end
im_d = decomp_reconst_WU(im, Nsc, daub_order, [blSzX blSzY], delta, parent, covariance, optim, sig);
else
error('Invalid representation parameter. See help info.');
end
t2 = clock;
elaps = t2 - t1;
elaps(4)*3600+elaps(5)*60+elaps(6); % elapsed time, in seconds
im_d = im_d(By+1:By+Npy,Bx+1:Bx+Npx);
im_d = im_d(1:Ny,1:Nx);
function fh = decomp_reconst_full(im,Nsc,Nor,block,noise,parent,covariance,optim,sig);
% Decompose image into subbands, denoise, and recompose again.
% fh = decomp_reconst(im,Nsc,Nor,block,noise,parent,covariance,optim,sig);
% covariance: are we considering covariance or just variance?
% optim: for choosing between BLS-GSM (optim = 1) and MAP-GSM (optim = 0)
% sig: standard deviation (scalar for uniform noise or matrix for spatially varying noise)
% Version using the Full steerable pyramid (2) (High pass residual
% splitted into orientations).
% JPM, Univ. de Granada, 5/02
% Last Revision: 11/04
if (block(1)/2==floor(block(1)/2))|(block(2)/2==floor(block(2)/2)),
error('Spatial dimensions of neighborhood must be odd!');
end
if ~exist('parent'),
parent = 1;
end
if ~exist('covariance'),
covariance = 1;
end
if ~exist('optim'),
optim = 1;
end
if ~exist('sig'),
sig = sqrt(mean(noise.^2));
end
[pyr,pind] = buildFullSFpyr2(im,Nsc,Nor-1);
[pyrN,pind] = buildFullSFpyr2(noise,Nsc,Nor-1);
pyrh = real(pyr);
Nband = size(pind,1)-1;
for nband = 2:Nband, % everything except the low-pass residual
fprintf('%d % ',round(100*(nband-1)/(Nband-1)))
aux = pyrBand(pyr, pind, nband);
auxn = pyrBand(pyrN, pind, nband);
[Nsy,Nsx] = size(aux);
prnt = parent & (nband < Nband-Nor); % has the subband a parent?
BL = zeros(size(aux,1),size(aux,2),1 + prnt);
BLn = zeros(size(aux,1),size(aux,2),1 + prnt);
BL(:,:,1) = aux;
BLn(:,:,1) = auxn*sqrt(((Nsy-2)*(Nsx-2))/(Nsy*Nsx)); % because we are discarding 2 coefficients on every dimension
if prnt,
aux = pyrBand(pyr, pind, nband+Nor);
auxn = pyrBand(pyrN, pind, nband+Nor);
if nband>Nor+1, % resample 2x2 the parent if not in the high-pass oriented subbands.
aux = real(expand(aux,2));
auxn = real(expand(auxn,2));
end
BL(:,:,2) = aux;
BLn(:,:,2) = auxn*sqrt(((Nsy-2)*(Nsx-2))/(Nsy*Nsx)); % because we are discarding 2 coefficients on every dimension
end
sy2 = mean2(BL(:,:,1).^2);
sn2 = mean2(BLn(:,:,1).^2);
if sy2>sn2,
SNRin = 10*log10((sy2-sn2)/sn2);
else
disp('Signal is not detectable in noisy subband');
end
% main
BL = denoi_BLS_GSM_band(BL,block,BLn,prnt,covariance,optim,sig);
pyrh(pyrBandIndices(pind,nband)) = BL(:)';
end
fh = reconFullSFpyr2(pyrh,pind);
function fh = decomp_reconst_W(im,Nsc,filter,block,noise,parent,covariance,optim,sig);
% Decompose image into subbands, denoise using BLS-GSM method, and recompose again.
% fh = decomp_reconst(im,Nsc,filter,block,noise,parent,covariance,optim,sig);
% im: image
% Nsc: number of scales
% filter: type of filter used (see namedFilters)
% block: 2x1 vector indicating the dimensions (rows and columns) of the spatial neighborhood
% noise: signal with the same autocorrelation as the noise
% parent: include (1) or not (0) a coefficient from the immediately coarser scale in the neighborhood
% covariance: are we considering covariance or just variance?
% optim: for choosing between BLS-GSM (optim = 1) and MAP-GSM (optim = 0)
% sig: standard deviation (scalar for uniform noise or matrix for spatially varying noise)
% Version using a critically sampled pyramid (orthogonal wavelet), as implemented in MatlabPyrTools (Eero).
% JPM, Univ. de Granada, 3/03
if (block(1)/2==floor(block(1)/2))|(block(2)/2==floor(block(2)/2)),
error('Spatial dimensions of neighborhood must be odd!');
end
if ~exist('parent'),
parent = 1;
end
if ~exist('covariance'),
covariance = 1;
end
if ~exist('optim'),
optim = 1;
end
if ~exist('sig'),
sig = sqrt(mean(noise.^2));
end
Nor = 3; % number of orientations: vertical, horizontal and mixed diagonals (for compatibility)
[pyr,pind] = buildWpyr(im,Nsc,filter,'circular');
[pyrN,pind] = buildWpyr(noise,Nsc,filter,'circular');
pyrh = pyr;
Nband = size(pind,1);
for nband = 1:Nband-1, % everything except the low-pass residual
fprintf('%d % ',round(100*(nband-1)/(Nband-1)))
aux = pyrBand(pyr, pind, nband);
auxn = pyrBand(pyrN, pind, nband);
prnt = parent & (nband < Nband-Nor); % has the subband a parent?
BL = zeros(size(aux,1),size(aux,2),1 + prnt);
BLn = zeros(size(aux,1),size(aux,2),1 + prnt);
BL(:,:,1) = aux;
BLn(:,:,1) = auxn;
if prnt,
aux = pyrBand(pyr, pind, nband+Nor);
auxn = pyrBand(pyrN, pind, nband+Nor);
aux = real(expand(aux,2));
auxn = real(expand(auxn,2));
BL(:,:,2) = aux;
BLn(:,:,2) = auxn;
end
sy2 = mean2(BL(:,:,1).^2);
sn2 = mean2(BLn(:,:,1).^2);
if sy2>sn2,
SNRin = 10*log10((sy2-sn2)/sn2);
else
disp('Signal is not detectable in noisy subband');
end
% main
BL = denoi_BLS_GSM_band(BL,block,BLn,prnt,covariance,optim,sig);
pyrh(pyrBandIndices(pind,nband)) = BL(:)';
end
fh = reconWpyr(pyrh,pind,filter,'circular');
function fh = decomp_reconst_WU(im,Nsc,daub_order,block,noise,parent,covariance,optim,sig);
% Decompose image into subbands (undecimated wavelet), denoise, and recompose again.
% fh = decomp_reconst_wavelet(im,Nsc,daub_order,block,noise,parent,covariance,optim,sig);
% im : image
% Nsc: Number of scales
% daub_order: Order of the daubechie fucntion used (must be even).
% block: size of neighborhood within each undecimated subband.
% noise: image having the same autocorrelation as the noise (e.g., a delta, for white noise)
% parent: are we including the coefficient at the central location at the next coarser scale?
% covariance: are we considering covariance or just variance?
% optim: for choosing between BLS-GSM (optim = 1) and MAP-GSM (optim = 0)
% sig: standard deviation (scalar for uniform noise or matrix for spatially varying noise)
% Javier Portilla, Univ. de Granada, 3/03
% Revised: 11/04
if (block(1)/2==floor(block(1)/2))|(block(2)/2==floor(block(2)/2)),
error('Spatial dimensions of neighborhood must be odd!');
end
if ~exist('parent'),
parent = 1;
end
if ~exist('covariance'),
covariance = 1;
end
if ~exist('optim'),
optim = 1;
end
if ~exist('sig'),
sig = sqrt(mean(noise.^2));
end
Nor = 3; % Number of orientations: vertical, horizontal and (mixed) diagonals.
[pyr,pind] = buildWUpyr(im,Nsc,daub_order);
[pyrN,pind] = buildWUpyr(noise,Nsc,daub_order);
pyrh = real(pyr);
Nband = size(pind,1)-1;
for nband = 2:Nband, % everything except the low-pass residual
% fprintf('%d % ',round(100*(nband-1)/(Nband-1)))
progressbar(nband-1,Nband-1);
aux = pyrBand(pyr, pind, nband);
auxn = pyrBand(pyrN, pind, nband);
[Nsy, Nsx] = size(aux);
prnt = parent & (nband < Nband-Nor); % has the subband a parent?
BL = zeros(size(aux,1),size(aux,2),1 + prnt);
BLn = zeros(size(aux,1),size(aux,2),1 + prnt);
BL(:,:,1) = aux;
BLn(:,:,1) = auxn*sqrt(((Nsy-2)*(Nsx-2))/(Nsy*Nsx)); % because we are discarding 2 coefficients on every dimension
if prnt,
aux = pyrBand(pyr, pind, nband+Nor);
auxn = pyrBand(pyrN, pind, nband+Nor);
if nband>Nor+1, % resample 2x2 the parent if not in the high-pass oriented subbands.
aux = real(expand(aux,2));
auxn = real(expand(auxn,2));
end
BL(:,:,2) = aux;
BLn(:,:,2) = auxn*sqrt(((Nsy-2)*(Nsx-2))/(Nsy*Nsx)); % because we are discarding 2 coefficients on every dimension
end
sy2 = mean2(BL(:,:,1).^2);
sn2 = mean2(BLn(:,:,1).^2);
if sy2>sn2,
SNRin = 10*log10((sy2-sn2)/sn2);
else
disp('Signal is not detectable in noisy subband');
end
% main
BL = denoi_BLS_GSM_band(BL,block,BLn,prnt,covariance,optim,sig);
pyrh(pyrBandIndices(pind,nband)) = BL(:)';
end
fh = reconWUpyr(pyrh,pind,daub_order);
function fh = decomp_reconst(fn,Nsc,Nor,block,noise,parent,covariance,optim,sig);
% Decompose image into subbands, denoise, and recompose again.
% fh = decomp_reconst(fn,Nsc,Nor,block,noise,parent);
% Javier Portilla, Univ. de Granada, 5/02
% Last revision: 11/04
if (block(1)/2==floor(block(1)/2))|(block(2)/2==floor(block(2)/2)),
error('Spatial dimensions of neighborhood must be odd!');
end
if ~exist('parent'),
parent = 1;
end
if ~exist('covariance'),
covariance = 1;
end
if ~exist('optim'),
optim = 1;
end
[pyr,pind] = buildSFpyr(fn,Nsc,Nor-1);
[pyrN,pind] = buildSFpyr(noise,Nsc,Nor-1);
pyrh = real(pyr);
Nband = size(pind,1);
for nband = 1:Nband -1,
fprintf('%d % ',round(100*nband/(Nband-1)))
aux = pyrBand(pyr, pind, nband);
auxn = pyrBand(pyrN, pind, nband);
[Nsy,Nsx] = size(aux);
prnt = parent & (nband < Nband-1-Nor) & (nband>1);
BL = zeros(size(aux,1),size(aux,2),1 + prnt);
BLn = zeros(size(aux,1),size(aux,2),1 + prnt);
BL(:,:,1) = aux;
BLn(:,:,1) = auxn*sqrt(((Nsy-2)*(Nsx-2))/(Nsy*Nsx)); % because we are discarding 2 coefficients on every dimension
if prnt,
aux = pyrBand(pyr, pind, nband+Nor);
aux = real(expand(aux,2));
auxn = pyrBand(pyrN, pind, nband+Nor);
auxn = real(expand(auxn,2));
BL(:,:,2) = aux;
BLn(:,:,2) = auxn*sqrt(((Nsy-2)*(Nsx-2))/(Nsy*Nsx)); % because we are discarding 2 coefficients on every dimension
end
sy2 = mean2(BL(:,:,1).^2);
sn2 = mean2(BLn(:,:,1).^2);
if sy2>sn2,
SNRin = 10*log10((sy2-sn2)/sn2);
else
disp('Signal is not detectable in noisy subband');
end
% main
BL = denoi_BLS_GSM_band(BL,block,BLn,prnt,covariance,optim,sig);
pyrh(pyrBandIndices(pind,nband)) = BL(:)';
end
fh = reconSFpyr(pyrh,pind);
function x_hat = denoi_BLS_GSM_band(y,block,noise,prnt,covariance,optim,sig);
% It solves for the BLS global optimum solution, using a flat (pseudo)prior for log(z)
% x_hat = denoi_BLS_GSM_band(y,block,noise,prnt,covariance,optim,sig);
%
% prnt: Include/ Not Include parent (1/0)
% covariance: Include / Not Include covariance in the GSM model (1/0)
% optim: BLS / MAP-Wiener(2-step) (1/0)
% JPM, Univ. de Granada, 5/02
% Last revision: JPM, 4/03
if ~exist('covariance'),
covariance = 1;
end
if ~exist('optim'),
optim = 1;
end
[nv,nh,nb] = size(y);
nblv = nv-block(1)+1; % Discard the outer coefficients
nblh = nh-block(2)+1; % for the reference (centrral) coefficients (to avoid boundary effects)
nexp = nblv*nblh; % number of coefficients considered
zM = zeros(nv,nh); % hidden variable z
x_hat = zeros(nv,nh); % coefficient estimation
N = prod(block) + prnt; % size of the neighborhood
Ly = (block(1)-1)/2; % block(1) and block(2) must be odd!
Lx = (block(2)-1)/2;
if (Ly~=floor(Ly))|(Lx~=floor(Lx)),
error('Spatial dimensions of neighborhood must be odd!');
end
cent = floor((prod(block)+1)/2); % reference coefficient in the neighborhood
% (central coef in the fine band)
Y = zeros(nexp,N); % It will be the observed signal (rearranged in nexp neighborhoods)
W = zeros(nexp,N); % It will be a signal with the same autocorrelation as the noise
foo = zeros(nexp,N);
% Compute covariance of noise from 'noise'
n = 0;
for ny = -Ly:Ly, % spatial neighbors
for nx = -Lx:Lx,
n = n + 1;
foo = shift(noise(:,:,1),[ny nx]);
foo = foo(Ly+1:Ly+nblv,Lx+1:Lx+nblh);
W(:,n) = vector(foo);
end
end
if prnt, % parent
n = n + 1;
foo = noise(:,:,2);
foo = foo(Ly+1:Ly+nblv,Lx+1:Lx+nblh);
W(:,n) = vector(foo);
end
C_w = innerProd(W)/nexp;
sig2 = mean(diag(C_w(1:N-prnt,1:N-prnt))); % noise variance in the (fine) subband
clear W;
if ~covariance,
if prnt,
C_w = diag([sig2*ones(N-prnt,1);C_w(N,N)]);
else
C_w = diag(sig2*ones(N,1));
end
end
% Rearrange observed samples in 'nexp' neighborhoods
n = 0;
for ny=-Ly:Ly, % spatial neighbors
for nx=-Lx:Lx,
n = n + 1;
foo = shift(y(:,:,1),[ny nx]);
foo = foo(Ly+1:Ly+nblv,Lx+1:Lx+nblh);
Y(:,n) = vector(foo);
end
end
if prnt, % parent
n = n + 1;
foo = y(:,:,2);
foo = foo(Ly+1:Ly+nblv,Lx+1:Lx+nblh);
Y(:,n) = vector(foo);
end
clear foo
% For modulating the local stdv of noise
if exist('sig') & prod(size(sig))>1,
sig = max(sig,sqrt(1/12)); % Minimum stdv in quantified (integer) pixels
subSampleFactor = log2(sqrt(prod(size(sig))/(nv*nh)));
zW = blurDn(reshape(sig, size(zM)*2^subSampleFactor)/2^subSampleFactor,subSampleFactor);
zW = zW.^2;
zW = zW/mean2(zW); % Expectation{zW} = 1
z_w = vector(zW(Ly+1:Ly+nblv,Lx+1:Lx+nblh));
end
[S,dd] = eig(C_w);
S = S*real(sqrt(dd)); % S*S' = C_w
iS = pinv(S);
clear noise
C_y = innerProd(Y)/nexp;
sy2 = mean(diag(C_y(1:N-prnt,1:N-prnt))); % observed (signal + noise) variance in the subband
C_x = C_y - C_w; % as signal and noise are assumed to be independent
[Q,L] = eig(C_x);
% correct possible negative eigenvalues, without changing the overall variance
L = diag(diag(L).*(diag(L)>0))*sum(diag(L))/(sum(diag(L).*(diag(L)>0))+(sum(diag(L).*(diag(L)>0))==0));
C_x = Q*L*Q';
sx2 = sy2 - sig2; % estimated signal variance in the subband
sx2 = sx2.*(sx2>0); % + (sx2<=0);
if ~covariance,
if prnt,
C_x = diag([sx2*ones(N-prnt,1);C_x(N,N)]);
else
C_x = diag(sx2*ones(N,1));
end
end
[Q,L] = eig(iS*C_x*iS'); % Double diagonalization of signal and noise
la = diag(L); % eigenvalues: energy in the new represetnation.
la = real(la).*(real(la)>0);
% Linearly transform the observations, and keep the quadratic values (we do not model phase)
V = Q'*iS*Y';
clear Y;
V2 = (V.^2).';
M = S*Q;
m = M(cent,:);
% Compute p(Y|log(z))
if 1, % non-informative prior
lzmin = -20.5;
lzmax = 3.5;
step = 2;
else % gamma prior for 1/z
lzmin = -6;
lzmax = 4;
step = 0.5;
end
lzi = lzmin:step:lzmax;
nsamp_z = length(lzi);
zi = exp(lzi);
laz = la*zi;
p_lz = zeros(nexp,nsamp_z);
mu_x = zeros(nexp,nsamp_z);
if ~exist('z_w'), % Spatially invariant noise
pg1_lz = 1./sqrt(prod(1 + laz,1)); % normalization term (depends on z, but not on Y)
aux = exp(-0.5*V2*(1./(1+laz)));
p_lz = aux*diag(pg1_lz); % That gives us the conditional Gaussian density values
% for the observed samples and the considered samples of z
% Compute mu_x(z) = E{x|log(z),Y}
aux = diag(m)*(laz./(1 + laz)); % Remember: laz = la*zi
mu_x = V.'*aux; % Wiener estimation, for each considered sample of z
else % Spatially variant noise
rep_z_w = repmat(z_w, 1, N);
for n_z = 1:nsamp_z,
rep_laz = repmat(laz(:,n_z).',nexp,1);
aux = rep_laz + rep_z_w; % lambda*z_u + z_w
p_lz(:,n_z) = exp(-0.5*sum(V2./aux,2))./sqrt(prod(aux,2));
% Compute mu_x(z) = E{x|log(z),Y,z_w}
aux = rep_laz./aux;
mu_x(:,n_z) = (V.'.*aux)*m.';
end
end
[foo, ind] = max(p_lz.'); % We use ML estimation of z only for the boundaries.
clear foo
if prod(size(ind)) == 0,
z = ones(1,size(ind,2));
else
z = zi(ind).';
end
clear V2 aux
% For boundary handling
uv=1+Ly;
lh=1+Lx;
dv=nblv+Ly;
rh=nblh+Lx;
ul1=ones(uv,lh);
u1=ones(uv-1,1);
l1=ones(1,lh-1);
ur1=ul1;
dl1=ul1;
dr1=ul1;
d1=u1;
r1=l1;
zM(uv:dv,lh:rh) = reshape(z,nblv,nblh);
% Propagation of the ML-estimated z to the boundaries
% a) Corners
zM(1:uv,1:lh)=zM(uv,lh)*ul1;
zM(1:uv,rh:nh)=zM(uv,rh)*ur1;
zM(dv:nv,1:lh)=zM(dv,lh)*dl1;
zM(dv:nv,rh:nh)=zM(dv,rh)*dr1;
% b) Bands
zM(1:uv-1,lh+1:rh-1)=u1*zM(uv,lh+1:rh-1);
zM(dv+1:nv,lh+1:rh-1)=d1*zM(dv,lh+1:rh-1);
zM(uv+1:dv-1,1:lh-1)=zM(uv+1:dv-1,lh)*l1;
zM(uv+1:dv-1,rh+1:nh)=zM(uv+1:dv-1,rh)*r1;
% We do scalar Wiener for the boundary coefficients
if exist('z_w'),
x_hat = y(:,:,1).*(sx2*zM)./(sx2*zM + sig2*zW);
else
x_hat = y(:,:,1).*(sx2*zM)./(sx2*zM + sig2);
end
% Prior for log(z)
p_z = ones(nsamp_z,1); % Flat log-prior (non-informative for GSM)
p_z = p_z/sum(p_z);
% Compute p(log(z)|Y) from p(Y|log(z)) and p(log(z)) (Bayes Rule)
p_lz_y = p_lz*diag(p_z);
clear p_lz
if ~optim,
p_lz_y = (p_lz_y==max(p_lz_y')'*ones(1,size(p_lz_y,2))); % ML in log(z): it becomes a delta function % at the maximum
end
aux = sum(p_lz_y, 2);
if any(aux==0),
foo = aux==0;
p_lz_y = repmat(~foo,1,nsamp_z).*p_lz_y./repmat(aux + foo,1,nsamp_z)...
+ repmat(foo,1,nsamp_z).*repmat(p_z',nexp,1); % Normalizing: p(log(z)|Y)
else
p_lz_y = p_lz_y./repmat(aux,1,nsamp_z); % Normalizing: p(log(z)|Y)
end
clear aux;
% Compute E{x|Y} = int_log(z){ E{x|log(z),Y} p(log(z)|Y) d(log(z)) }
aux = sum(mu_x.*p_lz_y, 2);
x_hat(1+Ly:nblv+Ly,1+Lx:nblh+Lx) = reshape(aux,nblv,nblh);
clear mu_x p_lz_y aux
function im_ext = bound_extension(im,By,Bx,type);
% im_ext = bound_extension(im,B,type);
%
% Extend an image for avoiding boundary artifacts,
%
% By, Bx: widths of the added stripes.
% type: 'mirror' Mirror extension
% 'mirror_nr': Mirror without repeating the last pixel
% 'circular': fft2-like
% 'zeros'
% Javier Portilla, Universidad de Granada, Jan 2004
[Ny,Nx,Nc] = size(im);
im_ext = zeros(Ny+2*By,Nx+2*Bx,Nc);
im_ext(By+1:Ny+By,Bx+1:Nx+Bx,:) = im;
if strcmp(type,'mirror'),
im_ext(1:By,:,:) = im_ext(2*By:-1:By+1,:,:);
im_ext(:,1:Bx,:) = im_ext(:,2*Bx:-1:Bx+1,:);
im_ext(Ny+1+By:Ny+2*By,:,:) = im_ext(Ny+By:-1:Ny+1,:,:);
im_ext(:,Nx+1+Bx:Nx+2*Bx,:) = im_ext(:,Nx+Bx:-1:Nx+1,:);
im_ext(1:By,1:Bx,:) = im_ext(2*By:-1:By+1,2*Bx:-1:Bx+1,:);
im_ext(Ny+1+By:Ny+2*By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(Ny+By:-1:Ny+1,Nx+Bx:-1:Nx+1,:);
im_ext(1:By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(2*By:-1:By+1,Nx+Bx:-1:Nx+1,:);
im_ext(Ny+1+By:Ny+2*By,1:Bx,:) = im_ext(Ny+By:-1:Ny+1,2*Bx:-1:Bx+1,:);
elseif strcmp(type,'mirror_nr'),
im_ext(1:By,:,:) = im_ext(2*By+1:-1:By+2,:,:);
im_ext(:,1:Bx,:) = im_ext(:,2*Bx+1:-1:Bx+2,:);
im_ext(Ny+1+By:Ny+2*By,:,:) = im_ext(Ny+By-1:-1:Ny,:,:);
im_ext(:,Nx+1+Bx:Nx+2*Bx,:) = im_ext(:,Nx+Bx-1:-1:Nx,:);
im_ext(1:By,1:Bx,:) = im_ext(2*By+1:-1:By+2,2*Bx+1:-1:Bx+2,:);
im_ext(Ny+1+By:Ny+2*By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(Ny+By-1:-1:Ny,Nx+Bx-1:-1:Nx,:);
im_ext(1:By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(2*By+1:-1:By+2,Nx+Bx-1:-1:Nx,:);
im_ext(Ny+1+By:Ny+2*By,1:Bx,:) = im_ext(Ny+By-1:-1:Ny,2*Bx+1:-1:Bx+2,:);
elseif strcmp(type,'circular'),
im_ext(1:By,:,:) = im_ext(Ny+1:Ny+By,:,:);
im_ext(:,1:Bx,:) = im_ext(:,Nx+1:Nx+Bx,:);
im_ext(Ny+1+By:Ny+2*By,:,:) = im_ext(By+1:2*By,:,:);
im_ext(:,Nx+1+Bx:Nx+2*Bx,:) = im_ext(:,Bx+1:2*Bx,:);
im_ext(1:By,1:Bx,:) = im_ext(Ny+1:Ny+By,Nx+1:Nx+Bx,:);
im_ext(Ny+1+By:Ny+2*By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(By+1:2*By,Bx+1:2*Bx,:);
im_ext(1:By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(Ny+1:Ny+By,Bx+1:2*Bx,:);
im_ext(Ny+1+By:Ny+2*By,1:Bx,:) = im_ext(By+1:2*By,Nx+1:Nx+Bx,:);
end
% M = MEAN2(MTX)
%
% Sample mean of a matrix.
function res = mean2(mtx)
res = mean(mean(mtx));
function [pyr,pind] = buildWUpyr(im, Nsc, daub_order);
% [PYR, INDICES] = buildWUpyr(IM, HEIGHT, DAUB_ORDER)
%
% Construct a separable undecimated orthonormal QMF/wavelet pyramid
% on matrix (or vector) IM.
%
% HEIGHT specifies the number of pyramid levels to build. Default
% is maxPyrHt(IM,FILT). You can also specify 'auto' to use this value.
%
% DAUB_ORDER: specifies the order of the daubechies wavelet filter used
%
% PYR is a vector containing the N pyramid subbands, ordered from fine
% to coarse. INDICES is an Nx2 matrix containing the sizes of
% each subband.
% JPM, Univ. de Granada, 03/2003, based on Rice Wavelet Toolbox
% function "mrdwt" and on Matlab Pyrtools from Eero Simoncelli.
if Nsc < 1,
display('Error: Number of scales must be >=1.');
else,
Nor = 3; % fixed number of orientations;
h = daubcqf(daub_order);
[lpr,yh] = mrdwt(im, h, Nsc+1); % performs the decomposition
[Ny,Nx] = size(im);
% Reorganize the output, forcing the same format as with buildFullSFpyr2
pyr = [];
pind = zeros((Nsc+1)*Nor+2,2); % Room for a "virtual" high pass residual, for compatibility
nband = 1;
for nsc = 1:Nsc+1,
for nor = 1:Nor,
nband = nband + 1;
band = yh(:,(nband-2)*Nx+1:(nband-1)*Nx);
sh = (daub_order/2 - 1)*2^nsc; % approximate phase compensation
if nor == 1, % horizontal
band = shift(band, [sh 2^(nsc-1)]);
elseif nor == 2, % vertical
band = shift(band, [2^(nsc-1) sh]);
else
band = shift(band, [sh sh]); % diagonal
end
if nsc>2,
band = real(shrink(band,2^(nsc-2))); % The low freq. bands are shrunk in the freq. domain
end
pyr = [pyr; vector(band)];
pind(nband,:) = size(band);
end
end
band = lpr;
band = shrink(band,2^Nsc);
pyr = [pyr; vector(band)];
pind(nband+1,:) = size(band);
end
function [h_0,h_1] = daubcqf(N,TYPE)
% [h_0,h_1] = daubcqf(N,TYPE);
%
% Function computes the Daubechies' scaling and wavelet filters
% (normalized to sqrt(2)).
%
% Input:
% N : Length of filter (must be even)
% TYPE : Optional parameter that distinguishes the minimum phase,
% maximum phase and mid-phase solutions ('min', 'max', or
% 'mid'). If no argument is specified, the minimum phase
% solution is used.
%
% Output:
% h_0 : Minimal phase Daubechies' scaling filter
% h_1 : Minimal phase Daubechies' wavelet filter
%
% Example:
% N = 4;
% TYPE = 'min';
% [h_0,h_1] = daubcqf(N,TYPE)
% h_0 = 0.4830 0.8365 0.2241 -0.1294
% h_1 = 0.1294 0.2241 -0.8365 0.4830
%
% Reference: "Orthonormal Bases of Compactly Supported Wavelets",
% CPAM, Oct.89
%
%File Name: daubcqf.m
%Last Modification Date: 01/02/96 15:12:57
%Current Version: daubcqf.m 2.4
%File Creation Date: 10/10/88
%Author: Ramesh Gopinath <[email protected]>
%
%Copyright (c) 2000 RICE UNIVERSITY. All rights reserved.
%Created by Ramesh Gopinath, Department of ECE, Rice University.
%
%This software is distributed and licensed to you on a non-exclusive
%basis, free-of-charge. Redistribution and use in source and binary forms,
%with or without modification, are permitted provided that the following
%conditions are met:
%
%1. Redistribution of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%2. Redistribution in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%3. All advertising materials mentioning features or use of this software
% must display the following acknowledgment: This product includes
% software developed by Rice University, Houston, Texas and its contributors.
%4. Neither the name of the University nor the names of its contributors
% may be used to endorse or promote products derived from this software
% without specific prior written permission.
%
%THIS SOFTWARE IS PROVIDED BY WILLIAM MARSH RICE UNIVERSITY, HOUSTON, TEXAS,
%AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
%BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
%FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RICE UNIVERSITY
%OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
%EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
%PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
%OR BUSINESS INTERRUPTIONS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
%WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
%OTHERWISE), PRODUCT LIABILITY, OR OTHERWISE ARISING IN ANY WAY OUT OF THE
%USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
%For information on commercial licenses, contact Rice University's Office of
%Technology Transfer at [email protected] or (713) 348-6173
if(nargin < 2),
TYPE = 'min';
end;
if(rem(N,2) ~= 0),
error('No Daubechies filter exists for ODD length');
end;
K = N/2;
a = 1;
p = 1;
q = 1;
h_0 = [1 1];
for j = 1:K-1,
a = -a * 0.25 * (j + K - 1)/j;
h_0 = [0 h_0] + [h_0 0];
p = [0 -p] + [p 0];
p = [0 -p] + [p 0];
q = [0 q 0] + a*p;
end;
q = sort(roots(q));
qt = q(1:K-1);
if TYPE=='mid',
if rem(K,2)==1,
qt = q([1:4:N-2 2:4:N-2]);
else
qt = q([1 4:4:K-1 5:4:K-1 N-3:-4:K N-4:-4:K]);
end;
end;
h_0 = conv(h_0,real(poly(qt)));
h_0 = sqrt(2)*h_0/sum(h_0); %Normalize to sqrt(2);
if(TYPE=='max'),
h_0 = fliplr(h_0);
end;
if(abs(sum(h_0 .^ 2))-1 > 1e-4)
error('Numerically unstable for this value of "N".');
end;
h_1 = rot90(h_0,2);
h_1(1:2:N)=-h_1(1:2:N);
% [RES] = shift(MTX, OFFSET)
%
% Circular shift 2D matrix samples by OFFSET (a [Y,X] 2-vector),
% such that RES(POS) = MTX(POS-OFFSET).
function res = shift(mtx, offset)
dims = size(mtx);
offset = mod(-offset,dims);
res = [ mtx(offset(1)+1:dims(1), offset(2)+1:dims(2)), ...
mtx(offset(1)+1:dims(1), 1:offset(2)); ...
mtx(1:offset(1), offset(2)+1:dims(2)), ...
mtx(1:offset(1), 1:offset(2)) ];
% [VEC] = vector(MTX)
%
% Pack elements of MTX into a column vector. Same as VEC = MTX(:)
% Previously named "vectorize" (changed to avoid overlap with Matlab's
% "vectorize" function).
function vec = vector(mtx)
vec = mtx(:);
function ts = shrink(t,f)
% im_shr = shrink(im0, f)
%
% It shrinks (spatially) an image into a factor f
% in each dimension. It does it by cropping the
% Fourier transform of the image.
% JPM, 5/1/95.
% Revised so it can work also with exponents of 3 factors: JPM 5/2003
[my,mx] = size(t);
T = fftshift(fft2(t))/f^2;
Ts = zeros(my/f,mx/f);
cy = ceil(my/2);
cx = ceil(mx/2);
evenmy = (my/2==floor(my/2));
evenmx = (mx/2==floor(mx/2));
y1 = cy + 2*evenmy - floor(my/(2*f));
y2 = cy + floor(my/(2*f));
x1 = cx + 2*evenmx - floor(mx/(2*f));
x2 = cx + floor(mx/(2*f));
Ts(1+evenmy:my/f,1+evenmx:mx/f)=T(y1:y2,x1:x2);
if evenmy,
Ts(1+evenmy:my/f,1)=(T(y1:y2,x1-1)+T(y1:y2,x2+1))/2;
end
if evenmx,
Ts(1,1+evenmx:mx/f)=(T(y1-1,x1:x2)+T(y2+1,x1:x2))/2;
end
if evenmy & evenmx,
Ts(1,1)=(T(y1-1,x1-1)+T(y1-1,x2+1)+T(y2+1,x1-1)+T(y2+1,x2+1))/4;
end
Ts = fftshift(Ts);
Ts = shift(Ts, [1 1] - [evenmy evenmx]);
ts = ifft2(Ts);
% RES = pyrBand(PYR, INDICES, BAND_NUM)
%
% Access a subband from a pyramid (gaussian, laplacian, QMF/wavelet,
% or steerable). Subbands are numbered consecutively, from finest
% (highest spatial frequency) to coarsest (lowest spatial frequency).
% Eero Simoncelli, 6/96.
function res = pyrBand(pyr, pind, band)
res = reshape( pyr(pyrBandIndices(pind,band)), pind(band,1), pind(band,2) );
% RES = pyrBandIndices(INDICES, BAND_NUM)
%
% Return indices for accessing a subband from a pyramid
% (gaussian, laplacian, QMF/wavelet, steerable).
% Eero Simoncelli, 6/96.
function indices = pyrBandIndices(pind,band)
if ((band > size(pind,1)) | (band < 1))
error(sprintf('BAND_NUM must be between 1 and number of pyramid bands (%d).', ...
size(pind,1)));
end
if (size(pind,2) ~= 2)
error('INDICES must be an Nx2 matrix indicating the size of the pyramid subbands');
end
ind = 1;
for l=1:band-1
ind = ind + prod(pind(l,:));
end
indices = ind:ind+prod(pind(band,:))-1;
function res = reconWUpyr(pyr, pind, daub_order);
% RES = reconWUpyr(PYR, INDICES, DAUB_ORDER)
% Reconstruct image from its separable undecimated orthonormal QMF/wavelet pyramid
% representation, as created by buildWUpyr.
%
% PYR is a vector containing the N pyramid subbands, ordered from fine
% to coarse. INDICES is an Nx2 matrix containing the sizes of
% each subband.
%
% DAUB_ORDER: specifies the order of the daubechies wavelet filter used
% JPM, Univ. de Granada, 03/2003, based on Rice Wavelet Toolbox
% functions "mrdwt" and "mirdwt", and on Matlab Pyrtools from Eero Simoncelli.
Nor = 3;
Nsc = (size(pind,1)-2)/Nor-1;
h = daubcqf(daub_order);
yh = [];
nband = 1;
last = prod(pind(1,:)); % empty "high pass residual band" for compatibility with full steerpyr 2
for nsc = 1:Nsc+1, % The number of scales corresponds to the number of pyramid levels (also for compatibility)
for nor = 1:Nor,
nband = nband +1;
first = last + 1;
last = first + prod(pind(nband,:)) - 1;
band = pyrBand(pyr,pind,nband);
sh = (daub_order/2 - 1)*2^nsc; % approximate phase compensation
if nsc > 2,
band = expand(band, 2^(nsc-2));
end
if nor == 1, % horizontal
band = shift(band, [-sh -2^(nsc-1)]);
elseif nor == 2, % vertical
band = shift(band, [-2^(nsc-1) -sh]);
else
band = shift(band, [-sh -sh]); % diagonal
end
yh = [yh band];
end
end
nband = nband + 1;
band = pyrBand(pyr,pind,nband);
lpr = expand(band,2^Nsc);
res= mirdwt(lpr,yh,h,Nsc+1);
function te = expand(t,f)
% im_exp = expand(im0, f)
%
% It expands (spatially) an image into a factor f
% in each dimension. It does it filling in with zeros
% the expanded Fourier domain.
% JPM, 5/1/95.
% Revised so it can work also with exponents of 3 factors: JPM 5/2003
[my mx] = size(t);
my = f*my;
mx = f*mx;
Te = zeros(my,mx);
T = f^2*fftshift(fft2(t));
cy = ceil(my/2);
cx = ceil(mx/2);
evenmy = (my/2==floor(my/2));
evenmx = (mx/2==floor(mx/2));
y1 = cy + 2*evenmy - floor(my/(2*f));
y2 = cy + floor(my/(2*f));
x1 = cx + 2*evenmx - floor(mx/(2*f));
x2 = cx + floor(mx/(2*f));
Te(y1:y2,x1:x2)=T(1+evenmy:my/f,1+evenmx:mx/f);
if evenmy,
Te(y1-1,x1:x2)=T(1,2:mx/f)/2;
Te(y2+1,x1:x2)=((T(1,mx/f:-1:2)/2)').';
end
if evenmx,
Te(y1:y2,x1-1)=T(2:my/f,1)/2;
Te(y1:y2,x2+1)=((T(my/f:-1:2,1)/2)').';
end
if evenmx & evenmy,
esq=T(1,1)/4;
Te(y1-1,x1-1)=esq;
Te(y1-1,x2+1)=esq;
Te(y2+1,x1-1)=esq;
Te(y2+1,x2+1)=esq;
end
Te=fftshift(Te);
Te = shift(Te, [1 1] - [evenmy evenmx]);
te=ifft2(Te);
% RES = innerProd(MTX)
%
% Compute (MTX' * MTX) efficiently (i.e., without copying the matrix)
function res = innerProd(mtx)
%% NOTE: THIS CODE SHOULD NOT BE USED! (MEX FILE IS CALLED INSTEAD)
% fprintf(1,'WARNING: You should compile the MEX version of "innerProd.c",\n found in the MEX subdirectory of matlabPyrTools, and put it in your matlab path. It is MUCH faster.\n');
res = mtx' * mtx;
|
github
|
jacksky64/imageProcessing-master
|
perform_wavelet_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_nlmeans/toolbox/perform_wavelet_transform.m
| 61,619 |
utf_8
|
ff04288ce6da8a2b6a0d33e1c20c57b6
|
function y = perform_wavelet_transform(x, Jmin, dir, options)
% perform_wavelet_transform - wrapper to wavelab Wavelet transform (1D/2D and orthogonal/biorthogonal).
%
% y = perform_wavelet_transform(x, Jmin, dir, options);
%
% 'x' is either a 1D or a 2D array.
% 'Jmin' is the minimum scale (i.e. the coarse channel is of size 2^Jmin
% in 1D).
% 'dir' is +1 for fwd transform and -1 for bwd.
% 'options.wavelet_vm' is the number of Vanishing moment (both for primal and dual).
% 'options.wavelet_type' can be
% 'daubechies', 'symmlet', 'battle', 'biorthogonal'.
%
% Typical use :
% M = <load your image here>;
% Jmin = 4;
% options.wavelet_type = 'biorthogonal_swapped';
% options.wavelet_vm = 4;
% MW = perform_wavelet_transform(M, Jmin, +1, options);
% Mt = <perform some modification on MW>
% M = perform_wavelet_transform(Mt, Jmin, -1, options);
%
% 'y' is an array of the same size as 'x'. This means that for the 2D
% we are stuck to the wavelab coding style, i.e. the result
% of each transform is an array organized using Mallat's ordering
% (whereas Matlab official toolbox use a 1D ordering for the 2D transform).
%
% Here the transform automaticaly select symmetric boundary condition
% if you use a symmetric filter. If your filter is not symmetric
% (e.g. Dauechies filters) then as the output must have same length
% as the input, the boundary condition are automatically set to periodic.
%
% You do not need Wavelab to use this function (the Wavelab .m file are
% included in this script). However, for faster execution time, you
% should install the mex file within the Wavelab distribution.
% http://www-stat.stanford.edu/~wavelab/
%
% Copyright (c) 2005 Gabriel Peyr?
if nargin<3
dir = 1;
end
if nargin<2
Jmin = 3;
end
options.null = 0;
if isfield(options, 'wavelet_type')
wavelet_type = options.wavelet_type;
else
wavelet_type = 'daubechies';
end
if isfield(options, 'wavelet_vm')
VM = options.wavelet_vm;
else
VM = 4;
end
if isfield(options, 'ti')
% for translation-invariant transform
ti = options.ti;
else
ti = 0;
end
ndim = length(size(x));
if ndim==2 && ( size(x,2)==1 || size(x,1)==1 )
ndim=1;
end
% for color images
if ndims(x)>2
y = x;
for i=1:size(x,3)
y(:,:,i) = perform_wavelet_transform(x(:,:,i), Jmin, dir, options);
end
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% WAVELAB
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% generate filters
switch lower(wavelet_type)
case 'daubechies'
qmf = MakeONFilter('Daubechies',VM*2); % in Wavelab, 2nd argument is VM*2 for Daubechies... no comment ...
case 'haar'
qmf = MakeONFilter('Haar'); % in Wavelab, 2nd argument is VM*2 for Daubechies... no comment ...
case 'symmlet'
qmf = MakeONFilter('Symmlet',VM);
case 'battle'
qmf = MakeONFilter('Battle',VM-1);
dqmf = qmf; % we need dual filter
case 'biorthogonal'
[qmf,dqmf] = MakeBSFilter( 'CDF', [VM,VM] );
case 'biorthogonal_swapped'
[dqmf,qmf] = MakeBSFilter( 'CDF', [VM,VM] );
otherwise
error('Unknown transform.');
end
% translation invariant transform
if ti
if ndim==2 && size(x,2)<50
ndim = 1;
end
if ndim==1
if dir==1
y = TI2Stat( FWT_TI(x,Jmin,qmf) );
else
y = IWT_TI( Stat2TI(x),qmf);
end
elseif ndim==2
if dir==1
y = FWT2_TI(x,Jmin,qmf);
else
y = IWT2_TI(x,Jmin,qmf);
end
end
return;
end
% perform transform
if ~exist('dqmf')
%%% ORTHOGONAL %%%
if ndim==1
if dir==1
y = FWT_PO(x,Jmin,qmf);
else
y = IWT_PO(x,Jmin,qmf);
end
elseif ndim==2
if dir==1
y = FWT2_PO(x,Jmin,qmf);
else
y = IWT2_PO(x,Jmin,qmf);
end
end
else
%%% BI-ORTHOGONAL %%%
if ndim==1
if dir==1
y = FWT_SBS(x,Jmin,qmf,dqmf);
else
y = IWT_SBS(x,Jmin,qmf,dqmf);
end
elseif ndim==2
if dir==1
y = FWT2_SBS(x,Jmin,qmf,dqmf);
else
y = IWT2_SBS(x,Jmin,qmf,dqmf);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% WAVELAB DISTRIBUTION -- http://www-stat.stanford.edu/~wavelab/
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% WAVELAB DISTRIBUTION -- http://www-stat.stanford.edu/~wavelab/
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = MakeONFilter(Type,Par)
% MakeONFilter -- Generate Orthonormal QMF Filter for Wavelet Transform
% Usage
% qmf = MakeONFilter(Type,Par)
% Inputs
% Type string, 'Haar', 'Beylkin', 'Coiflet', 'Daubechies',
% 'Symmlet', 'Vaidyanathan','Battle'
% Par integer, it is a parameter related to the support and vanishing
% moments of the wavelets, explained below for each wavelet.
%
% Outputs
% qmf quadrature mirror filter
%
% Description
% The Haar filter (which could be considered a Daubechies-2) was the
% first wavelet, though not called as such, and is discontinuous.
%
% The Beylkin filter places roots for the frequency response function
% close to the Nyquist frequency on the real axis.
%
% The Coiflet filters are designed to give both the mother and father
% wavelets 2*Par vanishing moments; here Par may be one of 1,2,3,4 or 5.
%
% The Daubechies filters are minimal phase filters that generate wavelets
% which have a minimal support for a given number of vanishing moments.
% They are indexed by their length, Par, which may be one of
% 4,6,8,10,12,14,16,18 or 20. The number of vanishing moments is par/2.
%
% Symmlets are also wavelets within a minimum size support for a given
% number of vanishing moments, but they are as symmetrical as possible,
% as opposed to the Daubechies filters which are highly asymmetrical.
% They are indexed by Par, which specifies the number of vanishing
% moments and is equal to half the size of the support. It ranges
% from 4 to 10.
%
% The Vaidyanathan filter gives an exact reconstruction, but does not
% satisfy any moment condition. The filter has been optimized for
% speech coding.
%
% The Battle-Lemarie filter generate spline orthogonal wavelet basis.
% The parameter Par gives the degree of the spline. The number of
% vanishing moments is Par+1.
%
% See Also
% FWT_PO, IWT_PO, FWT2_PO, IWT2_PO, WPAnalysis
%
% References
% The books by Daubechies and Wickerhauser.
%
if strcmp(Type,'Haar'),
f = [1 1] ./ sqrt(2);
end
if strcmp(Type,'Beylkin'),
f = [ .099305765374 .424215360813 .699825214057 ...
.449718251149 -.110927598348 -.264497231446 ...
.026900308804 .155538731877 -.017520746267 ...
-.088543630623 .019679866044 .042916387274 ...
-.017460408696 -.014365807969 .010040411845 ...
.001484234782 -.002736031626 .000640485329 ];
end
if strcmp(Type,'Coiflet'),
if Par==1,
f = [ .038580777748 -.126969125396 -.077161555496 ...
.607491641386 .745687558934 .226584265197 ];
end
if Par==2,
f = [ .016387336463 -.041464936782 -.067372554722 ...
.386110066823 .812723635450 .417005184424 ...
-.076488599078 -.059434418646 .023680171947 ...
.005611434819 -.001823208871 -.000720549445 ];
end
if Par==3,
f = [ -.003793512864 .007782596426 .023452696142 ...
-.065771911281 -.061123390003 .405176902410 ...
.793777222626 .428483476378 -.071799821619 ...
-.082301927106 .034555027573 .015880544864 ...
-.009007976137 -.002574517688 .001117518771 ...
.000466216960 -.000070983303 -.000034599773 ];
end
if Par==4,
f = [ .000892313668 -.001629492013 -.007346166328 ...
.016068943964 .026682300156 -.081266699680 ...
-.056077313316 .415308407030 .782238930920 ...
.434386056491 -.066627474263 -.096220442034 ...
.039334427123 .025082261845 -.015211731527 ...
-.005658286686 .003751436157 .001266561929 ...
-.000589020757 -.000259974552 .000062339034 ...
.000031229876 -.000003259680 -.000001784985 ];
end
if Par==5,
f = [ -.000212080863 .000358589677 .002178236305 ...
-.004159358782 -.010131117538 .023408156762 ...
.028168029062 -.091920010549 -.052043163216 ...
.421566206729 .774289603740 .437991626228 ...
-.062035963906 -.105574208706 .041289208741 ...
.032683574283 -.019761779012 -.009164231153 ...
.006764185419 .002433373209 -.001662863769 ...
-.000638131296 .000302259520 .000140541149 ...
-.000041340484 -.000021315014 .000003734597 ...
.000002063806 -.000000167408 -.000000095158 ];
end
end
if strcmp(Type,'Daubechies'),
if Par==4,
f = [ .482962913145 .836516303738 ...
.224143868042 -.129409522551 ];
end
if Par==6,
f = [ .332670552950 .806891509311 ...
.459877502118 -.135011020010 ...
-.085441273882 .035226291882 ];
end
if Par==8,
f = [ .230377813309 .714846570553 ...
.630880767930 -.027983769417 ...
-.187034811719 .030841381836 ...
.032883011667 -.010597401785 ];
end
if Par==10,
f = [ .160102397974 .603829269797 .724308528438 ...
.138428145901 -.242294887066 -.032244869585 ...
.077571493840 -.006241490213 -.012580751999 ...
.003335725285 ];
end
if Par==12,
f = [ .111540743350 .494623890398 .751133908021 ...
.315250351709 -.226264693965 -.129766867567 ...
.097501605587 .027522865530 -.031582039317 ...
.000553842201 .004777257511 -.001077301085 ];
end
if Par==14,
f = [ .077852054085 .396539319482 .729132090846 ...
.469782287405 -.143906003929 -.224036184994 ...
.071309219267 .080612609151 -.038029936935 ...
-.016574541631 .012550998556 .000429577973 ...
-.001801640704 .000353713800 ];
end
if Par==16,
f = [ .054415842243 .312871590914 .675630736297 ...
.585354683654 -.015829105256 -.284015542962 ...
.000472484574 .128747426620 -.017369301002 ...
-.044088253931 .013981027917 .008746094047 ...
-.004870352993 -.000391740373 .000675449406 ...
-.000117476784 ];
end
if Par==18,
f = [ .038077947364 .243834674613 .604823123690 ...
.657288078051 .133197385825 -.293273783279 ...
-.096840783223 .148540749338 .030725681479 ...
-.067632829061 .000250947115 .022361662124 ...
-.004723204758 -.004281503682 .001847646883 ...
.000230385764 -.000251963189 .000039347320 ];
end
if Par==20,
f = [ .026670057901 .188176800078 .527201188932 ...
.688459039454 .281172343661 -.249846424327 ...
-.195946274377 .127369340336 .093057364604 ...
-.071394147166 -.029457536822 .033212674059 ...
.003606553567 -.010733175483 .001395351747 ...
.001992405295 -.000685856695 -.000116466855 ...
.000093588670 -.000013264203 ];
end
end
if strcmp(Type,'Symmlet'),
if Par==4,
f = [ -.107148901418 -.041910965125 .703739068656 ...
1.136658243408 .421234534204 -.140317624179 ...
-.017824701442 .045570345896 ];
end
if Par==5,
f = [ .038654795955 .041746864422 -.055344186117 ...
.281990696854 1.023052966894 .896581648380 ...
.023478923136 -.247951362613 -.029842499869 ...
.027632152958 ];
end
if Par==6,
f = [ .021784700327 .004936612372 -.166863215412 ...
-.068323121587 .694457972958 1.113892783926 ...
.477904371333 -.102724969862 -.029783751299 ...
.063250562660 .002499922093 -.011031867509 ];
end
if Par==7,
f = [ .003792658534 -.001481225915 -.017870431651 ...
.043155452582 .096014767936 -.070078291222 ...
.024665659489 .758162601964 1.085782709814 ...
.408183939725 -.198056706807 -.152463871896 ...
.005671342686 .014521394762 ];
end
if Par==8,
f = [ .002672793393 -.000428394300 -.021145686528 ...
.005386388754 .069490465911 -.038493521263 ...
-.073462508761 .515398670374 1.099106630537 ...
.680745347190 -.086653615406 -.202648655286 ...
.010758611751 .044823623042 -.000766690896 ...
-.004783458512 ];
end
if Par==9,
f = [ .001512487309 -.000669141509 -.014515578553 ...
.012528896242 .087791251554 -.025786445930 ...
-.270893783503 .049882830959 .873048407349 ...
1.015259790832 .337658923602 -.077172161097 ...
.000825140929 .042744433602 -.016303351226 ...
-.018769396836 .000876502539 .001981193736 ];
end
if Par==10,
f = [ .001089170447 .000135245020 -.012220642630 ...
-.002072363923 .064950924579 .016418869426 ...
-.225558972234 -.100240215031 .667071338154 ...
1.088251530500 .542813011213 -.050256540092 ...
-.045240772218 .070703567550 .008152816799 ...
-.028786231926 -.001137535314 .006495728375 ...
.000080661204 -.000649589896 ];
end
end
if strcmp(Type,'Vaidyanathan'),
f = [ -.000062906118 .000343631905 -.000453956620 ...
-.000944897136 .002843834547 .000708137504 ...
-.008839103409 .003153847056 .019687215010 ...
-.014853448005 -.035470398607 .038742619293 ...
.055892523691 -.077709750902 -.083928884366 ...
.131971661417 .135084227129 -.194450471766 ...
-.263494802488 .201612161775 .635601059872 ...
.572797793211 .250184129505 .045799334111 ];
end
if strcmp(Type,'Battle'),
if Par == 1,
g = [0.578163 0.280931 -0.0488618 -0.0367309 ...
0.012003 0.00706442 -0.00274588 -0.00155701 ...
0.000652922 0.000361781 -0.000158601 -0.0000867523
];
end
if Par == 3,
g = [0.541736 0.30683 -0.035498 -0.0778079 ...
0.0226846 0.0297468 -0.0121455 -0.0127154 ...
0.00614143 0.00579932 -0.00307863 -0.00274529 ...
0.00154624 0.00133086 -0.000780468 -0.00065562 ...
0.000395946 0.000326749 -0.000201818 -0.000164264 ...
0.000103307
];
end
if Par == 5,
g = [0.528374 0.312869 -0.0261771 -0.0914068 ...
0.0208414 0.0433544 -0.0148537 -0.0229951 ...
0.00990635 0.0128754 -0.00639886 -0.00746848 ...
0.00407882 0.00444002 -0.00258816 -0.00268646 ...
0.00164132 0.00164659 -0.00104207 -0.00101912 ...
0.000662836 0.000635563 -0.000422485 -0.000398759 ...
0.000269842 0.000251419 -0.000172685 -0.000159168 ...
0.000110709 0.000101113
];
end
l = length(g);
f = zeros(1,2*l-1);
f(l:2*l-1) = g;
f(1:l-1) = reverse(g(2:l));
end
f = f ./ norm(f);
%
% Copyright (c) 1993-5. Jonathan Buckheit and David Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function wcoef = FWT_PO(x,L,qmf)
% FWT_PO -- Forward Wavelet Transform (periodized, orthogonal)
% Usage
% wc = FWT_PO(x,L,qmf)
% Inputs
% x 1-d signal; length(x) = 2^J
% L Coarsest Level of V_0; L << J
% qmf quadrature mirror filter (orthonormal)
% Outputs
% wc 1-d wavelet transform of x.
%
% Description
% 1. qmf filter may be obtained from MakeONFilter
% 2. usually, length(qmf) < 2^(L+1)
% 3. To reconstruct use IWT_PO
%
% See Also
% IWT_PO, MakeONFilter
%
[n,J] = dyadlength(x) ;
wcoef = zeros(1,n) ;
beta = ShapeAsRow(x); %take samples at finest scale as beta-coeffts
for j=J-1:-1:L
alfa = DownDyadHi(beta,qmf);
wcoef(dyad(j)) = alfa;
beta = DownDyadLo(beta,qmf) ;
end
wcoef(1:(2^L)) = beta;
wcoef = ShapeLike(wcoef,x);
%
% Copyright (c) 1993. Iain M. Johnstone
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function [n,J] = dyadlength(x)
% dyadlength -- Find length and dyadic length of array
% Usage
% [n,J] = dyadlength(x)
% Inputs
% x array of length n = 2^J (hopefully)
% Outputs
% n length(x)
% J least power of two greater than n
%
% Side Effects
% A warning is issued if n is not a power of 2.
%
% See Also
% quadlength, dyad, dyad2ix
%
n = length(x) ;
J = ceil(log(n)/log(2));
if 2^J ~= n ,
disp('Warning in dyadlength: n != 2^J')
end
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function row = ShapeAsRow(sig)
% ShapeAsRow -- Make signal a row vector
% Usage
% row = ShapeAsRow(sig)
% Inputs
% sig a row or column vector
% Outputs
% row a row vector
%
% See Also
% ShapeLike
%
row = sig(:)';
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function d = DownDyadHi(x,qmf)
% DownDyadHi -- Hi-Pass Downsampling operator (periodized)
% Usage
% d = DownDyadHi(x,f)
% Inputs
% x 1-d signal at fine scale
% f filter
% Outputs
% y 1-d signal at coarse scale
%
% See Also
% DownDyadLo, UpDyadHi, UpDyadLo, FWT_PO, iconv
%
d = iconv( MirrorFilt(qmf),lshift(x));
n = length(d);
d = d(1:2:(n-1));
%
% Copyright (c) 1993. Iain M. Johnstone
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = MirrorFilt(x)
% MirrorFilt -- Apply (-1)^t modulation
% Usage
% h = MirrorFilt(l)
% Inputs
% l 1-d signal
% Outputs
% h 1-d signal with DC frequency content shifted
% to Nyquist frequency
%
% Description
% h(t) = (-1)^(t-1) * x(t), 1 <= t <= length(x)
%
% See Also
% DyadDownHi
%
y = -( (-1).^(1:length(x)) ).*x;
%
% Copyright (c) 1993. Iain M. Johnstone
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = lshift(x)
% lshift -- Circular left shift of 1-d signal
% Usage
% l = lshift(x)
% Inputs
% x 1-d signal
% Outputs
% l 1-d signal
% l(i) = x(i+1) except l(n) = x(1)
%
y = [ x( 2:length(x) ) x(1) ];
%
% Copyright (c) 1993. Iain M. Johnstone
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = iconv(f,x)
% iconv -- Convolution Tool for Two-Scale Transform
% Usage
% y = iconv(f,x)
% Inputs
% f filter
% x 1-d signal
% Outputs
% y filtered result
%
% Description
% Filtering by periodic convolution of x with f
%
% See Also
% aconv, UpDyadHi, UpDyadLo, DownDyadHi, DownDyadLo
%
n = length(x);
p = length(f);
if p <= n,
xpadded = [x((n+1-p):n) x];
else
z = zeros(1,p);
for i=1:p,
imod = 1 + rem(p*n -p + i-1,n);
z(i) = x(imod);
end
xpadded = [z x];
end
ypadded = filter(f,1,xpadded);
y = ypadded((p+1):(n+p));
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function i = dyad(j)
% dyad -- Index entire j-th dyad of 1-d wavelet xform
% Usage
% ix = dyad(j);
% Inputs
% j integer
% Outputs
% ix list of all indices of wavelet coeffts at j-th level
%
i = (2^(j)+1):(2^(j+1)) ;
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function d = DownDyadLo(x,qmf)
% DownDyadLo -- Lo-Pass Downsampling operator (periodized)
% Usage
% d = DownDyadLo(x,f)
% Inputs
% x 1-d signal at fine scale
% f filter
% Outputs
% y 1-d signal at coarse scale
%
% See Also
% DownDyadHi, UpDyadHi, UpDyadLo, FWT_PO, aconv
%
d = aconv(qmf,x);
n = length(d);
d = d(1:2:(n-1));
%
% Copyright (c) 1993. Iain M. Johnstone
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = aconv(f,x)
% aconv -- Convolution Tool for Two-Scale Transform
% Usage
% y = aconv(f,x)
% Inputs
% f filter
% x 1-d signal
% Outputs
% y filtered result
%
% Description
% Filtering by periodic convolution of x with the
% time-reverse of f.
%
% See Also
% iconv, UpDyadHi, UpDyadLo, DownDyadHi, DownDyadLo
%
n = length(x);
p = length(f);
if p < n,
xpadded = [x x(1:p)];
else
z = zeros(1,p);
for i=1:p,
imod = 1 + rem(i-1,n);
z(i) = x(imod);
end
xpadded = [x z];
end
fflip = reverse(f);
ypadded = filter(fflip,1,xpadded);
y = ypadded(p:(n+p-1));
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function vec = ShapeLike(sig,proto)
% ShapeLike -- Make 1-d signal with given shape
% Usage
% vec = ShapeLike(sig,proto)
% Inputs
% sig a row or column vector
% proto a prototype shape (row or column vector)
% Outputs
% vec a vector with contents taken from sig
% and same shape as proto
%
% See Also
% ShapeAsRow
%
sp = size(proto);
ss = size(sig);
if( sp(1)>1 & sp(2)>1 )
disp('Weird proto argument to ShapeLike')
elseif ss(1)>1 & ss(2) > 1,
disp('Weird sig argument to ShapeLike')
else
if(sp(1) > 1),
if ss(1) > 1,
vec = sig;
else
vec = sig(:);
end
else
if ss(2) > 1,
vec = sig;
else
vec = sig(:)';
end
end
end
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function x = IWT_PO(wc,L,qmf)
% IWT_PO -- Inverse Wavelet Transform (periodized, orthogonal)
% Usage
% x = IWT_PO(wc,L,qmf)
% Inputs
% wc 1-d wavelet transform: length(wc) = 2^J.
% L Coarsest scale (2^(-L) = scale of V_0); L << J;
% qmf quadrature mirror filter
% Outputs
% x 1-d signal reconstructed from wc
%
% Description
% Suppose wc = FWT_PO(x,L,qmf) where qmf is an orthonormal quad. mirror
% filter, e.g. one made by MakeONFilter. Then x can be reconstructed by
% x = IWT_PO(wc,L,qmf)
%
% See Also
% FWT_PO, MakeONFilter
%
wcoef = ShapeAsRow(wc);
x = wcoef(1:2^L);
[n,J] = dyadlength(wcoef);
for j=L:J-1
x = UpDyadLo(x,qmf) + UpDyadHi(wcoef(dyad(j)),qmf) ;
end
x = ShapeLike(x,wc);
%
% Copyright (c) 1993. Iain M. Johnstone
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = UpDyadLo(x,qmf)
% UpDyadLo -- Lo-Pass Upsampling operator; periodized
% Usage
% u = UpDyadLo(d,f)
% Inputs
% d 1-d signal at coarser scale
% f filter
% Outputs
% u 1-d signal at finer scale
%
% See Also
% DownDyadLo, DownDyadHi, UpDyadHi, IWT_PO, iconv
%
y = iconv(qmf, UpSample(x) );
%
% Copyright (c) 1993. Iain M. Johnstone
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = UpSample(x,s)
% UpSample -- Upsampling operator
% Usage
% u = UpSample(d[,s])
% Inputs
% d 1-d signal, of length n
% s upsampling scale, default = 2
% Outputs
% u 1-d signal, of length s*n with zeros
% interpolating alternate samples
% u(s*i-1) = d(i), i=1,...,n
%
if nargin == 1, s = 2; end
n = length(x)*s;
y = zeros(1,n);
y(1:s:(n-s+1) )=x;
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = UpDyadHi(x,qmf)
% UpDyadHi -- Hi-Pass Upsampling operator; periodized
% Usage
% u = UpDyadHi(d,f)
% Inputs
% d 1-d signal at coarser scale
% f filter
% Outputs
% u 1-d signal at finer scale
%
% See Also
% DownDyadLo, DownDyadHi, UpDyadLo, IWT_PO, aconv
%
y = aconv( MirrorFilt(qmf), rshift( UpSample(x) ) );
%
% Copyright (c) 1993. Iain M. Johnstone
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = rshift(x)
% rshift -- Circular right shift of 1-d signal
% Usage
% r = rshift(x)
% Inputs
% x 1-d signal
% Outputs
% r 1-d signal
% r(i) = x(i-1) except r(1) = x(n)
%
n = length(x);
y = [ x(n) x( 1: (n-1) )];
%
% Copyright (c) 1993. Iain M. Johnstone
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function [qmf,dqmf] = MakeBSFilter(Type,Par)
% MakeBSFilter -- Generate Biorthonormal QMF Filter Pairs
% Usage
% [qmf,dqmf] = MakeBSFilter(Type,Par)
% Inputs
% Type string, one of:
% 'Triangle'
% 'Interpolating' 'Deslauriers' (the two are same)
% 'Average-Interpolating'
% 'CDF' (spline biorthogonal filters in Daubechies's book)
% 'Villasenor' (Villasenor's 5 best biorthogonal filters)
% Par integer list, e.g. if Type ='Deslauriers', Par=3 specifies
% Deslauriers-Dubuc filter, polynomial degree 3
% Outputs
% qmf quadrature mirror filter (odd length, symmetric)
% dqmf dual quadrature mirror filter (odd length, symmetric)
%
% See Also
% FWT_PBS, IWT_PBS, FWT2_PBS, IWT2_PBS
%
% References
% I. Daubechies, "Ten Lectures on Wavelets."
%
% G. Deslauriers and S. Dubuc, "Symmetric Iterative Interpolating Processes."
%
% D. Donoho, "Smooth Wavelet Decompositions with Blocky Coefficient Kernels."
%
% J. Villasenor, B. Belzer and J. Liao, "Wavelet Filter Evaluation for
% Image Compression."
%
if nargin < 2,
Par = 0;
end
sqr2 = sqrt(2);
if strcmp(Type,'Triangle'),
qmf = [0 1 0];
dqmf = [.5 1 .5];
elseif strcmp(Type,'Interpolating') | strcmp(Type,'Deslauriers'),
qmf = [0 1 0];
dqmf = MakeDDFilter(Par)';
dqmf = dqmf(1:(length(dqmf)-1));
elseif strcmp(Type,'Average-Interpolating'),
qmf = [0 .5 .5] ;
dqmf = [0 ; MakeAIFilter(Par)]';
elseif strcmp(Type,'CDF'),
if Par(1)==1,
dqmf = [0 .5 .5] .* sqr2;
if Par(2) == 1,
qmf = [0 .5 .5] .* sqr2;
elseif Par(2) == 3,
qmf = [0 -1 1 8 8 1 -1] .* sqr2 / 16;
elseif Par(2) == 5,
qmf = [0 3 -3 -22 22 128 128 22 -22 -3 3].*sqr2/256;
end
elseif Par(1)==2,
dqmf = [.25 .5 .25] .* sqr2;
if Par(2)==2,
qmf = [-.125 .25 .75 .25 -.125] .* sqr2;
elseif Par(2)==4,
qmf = [3 -6 -16 38 90 38 -16 -6 3] .* (sqr2/128);
elseif Par(2)==6,
qmf = [-5 10 34 -78 -123 324 700 324 -123 -78 34 10 -5 ] .* (sqr2/1024);
elseif Par(2)==8,
qmf = [35 -70 -300 670 1228 -3126 -3796 10718 22050 ...
10718 -3796 -3126 1228 670 -300 -70 35 ] .* (sqr2/32768);
end
elseif Par(1)==3,
dqmf = [0 .125 .375 .375 .125] .* sqr2;
if Par(2) == 1,
qmf = [0 -.25 .75 .75 -.25] .* sqr2;
elseif Par(2) == 3,
qmf = [0 3 -9 -7 45 45 -7 -9 3] .* sqr2/64;
elseif Par(2) == 5,
qmf = [0 -5 15 19 -97 -26 350 350 -26 -97 19 15 -5] .* sqr2/512;
elseif Par(2) == 7,
qmf = [0 35 -105 -195 865 363 -3489 -307 11025 11025 -307 -3489 363 865 -195 -105 35] .* sqr2/16384;
elseif Par(2) == 9,
qmf = [0 -63 189 469 -1911 -1308 9188 1140 -29676 190 87318 87318 190 -29676 ...
1140 9188 -1308 -1911 469 189 -63] .* sqr2/131072;
end
elseif Par(1)==4,
dqmf = [.026748757411 -.016864118443 -.078223266529 .266864118443 .602949018236 ...
.266864118443 -.078223266529 -.016864118443 .026748757411] .*sqr2;
if Par(2) == 4,
qmf = [0 -.045635881557 -.028771763114 .295635881557 .557543526229 ...
.295635881557 -.028771763114 -.045635881557 0] .*sqr2;
end
end
elseif strcmp(Type,'Villasenor'),
if Par == 1,
% The "7-9 filters"
qmf = [.037828455506995 -.023849465019380 -.11062440441842 .37740285561265];
qmf = [qmf .85269867900940 reverse(qmf)];
dqmf = [-.064538882628938 -.040689417609558 .41809227322221];
dqmf = [dqmf .78848561640566 reverse(dqmf)];
elseif Par == 2,
qmf = [-.008473 .003759 .047282 -.033475 -.068867 .383269 .767245 .383269 -.068867...
-.033475 .047282 .003759 -.008473];
dqmf = [0.014182 0.006292 -0.108737 -0.069163 0.448109 .832848 .448109 -.069163 -.108737 .006292 .014182];
elseif Par == 3,
qmf = [0 -.129078 .047699 .788486 .788486 .047699 -.129078];
dqmf = [0 .018914 .006989 -.067237 .133389 .615051 .615051 .133389 -.067237 .006989 .018914];
elseif Par == 4,
qmf = [-1 2 6 2 -1] / (4*sqr2);
dqmf = [1 2 1] / (2*sqr2);
elseif Par == 5,
qmf = [0 1 1]/sqr2;
dqmf = [0 -1 1 8 8 1 -1]/(8*sqr2);
end
end
%
% Copyright (c) 1995. Jonathan Buckheit, Shaobing Chen and David Donoho
%
% Modified by Maureen Clerc and Jerome Kalifa, 1997
% [email protected], [email protected]
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function wcoef = FWT_SBS(x,L,qmf,dqmf)
% FWT_SBS -- Forward Wavelet Transform (symmetric extension, biorthogonal, symmetric)
% Usage
% wc = FWT_SBS(x,L,qmf,dqmf)
% Inputs
% x 1-d signal; arbitrary length
% L Coarsest Level of V_0; L << J
% qmf quadrature mirror filter (symmetric)
% dqmf quadrature mirror filter (symmetric, dual of qmf)
% Outputs
% wc 1-d wavelet transform of x.
%
% Description
% 1. qmf filter may be obtained from MakePBSFilter
% 2. usually, length(qmf) < 2^(L+1)
% 3. To reconstruct use IWT_SBS
%
% See Also
% IWT_SBS, MakePBSFilter
%
% References
% Based on the algorithm developed by Christopher Brislawn.
% See "Classification of Symmetric Wavelet Transforms"
%
[n,J] = dyadlength(x);
wcoef = zeros(1,n);
beta = ShapeAsRow(x); % take samples at finest scale as beta-coeffts
dp = dyadpartition(n);
for j=J-1:-1:L,
[beta, alfa] = DownDyad_SBS(beta,qmf,dqmf);
dyadj = (dp(j+1)+1):dp(j+2);
wcoef(dyadj) = alfa;
end
wcoef(1:length(beta)) = beta;
wcoef = ShapeLike(wcoef,x);
%
% Copyright (c) 1996. Thomas P.Y. Yu
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function dp = dyadpartition(n)
% dyadpartition -- determine dyadic partition in wavelet transform of
% nondyadic signals
J = ceil(log2(n));
m = n;
for j=J-1:-1:0;
if rem(m,2)==0,
dps(j+1) = m/2;
m = m/2;
else
dps(j+1) = (m-1)/2;
m = (m+1)/2;
end
end
dp = cumsum([1 dps]);
%
% Copyright (c) 1996. Thomas P.Y. Yu
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function [beta, alpha] = DownDyad_SBS(x,qmf,dqmf)
% DownDyad_SBS -- Symmetric Downsampling operator
% Usage
% [beta,alpha] = DownDyad_SBS(x,qmf,dqmf)
% Inputs
% x 1-d signal at fine scale
% qmf quadrature mirror filter
% dqmf dual quadrature mirror filter
% Outputs
% beta coarse coefficients
% alpha fine coefficients
% See Also
% FWT_SBS
%
% oddf = (rem(length(qmf),2)==1);
oddf = ~(qmf(1)==0 & qmf(length(qmf))~=0);
oddx = (rem(length(x),2)==1);
% symmetric extension of x
if oddf,
ex = extend(x,1,1);
else
ex = extend(x,2,2);
end
% convolution
ebeta = DownDyadLo_PBS(ex,qmf);
ealpha = DownDyadHi_PBS(ex,dqmf);
% project
if oddx,
beta = ebeta(1:(length(x)+1)/2);
alpha = ealpha(1:(length(x)-1)/2);
else
beta = ebeta(1:length(x)/2);
alpha = ealpha(1:length(x)/2);
end
%
% Copyright (c) 1996. Thomas P.Y. Yu
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = extend(x, par1, par2)
% extend -- perform various kinds of symmetric extension
%
if par1==1 & par2==1,
y = [x x((length(x)-1):-1:2)];
elseif par1==1 & par2==2,
y = [x x((length(x)-1):-1:1)];
elseif par1==2 & par2==1,
y = [x x(length(x):-1:2)];
elseif par1==2 & par2==2,
y = [x reverse(x)];
end
%
% Copyright (c) 1996. Thomas P.Y. Yu
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function d = DownDyadLo_PBS(x,qmf)
% DownDyadLo_PBS -- Lo-Pass Downsampling operator (periodized,symmetric)
% Usage
% d = DownDyadLo_PBS(x,sf)
% Inputs
% x 1-d signal at fine scale
% sf symmetric filter
% Outputs
% y 1-d signal at coarse scale
%
% See Also
% DownDyadHi_PBS, UpDyadHi_PBS, UpDyadLo_PBS, FWT_PBSi, symm_aconv
%
d = symm_aconv(qmf,x);
n = length(d);
d = d(1:2:(n-1));
%
% Copyright (c) 1995. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = symm_aconv(sf,x)
% symm_aconv -- Symmetric Convolution Tool for Two-Scale Transform
% Usage
% y = symm_aconv(sf,x)
% Inputs
% sf symmetric filter
% x 1-d signal
% Outputs
% y filtered result
%
% Description
% Filtering by periodic convolution of x with the
% time-reverse of sf.
%
% See Also
% symm_iconv, UpDyadHi_PBS, UpDyadLo_PBS, DownDyadHi_PBS, DownDyadLo_PBS
%
n = length(x);
p = length(sf);
if p < n,
xpadded = [x x(1:p)];
else
z = zeros(1,p);
for i=1:p,
imod = 1 + rem(i-1,n);
z(i) = x(imod);
end
xpadded = [x z];
end
fflip = reverse(sf);
ypadded = filter(fflip,1,xpadded);
if p < n,
y = [ypadded((n+1):(n+p)) ypadded((p+1):(n))];
else
for i=1:n,
imod = 1 + rem(p+i-1,n);
y(imod) = ypadded(p+i);
end
end
shift = (p-1)/ 2 ;
shift = 1 + rem(shift-1, n);
y = [y((1+shift):n) y(1:(shift))] ;
%
% Copyright (c) 1995. Shaobing Chen and David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function d = DownDyadHi_PBS(x,qmf)
% DownDyadHi_PBS -- Hi-Pass Downsampling operator (periodized,symmetric)
% Usage
% d = DownDyadHi_PBS(x,sqmf)
% Inputs
% x 1-d signal at fine scale
% sqmf symmetric filter
% Outputs
% y 1-d signal at coarse scale
%
% See Also
% DownDyadLo_PBS, UpDyadHi_PBS, UpDyadLo_PBS, FWT_PBS, symm_iconv
%
d = symm_iconv( MirrorSymmFilt(qmf),lshift(x));
n = length(d);
d = d(1:2:(n-1));
%
% Copyright (c) 1995. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = MirrorSymmFilt(x)
% MirrorSymmFilt -- apply (-1)^t modulation to symmetric filter
% Usage
% h = MirrorSymmFilt(l)
% Inputs
% l symmetric filter
% Outputs
% h symmetric filter with DC frequency content shifted
% to Nyquist frequency
%
% Description
% h(t) = (-1)^t * x(t), -k <= t <= k ; length(x)=2k+1
%
% See Also
% DownDyadHi_PBS
%
k = (length(x)-1)/2;
y = ( (-1).^((-k):k) ) .*x;
%
% Copyright (c) 1993. Iain M. Johnstone
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = symm_iconv(sf,x)
% symm_iconv -- Symmetric Convolution Tool for Two-Scale Transform
% Usage
% y = iconv(sf,x)
% Inputs
% sf symmetric filter
% x 1-d signal
% Output
% y filtered result
%
% Description
% Filtering by periodic convolution of x with sf
%
% See Also
% symm_aconv, UpDyadHi_PBS, UpDyadLo_PBS, DownDyadHi_PBS, DownDyadLo_PBS
%
n = length(x);
p = length(sf);
if p <= n,
xpadded = [x((n+1-p):n) x];
else
z = zeros(1,p);
for i=1:p,
imod = 1 + rem(p*n -p + i-1,n);
z(i) = x(imod);
end
xpadded = [z x];
end
ypadded = filter(sf,1,xpadded);
y = ypadded((p+1):(n+p));
shift = (p+1)/2;
shift = 1 + rem(shift-1, n);
y = [y(shift:n) y(1:(shift-1))];
%
% Copyright (c) 1995. Shaobing Chen and David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function x = IWT_SBS(wc,L,qmf,dqmf)
% iwt_po -- Inverse Wavelet Transform (symmetric extension, biorthogonal, symmetric)
% Usage
% x = IWT_SBS(wc,L,qmf,dqmf)
% Inputs
% wc 1-d wavelet transform: length(wc)= 2^J.
% L Coarsest scale (2^(-L) = scale of V_0); L << J;
% qmf quadrature mirror filter
% dqmf dual quadrature mirror filter (symmetric, dual of qmf)
% Outputs
% x 1-d signal reconstructed from wc
% Description
% Suppose wc = FWT_SBS(x,L,qmf,dqmf) where qmf and dqmf are orthonormal
% quad. mirror filters made by MakeBioFilter. Then x can be reconstructed
% by
% x = IWT_SBS(wc,L,qmf,dqmf)
% See Also:
% FWT_SBS, MakeBioFilter
%
wcoef = ShapeAsRow(wc);
[n,J] = dyadlength(wcoef);
dp = dyadpartition(n);
x = wcoef(1:dp(L+1));
for j=L:J-1,
dyadj = (dp(j+1)+1):dp(j+2);
x = UpDyad_SBS(x, wcoef(dyadj), qmf, dqmf);
end
x = ShapeLike(x,wc);
%
% Copyright (c) 1996. Thomas P.Y. Yu
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function x = UpDyad_SBS(beta,alpha,qmf,dqmf)
% UpDyad_SBS -- Symmetric Upsampling operator
% Usage
% x = UpDyad_SBS(beta,alpha,qmf,dqmf)
% Inputs
% beta coarse coefficients
% alpha fine coefficients
% qmf quadrature mirror filter
% dqmf dual quadrature mirror filter
% Outputs
% x 1-d signal at fine scale
% See Also
% DownDyad_SBS, IWT_SBS
%
% oddf = (rem(length(qmf),2)==1);
oddf = ~(qmf(1)==0 & qmf(length(qmf))~=0);
oddx = (length(beta) ~= length(alpha));
L = length(beta)+length(alpha);
if oddf,
if oddx,
ebeta = extend(beta,1,1);
ealpha = extend(alpha,2,2);
else
ebeta = extend(beta,2,1);
ealpha = extend(alpha,1,2);
end
else
if oddx,
ebeta = extend(beta,1,2);
ealpha = [alpha 0 -reverse(alpha)];
else
ebeta = extend(beta,2,2);
ealpha = [alpha -reverse(alpha)];
end
end
coarse = UpDyadLo_PBS(ebeta,dqmf);
fine = UpDyadHi_PBS(ealpha,qmf);
x = coarse + fine;
x = x(1:L);
%
% Copyright (c) 1996. Thomas P.Y. Yu
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = UpDyadLo_PBS(x,qmf)
% UpDyadLo_PBS -- Lo-Pass Upsampling operator; periodized
% Usage
% u = UpDyadLo_PBS(d,sf)
% Inputs
% d 1-d signal at coarser scale
% sf symmetric filter
% Outputs
% u 1-d signal at finer scale
%
% See Also
% DownDyadLo_PBS , DownDyadHi_PBS , UpDyadHi_PBS, IWT_PBS, symm_iconv
%
y = symm_iconv(qmf, UpSample(x,2) );
%
% Copyright (c) 1995. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = UpDyadHi_PBS(x,qmf)
% UpDyadHi_PBS -- Hi-Pass Upsampling operator; periodized
% Usage
% u = UpDyadHi_PBS(d,f)
% Inputs
% d 1-d signal at coarser scale
% sf symmetric filter
% Outputs
% u 1-d signal at finer scale
%
% See Also
% DownDyadLo_PBS, DownDyadHi_PBS, UpDyadLo_PBS, IWT_PBS, symm_aconv
%
y = symm_aconv( MirrorSymmFilt(qmf), rshift( UpSample(x,2) ) );
%
% Copyright (c) 1995. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function wc = FWT2_SBS(x,L,qmf,dqmf)
% FWT2_SBS -- 2-dimensional wavelet transform
% (symmetric extension, bi-orthogonal)
% Usage
% wc = FWT2_SBS(x,L,qmf,dqmf)
% Inputs
% x 2-d image (n by n array, n arbitrary)
% L coarsest level
% qmf low-pass quadrature mirror filter
% dqmf high-pass dual quadrature mirror filter
% Output
% wc 2-d wavelet transform
% Description
% A two-dimensional Wavelet Transform is computed for the
% matrix x. To reconstruct, use IWT2_SBS.
% See Also
% IWT2_SBS
%
[m,J] = dyadlength(x(:,1));
[n,K] = dyadlength(x(1,:));
wc = x;
mc = m;
nc = n;
J = min([J,K]);
for jscal=J-1:-1:L,
if rem(mc,2)==0,
top = (mc/2+1):mc;
bot = 1:(mc/2);
else
top = ((mc+1)/2+1):mc;
bot = 1:((mc+1)/2);
end
if rem(nc,2)==0,
right = (nc/2+1):nc;
left = 1:(nc/2);
else
right = ((nc+1)/2+1):nc;
left = 1:((nc+1)/2);
end
for ix=1:mc,
row = wc(ix,1:nc);
[beta,alpha] = DownDyad_SBS(row,qmf,dqmf);
wc(ix,left) = beta;
wc(ix,right) = alpha;
end
for iy=1:nc,
column = wc(1:mc,iy)';
[beta,alpha] = DownDyad_SBS(column,qmf,dqmf);
wc(bot,iy) = beta';
wc(top,iy) = alpha';
end
mc = bot(length(bot));
nc = left(length(left));
end
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function x = IWT2_SBS(wc,L,qmf,dqmf)
% IWT2_SBS -- Inverse 2d Wavelet Transform
% (symmetric extention, bi-orthogonal)
% Usage
% x = IWT2_SBS(wc,L,qmf,dqmf)
% Inputs
% wc 2-d wavelet transform [n by n array, n arbitrary]
% L coarse level
% qmf low-pass quadrature mirror filter
% dqmf high-pas dual quadrature mirror filter
% Outputs
% x 2-d signal reconstructed from wc
% Description
% If wc is the result of a forward 2d wavelet transform, with
% wc = FWT2_SBS(x,L,qmf,dqmf)
% then x = IWT2_SBS(wc,L,qmf,dqmf) reconstructs x exactly if qmf is a nice
% quadrature mirror filter, e.g. one made by MakeBioFilter
% See Also:
% FWT2_SBS, MakeBioFilter
%
[m,J] = dyadlength(wc(:,1));
[n,K] = dyadlength(wc(1,:));
% assume m==n, J==K
x = wc;
dpm = dyadpartition(m);
for jscal=L:J-1,
bot = 1:dpm(jscal+1);
top = (dpm(jscal+1)+1):dpm(jscal+2);
all = [bot top];
nc = length(all);
for iy=1:nc,
x(all,iy) = UpDyad_SBS(x(bot,iy)', x(top,iy)', qmf, dqmf)';
end
for ix=1:nc,
x(ix,all) = UpDyad_SBS(x(ix,bot), x(ix,top), qmf, dqmf);
end
end
%
% Copyright (c) 1996. Thomas P.Y. Yu
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function wc = FWT2_PO(x,L,qmf)
% FWT2_PO -- 2-d MRA wavelet transform (periodized, orthogonal)
% Usage
% wc = FWT2_PO(x,L,qmf)
% Inputs
% x 2-d image (n by n array, n dyadic)
% L coarse level
% qmf quadrature mirror filter
% Outputs
% wc 2-d wavelet transform
%
% Description
% A two-dimensional Wavelet Transform is computed for the
% array x. To reconstruct, use IWT2_PO.
%
% See Also
% IWT2_PO, MakeONFilter
%
[n,J] = quadlength(x);
wc = x;
nc = n;
for jscal=J-1:-1:L,
top = (nc/2+1):nc; bot = 1:(nc/2);
for ix=1:nc,
row = wc(ix,1:nc);
wc(ix,bot) = DownDyadLo(row,qmf);
wc(ix,top) = DownDyadHi(row,qmf);
end
for iy=1:nc,
row = wc(1:nc,iy)';
wc(top,iy) = DownDyadHi(row,qmf)';
wc(bot,iy) = DownDyadLo(row,qmf)';
end
nc = nc/2;
end
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function x = IWT2_PO(wc,L,qmf)
% IWT2_PO -- Inverse 2-d MRA wavelet transform (periodized, orthogonal)
% Usage
% x = IWT2_PO(wc,L,qmf)
% Inputs
% wc 2-d wavelet transform [n by n array, n dyadic]
% L coarse level
% qmf quadrature mirror filter
% Outputs
% x 2-d signal reconstructed from wc
%
% Description
% If wc is the result of a forward 2d wavelet transform, with
% wc = FWT2_PO(x,L,qmf), then x = IWT2_PO(wc,L,qmf) reconstructs x
% exactly if qmf is a nice qmf, e.g. one made by MakeONFilter.
%
% See Also
% FWT2_PO, MakeONFilter
%
[n,J] = quadlength(wc);
x = wc;
nc = 2^(L+1);
for jscal=L:J-1,
top = (nc/2+1):nc; bot = 1:(nc/2); all = 1:nc;
for iy=1:nc,
x(all,iy) = UpDyadLo(x(bot,iy)',qmf)' ...
+ UpDyadHi(x(top,iy)',qmf)';
end
for ix=1:nc,
x(ix,all) = UpDyadLo(x(ix,bot),qmf) ...
+ UpDyadHi(x(ix,top),qmf);
end
nc = 2*nc;
end
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function [n,J] = quadlength(x)
% quadlength -- Find length and dyadic length of square matrix
% Usage
% [n,J] = quadlength(x)
% Inputs
% x 2-d image; size(n,n), n = 2^J (hopefully)
% Outputs
% n length(x)
% J least power of two greater than n
%
% Side Effects
% A warning message is issue if n is not a power of 2,
% or if x is not a square matrix.
%
s = size(x);
n = s(1);
if s(2) ~= s(1),
disp('Warning in quadlength: nr != nc')
end
k = 1 ; J = 0; while k < n , k=2*k; J = 1+J ; end ;
if k ~= n ,
disp('Warning in quadlength: n != 2^J')
end
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function wp = FWT_TI(x,L,qmf)
% FWT_TI -- translation invariant forward wavelet transform
% Usage
% TIWT = FWT_TI(x,L,qmf)
% Inputs
% x array of dyadic length n=2^J
% L degree of coarsest scale
% qmf orthonormal quadrature mirror filter
% Outputs
% TIWT stationary wavelet transform table
% formally same data structure as packet table
%
% See Also
% IWT_TI
%
[n,J] = dyadlength(x);
D = J-L;
wp = zeros(n,D+1);
x = ShapeAsRow(x);
%
wp(:,1) = x';
for d=0:(D-1),
for b=0:(2^d-1),
s = wp(packet(d,b,n),1)';
hsr = DownDyadHi(s,qmf);
hsl = DownDyadHi(rshift(s),qmf);
lsr = DownDyadLo(s,qmf);
lsl = DownDyadLo(rshift(s),qmf);
wp(packet(d+1,2*b ,n),d+2) = hsr';
wp(packet(d+1,2*b+1,n),d+2) = hsl';
wp(packet(d+1,2*b ,n),1 ) = lsr';
wp(packet(d+1,2*b+1,n),1 ) = lsl';
end
end
%
% Copyright (c) 1994. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function tiwt = FWT2_TI(x,L,qmf)
% FWT_TI -- 2-D translation invariant forward wavelet transform
% Usage
% TIWT = FWT2_TI(x,L,qmf)
% Inputs
% x 2-d image (n by n real array, n dyadic)
% L degree of coarsest scale
% qmf orthonormal quadrature mirror filter
% Outputs
% TIWT translation-invariant wavelet transform table, (3*(J-L)+1)*n by n
%
% See Also
% IWT2_TI, IWT2_TIMedian
%
[n,J] = quadlength(x);
D = J-L;
tiwt = zeros((3*D+1)*n, n);
lastx = (3*D*n+1):(3*D*n+n); lasty = 1:n;
tiwt(lastx,lasty) = x;
%
for d=0:(D-1),
l = J-d-1; ns = 2^(J-d);
for b1=0:(2^d-1), for b2=0:(2^d-1),
s = tiwt(3*D*n+packet(d,b1,n), packet(d,b2,n));
wc00 = FWT2_PO(s,l,qmf);
wc01 = FWT2_PO(CircularShift(s,0,1),l,qmf);
wc10 = FWT2_PO(CircularShift(s,1,0),l,qmf);
wc11 = FWT2_PO(CircularShift(s,1,1),l,qmf);
index10 = packet(d+1,2*b1,n); index20 = packet(d+1,2*b2,n);
index11 = packet(d+1,2*b1+1,n); index21 = packet(d+1,2*b2+1,n);
% horizontal stuff
tiwt(3*d*n + index10 , index20) = wc00(1:(ns/2),(ns/2+1):ns);
tiwt(3*d*n + index11, index20) = wc01(1:(ns/2),(ns/2+1):ns);
tiwt(3*d*n + index10 , index21) = wc10(1:(ns/2),(ns/2+1):ns);
tiwt(3*d*n + index11 , index21) = wc11(1:(ns/2),(ns/2+1):ns);
% vertical stuff
tiwt((3*d+1)*n + index10 , index20) = wc00((ns/2+1):ns,1:(ns/2));
tiwt((3*d+1)*n + index11, index20) = wc01((ns/2+1):ns,1:(ns/2));
tiwt((3*d+1)*n + index10 , index21) = wc10((ns/2+1):ns,1:(ns/2));
tiwt((3*d+1)*n + index11 , index21) = wc11((ns/2+1):ns,1:(ns/2));
% diagonal stuff
tiwt((3*d+2)*n + index10 , index20) = wc00((ns/2+1):ns,(ns/2+1):ns);
tiwt((3*d+2)*n + index11, index20) = wc01((ns/2+1):ns,(ns/2+1):ns);
tiwt((3*d+2)*n + index10 , index21) = wc10((ns/2+1):ns,(ns/2+1):ns);
tiwt((3*d+2)*n + index11 , index21) = wc11((ns/2+1):ns,(ns/2+1):ns);
% low freq stuff
tiwt(3*D*n + index10 , index20) = wc00(1:(ns/2),1:(ns/2));
tiwt(3*D*n + index11, index20) = wc01(1:(ns/2),1:(ns/2));
tiwt(3*D*n + index10 , index21) = wc10(1:(ns/2),1:(ns/2));
tiwt(3*D*n + index11 , index21) = wc11(1:(ns/2),1:(ns/2));
end, end
end
%
% Copyright (c) 1995. David L. Donoho and Thomas P.Y. Yu
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function p=packet(d,b,n)
% packet -- Packet table indexing
% Usage
% p = packet(d,b,n)
% Inputs
% d depth of splitting in packet decomposition
% b block index among 2^d possibilities at depth d
% n length of signal
% Outputs
% p linear indices of all coeff's in that block
%
npack = 2^d;
p = ( (b * (n/npack) + 1) : ((b+1)*n/npack ) ) ;
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function x = IWT_TI(pkt,qmf)
% IWT_TI -- Invert translation invariant wavelet transform
% Usage
% x = IWT_TI(TIWT,qmf)
% Inputs
% TIWT translation-invariant wavelet transform table
% qmf quadrature mirror filter
% Outputs
% x 1-d signal reconstructed from translation-invariant
% transform TIWT
%
% See Also
% FWT_TI
%
[n,D1] = size(pkt);
D = D1-1;
J = log2(n);
L = J-D;
%
wp = pkt;
%
sig = wp(:,1)';
for d= D-1:-1:0,
for b=0:(2^d-1)
hsr = wp(packet(d+1,2*b ,n),d+2)';
hsl = wp(packet(d+1,2*b+1,n),d+2)';
lsr = sig(packet(d+1,2*b ,n) );
lsl = sig(packet(d+1,2*b+1,n) );
loterm = (UpDyadLo(lsr,qmf) + lshift(UpDyadLo(lsl,qmf)))/2;
hiterm = (UpDyadHi(hsr,qmf) + lshift(UpDyadHi(hsl,qmf)))/2;
sig(packet(d,b,n)) = loterm+hiterm;
end
end
x = sig;
%
% Copyright (c) 1994. David L. Donoho
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function x = IWT2_TI(tiwt,L,qmf)
% IWT2_TI -- Invert 2-d translation invariant wavelet transform
% Usage
% x = IWT2_TI(TIWT,qmf)
% Inputs
% TIWT translation-invariant wavelet transform table, (3*(J-L)+1)*n by n
% L degree of coarsest scale
% qmf quadrature mirror filter
% Outputs
% x 2-d image reconstructed from translation-invariant transform TIWT
%
% See Also
% FWT2_TI, IWT2_TIMedian
%
[D1,n] = size(tiwt);
J = log2(n);
D = J-L;
%
lastx = (3*D*n+1):(3*D*n+n); lasty = 1:n;
x = tiwt(lastx,lasty);
for d=(D-1):-1:0,
l = J-d-1; ns = 2^(J-d);
for b1=0:(2^d-1), for b2=0:(2^d-1),
index10 = packet(d+1,2*b1,n); index20 = packet(d+1,2*b2,n);
index11 = packet(d+1,2*b1+1,n); index21 = packet(d+1,2*b2+1,n);
wc00 = [x(index10,index20) tiwt(3*d*n+index10,index20) ; ...
tiwt((3*d+1)*n+index10,index20) tiwt((3*d+2)*n+index10,index20)];
wc01 = [x(index11,index20) tiwt(3*d*n+index11,index20) ; ...
tiwt((3*d+1)*n+index11,index20) tiwt((3*d+2)*n+index11,index20)];
wc10 = [x(index10,index21) tiwt(3*d*n+index10,index21) ; ...
tiwt((3*d+1)*n+index10,index21) tiwt((3*d+2)*n+index10,index21)];
wc11 = [x(index11,index21) tiwt(3*d*n+index11,index21) ; ...
tiwt((3*d+1)*n+index11,index21) tiwt((3*d+2)*n+index11,index21)];
x(packet(d,b1,n), packet(d,b2,n)) = ( IWT2_PO(wc00,l,qmf) + ....
CircularShift(IWT2_PO(wc01,l,qmf),0,-1) + ...
CircularShift(IWT2_PO(wc10,l,qmf),-1,0) + ...
CircularShift(IWT2_PO(wc11,l,qmf),-1,-1) ) / 4;
end, end
end
%
% Copyright (c) 1995. David L. Donoho and Thomas P.Y. Yu
%
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function result = CircularShift(matrix, colshift, rowshift)
% CIRCULARSHIFT: Circular shifting of a matrix/image, i.e., pixels that get
% shifted off one side of the image are put back on the other side.
%
% result = circularShift(matrix, colshift, rowshift)
%
% EPS, DJH '96
lastrow = size(matrix, 1);
lastcol = size(matrix, 2);
result = matrix;
% Shift the cols
if (colshift>0)
result = [result(:,[lastcol-colshift+1:lastcol]) ...
result(:,[1:lastcol-colshift])];
else
colshift = -colshift;
result = [result(:,[colshift+1:lastcol]) ...
result(:,[1:colshift])];
end
% Shift the rows
if (rowshift>0)
result = [result([lastrow-rowshift+1:lastrow],:) ; ...
result([1:lastrow-rowshift],:)];
else
rowshift = -rowshift;
result = [result([rowshift+1:lastrow],:) ; ...
result([1:rowshift],:)];
end
function x = reverse(x)
x = x(end:-1:1);
function StatWT = TI2Stat(TIWT)
% TI2Stat -- Convert Translation-Invariant Transform to Stationary Wavelet Transform
% Usage
% StatWT = TI2Stat(TIWT)
% Inputs
% TIWT translation invariant table from FWT_TI
% Outputs
% StatWT stationary wavelet transform table table as FWT_Stat
%
% See Also
% Stat2TI, FWT_TI, FWT_Stat
%
StatWT = TIWT;
[n,D1] = size(StatWT);
D = D1-1;
J = log2(n);
L = J-D;
%
index = 1;
for d=1:D,
nb = 2^d;
nk = n/nb;
index = [ (index+nb/2); index];
index = index(:)';
for b= 0:(nb-1),
StatWT(d*n + (index(b+1):nb:n)) = TIWT(d*n + packet(d,b,n));
end
end
for b= 0:(nb-1),
StatWT((index(b+1):nb:n)) = TIWT(packet(d,b,n));
end
%
% Copyright (c) 1994. Shaobing Chen
%
function TIWT = Stat2TI(StatWT)
% Stat2TI -- Convert Stationary Wavelet Transform to Translation-Invariant Transform
% Usage
% TIWT = Stat2TI(StatWT)
% Inputs
% StatWT stationary wavelet transform table as FWT_Stat
% Outputs
% TIWT translation-invariant transform table as FWT_TI
%
% See Also
% Stat2TI, FWT_TI, FWT_Stat
%
TIWT = StatWT;
[n,D1] = size(StatWT);
D = D1-1;
index = 1;
for d=1:D,
nb = 2^d;
nk = n/nb;
index = [ (index+nb/2); index];
index = index(:)';
for b= 0:(nb-1),
TIWT(d*n + packet(d,b,n)) = StatWT(d*n + (index(b+1):nb:n));
end
end
for b= 0:(nb-1),
TIWT(packet(d,b,n)) = StatWT((index(b+1):nb:n));
end
%
% Copyright (c) 1994. Shaobing Chen
%
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:40 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
jacksky64/imageProcessing-master
|
medfilt2.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_nlmeans/toolbox/ordfilt2/medfilt2.m
| 4,441 |
utf_8
|
a78b7dbf3bc7c2a946de5e748467c722
|
function b = medfilt2(varargin)
%MEDFILT2 Perform 2-D median filtering.
% B = MEDFILT2(A,[M N]) performs median filtering of the matrix
% A in two dimensions. Each output pixel contains the median
% value in the M-by-N neighborhood around the corresponding
% pixel in the input image. MEDFILT2 pads the image with zeros
% on the edges, so the median values for the points within
% [M N]/2 of the edges may appear distorted.
%
% B = MEDFILT2(A) performs median filtering of the matrix A
% using the default 3-by-3 neighborhood.
%
% B = MEDFILT2(...,PADOPT) controls how the matrix boundaries
% are padded. PADOPT may be 'zeros' (the default),
% 'symmetric', or 'indexed'. If PADOPT is 'zeros', A is padded
% with zeros at the boundaries. If PADOPT is 'symmetric', A is
% symmetrically extended at the boundaries. If PADOPT is
% 'indexed', A is padded with ones if it is double; otherwise
% it is padded with zeros.
%
% Class Support
% -------------
% The input image A can be logical or numeric (unless the
% 'indexed' syntax is used, in which case A cannot be of class
% uint16). The output image B is of the same class as A.
%
% Remarks
% -------
% If the input image A is of integer class, all of the output
% values are returned as integers. If the number of
% pixels in the neighborhood (i.e., M*N) is even, some of the
% median values may not be integers. In these cases, the
% fractional parts are discarded. Logical input is treated
% similarly.
%
% Example
% -------
% I = imread('eight.tif');
% J = imnoise(I,'salt & pepper',0.02);
% K = medfilt2(J);
% imview(J), imview(K)
%
% See also FILTER2, ORDFILT2, WIENER2.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 5.18.4.6 $ $Date: 2003/08/23 05:53:02 $
[a, mn, padopt] = parse_inputs(varargin{:});
domain = ones(mn);
if (rem(prod(mn), 2) == 1)
order = (prod(mn)+1)/2;
b = ordfilt2(a, order, domain, padopt);
else
order1 = prod(mn)/2;
order2 = order1+1;
b = ordfilt2(a, order1, domain, padopt);
b2 = ordfilt2(a, order2, domain, padopt);
if islogical(b)
b = b | b2;
else
b = imlincomb(0.5, b, 0.5, b2);
end
end
%%%
%%% Function parse_inputs
%%%
function [a, mn, padopt] = parse_inputs(varargin)
% checknargin(1,4,nargin,mfilename);
% There are several grandfathered syntaxes we have to catch
% and parse successfully, so we're going to use a strategy
% that's a little different that usual.
%
% First, scan the input argument list for strings. The
% string 'indexed', 'zeros', or 'symmetric' can appear basically
% anywhere after the first argument.
%
% Second, delete the strings from the argument list.
%
% The remaining argument list can be one of the following:
% MEDFILT2(A)
% MEDFILT2(A,[M N])
% MEDFILT2(A,[M N],[Mb Nb])
%
% Any syntax in which 'indexed' is followed by other arguments
% is grandfathered. Any syntax in which [Mb Nb] appears is
% grandfathered.
%
% -sle, March 1998
a = varargin{1};
charLocation = [];
for k = 2:nargin
if (ischar(varargin{k}))
charLocation = [charLocation k];
end
end
if (length(charLocation) > 1)
% More than one string in input list
eid = 'Images:medfilt2:tooManyStringInputs';
error(eid,'%s','Too many input string arguments.');
elseif isempty(charLocation)
% No string specified
padopt = 'zeros';
else
options = {'indexed', 'zeros', 'symmetric'};
padopt = checkstrs(varargin{charLocation}, options, mfilename, ...
'PADOPT', charLocation);
varargin(charLocation) = [];
end
if (strcmp(padopt, 'indexed'))
if (isa(a,'double'))
padopt = 'ones';
else
padopt = 'zeros';
end
end
if length(varargin) == 1,
mn = [3 3];% default
elseif length(varargin) >= 2,
mn = varargin{2}(:).';
if size(mn,2)~=2,
msg = 'MEDFILT2(A,[M N]): Second argument must consist of two integers.';
eid = 'Images:medfilt2:secondArgMustConsistOfTwoInts';
error(eid, msg);
elseif length(varargin) > 2,
msg = ['MEDFILT2(A,[M N],[Mb Nb],...) is an obsolete syntax. [Mb Nb]' ...
' argument is ignored.'];
wid = 'Images:medfilt2:obsoleteSyntax';
warning(wid, msg);
end
end
% The grandfathered [Mb Nb] argument, if present, is ignored.
|
github
|
jacksky64/imageProcessing-master
|
padarray.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_nlmeans/toolbox/ordfilt2/padarray.m
| 7,671 |
utf_8
|
489e5e1fb612ce595b1baac73abfb897
|
function b = padarray(varargin)
%PADARRAY Pad an array.
% B = PADARRAY(A,PADSIZE) pads array A with PADSIZE(k) number of zeros
% along the k-th dimension of A. PADSIZE should be a vector of
% positive integers.
%
% B = PADARRAY(A,PADSIZE,PADVAL) pads array A with PADVAL (a scalar)
% instead of with zeros.
%
% B = PADARRAY(A,PADSIZE,PADVAL,DIRECTION) pads A in the direction
% specified by the string DIRECTION. DIRECTION can be one of the
% following strings.
%
% String values for DIRECTION
% 'pre' Pads before the first array element along each
% dimension .
% 'post' Pads after the last array element along each
% dimension.
% 'both' Pads before the first array element and after the
% last array element along each dimension.
%
% By default, DIRECTION is 'both'.
%
% B = PADARRAY(A,PADSIZE,METHOD,DIRECTION) pads array A using the
% specified METHOD. METHOD can be one of these strings:
%
% String values for METHOD
% 'circular' Pads with circular repetion of elements.
% 'replicate' Repeats border elements of A.
% 'symmetric' Pads array with mirror reflections of itself.
%
% Class Support
% -------------
% When padding with a constant value, A can be numeric or logical.
% When padding using the 'circular', 'replicate', or 'symmetric'
% methods, A can be of any class. B is of the same class as A.
%
% Example
% -------
% Add three elements of padding to the beginning of a vector. The
% padding elements contain mirror copies of the array.
%
% b = padarray([1 2 3 4],3,'symmetric','pre')
%
% Add three elements of padding to the end of the first dimension of
% the array and two elements of padding to the end of the second
% dimension. Use the value of the last array element as the padding
% value.
%
% B = padarray([1 2; 3 4],[3 2],'replicate','post')
%
% Add three elements of padding to each dimension of a
% three-dimensional array. Each pad element contains the value 0.
%
% A = [1 2; 3 4];
% B = [5 6; 7 8];
% C = cat(3,A,B)
% D = padarray(C,[3 3],0,'both')
%
% See also CIRCSHIFT, IMFILTER.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 1.11.4.3 $ $Date: 2003/08/23 05:53:08 $
[a, method, padSize, padVal, direction] = ParseInputs(varargin{:});
if isempty(a),% treat empty matrix similar for any method
if strcmp(direction,'both')
sizeB = size(a) + 2*padSize;
else
sizeB = size(a) + padSize;
end
b = mkconstarray(class(a), padVal, sizeB);
else
switch method
case 'constant'
b = ConstantPad(a, padSize, padVal, direction);
case 'circular'
b = CircularPad(a, padSize, direction);
case 'symmetric'
b = SymmetricPad(a, padSize, direction);
case 'replicate'
b = ReplicatePad(a, padSize, direction);
end
end
if (islogical(a))
b = logical(b);
end
%%%
%%% ConstantPad
%%%
function b = ConstantPad(a, padSize, padVal, direction)
numDims = numel(padSize);
% Form index vectors to subsasgn input array into output array.
% Also compute the size of the output array.
idx = cell(1,numDims);
sizeB = zeros(1,numDims);
for k = 1:numDims
M = size(a,k);
switch direction
case 'pre'
idx{k} = (1:M) + padSize(k);
sizeB(k) = M + padSize(k);
case 'post'
idx{k} = 1:M;
sizeB(k) = M + padSize(k);
case 'both'
idx{k} = (1:M) + padSize(k);
sizeB(k) = M + 2*padSize(k);
end
end
% Initialize output array with the padding value. Make sure the
% output array is the same type as the input.
b = mkconstarray(class(a), padVal, sizeB);
b(idx{:}) = a;
%%%
%%% CircularPad
%%%
function b = CircularPad(a, padSize, direction)
numDims = numel(padSize);
% Form index vectors to subsasgn input array into output array.
% Also compute the size of the output array.
idx = cell(1,numDims);
for k = 1:numDims
M = size(a,k);
dimNums = 1:M;
p = padSize(k);
switch direction
case 'pre'
idx{k} = dimNums(mod(-p:M-1, M) + 1);
case 'post'
idx{k} = dimNums(mod(0:M+p-1, M) + 1);
case 'both'
idx{k} = dimNums(mod(-p:M+p-1, M) + 1);
end
end
b = a(idx{:});
%%%
%%% SymmetricPad
%%%
function b = SymmetricPad(a, padSize, direction)
numDims = numel(padSize);
% Form index vectors to subsasgn input array into output array.
% Also compute the size of the output array.
idx = cell(1,numDims);
for k = 1:numDims
M = size(a,k);
dimNums = [1:M M:-1:1];
p = padSize(k);
switch direction
case 'pre'
idx{k} = dimNums(mod(-p:M-1, 2*M) + 1);
case 'post'
idx{k} = dimNums(mod(0:M+p-1, 2*M) + 1);
case 'both'
idx{k} = dimNums(mod(-p:M+p-1, 2*M) + 1);
end
end
b = a(idx{:});
%%%
%%% ReplicatePad
%%%
function b = ReplicatePad(a, padSize, direction)
numDims = numel(padSize);
% Form index vectors to subsasgn input array into output array.
% Also compute the size of the output array.
idx = cell(1,numDims);
for k = 1:numDims
M = size(a,k);
p = padSize(k);
onesVector = ones(1,p);
switch direction
case 'pre'
idx{k} = [onesVector 1:M];
case 'post'
idx{k} = [1:M M*onesVector];
case 'both'
idx{k} = [onesVector 1:M M*onesVector];
end
end
b = a(idx{:});
%%%
%%% ParseInputs
%%%
function [a, method, padSize, padVal, direction] = ParseInputs(varargin)
% default values
a = [];
method = 'constant';
padSize = [];
padVal = 0;
direction = 'both';
% checknargin(2,4,nargin,mfilename);
a = varargin{1};
padSize = varargin{2};
% checkinput(padSize, {'double'}, {'real' 'vector' 'nonnan' 'nonnegative' ...
% 'integer'}, mfilename, 'PADSIZE', 2);
% Preprocess the padding size
if (numel(padSize) < ndims(a))
padSize = padSize(:);
padSize(ndims(a)) = 0;
end
if nargin > 2
firstStringToProcess = 3;
if ~ischar(varargin{3})
% Third input must be pad value.
padVal = varargin{3};
% checkinput(padVal, {'numeric' 'logical'}, {'scalar'}, ...
% mfilename, 'PADVAL', 3);
firstStringToProcess = 4;
end
for k = firstStringToProcess:nargin
validStrings = {'circular' 'replicate' 'symmetric' 'pre' ...
'post' 'both'};
string = checkstrs(varargin{k}, validStrings, mfilename, ...
'METHOD or DIRECTION', k);
switch string
case {'circular' 'replicate' 'symmetric'}
method = string;
case {'pre' 'post' 'both'}
direction = string;
otherwise
error('Images:padarray:unexpectedError', '%s', ...
'Unexpected logic error.')
end
end
end
% Check the input array type
if strcmp(method,'constant') && ~(isnumeric(a) || islogical(a))
id = sprintf('Images:%s:badTypeForConstantPadding', mfilename);
msg1 = sprintf('Function %s expected A (argument 1)',mfilename);
msg2 = 'to be numeric or logical for constant padding.';
error(id,'%s\n%s',msg1,msg2);
end
|
github
|
jacksky64/imageProcessing-master
|
checkstrs.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_nlmeans/toolbox/ordfilt2/checkstrs.m
| 3,285 |
utf_8
|
ce89005e77c1e286eddbb59ed6c2d8b5
|
function out = checkstrs(in, valid_strings, function_name, ...
variable_name, argument_position)
%CHECKSTRS Check validity of option string.
% OUT = CHECKSTRS(IN,VALID_STRINGS,FUNCTION_NAME,VARIABLE_NAME, ...
% ARGUMENT_POSITION) checks the validity of the option string IN. It
% returns the matching string in VALID_STRINGS in OUT. CHECKSTRS looks
% for a case-insensitive nonambiguous match between IN and the strings
% in VALID_STRINGS.
%
% VALID_STRINGS is a cell array containing strings.
%
% FUNCTION_NAME is a string containing the function name to be used in the
% formatted error message.
%
% VARIABLE_NAME is a string containing the documented variable name to be
% used in the formatted error message.
%
% ARGUMENT_POSITION is a positive integer indicating which input argument
% is being checked; it is also used in the formatted error message.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 1.3.4.4 $ $Date: 2003/05/03 17:51:45 $
% Except for IN, input arguments are not checked for validity.
% checkinput(in, 'char', 'row', function_name, variable_name, argument_position);
start = regexpi(valid_strings, ['^' in]);
if ~iscell(start)
start = {start};
end
matches = ~cellfun('isempty',start);
idx = find(matches);
num_matches = length(idx);
if num_matches == 1
out = valid_strings{idx};
else
out = substringMatch(valid_strings(idx));
if isempty(out)
% Convert valid_strings to a single string containing a space-separated list
% of valid strings.
list = '';
for k = 1:length(valid_strings)
list = [list ', ' valid_strings{k}];
end
list(1:2) = [];
msg1 = sprintf('Function %s expected its %s input argument, %s,', ...
upper(function_name), num2ordinal(argument_position), ...
variable_name);
msg2 = 'to match one of these strings:';
if num_matches == 0
msg3 = sprintf('The input, ''%s'', did not match any of the valid strings.', in);
id = sprintf('Images:%s:unrecognizedStringChoice', function_name);
else
msg3 = sprintf('The input, ''%s'', matched more than one valid string.', in);
id = sprintf('Images:%s:ambiguousStringChoice', function_name);
end
error(id,'%s\n%s\n\n %s\n\n%s', msg1, msg2, list, msg3);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function str = substringMatch(strings)
% STR = substringMatch(STRINGS) looks at STRINGS (a cell array of
% strings) to see whether the shortest string is a proper substring of
% all the other strings. If it is, then substringMatch returns the
% shortest string; otherwise, it returns the empty string.
if isempty(strings)
str = '';
else
len = cellfun('prodofsize',strings);
[tmp,sortIdx] = sort(len);
strings = strings(sortIdx);
start = regexpi(strings(2:end), ['^' strings{1}]);
if isempty(start) || (iscell(start) && any(cellfun('isempty',start)))
str = '';
else
str = strings{1};
end
end
|
github
|
jacksky64/imageProcessing-master
|
ordfilt2.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_nlmeans/toolbox/ordfilt2/ordfilt2.m
| 4,253 |
utf_8
|
1ead5ab3bf1749efe031d260f06b3578
|
function B = ordfilt2(varargin)
%ORDFILT2 Perform 2-D order-statistic filtering.
% B=ORDFILT2(A,ORDER,DOMAIN) replaces each element in A by the
% ORDER-th element in the sorted set of neighbors specified by
% the nonzero elements in DOMAIN.
%
% B = ORDFILT2(A,ORDER,DOMAIN,S), where S is the same size as
% DOMAIN, uses the values of S corresponding to the nonzero
% values of DOMAIN as additive offsets.
%
% B = ORDFILT2(...,PADOPT) controls how the matrix boundaries
% are padded. PADOPT may be 'zeros' (the default) or
% 'symmetric'. If PADOPT is 'zeros', A is padded with zeros at
% the boundaries. If PADOPT is 'symmetric', A is symmetrically
% extended at the boundaries.
%
% Class Support
% -------------
% The class of A may be numeric or logical. The class of B is
% the same as the class of A, unless the additive offset form of
% ORDFILT2 is used, in which case the class of B is double.
%
% Example
% -------
% Use a maximum filter on snowflakes.png with a [5 5] neighborhood. This is
% equivalent to imdilate(image,strel('square',5)).
%
% A = imread('snowflakes.png');
% B = ordfilt2(A,25,true(5));
% imview(A), imview(B)
%
% Remarks
% -------
% DOMAIN is equivalent to the structuring element used for
% binary image operations. It is a matrix containing only 1's
% and 0's; the 1's define the neighborhood for the filtering
% operation.
%
% For example, B=ORDFILT2(A,5,ONES(3,3)) implements a 3-by-3
% median filter; B=ORDFILT2(A,1,ONES(3,3)) implements a 3-by-3
% minimum filter; and B=ORDFILT2(A,9,ONES(3,3)) implements a
% 3-by-3 maximum filter. B=ORDFILT2(A,4,[0 1 0; 1 0 1; 0 1 0])
% replaces each element in A by the maximum of its north, east,
% south, and west neighbors.
%
% See also MEDFILT2.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 5.17.4.5 $ $Date: 2003/08/23 05:53:07 $
[A,order,domain,s,padopt,msg] = ParseInputs(varargin{:});
domainSize = size(domain);
center = floor((domainSize + 1) / 2);
[r,c] = find(domain);
r = r - center(1);
c = c - center(2);
padSize = max(max(abs(r)), max(abs(c)));
originalSize = size(A);
if (strcmp(padopt, 'zeros'))
A = padarray(A, padSize * [1 1], 0, 'both');
elseif (strcmp(padopt, 'ones'))
% padopt of 'ones' is for support of medfilt2; it is
% undocumented
A = padarray(A, padSize * [1 1], 1, 'both');
else
A = padarray(A, padSize * [1 1], 'symmetric', 'both');
end
Ma = size(A,1);
offsets = c*Ma + r;
% make sure that offsets are valid
if ~isreal(offsets) || any(floor(offsets) ~= offsets) || any(~isfinite(offsets))
%should never get here
eid = sprintf('Images:%s:internalError', mfilename);
msg = 'Internal error: bad OFFSETS.';
error(eid,'%s',msg);
end
if isempty(s)
%ORDFILT2(A,ORDER,DOMAIN)
B = ordf(A, order, offsets, [padSize padSize] + 1, ...
originalSize, domainSize);
else
%ORDFILT2(A,ORDER,DOMAIN,S,PADOPT)
B = ordf(A, order, offsets, [padSize padSize] + 1, ...
originalSize, domainSize, s);
end
%%%
%%% ParseInputs
%%%
function [A,order,domain,s,padopt,msg] = ParseInputs(varargin)
A = [];
order = [];
domain = [];
s = [];
padopt = 'zeros';
msg = '';
% checknargin(3,5,nargin,mfilename);
A = varargin{1};
order = varargin{2};
domain = varargin{3};
options = {'zeros', 'ones', 'symmetric'};
% padopt of 'ones' is for supporting medfilt2; it is undocumented.
if (nargin == 4)
if (ischar(varargin{4}))
padopt = checkstrs(varargin{4},options,mfilename,'PADOPT',4);
else
s = varargin{4};
end
elseif (nargin == 5)
s = varargin{4};
padopt = checkstrs(varargin{5},options,mfilename,'PADOPT',5);
end
% make sure that arguments are valid
% checkinput(order,'double',{'real','scalar','integer'},mfilename, ...
% 'ORDER',2);
if ~isempty(s)
if (~isa(A, 'double'))
A = double(A);
end
% checkinput(A, 'double', {'2d','real'}, mfilename, 'A', 1);
s = s(find(domain));
% checkinput(s, 'double', 'real', mfilename, 'S', 4);
else
% checkinput(A, {'numeric','logical'}, {'2d','real'}, mfilename, 'A', 1);
end
|
github
|
jacksky64/imageProcessing-master
|
compute_butterfly_neighbors.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelet_meshes/compute_butterfly_neighbors.m
| 1,398 |
utf_8
|
0a690efe10cc4cbba37565df43f15a2f
|
function [e,v,g] = compute_butterfly_neighbors(k, nj)
% compute_butterfly_neighbors - compute local neighbors of a vertex
%
% [e,v,g] = compute_butterfly_neighbors(k, nj);
%
% This is for internal use.
%
% e are the 2 direct edge neighbors
% v are the 2 indirect neighbors
% g are the fare neighbors
%
% You need to provide:
% for e: vring, e2f
% for v: fring
% for g: facej
%
% Copyright (c) 2007 Gabriel Peyre
global vring e2f fring facej;
% find the 2 edges in the fine subdivition
vr = vring{k};
I = find(vr<=nj);
e = vr(I);
% find the coarse faces associated to the edge e
f = [e2f(e(1),e(2)) e2f(e(2),e(1))];
% symmetrize for boundary faces ...
f(f==-1) = f(3 - find(f==-1));
if nargout>1
F1 = mysetdiff(fring{f(1)}, f(2));
F2 = mysetdiff(fring{f(2)}, f(1));
% symmetrize for boundary faces
F1 = [F1 repmat(f(1), 1, 3-length(F1))];
F2 = [F2 repmat(f(2), 1, 3-length(F2))];
v = [ mysetdiff( facej(:,f(1)), e ) mysetdiff( facej(:,f(2)), e ) ];
if nargout>2
d = [v, e];
g = [setdiff( facej(:,F1(1)),d ), ...
mysetdiff( facej(:,F1(2)),d ), ...
mysetdiff( facej(:,F2(1)),d ), ...
mysetdiff( facej(:,F2(2)),d ) ];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function a = mysetdiff(a,b)
% removed in a entries equal to entries in b
for s=b
a(a==s) = [];
end
|
github
|
jacksky64/imageProcessing-master
|
load_spherical_function.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelet_meshes/load_spherical_function.m
| 1,810 |
utf_8
|
1999ea966df43f6770f67d42cee2a6f7
|
function f = load_spherical_function(name, pos, options)
% load_spherical_function - load a function on the sphere
%
% f = load_spherical_function(name, pos, options);
%
% Copyright (c) 2007 Gabriel Peyre
if iscell(pos)
pos = pos{end};
end
if size(pos,1)>size(pos,2)
pos = pos';
end
x = pos(1,:); x = x(:);
switch name
case 'linear'
f = x;
case 'cos'
f = cos(6*pi*x);
case 'singular'
f = abs(x).^.4;
case 'image'
name = getoptions(options, 'image_name', 'lena');
M = load_image(name);
q = size(M,1);
q = min(q,512);
M = crop(M,q);
M = perform_blurring(M,4);
f = perform_spherical_interpolation(pos,M);
case 'etopo'
resol = 15;
fname = ['ETOPO' num2str(resol)];
fid = fopen(fname, 'rb');
if fid<0
error('Unable to read ETOPO file');
end
s = [360*(60/resol), 180*(60/resol)];
M = fread(fid, Inf, 'short');
M = reshape(M, s(1),s(2) );
fclose(fid);
f = perform_spherical_interpolation(pos,M, 0);
case 'earth'
filename = 'earth-bw';
M = double( load_image(filename) );
M = perform_blurring(M,4);
f = perform_spherical_interpolation(pos,M,0);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = perform_spherical_interpolation(pos,M,center)
if nargin<3
center = 1;
end
qx = size(M,1);
qy = size(M,2);
Y = atan2(pos(2,:),pos(1,:))/(2*pi) + 1/2;
if center
X = acos(pos(3,:))/(2*pi) + 1/4;
else
X = acos(pos(3,:))/(pi);
end
x = linspace(0,1,qx);
y = linspace(0,1,qy);
f = interp2( y,x,M, Y(:),X(:) );
|
github
|
jacksky64/imageProcessing-master
|
perform_spherial_planar_sampling.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelet_meshes/perform_spherial_planar_sampling.m
| 2,972 |
utf_8
|
76d71d45fe348bef0c0f7dd26434dc52
|
function posw = perform_spherial_planar_sampling(pos_sphere, sampling_type)
% perform_spherial_planar_sampling - project sampling location from sphere to a square
%
% posw = perform_spherial_planar_sampling(pos_sphere, type)
%
% 'type' can be 'area' or 'gnomonic'.
%
% This is used to produced spherical geometry images.
% The sampling is first projected onto an octahedron and then unfolded on
% a square.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
sampling_type = 'area';
end
% all 3-tuple of {-1,1}
a = [-1 1];
[X,Y,Z] = meshgrid(a,a,a);
anchor_2d = {};
anchor_3d = {};
for i=1:8
x = X(i); y = Y(i); z = Z(i);
a2d = []; a3d = [];
if z>0
a2d = [a2d, [0;0]];
else
a2d = [a2d, [x;y]];
end
a2d = [a2d, [x;0]];
a2d = [a2d, [0;y]];
anchor_2d{i} = a2d;
a3d = [a3d, [0;0;z]];
a3d = [a3d, [x;0;0]];
a3d = [a3d, [0;y;0]];
anchor_3d{i} = a3d;
end
pos = pos_sphere;
n = size(pos, 2);
posw = zeros(2,n);
for s = 1:8
x = X(s); y = Y(s); z = Z(s);
anc2d = anchor_2d{s};
anc3d = anchor_3d{s};
I = find( signe(pos(1,:))==x & signe(pos(2,:))==y & signe(pos(3,:))==z );
posI = pos(:,I);
nI = length(I);
if strcmp(sampling_type, 'area')
% find the area of the 3 small triangles
p1 = repmat(anc3d(:,1), 1, nI);
p2 = repmat(anc3d(:,2), 1, nI);
p3 = repmat(anc3d(:,3), 1, nI);
a1 = compute_spherical_area( posI, p2, p3 );
a2 = compute_spherical_area( posI, p1, p3 );
a3 = compute_spherical_area( posI, p1, p2 );
% barycentric coordinates
a = a1+a2+a3;
% aa = compute_spherical_area( p1, p2, p3 );
a1 = a1./a; a2 = a2./a; a3 = a3./a;
elseif strcmp(sampling_type, 'gnomonic')
% we are searching for a point y=b*x (projection on the triangle)
% such that : a1*anc3d(:,1)+a2*anc3d(:,2)+a3*anc3d(:,3)-b*x=0
% a1+a2+a3=1
a1 = zeros(1,nI); a2 = a1; a3 = a1;
for i=1:nI
x = posI(:,i);
M = [1 1 1 0; anc3d(:,1), anc3d(:,2), anc3d(:,3), x];
a = M\[1;0;0;0];
a1(i) = a(1);
a2(i) = a(2);
a3(i) = a(3);
end
else
error('Unknown projection method.');
end
posw(:,I) = anc2d(:,1)*a1 + anc2d(:,2)*a2 + anc2d(:,3)*a3;
end
function y = signe(x)
y = double(x>=0)*2-1;
function A = compute_spherical_area( p1, p2, p3 )
% length of the sides of the triangles :
% cos(a)=p1*p2
a = acos( dotp(p2,p3) );
b = acos( dotp(p1,p3) );
c = acos( dotp(p1,p2) );
s = (a+b+c)/2;
% use L'Huilier's Theorem
% tand(E/4)^2 = tan(s/2).*tan( (s-a)/2 ).*tan( (s-b)/2 ).*tan( (s-c)/2 )
E = tan(s/2).*tan( (s-a)/2 ).*tan( (s-b)/2 ).*tan( (s-c)/2 );
A = 4*atan( sqrt( E ) );
A = real(A);
function d = dotp(x,y)
d = x(1,:).*y(1,:) + x(2,:).*y(2,:) + x(3,:).*y(3,:);
|
github
|
jacksky64/imageProcessing-master
|
load_image.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelet_meshes/toolbox/load_image.m
| 19,503 |
utf_8
|
16a3a912ce98f3734882ac9fe80494c2
|
function M = load_image(type, n, options)
% load_image - load benchmark images.
%
% M = load_image(name, n, options);
%
% name can be:
% Synthetic images:
% 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line',
% 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle',
% 'parabola', 'sin', 'phantom', 'circ_oscil',
% 'fnoise' (1/f^alpha noise).
% Natural images:
% 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
n = 512;
end
options.null = 0;
type = lower(type);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters for geometric objects
eta = 0.1; % translation
gamma = 1/sqrt(2); % slope
if isfield( options, 'eta' )
eta = options.eta;
end
if isfield( options, 'gamma' )
eta = options.gamma;
end
if isfield( options, 'radius' )
radius = options.radius;
end
if isfield( options, 'center' )
center = options.center;
end
if isfield( options, 'center1' )
center1 = options.center1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the line, can be vertical / horizontal / diagonal / any
if strcmp(type, 'line_vertical')
eta = 0.5; % translation
gamma = 0; % slope
elseif strcmp(type, 'line_horizontal')
eta = 0.5; % translation
gamma = Inf; % slope
elseif strcmp(type, 'line_diagonal')
eta = 0; % translation
gamma = 1; % slope
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for some blurring
sigma = 0;
if isfield(options, 'sigma')
sigma = options.sigma;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(type)
case {'letter-x' 'letter-v' 'letter-z' 'letter-y'}
if isfield(options, 'radius')
r = options.radius;
else
r = 10;
end
M = create_letter(type(8), r, n);
case 'l'
r1 = [.1 .1 .3 .9];
r2 = [.1 .1 .9 .4];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
case 'ellipse'
c1 = [0.15 0.5];
c2 = [0.85 0.5];
if isfield(options, 'eccentricity')
eccentricity = options.eccentricity;
else
eccentricity = 1.3;
end
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2);
M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) );
case 'ellipse-thin'
options.eccentricity = 1.06;
M = load_image('ellipse', n, options);
case 'ellipse-fat'
options.eccentricity = 1.3;
M = load_image('ellipse', n, options);
case 'square-tube'
if isfield(options, 'tube_width')
w = options.tube_width;
else
w = 0.06;
end
c1 = [.25 .5];
c2 = [.75 .5];
r1 = [c1 c1] + .18*[-1 -1 1 1];
r2 = [c2 c2] + .18*[-1 -1 1 1];
r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) );
case 'square-tube-1'
options.tube_width = 0.03;
M = load_image('square-tube', n, options);
case 'square-tube-2'
options.tube_width = 0.06;
M = load_image('square-tube', n, options);
case 'square-tube-3'
options.tube_width = 0.09;
M = load_image('square-tube', n, options);
case 'polygon'
if isfield(options, 'nb_points')
nb_points = options.nb_points;
else
nb_points = 9;
end
if isfield(options, 'scaling')
scaling = options.scaling;
else
scaling = 1;
end
theta = sort( rand(nb_points,1)*2*pi );
radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93);
points = [cos(theta) sin(theta)] .* repmat(radius, 1,2);
points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:);
M = draw_polygons(zeros(n),0.8,{points'});
[x,y] = ind2sub(size(M),find(M));
p = 100; m = length(x);
lambda = linspace(0,1,p);
X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]);
Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]);
I = round(X) + (round(Y)-1)*n;
M = zeros(n); M(I) = 1;
case 'polygon-8'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-10'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-12'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'pacman'
if isfield(options, 'theta')
theta = options.theta;
else
theta = 30 * 2*pi/360;
end
options.radius = 0.45;
M = load_image('disk', n, options);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
T =atan2(Y,X);
M = M .* (1-(abs(T)<theta/2));
case 'square-hole'
options.radius = 0.45;
M = load_image('disk', n, options);
options.scaling = 0.5;
M = M - load_image('polygon-10', n, options);
case 'grid-circles'
if isempty(n)
n = 256;
end
if isfield(options, 'frequency')
f = options.frequency;
else
f = 30;
end
if isfield(options, 'width')
eta = options.width;
else
eta = 0.3;
end
x = linspace(-n/2,n/2,n) - round(n*0.03);
y = linspace(0,n,n);
[Y,X] = meshgrid(y,x);
R = sqrt(X.^2+Y.^2);
theta = 0.05*pi/2;
X1 = cos(theta)*X+sin(theta)*Y;
Y1 = -sin(theta)*X+cos(theta)*Y;
A1 = abs(cos(2*pi*R/f))<eta;
A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta );
M = A1;
M(X1>0) = A2(X1>0);
case 'chessboard1'
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (2*(Y>=0)-1).*(2*(X>=0)-1);
case 'chessboard'
if ~isfield( options, 'width' )
width = round(n/16);
else
width = options.width;
end
[Y,X] = meshgrid(0:n-1,0:n-1);
M = mod( floor(X/width)+floor(Y/width), 2 ) == 0;
case 'square'
if ~isfield( options, 'radius' )
radius = 0.6;
end
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = max( abs(X),abs(Y) )<radius;
case 'squareregular'
M = rescale(load_image('square',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'regular1'
options.alpha = 1;
M = load_image('fnoise',n,options);
case 'regular2'
options.alpha = 2;
M = load_image('fnoise',n,options);
case 'regular3'
options.alpha = 3;
M = load_image('fnoise',n,options);
case 'sparsecurves'
options.alpha = 3;
M = load_image('fnoise',n,options);
M = rescale(M);
ncurves = 3;
M = cos(2*pi*ncurves);
case 'square_texture'
M = load_image('square',n);
M = rescale(M);
% make a texture patch
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta );
case 'oscillatory_texture'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M = sin( x * 2*pi / eta );
case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'}
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
if gamma~=Inf
M = (X-eta) - gamma*Y < 0;
else
M = (Y-eta) < 0;
end
case 'grating'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
if isfield(options, 'theta')
theta = options.theta;
else
theta = 0.2;
end
if isfield(options, 'freq')
freq = options.freq;
else
freq = 0.2;
end
X = cos(theta)*X + sin(theta)*Y;
M = sin(2*pi*X/freq);
case 'disk'
if ~isfield( options, 'radius' )
radius = 0.35;
end
if ~isfield( options, 'center' )
center = [0.5, 0.5]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'diskregular'
M = rescale(load_image('disk',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'quarterdisk'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'fading_contour'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
theta = 2/pi*atan2(Y,X);
h = 0.5;
M = exp(-(1-theta).^2/h^2).*M;
case '3contours'
radius = 1.3;
center = [-1, 1];
radius1 = 0.8;
center1 = [0, 0];
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2;
M = f1 + 0.5*f2.*(1-f1);
case 'line_circle'
gamma = 1/sqrt(2);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M1 = double( X>gamma*Y+0.25 );
M2 = X.^2 + Y.^2 < 0.6^2;
M = 20 + max(0.5*M1,M2) * 216;
case 'fnoise'
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
if isfield(options, 'alpha')
alpha = options.alpha;
else
alpha = 1;
end
M = gen_noisy_image(n,alpha);
case 'gaussiannoise'
% generate an image of filtered noise with gaussian
if isfield(options, 'sigma')
sigma = options.sigma;
else
sigma = 10;
end
M = randn(n);
m = 51;
h = compute_gaussian_filter([m m],sigma/(4*n),[n n]);
M = perform_convolution(M,h);
return;
case {'bwhorizontal','bwvertical','bwcircle'}
[Y,X] = meshgrid(0:n-1,0:n-1);
if strcmp(type, 'bwhorizontal')
d = X;
elseif strcmp(type, 'bwvertical')
d = Y;
elseif strcmp(type, 'bwcircle')
d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 );
end
if isfield(options, 'stripe_width')
stripe_width = options.stripe_width;
else
stripe_width = 5;
end
if isfield(options, 'black_prop')
black_prop = options.black_prop;
else
black_prop = 0.5;
end
M = double( mod( d/(2*stripe_width),1 )>=black_prop );
case 'parabola'
% curvature
if isfield(options, 'c')
c = options.c;
else
c = 0.1;
end
% angle
if isfield(options, 'theta');
theta = options.theta;
else
theta = pi/sqrt(2);
end
x = -0.5:1/(n-1):0.5;
[Y,X] = meshgrid(x,x);
Xs = X*cos(theta) + Y*sin(theta);
Y =-X*sin(theta) + Y*cos(theta); X = Xs;
M = Y>c*X.^2;
case 'sin'
[Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1);
M = Y >= 0.6*cos(pi*X);
M = double(M);
case 'circ_oscil'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
R = sqrt(X.^2+Y.^2);
M = cos(R.^3*50);
case 'phantom'
M = phantom(n);
case 'periodic_bumps'
if isfield(options, 'nbr_periods')
nbr_periods = options.nbr_periods;
else
nbr_periods = 8;
end
if isfield(options, 'theta')
theta = options.theta;
else
theta = 1/sqrt(2);
end
if isfield(options, 'skew')
skew = options.skew;
else
skew = 1/sqrt(2);
end
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];
B = [1 skew; 0 1];
T = B*A;
x = (0:n-1)*2*pi*nbr_periods/(n-1);
[Y,X] = meshgrid(x,x);
pos = [X(:)'; Y(:)'];
pos = T*pos;
X = reshape(pos(1,:), n,n);
Y = reshape(pos(2,:), n,n);
M = cos(X).*sin(Y);
case 'noise'
if isfield(options, 'sigma')
sigma = options.sigma;
else
sigma = 1;
end
M = randn(n);
otherwise
ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'};
for i=1:length(ext)
name = [type '.' ext{i}];
if( exist(name) )
M = imread( name );
M = double(M);
if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2
M = image_resize(M,n,n);
end
return;
end
end
error( ['Image ' type ' does not exists.'] );
end
M = double(M);
if sigma>0
h = compute_gaussian_filter( [9 9], sigma/(2*n), [n n]);
M = perform_convolution(M,h);
end
M = rescale(M) * 256;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = create_letter(a, r, n)
c = 0.2;
p1 = [c;c];
p2 = [c; 1-c];
p3 = [1-c; 1-c];
p4 = [1-c; c];
p4 = [1-c; c];
pc = [0.5;0.5];
pu = [0.5; c];
switch a
case 'x'
point_list = { [p1 p3] [p2 p4] };
case 'z'
point_list = { [p2 p3 p1 p4] };
case 'v'
point_list = { [p2 pu p3] };
case 'y'
point_list = { [p2 pc pu] [pc p3] };
end
% fit image
for i=1:length(point_list)
a = point_list{i}(2:-1:1,:);
a(1,:) = 1-a(1,:);
point_list{i} = round( a*(n-1)+1 );
end
M = draw_polygons(zeros(n),r,point_list);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_polygons(mask,r,point_list)
sk = mask*0;
for i=1:length(point_list)
pl = point_list{i};
for k=2:length(pl)
sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_line(sk,x1,y1,x2,y2,r)
n = size(sk,1);
[Y,X] = meshgrid(1:n,1:n);
q = 100;
t = linspace(0,1,q);
x = x1*t+x2*(1-t); y = y1*t+y2*(1-t);
if r==0
x = round( x ); y = round( y );
sk( x+(y-1)*n ) = 1;
else
for k=1:q
I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 );
sk(I) = 1;
end
end
function M = gen_noisy_image(n,alpha)
% gen_noisy_image - generate a noisy cloud-like image.
%
% M = gen_noisy_image(n,alpha);
%
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin<1
n = 128;
end
if nargin<2
alpha = 1.5;
end
if mod(n(1),2)==0
x = -n/2:n/2-1;
else
x = -(n-1)/2:(n-1)/2;
end
[Y,X] = meshgrid(x,x);
d = sqrt(X.^2 + Y.^2) + 0.1;
f = rand(n)*2*pi;
M = (d.^(-alpha)) .* exp(f*1i);
% M = real(ifft2(fftshift(M)));
M = ifftshift(M);
M = real( ifft2(M) );
function y = gen_signal_2d(n,alpha)
% gen_signal_2d - generate a 2D C^\alpha signal of length n x n.
% gen_signal_2d(n,alpha) generate a 2D signal C^alpha.
%
% The signal is scale in [0,1].
%
% Copyright (c) 2003 Gabriel Peyr?
% new new method
[Y,X] = meshgrid(0:n-1, 0:n-1);
A = X+Y+1;
B = X-Y+n+1;
a = gen_signal(2*n+1, alpha);
b = gen_signal(2*n+1, alpha);
y = a(A).*b(B);
% M = a(1:n)*b(1:n)';
return;
% new method
h = (-n/2+1):(n/2); h(n/2)=1;
[X,Y] = meshgrid(h,h);
h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2);
h = h .* exp( 2i*pi*rand(n,n) );
h = fftshift(h);
y = real( ifft2(h) );
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
return;
%% old code
y = rand(n,n);
y = y - mean(mean(y));
for i=1:alpha
y = cumsum(cumsum(y)')';
y = y - mean(mean(y));
end
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
function newimg = image_resize(img,p1,q1,r1)
% image_resize - resize an image using bicubic interpolation
%
% newimg = image_resize(img,nx,ny,nz);
% or
% newimg = image_resize(img,newsize);
%
% Works for 2D, 2D 2 or 3 channels, 3D images.
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin==2
% size specified as an array
q1 = p1(2);
if length(p1)>2
r1 = p1(3);
else
r1 = size(img,3);
end
p1 = p1(1);
end
if nargin<4
r1 = size(img,3);
end
if ndims(img)<2 || ndims(img)>3
error('Works only for grayscale or color images');
end
if ndims(img)==3 && size(img,3)<4
% RVB image
newimg = zeros(p1,q1, size(img,3));
for m=1:size(img,3)
newimg(:,:,m) = image_resize(img(:,:,m), p1, q1);
end
return;
elseif ndims(img)==3
p = size(img,1);
q = size(img,2);
r = size(img,3);
[Y,X,Z] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1), (0:r-1)/(r-1) );
[YI,XI,ZI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1), (0:r1-1)/(r1-1) );
newimg = interp3( Y,X,Z, img, YI,XI,ZI ,'cubic');
return;
end
p = size(img,1);
q = size(img,2);
[Y,X] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1) );
[YI,XI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1) );
newimg = interp2( Y,X, img, YI,XI ,'cubic');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = draw_rectangle(r,n)
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
|
github
|
jacksky64/imageProcessing-master
|
check_face_vertex.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelet_meshes/toolbox/check_face_vertex.m
| 646 |
utf_8
|
fe3c5da3b1ca8f15eb7eed61acfc2259
|
function [vertex,face] = check_face_vertex(vertex,face, options)
% check_face_vertex - check that vertices and faces have the correct size
%
% [vertex,face] = check_face_vertex(vertex,face);
%
% Copyright (c) 2007 Gabriel Peyre
vertex = check_size(vertex);
face = check_size(face);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function a = check_size(a)
if isempty(a)
return;
end
if size(a,1)>size(a,2)
a = a';
end
if size(a,1)<3 && size(a,2)==3
a = a';
end
if size(a,1)<=3 && size(a,2)>=3 && sum(abs(a(:,3)))==0
% for flat triangles
a = a';
end
if size(a,1)~=3 && size(a,1)~=4
error('face or vertex is not of correct size');
end
|
github
|
jacksky64/imageProcessing-master
|
compute_mesh_weight.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelet_meshes/toolbox/compute_mesh_weight.m
| 2,820 |
utf_8
|
c90377b7ee516f5f952ce8c31dcfd43b
|
function W = compute_mesh_weight(vertex,face,type,options)
% compute_mesh_weight - compute a weight matrix
%
% W = compute_mesh_weight(vertex,face,type,options);
%
% W is sparse weight matrix and W(i,j)=0 is vertex i and vertex j are not
% connected in the mesh.
%
% type is either
% 'combinatorial': W(i,j)=1 is vertex i is conntected to vertex j.
% 'distance': W(i,j) = 1/d_ij^2 where d_ij is distance between vertex
% i and j.
% 'conformal': W(i,j) = cot(alpha_ij)+cot(beta_ij) where alpha_ij and
% beta_ij are the adjacent angle to edge (i,j)
%
% If options.normalize=1, the the rows of W are normalize to sum to 1.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
[vertex,face] = check_face_vertex(vertex,face);
nface = size(face,1);
n = max(max(face));
if isfield(options, 'verb')
verb = options.verb;
else
verb = n>5000;
end
if nargin<3
type = 'conformal';
end
switch lower(type)
case 'combinatorial'
W = triangulation2adjacency(face);
case 'distance'
W = my_euclidean_distance(triangulation2adjacency(face),vertex);
W(W>0) = 1./W(W>0);
W = (W+W')/2;
case 'conformal'
% conformal laplacian
W = sparse(n,n);
ring = compute_vertex_face_ring(face);
for i = 1:n
if verb
progressbar(i,n);
end
for b = ring{i}
% b is a face adjacent to a
bf = face(:,b);
% compute complementary vertices
if bf(1)==i
v = bf(2:3);
elseif bf(2)==i
v = bf([1 3]);
elseif bf(3)==i
v = bf(1:2);
else
error('Problem in face ring.');
end
j = v(1); k = v(2);
vi = vertex(:,i);
vj = vertex(:,j);
vk = vertex(:,k);
% angles
alpha = myangle(vk-vi,vk-vj);
beta = myangle(vj-vi,vj-vk);
% add weight
W(i,j) = W(i,j) + cot( alpha );
W(i,k) = W(i,k) + cot( beta );
end
end
otherwise
error('Unknown type.')
end
if isfield(options, 'normalize') && options.normalize==1
W = diag(sum(W,2).^(-1)) * W;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function beta = myangle(u,v);
du = sqrt( sum(u.^2) );
dv = sqrt( sum(v.^2) );
du = max(du,eps); dv = max(dv,eps);
beta = acos( sum(u.*v) / (du*dv) );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function W = my_euclidean_distance(A,vertex)
if size(vertex,1)<size(vertex,2)
vertex = vertex';
end
[i,j,s] = find(sparse(A));
d = sum( (vertex(i,:) - vertex(j,:)).^2, 2);
W = sparse(i,j,d);
|
github
|
jacksky64/imageProcessing-master
|
plot_tensor_field.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_diffc/plot_tensor_field.m
| 5,736 |
utf_8
|
8e241783316bc4c13529031d81db17d4
|
function h = plot_tensor_field(H, M, options)
% plot_tensor_field - display a tensor field
%
% h = plot_tensor_field(H, M, options);
%
% options.sub controls sub-sampling
% options.color controls color
%
% Copyright (c) 2006 Gabriel Peyre
if nargin<3
options.null = 0;
end
if not( isstruct(options) )
sub = options;
clear options;
options.sub = sub;
end
% sub = getoptions(options, 'sub', 1);
sub = getoptions(options, 'sub', round(size(H,1)/30) );
color = getoptions(options, 'color', 'r');
if nargin<2
M = [];
end
if not(isempty(M)) && size(M,3)==1
M = repmat(M, [1 1 3]); % ensure B&W image
end
if size(H,3)==3 && size(H,4)==1
H = cat(3, H(:,:,1), H(:,:,3), H(:,:,3), H(:,:,2) );
H = reshape(H, size(H,1), size(H,2), 2, 2);
if 0
% flip the main eigen-axes
[e1,e2,l1,l2] = perform_tensor_decomp(H);
H = perform_tensor_recomp(e2,e1,l1,l2);
end
h = plot_tensor_field(H, M, sub);
return;
end
% swap X and Y axis
%%% TODO
a = H(:,:,2,2);
H(:,:,2,2) = H(:,:,1,1);
H(:,:,1,1) = a;
hold on;
if ~isempty(M)
imagesc(rescale(M)); drawnow;
end
h = fn_tensordisplay(H(:,:,1,1),H(:,:,1,2), H(:,:,2,2), 'sub', sub, 'color', color);
axis image; axis off;
colormap jet(256);
% hold off;
function h = fn_tensordisplay(varargin)
% function h = fn_tensordisplay([X,Y,]Txx,Txy,Tyy[,'sigma',sigma][,'sub',sub][,color][,patch options...]])
% function h = fn_tensordisplay([X,Y,]e[,'sigma',sigma][,'sub',sub][,color][,patch options...]])
% X,Y,Txx,Txy,Tyy
if isstruct(varargin{1}) || isstruct(varargin{3})
if isstruct(varargin{1}), nextarg=1; else nextarg=3; end
e = varargin{nextarg};
Txx = e.ytyt;
Txy = -e.ytyx;
Tyy = e.yxyx;
if nextarg==1
[nj ni] = size(Txx);
[X Y] = meshgrid(1:ni,1:nj);
else
[X Y] = deal(varargin{1:2});
end
nextarg = nextarg+1;
else
[nj ni] = size(varargin{3});
if nargin<5 || ischar(varargin{4}) || ischar(varargin{5}) || any(size(varargin{5})~=[nj ni])
[X Y] = meshgrid(1:ni,1:nj);
nextarg = 1;
else
[X Y] = deal(varargin{1:2});
nextarg = 3;
end
[Txx Txy Tyy] = deal(varargin{nextarg:nextarg+2});
nextarg = nextarg+3;
end
if any(size(X)==1), [X Y] = meshgrid(X,Y); end
[nj,ni] = size(X);
if any(size(Y)~=[nj ni]) || ...
any(size(Txx)~=[nj ni]) || any(size(Txy)~=[nj ni]) || any(size(Tyy)~=[nj ni])
error('Matrices must be same size')
end
% sigma, sub, color
color = 'r';
while nextarg<=nargin
flag = varargin{nextarg};
nextarg=nextarg+1;
if ~ischar(flag), color = flag; continue, end
switch lower(flag)
case 'sigma'
sigma = varargin{nextarg};
nextarg = nextarg+1;
switch length(sigma)
case 1
sigmax = sigma;
sigmay = sigma;
case 2
sigmax = sigma(1);
sigmay = sigma(2);
otherwise
error('sigma definition should entail two values');
end
h = fspecial('gaussian',[ceil(2*sigmay) 1],sigmay)*fspecial('gaussian',[1 ceil(2*sigmax)],sigmax);
Txx = imfilter(Txx,h,'replicate');
Txy = imfilter(Txy,h,'replicate');
Tyy = imfilter(Tyy,h,'replicate');
case 'sub'
sub = varargin{nextarg};
nextarg = nextarg+1;
switch length(sub)
case 1
[x y] = meshgrid(1:sub:ni,1:sub:nj);
sub = y+nj*(x-1);
case 2
[x y] = meshgrid(1:sub(1):ni,1:sub(2):nj);
sub = y+nj*(x-1);
end
X = X(sub); Y = Y(sub);
Txx = Txx(sub); Txy = Txy(sub); Tyy = Tyy(sub);
[nj ni] = size(sub);
case 'color'
color = varargin{nextarg};
nextarg = nextarg+1;
otherwise
break
end
end
% options
options = {varargin{nextarg:end}};
npoints = 50;
theta = (0:npoints-1)*(2*pi/npoints);
circle = [cos(theta) ; sin(theta)];
Tensor = cat(3,Txx,Txy,Txy,Tyy); % jdisplay x idisplay x tensor
Tensor = reshape(Tensor,2*nj*ni,2); % (display x 1tensor) x 2tensor
Ellipse = Tensor * circle; % (display x uv) x npoints
Ellipse = reshape(Ellipse,nj*ni,2,npoints); % display x uv x npoints
XX = repmat(X(:),1,npoints); % display x npoints
YY = repmat(Y(:),1,npoints); % display x npoints
U = reshape(Ellipse(:,1,:),nj*ni,npoints); % display x npoints
V = reshape(Ellipse(:,2,:),nj*ni,npoints); % display x npoints
umax = max(U')'; vmax = max(V')';
umax(umax==0)=1; vmax(vmax==0)=1;
if ni==1, dx=1; else dx = X(1,2)-X(1,1); end
if nj==1, dy=1; else dy = Y(2,1)-Y(1,1); end
fact = min(dx./umax,dy./vmax)*.35;
fact = repmat(fact,1,npoints);
U = XX + fact.*U;
V = YY + fact.*V;
%-----------
MM = mmax(Txx+Tyy);
mm = mmin(Txx+Tyy);
[S1, S2] = size(U);
Colormap = zeros(S2, S1, 3);
Map = colormap(jet(256));
for k =1:npoints
Colormap(k,:,1) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 1);
Colormap(k,:,2) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 2);
Colormap(k,:,3) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 3);
end
%-----------
%h = fill(U',V',color,'EdgeColor',color,options{:});
h = fill(U',V',Colormap,'EdgeColor', 'interp');
axis ij;
if nargout==0, clear h, end
function a=mmax(a)
a = max(a(:));
function a=mmin(a)
a = min(a(:));
|
github
|
jacksky64/imageProcessing-master
|
compute_structure_tensor.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_diffc/compute_structure_tensor.m
| 5,058 |
utf_8
|
606bd8981d5d25ac5b04496f5007d00b
|
function H = compute_structure_tensor(M,sigma1,sigma2, options)
% compute_structure_tensor - compute the structure tensor
%
% T = compute_structure_tensor(M,sigma1,sigma2);
%
% sigma1 is pre smoothing width (in pixels).
% sigma2 is post smoothing width (in pixels).
%
% Follows the ideas of
% U. K?the, "Edge and Junction Detection with an Improved Structure Tensor",
% Proc. of 25th DAGM Symposium, Magdeburg 2003,
% Lecture Notes in Computer Science 2781, pp. 25-32, Berlin: Springer, 2003
%
% You can set:
% - options.sub=2 [default=2] to perform x2 interpolation of the
% gradient to avoid aliasing.
% - options.use_renormalization=1 [detault=0] to compute the tensor
% using unit norm gradient vectors.
% - options.use_anisotropic=1 [detaul=0] to perform anisotropic
% smoothing using a hour-glass shaped gaussian kernel.
% This better capture edges anisotropy.
%
% Copyright (c) 2006 Gabriel Peyre
n = size(M,1);
if nargin<2
sigma1 = 1;
end
if nargin<3
sigma2 = 3;
end
options.null = 0;
sub = getoptions(options, 'sub', 2);
use_anisotropic = getoptions(options, 'use_anisotropic', 0);
use_grad_renormalization = getoptions(options, 'use_grad_renormalization', 0);
use_tensor_renormalization = getoptions(options, 'use_tensor_renormalization', 0);
m_theta = getoptions(options, 'm_theta', 16);
sigmat = getoptions(options, 'sigmat', .4);
lambda = 3;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% pre smoothing
m = round( sigma1 )*2+1;
m = max(m,7);
h = compute_gaussian_filter([m m],sigma1/(lambda*n),[n n]);
M = perform_convolution(M,h);
% compute gradient
[gx,gy] = compute_grad(M);
% take the vector orthogonal to the gradient
tmp = gx; gx = gy; gy = -tmp;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% interpolates
if sub>1
meth = 'cubic';
[X,Y] = meshgrid(1:n,1:n);
[XI,YI] = meshgrid(1:1/2:n+1/2,1:1/2:n+1/2); XI(:,end) = n; YI(end,:) = n;
gx = interp2(X,Y,gx,XI,YI);
gy = interp2(X,Y,gy,XI,YI);
end
if use_grad_renormalization
d = sqrt( gx.^2 + gy.^2 );
d(d<eps) = 1;
gx = gx./d; gy = gy./d;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute tensors
T = zeros(n,n,2,2);
gx2 = gx.^2;
gy2 = gy.^2;
gxy = gx.*gy;
H = zeros(n*sub,n*sub,2,2);
H(:,:,1,1) = gx2;
H(:,:,2,2) = gy2;
H(:,:,1,2) = gxy;
H(:,:,2,1) = gxy;
if use_tensor_renormalization
sigma0 = 16; % initial isotropy
eta0 = 12; % intial anisotropy
[e1,e2,l1,l2] = perform_tensor_decomp(H);
l1 = l1*0 + sqrt(sigma0*eta0);
l2 = l2*0 + sqrt(sigma0/eta0);
H = perform_tensor_recomp(e1,e2,l1,l2);
end
gx2 = H(:,:,1,1);
gy2 = H(:,:,2,2);
gxy = H(:,:,1,2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% smooth
if ~use_anisotropic
m = round( sub*sigma2*1.2 )*2+1;
m = min(m, round(n/2)*2+1);
% perform isotropic smoothing
h = compute_gaussian_filter([m m],sub*sigma2/(lambda*n),[n n]);
gx2 = perform_convolution(gx2,h);
gy2 = perform_convolution(gy2,h);
gxy = perform_convolution(gxy,h);
else
% perform anisotropic hour-glass smoothing
theta = linspace(0,pi,m_theta+1); theta(end) = [];
for i=1:m_theta
h = compute_hour_glass_filters( m*sub, sub*sigma2/(lambda*n), sigmat, n, theta(i) );
Gx2(:,:,i) = perform_convolution(gx2,h);
Gy2(:,:,i) = perform_convolution(gy2,h);
Gxy(:,:,i) = perform_convolution(gxy,h);
end
% select correct location
Theta = repmat( mod(atan2(gy,gx),pi), [1 1 m_theta] );
theta = repmat( reshape(theta(:),[1 1 m_theta]), [sub*n sub*n 1] );
[tmp,I] = min( abs(Theta-theta),[],3 );
I = reshape( (1:(sub*n)^2)' + (I(:)-1)*(sub*n)^2, sub*n,sub*n );
gx2 = Gx2(I);
gy2 = Gy2(I);
gxy = Gxy(I);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% assemble tensor
H = zeros(n,n,2,2);
H(:,:,1,1) = gx2(1:sub:end,1:sub:end);
H(:,:,2,2) = gy2(1:sub:end,1:sub:end);
H(:,:,1,2) = gxy(1:sub:end,1:sub:end);
H(:,:,2,1) = H(:,:,1,2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = compute_hour_glass_filters( n, sigmar, sigmat, N, theta )
% sigmar is variance in radial direction (in pixels, so sigmar=4 is a good
% choice)
% sigmat is variance in angular direction (in radian, so sigmar=0.4 is a good
% choice)
if length(theta)>1
for i=1:length(theta)
h(:,:,i) = compute_hour_glass_filters( n, sigma, N, theta(i) );
end
return;
end
x = ( (0:n-1)-(n-1)/2 )/(N-1);
[Y,X] = meshgrid(x,x);
r = sqrt(X.^2 + Y.^2);
phi = atan2(Y,X);
f = exp( - r.^2 / (2*sigmar^2) );
f = f .* exp( - tan(phi-theta).^2 / (2*sigmat^2) );
f = f / sum(f(:));
|
github
|
jacksky64/imageProcessing-master
|
plot_tensor_field_nb.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_diffc/plot_tensor_field_nb.m
| 5,107 |
utf_8
|
5f6826cefc68c6e07eaf23afe0858e50
|
function h = plot_tensor_field(H, M, options)
% plot_tensor_field - display a tensor field
%
% h = plot_tensor_field(H, M, options);
%
% options.sub controls sub-sampling
% options.color controls color
%
% Copyright (c) 2006 Gabriel Peyre
if nargin<3
options.null = 0;
end
if not( isstruct(options) )
sub = options;
clear options;
options.sub = sub;
end
sub = getoptions(options, 'sub', round(size(H,1)/30) );
color = getoptions(options, 'color', 'r');
if nargin<2
M = [];
end
if size(H,3)==3 && size(H,4)==1
H = cat(3, H(:,:,1), H(:,:,3), H(:,:,3), H(:,:,2) );
H = reshape(H, size(H,1), size(H,2), 2, 2);
if 0
% flip the main eigen-axes
[e1,e2,l1,l2] = perform_tensor_decomp(H);
H = perform_tensor_recomp(e2,e1,l1,l2);
end
h = plot_tensor_field(H, M, sub);
return;
end
% swap X and Y axis
a = H(:,:,2,2);
H(:,:,2,2) = H(:,:,1,1);
H(:,:,1,1) = a;
hold on;
if ~isempty(M)
imagesc(rescale(M));
end
h = fn_tensordisplay(H(:,:,1,1),H(:,:,1,2), H(:,:,2,2), 'sub', sub, 'color', color);
axis image; axis off;
if ~isempty(M) && size(M,3)==1
colormap gray(256);
end
% hold off;
function h = fn_tensordisplay(varargin)
% function h = fn_tensordisplay([X,Y,]Txx,Txy,Tyy[,'sigma',sigma][,'sub',sub][,color][,patch options...]])
% function h = fn_tensordisplay([X,Y,]e[,'sigma',sigma][,'sub',sub][,color][,patch options...]])
% X,Y,Txx,Txy,Tyy
if isstruct(varargin{1}) || isstruct(varargin{3})
if isstruct(varargin{1}), nextarg=1; else nextarg=3; end
e = varargin{nextarg};
Txx = e.ytyt;
Txy = -e.ytyx;
Tyy = e.yxyx;
if nextarg==1
[nj ni] = size(Txx);
[X Y] = meshgrid(1:ni,1:nj);
else
[X Y] = deal(varargin{1:2});
end
nextarg = nextarg+1;
else
[nj ni] = size(varargin{3});
if nargin<5 || ischar(varargin{4}) || ischar(varargin{5}) || any(size(varargin{5})~=[nj ni])
[X Y] = meshgrid(1:ni,1:nj);
nextarg = 1;
else
[X Y] = deal(varargin{1:2});
nextarg = 3;
end
[Txx Txy Tyy] = deal(varargin{nextarg:nextarg+2});
nextarg = nextarg+3;
end
if any(size(X)==1), [X Y] = meshgrid(X,Y); end
[nj,ni] = size(X);
if any(size(Y)~=[nj ni]) || ...
any(size(Txx)~=[nj ni]) || any(size(Txy)~=[nj ni]) || any(size(Tyy)~=[nj ni])
error('Matrices must be same size')
end
% sigma, sub, color
color = 'r';
while nextarg<=nargin
flag = varargin{nextarg};
nextarg=nextarg+1;
if ~ischar(flag), color = flag; continue, end
switch lower(flag)
case 'sigma'
sigma = varargin{nextarg};
nextarg = nextarg+1;
switch length(sigma)
case 1
sigmax = sigma;
sigmay = sigma;
case 2
sigmax = sigma(1);
sigmay = sigma(2);
otherwise
error('sigma definition should entail two values');
end
h = fspecial('gaussian',[ceil(2*sigmay) 1],sigmay)*fspecial('gaussian',[1 ceil(2*sigmax)],sigmax);
Txx = imfilter(Txx,h,'replicate');
Txy = imfilter(Txy,h,'replicate');
Tyy = imfilter(Tyy,h,'replicate');
case 'sub'
sub = varargin{nextarg};
nextarg = nextarg+1;
switch length(sub)
case 1
[x y] = meshgrid(1:sub:ni,1:sub:nj);
sub = y+nj*(x-1);
case 2
[x y] = meshgrid(1:sub(1):ni,1:sub(2):nj);
sub = y+nj*(x-1);
end
X = X(sub); Y = Y(sub);
Txx = Txx(sub); Txy = Txy(sub); Tyy = Tyy(sub);
[nj ni] = size(sub);
case 'color'
color = varargin{nextarg};
nextarg = nextarg+1;
otherwise
break
end
end
% options
options = {varargin{nextarg:end}};
npoints = 50;
theta = (0:npoints-1)*(2*pi/npoints);
circle = [cos(theta) ; sin(theta)];
Tensor = cat(3,Txx,Txy,Txy,Tyy); % jdisplay x idisplay x tensor
Tensor = reshape(Tensor,2*nj*ni,2); % (display x 1tensor) x 2tensor
Ellipse = Tensor * circle; % (display x uv) x npoints
Ellipse = reshape(Ellipse,nj*ni,2,npoints); % display x uv x npoints
XX = repmat(X(:),1,npoints); % display x npoints
YY = repmat(Y(:),1,npoints); % display x npoints
U = reshape(Ellipse(:,1,:),nj*ni,npoints); % display x npoints
V = reshape(Ellipse(:,2,:),nj*ni,npoints); % display x npoints
umax = max(U')'; vmax = max(V')';
umax(umax==0)=1; vmax(vmax==0)=1;
if ni==1, dx=1; else dx = X(1,2)-X(1,1); end
if nj==1, dy=1; else dy = Y(2,1)-Y(1,1); end
fact = min(dx./umax,dy./vmax)*.35;
fact = repmat(fact,1,npoints);
U = XX + fact.*U;
V = YY + fact.*V;
h = fill(U',V',color,'EdgeColor',color,options{:});
axis ij;
if nargout==0, clear h, end
|
github
|
jacksky64/imageProcessing-master
|
load_image.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_diffc/toolbox/load_image.m
| 20,485 |
utf_8
|
59636d167046aad9d9e169c474427ee1
|
function M = load_image(type, n, options)
% load_image - load benchmark images.
%
% M = load_image(name, n, options);
%
% name can be:
% Synthetic images:
% 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line',
% 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle',
% 'parabola', 'sin', 'phantom', 'circ_oscil',
% 'fnoise' (1/f^alpha noise).
% Natural images:
% 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
n = 512;
end
options.null = 0;
type = lower(type);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters for geometric objects
eta = getoptions(options, 'eta', .1);
gamma = getoptions(options, 'gamma', 1/sqrt(2));
radius = getoptions(options, 'radius', 10);
center = getoptions(options, 'center', [0 0]);
center1 = getoptions(options, 'center1', [0 0]);
w = getoptions(options, 'tube_width', 0.06);
nb_points = getoptions(options, 'nb_points', 9);
scaling = getoptions(options, 'scaling', 1);
theta = getoptions(options, 'theta', 30 * 2*pi/360);
eccentricity = getoptions(options, 'eccentricity', 1.3);
sigma = getoptions(options, 'sigma', 0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the line, can be vertical / horizontal / diagonal / any
if strcmp(type, 'line_vertical')
eta = 0.5; % translation
gamma = 0; % slope
elseif strcmp(type, 'line_horizontal')
eta = 0.5; % translation
gamma = Inf; % slope
elseif strcmp(type, 'line_diagonal')
eta = 0; % translation
gamma = 1; % slope
end
if strcmp(type(1:min(12,end)), 'square-tube-')
k = str2double(type(13:end));
c1 = [.22 .5]; c2 = [1-c1(1) .5];
eta = 1.5;
r1 = [c1 c1] + .21*[-1 -eta 1 eta];
r2 = [c2 c2] + .21*[-1 -eta 1 eta];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
if mod(k,2)==0
sel = n/2-k/2+1:n/2+k/2;
else
sel = n/2-(k-1)/2:n/2+(k-1)/2;
end
M( round(.25*n:.75*n), sel ) = 1;
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(type)
case 'constant'
M = ones(n);
case 'ramp'
x = linspace(0,1,n);
[Y,M] = meshgrid(x,x);
case 'bump'
s = getoptions(options, 'bump_size', .5);
c = getoptions(options, 'center', [0 0]);
if length(s)==1
s = [s s];
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
X = (X-c(1))/s(1); Y = (Y-c(2))/s(2);
M = exp( -(X.^2+Y.^2)/2 );
case 'periodic'
x = linspace(-pi,pi,n)/1.1;
[Y,X] = meshgrid(x,x);
f = getoptions(options, 'freq', 6);
M = (1+cos(f*X)).*(1+cos(f*Y));
case {'letter-x' 'letter-v' 'letter-z' 'letter-y'}
M = create_letter(type(8), radius, n);
case 'l'
r1 = [.1 .1 .3 .9];
r2 = [.1 .1 .9 .4];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
case 'ellipse'
c1 = [0.15 0.5];
c2 = [0.85 0.5];
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2);
M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) );
case 'ellipse-thin'
options.eccentricity = 1.06;
M = load_image('ellipse', n, options);
case 'ellipse-fat'
options.eccentricity = 1.3;
M = load_image('ellipse', n, options);
case 'square-tube'
c1 = [.25 .5];
c2 = [.75 .5];
r1 = [c1 c1] + .18*[-1 -1 1 1];
r2 = [c2 c2] + .18*[-1 -1 1 1];
r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) );
case 'square-tube-1'
options.tube_width = 0.03;
M = load_image('square-tube', n, options);
case 'square-tube-2'
options.tube_width = 0.06;
M = load_image('square-tube', n, options);
case 'square-tube-3'
options.im = 0.09;
M = load_image('square-tube', n, options);
case 'polygon'
theta = sort( rand(nb_points,1)*2*pi );
radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93);
points = [cos(theta) sin(theta)] .* repmat(radius, 1,2);
points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:);
M = draw_polygons(zeros(n),0.8,{points'});
[x,y] = ind2sub(size(M),find(M));
p = 100; m = length(x);
lambda = linspace(0,1,p);
X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]);
Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]);
I = round(X) + (round(Y)-1)*n;
M = zeros(n); M(I) = 1;
case 'polygon-8'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-10'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-12'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'pacman'
options.radius = 0.45;
options.center = [.5 .5];
M = load_image('disk', n, options);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
T =atan2(Y,X);
M = M .* (1-(abs(T-pi/2)<theta/2));
case 'square-hole'
options.radius = 0.45;
M = load_image('disk', n, options);
options.scaling = 0.5;
M = M - load_image('polygon-10', n, options);
case 'grid-circles'
if isempty(n)
n = 256;
end
f = getoptions(options, 'frequency', 30);
eta = getoptions(options, 'width', .3);
x = linspace(-n/2,n/2,n) - round(n*0.03);
y = linspace(0,n,n);
[Y,X] = meshgrid(y,x);
R = sqrt(X.^2+Y.^2);
theta = 0.05*pi/2;
X1 = cos(theta)*X+sin(theta)*Y;
Y1 = -sin(theta)*X+cos(theta)*Y;
A1 = abs(cos(2*pi*R/f))<eta;
A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta );
M = A1;
M(X1>0) = A2(X1>0);
case 'chessboard1'
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (2*(Y>=0)-1).*(2*(X>=0)-1);
case 'chessboard'
width = getoptions(width, round(n/16) );
[Y,X] = meshgrid(0:n-1,0:n-1);
M = mod( floor(X/width)+floor(Y/width), 2 ) == 0;
case 'square'
if ~isfield( options, 'radius' )
radius = 0.6;
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M = max( abs(X),abs(Y) )<radius;
case 'squareregular'
M = rescale(load_image('square',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'regular1'
options.alpha = 1;
M = load_image('fnoise',n,options);
case 'regular2'
options.alpha = 2;
M = load_image('fnoise',n,options);
case 'regular3'
options.alpha = 3;
M = load_image('fnoise',n,options);
case 'sparsecurves'
options.alpha = 3;
M = load_image('fnoise',n,options);
M = rescale(M);
ncurves = 3;
M = cos(2*pi*ncurves);
case 'geometrical'
J = getoptions(options, 'Jgeometrical', 4);
sgeom = 100*n/256;
options.bound = 'per';
A = ones(n);
for j=0:J-1
B = A;
for k=1:2^j
I = find(B==k);
U = perform_blurring(randn(n),sgeom,options);
s = median(U(I));
I1 = find( (B==k) & (U>s) );
I2 = find( (B==k) & (U<=s) );
A(I1) = 2*k-1;
A(I2) = 2*k;
end
end
M = A;
case 'lic-texture'
disp('Computing random tensor field.');
options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256);
T = compute_tensor_field_random(n,options);
Flow = perform_tensor_decomp(T); % extract eigenfield.
options.isoriented = 0; % no orientation in streamlines
% initial texture
lic_width = getoptions(options, 'lic_width', 0);
M0 = perform_blurring(randn(n),lic_width);
M0 = perform_histogram_equalization( M0, 'linear');
options.histogram = 'linear';
options.dt = 0.4;
options.M0 = M0;
options.verb = 1;
options.flow_correction = 1;
options.niter_lic = 3;
w = 30;
M = perform_lic(Flow, w, options);
case 'square_texture'
M = load_image('square',n);
M = rescale(M);
% make a texture patch
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta );
case 'tv-image'
M = rand(n);
tau = compute_total_variation(M);
options.niter = 400;
[M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options);
M = perform_histogram_equalization(M,'linear');
case 'oscillatory_texture'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M = sin( x * 2*pi / eta );
case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'}
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
if gamma~=Inf
M = (X-eta) - gamma*Y < 0;
else
M = (Y-eta) < 0;
end
case 'grating'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
theta = getoptions(options, 'theta', .2);
freq = getoptions(options, 'freq', .2);
X = cos(theta)*X + sin(theta)*Y;
M = sin(2*pi*X/freq);
case 'disk'
if ~isfield( options, 'radius' )
radius = 0.35;
end
if ~isfield( options, 'center' )
center = [0.5, 0.5]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'diskregular'
M = rescale(load_image('disk',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'quarterdisk'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'fading_contour'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
theta = 2/pi*atan2(Y,X);
h = 0.5;
M = exp(-(1-theta).^2/h^2).*M;
case '3contours'
radius = 1.3;
center = [-1, 1];
radius1 = 0.8;
center1 = [0, 0];
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2;
M = f1 + 0.5*f2.*(1-f1);
case 'line_circle'
gamma = 1/sqrt(2);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M1 = double( X>gamma*Y+0.25 );
M2 = X.^2 + Y.^2 < 0.6^2;
M = 20 + max(0.5*M1,M2) * 216;
case 'fnoise'
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
alpha = getoptions(options, 'alpha', 1);
M = gen_noisy_image(n,alpha);
case 'gaussiannoise'
% generate an image of filtered noise with gaussian
sigma = getoptions(options, 'sigma', 10);
M = randn(n);
m = 51;
h = compute_gaussian_filter([m m],sigma/(4*n),[n n]);
M = perform_convolution(M,h);
return;
case {'bwhorizontal','bwvertical','bwcircle'}
[Y,X] = meshgrid(0:n-1,0:n-1);
if strcmp(type, 'bwhorizontal')
d = X;
elseif strcmp(type, 'bwvertical')
d = Y;
elseif strcmp(type, 'bwcircle')
d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 );
end
if isfield(options, 'stripe_width')
stripe_width = options.stripe_width;
else
stripe_width = 5;
end
if isfield(options, 'black_prop')
black_prop = options.black_prop;
else
black_prop = 0.5;
end
M = double( mod( d/(2*stripe_width),1 )>=black_prop );
case 'parabola'
% curvature
c = getoptions(c, 'c', .1);
% angle
theta = getoptions(options, 'theta', pi/sqrt(2));
x = -0.5:1/(n-1):0.5;
[Y,X] = meshgrid(x,x);
Xs = X*cos(theta) + Y*sin(theta);
Y =-X*sin(theta) + Y*cos(theta); X = Xs;
M = Y>c*X.^2;
case 'sin'
[Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1);
M = Y >= 0.6*cos(pi*X);
M = double(M);
case 'circ_oscil'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
R = sqrt(X.^2+Y.^2);
M = cos(R.^3*50);
case 'phantom'
M = phantom(n);
case 'periodic_bumps'
nbr_periods = getoptions(options, 'nbr_periods', 8);
theta = getoptions(options, 'theta', 1/sqrt(2));
skew = getoptions(options, 'skew', 1/sqrt(2) );
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];
B = [1 skew; 0 1];
T = B*A;
x = (0:n-1)*2*pi*nbr_periods/(n-1);
[Y,X] = meshgrid(x,x);
pos = [X(:)'; Y(:)'];
pos = T*pos;
X = reshape(pos(1,:), n,n);
Y = reshape(pos(2,:), n,n);
M = cos(X).*sin(Y);
case 'noise'
sigma = getoptions(options, 'sigma', 1);
M = randn(n) * sigma;
otherwise
ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'};
for i=1:length(ext)
name = [type '.' ext{i}];
if( exist(name) )
M = imread( name );
M = double(M);
if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2
M = image_resize(M,n,n);
end
M = perform_blurring(M,sigma);
return;
end
end
error( ['Image ' type ' does not exists.'] );
end
M = double(M);
if sigma>0
M = perform_blurring(M,sigma);
end
M = rescale(M);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = create_letter(a, r, n)
c = 0.2;
p1 = [c;c];
p2 = [c; 1-c];
p3 = [1-c; 1-c];
p4 = [1-c; c];
p4 = [1-c; c];
pc = [0.5;0.5];
pu = [0.5; c];
switch a
case 'x'
point_list = { [p1 p3] [p2 p4] };
case 'z'
point_list = { [p2 p3 p1 p4] };
case 'v'
point_list = { [p2 pu p3] };
case 'y'
point_list = { [p2 pc pu] [pc p3] };
end
% fit image
for i=1:length(point_list)
a = point_list{i}(2:-1:1,:);
a(1,:) = 1-a(1,:);
point_list{i} = round( a*(n-1)+1 );
end
M = draw_polygons(zeros(n),r,point_list);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_polygons(mask,r,point_list)
sk = mask*0;
for i=1:length(point_list)
pl = point_list{i};
for k=2:length(pl)
sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_line(sk,x1,y1,x2,y2,r)
n = size(sk,1);
[Y,X] = meshgrid(1:n,1:n);
q = 100;
t = linspace(0,1,q);
x = x1*t+x2*(1-t); y = y1*t+y2*(1-t);
if r==0
x = round( x ); y = round( y );
sk( x+(y-1)*n ) = 1;
else
for k=1:q
I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 );
sk(I) = 1;
end
end
function M = gen_noisy_image(n,alpha)
% gen_noisy_image - generate a noisy cloud-like image.
%
% M = gen_noisy_image(n,alpha);
%
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin<1
n = 128;
end
if nargin<2
alpha = 1.5;
end
if mod(n(1),2)==0
x = -n/2:n/2-1;
else
x = -(n-1)/2:(n-1)/2;
end
[Y,X] = meshgrid(x,x);
d = sqrt(X.^2 + Y.^2) + 0.1;
f = rand(n)*2*pi;
M = (d.^(-alpha)) .* exp(f*1i);
% M = real(ifft2(fftshift(M)));
M = ifftshift(M);
M = real( ifft2(M) );
function y = gen_signal_2d(n,alpha)
% gen_signal_2d - generate a 2D C^\alpha signal of length n x n.
% gen_signal_2d(n,alpha) generate a 2D signal C^alpha.
%
% The signal is scale in [0,1].
%
% Copyright (c) 2003 Gabriel Peyr?
% new new method
[Y,X] = meshgrid(0:n-1, 0:n-1);
A = X+Y+1;
B = X-Y+n+1;
a = gen_signal(2*n+1, alpha);
b = gen_signal(2*n+1, alpha);
y = a(A).*b(B);
% M = a(1:n)*b(1:n)';
return;
% new method
h = (-n/2+1):(n/2); h(n/2)=1;
[X,Y] = meshgrid(h,h);
h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2);
h = h .* exp( 2i*pi*rand(n,n) );
h = fftshift(h);
y = real( ifft2(h) );
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
return;
%% old code
y = rand(n,n);
y = y - mean(mean(y));
for i=1:alpha
y = cumsum(cumsum(y)')';
y = y - mean(mean(y));
end
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
function newimg = image_resize(img,p1,q1,r1)
% image_resize - resize an image using bicubic interpolation
%
% newimg = image_resize(img,nx,ny,nz);
% or
% newimg = image_resize(img,newsize);
%
% Works for 2D, 2D 2 or 3 channels, 3D images.
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin==2
% size specified as an array
q1 = p1(2);
if length(p1)>2
r1 = p1(3);
else
r1 = size(img,3);
end
p1 = p1(1);
end
if nargin<4
r1 = size(img,3);
end
if ndims(img)<2 || ndims(img)>3
error('Works only for grayscale or color images');
end
if ndims(img)==3 && size(img,3)<4
% RVB image
newimg = zeros(p1,q1, size(img,3));
for m=1:size(img,3)
newimg(:,:,m) = image_resize(img(:,:,m), p1, q1);
end
return;
elseif ndims(img)==3
p = size(img,1);
q = size(img,2);
r = size(img,3);
[Y,X,Z] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1), (0:r-1)/(r-1) );
[YI,XI,ZI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1), (0:r1-1)/(r1-1) );
newimg = interp3( Y,X,Z, img, YI,XI,ZI ,'cubic');
return;
end
p = size(img,1);
q = size(img,2);
[Y,X] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1) );
[YI,XI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1) );
newimg = interp2( Y,X, img, YI,XI ,'cubic');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = draw_rectangle(r,n)
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
|
github
|
jacksky64/imageProcessing-master
|
compute_periodic_poisson.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_diffc/toolbox/compute_periodic_poisson.m
| 855 |
utf_8
|
52f67b893134bee2f5ec735f55733e1f
|
function G = compute_periodic_poisson(d, symmetrize)
% compute_periodic_poisson - solve poisson equation
%
% G = compute_periodic_poisson(d,symmetrize);
%
% Solve
% Delta(G) = d
% with periodic boundary condition.
% G has zero mean.
%
% Set symmetrize=1 (default 0) if the data divergence d is not periodic.
% This will double the size and consider symmetric extension.
%
% Copyright (c) 2007 Gabriel Peyre
n = size(d,1);
if nargin==2 && symmetrize
d = perform_size_doubling(d);
G = compute_periodic_poisson(d);
G = G(1:n,1:n);
return;
end
% solve for laplacian
[Y,X] = meshgrid(0:n-1,0:n-1);
mu = sin(X*pi/n).^2; mu = -4*( mu+mu' );
mu(1) = 1; % avoid division by 0
G = fft2(d) ./ mu; G(1) = 0;
G = real( ifft2( G ) );
%%
function g = perform_size_doubling(g)
g = [g;g(end:-1:1,:,:)];
g = [g,g(:,end:-1:1,:)];
|
github
|
jacksky64/imageProcessing-master
|
perform_windowed_fourier_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/perform_windowed_fourier_transform.m
| 5,038 |
utf_8
|
96c27071ef4e8304b6051ed54d7ad8b8
|
function y = perform_windowed_fourier_transform(x,w,q,n, options)
% perform_windowed_fourier_transform - compute a local Fourier transform
%
% Forward transform:
% MF = perform_windowed_fourier_transform(M,w,q,n, options);
% Backward transform:
% M = perform_windowed_fourier_transform(MF,w,q,n, options);
%
% w is the width of the window used to perform local computation.
% q is the spacing betwen each window.
%
% MF(:,:,,i,j) contains the spectrum around point ((i-1)*q,(j-1)*q)+1.
%
% A typical use, for an redundancy of 2x2 could be w=2*q+1
%
% options.bound can be either 'per' or 'sym'
%
% options.normalization can be set to
% 'tightframe': tight frame transform, with energy conservation.
% 'unit': unit norm basis vectors, usefull to do thresholding
%
% Copyright (c) 2006 Gabriel Peyre
options.null = 0;
if size(x,3)>1
dir = -1;
if nargin<4
% assume power of 2 size
n = q*size(x,3);
n = 2^floor(log2(n));
end
else
dir = 1;
n = size(x,1);
end
if isfield(options, 'bound')
bound = options.bound;
else
bound = 'sym';
bound = 'per';
end
if isfield(options, 'transform_type')
transform_type = options.transform_type;
else
transform_type = 'fourier';
end
if isfield(options, 'normalization')
normalization = options.normalization;
else
normalization = 'tightframe';
end
% perform sampling
t = 1:q:n+1;
[Y,X] = meshgrid(t,t);
p = size(X,1);
if mod(w,2)==1
% w = ceil((w-1)/2)*2+1;
w1 = (w-1)/2;
t = -w1:w1;
else
t = -w/2+1:w/2;
end
[dY,dX] = meshgrid(t,t);
X = reshape(X,[1 1 p p]);
Y = reshape(Y,[1 1 p p]);
X = repmat( X, [w w 1 1] );
Y = repmat( Y, [w w 1 1] );
dX = repmat( dX, [1 1 p p] );
dY = repmat( dY, [1 1 p p] );
X1 = X+dX;
Y1 = Y+dY;
switch lower(bound)
case 'sym'
X1(X1<1) = 1-X1(X1<1);
X1(X1>n) = 2*n+1-X1(X1>n);
Y1(Y1<1) = 1-Y1(Y1<1);
Y1(Y1>n) = 2*n+1-Y1(Y1>n);
case 'per'
X1 = mod(X1-1,n)+1;
Y1 = mod(Y1-1,n)+1;
end
% build a weight function
if isfield(options, 'window_type')
window_type = options.window_type;
else
window_type = 'sin';
end
if isfield(options, 'eta')
eta = options.eta;
else
eta = 1;
end
if strcmp(window_type, 'sin')
t = linspace(0,1,w);
W = sin(t(:)*pi).^2;
W = W * W';
elseif strcmp(window_type, 'constant')
W = ones(w);
else
error('Unkwnown winow.');
end
I = X1 + (Y1-1)*n;
%% renormalize the windows
weight = zeros(n);
for i=1:p
for j=1:p
weight(I(:,:,i,j)) = weight(I(:,:,i,j)) + W.^2;
end
end
weight = sqrt(weight);
Weight = repmat(W, [1 1 p p]);
for i=1:p
for j=1:p
Weight(:,:,i,j) = Weight(:,:,i,j) ./ weight(I(:,:,i,j));
end
end
if strcmp(normalization, 'unit')
if strcmp(transform_type, 'fourier')
% for Fourier it is easy
Renorm = sqrt( sum( sum( Weight.^2, 1 ), 2 ) )/w;
else
% for DCT it is less easy ...
% take a typical window in the middle of the image
weight = Weight(:,:,round(end/2),round(end/2));
% compute diracs
[X,Y,fX,fY] = ndgrid(0:w-1,0:w-1,0:w-1,0:w-1);
A = 2 * cos( pi/w * ( X+1/2 ).*fX ) .* cos( pi/w * ( Y+1/2 ).*fY ) / w;
A(:,:,1,:) = A(:,:,1,:) / sqrt(2); % scale zero frequency
A(:,:,:,1) = A(:,:,:,1) / sqrt(2);
A = A .* repmat( weight, [1 1 w w] );
Renorm = sqrt( sum( sum( abs(A).^2, 1 ),2 ) );
end
Renorm = reshape( Renorm, w,w );
end
%% compute the transform
if dir==1
y = zeros(eta*w,eta*w,p,p);
if mod(w,2)==1
m = (eta*w+1)/2; w1 = (w-1)/2;
sel = m-w1:m+w1;
else
m = (eta*w)/2+1; w1 = w/2;
sel = m-w1:m+w1-1;
end
y(sel,sel,:,:) = x(I) .* Weight;
% perform the transform
y = my_transform( y, +1, transform_type );
% renormalize if necessary
if strcmp(normalization, 'unit')
y = y ./ repmat( Renorm, [1 1 p p] );
end
else
if strcmp(normalization, 'unit')
x = x .* repmat( Renorm, [1 1 p p] );
end
x = my_transform( x, -1, transform_type );
x = real( x.*Weight );
y = zeros(n);
for i=1:p
for j=1:p
y(I(:,:,i,j)) = y(I(:,:,i,j)) + x(:,:,i,j);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = my_transform(x,dir,transform_type)
% my_transform - perform either FFT or DCT with energy conservation.
% Works on array of size (w,w,a,b) on the 2 first dimensions.
w = size(x,1);
if strcmp(transform_type, 'fourier')
% normalize for energy conservation
if dir==1
y = fftshift( fft2(x) ) / w;
else
y = ifft2( ifftshift(x*w) );
end
elseif strcmp(transform_type, 'dct')
for i=1:size(x,3)
for j=1:size(x,4)
y(:,:,i,j) = perform_dct_transform(x(:,:,i,j),dir);
end
end
else
error('Unknown transform');
end
|
github
|
jacksky64/imageProcessing-master
|
load_hdr.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/load_hdr.m
| 4,928 |
utf_8
|
cdf17b3681f4c6902ed0f7de2ad31f7d
|
function [img, fileinfo] = read_hdr(filename)
% load_hdr - loading a radiance RBGE file.
%
% [img, fileinfo] = read_rle_rgbe(filename);
%
% Written by Lawrence A. Taplin ([email protected])
%
% Based loosely on the c-code RGBE implementation written by Bruce Walters
% http://www.graphics.cornell.edu/~bjw/rgbe.html
%
% function to read a run length encoded RGBE picture file and header. This does
% not work if the image is not RLE!!!
do_rescale = 0;
% check if the image is in classical image (eg. TIFF) format
if ~strcmp(filename(end-2:end), 'hdr')
img = double(imread(filename));
if do_rescale
img = rescale(img);
end
fileinfo = [];
return;
end
tic
%open the file
fid = fopen(filename,'r');
if fid<0
error(['File not found:' filename '.']);
end
%read the magic number
tline = fgetl(fid);
if length(tline)<3 | tline(1:2) ~= '#?'
error('invalid header');
end
fileinfo.identifier = tline(3:end);
%read the header variables into a structure
tline = fgetl(fid);
while ~isempty(tline)
%find and set the variable name
n = strfind(tline,'=');
if ~isempty(n) % skip stuff I don't understand
vname = lower(tline(1:n(1)-1));
vval = tline(n+1:end);
fileinfo = setfield(fileinfo,vname,tline(n+1:end));
fprintf('Variable = %s, Value = %s\n',vname, vval);
end
%read the next line
tline = fgetl(fid);
end
%set the resolution variables
tline = fgetl(fid);
fileinfo.Ysign = tline(1);
[fileinfo.height,count,errmsg,nextindex] = sscanf(tline(4:end),'%d',1);
fileinfo.Xsign = tline(nextindex+4);
[fileinfo.width,count,errmsg,nextindex] = sscanf(tline(nextindex+7:end),'%d',1);
fprintf('resolution: %s\n',tline);
%allocate space for the scan line data
img = zeros(fileinfo.height, fileinfo.width, 3);
%read the scanline data
if fileinfo.format == '32-bit_rle_rgbe';
fprintf('Decoding RLE Data stream\n');
end
%read the remaining data
[data, count] = fread(fid,inf,'uint8');
fclose(fid);
scanline_width = fileinfo.width;
num_scanlines = fileinfo.height;
if ((scanline_width < 8)|(scanline_width > 32767))
% run length encoding is not allowed so read flat
img = rgbe2float(reshape(data,fileinfo.width,fileinfo.height,4));
return;
end
scanline_buffer = repmat(uint8(0),scanline_width,4);
dp = 1; %set the data pointer to the begining of the read data
% read in each successive scanline */
for scanline=1:num_scanlines
% if mod(scanline,fix(num_scanlines/100))==0
% fprintf('scanline = %d\n',scanline);
% end
%
if (data(dp) ~= 2) | (data(dp+1) ~= 2)% | (bitget(data(dp+2),8)~=1)
error('this file is not run length encoded');
end
if (bitshift(data(dp+2),8)+data(dp+3))~=scanline_width % -128
error('wrong scanline width');
end
dp = dp+4;
% read each of the four channels read the scanline into the buffer
for i=1:4
ptr = 1;
while(ptr <= scanline_width)
if (data(dp) > 128) % a run of the same value
count = data(dp)-128;
if ((count == 0)|(count-1 > scanline_width - ptr))
warning('bad scanline data');
end
scanline_buffer(ptr:ptr+count-1,i) = data(dp+1);
dp = dp+2;
ptr = ptr+count;
else % a non-run
count = data(dp);
dp = dp+1;
if ((count == 0)|(count-1 > scanline_width - ptr))
warning('bad scanline data');
end
scanline_buffer(ptr:ptr+count-1,i) = data(dp:dp+count-1);
ptr = ptr+count;
dp = dp+count;
end
end
end
% now convert data from buffer into floats
img(scanline,:,:) = rgbe2float(scanline_buffer);
end
toc
% rescale to 0-1
if do_rescale
a = min(img(:));
b = max(img(:));
img = (img-a)/(b-a);
end
% standard conversion from float pixels to rgbe pixels
% the last dimension is assumed to be color
function [rgbe] = float2rgbe(rgb)
s = size(rgb);
rgb = reshape(rgb,prod(s)/3,3);
rgbe = reshape(repmat(uint8(0),[s(1:end-1),4]),prod(s)/3,4);
v = max(rgb,[],2); %find max rgb
l = find(v>1e-32); %find non zero pixel list
rgbe(l,4) = uint8(round(128.5+log(v)/log(2))); %find E
rgbe(l,1:3) = uint8(rgb(l,1:3)./repmat(2.^(double(rgbe(l,4))-128-8),1,3)); %find rgb multiplier
reshape(rgbe,[s(1:end-1),4]); %reshape back to original dimensions
% standard conversion from rgbe to float pixels */
% note: Ward uses ldexp(col+0.5,exp-(128+8)). However we wanted pixels */
% in the range [0,1] to map back into the range [0,1]. */
function [rgb] = rgbe2float(rgbe)
s = size(rgbe);
rgbe = reshape(rgbe,prod(s)/4,4);
rgb = zeros(prod(s)/4,3);
l = find(rgbe(:,4)>0); %nonzero pixel list
rgb(l,:) = double(rgbe(l,1:3)).*repmat(2.^(double(rgbe(l,4))-128-8),1,3);
rgb = reshape(rgb,[s(1:end-1),3]);
|
github
|
jacksky64/imageProcessing-master
|
load_image.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/load_image.m
| 21,410 |
utf_8
|
a83de39372a6892ac46820c6bea2e094
|
function M = load_image(type, n, options)
% load_image - load benchmark images.
%
% M = load_image(name, n, options);
%
% name can be:
% Synthetic images:
% 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line',
% 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle',
% 'parabola', 'sin', 'phantom', 'circ_oscil',
% 'fnoise' (1/f^alpha noise).
% Natural images:
% 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
n = 512;
end
options.null = 0;
if iscell(type)
for i=1:length(type)
M{i} = load_image(type{i},n,options);
end
return;
end
type = lower(type);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters for geometric objects
eta = getoptions(options, 'eta', .1);
gamma = getoptions(options, 'gamma', 1/sqrt(2));
radius = getoptions(options, 'radius', 10);
center = getoptions(options, 'center', [0 0]);
center1 = getoptions(options, 'center1', [0 0]);
w = getoptions(options, 'tube_width', 0.06);
nb_points = getoptions(options, 'nb_points', 9);
scaling = getoptions(options, 'scaling', 1);
theta = getoptions(options, 'theta', 30 * 2*pi/360);
eccentricity = getoptions(options, 'eccentricity', 1.3);
sigma = getoptions(options, 'sigma', 0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the line, can be vertical / horizontal / diagonal / any
if strcmp(type, 'line_vertical')
eta = 0.5; % translation
gamma = 0; % slope
elseif strcmp(type, 'line_horizontal')
eta = 0.5; % translation
gamma = Inf; % slope
elseif strcmp(type, 'line_diagonal')
eta = 0; % translation
gamma = 1; % slope
end
if strcmp(type(1:min(12,end)), 'square-tube-')
k = str2double(type(13:end));
c1 = [.22 .5]; c2 = [1-c1(1) .5];
eta = 1.5;
r1 = [c1 c1] + .21*[-1 -eta 1 eta];
r2 = [c2 c2] + .21*[-1 -eta 1 eta];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
if mod(k,2)==0
sel = n/2-k/2+1:n/2+k/2;
else
sel = n/2-(k-1)/2:n/2+(k-1)/2;
end
M( round(.25*n:.75*n), sel ) = 1;
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(type)
case 'constant'
M = ones(n);
case 'ramp'
x = linspace(0,1,n);
[Y,M] = meshgrid(x,x);
case 'bump'
s = getoptions(options, 'bump_size', .5);
c = getoptions(options, 'center', [0 0]);
if length(s)==1
s = [s s];
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
X = (X-c(1))/s(1); Y = (Y-c(2))/s(2);
M = exp( -(X.^2+Y.^2)/2 );
case 'periodic'
x = linspace(-pi,pi,n)/1.1;
[Y,X] = meshgrid(x,x);
f = getoptions(options, 'freq', 6);
M = (1+cos(f*X)).*(1+cos(f*Y));
case {'letter-x' 'letter-v' 'letter-z' 'letter-y'}
M = create_letter(type(8), radius, n);
case 'l'
r1 = [.1 .1 .3 .9];
r2 = [.1 .1 .9 .4];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
case 'ellipse'
c1 = [0.15 0.5];
c2 = [0.85 0.5];
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2);
M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) );
case 'ellipse-thin'
options.eccentricity = 1.06;
M = load_image('ellipse', n, options);
case 'ellipse-fat'
options.eccentricity = 1.3;
M = load_image('ellipse', n, options);
case 'square-tube'
c1 = [.25 .5];
c2 = [.75 .5];
r1 = [c1 c1] + .18*[-1 -1 1 1];
r2 = [c2 c2] + .18*[-1 -1 1 1];
r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) );
case 'square-tube-1'
options.tube_width = 0.03;
M = load_image('square-tube', n, options);
case 'square-tube-2'
options.tube_width = 0.06;
M = load_image('square-tube', n, options);
case 'square-tube-3'
options.im = 0.09;
M = load_image('square-tube', n, options);
case 'polygon'
theta = sort( rand(nb_points,1)*2*pi );
radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93);
points = [cos(theta) sin(theta)] .* repmat(radius, 1,2);
points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:);
M = draw_polygons(zeros(n),0.8,{points'});
[x,y] = ind2sub(size(M),find(M));
p = 100; m = length(x);
lambda = linspace(0,1,p);
X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]);
Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]);
I = round(X) + (round(Y)-1)*n;
M = zeros(n); M(I) = 1;
case 'polygon-8'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-10'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-12'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'pacman'
options.radius = 0.45;
options.center = [.5 .5];
M = load_image('disk', n, options);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
T =atan2(Y,X);
M = M .* (1-(abs(T-pi/2)<theta/2));
case 'square-hole'
options.radius = 0.45;
M = load_image('disk', n, options);
options.scaling = 0.5;
M = M - load_image('polygon-10', n, options);
case 'grid-circles'
if isempty(n)
n = 256;
end
f = getoptions(options, 'frequency', 30);
eta = getoptions(options, 'width', .3);
x = linspace(-n/2,n/2,n) - round(n*0.03);
y = linspace(0,n,n);
[Y,X] = meshgrid(y,x);
R = sqrt(X.^2+Y.^2);
theta = 0.05*pi/2;
X1 = cos(theta)*X+sin(theta)*Y;
Y1 = -sin(theta)*X+cos(theta)*Y;
A1 = abs(cos(2*pi*R/f))<eta;
A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta );
M = A1;
M(X1>0) = A2(X1>0);
case 'chessboard1'
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (2*(Y>=0)-1).*(2*(X>=0)-1);
case 'chessboard'
width = getoptions(options, 'width', round(n/16) );
[Y,X] = meshgrid(0:n-1,0:n-1);
M = mod( floor(X/width)+floor(Y/width), 2 ) == 0;
case 'square'
if ~isfield( options, 'radius' )
radius = 0.6;
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M = max( abs(X),abs(Y) )<radius;
case 'squareregular'
M = rescale(load_image('square',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'regular1'
options.alpha = 1;
M = load_image('fnoise',n,options);
case 'regular2'
options.alpha = 2;
M = load_image('fnoise',n,options);
case 'regular3'
options.alpha = 3;
M = load_image('fnoise',n,options);
case 'sparsecurves'
options.alpha = 3;
M = load_image('fnoise',n,options);
M = rescale(M);
ncurves = 3;
M = cos(2*pi*ncurves);
case 'geometrical'
J = getoptions(options, 'Jgeometrical', 4);
sgeom = 100*n/256;
options.bound = 'per';
A = ones(n);
for j=0:J-1
B = A;
for k=1:2^j
I = find(B==k);
U = perform_blurring(randn(n),sgeom,options);
s = median(U(I));
I1 = find( (B==k) & (U>s) );
I2 = find( (B==k) & (U<=s) );
A(I1) = 2*k-1;
A(I2) = 2*k;
end
end
M = A;
case 'lic-texture'
disp('Computing random tensor field.');
options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256);
T = compute_tensor_field_random(n,options);
Flow = perform_tensor_decomp(T); % extract eigenfield.
options.isoriented = 0; % no orientation in streamlines
% initial texture
lic_width = getoptions(options, 'lic_width', 0);
M0 = perform_blurring(randn(n),lic_width);
M0 = perform_histogram_equalization( M0, 'linear');
options.histogram = 'linear';
options.dt = 0.4;
options.M0 = M0;
options.verb = 1;
options.flow_correction = 1;
options.niter_lic = 3;
w = 30;
M = perform_lic(Flow, w, options);
case 'square_texture'
M = load_image('square',n);
M = rescale(M);
% make a texture patch
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta );
case 'tv-image'
M = rand(n);
tau = compute_total_variation(M);
options.niter = 400;
[M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options);
M = perform_histogram_equalization(M,'linear');
case 'oscillatory_texture'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M = sin( x * 2*pi / eta );
case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'}
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
if gamma~=Inf
M = (X-eta) - gamma*Y < 0;
else
M = (Y-eta) < 0;
end
case 'line-windowed'
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
eta = .3;
gamma = getoptions(options, 'gamma', pi/10);
parabola = getoptions(options, 'parabola', 0);
M = (X-eta) - gamma*Y - parabola*Y.^2 < 0;
f = sin( pi*x ).^2;
M = M .* ( f'*f );
case 'grating'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
theta = getoptions(options, 'theta', .2);
freq = getoptions(options, 'freq', .2);
X = cos(theta)*X + sin(theta)*Y;
M = sin(2*pi*X/freq);
case 'disk'
if ~isfield( options, 'radius' )
radius = 0.35;
end
if ~isfield( options, 'center' )
center = [0.5, 0.5]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'diskregular'
M = rescale(load_image('disk',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'quarterdisk'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'fading_contour'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
theta = 2/pi*atan2(Y,X);
h = 0.5;
M = exp(-(1-theta).^2/h^2).*M;
case '3contours'
radius = 1.3;
center = [-1, 1];
radius1 = 0.8;
center1 = [0, 0];
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2;
M = f1 + 0.5*f2.*(1-f1);
case 'line_circle'
gamma = 1/sqrt(2);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M1 = double( X>gamma*Y+0.25 );
M2 = X.^2 + Y.^2 < 0.6^2;
M = 20 + max(0.5*M1,M2) * 216;
case 'fnoise'
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
alpha = getoptions(options, 'alpha', 1);
M = gen_noisy_image(n,alpha);
case 'gaussiannoise'
% generate an image of filtered noise with gaussian
sigma = getoptions(options, 'sigma', 10);
M = randn(n);
m = 51;
h = compute_gaussian_filter([m m],sigma/(4*n),[n n]);
M = perform_convolution(M,h);
return;
case {'bwhorizontal','bwvertical','bwcircle'}
[Y,X] = meshgrid(0:n-1,0:n-1);
if strcmp(type, 'bwhorizontal')
d = X;
elseif strcmp(type, 'bwvertical')
d = Y;
elseif strcmp(type, 'bwcircle')
d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 );
end
if isfield(options, 'stripe_width')
stripe_width = options.stripe_width;
else
stripe_width = 5;
end
if isfield(options, 'black_prop')
black_prop = options.black_prop;
else
black_prop = 0.5;
end
M = double( mod( d/(2*stripe_width),1 )>=black_prop );
case 'parabola'
% curvature
c = getoptions(c, 'c', .1);
% angle
theta = getoptions(options, 'theta', pi/sqrt(2));
x = -0.5:1/(n-1):0.5;
[Y,X] = meshgrid(x,x);
Xs = X*cos(theta) + Y*sin(theta);
Y =-X*sin(theta) + Y*cos(theta); X = Xs;
M = Y>c*X.^2;
case 'sin'
[Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1);
M = Y >= 0.6*cos(pi*X);
M = double(M);
case 'circ_oscil'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
R = sqrt(X.^2+Y.^2);
M = cos(R.^3*50);
case 'phantom'
M = phantom(n);
case 'periodic_bumps'
nbr_periods = getoptions(options, 'nbr_periods', 8);
theta = getoptions(options, 'theta', 1/sqrt(2));
skew = getoptions(options, 'skew', 1/sqrt(2) );
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];
B = [1 skew; 0 1];
T = B*A;
x = (0:n-1)*2*pi*nbr_periods/(n-1);
[Y,X] = meshgrid(x,x);
pos = [X(:)'; Y(:)'];
pos = T*pos;
X = reshape(pos(1,:), n,n);
Y = reshape(pos(2,:), n,n);
M = cos(X).*sin(Y);
case 'noise'
sigma = getoptions(options, 'sigma', 1);
M = randn(n) * sigma;
case 'disk-corner'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
rho = .3; eta = .1;
M1 = rho*X+eta<Y;
c = [0 .2]; r = .85;
d = (X-c(1)).^2 + (Y-c(2)).^2;
M2 = d<r^2;
M = M1.*M2;
otherwise
ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'tif', 'pgm', 'ppm'};
for i=1:length(ext)
name = [type '.' ext{i}];
if( exist(name) )
M = imread( name );
M = double(M);
if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2
M = image_resize(M,n,n);
end
if strcmp(type, 'peppers-bw')
M(:,1) = M(:,2);
M(1,:) = M(2,:);
end
if sigma>0
M = perform_blurring(M,sigma);
end
return;
end
end
error( ['Image ' type ' does not exists.'] );
end
M = double(M);
if sigma>0
M = perform_blurring(M,sigma);
end
M = rescale(M);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = create_letter(a, r, n)
c = 0.2;
p1 = [c;c];
p2 = [c; 1-c];
p3 = [1-c; 1-c];
p4 = [1-c; c];
p4 = [1-c; c];
pc = [0.5;0.5];
pu = [0.5; c];
switch a
case 'x'
point_list = { [p1 p3] [p2 p4] };
case 'z'
point_list = { [p2 p3 p1 p4] };
case 'v'
point_list = { [p2 pu p3] };
case 'y'
point_list = { [p2 pc pu] [pc p3] };
end
% fit image
for i=1:length(point_list)
a = point_list{i}(2:-1:1,:);
a(1,:) = 1-a(1,:);
point_list{i} = round( a*(n-1)+1 );
end
M = draw_polygons(zeros(n),r,point_list);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_polygons(mask,r,point_list)
sk = mask*0;
for i=1:length(point_list)
pl = point_list{i};
for k=2:length(pl)
sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_line(sk,x1,y1,x2,y2,r)
n = size(sk,1);
[Y,X] = meshgrid(1:n,1:n);
q = 100;
t = linspace(0,1,q);
x = x1*t+x2*(1-t); y = y1*t+y2*(1-t);
if r==0
x = round( x ); y = round( y );
sk( x+(y-1)*n ) = 1;
else
for k=1:q
I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 );
sk(I) = 1;
end
end
function M = gen_noisy_image(n,alpha)
% gen_noisy_image - generate a noisy cloud-like image.
%
% M = gen_noisy_image(n,alpha);
%
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin<1
n = 128;
end
if nargin<2
alpha = 1.5;
end
if mod(n(1),2)==0
x = -n/2:n/2-1;
else
x = -(n-1)/2:(n-1)/2;
end
[Y,X] = meshgrid(x,x);
d = sqrt(X.^2 + Y.^2) + 0.1;
f = rand(n)*2*pi;
M = (d.^(-alpha)) .* exp(f*1i);
% M = real(ifft2(fftshift(M)));
M = ifftshift(M);
M = real( ifft2(M) );
function y = gen_signal_2d(n,alpha)
% gen_signal_2d - generate a 2D C^\alpha signal of length n x n.
% gen_signal_2d(n,alpha) generate a 2D signal C^alpha.
%
% The signal is scale in [0,1].
%
% Copyright (c) 2003 Gabriel Peyr?
% new new method
[Y,X] = meshgrid(0:n-1, 0:n-1);
A = X+Y+1;
B = X-Y+n+1;
a = gen_signal(2*n+1, alpha);
b = gen_signal(2*n+1, alpha);
y = a(A).*b(B);
% M = a(1:n)*b(1:n)';
return;
% new method
h = (-n/2+1):(n/2); h(n/2)=1;
[X,Y] = meshgrid(h,h);
h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2);
h = h .* exp( 2i*pi*rand(n,n) );
h = fftshift(h);
y = real( ifft2(h) );
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
return;
%% old code
y = rand(n,n);
y = y - mean(mean(y));
for i=1:alpha
y = cumsum(cumsum(y)')';
y = y - mean(mean(y));
end
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
function newimg = image_resize(img,p1,q1,r1)
% image_resize - resize an image using bicubic interpolation
%
% newimg = image_resize(img,nx,ny,nz);
% or
% newimg = image_resize(img,newsize);
%
% Works for 2D, 2D 2 or 3 channels, 3D images.
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin==2
% size specified as an array
q1 = p1(2);
if length(p1)>2
r1 = p1(3);
else
r1 = size(img,3);
end
p1 = p1(1);
end
if nargin<4
r1 = size(img,3);
end
if ndims(img)<2 || ndims(img)>3
error('Works only for grayscale or color images');
end
if ndims(img)==3 && size(img,3)<4
% RVB image
newimg = zeros(p1,q1, size(img,3));
for m=1:size(img,3)
newimg(:,:,m) = image_resize(img(:,:,m), p1, q1);
end
return;
elseif ndims(img)==3
p = size(img,1);
q = size(img,2);
r = size(img,3);
[Y,X,Z] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1), (0:r-1)/(r-1) );
[YI,XI,ZI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1), (0:r1-1)/(r1-1) );
newimg = interp3( Y,X,Z, img, YI,XI,ZI ,'cubic');
return;
end
p = size(img,1);
q = size(img,2);
[Y,X] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1) );
[YI,XI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1) );
newimg = interp2( Y,X, img, YI,XI ,'cubic');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = draw_rectangle(r,n)
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
|
github
|
jacksky64/imageProcessing-master
|
grab_inpainting_mask.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/grab_inpainting_mask.m
| 3,717 |
utf_8
|
c160d95ddbbe80a15f290993fd6bac1a
|
function [U,point_list] = grab_inpainting_mask(M, options)
% grab_inpainting_mask - create a mask from user input
%
% U = grab_inpainting_mask(M, options);
%
% Select set of point in an image (useful to select a region for
% inpainting). The set of point is U==Inf.
%
% options.r is the radius for selection (default r=5).
%
% Selection stops with right click.
%
% Set options.mode='points' to gather disconnected points.
% Set options.mode='line' to gather connected lines.
%
% Copyright (c) 2006 Gabriel Peyre
if nargin==3 && method==1
U = grab_inpainting_mask_old(M, options);
return;
end
options.null = 0;
r = getoptions(options, 'r', 5);
method = getoptions(options, 'mode', 'points');
if strcmp(method, 'line')
if not(isfield(options, 'point_list'))
[V,point_list] = pick_polygons(rescale(sum(M,3)),r);
else
point_list = options.point_list;
V = draw_polygons(rescale(sum(M,3)),r,point_list);
end
U = M; U(V==1) = Inf;
return;
end
m = size(M,1);
n = size(M,2);
s = size(M,3);
U = sum(M,3)/3;
b = 1;
[Y,X] = meshgrid(1:n,1:m);
point_list = [];
while b==1
clf;
hold on;
imagesc(rescale(M));
axis image; axis off; colormap gray(256);
[y,x,b] = ginput(1);
point_list(:,end+1) = [x;y];
I = find((X-x).^2 + (Y-y).^2 <= r^2 );
U(I) = Inf;
for k=1:s
Ma = M(:,:,k);
Ma(I) = 0;
M(:,:,k) = Ma;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_polygons(mask,r,point_list)
sk = mask*0;
for i=1:length(point_list)
pl = point_list{i};
for k=2:length(pl)
sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r);
end
end
function [sk,point_list] = pick_polygons(mask,r)
% pick_polygons - ask for the user to build a set of curves
%
% sk = pick_polygons(mask,r);
%
% mask is a background image (should be in [0,1] approx).
%
% The user right-click on a set of point which create a curve.
% Left click stop a curve.
% Another left click stop the process.
%
% Copyright (c) 2007 Gabriel Peyre
n = size(mask,1);
sk = zeros(n);
point_list = {};
b = 1;
while b(end)==1
% draw a line
clf;
imagesc(mask+sk); axis image; axis off;
colormap gray(256);
[y1,x1,b] = ginput(1);
pl = [x1;y1];
while b==1
clf;
imagesc(mask+sk); axis image; axis off;
[y2,x2,c] = ginput(1);
if c~=1
if length(pl)>1
point_list{end+1} = pl;
end
break;
end
pl(:,end+1) = [x2;y2];
sk = draw_line(sk,x1,y1,x2,y2,r);
x1 = x2; y1 = y2;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_line(sk,x1,y1,x2,y2,r)
n = size(sk,1);
[Y,X] = meshgrid(1:n,1:n);
q = 80;
t = linspace(0,1,q);
x = x1*t+x2*(1-t); y = y1*t+y2*(1-t);
if r==0
x = round( x ); y = round( y );
sk( x+(y-1)*n ) = 1;
else
for k=1:q
I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 );
sk(I) = 1;
end
end
function U = grab_inpainting_mask_old(M, r)
% grab_inpainting_mask - create a mask from user input
%
% U = grab_inpainting_mask(M, r);
%
% r is the radius for selection (default r=5).
%
% Selection stops with right click.
%
% Copyright (c) 2006 Gabriel Peyr?
if nargin<2
r = 5;
end
m = size(M,1);
n = size(M,2);
s = size(M,3);
U = sum(M,3)/3;
b = 1;
[Y,X] = meshgrid(1:n,1:m);
while b==1
clf;
hold on;
imagesc(rescale(M));
axis image; axis off; colormap gray(256);
[y,x,b] = ginput(1);
I = find((X-x).^2 + (Y-y).^2 <= r^2 );
U(I) = Inf;
for k=1:s
Ma = M(:,:,k);
Ma(I) = 0;
M(:,:,k) = Ma;
end
end
|
github
|
jacksky64/imageProcessing-master
|
change_color_mode.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/change_color_mode.m
| 7,483 |
utf_8
|
184fcadc594ac09e3b2a2086820890bb
|
function [M,ColorP] = change_color_mode(M,dir,options)
% change_color_mode - change of color representation
%
% M = change_color_mode(M,dir,options);
%
% switch between RGB and another color mode.
%
% options.color_mode can be:
% 'rgb' (no change), 'hsv', 'ycbcr', 'pca'
%
% For PCA you should proceed like this:
% [Mg,options.ColorP] = change_color_mode(M0,+1,options);
% M1 = change_color_mode(Mg,-1,options);
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
color_mode = getoptions(options, 'color_mode', 'hsv');
if strcmp(color_mode,'rgb')
return;
end
n = size(M,1);
if size(M,3)~=3
error('Works only for color images');
end
if strcmp(color_mode, 'pca')
nsamples = min(8000,n^2);
if not(isfield(options, 'ColorP'))
if dir==-1
error('You must provide options.ColorP');
end
if nargout==1
error('Output argument ColorP Missing');
end
% compute PCA components
Ma = reshape(M,n^2,3);
sel = randperm(n^2); sel = sel(1:nsamples);
[Y,X1,v,Psi] = pca( Ma(sel,:)',3);
ColorP = cat(2, Y, Psi(:));
else
ColorP = options.ColorP;
end
if dir==1
M = reshape(M,n^2,3)';
M = ColorP(:,1:3)'*(M - repmat(ColorP(:,4), 1,n^2));
M = reshape(M',n,n,3);
else
M = reshape(M,n^2,3)';
M = ColorP(:,1:3)*M + repmat(ColorP(:,4), 1,n^2);
M = reshape(M',n,n,3);
end
return;
end
warning off;
if dir==1
M = feval( ['rgb2' color_mode], M);
end
if strcmp(color_mode, 'hsv')
M = M(:,:,3:-1:1);
end
if dir==-1
M = feval( [color_mode '2rgb'], M);
end
warning on;
function out = rgb2ycbcr(in)
%RGB2YCBCR Convert RGB values to YCBCR color space.
% YCBCRMAP = RGB2YCBCR(MAP) converts the RGB values in MAP to
% the YCBCR color space. YCBCRMAP is a M-by-3 matrix that contains
% the YCBCR luminance (Y) and chrominance (Cb and Cr) color values as
% columns. Each row represents the equivalent color to the
% corresponding row in the RGB colormap.
%
% YCBCR = RGB2YCBCR(RGB) converts the truecolor image RGB to the
% equivalent image in the YCBCR color space.
%
% Class Support
% -------------
% If the input is an RGB image, it can be of class uint8, uint16,
% or double; the output image is of the same class as the input
% image. If the input is a colormap, the input and output colormaps
% are both of class double.
%
% Examples
% --------
% Convert RGB image to YCbCr.
%
% RGB = imread('board.tif');
% YCBCR = rgb2ycbcr(RGB);
%
% Convert RGB color space to YCbCr.
%
% map = jet(256);
% newmap = rgb2ycbcr(map);
% See also NTSC2RGB, RGB2NTSC, YCBCR2RGB.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 1.13.4.2 $ $Date: 2003/08/23 05:54:37 $
% Reference:
% C.A. Poynton, "A Technical Introduction to Digital Video", John Wiley
% & Sons, Inc., 1996, p. 175
%initialize variables
isColormap = false;
classin = class(in);
%must reshape colormap to be m x n x 3 for transformation
if (ndims(in)==2)
%colormap
isColormap=true;
colors = size(in,1);
in = reshape(in, [colors 1 3]);
end
% set up constants for transformation
T = [65.481 128.553 24.966;...
-37.797 -74.203 112; ...
112 -93.786 -18.214];
offset = [16;128;128];
offset16 = 257 * offset;
fac8 = 1/255;
fac16 = 257/65535;
%initialize output
out = in;
% do transformation
switch classin
case 'uint8'
for p=1:3
out(:,:,p) = imlincomb(T(p,1)*fac8,in(:,:,1),T(p,2)*fac8,in(:,:,2),...
T(p,3)*fac8,in(:,:,3),offset(p));
end
case 'uint16'
for p=1:3
out(:,:,p) = imlincomb(T(p,1)*fac16,in(:,:,1),T(p,2)*fac16,in(:,:,2),...
T(p,3)*fac16,in(:,:,3),offset16(p));
end
case 'double'
% These equations transform RGB in [0,1] to YCBCR in [0, 255]
for p=1:3
out(:,:,p) = T(p,1) * in(:,:,1) + T(p,2) * in(:,:,2) + T(p,3) * ...
in(:,:,3) + offset(p);
end
out = out / 255;
end
if isColormap
out = reshape(out, [colors 3 1]);
end
function rgb = ycbcr2rgb(in)
%YCBCR2RGB Convert YCbCr values to RGB color space.
% RGBMAP = YCBCR2RGB(YCBCRMAP) converts the YCbCr values in the
% colormap YCBCRMAP to the RGB color space. If YCBCRMAP is M-by-3 and
% contains the YCbCr luminance (Y) and chrominance (Cb and Cr) color
% values as columns, then RGBMAP is an M-by-3 matrix that contains
% the red, green, and blue values equivalent to those colors.
%
% RGB = YCBCR2RGB(YCBCR) converts the YCbCr image to the equivalent
% truecolor image RGB.
%
% Class Support
% -------------
% If the input is a YCbCr image, it can be of class uint8, uint16,
% or double; the output image is of the same class as the input
% image. If the input is a colormap, the input and output
% colormaps are both of class double.
%
% Example
% -------
% Convert image from RGB space to YCbCr space and back.
%
% rgb = imread('board.tif');
% ycbcr = rgb2ycbcr(rgb);
% rgb2 = ycbcr2rgb(ycbcr);
%
% See also NTSC2RGB, RGB2NTSC, RGB2YCBCR.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 1.15.4.2 $ $Date: 2003/08/23 05:54:51 $
% Reference:
% Charles A. Poynton, "A Technical Introduction to Digital Video",
% John Wiley & Sons, Inc., 1996
%initialize variables
isColormap = false;
classin = class(in);
%must reshape colormap to be m x n x 3 for transformation
if (ndims(in)==2)
%colormap
isColormap=true;
colors = size(in,1);
in = reshape(in, [colors 1 3]);
end
%initialize output
rgb = in;
% set up constants for transformation. T alone will transform YCBCR in [0,255]
% to RGB in [0,1]. We must scale T and the offsets to get RGB in the appropriate
% range for uint8 and for uint16 arrays.
T = [65.481 128.553 24.966;...
-37.797 -74.203 112; ...
112 -93.786 -18.214];
Tinv = T^-1;
offset = [16;128;128];
Td = 255 * Tinv;
offsetd = Tinv * offset;
T8 = Td;
offset8 = T8 * offset;
T16 = (65535/257) * Tinv;
offset16 = 65535 * Tinv * offset;
switch classin
case 'double'
for p = 1:3
rgb(:,:,p) = Td(p,1) * in(:,:,1) + Td(p,2) * in(:,:,2) + ...
Td(p,3) * in(:,:,3) - offsetd(p);
end
case 'uint8'
for p = 1:3
rgb(:,:,p) = imlincomb(T8(p,1),in(:,:,1),T8(p,2),in(:,:,2), ...
T8(p,3),in(:,:,3),-offset8(p));
end
case 'uint16'
for p = 1:3
rgb(:,:,p) = imlincomb(T16(p,1),in(:,:,1),T16(p,2),in(:,:,2), ...
T16(p,3),in(:,:,3),-offset16(p));
end
end
if isColormap
rgb = reshape(rgb, [colors 3 1]);
end
if isa(rgb,'double')
rgb = min(max(rgb,0.0),1.0);
end
%%%
%Parse Inputs
%%%
function X = parse_inputs(varargin)
checknargin(1,1,nargin,mfilename);
X = varargin{1};
if ndims(X)==2
checkinput(X,{'uint8','uint16','double'},'real nonempty',mfilename,'MAP',1);
if (size(X,2) ~=3 || size(X,1) < 1)
eid = sprintf('Images:%s:invalidSizeForColormap',mfilename);
msg = 'MAP must be a m x 3 array.';
error(eid,'%s',msg);
end
elseif ndims(X)==3
checkinput(X,{'uint8','uint16','double'},'real',mfilename,'RGB',1);
if (size(X,3) ~=3)
eid = sprintf('Images:%s:invalidTruecolorImage',mfilename);
msg = 'RGB must a m x n x 3 array.';
error(eid,'%s',msg);
end
else
eid = sprintf('Images:%s:invalidInputSize',mfilename);
msg = ['RGB2GRAY only accepts two-dimensional or three-dimensional ' ...
'inputs.'];
error(eid,'%s',msg);
end
|
github
|
jacksky64/imageProcessing-master
|
compute_ssim_index.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/compute_ssim_index.m
| 19,068 |
utf_8
|
5e9683c1871d1245fa1be59a084a9927
|
function [mssim, ssim_map] = compute_ssim_index(img1, img2, K, window, L)
%========================================================================
%SSIM Index, Version 1.0
%Copyright(c) 2003 Zhou Wang
%All Rights Reserved.
%
%The author is with Howard Hughes Medical Institute, and Laboratory
%for Computational Vision at Center for Neural Science and Courant
%Institute of Mathematical Sciences, New York University.
%
%----------------------------------------------------------------------
%Permission to use, copy, or modify this software and its documentation
%for educational and research purposes only and without fee is hereby
%granted, provided that this copyright notice and the original authors'
%names appear on all copies and supporting documentation. This program
%shall not be used, rewritten, or adapted as the basis of a commercial
%software or hardware product without first obtaining permission of the
%authors. The authors make no representations about the suitability of
%this software for any purpose. It is provided "as is" without express
%or implied warranty.
%----------------------------------------------------------------------
%
%This is an implementation of the algorithm for calculating the
%Structural SIMilarity (SSIM) index between two images. Please refer
%to the following paper:
%
%Z. Wang, A. C. Bovik, H. R. Sheikh, and E. P. Simoncelli, "Image
%quality assessment: From error visibility to structural similarity"
%IEEE Transactios on Image Processing, vol. 13, no. 4, pp.600-612,
%Apr. 2004.
%
%Kindly report any suggestions or corrections to [email protected]
%
%----------------------------------------------------------------------
%
%Input : (1) img1: the first image being compared
% (2) img2: the second image being compared
% (3) K: constants in the SSIM index formula (see the above
% reference). defualt value: K = [0.01 0.03]
% (4) window: local window for statistics (see the above
% reference). default widnow is Gaussian given by
% window = fspecial('gaussian', 11, 1.5);
% (5) L: dynamic range of the images. default: L = 255
%
%Output: (1) mssim: the mean SSIM index value between 2 images.
% If one of the images being compared is regarded as
% perfect quality, then mssim can be considered as the
% quality measure of the other image.
% If img1 = img2, then mssim = 1.
% (2) ssim_map: the SSIM index map of the test image. The map
% has a smaller size than the input images. The actual size:
% size(img1) - size(window) + 1.
%
%Default Usage:
% Given 2 test images img1 and img2, whose dynamic range is 0-255
%
% [mssim ssim_map] = ssim_index(img1, img2);
%
%Advanced Usage:
% User defined parameters. For example
%
% K = [0.05 0.05];
% window = ones(8);
% L = 100;
% [mssim ssim_map] = ssim_index(img1, img2, K, window, L);
%
%See the results:
%
% mssim %Gives the mssim value
% imshow(max(0, ssim_map).^4) %Shows the SSIM index map
%
%========================================================================
Lmax = 1;
if (nargin < 2 | nargin > 5)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
if (size(img1) ~= size(img2))
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
[M N] = size(img1);
if (nargin == 2)
if ((M < 11) | (N < 11))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5); %
K(1) = 0.01; % default settings
K(2) = 0.03; %
L = Lmax; %
end
if (nargin == 3)
if ((M < 11) | (N < 11))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5);
L = Lmax;
if (length(K) == 2)
if (K(1) < 0 | K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 4)
[H W] = size(window);
if ((H*W) < 4 | (H > M) | (W > N))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
L = Lmax;
if (length(K) == 2)
if (K(1) < 0 | K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 5)
[H W] = size(window);
if ((H*W) < 4 | (H > M) | (W > N))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
if (length(K) == 2)
if (K(1) < 0 | K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
C1 = (K(1)*L)^2;
C2 = (K(2)*L)^2;
window = window/sum(sum(window));
img1 = double(img1);
img2 = double(img2);
mu1 = filter2(window, img1, 'valid');
mu2 = filter2(window, img2, 'valid');
mu1_sq = mu1.*mu1;
mu2_sq = mu2.*mu2;
mu1_mu2 = mu1.*mu2;
sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq;
sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq;
sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2;
if (C1 > 0 & C2 > 0)
ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2));
else
numerator1 = 2*mu1_mu2 + C1;
numerator2 = 2*sigma12 + C2;
denominator1 = mu1_sq + mu2_sq + C1;
denominator2 = sigma1_sq + sigma2_sq + C2;
ssim_map = ones(size(mu1));
index = (denominator1.*denominator2 > 0);
ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index));
index = (denominator1 ~= 0) & (denominator2 == 0);
ssim_map(index) = numerator1(index)./denominator1(index);
end
mssim = mean(ssim_map(:));
return
function h = fspecial(varargin)
%FSPECIAL Create 2-D special filters.
% H = FSPECIAL(TYPE) creates a two-dimensional filter H of the
% specified type. Possible values for TYPE are:
%
% 'average' averaging filter
% 'disk' circular averaging filter
% 'gaussian' Gaussian lowpass filter
% 'laplacian' filter approximating the 2-D Laplacian operator
% 'log' Laplacian of Gaussian filter
% 'motion' motion filter
% 'prewitt' Prewitt horizontal edge-emphasizing filter
% 'sobel' Sobel horizontal edge-emphasizing filter
% 'unsharp' unsharp contrast enhancement filter
%
% Depending on TYPE, FSPECIAL may take additional parameters
% which you can supply. These parameters all have default
% values.
%
% H = FSPECIAL('average',HSIZE) returns an averaging filter H of size
% HSIZE. HSIZE can be a vector specifying the number of rows and columns in
% H or a scalar, in which case H is a square matrix.
% The default HSIZE is [3 3].
%
% H = FSPECIAL('disk',RADIUS) returns a circular averaging filter
% (pillbox) within the square matrix of side 2*RADIUS+1.
% The default RADIUS is 5.
%
% H = FSPECIAL('gaussian',HSIZE,SIGMA) returns a rotationally
% symmetric Gaussian lowpass filter of size HSIZE with standard
% deviation SIGMA (positive). HSIZE can be a vector specifying the
% number of rows and columns in H or a scalar, in which case H is a
% square matrix.
% The default HSIZE is [3 3], the default SIGMA is 0.5.
%
% H = FSPECIAL('laplacian',ALPHA) returns a 3-by-3 filter
% approximating the shape of the two-dimensional Laplacian
% operator. The parameter ALPHA controls the shape of the
% Laplacian and must be in the range 0.0 to 1.0.
% The default ALPHA is 0.2.
%
% H = FSPECIAL('log',HSIZE,SIGMA) returns a rotationally symmetric
% Laplacian of Gaussian filter of size HSIZE with standard deviation
% SIGMA (positive). HSIZE can be a vector specifying the number of rows
% and columns in H or a scalar, in which case H is a square matrix.
% The default HSIZE is [5 5], the default SIGMA is 0.5.
%
% H = FSPECIAL('motion',LEN,THETA) returns a filter to approximate, once
% convolved with an image, the linear motion of a camera by LEN pixels,
% with an angle of THETA degrees in a counter-clockwise direction. The
% filter becomes a vector for horizontal and vertical motions. The
% default LEN is 9, the default THETA is 0, which corresponds to a
% horizontal motion of 9 pixels.
%
% H = FSPECIAL('prewitt') returns 3-by-3 filter that emphasizes
% horizontal edges by approximating a vertical gradient. If you need to
% emphasize vertical edges, transpose the filter H: H'.
%
% [1 1 1;0 0 0;-1 -1 -1].
%
% H = FSPECIAL('sobel') returns 3-by-3 filter that emphasizes
% horizontal edges utilizing the smoothing effect by approximating a
% vertical gradient. If you need to emphasize vertical edges, transpose
% the filter H: H'.
%
% [1 2 1;0 0 0;-1 -2 -1].
%
% H = FSPECIAL('unsharp',ALPHA) returns a 3-by-3 unsharp contrast
% enhancement filter. FSPECIAL creates the unsharp filter from the
% negative of the Laplacian filter with parameter ALPHA. ALPHA controls
% the shape of the Laplacian and must be in the range 0.0 to 1.0.
% The default ALPHA is 0.2.
%
% Class Support
% -------------
% H is of class double.
%
% Example
% -------
% I = imread('cameraman.tif');
% subplot(2,2,1);imshow(I);title('Original Image');
% H = fspecial('motion',20,45);
% MotionBlur = imfilter(I,H,'replicate');
% subplot(2,2,2);imshow(MotionBlur);title('Motion Blurred Image');
% H = fspecial('disk',10);
% blurred = imfilter(I,H,'replicate');
% subplot(2,2,3);imshow(blurred);title('Blurred Image');
% H = fspecial('unsharp');
% sharpened = imfilter(I,H,'replicate');
% subplot(2,2,4);imshow(sharpened);title('Sharpened Image');
%
% See also CONV2, EDGE, FILTER2, FSAMP2, FWIND1, FWIND2, IMFILTER.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 5.28.4.2 $ $Date: 2003/01/26 05:55:24 $
[type, p2, p3] = ParseInputs(varargin{:});
switch type
case 'average' % Smoothing filter
siz = p2;
h = ones(siz)/prod(siz);
case 'disk' % Disk filter
rad = p2;
crad = ceil(rad-0.5);
[x,y] = meshgrid(-crad:crad,-crad:crad);
maxxy = max(abs(x),abs(y));
minxy = min(abs(x),abs(y));
m1 = (rad^2 < (maxxy+0.5).^2 + (minxy-0.5).^2).*(minxy-0.5) + ...
(rad^2 >= (maxxy+0.5).^2 + (minxy-0.5).^2).* ...
sqrt(rad^2 - (maxxy + 0.5).^2);
m2 = (rad^2 > (maxxy-0.5).^2 + (minxy+0.5).^2).*(minxy+0.5) + ...
(rad^2 <= (maxxy-0.5).^2 + (minxy+0.5).^2).* ...
sqrt(rad^2 - (maxxy - 0.5).^2);
sgrid = (rad^2*(0.5*(asin(m2/rad) - asin(m1/rad)) + ...
0.25*(sin(2*asin(m2/rad)) - sin(2*asin(m1/rad)))) - ...
(maxxy-0.5).*(m2-m1) + (m1-minxy+0.5)) ...
.*((((rad^2 < (maxxy+0.5).^2 + (minxy+0.5).^2) & ...
(rad^2 > (maxxy-0.5).^2 + (minxy-0.5).^2)) | ...
((minxy==0)&(maxxy-0.5 < rad)&(maxxy+0.5>=rad))));
sgrid = sgrid + ((maxxy+0.5).^2 + (minxy+0.5).^2 < rad^2);
sgrid(crad+1,crad+1) = min(pi*rad^2,pi/2);
if ((crad>0) & (rad > crad-0.5) & (rad^2 < (crad-0.5)^2+0.25))
m1 = sqrt(rad^2 - (crad - 0.5).^2);
m1n = m1/rad;
sg0 = 2*(rad^2*(0.5*asin(m1n) + 0.25*sin(2*asin(m1n)))-m1*(crad-0.5));
sgrid(2*crad+1,crad+1) = sg0;
sgrid(crad+1,2*crad+1) = sg0;
sgrid(crad+1,1) = sg0;
sgrid(1,crad+1) = sg0;
sgrid(2*crad,crad+1) = sgrid(2*crad,crad+1) - sg0;
sgrid(crad+1,2*crad) = sgrid(crad+1,2*crad) - sg0;
sgrid(crad+1,2) = sgrid(crad+1,2) - sg0;
sgrid(2,crad+1) = sgrid(2,crad+1) - sg0;
end
sgrid(crad+1,crad+1) = min(sgrid(crad+1,crad+1),1);
h = sgrid/sum(sgrid(:));
case 'gaussian' % Gaussian filter
siz = (p2-1)/2;
std = p3;
[x,y] = meshgrid(-siz(2):siz(2),-siz(1):siz(1));
arg = -(x.*x + y.*y)/(2*std*std);
h = exp(arg);
h(h<eps*max(h(:))) = 0;
sumh = sum(h(:));
if sumh ~= 0,
h = h/sumh;
end;
case 'laplacian' % Laplacian filter
alpha = p2;
alpha = max(0,min(alpha,1));
h1 = alpha/(alpha+1); h2 = (1-alpha)/(alpha+1);
h = [h1 h2 h1;h2 -4/(alpha+1) h2;h1 h2 h1];
case 'log' % Laplacian of Gaussian
% first calculate Gaussian
siz = (p2-1)/2;
std2 = p3^2;
[x,y] = meshgrid(-siz(2):siz(2),-siz(1):siz(1));
arg = -(x.*x + y.*y)/(2*std2);
h = exp(arg);
h(h<eps*max(h(:))) = 0;
sumh = sum(h(:));
if sumh ~= 0,
h = h/sumh;
end;
% now calculate Laplacian
h1 = h.*(x.*x + y.*y - 2*std2)/(std2^2);
h = h1 - sum(h1(:))/prod(p2); % make the filter sum to zero
case 'motion' % Motion filter uses bilinear interpolation
len = max(1,p2);
half = (len-1)/2;% rotate half length around center
phi = mod(p3,180)/180*pi;
cosphi = cos(phi);
sinphi = sin(phi);
xsign = sign(cosphi);
linewdt = 1;
% define mesh for the half matrix, eps takes care of the right size
% for 0 & 90 rotation
sx = fix(half*cosphi + linewdt*xsign - len*eps);
sy = fix(half*sinphi + linewdt - len*eps);
[x y] = meshgrid([0:xsign:sx],[0:sy]);
% define shortest distance from a pixel to the rotated line
dist2line = (y*cosphi-x*sinphi);% distance perpendicular to the line
rad = sqrt(x.^2 + y.^2);
% find points beyond the line's end-point but within the line width
lastpix = find((rad >= half)&(abs(dist2line)<=linewdt));
%distance to the line's end-point parallel to the line
x2lastpix = half - abs((x(lastpix) + dist2line(lastpix)*sinphi)/cosphi);
dist2line(lastpix) = sqrt(dist2line(lastpix).^2 + x2lastpix.^2);
dist2line = linewdt + eps - abs(dist2line);
dist2line(dist2line<0) = 0;% zero out anything beyond line width
% unfold half-matrix to the full size
h = rot90(dist2line,2);
h(end+[1:end]-1,end+[1:end]-1) = dist2line;
h = h./(sum(h(:)) + eps*len*len);
if cosphi>0,
h = flipud(h);
end
case 'prewitt' % Prewitt filter
h = [1 1 1;0 0 0;-1 -1 -1];
case 'sobel' % Sobel filter
h = [1 2 1;0 0 0;-1 -2 -1];
case 'unsharp' % Unsharp filter
alpha = p2;
h = [0 0 0;0 1 0;0 0 0] - fspecial('laplacian',alpha);
end
%%%
%%% ParseInputs
%%%
function [type, p2, p3] = ParseInputs(varargin)
% default values
type = '';
p2 = [];
p3 = [];
% Check the number of input arguments.
% checknargin(1,3,nargin,mfilename);
% Determine filter type from the user supplied string.
type = varargin{1};
% type = checkstrs(type,{'gaussian','sobel','prewitt','laplacian','log',...
% 'average','unsharp','disk','motion'},mfilename,'TYPE',1);
% default values
switch type
case 'average'
p2 = [3 3]; % siz
case 'disk'
p2 = 5; % rad
case 'gaussian'
p2 = [3 3]; % siz
p3 = 0.5; % std
case {'laplacian', 'unsharp'}
p2 = 1/5; % alpha
case 'log'
p2 = [5 5]; % siz
p3 = 0.5; % std
case 'motion'
p2 = 9; % len
p3 = 0; % theta
end
switch nargin
case 1
% FSPECIAL('average')
% FSPECIAL('disk')
% FSPECIAL('gaussian')
% FSPECIAL('laplacian')
% FSPECIAL('log')
% FSPECIAL('motion')
% FSPECIAL('prewitt')
% FSPECIAL('sobel')
% FSPECIAL('unsharp')
% Nothing to do here; the default values have
% already been assigned.
case 2
% FSPECIAL('average',N)
% FSPECIAL('disk',RADIUS)
% FSPECIAL('gaussian',N)
% FSPECIAL('laplacian',ALPHA)
% FSPECIAL('log',N)
% FSPECIAL('motion',LEN)
% FSPECIAL('unsharp',ALPHA)
p2 = varargin{2};
switch type
case {'sobel','prewitt'}
msg = sprintf('%s: Too many arguments for this type of filter.', upper(mfilename));
eid = sprintf('Images:%s:tooManyArgsForThisFilter', mfilename);
error(eid,msg);
case {'laplacian','unsharp'}
checkinput(p2,{'double'},{'nonnegative','real',...
'nonempty','finite','scalar'},...
mfilename,'ALPHA',2);
if p2 > 1
msg = sprintf('%s: ALPHA should be less than or equal 1 and greater than 0.', upper(mfilename));
eid = sprintf('Images:%s:outOfRangeAlpha', mfilename);
error(eid,msg);
end
case {'disk','motion'}
checkinput(p2,{'double'},{'positive','finite','real','nonempty','scalar'},mfilename,'RADIUS or LEN',2);
case {'gaussian','log','average'}
checkinput(p2,{'double'},{'positive','finite','real','nonempty','integer'},mfilename,'HSIZE',2);
if prod(size(p2)) > 2
msg = 'HSIZE should have 1 or 2 elements.';
eid = sprintf('Images:%s:wrongSizeN', mfilename);
error(eid,msg);
elseif (prod(size(p2))==1)
p2 = [p2 p2];
end
end
case 3
% FSPECIAL('gaussian',N,SIGMA)
% FSPECIAL('log',N,SIGMA)
% FSPECIAL('motion',LEN,THETA)
p2 = varargin{2};
p3 = varargin{3};
switch type
case 'motion'
% checkinput(p2,{'double'},{'positive','finite','real','nonempty','scalar'},mfilename,'LEN',2);
% checkinput(p3,{'double'},{'real','nonempty','finite','scalar'},mfilename,'THETA',3);
case {'gaussian','log'}
% checkinput(p2,{'double'},{'positive','finite','real','nonempty','integer'},mfilename,'N',2);
% checkinput(p3,{'double'},{'positive','finite','real','nonempty','scalar'},mfilename,'SIGMA',3);
if prod(size(p2)) > 2
msg = sprintf('%s: size(N) should be less than or equal 2.', upper(mfilename));
eid = sprintf('Images:%s:wrongSizeN', mfilename);
error(eid,msg);
elseif (prod(size(p2))==1)
p2 = [p2 p2];
end
otherwise
msg = sprintf('%s: Too many arguments for this type of filter.', upper(mfilename));
eid = sprintf('Images:%s:tooManyArgsForThisFilter', mfilename);
error(eid,msg);
end
end
|
github
|
jacksky64/imageProcessing-master
|
perform_tv_hilbert_projection.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/perform_tv_hilbert_projection.m
| 3,727 |
utf_8
|
f96d06428439140dc4dc1f0182805595
|
function [u,v,px,py] = perform_tv_hilbert_projection(f,kernel,lam,options)
% Aujol & Chambolle projection for solving TV-K regularization
%
% [u,v,px,py] = perform_tv_hilbert_projection(f,kernel,lam,options);
%
% Solve the image separation problem :
% u = argmin_u |f-u|_K^2 + lam*|u|_TV
%
% f = u+v
% u is the cartoon part.
% v is the texture part.
%
% where |.|_K is an hilber space norm defined by some operator K
% <f,g>_K = <f,K*g>
% |f|_K^2 = <f,f>_K
%
% f is the input image.
% kernel is a callback function of the kernel operator, should be like
% f = kernel(f, options);
%
% Set options.use_gabor==1 to setup the Gabor Kernel automatically
% and options.use_gabor==-1 to set up the L2 identity kernel.
%
% Original code by Guy Gilboa, modified by Gabriel Peyre
%
% Copyright (c) 2006 Gabriel Peyre
[ny,nx]=size(f);
options.null = 0;
if isfield(options, 'niter')
niter = options.niter;
else
niter = 30;
end
if isfield(options, 'dt')
dt = options.dt;
else
dt = 0.01;
end
if isfield(options, 'p0x') && ~isempty(options.p0x)
p0x = options.p0x;
else
p0x=zeros(ny,nx);
end
if isfield(options, 'p0y') && ~isempty(options.p0y)
p0y = options.p0y;
else
p0y=p0x;
end
use_gabor = 1;
if isfield(options, 'use_gabor')
use_gabor = options.use_gabor;
end
px=p0x; py=p0y;
lami=1/lam; % here the algorithm works with inverse of lambda
if use_gabor==1
sig_k=1; freq=0.25; bias=0;
n=11; %kernel size
x=ones(n,1)*(-(n-1)/2:(n-1)/2); y=x';
gs=exp(-((x/sig_k).^2+(y/sig_k).^2)/2); % 2D gaussian
gs=gs/sum(sum(gs)); % normalize
r=sqrt(x.^2+y.^2); cs=cos(2*pi*r*freq); %radially symmetric
iKx = cs.*gs; %% "Gabor filter" for inverse K
iKx=iKx-mean(mean(iKx)); % zero mean filter
cp=(n+1)/2; % center of kernel
iKx(cp,cp) = iKx(cp,cp)-bias;
elseif use_gabor==-1
iKx = 1;
end
%% perform iterations
if use_gabor~=0
for i=1:niter, %% do niterations
progressbar(i,niter);
%% compute projection
km1div = filter2(iKx,div(px,py))-f*lam;
%[Gx,Gy] = grad(km1div);
Gx=gradx(km1div); Gy=grady(km1div);
aG = sqrt(Gx.^2+Gy.^2); %abs(G)
px = (px + dt*Gx)./(1+dt*aG);
py = (py + dt*Gy)./(1+dt*aG);
end % for i
v = filter2(iKx,div(px,py))/lam;
else
for i=1:niter, %% do niterations
progressbar(i,niter);
% compute projection
km1div = feval( kernel, div(px,py), options ) - f*lam;
% compute gradient
Gx=gradx(km1div); Gy=grady(km1div);
% [Gx,Gy] = grad(km1div);
aG = sqrt(Gx.^2+Gy.^2); %abs(G)
px = (px + dt*Gx)./(1+dt*aG);
py = (py + dt*Gy)./(1+dt*aG);
end % for i
v = lami*feval( kernel, div(px,py), options );
end
u=f-v;
%% additional functions
%%%%%%%%%%%%%%%%%%%%%%%%%%% Gradient (forward difference)
function [fx,fy] = grad(P)
error('Should not be used.');
fx = P(:,[2:end end])-P;
fy = P([2:end end],:)-P;
%%%%%%%%%%%%%%%%%%%%%%%%%%% Divergence (backward difference)
function M=div(px,py)
[m,n]=size(px);
M=zeros(m,n);
Mx=M; My=M;
Mx(2:m-1,1:n)=px(2:m-1,1:n)-px(1:m-2,1:n);
Mx(1,:)=px(1,:);
Mx(m,:)=-px(m-1,:);
My(1:m,2:n-1)=py(1:m,2:n-1)-py(1:m,1:n-2);
My(:,1)=py(:,1);
My(:,n)=-py(:,n-1);
M=Mx+My;
%%%%%%%%%%%%%%%%%%%%%%%%%%% Laplacian (central difference)
function fl = lap(P)
[gx,gy]=grad(P);
fl=div(gx,gy);
%%%%%%%%%%%%%%%%%%%%%%%%%%% Gradient on X (forward difference)
function M=gradx(I)
[m,n]=size(I);
M=zeros(m,n);
M(1:m-1,1:n)=-I(1:m-1,:)+I(2:m,:);
M(m,1:n)=zeros(1,n);
%%%%%%%%%%%%%%%%%%%%%%%%%%% Gradient on Y (forward difference)
function M=grady(I)
[m,n]=size(I);
M=zeros(m,n);
M(1:m,1:n-1)=-I(:,1:n-1)+I(:,2:n);
M(1:m,n)=zeros(m,1);
|
github
|
jacksky64/imageProcessing-master
|
perform_tv_correction.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/perform_tv_correction.m
| 985 |
utf_8
|
e9637dd038c9c859b0c6dedd242fecae
|
function y = perform_tv_correction(x,T)
% perform_tv_correction - perform correction of the image to that it minimizes the TV norm.
%
% y = perform_tv_correction(x,T);
%
% Perform correction using thresholding of haar wavelet coefficients on 1
% scale.
%
% Copyright (c) 2006 Gabriel Peyre
n = size(x,1);
Jmin = log2(n)-1;
% do haar transform
options.wavelet_type = 'daubechies';
options.wavelet_vm = 1;
y = perform_atrou_transform(x,Jmin,options);
% perform soft thesholding
y = perform_soft_tresholding(y,T);
% do reconstruction
y = perform_atrou_transform(y,Jmin,options);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_soft_tresholding(x,t)
if iscell(x)
for i=1:length(x)
y{i} = perform_soft_tresholding(x{i},t);
end
return;
end
s = abs(x) - t;
s = (s + abs(s))/2;
y = sign(x).*s;
|
github
|
jacksky64/imageProcessing-master
|
compute_periodic_poisson.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/compute_periodic_poisson.m
| 855 |
utf_8
|
52f67b893134bee2f5ec735f55733e1f
|
function G = compute_periodic_poisson(d, symmetrize)
% compute_periodic_poisson - solve poisson equation
%
% G = compute_periodic_poisson(d,symmetrize);
%
% Solve
% Delta(G) = d
% with periodic boundary condition.
% G has zero mean.
%
% Set symmetrize=1 (default 0) if the data divergence d is not periodic.
% This will double the size and consider symmetric extension.
%
% Copyright (c) 2007 Gabriel Peyre
n = size(d,1);
if nargin==2 && symmetrize
d = perform_size_doubling(d);
G = compute_periodic_poisson(d);
G = G(1:n,1:n);
return;
end
% solve for laplacian
[Y,X] = meshgrid(0:n-1,0:n-1);
mu = sin(X*pi/n).^2; mu = -4*( mu+mu' );
mu(1) = 1; % avoid division by 0
G = fft2(d) ./ mu; G(1) = 0;
G = real( ifft2( G ) );
%%
function g = perform_size_doubling(g)
g = [g;g(end:-1:1,:,:)];
g = [g,g(:,end:-1:1,:)];
|
github
|
jacksky64/imageProcessing-master
|
perform_quincunx_interpolation.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/perform_quincunx_interpolation.m
| 1,537 |
utf_8
|
6d747ffd41f26abbb6804e53fb57335d
|
function Mi = perform_quincunx_interpolation(M,vm)
% perform_quincunx_interpolation - interpolate data on a quincunx grid
%
% Mi = perform_quincunx_interpolation(M,vm);
%
% M is a 2D image where only pixels M(i+j,i-j) are available
% (checkboard subsampling)
%
% vm is 2, 4 or 6
%
% Copyright (c) 2008 Gabriel Peyre
if nargin<2
vm = 2;
end
n = size(M,1);
%% compute mask
qsub = 2;
x = floor(0:1/(qsub-1):n); x= x(1:n);
[Y,X] = meshgrid(x,x);
mask = mod( X+Y,2 )==0;
%% compute filters
[dx,dy,w] = get_quincunx_filter(vm);
%% do averaging
[Y,X] = meshgrid(1:n,1:n);
Mi = zeros(n);
[Y,X] = meshgrid(1:n,1:n);
for i=1:length(dx)
Xi = X+dx(i); Xi(Xi<1) = 2 - Xi(Xi<1); Xi(Xi>n) = 2*n - Xi(Xi>n);
Yi = Y+dy(i); Yi(Yi<1) = 2 - Yi(Yi<1); Yi(Yi>n) = 2*n - Yi(Yi>n);
Mi = Mi + w(i) * M(Xi+(Yi-1)*n);
end
Mi(mask==0) = M(mask==0);
%%
function [dX,dY,w] = get_quincunx_filter(vm)
switch vm
case 2
dX = [0 0 1 -1];
dY = [1 -1 0 0];
w = [1 1 1 1];
case 4
dX = [0 0 1 -1 2 2 -2 -2 1 -1 1 -1];
dY = [1 -1 0 0 1 -1 1 -1 2 2 -2 -2];
w = [10 10 10 10 -1 -1 -1 -1 -1 -1 -1 -1];
case 6
dX = [0 0 1 -1 2 2 -2 -2 1 -1 1 -1 0 0 3 -3 ...
3 3 -3 -3 2 2 -2 -2];
dY = [1 -1 0 0 1 -1 1 -1 2 2 -2 -2 3 -3 0 0 ...
2 -2 2 -2 3 -3 3 -3];
w = [174*ones(1,4) -27*ones(1,8) 2*ones(1,4) 3*ones(1,8)];
otherwise
error('Only 2/4/6 vanishing moments are supported.');
end
w = w/sum(w);
|
github
|
jacksky64/imageProcessing-master
|
perform_windowed_dct_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/perform_windowed_dct_transform.m
| 2,282 |
utf_8
|
9c456075e56465427a4442c1e5c9afc8
|
function y = perform_windowed_dct_transform(x,w,q,n, options)
% perform_windowed_dct_transform - compute a local DCT transform
%
% Forward transform:
% MF = perform_windowed_dct_transform(M,w,q,n, options);
% Backward transform:
% M = perform_windowed_dct_transform(MF,w,q,n, options);
%
% w is the width of the window used to perform local computation.
% q is the spacing betwen each window.
%
% MF(:,:,,i,j) contains the transform around point ((i-1)*q,(j-1)*q)+1.
%
% A typical use, for an redundancy of 2x2 could be w=2*q
%
% Copyright (c) 2007 Gabriel Peyre
options.transform_type = 'dct';
y = perform_windowed_fourier_transform(x,w,q,n, options);
return;
%%%%%%%%%%% OLD CODE %%%%%%%%%%%%
options.null = 0;
if size(x,3)>1
dir = -1;
if nargin<4
% assume power of 2 size
n = q*size(x,3);
n = 2^floor(log2(n));
end
else
dir = 1;
n = size(x,1);
end
% perform sampling
t = 1:q:n-w+1;
[Y,X] = meshgrid(t,t);
p = size(X,1);
w = ceil(w/2)*2;
w1 = w/2;
t = 0:w-1;
[dY,dX] = meshgrid(t,t);
X = reshape(X,[1 1 p p]);
Y = reshape(Y,[1 1 p p]);
X = repmat( X, [w w 1 1] );
Y = repmat( Y, [w w 1 1] );
dX = repmat( dX, [1 1 p p] );
dY = repmat( dY, [1 1 p p] );
X1 = X+dX;
Y1 = Y+dY;
if 0
I = find(X1<1); X1(I) = 1-X1(I);
I = find(X1>n); X1(I) = 2*n+1-X1(I);
I = find(Y1<1); Y1(I) = 1-Y1(I);
I = find(Y1>n); Y1(I) = 2*n+1-Y1(I);
end
% build a weight function
if isfield(options, 'window_type')
window_type = options.window_type;
else
window_type = 'constant';
end
if strcmp(window_type, 'sin') || strcmp(window_type, 'sine')
t = linspace(0,1,w);
W = sin(t(:)*pi).^2;
W = W * W';
elseif strcmp(window_type, 'constant')
W = ones(w);
else
error('Unkwnown winow.');
end
I = X1 + (Y1-1)*n;
if dir==1
y = x(I) .* repmat( W, [1 1 p p] );
y = my_dct_transform( y, +1 );
else
x = my_dct_transform( x, -1 );
weight = zeros(n); y = zeros(n);
for i=1:p
for j=1:p
y(I(:,:,i,j)) = y(I(:,:,i,j)) + x(:,:,i,j);
weight(I(:,:,i,j)) = weight(I(:,:,i,j)) + W;
end
end
y = real( y./weight );
end
function y = my_dct_transform(x,dir)
for i=1:size(x,3)
for j=1:size(x,4)
y(:,:,i,j) = perform_dct_transform(x(:,:,i,j),dir);
end
end
|
github
|
jacksky64/imageProcessing-master
|
perform_windowed_dct4_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/perform_windowed_dct4_transform.m
| 14,528 |
utf_8
|
14fb4b703d9af03093b3a48e38dceded
|
function y = perform_windowed_dct4_transform(x, w, dir, options)
% perform_windowed_dct4_transform - orthogonal local DCT
%
% y = perform_windowed_dct4_transform(x, w, dir, options);
%
% This is an orthogonal transform, with x2 overlap,
% note that the low frequencies are removes if options.remove_lowfreq = 1.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
window_type = getoptions(options, 'window_type', 'Sine');
remove_lowfreq = getoptions(options, 'remove_lowfreq', 1);
if dir==1
y = FastLDCT2ivAnalysis(x,window_type,w);
y = y(2).coeff;
else
c(1).coeff = zeros( size(x)/w );
c(2).coeff = x;
c(1).winwidth = w;
c(2).winwidth = w;
y = FastLDCT2ivSynthesis(c,window_type,w,remove_lowfreq);
end
function img = FastLDCT2ivSynthesis(coef,bellname,w,remove_low_freq) % pars3)
% FastLDCT2Synthesis -- 2D Local inverse DCT iv transform
% Usage
% img = FastLDCT2Synthesis(ldct,w)
% Inputs
% coef 2D Local DCT structure array
% w width of window
% bellname name of bell to use, defaults to 'Sine'
% Outputs
% img 2D reconstructed n by n image
% Description
% The matrix img contains image reconstructed from the Local DCT Decomposition.
% See Also
% FastLDCT2Analysis, idct2
%
if nargin < 3 | bellname==0,
bellname = 'Sine';
end
[n,J] = quadlength(coef(2).coeff);
if coef(2).winwidth ~= w
error('Window width is different from given argument.');
return;
end
img = zeros(n,n);
%
nbox = floor(n/w);
lfign=0.25;
if remove_low_freq
for boxcnt1=0:nbox-1
for boxcnt2=0:nbox-1
coef(2).coeff(boxcnt1*w+1:boxcnt1*w+1+floor(w*lfign),boxcnt2*w+1:boxcnt2*w+1+floor(w*lfign)) = 0;
end
end
end
for ncol=1:n
ldct = [struct('winwidth', w, 'coeff', 0) ...
struct('winwidth', w, 'coeff', coef(2).coeff(:,ncol))];
x = FastLDCTivSynthesis(ldct,bellname,w);
img(:,ncol) = x;
end
for nrow=1:n
ldct = [struct('winwidth', w, 'coeff', 0) ...
struct('winwidth', w, 'coeff', img(nrow,:))];
x = FastLDCTivSynthesis(ldct,bellname,w);
img(nrow,:) = x';
end
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function sig = FastLDCTivSynthesis(ldct,bellname,w,par3)
% FastLDCTivSynthesis -- Synthesize signal from local DCT iv coefficients (orthogonal fixed folding)
% Usage
% sig = FastLDCTivSynthesis(ldct,bellname,w)
% Inputs
% ldct local DCT iv coefficients (structure array)
% w width of window
% bell name of bell to use, defaults to 'Sine'
% Outputs
% sig signal whose orthonormal local DCT iv coeff's are ldct
%
% See Also
% FastLDCTivAnalysis, CPAnalysis, FCPSynthesis, fold, unfold, dct_iv, packet
%
[n,J] = dyadlength(ldct(2).coeff);
d = floor(log2(n/w));
%
% Create Bell
%
if nargin < 3,
bellname = 'Sine';
end
m = n / 2^d /2;
[bp,bm] = MakeONBell(bellname,m);
%
%
%
x = zeros(1,n);
for b=0:(2^d-1),
c = ldct(2).coeff(packet(d,b,n));
y = dct_iv(c);
[xc,xl,xr] = unfold(y,bp,bm);
x(packet(d,b,n)) = x(packet(d,b,n)) + xc;
if b>0,
x(packet(d,b-1,n)) = x(packet(d,b-1,n)) + xl;
else
x(packet(d,0,n)) = x(packet(d,0,n)) + edgeunfold('left',xc,bp,bm);
end
if b < 2^d-1,
x(packet(d,b+1,n)) = x(packet(d,b+1,n)) + xr;
else
x(packet(d,b,n)) = x(packet(d,b,n)) + edgeunfold('right',xc,bp,bm);
end
end
sig = ShapeAsRow(x)';
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function coef = FastLDCT2ivAnalysis(img,bellname,w,pars3)
% FastLDCT2ivAnalysis -- Analyze image into 2-d cosine packet coefficients at a given depth (window width)
% Usage
% coef = FastLDCT2ivAnalysis(img,w)
% Inputs
% img 2-d image to be transformed into basis
% w width of window
% bellname name of bell to use, defaults to 'Sine'
% Outputs
% coef 2-d Local DCT iv coeffts
%
% Description
% Once a cosine packet basis has been selected (at a given depth),
% this function may be used to expand a given
% image in that basis.
%
if nargin < 3 | bellname==0,
bellname = 'Sine';
end
[n,J] = quadlength(img);
d = floor(log2(n/w));
%
% CP image at depth d
%
coef = [struct('winwidth', w, 'coeff', zeros(floor(n/w),floor(n/w))) ...
struct('winwidth', w, 'coeff', zeros(n,n))];
%
for nrow=1:n
ldct = FastLDCTivAnalysis(img(nrow,:),bellname,w);
coef(2).coeff(nrow,:) = ldct(2).coeff;
end
for ncol=1:n
ldct = FastLDCTivAnalysis(coef(2).coeff(:,ncol),bellname,w);
coef(2).coeff(:,ncol) = ldct(2).coeff;
end
function ldct = FastLDCTivAnalysis(x,bellname,w,par3)
% FastLDCTivAnalysis -- Local DCT iv transform (orthogonal fixed folding)
% Usage
% ldct = FastLDCTivAnalysis(x,bell,w)
% Inputs
% x 1-d signal: length(x)=2^J
% w width of window
% bell name of bell to use, defaults to 'Sine'
% Outputs
% ldct 1-d Local DCT iv coefficients (structure array)
% Description
% The vector ldct contains coefficients of the Local DCT Decomposition.
% See Also
% FastLDCTivSynthesis, CPAnalysis, FCPSynthesis, fold, unfold, dct_iv, packet
%
if nargin < 3,
bellname = 'Sine';
end
[n,J] = dyadlength(x);
d = floor(log2(n/w));
%
% taper window
%
m = n / 2^d /2;
[bp,bm] = MakeONBell(bellname,m);
%
% packet table
%
n = length(x);
ldct = [struct('winwidth', w, 'coeff', zeros(floor(n/w),1)) ...
struct('winwidth', w, 'coeff', zeros(n,1))];
x = ShapeAsRow(x);
%
nbox = 2^d;
for b=0:(nbox-1)
if(b == 0) , % gather packet and
xc = x(packet(d,b,n)); % left, right neighbors
xl = edgefold('left',xc,bp,bm); % taking care of edge effects
else
xl = xc;
xc = xr;
end
if (b+1 < nbox)
xr = x(packet(d,b+1,n));
else
xr = edgefold('right',xc,bp,bm);
end
y = fold(xc,xl,xr,bp,bm); % folding projection
c = dct_iv(y); % DCT-IV
ldct(2).coeff(packet(d,b,n)) = c'; % store
end
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function c = dct_iv(x)
% dct_iv -- Type (IV) Discrete Cosine Xform
% Usage
% c = dct_iv(x)
% Inputs
% x 1-d signal, length(x) = 2^J
% Outputs
% c 1-d cosine transform, length(x)=2^J
%
% Description
% The form c = dct_iv(x) computes c defined by
% c_m = sqrt(2/N) * sum_n x(n) cos( pi * (m-.5) * (n-.5) / N )
% where
% 1 <= m,n <= N, N = length(x) = length(c)
%
% To reconstruct, use the same function:
% x = dct_iv(c)
%
% See Also
% CPAnalysis, CPSynthesis
%
n2 = 2*length(x);
y = zeros(1, 4*n2);
y(2:2:n2) = x(:);
z = fft(y);
c = sqrt(4/n2) .* real(z(2:2:n2));
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:40 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
function [n,J] = dyadlength(x)
% dyadlength -- Find length and dyadic length of array
% Usage
% [n,J] = dyadlength(x)
% Inputs
% x array of length n = 2^J (hopefully)
% Outputs
% n length(x)
% J least power of two greater than n
%
% Side Effects
% A warning is issued if n is not a power of 2.
%
% See Also
% quadlength, dyad, dyad2ix
%
n = length(x) ;
J = ceil(log(n)/log(2));
if 2^J ~= n ,
disp('Warning in dyadlength: n != 2^J')
end
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:40 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
function [bp,bm] = MakeONBell(Name,m)
% MakeONBell -- Make Bell for Orthonormal Local Cosine Analysis
% Usage
% [bp,bm] = MakeONBell(bell,m)
% Inputs
% bell bellname, currently 'Trivial','Sine'
% m length of bell
% Outputs
% bp part of bell interior to domain
% bm part of bell exterior to domain
%
% See Also
% CPAnalysis, CPSynthesis, MakeCosinePacket
%
Name = lower(Name);
xi = (1 + (.5:(m-.5))./m)./2;
if strcmp(Name,'trivial') || strcmp(Name,'constant')
bp = sqrt(xi);
elseif strcmp(Name,'sine') || strcmp(Name,'sin')
bp = sin( pi/2 .* xi );
else
error('Unknown bell shape.');
end
bm = sqrt(1 - bp .^2);
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:40 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
function row = ShapeAsRow(sig)
% ShapeAsRow -- Make signal a row vector
% Usage
% row = ShapeAsRow(sig)
% Inputs
% sig a row or column vector
% Outputs
% row a row vector
%
% See Also
% ShapeLike
%
row = sig(:)';
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:43 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
function p = packet(d,b,n)
% packet -- Packet table indexing
% Usage
% p = packet(d,b,n)
% Inputs
% d depth of splitting in packet decomposition
% b block index among 2^d possibilities at depth d
% n length of signal
% Outputs
% p linear indices of all coeff's in that block
%
npack = 2^d;
p = ( (b * (n/npack) + 1) : ((b+1)*n/npack ) ) ;
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:40 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
function extra = edgefold(which,xc,bp,bm)
% edgefold -- Perform folding projection with (+,-) polarity at EDGES
% Usage
% extra = edgefold(which,xc,bp,bm)
% Inputs
% which string, 'left'/'right', indicating which edge we are at
% xc unfolded data, center window
% bp interior of window
% bm exterior of window
% Outputs
% extra pseudo-left/right packet
%
% Description
% The result should be used as either left or right packet in
% fold to ensure exact reconstruction at edges.
%
% See Also
% fold, unfold, CPSynthesis, CPImpulse
%
n = length(xc);
m = length(bp);
back = n:-1:(n-m+1);
front = 1:m;
extra = xc.*0;
%
if strcmp(which,'left'),
extra(back) = xc(front) .* (1-bp)./bm;
else
extra(front) = -xc(back) .* (1-bp)./bm;
end
%
% Copyright (c) 1994. David L. Donoho
%
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:40 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
function y = fold(xc,xl,xr,bp,bm)
% fold -- Folding projection with (+,-) polarity
% Usage
% y = fold(xc,xl,xr,bp,bm)
% Inputs
% xc,xl,xr 1-d signals: center, left, and right packets
% bp,bm interior and exterior of taper window
% Outputs
% y the folded series, whose DCT gives the LCT coeffs
%
% See Also
% CPAnalysis
%
% References
% H. Malvar, IEEE ASSP, 1990.
%
% Auscher, Weiss and Wickerhauser, in ``Wavelets: A Tutorial in
% Theory and Applications,'' C. Chui, ed., Academic Press, 1992.
%
m = length(bp);
n = length(xc);
front = 1:m;
back = n:-1:(n+1-m);
y = xc;
y(front) = bp .* y(front) + bm .* xl(back );
y(back ) = bp .* y(back ) - bm .* xr(front);
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:40 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
function [xc,xl,xr] = unfold(y,bp,bm)
% unfold -- Undo folding projection with (+,-) polarity
% Usage
% [xc,xl,xr] = unfold(y,bp,bm)
% Inputs
% y folded series
% bp interior of window
% bm exterior of window
% Outputs
% xc unfolded central packet
% xl contribution of unfolding to left packet
% xr contribution of unfolding to right packet
%
% See Also
% fold, CPAnalysis, CPSynthesis, CPImpulse
%
n = length(y);
m = length(bp);
xc = y;
xl = 0 .*y;
xr = 0 .*y;
front = 1:m;
back = n:-1:(n+1-m);
xc(front) = bp .* y(front);
xc(back) = bp .* y(back );
xl(back) = bm .* y(front);
xr(front) = (-1) .* bm .* y(back);
%
% Copyright (c) 1993. David L. Donoho
%
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:40 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
function extra = edgeunfold(which,xc,bp,bm)
% edgeunfold -- Undo folding projection with (+,-) polarity at EDGES
% Usage
% extra = endfold(which,xc,bp,bm)
% Inputs
% which string, 'left'/'right', indicating which edge we are at
% xc unfolded data, center window, produced by unfold
% bp interior of window
% bm exterior of window
% Outputs
% extra extra contribution to central packet
%
% Description
% The result should be added to the central packet to
% ensure exact reconstruction at edges.
%
% See Also
% unfold, CPSynthesis, CPImpulse
%
n = length(xc);
m = length(bp);
extra = xc.*0;
%
if strcmp(which,'left'),
front = 1:m;
extra(front) = xc(front) .* (1-bp)./bp;
else
back = n:-1:(n+1-m);
extra(back) = xc(back) .* (1-bp)./bp;
end
%
% Copyright (c) 1994. David L. Donoho
%
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:40 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
function [n,J] = quadlength(x)
% quadlength -- Find length and dyadic length of square matrix
% Usage
% [n,J] = quadlength(x)
% Inputs
% x 2-d image; size(n,n), n = 2^J (hopefully)
% Outputs
% n length(x)
% J least power of two greater than n
%
% Side Effects
% A warning message is issue if n is not a power of 2,
% or if x is not a square matrix.
%
s = size(x);
n = s(1);
if s(2) ~= s(1),
disp('Warning in quadlength: nr != nc')
end
k = 1 ; J = 0; while k < n , k=2*k; J = 1+J ; end ;
if k ~= n ,
disp('Warning in quadlength: n != 2^J')
end
%
% Copyright (c) 1993. David L. Donoho
%
|
github
|
jacksky64/imageProcessing-master
|
perform_dct_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_image/toolbox/perform_dct_transform.m
| 7,750 |
utf_8
|
07f7ce84cf4f6dfc91ad645a17eab05c
|
function y = perform_dct_transform(x,dir)
% perform_dct_transform - discrete cosine transform
%
% y = perform_dct_transform(x,dir);
%
% Copyright (c) 2006 Gabriel Peyre
if size(x,1)==1 || size(x,2)==1
% 1D transform
if dir==1
y = dct(x);
else
y = idct(x);
end
else
if dir==1
y = dct2(x);
% y = perform_dct2_transform(x);
else
y = idct2(x);
end
end
function b=dct(a,n)
%DCT Discrete cosine transform.
%
% Y = DCT(X) returns the discrete cosine transform of X.
% The vector Y is the same size as X and contains the
% discrete cosine transform coefficients.
%
% Y = DCT(X,N) pads or truncates the vector X to length N
% before transforming.
%
% If X is a matrix, the DCT operation is applied to each
% column. This transform can be inverted using IDCT.
%
% See also FFT, IFFT, IDCT.
% Author(s): C. Thompson, 2-12-93
% S. Eddins, 10-26-94, revised
% Copyright 1988-2002 The MathWorks, Inc.
% $Revision: 1.7 $ $Date: 2002/04/15 01:10:40 $
% References:
% 1) A. K. Jain, "Fundamentals of Digital Image
% Processing", pp. 150-153.
% 2) Wallace, "The JPEG Still Picture Compression Standard",
% Communications of the ACM, April 1991.
if nargin == 0,
error('Not enough input arguments.');
end
if isempty(a)
b = [];
return
end
% If input is a vector, make it a column:
do_trans = (size(a,1) == 1);
if do_trans, a = a(:); end
if nargin==1,
n = size(a,1);
end
m = size(a,2);
% Pad or truncate input if necessary
if size(a,1)<n,
aa = zeros(n,m);
aa(1:size(a,1),:) = a;
else
aa = a(1:n,:);
end
% Compute weights to multiply DFT coefficients
ww = (exp(-i*(0:n-1)*pi/(2*n))/sqrt(2*n)).';
ww(1) = ww(1) / sqrt(2);
if rem(n,2)==1 | ~isreal(a), % odd case
% Form intermediate even-symmetric matrix
y = zeros(2*n,m);
y(1:n,:) = aa;
y(n+1:2*n,:) = flipud(aa);
% Compute the FFT and keep the appropriate portion:
yy = fft(y);
yy = yy(1:n,:);
else % even case
% Re-order the elements of the columns of x
y = [ aa(1:2:n,:); aa(n:-2:2,:) ];
yy = fft(y);
ww = 2*ww; % Double the weights for even-length case
end
% Multiply FFT by weights:
b = ww(:,ones(1,m)) .* yy;
if isreal(a), b = real(b); end
if do_trans, b = b.'; end
function b=dct2(arg1,mrows,ncols)
%DCT2 Compute 2-D discrete cosine transform.
% B = DCT2(A) returns the discrete cosine transform of A.
% The matrix B is the same size as A and contains the
% discrete cosine transform coefficients.
%
% B = DCT2(A,[M N]) or B = DCT2(A,M,N) pads the matrix A with
% zeros to size M-by-N before transforming. If M or N is
% smaller than the corresponding dimension of A, DCT2 truncates
% A.
%
% This transform can be inverted using IDCT2.
%
% Class Support
% -------------
% A can be numeric or logical. The returned matrix B is of
% class double.
%
% Example
% -------
% RGB = imread('autumn.tif');
% I = rgb2gray(RGB);
% J = dct2(I);
% imshow(log(abs(J)),[]), colormap(jet), colorbar
%
% The commands below set values less than magnitude 10 in the
% DCT matrix to zero, then reconstruct the image using the
% inverse DCT function IDCT2.
%
% J(abs(J)<10) = 0;
% K = idct2(J);
% imview(I)
% imview(K,[0 255])
%
% See also FFT2, IDCT2, IFFT2.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 5.22.4.2 $ $Date: 2003/05/03 17:50:23 $
% References:
% 1) A. K. Jain, "Fundamentals of Digital Image
% Processing", pp. 150-153.
% 2) Wallace, "The JPEG Still Picture Compression Standard",
% Communications of the ACM, April 1991.
[m, n] = size(arg1);
% Basic algorithm.
if (nargin == 1),
if (m > 1) & (n > 1),
b = dct(dct(arg1).').';
return;
else
mrows = m;
ncols = n;
end
end
% Padding for vector input.
a = arg1;
if nargin==2, ncols = mrows(2); mrows = mrows(1); end
mpad = mrows; npad = ncols;
if m == 1 & mpad > m, a(2, 1) = 0; m = 2; end
if n == 1 & npad > n, a(1, 2) = 0; n = 2; end
if m == 1, mpad = npad; npad = 1; end % For row vector.
% Transform.
b = dct(a, mpad);
if m > 1 & n > 1, b = dct(b.', npad).'; end
function a = idct(b,n)
%IDCT Inverse discrete cosine transform.
%
% X = IDCT(Y) inverts the DCT transform, returning the original
% vector if Y was obtained using Y = DCT(X).
%
% X = IDCT(Y,N) pads or truncates the vector Y to length N
% before transforming.
%
% If Y is a matrix, the IDCT operation is applied to each
% column.
%
% See also FFT,IFFT,DCT.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 5.12.4.1 $ $Date: 2003/01/26 05:59:37 $
% References:
% 1) A. K. Jain, "Fundamentals of Digital Image
% Processing", pp. 150-153.
% 2) Wallace, "The JPEG Still Picture Compression Standard",
% Communications of the ACM, April 1991.
% checknargin(1,2,nargin,mfilename);
if ~isa(b, 'double')
b = double(b);
end
if min(size(b))==1
if size(b,2)>1
do_trans = 1;
else
do_trans = 0;
end
b = b(:);
else
do_trans = 0;
end
if nargin==1,
n = size(b,1);
end
m = size(b,2);
% Pad or truncate b if necessary
if size(b,1)<n,
bb = zeros(n,m);
bb(1:size(b,1),:) = b;
else
bb = b(1:n,:);
end
if rem(n,2)==1 | ~isreal(b), % odd case
% Form intermediate even-symmetric matrix.
ww = sqrt(2*n) * exp(j*(0:n-1)*pi/(2*n)).';
ww(1) = ww(1) * sqrt(2);
W = ww(:,ones(1,m));
yy = zeros(2*n,m);
yy(1:n,:) = W.*bb;
yy(n+2:n+n,:) = -j*W(2:n,:).*flipud(bb(2:n,:));
y = ifft(yy);
% Extract inverse DCT
a = y(1:n,:);
else % even case
% Compute precorrection factor
ww = sqrt(2*n) * exp(j*pi*(0:n-1)/(2*n)).';
ww(1) = ww(1)/sqrt(2);
W = ww(:,ones(1,m));
% Compute x tilde using equation (5.93) in Jain
y = ifft(W.*bb);
% Re-order elements of each column according to equations (5.93) and
% (5.94) in Jain
a = zeros(n,m);
a(1:2:n,:) = y(1:n/2,:);
a(2:2:n,:) = y(n:-1:n/2+1,:);
end
if isreal(b), a = real(a); end
if do_trans, a = a.'; end
function a = idct2(arg1,mrows,ncols)
%IDCT2 Compute 2-D inverse discrete cosine transform.
% B = IDCT2(A) returns the two-dimensional inverse discrete
% cosine transform of A.
%
% B = IDCT2(A,[M N]) or B = IDCT2(A,M,N) pads A with zeros (or
% truncates A) to create a matrix of size M-by-N before
% transforming.
%
% For any A, IDCT2(DCT2(A)) equals A to within roundoff error.
%
% The discrete cosine transform is often used for image
% compression applications.
%
% Class Support
% -------------
% The input matrix A can be of class double or of any
% numeric class. The output matrix B is of class double.
%
% See also DCT2, DCTMTX, FFT2, IFFT2.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 5.17.4.1 $ $Date: 2003/01/26 05:55:39 $
% References:
% 1) A. K. Jain, "Fundamentals of Digital Image
% Processing", pp. 150-153.
% 2) Wallace, "The JPEG Still Picture Compression Standard",
% Communications of the ACM, April 1991.
% checknargin(1,3,nargin,mfilename);
[m, n] = size(arg1);
% Basic algorithm.
if (nargin == 1),
if (m > 1) & (n > 1),
a = idct(idct(arg1).').';
return;
else
mrows = m;
ncols = n;
end
end
% Padding for vector input.
b = arg1;
if nargin==2,
ncols = mrows(2);
mrows = mrows(1);
end
mpad = mrows; npad = ncols;
if m == 1 & mpad > m, b(2, 1) = 0; m = 2; end
if n == 1 & npad > n, b(1, 2) = 0; n = 2; end
if m == 1, mpad = npad; npad = 1; end % For row vector.
% Transform.
a = idct(b, mpad);
if m > 1 & n > 1, a = idct(a.', npad).'; end
|
github
|
jacksky64/imageProcessing-master
|
dump_struct.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_misc/dump_struct.m
| 1,389 |
utf_8
|
746b6d65b8fc8c67e8cb806c235f5e6a
|
function fid = dump_struct(s,fid,header)
% dump_struct - dump the content of a struct to a file
%
% dump_struct(s,fid, header);
%
% Copyright (c) 2008 Gabriel Peyre
if nargin<3
header = '';
end
if isstr(fid)
fid = fopen(fid, 'a');
if fid<=0
error(['File ' fid ' does not exist.']);
end
end
if not(isempty(header))
fprintf(fid, '%s\n', header );
end
% central line (position of ':')
cl = 15;
if iscell(s)
for i=1:length(s)
fprintf(fid, '%s\n', convert_string(s{i},0) );
end
elseif isstruct(s)
s = orderfields(s);
f = fieldnames(s);
for i=1:length(f)
v = getfield(s,f{i});
fprintf(fid, '%s: %s\n', convert_string(f{i},cl), convert_string(v,0) );
end
else
error('Unknown type.');
end
if nargout==0
fclose(fid);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = convert_string(v,cl)
if nargin<2
cl = 15;
end
nmax = 10; % maximum of dumped string results
if isa(v, 'numeric')
% v = v(1);
s = [];
for i = 1:min(length(v(:)), nmax)
if mod(v,1)==0
s = [s int2str(v(i)) ' '];
else
s = [s num2str(v(i)) ' '];
end
end
if length(v(:))>nmax
s = [s '...'];
end
elseif isstr(v)
s = v;
else
s = '-';
end
% try to align on central line
d = cl - length(s);
if d>0
s = [repmat(' ',[1 d]) s];
end
|
github
|
jacksky64/imageProcessing-master
|
pad.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/pad.m
| 2,742 |
utf_8
|
9bf9d823661a04611d1004e631e3b34c
|
function Y=pad(varargin)
% PAD Pads matrix.
%
% Y = PAD(X,[Mi]) creates the matrix Y by expanding X and and
% padding the new elements with zeros. X will be expanded Mi
% elements in the directions -i and +i so that:
% size(Y) = size(X) + 2*[Mi]
%
% If Mi is scalar the same value will be used in all directions.
%
% Y = PAD(...,'e',E) will pad X with element E instead of zero.
%
% Y = PAD(X,[Mi],'a') performs an assimetric padding. If Mi is
% even assimetric padding will be the same as simmetric padding,
% except that the expansion in assim. mode will be half the one
% in simmetric mode. If Mi is odd, X will be expanded floor(Mi/2)
% elements in direction -i and ceil(Mi/2) elements in direction
% i. The size of Y in the assimetric mode will then be:
% size(Y) = size(X) + [Mi]
%
% Y = PAD(X,[Mi],[Ni]) will pad the matrix with Mi elements in
% direction i and with Ni elements in direction -i.
%
% Y = PAD(X,[Si], 'size') will pad X so that size(Y) = [Si].
% It`s necessary that [Si] > size(Y).
%
[X,M,N,E] = parse_inputs(varargin{:});
Y = E*ones(size(X)+M+N);
for i = 1 : length(M)
ind{i} = N(i)+1:N(i)+size(X,i);
end
Y(ind{:}) = X;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [X,M,N,E,S] = parse_inputs(varargin)
if nargin==0
error('Too few inputs!')
end
E = 0;
X = varargin{1};
if nargin > 1
M = varargin{2};
else
M = 1;
end
N = M;
flagN = 0;
flagA = 0;
Epos = -1;
for i = 3 : nargin
flag = 0;
if i == Epos
flag = 1;
elseif strcmp(varargin{i},'a')
if flagN
error('Assimetric mode cannot be used together with [Mi] and [Ni].')
end
M = ceil(M/2);
N = floor(N/2);
flag = 1;
flagA = 1;
elseif strcmp(varargin{i},'e')
E = varargin{i+1};
flag = 1;
Epos = i+1;
elseif strcmp(varargin{i},'size')
M = ceil( (varargin{2}-size(X))/2 );
N = floor( (varargin{2}-size(X))/2 );
if any(M<0) | any(N<0)
error('Cannot specify a size smaller than size(X).')
end
flag = 1;
flagN = 1;
if flagA
error('Cannot use assimetric mode and fix size.')
end
elseif flag == 0 & flagN == 0
N = varargin{i};
flagN = 1;
else
error('Too many inputs.')
end
end
if length(M)==1
M = M*ones(1,ndims(X));
end
if length(N)==1
N = N*ones(1,ndims(X));
end
if length(M)~=ndims(X) | length(N)~=ndims(X)
error('[Mi],[Ni] and [Si] must have length equal to ndims(X).')
end
if length(E)~=1
error('`E` must be a number.')
end
|
github
|
jacksky64/imageProcessing-master
|
roll.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/roll.m
| 2,119 |
utf_8
|
ae0c1da9cb4a28bee3b76a6360a1646a
|
function Y = roll(varargin)
% ROLL Rolls matrix elements.
% y = ROLL(x,[Ri]) rolls matrix x Ri elements in dimension i.
% The rolled matrix y is the same size as x. The last element
% in each dimension is repeated to fill blank places
%
% Example: ROLL([1 2 3 4],1) = [1 1 2 3]
% ROLL([1 2 3 4], -1) = [2 3 4 4]
% ROLL([1 2 3 4] [1 1 2 3]
% [5 6 7 8] = [1 1 2 3]
% [9 10 11 12],[1 1]) [5 5 6 7]
%
% If ndims(x)>1, ROLL(x,N) == ROLL(x,N*ones(1,ndims(x)))
%
% ROLL(x,[Ri],'rot') rotates the elements instead of
% discarding them.
% Example: ROLL([1 2 3 4],1,'rot') = [4 1 2 3]
%
[X,R,ROT] = parse_inputs(varargin{:});
Y = zeros(size(X));
ind = cell(length(R),1);
if ROT == 1 % rotate elements
R = mod(abs(R),size(X)).*sign(R); % Eliminates complete rotations
for i = 1 : length(R)
if R(i) >= 0
ind{i} = [size(X,i)-R(i)+1:size(X,i) 1:size(X,i)-R(i)];
else
ind{i} = [1-R(i):size(X,i) 1:-R(i)];
end
end
else %% if ROT == 0
for i = 1 : length(R)
if R(i) >= 0
ind{i} = [repmat(1,[1 R(i)]) 1:size(X,i)-R(i)];
else
ind{i} = [1-R(i):size(X,i) repmat(size(X,i),[1 -R(i)])];
end
end
end
Y = X(ind{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [X,R,ROT] = parse_inputs(varargin)
ROT = 0;
switch nargin
case 0
error('Too few arguments')
case 1
X = varargin{1};
R = 1;
case 2
X = varargin{1};
R = varargin{2};
case 3
X = varargin{1};
R = varargin{2};
if strcmp(lower(varargin{3}),'rot')
ROT = 1;
else
error('Unknown parameter.')
end
case 4
error('Too many parameters')
end
if length(R)==1
R = R*ones(1,ndims(X));
if sum(size(X)>1)==1 % X is vector
R(size(X)==1) = 0;
end
end
if ndims(X) ~= length(R)
error('Incompatible dimensions!')
end
if any((size(X)-abs(R)-1)<0) & ROT == 0
error('Rolling bigger the matrix size')
return
end
|
github
|
jacksky64/imageProcessing-master
|
scale.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/scale.m
| 790 |
utf_8
|
ebfcd3e0683fa90f71268707ae2275e8
|
function y = scale(varargin)
% SCALE Scales matrix elements to a new range.
%
% y = SCALE(x,[min max]) scales the elements of matrix x to a new range
% defined by [min, max].
%
% y = SCALE(x) uses the default range = [0 1]
%
[x,Imin,Imax] = parse_inputs(varargin{:});
x = double(x);
M = max(x(:));
m = min(x(:));
y = ( (x-m)/(M-m) * (Imax-Imin) ) + Imin;
function [x,Imin,Imax] = parse_inputs(varargin)
switch nargin
case 0
error('Missing variable or function')
case 1
x = varargin{1};
Imax = 1;
Imin = 0;
case 2
x = varargin{1};
I = varargin{2};
if size(I,1) ~= 2 & size(I,2) ~= 2
error('Range must be a 1x2 vector')
end
Imin = I(1);
Imax = I(2);
case 3
error('Too many inputs')
end
|
github
|
jacksky64/imageProcessing-master
|
nfft.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/nfft.m
| 2,978 |
utf_8
|
1ebdbe2e01ff9f619d743df60c2b62b6
|
function y = nfft(varargin)
% NFFT Discrete Fourier transform.
% Y = NFFT(X) returns the Fourier transform of matrix X
% performing the visualization correction.
%
% Y = NFFT(X,MROWS) pads matrix X with zeros to size MROWS before transforming.
%
% Y = NFFT(X,MROWS,type) plots single sided(type='s') or double sided(type='d')
% frequency responce graphic (default = 's' - single sided)
%
% Y = NFFT(X,MROWS,type,'normalize') normalizes the magnitude of 'Y'.
%
% See also FFT, IFFT, FFT2, IFFT2, FFT, FFTSHIFT.
[X, MROWS, tipo, normalize] = parse_inputs(varargin{:});
R2 = floor(MROWS/2);
temp = fft(X, MROWS);
temp = temp(1:R2);
if tipo ==1
y= zeros(1,R2);
y=temp;
w1 = linspace(0,1,length(y));
else
y = zeros(1,2*R2);
y(R2+1:2*R2) = temp;
y(1:R2) = fliplr(temp);
w1 = linspace(-1,1,length(y));
end
abs_y = abs(y);
if normalize == 1
plot(w1,abs_y/max(abs_y));
ylabel('Normed Magnitude')
else
plot(w1,abs_y);
ylabel('Magnitude')
end
xlabel('Wn')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [X, MROWS, tipo, normalize] = parse_inputs(varargin)
switch nargin
case 0
error('Missing variable or function')
case 1
X = varargin{1};
MROWS = max(size(X,2),size(X,1));
tipo = 1;
normalize = 0;
case 2
X = varargin{1};
if strcmp(varargin{2},'normalize')
normalize = 1;
MROWS = max(size(X,2),size(X,1));
tipo = 1;
elseif strcmp(varargin{2},'s')
normalize = 0;
MROWS = max(size(X,2),size(X,1));
tipo = 1;
elseif strcmp(varargin{2},'d')
normalize = 0;
MROWS = max(size(X,2),size(X,1));
tipo = 0;
else
MROWS = varargin{2};
normalize = 0;
tipo = 1;
end
case 3
X = varargin{1};
flag=[0 0 0]; %[MROWS tipo normalize]
for ct = 2 : 3
if strcmp(varargin{ct},'normalize')
normalize = 1;
flag(3) = 1;
elseif strcmp(varargin{ct},'s')
tipo = 1;
flag(2) = 1;
elseif strcmp(varargin{ct},'d')
tipo = 0;
flag(2) = 1;
else
if flag(1) == 1;
error('Unknown parameter.')
return
elseif flag(1) == 0
flag(1) = 1;
end
MROWS = varargin{ct};
end
if flag(1) == 0
MROWS = max(size(X,2),size(X,1));
end
if flag(2) == 0
tipo = 1;
end
if flag(3) == 0
normalize = 0;
end
end
case 4
X = varargin{1};
MROWS = varargin{2};
if strcmp(varargin{3},'s')
tipo = 1;
elseif strcmp(varargin{3},'d')
tipo = 0;
else
error('Unknown parameter.')
return
end
if strcmp(varargin{4},'normalize')
normalize = 1;
else
error('Unknown parameter.')
return
end
case 5
error('Too many inputs')
end
|
github
|
jacksky64/imageProcessing-master
|
resize.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/resize.m
| 1,810 |
utf_8
|
219f27dea979cbaf2d6f9a7720824227
|
function Y = resize(varargin)
% RESIZE Resizes an matrix.
%
% Y = RESIZE(X,[R1 R2 ... Rn]) creates the matrix Y containing the elements of X
% which are at indexes m*Ri+1 (m = 0,1,2,..) at dimension i.
% Y = RESIZE(X, R) is the same as Y = RESIZE(X,[R R ... R]).
%
% Y = RESIZE(X,[L1 L2 ... Ln],'size') creates the image Y with Li elements on
% dimension i.
%
% ATENTION : No interpolation is done by this function. It only works with
% the matrix indexes.
%
% See also : RESIZE, RESIZE2
[X, R, FIXSIZE] = parse_inputs(varargin{:});
% Creates indexes list
if FIXSIZE
for dim = 1 : length(R)
ind{dim} = round( linspace(1,size(X,dim),R(dim)) );
end
else
for dim = 1 : length(R)
ind{dim} = round(1 : R(dim) : size(X,dim));
end
end
Y = X(ind{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [X, R, FIXSIZE] = parse_inputs(varargin)
if nargin < 2
error('Too few inputs.')
elseif nargin == 2
X = varargin{1};
R = varargin{2};
FIXSIZE = 0;
elseif nargin == 3;
X = varargin{1};
R = varargin{2};
FIXSIZE = 0;
if strcmp(varargin{3},'size')
FIXSIZE = 1;
else
error('Unknown parameter.')
end
else
error('Too many inputs.')
end
if length(R) == 1 & ndims(X) > 2
R(2:ndims(X)) = R(1);
end
if length(R)==1 & ndims(X)==2
if size(X,1)==1 & size(X,2)~=1
R = [1 R];
elseif size(X,1)~=1 & size(X,2)==1
R = [R 1];
else
R(2:ndims(X)) = R(1);
end
end
if ndims(X) > length(R)
error('Use length(R)=1 or length(R)>=ndims(X).')
end
if FIXSIZE == 1
if any(mod(R,1))
error('L must contain only integers.')
end
end
|
github
|
jacksky64/imageProcessing-master
|
vanherk.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/vanherk.m
| 4,841 |
utf_8
|
5b0cf60c12e2432af9a978d4bad7ff3b
|
function Y = vanherk(X,N,TYPE,varargin)
% VANHERK Fast max/min 1D filter
%
% Y = VANHERK(X,N,TYPE) performs the 1D max/min filtering of the row
% vector X using a N-length filter.
% The filtering type is defined by TYPE = 'max' or 'min'. This function
% uses the van Herk algorithm for min/max filters that demands only 3
% min/max calculations per element, independently of the filter size.
%
% If X is a 2D matrix, each row will be filtered separately.
%
% Y = VANHERK(...,'col') performs the filtering on the columns of X.
%
% Y = VANHERK(...,'shape') returns the subset of the filtering specified
% by 'shape' :
% 'full' - Returns the full filtering result,
% 'same' - (default) Returns the central filter area that is the
% same size as X,
% 'valid' - Returns only the area where no filter elements are outside
% the image.
%
% X can be uint8 or double. If X is uint8 the processing is quite faster, so
% dont't use X as double, unless it is really necessary.
%
% Initialization
[direc, shape] = parse_inputs(varargin{:});
if strcmp(direc,'col')
X = X';
end
if strcmp(TYPE,'max')
maxfilt = 1;
elseif strcmp(TYPE,'min')
maxfilt = 0;
else
error([ 'TYPE must be ' char(39) 'max' char(39) ' or ' char(39) 'min' char(39) '.'])
end
% Correcting X size
fixsize = 0;
addel = 0;
if mod(size(X,2),N) ~= 0
fixsize = 1;
addel = N-mod(size(X,2),N);
if maxfilt
f = [ X zeros(size(X,1), addel) ];
else
f = [X repmat(X(:,end),1,addel)];
end
else
f = X;
end
lf = size(f,2);
lx = size(X,2);
clear X
% Declaring aux. mat.
g = f;
h = g;
% Filling g & h (aux. mat.)
ig = 1:N:size(f,2);
ih = ig + N - 1;
g(:,ig) = f(:,ig);
h(:,ih) = f(:,ih);
if maxfilt
for i = 2 : N
igold = ig;
ihold = ih;
ig = ig + 1;
ih = ih - 1;
g(:,ig) = max(f(:,ig),g(:,igold));
h(:,ih) = max(f(:,ih),h(:,ihold));
end
else
for i = 2 : N
igold = ig;
ihold = ih;
ig = ig + 1;
ih = ih - 1;
g(:,ig) = min(f(:,ig),g(:,igold));
h(:,ih) = min(f(:,ih),h(:,ihold));
end
end
clear f
% Comparing g & h
if strcmp(shape,'full')
ig = [ N : 1 : lf ];
ih = [ 1 : 1 : lf-N+1 ];
if fixsize
if maxfilt
Y = [ g(:,1:N-1) max(g(:,ig), h(:,ih)) h(:,end-N+2:end-addel) ];
else
Y = [ g(:,1:N-1) min(g(:,ig), h(:,ih)) h(:,end-N+2:end-addel) ];
end
else
if maxfilt
Y = [ g(:,1:N-1) max(g(:,ig), h(:,ih)) h(:,end-N+2:end) ];
else
Y = [ g(:,1:N-1) min(g(:,ig), h(:,ih)) h(:,end-N+2:end) ];
end
end
elseif strcmp(shape,'same')
if fixsize
if addel > (N-1)/2
disp('hoi')
ig = [ N : 1 : lf - addel + floor((N-1)/2) ];
ih = [ 1 : 1 : lf-N+1 - addel + floor((N-1)/2)];
if maxfilt
Y = [ g(:,1+ceil((N-1)/2):N-1) max(g(:,ig), h(:,ih)) ];
else
Y = [ g(:,1+ceil((N-1)/2):N-1) min(g(:,ig), h(:,ih)) ];
end
else
ig = [ N : 1 : lf ];
ih = [ 1 : 1 : lf-N+1 ];
if maxfilt
Y = [ g(:,1+ceil((N-1)/2):N-1) max(g(:,ig), h(:,ih)) h(:,lf-N+2:lf-N+1+floor((N-1)/2)-addel) ];
else
Y = [ g(:,1+ceil((N-1)/2):N-1) min(g(:,ig), h(:,ih)) h(:,lf-N+2:lf-N+1+floor((N-1)/2)-addel) ];
end
end
else % not fixsize (addel=0, lf=lx)
ig = [ N : 1 : lx ];
ih = [ 1 : 1 : lx-N+1 ];
if maxfilt
Y = [ g(:,N-ceil((N-1)/2):N-1) max( g(:,ig), h(:,ih) ) h(:,lx-N+2:lx-N+1+floor((N-1)/2)) ];
else
Y = [ g(:,N-ceil((N-1)/2):N-1) min( g(:,ig), h(:,ih) ) h(:,lx-N+2:lx-N+1+floor((N-1)/2)) ];
end
end
elseif strcmp(shape,'valid')
ig = [ N : 1 : lx];
ih = [ 1 : 1: lx-N+1];
if maxfilt
Y = [ max( g(:,ig), h(:,ih) ) ];
else
Y = [ min( g(:,ig), h(:,ih) ) ];
end
end
if strcmp(direc,'col')
Y = Y';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [direc, shape] = parse_inputs(varargin)
direc = 'lin';
shape = 'same';
flag = [0 0]; % [dir shape]
for i = 1 : nargin
t = varargin{i};
if strcmp(t,'col') & flag(1) == 0
direc = 'col';
flag(1) = 1;
elseif strcmp(t,'full') & flag(2) == 0
shape = 'full';
flag(2) = 1;
elseif strcmp(t,'same') & flag(2) == 0
shape = 'same';
flag(2) = 1;
elseif strcmp(t,'valid') & flag(2) == 0
shape = 'valid';
flag(2) = 1;
else
error(['Too many / Unkown parameter : ' t ])
end
end
|
github
|
jacksky64/imageProcessing-master
|
grow.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/grow.m
| 2,699 |
utf_8
|
98b0c97617d00069de86838244622d83
|
function Y = grow(varargin)
%
% GROW Expands a matrix.
%
% Y = GROW(X,[M1 M2 ... Mn]) creates a matrix 'Y' by the expansion
% of the matrix 'x' of Mi elements on directions i e -i. The size
% of the new matrix 'Y' will be:
% size(Y) = size(x) + 2*[M]
%
% Example: X = [ 1 2 3; 4 5 6; 7 8 9]
% Y = GROW(X,[1 0])
% Y = [1 2 3; 1 2 3; 4 5 6; 7 8 9; 7 8 9]
%
% Y = GROW(X,[1 1])
% Y = [1 1 2 3 3; 1 1 2 3 3; 4 4 5 6 6; 7 7 8 9 9; 7 7 8 9 9]
%
% Y = GROW(X) uses as standard Mi = 1.
%
% If DIM(X)>1, GROW(X,N) = GROW(X,N*ones(DIM(x)))
%
% Y = GROW(X,[M], 'a') performs assimetric expansion. If Mi is even
% assimetric expansion is the same as simmetric expansion, execpt that
% the expansion in the assimetric mode will be half of the one in the
% simmetric mode. If Mi is odd, the matrix will be expanded ceil(Mi/2)
% elements in the -i direction and floor(Mi/2) in the i. The size of
% the expanded matrix will be:
% size(y) = size(X) + [M]
%
% [M] can contain negative integers. In this case, the outer elements
% of X will be discarded.
%
% See also ROLL, PAD, PADC, SHRINK.
%
[X, M, assimetric] = parse_inputs(varargin{:});
ind = cell(length(M),1);
if assimetric == 0
for i = 1 : length(M)
if M(i) >= 0
ind{i} = [repmat(1,[1 M(i)]) 1:size(X,i) repmat(size(X,i),[1 M(i)]) ];
else
ind{i} = 1+(-M(i)) : size(X,i)-(-M(i)); % using -M(i) to change sign
end
end
else % if not assimetric
for i = 1 : length(M)
if M(i) >= 0
ind{i} = [repmat(1,[1 ceil(M(i)/2)]) 1:size(X,i) repmat(size(X,i),[1 floor(M(i)/2)]) ];
else
ind{i} = 1+ceil(-M(i)/2) : size(X,i) - floor(-M(i)/2);
end
end
end
Y = X(ind{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [X,M,assimetric] = parse_inputs(varargin)
assimetric = 0;
switch nargin
case 0
error('Too few inputs!')
return
case 1
X = varargin{1};
M = ones(1,ndims(X));
case 2
X = varargin{1};
M = varargin{2};
if strcmp(M,'a')
M = ones(1,ndims(X));
assimetric = 1;
end
case 3
X = varargin{1};
M = varargin{2};
if ~strcmp('a', lower(varargin{3}))
error('Unknown parameter.');
end
assimetric = 1;
case 4
error('Too many inputs!')
return
end
if length(M)==1
if sum(size(X)>1)>1
M = M*ones(1,ndims(X));
elseif ndims(X)==2 & size(X,1)==1 & size(X,2)>1
M = [0 M];
elseif ndims(X)==2 & size(X,1)>1 & size(X,2)==1
M = [M 0];
end
end
if length(M)~=ndims(X)
error('Invalid dimensions')
end
|
github
|
jacksky64/imageProcessing-master
|
posterize.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/posterize.m
| 2,427 |
utf_8
|
a008b17a4f649fdcad5fbbd48d8dabde
|
function Y = posterize(varargin)
%
% POSTERIZE Reduces number of colors in an image.
%
% Y = POSTERIZE(X,N) creates the image Y by reduncing the number
% of different colors of X to N. The N color values of Y are evenly
% spaced in the same range as the values of X, however Y has only N
% different values. The values of X are rounded to the closet allowed
% values of Y.
%
% Y = POSTERIZE(X,N,[MIN MAX]) scales the N allowed values of Y so
% that they have the new [MIN MAX] range.
%
% Y = POSTERIZE(X,N,'noint') allows non integer values on Y. By default,
% the allowed values of Y are rounded to the closest integer so that they
% are evenly spaced. If using the 'noint' parameter this rounding is not
% performed.
%
% Y = POSTERIZE(X,N,'img') uses [MIN MAX] = [0 255], do not allow non
% integer values on Y and returns Y as UINT8.
%
% Y = POSTERIZE(x) uses N=64 and the 'img' parameter.
%
[x,N,I,frac] = parse_inputs(varargin{:});
if ~isa(x,'double')
x = double(x);
end
M = max(x(:));
m = min(x(:));
Y = round((x-m)/(M-m) * (N-1)); % Separetes in N levels from 0 toa N-1
Y = Y/(N-1); % Scales to 0 - 1
Y = Y*(I(2)-I(1))+I(1); % Scale to MIN, MAX
if frac==0
Y = round(Y); % Rounds
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [x,N,I,frac] = parse_inputs(varargin)
switch nargin
case 0
error('Too few inputs!')
return
case 1
x = varargin{1};
I = [0 255];
frac = 0;
N=64;
case 2
x = varargin{1};
if strcmp(varargin{2},'img')
I = [0 255];
frac = 0;
N=64;
else
N = varargin{2};
I = [min(x(:)) max(x(:))]; % ??? round ???
frac = 0;
end
case 3
x = varargin{1};
N = varargin{2};
if strcmp(varargin{3},'noint')
frac = 1;
I = [min(x(:)) max(x(:))];
elseif strcmp(varargin{3},'img')
I = [0 255];
frac = 0;
else
I = varargin{3};
frac = 0;
end
case 4
x = varargin{1};
N = varargin{2};
if strcmp(varargin{3},'noint')
frac = 1;
I = varargin{4};
else
if strcmp(varargin{4},'noint')
frac = 1;
I = varargin{3};
else
error('Invalid parameter!')
return
end
end
case 5
error('Too many inputs!')
return
end
|
github
|
jacksky64/imageProcessing-master
|
maxfilt2.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/maxfilt2.m
| 1,849 |
utf_8
|
45cc67fb2afee0dc77cfc7798629574f
|
function Y = maxfilt2(X,varargin)
% MAXFILT2 Two-dimensional max filter
%
% Y = MAXFILT2(X,[M N]) performs two-dimensional maximum
% filtering on the image X using an M-by-N window. The result
% Y contains the maximun value in the M-by-N neighborhood around
% each pixel in the original image.
% This function uses the van Herk algorithm for max filters.
%
% Y = MAXFILT2(X,M) is the same as Y = MAXFILT2(X,[M M])
%
% Y = MAXFILT2(X) uses a 3-by-3 neighborhood.
%
% Y = MAXFILT2(..., 'shape') returns a subsection of the 2D
% filtering specified by 'shape' :
% 'full' - Returns the full filtering result,
% 'same' - (default) Returns the central filter area that is the
% same size as X,
% 'valid' - Returns only the area where no filter elements are outside
% the image.
%
% See also : MINFILT2, VANHERK
%
% Initialization
[S, shape] = parse_inputs(varargin{:});
% filtering
Y = vanherk(X,S(1),'max',shape);
Y = vanherk(Y,S(2),'max','col',shape);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [S, shape] = parse_inputs(varargin)
shape = 'same';
flag = [0 0]; % size shape
for i = 1 : nargin
t = varargin{i};
if strcmp(t,'full') & flag(2) == 0
shape = 'full';
flag(2) = 1;
elseif strcmp(t,'same') & flag(2) == 0
shape = 'same';
flag(2) = 1;
elseif strcmp(t,'valid') & flag(2) == 0
shape = 'valid';
flag(2) = 1;
elseif flag(1) == 0
S = t;
flag(1) = 1;
else
error(['Too many / Unkown parameter : ' t ])
end
end
if flag(1) == 0
S = [3 3];
end
if length(S) == 1;
S(2) = S(1);
end
if length(S) ~= 2
error('Wrong window size parameter.')
end
|
github
|
jacksky64/imageProcessing-master
|
minfilt2.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/minfilt2.m
| 1,849 |
utf_8
|
99705de3e51cb81a30a34c274cf65366
|
function Y = minfilt2(X,varargin)
% MINFILT2 Two-dimensional min filter
%
% Y = MINFILT2(X,[M N]) performs two-dimensional minimum
% filtering on the image X using an M-by-N window. The result
% Y contains the minimun value in the M-by-N neighborhood around
% each pixel in the original image.
% This function uses the van Herk algorithm for min filters.
%
% Y = MINFILT2(X,M) is the same as Y = MINFILT2(X,[M M])
%
% Y = MINFILT2(X) uses a 3-by-3 neighborhood.
%
% Y = MINFILT2(..., 'shape') returns a subsection of the 2D
% filtering specified by 'shape' :
% 'full' - Returns the full filtering result,
% 'same' - (default) Returns the central filter area that is the
% same size as X,
% 'valid' - Returns only the area where no filter elements are outside
% the image.
%
% See also : MAXFILT2, VANHERK
%
% Initialization
[S, shape] = parse_inputs(varargin{:});
% filtering
Y = vanherk(X,S(1),'min',shape);
Y = vanherk(Y,S(2),'min','col',shape);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [S, shape] = parse_inputs(varargin)
shape = 'same';
flag = [0 0]; % size shape
for i = 1 : nargin
t = varargin{i};
if strcmp(t,'full') & flag(2) == 0
shape = 'full';
flag(2) = 1;
elseif strcmp(t,'same') & flag(2) == 0
shape = 'same';
flag(2) = 1;
elseif strcmp(t,'valid') & flag(2) == 0
shape = 'valid';
flag(2) = 1;
elseif flag(1) == 0
S = t;
flag(1) = 1;
else
error(['Too many / Unkown parameter : ' t ])
end
end
if flag(1) == 0
S = [3 3];
end
if length(S) == 1;
S(2) = S(1);
end
if length(S) ~= 2
error('Wrong window size parameter.')
end
|
github
|
jacksky64/imageProcessing-master
|
plotline.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/plotline.m
| 1,778 |
utf_8
|
44ac4c98d32432076d5d7b9c745300e3
|
function y = plotline(x,d,varargin)
% PLOTLINE Plots a vertical or horizontal line
%
% PLOTLINE(x,dir) plots a horizontal (dir='h') or vertical (dir='v')
% dotted line at position x on the current figure.
%
% PLOTLINE(x,dir,S) uses plots the line using the specified color and
% linestyle. S is a string containing one element from any or all the
% columns bellow (just like in the plot command).
%
% Colors: Styles:
% y yellow - solid
% m magenta : dotted
% c cyan -. dashdot
% r red -- dashed
% g green
% b blue
% w white
% k black
%
% PLOTLINE(...,'label') plots the value label x next to the line.
%
[S,lab] = parse_inputs(varargin{:});
h = ishold;
ax = axis;
hold on;
if strcmp(d,'h')
for i = 1 : length(x)
plot([ax(1) ax(2)], [x(i) x(i)], S)
if lab
text( (ax(1)+ax(2))/2, x(i), num2str(x(i)))
end
end
elseif strcmp(d,'v')
for i = 1 : length(x)
plot([x(i) x(i)], [ax(3) ax(4)], S)
if lab
text( x(i), (ax(3)+ax(4))/2, num2str(x(i)))
end
end
else
error('Unknow direction.')
end
if h
hold on;
else
hold off
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [S,lab] = parse_inputs(varargin)
S = [];
lab = -1;
for i = 1 : nargin
if strcmp('label',varargin{i}) & lab==-1
lab = 1;
elseif isempty(S)
S = varargin{i};
else
error('Too many parameters.')
end
end
if lab==-1
lab=0;
end
if isempty(S)
S='k:';
end
|
github
|
jacksky64/imageProcessing-master
|
nfft2.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/nfft2.m
| 2,714 |
utf_8
|
246579cf697dfb614364498b06c06386
|
function [varargout] = nfft2(varargin)
%
% NFFT2 Two-dimensional discrete Fourier Transform.
%
% Y = NFFT2(X) returns the two-dimensional Fourier transform of matrix X
% performing the visualization correction.
%
% Y = NFFT2(X,MROWS,NCOLS) pads matrix X with zeros to size MROWS-by-NCOLS
% before transforming.
%
% [Y,W1,W2] = NFFT2(X) returns also the normalized frequencies W1 and W2.
%
% NFFT2(X) makes the surf plot of NFFT2(X).
%
% Y = NFFT2(X,...,'normalize') normalizes the transform [0 - 1].
%
% See also FFT2, IFFT2, FFT, FFTSHIFT.
%
[X, MROWS, NCOLS, normalize] = parse_inputs(varargin{:});
R2 = floor(MROWS/2);
C2 = floor(NCOLS/2);
temp = fft2(X, MROWS, NCOLS);
%r = floor(size(X,1)/2);
%c = floor(size(X,2)/2);
%X = X(1:r, 1:c);
%Y = zeros(2*r, 2*c);
%Y(r+1:2*r, c+1:2*c) = X;
%Y(1:r, c+1:2*c) = flipud(X);
%Y(1:r, 1:c) = fliplr(Y(1:r,c+1:2*c));
%Y(r+1:2*r, 1:c) = fliplr(X);
Y = fft2fix(temp);
clear temp
abs_Y = abs(Y);
max_abs_Y = max(max(abs_Y));
if normalize == 1;
Y = Y/max_abs_Y;
end
switch nargout
case 0
[W1,W2]=freqspace(size(Y),'meshgrid');
if normalize == 0
surf(W1,W2,abs_Y)
zlabel('Magnitude');
else
surf(W1,W2,abs_Y/max_abs_Y)
zlabel('Normed Magnitude');
end
if prod(size(Y)) > 7500
shading interp
end
xlabel('Wn1');
ylabel('Wn2');
case 1
varargout(1) = {Y};
case 2
varargout(1) = {Y};
varargout(2) = {W1};
case 3
varargout(1) = {Y};
varargout(2) = {W1};
varargout(3) = {W2};
case 4
error('Incorrect number of output parameters!')
return
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [X, MROWS, NCOLS, normalize] = parse_inputs(varargin)
switch nargin
case 0
error('Missing variable or function')
case 1
X = varargin{1};
MROWS = size(X,1);
NCOLS = size(X,2);
normalize = 0;
case 2
X = varargin{1};
if strcmp(varargin{2},'normalize')
MROWS = size(X,1);
normalize = 1;
else
MROWS = varargin{2};
normalize = 0;
end
NCOLS = size(X,2);
case 3
X = varargin{1};
MROWS = varargin{2};
if strcmp(varargin{3},'normalize')
NCOLS = size(X,2);
normalize = 1;
else
NCOLS = varargin{2};
normalize = 0;
end
case 4
X = varargin{1};
MROWS = varargin{2};
NCOLS = varargin{3};
if strcmp('normalize', varargin{4})
normalize = 1;
else
error('Unknown parameter.')
return
end
case 5
error('Too many inputs')
end
|
github
|
jacksky64/imageProcessing-master
|
thomas.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/thomas.m
| 3,148 |
utf_8
|
4b9db75fb4b91a56471d767ec26e0adb
|
function x = thomas(varargin)
% THOMAS Solves a tridiagonal linear system
%
% x = THOMAS(A,d) solves a tridiagonal linear system using the very efficient
% Thomas Algorith. The vector x is the returned answer.
%
% A*x = d; / a1 b1 0 0 0 ... 0 \ / x1 \ / d1 \
% | c1 a2 b2 0 0 ... 0 | | x2 | | d2 |
% | 0 c2 a3 b3 0 ... 0 | x | x3 | = | d3 |
% | : : : : : : : | | x4 | | d4 |
% | 0 0 0 0 cn-2 an-1 bn-1 | | : | | : |
% \ 0 0 0 0 0 cn-1 an / \ xn / \ dn /
%
% - The matrix A must be strictly diagonally dominant for a stable solution.
% - This algorithm solves this system on (5n-4) multiplications/divisions and
% (3n-3) subtractions.
%
% x = THOMAS(a,b,c,d) where a is the diagonal, b is the upper diagonal, and c is
% the lower diagonal of A also solves A*x = d for x. Note that a is size n
% while b and c is size n-1.
% If size(a)=size(d)=[L C] and size(b)=size(c)=[L-1 C], THOMAS solves the C
% independent systems simultaneously.
%
%
% ATTENTION : No verification is done in order to assure that A is a tridiagonal matrix.
% If this function is used with a non tridiagonal matrix it will produce wrong results.
%
[a,b,c,d] = parse_inputs(varargin{:});
% Initialization
m = zeros(size(a));
l = zeros(size(c));
y = zeros(size(d));
n = size(a,1);
%1. LU decomposition ________________________________________________________________________________
%
% L = / 1 \ U = / m1 r1 \
% | l1 1 | | m2 r2 |
% | l2 1 | | m3 r3 |
% | : : : | | : : : |
% \ ln-1 1 / \ mn /
%
% ri = bi -> not necessary
m(1,:) = a(1,:);
y(1,:) = d(1,:); %2. Forward substitution (L*y=d, for y) ____________________________
for i = 2 : n
i_1 = i-1;
l(i_1,:) = c(i_1,:)./m(i_1,:);
m(i,:) = a(i,:) - l(i_1,:).*b(i_1,:);
y(i,:) = d(i,:) - l(i_1,:).*y(i_1,:); %2. Forward substitution (L*y=d, for y) ____________________________
end
%2. Forward substitution (L*y=d, for y) ______________________________________________________________
%y(1) = d(1);
%for i = 2 : n
% y(i,:) = d(i,:) - l(i-1,:).*y(i-1,:);
%end
%3. Backward substitutions (U*x=y, for x) ____________________________________________________________
x(n,:) = y(n,:)./m(n,:);
for i = n-1 : -1 : 1
x(i,:) = (y(i,:) - b(i,:).*x(i+1,:))./m(i,:);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [a,b,c,d] = parse_inputs(varargin)
if nargin == 4
a = varargin{1};
b = varargin{2};
c = varargin{3};
d = varargin{4};
elseif nargin == 2
A = sparse(varargin{1});
a = diag(A);
b = diag(A,1);
c = diag(A,-1);
d = varargin{2};
else
error('Incorrect number of inputs.')
end
|
github
|
jacksky64/imageProcessing-master
|
toggle.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/toggle.m
| 2,005 |
utf_8
|
96627feed2dcff5c420f0cdec2df8801
|
function Y = toggle(varargin)
% TOGGLE Matrix elements classification.
%
% Y = TOGGLE(X,X1,X2) generates the binary matrix Y by comparing
% each element of the matrix X with X1 and X2. If the element of
% X is closer to the element of X1, the corresponding element of
% Y will be zero. Otherwise if the element of X is closer to the
% one in X2, the corresponding Y element will be 1.
%
% Y = TOGGLE(X,X1,X2,'s') substitutes the output zeros for the
% coresponding elements of X1 and the output ones for the
% correspondig elements of X2.
%
% X1 and X2 must be the same size as X or scalars.
% If X, X1 and X2 are uint8, Y is uint8. Otherwise Y is double.
%
[X,X1,X2,S] = parse_inputs(varargin{:});
flag = 0;
if ~isa(X1,'double')
X1 = double(X1);
flag = flag + 1;
end
if ~isa(X2,'double')
X2 = double(X2);
flag = flag + 1;
end
Y = zeros(size(X));
d = abs(X-X1) > abs(X-X2);
if S==0
Y(d) = 1;
else
Y(d) = X2(d);
Y(~d) = X1(~d);
end
if flag==0
Y = uint8(Y);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [X,X1,X2,S] = parse_inputs(varargin)
switch nargin
case {0,1,2}
error('Too few inputs')
%case 1
% error('Missing variable or function')
%case 2
% error('Missing variable or function')
case 3
X = varargin{1};
X1 = varargin{2};
X2 = varargin{3};
S = 0;
case 4
X = varargin{1};
X1 = varargin{2};
X2 = varargin{3};
if strcmp('s',varargin{4})
S = 1;
else
error('Unknown parameter')
end
case 5
error('Too many inputs')
end
if size(X) ~= size(X1)
if length(X1)==1
X1 = X1*ones(size(X));
else
error('X1 must be the same size as X, or scalar');
end
end
if size(X) ~= size(X2)
if length(X2)==1
X2 = X2*ones(size(X));
else
error('X2 must be the same size as X, or scalar');
end
end
|
github
|
jacksky64/imageProcessing-master
|
colormapc.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/colormapc.m
| 1,625 |
utf_8
|
bf7ec4fa92fbcd4ccc19569cee309220
|
function Y = colormapc(varargin)
% COLORMAPC Circular colormap
%
% Y = COLORMAPC(T) creates a circular colormap type T. Circular colormaps
% are build so that the first and last colors are the same. This kind of
% colormap is useful for ploting angle images which have a circular behavior
% (0 = 2*pi).
%
% Y = COLORMAPC(T,N) creates the circular colormap T with size N.
%
% T = 1 -> blk, yel, red, gre, blk T = 2 -> cya, blu, mag, cya (cool)
% T = 3 -> blu, cya, gre, yel, blu T = 4 -> blk, red, yel, blk (hot)
%
switch nargin
case 0
T = 1;
N = 256;
case 1
T = varargin{1};
N = 256;
case 2
T = varargin{1};
N = varargin{2};
otherwise
error('Too many parameters.')
end
Y = zeros(N,3);
switch T
case 1
Y = cmapc(N,[0 0 0],[1 0 0],[1 1 0],[0 1 0]);
case 2
Y = cmapc(N,[0 1 1],[0 0 1],[1 0 1]);
case 3
Y = cmapc(N,[0 0 1],[0 1 1],[0 1 0],[1 1 0]);
case 4
Y = cmapc(N,[0 0 0],[1 0 0],[1 1 0]);
otherwise
error('Unknown colormap type.')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Y = cmapc(varargin)
%if nargin < 3
% error('Too few inputs.')
%end
N = varargin{1};
C = zeros(nargin,3);
C = cat(1,varargin{2:end},varargin{2});
Y = zeros(N,3);
ls = 1;
r = N/(size(C,1)-1); % Length of each color transition.
for i = 1 : size(C,1)-1
li = ls;
ls = round(i*r);
d = ls - li + 1;
Y(li:ls,:) = [linspace(C(i,1),C(i+1,1),d); linspace(C(i,2),C(i+1,2),d); linspace(C(i,3),C(i+1,3),d)]';
end
|
github
|
jacksky64/imageProcessing-master
|
noise.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/noise.m
| 4,300 |
utf_8
|
462689c50cc2ff1e7f79053cede6d16b
|
function y = noise(varargin)
% NOISE Adds noise to an image.
%
% NOISE creates a new image by adding noise to the original image.
% NOISE can be used to any matrix (1D, 2D, 3D, nD)
%
% Noisetypes are:
% 'ag' : additive gaussian (default) 'au' : additive uniform
% 'mg' : multiplicative gaussian 'mu' : multiplicative uniform
% 'sp' : salt and pepper
%
% Additive noise sums an random value to the image value at each pixel,
% Multiplicative noise replaces a pixel value with an random value,
% Salt and Pepper noise replaces a pixel value with the maximum or minimum possible values.
%
% For 'ag' noisetype use: y = NOISE(x,'ag', variance, [incidence])
% where 'variance' is the variance of the gaussian noise added and the optional parameter
% 'incidence' is the percetual of pixels affected be the noise (default for additive noise=1).
% For a 50% incidence use 'incidence' = .5 and so on.
%
% For 'au' noisetype use : y = NOISE(x,'au', maximum, [incidence])
% where 'maximum' is the maximum value the uniform noise can achieve
%
% For 'mg' noisetype use : y = NOISE(x,'mg', incidence)
% For 'mu' noisetype use : y = NOISE(x,'mu', incidence)
% Multiplicative noisetypes require that the 'incidence' parameter. For this kind of noise
% the variance or the maximum (respectivelly for gaussian and uniform noisetypes) are allways
% set to the maximum image value.
%
% For 'sp' noisetype use : y = NOISE(x,'sp', incidence)
%
% The 'maximum' and 'variance' parameters can be set as percentual of the maximum - minimum image
% values by using these values as strings containg the percentual rate followed by the percent symbol.
% The 'incidence' can also be expressed as a pecentual in this same way
%
% Example: y = NOISE(x,'ag', '25%')
% y = NOISE(x,'mu', 10, .5) -> same as y = NOISE(x,'mu',10, '50%')
%
[u, noisetype, scale, incid] = parse_inputs(varargin{:});
if ~isa(u,'double')
u = double(u);
end
y = u;
n = zeros(size(u));
if incid == 1
m_incid = logical(ones(size(u)));
else
m_incid = rand(size(u));
m_incid = find(m_incid <= incid);
end
if strcmp(noisetype, 'ag')
n(m_incid) = scale*randn(size(m_incid));
y = u + n;
elseif strcmp(noisetype, 'au')
n(m_incid) = scale*rand(size(m_incid));
y = u + n;
elseif strcmp(noisetype, 'mg')
n(m_incid) = scale*randn(size(m_incid));
y(m_incid) = n(m_incid);
elseif strcmp(noisetype, 'mu')
n(m_incid) = scale*rand(size(m_incid));
y(m_incid) = n(m_incid);
elseif strcmp(noisetype, 'sp')
n(m_incid) = sign(randn(size(m_incid)));
umax = max(u(:));
umin = min(u(:));
salt = find(n==-1);
pepper = find(n==1);
y(salt) = umax;
y(pepper) = umin;
end
function [u, noisetype, scale, incid] = parse_inputs(varargin)
switch nargin
case 0
error('Too few inputs')
case 1
u = varargin{1};
noisetype = 'ag';
scale = double(max(u(:)));
incid = 1;
case 2
u = varargin{1};
if strmatch(varargin{2},['ag';'au'])
noisetype = varargin{2};
scale = double(max(u(:)));
incid = 1;
elseif strmatch(varargin{2},['mg'; 'mu'; 'sp'])
error('Incidence missing');
else
noisetype = 'ag';
scale = varargin{2};
incid = 1;
end
case 3
u = varargin{1};
if strmatch(varargin{2},['ag';'au'])
noisetype = varargin{2};
scale = varargin{3};
incid = 1;
elseif strmatch(varargin{2},['mg'; 'mu'; 'sp'])
noisetype = varargin{2};
scale = double(max(u(:)));
incid = varargin{3};
else
noisetype = 'ag';
scale = varargin{2};
incid = varargin{3};
end
case 4
u = varargin{1};
if strmatch(varargin{2},['ag';'au'])
noisetype = varargin{2};
scale = varargin{3};
incid = varargin{4};
else
error('Too many parameters')
end
otherwise
error('Too many parameters')
end
if findstr(scale,'%')
scale = ( double(max(u(:))) - double(min(u(:))) )*str2num(scale(1:end-1))/100;
end
if findstr(incid,'%')
incid = str2num(incid(1:end-1))/100;
end
|
github
|
jacksky64/imageProcessing-master
|
imagem.m
|
.m
|
imageProcessing-master/Matlab imaging/Extra/imagem.m
| 3,626 |
utf_8
|
1780eff1083db2a93964e4dc0cb295ca
|
function varargout = imagem(varargin)
% IMAGEM Displays image and marker.
%
% IMAGEM(X,M) displays the grayscale or RGB image X and superimposes the
% b/w image M to it. The image M is intended to be a marker image of
% some characteristics of X. X and M must have the same size.
%
% IMAGEM(X,M1,M2,..,Mn) superimposes each new image at a different color.
%
% IMAGEM(X,M1,M2,..,Mn,'color',C1,C2,..,Cn) uses the colors specified as
% a RGB color vector. Alternativelly its possible to pass colors as strings.
% The following color strings are accepted:
%
% 'r':red, 'g':green, 'b':blue, 'y':yellow,
% 'm':magenta, 'c':cyan, 'w':white, 'k':black
%
% Y = IMAGEM(...) returns the new superimposed image as an RGB image.
%
if nargout > 1
error('Too many outputs.')
end
[X, MARK, COLOR] = parse_inputs(varargin{:});
if isempty(MARK)
image(X)
if nargout == 1
varargout{1} = X;
end
return
end
if size(X,3) == 1 % normalizing image
xmax = max(X(:));
xmin = min(X(:));
if ~(isa(X,'uint8') | (xmax<=1 & xmin>=1))
X = (X-xmin)./(xmax-xmin);
end
X = repmat(X,[1 1 3]);
end
Y = mountim(X,MARK,COLOR); % Creates mounted image
if nargout == 1
varargout{1} = Y;
elseif nargout == 0
image(Y);
figure(gcf)
else
error('Too many outputs.')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [X, MARK, COLOR] = parse_inputs(varargin)
if nargin==0
error('Too few inputs')
elseif nargin==1
X = varargin{1};
MARK = [];
COLOR = [];
else
X = varargin{1};
flag = 0;
for i = 2 : nargin
if strcmp(varargin{i},'color')
MARK = varargin(2:i-1);
COLOR = varargin(i+1:end);
flag = 1;
break
end
end
if flag == 0
MARK = varargin(2:end);
COLOR = [];
end
sizechk(X,MARK{:}); % Checks if all images have the same size
if length(COLOR)~=length(MARK) & ~isempty(COLOR)
error('Number of image markers and colors must be equal.')
end
MARK = cat(3,MARK{:}); % Convert mark from cell to matrix
MARK = logical(uint8(MARK~=0));
COLOR = convcolor(COLOR);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sizechk(X,varargin)
S = size(X(:,:,1));
for i = 1 : nargin-1
if size(varargin{i},3) > 1
error('Marker images must be bidimensional.')
end
if size(varargin{i}) ~= S
error('All images must have the same size.')
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Y = mountim(X,MARK,COLOR)
if isempty(COLOR)
COLOR = [1 0 0;0 1 0;0 0 1; 1 1 0;1 0 1;0 1 1; .75 .25 0; .75 0 .25;.25 .75 0; .25 0 .75];
if isa(X,'uint8')
COLOR = 255*COLOR;
end
end
r = X(:,:,1); g = X(:,:,2); b = X(:,:,3);
for i = 1 : size(MARK,3)
j = mod(i-1,length(COLOR))+1;
r(MARK(:,:,i)) = COLOR(j,1);
g(MARK(:,:,i)) = COLOR(j,2);
b(MARK(:,:,i)) = COLOR(j,3);
end
Y = X;
Y(:,:,1) = r; Y(:,:,2) = g; Y(:,:,3) = b;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Y = convcolor(X)
COLOR = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 1 0 1; 0 1 1; 1 1 1; 0 0 0];
Y = zeros(length(X),3);
for i = 1 : length(X)
if ischar(X{i})
k = findstr('rgbymcwk', X{i});
Y(i,:) = COLOR(k,:);
else
Y(i,:) = X{i};
end
end
|
github
|
jacksky64/imageProcessing-master
|
sp3Filters.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/sp3Filters.m
| 17,188 |
utf_8
|
a3514d77e5a92b96d96197ebad343395
|
% Steerable pyramid filters. Transform described in:
%
% @INPROCEEDINGS{Simoncelli95b,
% TITLE = "The Steerable Pyramid: A Flexible Architecture for
% Multi-Scale Derivative Computation",
% AUTHOR = "E P Simoncelli and W T Freeman",
% BOOKTITLE = "Second Int'l Conf on Image Processing",
% ADDRESS = "Washington, DC", MONTH = "October", YEAR = 1995 }
%
% Filter kernel design described in:
%
%@INPROCEEDINGS{Karasaridis96,
% TITLE = "A Filter Design Technique for
% Steerable Pyramid Image Transforms",
% AUTHOR = "A Karasaridis and E P Simoncelli",
% BOOKTITLE = "ICASSP", ADDRESS = "Atlanta, GA",
% MONTH = "May", YEAR = 1996 }
% Eero Simoncelli, 6/96.
function [lo0filt,hi0filt,lofilt,bfilts,mtx,harmonics] = sp3Filters();
harmonics = [1 3];
mtx = [ ...
0.5000 0.3536 0 -0.3536
-0.0000 0.3536 0.5000 0.3536
0.5000 -0.3536 0 0.3536
-0.0000 0.3536 -0.5000 0.3536];
hi0filt = [
-4.0483998600E-4 -6.2596000498E-4 -3.7829999201E-5 8.8387000142E-4 1.5450799838E-3 1.9235999789E-3 2.0687500946E-3 2.0898699295E-3 2.0687500946E-3 1.9235999789E-3 1.5450799838E-3 8.8387000142E-4 -3.7829999201E-5 -6.2596000498E-4 -4.0483998600E-4
-6.2596000498E-4 -3.2734998967E-4 7.7435001731E-4 1.5874400269E-3 2.1750701126E-3 2.5626500137E-3 2.2892199922E-3 1.9755100366E-3 2.2892199922E-3 2.5626500137E-3 2.1750701126E-3 1.5874400269E-3 7.7435001731E-4 -3.2734998967E-4 -6.2596000498E-4
-3.7829999201E-5 7.7435001731E-4 1.1793200392E-3 1.4050999889E-3 2.2253401112E-3 2.1145299543E-3 3.3578000148E-4 -8.3368999185E-4 3.3578000148E-4 2.1145299543E-3 2.2253401112E-3 1.4050999889E-3 1.1793200392E-3 7.7435001731E-4 -3.7829999201E-5
8.8387000142E-4 1.5874400269E-3 1.4050999889E-3 1.2960999738E-3 -4.9274001503E-4 -3.1295299996E-3 -4.5751798898E-3 -5.1014497876E-3 -4.5751798898E-3 -3.1295299996E-3 -4.9274001503E-4 1.2960999738E-3 1.4050999889E-3 1.5874400269E-3 8.8387000142E-4
1.5450799838E-3 2.1750701126E-3 2.2253401112E-3 -4.9274001503E-4 -6.3222697936E-3 -2.7556000277E-3 5.3632198833E-3 7.3032598011E-3 5.3632198833E-3 -2.7556000277E-3 -6.3222697936E-3 -4.9274001503E-4 2.2253401112E-3 2.1750701126E-3 1.5450799838E-3
1.9235999789E-3 2.5626500137E-3 2.1145299543E-3 -3.1295299996E-3 -2.7556000277E-3 1.3962360099E-2 7.8046298586E-3 -9.3812197447E-3 7.8046298586E-3 1.3962360099E-2 -2.7556000277E-3 -3.1295299996E-3 2.1145299543E-3 2.5626500137E-3 1.9235999789E-3
2.0687500946E-3 2.2892199922E-3 3.3578000148E-4 -4.5751798898E-3 5.3632198833E-3 7.8046298586E-3 -7.9501636326E-2 -0.1554141641 -7.9501636326E-2 7.8046298586E-3 5.3632198833E-3 -4.5751798898E-3 3.3578000148E-4 2.2892199922E-3 2.0687500946E-3
2.0898699295E-3 1.9755100366E-3 -8.3368999185E-4 -5.1014497876E-3 7.3032598011E-3 -9.3812197447E-3 -0.1554141641 0.7303866148 -0.1554141641 -9.3812197447E-3 7.3032598011E-3 -5.1014497876E-3 -8.3368999185E-4 1.9755100366E-3 2.0898699295E-3
2.0687500946E-3 2.2892199922E-3 3.3578000148E-4 -4.5751798898E-3 5.3632198833E-3 7.8046298586E-3 -7.9501636326E-2 -0.1554141641 -7.9501636326E-2 7.8046298586E-3 5.3632198833E-3 -4.5751798898E-3 3.3578000148E-4 2.2892199922E-3 2.0687500946E-3
1.9235999789E-3 2.5626500137E-3 2.1145299543E-3 -3.1295299996E-3 -2.7556000277E-3 1.3962360099E-2 7.8046298586E-3 -9.3812197447E-3 7.8046298586E-3 1.3962360099E-2 -2.7556000277E-3 -3.1295299996E-3 2.1145299543E-3 2.5626500137E-3 1.9235999789E-3
1.5450799838E-3 2.1750701126E-3 2.2253401112E-3 -4.9274001503E-4 -6.3222697936E-3 -2.7556000277E-3 5.3632198833E-3 7.3032598011E-3 5.3632198833E-3 -2.7556000277E-3 -6.3222697936E-3 -4.9274001503E-4 2.2253401112E-3 2.1750701126E-3 1.5450799838E-3
8.8387000142E-4 1.5874400269E-3 1.4050999889E-3 1.2960999738E-3 -4.9274001503E-4 -3.1295299996E-3 -4.5751798898E-3 -5.1014497876E-3 -4.5751798898E-3 -3.1295299996E-3 -4.9274001503E-4 1.2960999738E-3 1.4050999889E-3 1.5874400269E-3 8.8387000142E-4
-3.7829999201E-5 7.7435001731E-4 1.1793200392E-3 1.4050999889E-3 2.2253401112E-3 2.1145299543E-3 3.3578000148E-4 -8.3368999185E-4 3.3578000148E-4 2.1145299543E-3 2.2253401112E-3 1.4050999889E-3 1.1793200392E-3 7.7435001731E-4 -3.7829999201E-5
-6.2596000498E-4 -3.2734998967E-4 7.7435001731E-4 1.5874400269E-3 2.1750701126E-3 2.5626500137E-3 2.2892199922E-3 1.9755100366E-3 2.2892199922E-3 2.5626500137E-3 2.1750701126E-3 1.5874400269E-3 7.7435001731E-4 -3.2734998967E-4 -6.2596000498E-4
-4.0483998600E-4 -6.2596000498E-4 -3.7829999201E-5 8.8387000142E-4 1.5450799838E-3 1.9235999789E-3 2.0687500946E-3 2.0898699295E-3 2.0687500946E-3 1.9235999789E-3 1.5450799838E-3 8.8387000142E-4 -3.7829999201E-5 -6.2596000498E-4 -4.0483998600E-4
];
lo0filt = [
-8.7009997515E-5 -1.3542800443E-3 -1.6012600390E-3 -5.0337001448E-4 2.5240099058E-3 -5.0337001448E-4 -1.6012600390E-3 -1.3542800443E-3 -8.7009997515E-5
-1.3542800443E-3 2.9215801042E-3 7.5227199122E-3 8.2244202495E-3 1.1076199589E-3 8.2244202495E-3 7.5227199122E-3 2.9215801042E-3 -1.3542800443E-3
-1.6012600390E-3 7.5227199122E-3 -7.0612900890E-3 -3.7694871426E-2 -3.2971370965E-2 -3.7694871426E-2 -7.0612900890E-3 7.5227199122E-3 -1.6012600390E-3
-5.0337001448E-4 8.2244202495E-3 -3.7694871426E-2 4.3813198805E-2 0.1811603010 4.3813198805E-2 -3.7694871426E-2 8.2244202495E-3 -5.0337001448E-4
2.5240099058E-3 1.1076199589E-3 -3.2971370965E-2 0.1811603010 0.4376249909 0.1811603010 -3.2971370965E-2 1.1076199589E-3 2.5240099058E-3
-5.0337001448E-4 8.2244202495E-3 -3.7694871426E-2 4.3813198805E-2 0.1811603010 4.3813198805E-2 -3.7694871426E-2 8.2244202495E-3 -5.0337001448E-4
-1.6012600390E-3 7.5227199122E-3 -7.0612900890E-3 -3.7694871426E-2 -3.2971370965E-2 -3.7694871426E-2 -7.0612900890E-3 7.5227199122E-3 -1.6012600390E-3
-1.3542800443E-3 2.9215801042E-3 7.5227199122E-3 8.2244202495E-3 1.1076199589E-3 8.2244202495E-3 7.5227199122E-3 2.9215801042E-3 -1.3542800443E-3
-8.7009997515E-5 -1.3542800443E-3 -1.6012600390E-3 -5.0337001448E-4 2.5240099058E-3 -5.0337001448E-4 -1.6012600390E-3 -1.3542800443E-3 -8.7009997515E-5
];
lofilt = [
-4.3500000174E-5 1.2078000145E-4 -6.7714002216E-4 -1.2434000382E-4 -8.0063997302E-4 -1.5970399836E-3 -2.5168000138E-4 -4.2019999819E-4 1.2619999470E-3 -4.2019999819E-4 -2.5168000138E-4 -1.5970399836E-3 -8.0063997302E-4 -1.2434000382E-4 -6.7714002216E-4 1.2078000145E-4 -4.3500000174E-5
1.2078000145E-4 4.4606000301E-4 -5.8146001538E-4 5.6215998484E-4 -1.3688000035E-4 2.3255399428E-3 2.8898599558E-3 4.2872801423E-3 5.5893999524E-3 4.2872801423E-3 2.8898599558E-3 2.3255399428E-3 -1.3688000035E-4 5.6215998484E-4 -5.8146001538E-4 4.4606000301E-4 1.2078000145E-4
-6.7714002216E-4 -5.8146001538E-4 1.4607800404E-3 2.1605400834E-3 3.7613599561E-3 3.0809799209E-3 4.1121998802E-3 2.2212199401E-3 5.5381999118E-4 2.2212199401E-3 4.1121998802E-3 3.0809799209E-3 3.7613599561E-3 2.1605400834E-3 1.4607800404E-3 -5.8146001538E-4 -6.7714002216E-4
-1.2434000382E-4 5.6215998484E-4 2.1605400834E-3 3.1757799443E-3 3.1846798956E-3 -1.7774800071E-3 -7.4316998944E-3 -9.0569201857E-3 -9.6372198313E-3 -9.0569201857E-3 -7.4316998944E-3 -1.7774800071E-3 3.1846798956E-3 3.1757799443E-3 2.1605400834E-3 5.6215998484E-4 -1.2434000382E-4
-8.0063997302E-4 -1.3688000035E-4 3.7613599561E-3 3.1846798956E-3 -3.5306399222E-3 -1.2604200281E-2 -1.8847439438E-2 -1.7508180812E-2 -1.6485679895E-2 -1.7508180812E-2 -1.8847439438E-2 -1.2604200281E-2 -3.5306399222E-3 3.1846798956E-3 3.7613599561E-3 -1.3688000035E-4 -8.0063997302E-4
-1.5970399836E-3 2.3255399428E-3 3.0809799209E-3 -1.7774800071E-3 -1.2604200281E-2 -2.0229380578E-2 -1.1091699824E-2 3.9556599222E-3 1.4385120012E-2 3.9556599222E-3 -1.1091699824E-2 -2.0229380578E-2 -1.2604200281E-2 -1.7774800071E-3 3.0809799209E-3 2.3255399428E-3 -1.5970399836E-3
-2.5168000138E-4 2.8898599558E-3 4.1121998802E-3 -7.4316998944E-3 -1.8847439438E-2 -1.1091699824E-2 2.1906599402E-2 6.8065837026E-2 9.0580143034E-2 6.8065837026E-2 2.1906599402E-2 -1.1091699824E-2 -1.8847439438E-2 -7.4316998944E-3 4.1121998802E-3 2.8898599558E-3 -2.5168000138E-4
-4.2019999819E-4 4.2872801423E-3 2.2212199401E-3 -9.0569201857E-3 -1.7508180812E-2 3.9556599222E-3 6.8065837026E-2 0.1445499808 0.1773651242 0.1445499808 6.8065837026E-2 3.9556599222E-3 -1.7508180812E-2 -9.0569201857E-3 2.2212199401E-3 4.2872801423E-3 -4.2019999819E-4
1.2619999470E-3 5.5893999524E-3 5.5381999118E-4 -9.6372198313E-3 -1.6485679895E-2 1.4385120012E-2 9.0580143034E-2 0.1773651242 0.2120374441 0.1773651242 9.0580143034E-2 1.4385120012E-2 -1.6485679895E-2 -9.6372198313E-3 5.5381999118E-4 5.5893999524E-3 1.2619999470E-3
-4.2019999819E-4 4.2872801423E-3 2.2212199401E-3 -9.0569201857E-3 -1.7508180812E-2 3.9556599222E-3 6.8065837026E-2 0.1445499808 0.1773651242 0.1445499808 6.8065837026E-2 3.9556599222E-3 -1.7508180812E-2 -9.0569201857E-3 2.2212199401E-3 4.2872801423E-3 -4.2019999819E-4
-2.5168000138E-4 2.8898599558E-3 4.1121998802E-3 -7.4316998944E-3 -1.8847439438E-2 -1.1091699824E-2 2.1906599402E-2 6.8065837026E-2 9.0580143034E-2 6.8065837026E-2 2.1906599402E-2 -1.1091699824E-2 -1.8847439438E-2 -7.4316998944E-3 4.1121998802E-3 2.8898599558E-3 -2.5168000138E-4
-1.5970399836E-3 2.3255399428E-3 3.0809799209E-3 -1.7774800071E-3 -1.2604200281E-2 -2.0229380578E-2 -1.1091699824E-2 3.9556599222E-3 1.4385120012E-2 3.9556599222E-3 -1.1091699824E-2 -2.0229380578E-2 -1.2604200281E-2 -1.7774800071E-3 3.0809799209E-3 2.3255399428E-3 -1.5970399836E-3
-8.0063997302E-4 -1.3688000035E-4 3.7613599561E-3 3.1846798956E-3 -3.5306399222E-3 -1.2604200281E-2 -1.8847439438E-2 -1.7508180812E-2 -1.6485679895E-2 -1.7508180812E-2 -1.8847439438E-2 -1.2604200281E-2 -3.5306399222E-3 3.1846798956E-3 3.7613599561E-3 -1.3688000035E-4 -8.0063997302E-4
-1.2434000382E-4 5.6215998484E-4 2.1605400834E-3 3.1757799443E-3 3.1846798956E-3 -1.7774800071E-3 -7.4316998944E-3 -9.0569201857E-3 -9.6372198313E-3 -9.0569201857E-3 -7.4316998944E-3 -1.7774800071E-3 3.1846798956E-3 3.1757799443E-3 2.1605400834E-3 5.6215998484E-4 -1.2434000382E-4
-6.7714002216E-4 -5.8146001538E-4 1.4607800404E-3 2.1605400834E-3 3.7613599561E-3 3.0809799209E-3 4.1121998802E-3 2.2212199401E-3 5.5381999118E-4 2.2212199401E-3 4.1121998802E-3 3.0809799209E-3 3.7613599561E-3 2.1605400834E-3 1.4607800404E-3 -5.8146001538E-4 -6.7714002216E-4
1.2078000145E-4 4.4606000301E-4 -5.8146001538E-4 5.6215998484E-4 -1.3688000035E-4 2.3255399428E-3 2.8898599558E-3 4.2872801423E-3 5.5893999524E-3 4.2872801423E-3 2.8898599558E-3 2.3255399428E-3 -1.3688000035E-4 5.6215998484E-4 -5.8146001538E-4 4.4606000301E-4 1.2078000145E-4
-4.3500000174E-5 1.2078000145E-4 -6.7714002216E-4 -1.2434000382E-4 -8.0063997302E-4 -1.5970399836E-3 -2.5168000138E-4 -4.2019999819E-4 1.2619999470E-3 -4.2019999819E-4 -2.5168000138E-4 -1.5970399836E-3 -8.0063997302E-4 -1.2434000382E-4 -6.7714002216E-4 1.2078000145E-4 -4.3500000174E-5
];
bfilts = [...
-8.1125000725E-4 4.4451598078E-3 1.2316980399E-2 1.3955879956E-2 1.4179450460E-2 1.3955879956E-2 1.2316980399E-2 4.4451598078E-3 -8.1125000725E-4 ...
3.9103501476E-3 4.4565401040E-3 -5.8724298142E-3 -2.8760801069E-3 8.5267601535E-3 -2.8760801069E-3 -5.8724298142E-3 4.4565401040E-3 3.9103501476E-3 ...
1.3462699717E-3 -3.7740699481E-3 8.2581602037E-3 3.9442278445E-2 5.3605638444E-2 3.9442278445E-2 8.2581602037E-3 -3.7740699481E-3 1.3462699717E-3 ...
7.4700999539E-4 -3.6522001028E-4 -2.2522680461E-2 -0.1105690673 -0.1768419296 -0.1105690673 -2.2522680461E-2 -3.6522001028E-4 7.4700999539E-4 ...
0.0000000000 0.0000000000 0.0000000000 0.0000000000 0.0000000000 0.0000000000 0.0000000000 0.0000000000 0.0000000000 ...
-7.4700999539E-4 3.6522001028E-4 2.2522680461E-2 0.1105690673 0.1768419296 0.1105690673 2.2522680461E-2 3.6522001028E-4 -7.4700999539E-4 ...
-1.3462699717E-3 3.7740699481E-3 -8.2581602037E-3 -3.9442278445E-2 -5.3605638444E-2 -3.9442278445E-2 -8.2581602037E-3 3.7740699481E-3 -1.3462699717E-3 ...
-3.9103501476E-3 -4.4565401040E-3 5.8724298142E-3 2.8760801069E-3 -8.5267601535E-3 2.8760801069E-3 5.8724298142E-3 -4.4565401040E-3 -3.9103501476E-3 ...
8.1125000725E-4 -4.4451598078E-3 -1.2316980399E-2 -1.3955879956E-2 -1.4179450460E-2 -1.3955879956E-2 -1.2316980399E-2 -4.4451598078E-3 8.1125000725E-4; ...
...
0.0000000000 -8.2846998703E-4 -5.7109999034E-5 4.0110000555E-5 4.6670897864E-3 8.0871898681E-3 1.4807609841E-2 8.6204400286E-3 -3.1221499667E-3 ...
8.2846998703E-4 0.0000000000 -9.7479997203E-4 -6.9718998857E-3 -2.0865600090E-3 2.3298799060E-3 -4.4814897701E-3 1.4917500317E-2 8.6204400286E-3 ...
5.7109999034E-5 9.7479997203E-4 0.0000000000 -1.2145539746E-2 -2.4427289143E-2 5.0797060132E-2 3.2785870135E-2 -4.4814897701E-3 1.4807609841E-2 ...
-4.0110000555E-5 6.9718998857E-3 1.2145539746E-2 0.0000000000 -0.1510555595 -8.2495503128E-2 5.0797060132E-2 2.3298799060E-3 8.0871898681E-3 ...
-4.6670897864E-3 2.0865600090E-3 2.4427289143E-2 0.1510555595 0.0000000000 -0.1510555595 -2.4427289143E-2 -2.0865600090E-3 4.6670897864E-3 ...
-8.0871898681E-3 -2.3298799060E-3 -5.0797060132E-2 8.2495503128E-2 0.1510555595 0.0000000000 -1.2145539746E-2 -6.9718998857E-3 4.0110000555E-5 ...
-1.4807609841E-2 4.4814897701E-3 -3.2785870135E-2 -5.0797060132E-2 2.4427289143E-2 1.2145539746E-2 0.0000000000 -9.7479997203E-4 -5.7109999034E-5 ...
-8.6204400286E-3 -1.4917500317E-2 4.4814897701E-3 -2.3298799060E-3 2.0865600090E-3 6.9718998857E-3 9.7479997203E-4 0.0000000000 -8.2846998703E-4 ...
3.1221499667E-3 -8.6204400286E-3 -1.4807609841E-2 -8.0871898681E-3 -4.6670897864E-3 -4.0110000555E-5 5.7109999034E-5 8.2846998703E-4 0.0000000000; ...
...
8.1125000725E-4 -3.9103501476E-3 -1.3462699717E-3 -7.4700999539E-4 0.0000000000 7.4700999539E-4 1.3462699717E-3 3.9103501476E-3 -8.1125000725E-4 ...
-4.4451598078E-3 -4.4565401040E-3 3.7740699481E-3 3.6522001028E-4 0.0000000000 -3.6522001028E-4 -3.7740699481E-3 4.4565401040E-3 4.4451598078E-3 ...
-1.2316980399E-2 5.8724298142E-3 -8.2581602037E-3 2.2522680461E-2 0.0000000000 -2.2522680461E-2 8.2581602037E-3 -5.8724298142E-3 1.2316980399E-2 ...
-1.3955879956E-2 2.8760801069E-3 -3.9442278445E-2 0.1105690673 0.0000000000 -0.1105690673 3.9442278445E-2 -2.8760801069E-3 1.3955879956E-2 ...
-1.4179450460E-2 -8.5267601535E-3 -5.3605638444E-2 0.1768419296 0.0000000000 -0.1768419296 5.3605638444E-2 8.5267601535E-3 1.4179450460E-2 ...
-1.3955879956E-2 2.8760801069E-3 -3.9442278445E-2 0.1105690673 0.0000000000 -0.1105690673 3.9442278445E-2 -2.8760801069E-3 1.3955879956E-2 ...
-1.2316980399E-2 5.8724298142E-3 -8.2581602037E-3 2.2522680461E-2 0.0000000000 -2.2522680461E-2 8.2581602037E-3 -5.8724298142E-3 1.2316980399E-2 ...
-4.4451598078E-3 -4.4565401040E-3 3.7740699481E-3 3.6522001028E-4 0.0000000000 -3.6522001028E-4 -3.7740699481E-3 4.4565401040E-3 4.4451598078E-3 ...
8.1125000725E-4 -3.9103501476E-3 -1.3462699717E-3 -7.4700999539E-4 0.0000000000 7.4700999539E-4 1.3462699717E-3 3.9103501476E-3 -8.1125000725E-4; ...
...
3.1221499667E-3 -8.6204400286E-3 -1.4807609841E-2 -8.0871898681E-3 -4.6670897864E-3 -4.0110000555E-5 5.7109999034E-5 8.2846998703E-4 0.0000000000 ...
-8.6204400286E-3 -1.4917500317E-2 4.4814897701E-3 -2.3298799060E-3 2.0865600090E-3 6.9718998857E-3 9.7479997203E-4 -0.0000000000 -8.2846998703E-4 ...
-1.4807609841E-2 4.4814897701E-3 -3.2785870135E-2 -5.0797060132E-2 2.4427289143E-2 1.2145539746E-2 0.0000000000 -9.7479997203E-4 -5.7109999034E-5 ...
-8.0871898681E-3 -2.3298799060E-3 -5.0797060132E-2 8.2495503128E-2 0.1510555595 -0.0000000000 -1.2145539746E-2 -6.9718998857E-3 4.0110000555E-5 ...
-4.6670897864E-3 2.0865600090E-3 2.4427289143E-2 0.1510555595 0.0000000000 -0.1510555595 -2.4427289143E-2 -2.0865600090E-3 4.6670897864E-3 ...
-4.0110000555E-5 6.9718998857E-3 1.2145539746E-2 0.0000000000 -0.1510555595 -8.2495503128E-2 5.0797060132E-2 2.3298799060E-3 8.0871898681E-3 ...
5.7109999034E-5 9.7479997203E-4 -0.0000000000 -1.2145539746E-2 -2.4427289143E-2 5.0797060132E-2 3.2785870135E-2 -4.4814897701E-3 1.4807609841E-2 ...
8.2846998703E-4 -0.0000000000 -9.7479997203E-4 -6.9718998857E-3 -2.0865600090E-3 2.3298799060E-3 -4.4814897701E-3 1.4917500317E-2 8.6204400286E-3 ...
0.0000000000 -8.2846998703E-4 -5.7109999034E-5 4.0110000555E-5 4.6670897864E-3 8.0871898681E-3 1.4807609841E-2 8.6204400286E-3 -3.1221499667E-3 ...
]';
|
github
|
jacksky64/imageProcessing-master
|
buildWpyr.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/buildWpyr.m
| 2,644 |
utf_8
|
e741b2037d9a1358d4de94580ebcc4bf
|
% [PYR, INDICES] = buildWpyr(IM, HEIGHT, FILT, EDGES)
%
% Construct a separable orthonormal QMF/wavelet pyramid on matrix (or vector) IM.
%
% HEIGHT (optional) specifies the number of pyramid levels to build. Default
% is maxPyrHt(IM,FILT). You can also specify 'auto' to use this value.
%
% FILT (optional) can be a string naming a standard filter (see
% namedFilter), or a vector which will be used for (separable)
% convolution. Filter can be of even or odd length, but should be symmetric.
% Default = 'qmf9'. EDGES specifies edge-handling, and
% defaults to 'reflect1' (see corrDn).
%
% PYR is a vector containing the N pyramid subbands, ordered from fine
% to coarse. INDICES is an Nx2 matrix containing the sizes of
% each subband. This is compatible with the MatLab Wavelet toolbox.
% Eero Simoncelli, 6/96, based on original lisp code from 1987.
function [pyr,pind] = buildWpyr(im, ht, filt, edges)
if (nargin < 1)
error('First argument (IM) is required');
end
%------------------------------------------------------------
%% OPTIONAL ARGS:
if (exist('filt') ~= 1)
filt = 'qmf9';
end
if (exist('edges') ~= 1)
edges= 'reflect1';
end
if isstr(filt)
filt = namedFilter(filt);
end
if ( (size(filt,1) > 1) & (size(filt,2) > 1) )
error('FILT should be a 1D filter (i.e., a vector)');
else
filt = filt(:);
end
hfilt = modulateFlip(filt);
% Stagger sampling if filter is odd-length:
if (mod(size(filt,1),2) == 0)
stag = 2;
else
stag = 1;
end
im_sz = size(im);
max_ht = maxPyrHt(im_sz, size(filt,1));
if ( (exist('ht') ~= 1) | (ht == 'auto') )
ht = max_ht;
else
if (ht > max_ht)
error(sprintf('Cannot build pyramid higher than %d levels.',max_ht));
end
end
if (ht <= 0)
pyr = im(:);
pind = im_sz;
else
if (im_sz(2) == 1)
lolo = corrDn(im, filt, edges, [2 1], [stag 1]);
hihi = corrDn(im, hfilt, edges, [2 1], [2 1]);
elseif (im_sz(1) == 1)
lolo = corrDn(im, filt', edges, [1 2], [1 stag]);
hihi = corrDn(im, hfilt', edges, [1 2], [1 2]);
else
lo = corrDn(im, filt, edges, [2 1], [stag 1]);
hi = corrDn(im, hfilt, edges, [2 1], [2 1]);
lolo = corrDn(lo, filt', edges, [1 2], [1 stag]);
lohi = corrDn(hi, filt', edges, [1 2], [1 stag]); % horizontal
hilo = corrDn(lo, hfilt', edges, [1 2], [1 2]); % vertical
hihi = corrDn(hi, hfilt', edges, [1 2], [1 2]); % diagonal
end
[npyr,nind] = buildWpyr(lolo, ht-1, filt, edges);
if ((im_sz(1) == 1) | (im_sz(2) == 1))
pyr = [hihi(:); npyr];
pind = [size(hihi); nind];
else
pyr = [lohi(:); hilo(:); hihi(:); npyr];
pind = [size(lohi); size(hilo); size(hihi); nind];
end
end
|
github
|
jacksky64/imageProcessing-master
|
reconLpyr.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/reconLpyr.m
| 2,049 |
utf_8
|
657b8012a1ed06b6573496855309b2ae
|
% RES = reconLpyr(PYR, INDICES, LEVS, FILT2, EDGES)
%
% Reconstruct image from Laplacian pyramid, as created by buildLpyr.
%
% PYR is a vector containing the N pyramid subbands, ordered from fine
% to coarse. INDICES is an Nx2 matrix containing the sizes of
% each subband. This is compatible with the MatLab Wavelet toolbox.
%
% LEVS (optional) should be a list of levels to include, or the string
% 'all' (default). The finest scale is number 1. The lowpass band
% corresponds to lpyrHt(INDICES)+1.
%
% FILT2 (optional) can be a string naming a standard filter (see
% namedFilter), or a vector which will be used for (separable)
% convolution. Default = 'binom5'. EDGES specifies edge-handling,
% and defaults to 'reflect1' (see corrDn).
% Eero Simoncelli, 6/96
function res = reconLpyr(pyr, ind, levs, filt2, edges)
if (nargin < 2)
error('First two arguments (PYR, INDICES) are required');
end
%%------------------------------------------------------------
%% DEFAULTS:
if (exist('levs') ~= 1)
levs = 'all';
end
if (exist('filt2') ~= 1)
filt2 = 'binom5';
end
if (exist('edges') ~= 1)
edges= 'reflect1';
end
%%------------------------------------------------------------
maxLev = 1+lpyrHt(ind);
if strcmp(levs,'all')
levs = [1:maxLev]';
else
if (any(levs > maxLev))
error(sprintf('Level numbers must be in the range [1, %d].', maxLev));
end
levs = levs(:);
end
if isstr(filt2)
filt2 = namedFilter(filt2);
end
filt2 = filt2(:);
res_sz = ind(1,:);
if any(levs > 1)
int_sz = [ind(1,1), ind(2,2)];
nres = reconLpyr( pyr(prod(res_sz)+1:size(pyr,1)), ...
ind(2:size(ind,1),:), levs-1, filt2, edges);
if (res_sz(1) == 1)
res = upConv(nres, filt2', edges, [1 2], [1 1], res_sz);
elseif (res_sz(2) == 1)
res = upConv(nres, filt2, edges, [2 1], [1 1], res_sz);
else
hi = upConv(nres, filt2, edges, [2 1], [1 1], int_sz);
res = upConv(hi, filt2', edges, [1 2], [1 1], res_sz);
end
else
res = zeros(res_sz);
end
if any(levs == 1)
res = res + pyrBand(pyr,ind,1);
end
|
github
|
jacksky64/imageProcessing-master
|
mkDisc.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/mkDisc.m
| 1,428 |
utf_8
|
c6acae0ac1aa738b7ef094eb2ac60f52
|
% IM = mkDisc(SIZE, RADIUS, ORIGIN, TWIDTH, VALS)
%
% Make a "disk" image. SIZE specifies the matrix size, as for
% zeros(). RADIUS (default = min(size)/4) specifies the radius of
% the disk. ORIGIN (default = (size+1)/2) specifies the
% location of the disk center. TWIDTH (in pixels, default = 2)
% specifies the width over which a soft threshold transition is made.
% VALS (default = [0,1]) should be a 2-vector containing the
% intensity value inside and outside the disk.
% Eero Simoncelli, 6/96.
function [res] = mkDisc(sz, rad, origin, twidth, vals)
if (nargin < 1)
error('Must pass at least a size argument');
end
sz = sz(:);
if (size(sz,1) == 1)
sz = [sz sz];
end
%------------------------------------------------------------
% OPTIONAL ARGS:
if (exist('rad') ~= 1)
rad = min(sz(1),sz(2))/4;
end
if (exist('origin') ~= 1)
origin = (sz+1)./2;
end
if (exist('twidth') ~= 1)
twidth = 2;
end
if (exist('vals') ~= 1)
vals = [1,0];
end
%------------------------------------------------------------
res = mkR(sz,1,origin);
if (abs(twidth) < realmin)
res = vals(2) + (vals(1) - vals(2)) * (res <= rad);
else
[Xtbl,Ytbl] = rcosFn(twidth, rad, [vals(1), vals(2)]);
res = pointOp(res, Ytbl, Xtbl(1), Xtbl(2)-Xtbl(1), 0);
%
% OLD interp1 VERSION:
% res = res(:);
% Xtbl(1) = min(res);
% Xtbl(size(Xtbl,2)) = max(res);
% res = reshape(interp1(Xtbl,Ytbl,res), sz(1), sz(2));
%
end
|
github
|
jacksky64/imageProcessing-master
|
spyrHigh.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/spyrHigh.m
| 189 |
utf_8
|
3132a747e0c7bf1879bb32e4d5fda257
|
% RES = spyrHigh(PYR, INDICES)
%
% Access the highpass residual band from a steerable pyramid.
% Eero Simoncelli, 6/96.
function res = spyrHigh(pyr,pind)
res = pyrBand(pyr, pind, 1);
|
github
|
jacksky64/imageProcessing-master
|
mkImpulse.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/mkImpulse.m
| 529 |
utf_8
|
cf6f3809cb123791501bb0e92845a0c6
|
% IM = mkImpulse(SIZE, ORIGIN, AMPLITUDE)
%
% Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar)
% containing a single non-zero entry, at position ORIGIN (defaults to
% ceil(size/2)), of value AMPLITUDE (defaults to 1).
% Eero Simoncelli, 6/96.
function [res] = mkImpulse(sz, origin, amplitude)
sz = sz(:)';
if (size(sz,2) == 1)
sz = [sz sz];
end
if (exist('origin') ~= 1)
origin = ceil(sz/2);
end
if (exist('amplitude') ~= 1)
amplitude = 1;
end
res = zeros(sz);
res(origin(1),origin(2)) = amplitude;
|
github
|
jacksky64/imageProcessing-master
|
rconv2.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/rconv2.m
| 1,435 |
utf_8
|
da3a54d6c7b1ac17c78eab0a4a7648d9
|
% RES = RCONV2(MTX1, MTX2, CTR)
%
% Convolution of two matrices, with boundaries handled via reflection
% about the edge pixels. Result will be of size of LARGER matrix.
%
% The origin of the smaller matrix is assumed to be its center.
% For even dimensions, the origin is determined by the CTR (optional)
% argument:
% CTR origin
% 0 DIM/2 (default)
% 1 (DIM/2)+1
% Eero Simoncelli, 6/96.
function c = rconv2(a,b,ctr)
if (exist('ctr') ~= 1)
ctr = 0;
end
if (( size(a,1) >= size(b,1) ) & ( size(a,2) >= size(b,2) ))
large = a; small = b;
elseif (( size(a,1) <= size(b,1) ) & ( size(a,2) <= size(b,2) ))
large = b; small = a;
else
error('one arg must be larger than the other in both dimensions!');
end
ly = size(large,1);
lx = size(large,2);
sy = size(small,1);
sx = size(small,2);
%% These values are one less than the index of the small mtx that falls on
%% the border pixel of the large matrix when computing the first
%% convolution response sample:
sy2 = floor((sy+ctr-1)/2);
sx2 = floor((sx+ctr-1)/2);
% pad with reflected copies
clarge = [
large(sy-sy2:-1:2,sx-sx2:-1:2), large(sy-sy2:-1:2,:), ...
large(sy-sy2:-1:2,lx-1:-1:lx-sx2); ...
large(:,sx-sx2:-1:2), large, large(:,lx-1:-1:lx-sx2); ...
large(ly-1:-1:ly-sy2,sx-sx2:-1:2), ...
large(ly-1:-1:ly-sy2,:), ...
large(ly-1:-1:ly-sy2,lx-1:-1:lx-sx2) ];
c = conv2(clarge,small,'valid');
|
github
|
jacksky64/imageProcessing-master
|
mkR.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/mkR.m
| 775 |
utf_8
|
504bc90f67c72730edc4a9d86630bdf2
|
% IM = mkR(SIZE, EXPT, ORIGIN)
%
% Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar)
% containing samples of a radial ramp function, raised to power EXPT
% (default = 1), with given ORIGIN (default = (size+1)/2, [1 1] =
% upper left). All but the first argument are optional.
% Eero Simoncelli, 6/96.
function [res] = mkR(sz, expt, origin)
sz = sz(:);
if (size(sz,1) == 1)
sz = [sz,sz];
end
% -----------------------------------------------------------------
% OPTIONAL args:
if (exist('expt') ~= 1)
expt = 1;
end
if (exist('origin') ~= 1)
origin = (sz+1)/2;
end
% -----------------------------------------------------------------
[xramp,yramp] = meshgrid( [1:sz(2)]-origin(2), [1:sz(1)]-origin(1) );
res = (xramp.^2 + yramp.^2).^(expt/2);
|
github
|
jacksky64/imageProcessing-master
|
blur.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/blur.m
| 1,731 |
utf_8
|
a2dc57fdfe85f98549b2f7ddf721c298
|
% RES = blur(IM, LEVELS, FILT)
%
% Blur an image, by filtering and downsampling LEVELS times
% (default=1), followed by upsampling and filtering LEVELS times. The
% blurring is done with filter kernel specified by FILT (default =
% 'binom5'), which can be a string (to be passed to namedFilter), a
% vector (applied separably as a 1D convolution kernel in X and Y), or
% a matrix (applied as a 2D convolution kernel). The downsampling is
% always by 2 in each direction.
% Eero Simoncelli, 3/04.
function res = blur(im, nlevs, filt)
%------------------------------------------------------------
%% OPTIONAL ARGS:
if (exist('nlevs') ~= 1)
nlevs = 1;
end
if (exist('filt') ~= 1)
filt = 'binom5';
end
%------------------------------------------------------------
if isstr(filt)
filt = namedFilter(filt);
end
filt = filt/sum(filt(:));
if nlevs > 0
if (any(size(im)==1))
if (~any(size(filt)==1))
error('Cant apply 2D filter to 1D signal');
end
if (size(im,2)==1)
filt = filt(:);
else
filt = filt(:)';
end
in = corrDn(im,filt,'reflect1',(size(im)~=1)+1);
out = blur(in, nlevs-1, filt);
res = upConv(out, filt, 'reflect1', (size(im)~=1)+1, [1 1], size(im));
elseif (any(size(filt)==1))
filt = filt(:);
in = corrDn(im,filt,'reflect1',[2 1]);
in = corrDn(in,filt','reflect1',[1 2]);
out = blur(in, nlevs-1, filt);
res = upConv(out, filt', 'reflect1', [1 2], [1 1], [size(out,1),size(im,2)]);
res = upConv(res, filt, 'reflect1', [2 1], [1 1], size(im));
else
in = corrDn(im,filt,'reflect1',[2 2]);
out = blur(in, nlevs-1, filt);
res = upConv(out, filt, 'reflect1', [2 2], [1 1], size(im));
end
else
res = im;
end
|
github
|
jacksky64/imageProcessing-master
|
pyrBand.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/pyrBand.m
| 395 |
utf_8
|
39c1e3772426a1362119d302d9767a24
|
% RES = pyrBand(PYR, INDICES, BAND_NUM)
%
% Access a subband from a pyramid (gaussian, laplacian, QMF/wavelet,
% or steerable). Subbands are numbered consecutively, from finest
% (highest spatial frequency) to coarsest (lowest spatial frequency).
% Eero Simoncelli, 6/96.
function res = pyrBand(pyr, pind, band)
res = reshape( pyr(pyrBandIndices(pind,band)), pind(band,1), pind(band,2) );
|
github
|
jacksky64/imageProcessing-master
|
kurt2.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/kurt2.m
| 551 |
utf_8
|
cd20c1a5155cba8de454011552ec4f2a
|
% K = KURT2(MTX,MEAN,VAR)
%
% Sample kurtosis (fourth moment divided by squared variance)
% of a matrix. Kurtosis of a Gaussian distribution is 3.
% MEAN (optional) and VAR (optional) make the computation faster.
% Eero Simoncelli, 6/96.
function res = kurt2(mtx, mn, v)
if (exist('mn') ~= 1)
mn = mean(mean(mtx));
end
if (exist('v') ~= 1)
v = var2(mtx,mn);
end
if (isreal(mtx))
res = mean(mean(abs(mtx-mn).^4)) / (v^2);
else
res = mean(mean(real(mtx-mn).^4)) / (real(v)^2) + ...
i*mean(mean(imag(mtx-mn).^4)) / (imag(v)^2);
end
|
github
|
jacksky64/imageProcessing-master
|
buildSpyr.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/buildSpyr.m
| 2,064 |
utf_8
|
b0caf60e63a52aa734956dd74ea39f95
|
% [PYR, INDICES, STEERMTX, HARMONICS] = buildSpyr(IM, HEIGHT, FILTFILE, EDGES)
%
% Construct a steerable pyramid on matrix IM. Convolutions are
% done with spatial filters.
%
% HEIGHT (optional) specifies the number of pyramid levels to build. Default
% is maxPyrHt(size(IM),size(FILT)).
% You can also specify 'auto' to use this value.
%
% FILTFILE (optional) should be a string referring to an m-file that
% returns the rfilters. (examples: 'sp0Filters', 'sp1Filters',
% 'sp3Filters','sp5Filters'. default = 'sp1Filters'). EDGES specifies
% edge-handling, and defaults to 'reflect1' (see corrDn).
%
% PYR is a vector containing the N pyramid subbands, ordered from fine
% to coarse. INDICES is an Nx2 matrix containing the sizes of
% each subband. This is compatible with the MatLab Wavelet toolbox.
% See the function STEER for a description of STEERMTX and HARMONICS.
% Eero Simoncelli, 6/96.
% See http://www.cis.upenn.edu/~eero/steerpyr.html for more
% information about the Steerable Pyramid image decomposition.
function [pyr,pind,steermtx,harmonics] = buildSpyr(im, ht, filtfile, edges)
%-----------------------------------------------------------------
%% DEFAULTS:
if (exist('filtfile') ~= 1)
filtfile = 'sp1Filters';
end
if (exist('edges') ~= 1)
edges= 'reflect1';
end
if (isstr(filtfile) & (exist(filtfile) == 2))
[lo0filt,hi0filt,lofilt,bfilts,steermtx,harmonics] = eval(filtfile);
else
fprintf(1,'\nUse buildSFpyr for pyramids with arbitrary numbers of orientation bands.\n');
error('FILTFILE argument must be the name of an M-file containing SPYR filters.');
end
max_ht = maxPyrHt(size(im), size(lofilt,1));
if ( (exist('ht') ~= 1) | (ht == 'auto') )
ht = max_ht;
else
if (ht > max_ht)
error(sprintf('Cannot build pyramid higher than %d levels.',max_ht));
end
end
%-----------------------------------------------------------------
hi0 = corrDn(im, hi0filt, edges);
lo0 = corrDn(im, lo0filt, edges);
[pyr,pind] = buildSpyrLevs(lo0, ht, lofilt, bfilts, edges);
pyr = [hi0(:) ; pyr];
pind = [size(hi0); pind];
|
github
|
jacksky64/imageProcessing-master
|
setPyrBand.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/setPyrBand.m
| 1,049 |
utf_8
|
76554eb735e969097a4723a508facd37
|
% NEWPYR = setPyrBand(PYR, INDICES, NEWBAND, BAND_NUM)
%
% Insert an image (BAND) into a pyramid (gaussian, laplacian, QMF/wavelet,
% or steerable). Subbands are numbered consecutively, from finest
% (highest spatial frequency) to coarsest (lowest spatial frequency).
% Eero Simoncelli, 1/03.
function pyr = setPyrBand(pyr, pind, band, bandNum)
%% Check: PIND a valid index matrix?
if ( ~(ndims(pind) == 2) | ~(size(pind,2) == 2) | ~all(pind==round(pind)) )
pind
error('pyrTools:badArg',...
'PIND argument is not an Nbands X 2 matrix of integers');
end
%% Check: PIND consistent with size of PYR?
if ( length(pyr) ~= sum(prod(pind,2)) )
error('pyrTools:badPyr',...
'Pyramid data vector length is inconsistent with index matrix PIND');
end
%% Check: size of BAND consistent with desired BANDNUM?
if (~all(size(band) == pind(bandNum,:)))
size(band)
pind(bandNum,:)
error('pyrTools:badArg',...
'size of BAND to be inserted is inconsistent with BAND_NUM');
end
pyr(pyrBandIndices(pind,bandNum)) = vectify(band);
|
github
|
jacksky64/imageProcessing-master
|
var2.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/var2.m
| 390 |
utf_8
|
de26727e055081aa670024c273f0e885
|
% V = VAR2(MTX,MEAN)
%
% Sample variance of a matrix.
% Passing MEAN (optional) makes the calculation faster.
function res = var2(mtx, mn)
if (exist('mn') ~= 1)
mn = mean2(mtx);
end
if (isreal(mtx))
res = sum(sum(abs(mtx-mn).^2)) / max((prod(size(mtx)) - 1),1);
else
res = sum(sum(real(mtx-mn).^2)) + i*sum(sum(imag(mtx-mn).^2));
res = res / max((prod(size(mtx)) - 1),1);
end
|
github
|
jacksky64/imageProcessing-master
|
reconSFpyrLevs.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/reconSFpyrLevs.m
| 2,016 |
utf_8
|
ff83a4f3d2f0927dcaa8851535e6b20a
|
% RESDFT = reconSFpyrLevs(PYR,INDICES,LOGRAD,XRCOS,YRCOS,ANGLE,NBANDS,LEVS,BANDS)
%
% Recursive function for reconstructing levels of a steerable pyramid
% representation. This is called by reconSFpyr, and is not usually
% called directly.
% Eero Simoncelli, 5/97.
function resdft = reconSFpyrLevs(pyr,pind,log_rad,Xrcos,Yrcos,angle,nbands,levs,bands);
lo_ind = nbands+1;
dims = pind(1,:);
ctr = ceil((dims+0.5)/2);
% log_rad = log_rad + 1;
Xrcos = Xrcos - log2(2); % shift origin of lut by 1 octave.
if any(levs > 1)
lodims = ceil((dims-0.5)/2);
loctr = ceil((lodims+0.5)/2);
lostart = ctr-loctr+1;
loend = lostart+lodims-1;
nlog_rad = log_rad(lostart(1):loend(1),lostart(2):loend(2));
nangle = angle(lostart(1):loend(1),lostart(2):loend(2));
if (size(pind,1) > lo_ind)
nresdft = reconSFpyrLevs( pyr(1+sum(prod(pind(1:lo_ind-1,:)')):size(pyr,1)),...
pind(lo_ind:size(pind,1),:), ...
nlog_rad, Xrcos, Yrcos, nangle, nbands,levs-1, bands);
else
nresdft = fftshift(fft2(pyrBand(pyr,pind,lo_ind)));
end
YIrcos = sqrt(abs(1.0 - Yrcos.^2));
lomask = pointOp(nlog_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0);
resdft = zeros(dims);
resdft(lostart(1):loend(1),lostart(2):loend(2)) = nresdft .* lomask;
else
resdft = zeros(dims);
end
if any(levs == 1)
lutsize = 1024;
Xcosn = pi*[-(2*lutsize+1):(lutsize+1)]/lutsize; % [-2*pi:pi]
order = nbands-1;
%% divide by sqrt(sum_(n=0)^(N-1) cos(pi*n/N)^(2(N-1)) )
const = (2^(2*order))*(factorial(order)^2)/(nbands*factorial(2*order));
Ycosn = sqrt(const) * (cos(Xcosn)).^order;
himask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1),0);
ind = 1;
for b = 1:nbands
if any(bands == b)
anglemask = pointOp(angle,Ycosn,Xcosn(1)+pi*(b-1)/nbands,Xcosn(2)-Xcosn(1));
band = reshape(pyr(ind:ind+prod(dims)-1), dims(1), dims(2));
banddft = fftshift(fft2(band));
resdft = resdft + (sqrt(-1))^(nbands-1) * banddft.*anglemask.*himask;
end
ind = ind + prod(dims);
end
end
|
github
|
jacksky64/imageProcessing-master
|
rcosFn.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/rcosFn.m
| 1,122 |
utf_8
|
36283e0a34f1baf7ea2c5e6cb23aab89
|
% [X, Y] = rcosFn(WIDTH, POSITION, VALUES)
%
% Return a lookup table (suitable for use by INTERP1)
% containing a "raised cosine" soft threshold function:
%
% Y = VALUES(1) + (VALUES(2)-VALUES(1)) *
% cos^2( PI/2 * (X - POSITION + WIDTH)/WIDTH )
%
% WIDTH is the width of the region over which the transition occurs
% (default = 1). POSITION is the location of the center of the
% threshold (default = 0). VALUES (default = [0,1]) specifies the
% values to the left and right of the transition.
% Eero Simoncelli, 7/96.
function [X, Y] = rcosFn(width,position,values)
%------------------------------------------------------------
% OPTIONAL ARGS:
if (exist('width') ~= 1)
width = 1;
end
if (exist('position') ~= 1)
position = 0;
end
if (exist('values') ~= 1)
values = [0,1];
end
%------------------------------------------------------------
sz = 256; %% arbitrary!
X = pi * [-sz-1:1] / (2*sz);
Y = values(1) + (values(2)-values(1)) * cos(X).^2;
% Make sure end values are repeated, for extrapolation...
Y(1) = Y(2);
Y(sz+3) = Y(sz+2);
X = position + (2*width/pi) * (X + pi/4);
|
github
|
jacksky64/imageProcessing-master
|
wpyrLev.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/wpyrLev.m
| 729 |
utf_8
|
77f309b76f98f3421e786fde4fe2d429
|
% [LEV,IND] = wpyrLev(PYR,INDICES,LEVEL)
%
% Access a level from a separable QMF/wavelet pyramid.
% Return as an SxB matrix, B = number of bands, S = total size of a band.
% Also returns an Bx2 matrix containing dimensions of the subbands.
% Eero Simoncelli, 6/96.
function [lev,ind] = wpyrLev(pyr,pind,level)
if ((pind(1,1) == 1) | (pind(1,2) ==1))
nbands = 1;
else
nbands = 3;
end
if ((level > wpyrHt(pind)) | (level < 1))
error(sprintf('Level number must be in the range [1, %d].', wpyrHt(pind)));
end
firstband = 1 + nbands*(level-1)
firstind = 1;
for l=1:firstband-1
firstind = firstind + prod(pind(l,:));
end
ind = pind(firstband:firstband+nbands-1,:);
lev = pyr(firstind:firstind+sum(prod(ind'))-1);
|
github
|
jacksky64/imageProcessing-master
|
binomialFilter.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/binomialFilter.m
| 309 |
utf_8
|
47b67219b2519bd65a435f3df318d41a
|
% KERNEL = binomialFilter(size)
%
% Returns a vector of binomial coefficients of order (size-1) .
% Eero Simoncelli, 2/97.
function [kernel] = binomialFilter(sz)
if (sz < 2)
error('size argument must be larger than 1');
end
kernel = [0.5 0.5]';
for n=1:sz-2
kernel = conv([0.5 0.5]', kernel);
end
|
github
|
jacksky64/imageProcessing-master
|
cconv2.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/cconv2.m
| 1,325 |
utf_8
|
8e564b623ba5cebd51e585eac6c66ba8
|
% RES = CCONV2(MTX1, MTX2, CTR)
%
% Circular convolution of two matrices. Result will be of size of
% LARGER vector.
%
% The origin of the smaller matrix is assumed to be its center.
% For even dimensions, the origin is determined by the CTR (optional)
% argument:
% CTR origin
% 0 DIM/2 (default)
% 1 (DIM/2)+1
% Eero Simoncelli, 6/96. Modified 2/97.
function c = cconv2(a,b,ctr)
if (exist('ctr') ~= 1)
ctr = 0;
end
if (( size(a,1) >= size(b,1) ) & ( size(a,2) >= size(b,2) ))
large = a; small = b;
elseif (( size(a,1) <= size(b,1) ) & ( size(a,2) <= size(b,2) ))
large = b; small = a;
else
error('one arg must be larger than the other in both dimensions!');
end
ly = size(large,1);
lx = size(large,2);
sy = size(small,1);
sx = size(small,2);
%% These values are the index of the small mtx that falls on the
%% border pixel of the large matrix when computing the first
%% convolution response sample:
sy2 = floor((sy+ctr+1)/2);
sx2 = floor((sx+ctr+1)/2);
% pad:
clarge = [ ...
large(ly-sy+sy2+1:ly,lx-sx+sx2+1:lx), large(ly-sy+sy2+1:ly,:), ...
large(ly-sy+sy2+1:ly,1:sx2-1); ...
large(:,lx-sx+sx2+1:lx), large, large(:,1:sx2-1); ...
large(1:sy2-1,lx-sx+sx2+1:lx), ...
large(1:sy2-1,:), ...
large(1:sy2-1,1:sx2-1) ];
c = conv2(clarge,small,'valid');
|
github
|
jacksky64/imageProcessing-master
|
reconSCFpyr.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/reconSCFpyr.m
| 4,475 |
utf_8
|
a0a6a06af4b5c9f7aa195bb8188fc754
|
% RES = reconSCFpyr(PYR, INDICES, LEVS, BANDS, TWIDTH)
%
% The inverse of buildSCFpyr: Reconstruct image from its complex steerable pyramid representation,
% in the Fourier domain.
%
% The image is reconstructed by forcing the complex subbands to be analytic
% (zero on half of the 2D Fourier plane, as they are supossed to be unless
% they have being modified), and reconstructing from the real part of those
% analytic subbands. That is equivalent to compute the Hilbert transforms of
% the imaginary parts of the subbands, average them with their real
% counterparts, and then reconstructing from the resulting real subbands.
%
% PYR is a vector containing the N pyramid subbands, ordered from fine
% to coarse. INDICES is an Nx2 matrix containing the sizes of
% each subband. This is compatible with the MatLab Wavelet toolbox.
%
% LEVS (optional) should be a list of levels to include, or the string
% 'all' (default). 0 corresonds to the residual highpass subband.
% 1 corresponds to the finest oriented scale. The lowpass band
% corresponds to number spyrHt(INDICES)+1.
%
% BANDS (optional) should be a list of bands to include, or the string
% 'all' (default). 1 = vertical, rest proceeding anti-clockwise.
%
% TWIDTH is the width of the transition region of the radial lowpass
% function, in octaves (default = 1, which gives a raised cosine for
% the bandpass filters).
% Javier Portilla, 7/04, basing on Eero Simoncelli's Matlab Pyrtools code
% and our common code on texture synthesis (textureSynthesis.m).
function res = reconSCFpyr(pyr, indices, levs, bands, twidth)
%%------------------------------------------------------------
%% DEFAULTS:
if ~exist('levs'),
levs = 'all';
end
if ~exist('bands')
bands = 'all';
end
if ~exist('twidth'),
twidth = 1;
elseif (twidth <= 0)
fprintf(1,'Warning: TWIDTH must be positive. Setting to 1.\n');
twidth = 1;
end
%%------------------------------------------------------------
pind = indices;
Nsc = log2(pind(1,1)/pind(end,1));
Nor = (size(pind,1)-2)/Nsc;
for nsc = 1:Nsc,
firstBnum = (nsc-1)*Nor+2;
%% Re-create analytic subbands
dims = pind(firstBnum,:);
ctr = ceil((dims+0.5)/2);
ang = mkAngle(dims, 0, ctr);
ang(ctr(1),ctr(2)) = -pi/2;
for nor = 1:Nor,
nband = (nsc-1)*Nor+nor+1;
ind = pyrBandIndices(pind,nband);
ch = pyrBand(pyr, pind, nband);
ang0 = pi*(nor-1)/Nor;
xang = mod(ang-ang0+pi, 2*pi) - pi;
amask = 2*(abs(xang) < pi/2) + (abs(xang) == pi/2);
amask(ctr(1),ctr(2)) = 1;
amask(:,1) = 1;
amask(1,:) = 1;
amask = fftshift(amask);
ch = ifft2(amask.*fft2(ch)); % "Analytic" version
%f = 1.000008; % With this factor the reconstruction SNR goes up around 6 dB!
f = 1;
ch = f*0.5*real(ch); % real part
pyr(ind) = ch;
end % nor
end % nsc
res = reconSFpyr(pyr, indices, levs, bands, twidth);
|
github
|
jacksky64/imageProcessing-master
|
buildSCFpyr.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/buildSCFpyr.m
| 2,713 |
utf_8
|
d94b4004138b50b6651511e8ba6ccb93
|
% [PYR, INDICES, STEERMTX, HARMONICS] = buildSCFpyr(IM, HEIGHT, ORDER, TWIDTH)
%
% This is a modified version of buildSFpyr, that constructs a
% complex-valued steerable pyramid using Hilbert-transform pairs
% of filters. Note that the imaginary parts will *not* be steerable.
%
% To reconstruct from this representation, either call reconSFpyr
% on the real part of the pyramid, *or* call reconSCFpyr which will
% use both real and imaginary parts (forcing analyticity).
%
% Description of this transform appears in: Portilla & Simoncelli,
% Int'l Journal of Computer Vision, 40(1):49-71, Oct 2000.
% Further information: http://www.cns.nyu.edu/~eero/STEERPYR/
% Original code: Eero Simoncelli, 5/97.
% Modified by Javier Portilla to return complex (quadrature pair) channels,
% 9/97.
function [pyr,pind,steermtx,harmonics] = buildSCFpyr(im, ht, order, twidth)
%-----------------------------------------------------------------
%% DEFAULTS:
max_ht = floor(log2(min(size(im)))) - 2;
if (exist('ht') ~= 1)
ht = max_ht;
else
if (ht > max_ht)
error(sprintf('Cannot build pyramid higher than %d levels.',max_ht));
end
end
if (exist('order') ~= 1)
order = 3;
elseif ((order > 15) | (order < 0))
fprintf(1,'Warning: ORDER must be an integer in the range [0,15]. Truncating.\n');
order = min(max(order,0),15);
else
order = round(order);
end
nbands = order+1;
if (exist('twidth') ~= 1)
twidth = 1;
elseif (twidth <= 0)
fprintf(1,'Warning: TWIDTH must be positive. Setting to 1.\n');
twidth = 1;
end
%-----------------------------------------------------------------
%% Steering stuff:
if (mod((nbands),2) == 0)
harmonics = [0:(nbands/2)-1]'*2 + 1;
else
harmonics = [0:(nbands-1)/2]'*2;
end
steermtx = steer2HarmMtx(harmonics, pi*[0:nbands-1]/nbands, 'even');
%-----------------------------------------------------------------
dims = size(im);
ctr = ceil((dims+0.5)/2);
[xramp,yramp] = meshgrid( ([1:dims(2)]-ctr(2))./(dims(2)/2), ...
([1:dims(1)]-ctr(1))./(dims(1)/2) );
angle = atan2(yramp,xramp);
log_rad = sqrt(xramp.^2 + yramp.^2);
log_rad(ctr(1),ctr(2)) = log_rad(ctr(1),ctr(2)-1);
log_rad = log2(log_rad);
%% Radial transition function (a raised cosine in log-frequency):
[Xrcos,Yrcos] = rcosFn(twidth,(-twidth/2),[0 1]);
Yrcos = sqrt(Yrcos);
YIrcos = sqrt(1.0 - Yrcos.^2);
lo0mask = pointOp(log_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0);
imdft = fftshift(fft2(im));
lo0dft = imdft .* lo0mask;
[pyr,pind] = buildSCFpyrLevs(lo0dft, log_rad, Xrcos, Yrcos, angle, ht, nbands);
hi0mask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0);
hi0dft = imdft .* hi0mask;
hi0 = ifft2(ifftshift(hi0dft));
pyr = [real(hi0(:)) ; pyr];
pind = [size(hi0); pind];
|
github
|
jacksky64/imageProcessing-master
|
showIm.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/showIm.m
| 6,111 |
utf_8
|
15fbbf55e2fd54e3f48ca936e23c3f32
|
% RANGE = showIm (MATRIX, RANGE, ZOOM, LABEL, NSHADES )
%
% Display a MatLab MATRIX as a grayscale image in the current figure,
% inside the current axes. If MATRIX is complex, the real and imaginary
% parts are shown side-by-side, with the same grayscale mapping.
%
% If MATRIX is a string, it should be the name of a variable bound to a
% MATRIX in the base (global) environment. This matrix is displayed as an
% image, with the title set to the string.
%
% RANGE (optional) is a 2-vector specifying the values that map to
% black and white, respectively. Passing a value of 'auto' (default)
% sets RANGE=[min,max] (as in MatLab's imagesc). 'auto2' sets
% RANGE=[mean-2*stdev, mean+2*stdev]. 'auto3' sets
% RANGE=[p1-(p2-p1)/8, p2+(p2-p1)/8], where p1 is the 10th percentile
% value of the sorted MATRIX samples, and p2 is the 90th percentile
% value.
%
% ZOOM specifies the number of matrix samples per screen pixel. It
% will be rounded to an integer, or 1 divided by an integer. A value
% of 'same' or 'auto' (default) causes the zoom value to be chosen
% automatically to fit the image into the current axes. A value of
% 'full' fills the axis region (leaving no room for labels). See
% pixelAxes.m.
%
% If LABEL (optional, default = 1, unless zoom='full') is non-zero, the range
% of values that are mapped into the gray colormap and the dimensions
% (size) of the matrix and zoom factor are printed below the image. If label
% is a string, it is used as a title.
%
% NSHADES (optional) specifies the number of gray shades, and defaults
% to the size of the current colormap.
% Eero Simoncelli, 6/96.
%%TODO: should use "newplot"
function range = showIm( im, range, zoom, label, nshades );
%------------------------------------------------------------
%% OPTIONAL ARGS:
if (nargin < 1)
error('Requires at least one input argument.');
end
MLv = version;
if isstr(im)
if (strcmp(MLv(1),'4'))
error('Cannot pass string arg for MATRIX in MatLab version 4.x');
end
label = im;
im = evalin('base',im);
end
if (exist('range') ~= 1)
range = 'auto1';
end
if (exist('nshades') ~= 1)
nshades = size(colormap,1);
end
nshades = max( nshades, 2 );
if (exist('zoom') ~= 1)
zoom = 'auto';
end
if (exist('label') ~= 1)
if strcmp(zoom,'full')
label = 0; % no labeling
else
label = 1; % just print grayrange & dims
end
end
%------------------------------------------------------------
%% Automatic range calculation:
if (strcmp(range,'auto1') | strcmp(range,'auto'))
if isreal(im)
[mn,mx] = range2(im);
else
[mn1,mx1] = range2(real(im));
[mn2,mx2] = range2(imag(im));
mn = min(mn1,mn2);
mx = max(mx1,mx2);
end
if any(size(im)==1)
pad = (mx-mn)/12; % MAGIC NUMBER: graph padding
range = [mn-pad, mx+pad];
else
range = [mn,mx];
end
elseif strcmp(range,'auto2')
if isreal(im)
stdev = sqrt(var2(im));
av = mean2(im);
else
stdev = sqrt((var2(real(im)) + var2(imag(im)))/2);
av = (mean2(real(im)) + mean2(imag(im)))/2;
end
range = [av-2*stdev,av+2*stdev]; % MAGIC NUMBER: 2 stdevs
elseif strcmp(range, 'auto3')
percentile = 0.1; % MAGIC NUMBER: 0<p<0.5
[N,X] = histo(im);
binsz = X(2)-X(1);
N = N+1e-10; % Ensure cumsum will be monotonic for call to interp1
cumN = [0, cumsum(N)]/sum(N);
cumX = [X(1)-binsz, X] + (binsz/2);
ctrRange = interp1(cumN,cumX, [percentile, 1-percentile]);
range = mean(ctrRange) + (ctrRange-mean(ctrRange))/(1-2*percentile);
elseif isstr(range)
error(sprintf('Bad RANGE argument: %s',range))
end
if ((range(2) - range(1)) <= eps)
range(1) = range(1) - 0.5;
range(2) = range(2) + 0.5;
end
if isreal(im)
factor=1;
else
factor = 1+sqrt(-1);
end
xlbl_offset = 0; % default value
if (~any(size(im)==1))
%% MatLab's "image" rounds when mapping to the colormap, so we compute
%% (im-r1)*(nshades-1)/(r2-r1) + 1.5
mult = ((nshades-1) / (range(2)-range(1)));
d_im = (mult * im) + factor*(1.5 - range(1)*mult);
end
if isreal(im)
if (any(size(im)==1))
hh = plot( im);
axis([1, prod(size(im)), range]);
else
hh = image( d_im );
axis('off');
zoom = pixelAxes(size(d_im),zoom);
end
else
if (any(size(im)==1))
subplot(2,1,1);
hh = plot(real(im));
axis([1, prod(size(im)), range]);
subplot(2,1,2);
hh = plot(imag(im));
axis([1, prod(size(im)), range]);
else
subplot(1,2,1);
hh = image(real(d_im));
axis('off'); zoom = pixelAxes(size(d_im),zoom);
ax = gca; orig_units = get(ax,'Units');
set(ax,'Units','points');
pos1 = get(ax,'Position');
set(ax,'Units',orig_units);
subplot(1,2,2);
hh = image(imag(d_im));
axis('off'); zoom = pixelAxes(size(d_im),zoom);
ax = gca; orig_units = get(ax,'Units');
set(ax,'Units','points');
pos2 = get(ax,'Position');
set(ax,'Units',orig_units);
xlbl_offset = (pos1(1)-pos2(1))/2;
end
end
if ~any(size(im)==1)
colormap(gray(nshades));
end
if ((label ~= 0))
if isstr(label)
title(label);
h = get(gca,'Title');
orig_units = get(h,'Units');
set(h,'Units','points');
pos = get(h,'Position');
pos(1:2) = pos(1:2) + [xlbl_offset, -3]; % MAGIC NUMBER: y pixel offset
set(h,'Position',pos);
set(h,'Units',orig_units);
end
if (~any(size(im)==1))
if (zoom > 1)
zformat = sprintf('* %d',round(zoom));
else
zformat = sprintf('/ %d',round(1/zoom));
end
if isreal(im)
format=[' Range: [%.3g, %.3g] \n Dims: [%d, %d] ', zformat];
else
format=['Range: [%.3g, %.3g] ---- Dims: [%d, %d]', zformat];
end
xlabel(sprintf(format, range(1), range(2), size(im,1), size(im,2)));
h = get(gca,'Xlabel');
set(h,'FontSize', 9); % MAGIC NUMBER: font size!!!
orig_units = get(h,'Units');
set(h,'Units','points');
pos = get(h,'Position');
pos(1:2) = pos(1:2) + [xlbl_offset, 10]; % MAGIC NUMBER: y offset in points
set(h,'Position',pos);
set(h,'Units',orig_units);
set(h,'Visible','on'); % axis('image') turned the xlabel off...
end
end
return;
|
github
|
jacksky64/imageProcessing-master
|
pyrLow.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/pyrLow.m
| 287 |
utf_8
|
b3514ec06e2e106d7b61e534cac20a8e
|
% RES = pyrLow(PYR, INDICES)
%
% Access the lowpass subband from a pyramid
% (gaussian, laplacian, QMF/wavelet, steerable).
% Eero Simoncelli, 6/96.
function res = pyrLow(pyr,pind)
band = size(pind,1);
res = reshape( pyr(pyrBandIndices(pind,band)), pind(band,1), pind(band,2) );
|
github
|
jacksky64/imageProcessing-master
|
pgmRead.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/pgmRead.m
| 1,259 |
utf_8
|
6f07c13cf0f5d8930a46ac0d778bf86f
|
% IM = pgmRead( FILENAME )
%
% Load a pgm image into a MatLab matrix.
% This format is accessible from the XV image browsing utility.
% Only works for 8bit gray images (raw or ascii)
% Hany Farid, Spring '96. Modified by Eero Simoncelli, 6/96.
function im = pgmRead( fname );
[fid,msg] = fopen( fname, 'r' );
if (fid == -1)
error(msg);
end
%%% First line contains ID string:
%%% "P1" = ascii bitmap, "P2" = ascii greymap,
%%% "P3" = ascii pixmap, "P4" = raw bitmap,
%%% "P5" = raw greymap, "P6" = raw pixmap
TheLine = fgetl(fid);
format = TheLine;
if ~((format(1:2) == 'P2') | (format(1:2) == 'P5'))
error('PGM file must be of type P2 or P5');
end
%%% Any number of comment lines
TheLine = fgetl(fid);
while TheLine(1) == '#'
TheLine = fgetl(fid);
end
%%% dimensions
sz = sscanf(TheLine,'%d',2);
xdim = sz(1);
ydim = sz(2);
sz = xdim * ydim;
%%% Maximum pixel value
TheLine = fgetl(fid);
maxval = sscanf(TheLine, '%d',1);
%%im = zeros(dim,1);
if (format(2) == '2')
[im,count] = fscanf(fid,'%d',sz);
else
[im,count] = fread(fid,sz,'uchar');
end
fclose(fid);
if (count == sz)
im = reshape( im, xdim, ydim )';
else
fprintf(1,'Warning: File ended early!');
im = reshape( [im ; zeros(sz-count,1)], xdim, ydim)';
end
|
github
|
jacksky64/imageProcessing-master
|
upConv.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/upConv.m
| 2,779 |
utf_8
|
34137e966f38700416bfb0ebb72663ee
|
% RES = upConv(IM, FILT, EDGES, STEP, START, STOP, RES)
%
% Upsample matrix IM, followed by convolution with matrix FILT. These
% arguments should be 1D or 2D matrices, and IM must be larger (in
% both dimensions) than FILT. The origin of filt
% is assumed to be floor(size(filt)/2)+1.
%
% EDGES is a string determining boundary handling:
% 'circular' - Circular convolution
% 'reflect1' - Reflect about the edge pixels
% 'reflect2' - Reflect, doubling the edge pixels
% 'repeat' - Repeat the edge pixels
% 'zero' - Assume values of zero outside image boundary
% 'extend' - Reflect and invert
% 'dont-compute' - Zero output when filter overhangs OUTPUT boundaries
%
% Upsampling factors are determined by STEP (optional, default=[1 1]),
% a 2-vector [y,x].
%
% The window over which the convolution occurs is specfied by START
% (optional, default=[1,1], and STOP (optional, default =
% step .* (size(IM) + floor((start-1)./step))).
%
% RES is an optional result matrix. The convolution result will be
% destructively added into this matrix. If this argument is passed, the
% result matrix will not be returned. DO NOT USE THIS ARGUMENT IF
% YOU DO NOT UNDERSTAND WHAT THIS MEANS!!
%
% NOTE: this operation corresponds to multiplication of a signal
% vector by a matrix whose columns contain copies of the time-reversed
% (or space-reversed) FILT shifted by multiples of STEP. See corrDn.m
% for the operation corresponding to the transpose of this matrix.
% Eero Simoncelli, 6/96. revised 2/97.
function result = upConv(im,filt,edges,step,start,stop,res)
%% THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD)
fprintf(1,'WARNING: You should compile the MEX version of "upConv.c",\n found in the MEX subdirectory of matlabPyrTools, and put it in your matlab path. It is MUCH faster, and provides more boundary-handling options.\n');
%------------------------------------------------------------
%% OPTIONAL ARGS:
if (exist('edges') == 1)
if (strcmp(edges,'reflect1') ~= 1)
warning('Using REFLECT1 edge-handling (use MEX code for other options).');
end
end
if (exist('step') ~= 1)
step = [1,1];
end
if (exist('start') ~= 1)
start = [1,1];
end
% A multiple of step
if (exist('stop') ~= 1)
stop = step .* (floor((start-ones(size(start)))./step)+size(im))
end
if ( ceil((stop(1)+1-start(1)) / step(1)) ~= size(im,1) )
error('Bad Y result dimension');
end
if ( ceil((stop(2)+1-start(2)) / step(2)) ~= size(im,2) )
error('Bad X result dimension');
end
if (exist('res') ~= 1)
res = zeros(stop-start+1);
end
%------------------------------------------------------------
tmp = zeros(size(res));
tmp(start(1):step(1):stop(1),start(2):step(2):stop(2)) = im;
result = rconv2(tmp,filt) + res;
|
github
|
jacksky64/imageProcessing-master
|
mean2.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/mean2.m
| 97 |
utf_8
|
cacc007ef6e32ba40a1e0da3b3d80a0e
|
% M = MEAN2(MTX)
%
% Sample mean of a matrix.
function res = mean2(mtx)
res = mean(mean(mtx));
|
github
|
jacksky64/imageProcessing-master
|
range2.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/range2.m
| 523 |
utf_8
|
b9f23c3a4f73bf568a1b5793f516aa80
|
% [MIN, MAX] = range2(MTX)
%
% Compute minimum and maximum values of MTX, returning them as a 2-vector.
% Eero Simoncelli, 3/97.
function [mn, mx] = range2(mtx)
%% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD)
fprintf(1,'WARNING: You should compile the MEX version of "range2.c",\n found in the MEX subdirectory of matlabPyrTools, and put it in your matlab path. It is MUCH faster.\n');
if (~isreal(mtx))
error('MTX must be real-valued');
end
mn = min(min(mtx));
mx = max(max(mtx));
|
github
|
jacksky64/imageProcessing-master
|
buildSCFpyrLevs.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/buildSCFpyrLevs.m
| 2,187 |
utf_8
|
26747285064a0eaa2f3db75013e80849
|
% [PYR, INDICES] = buildSCFpyrLevs(LODFT, LOGRAD, XRCOS, YRCOS, ANGLE, HEIGHT, NBANDS)
%
% Recursive function for constructing levels of a steerable pyramid. This
% is called by buildSCFpyr, and is not usually called directly.
% Original code: Eero Simoncelli, 5/97.
% Modified by Javier Portilla to generate complex bands in 9/97.
function [pyr,pind] = buildSCFpyrLevs(lodft,log_rad,Xrcos,Yrcos,angle,ht,nbands);
if (ht <= 0)
lo0 = ifft2(ifftshift(lodft));
pyr = real(lo0(:));
pind = size(lo0);
else
bands = zeros(prod(size(lodft)), nbands);
bind = zeros(nbands,2);
% log_rad = log_rad + 1;
Xrcos = Xrcos - log2(2); % shift origin of lut by 1 octave.
lutsize = 1024;
Xcosn = pi*[-(2*lutsize+1):(lutsize+1)]/lutsize; % [-2*pi:pi]
order = nbands-1;
%% divide by sqrt(sum_(n=0)^(N-1) cos(pi*n/N)^(2(N-1)) )
%% Thanks to Patrick Teo for writing this out :)
const = (2^(2*order))*(factorial(order)^2)/(nbands*factorial(2*order));
%
% Ycosn = sqrt(const) * (cos(Xcosn)).^order;
%
% analityc version: only take one lobe
alfa= mod(pi+Xcosn,2*pi)-pi;
Ycosn = 2*sqrt(const) * (cos(Xcosn).^order) .* (abs(alfa)<pi/2);
himask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0);
for b = 1:nbands
anglemask = pointOp(angle, Ycosn, Xcosn(1)+pi*(b-1)/nbands, Xcosn(2)-Xcosn(1));
banddft = ((-i)^(nbands-1)) .* lodft .* anglemask .* himask;
band = ifft2(ifftshift(banddft));
% bands(:,b) = real(band(:));
% analytic version: full complex value
bands(:,b)=band(:);
bind(b,:) = size(band);
end
dims = size(lodft);
ctr = ceil((dims+0.5)/2);
lodims = ceil((dims-0.5)/2);
loctr = ceil((lodims+0.5)/2);
lostart = ctr-loctr+1;
loend = lostart+lodims-1;
log_rad = log_rad(lostart(1):loend(1),lostart(2):loend(2));
angle = angle(lostart(1):loend(1),lostart(2):loend(2));
lodft = lodft(lostart(1):loend(1),lostart(2):loend(2));
YIrcos = abs(sqrt(1.0 - Yrcos.^2));
lomask = pointOp(log_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0);
lodft = lomask .* lodft;
[npyr,nind] = buildSCFpyrLevs(lodft, log_rad, Xrcos, Yrcos, angle, ht-1, nbands);
pyr = [bands(:); npyr];
pind = [bind; nind];
end
|
github
|
jacksky64/imageProcessing-master
|
clip.m
|
.m
|
imageProcessing-master/Matlab imaging/matlabPyrTools/clip.m
| 814 |
utf_8
|
13c82937ba69d5bc8c94b2ccca783e1b
|
% [RES] = clip(IM, MINVALorRANGE, MAXVAL)
%
% Clip values of matrix IM to lie between minVal and maxVal:
% RES = max(min(IM,MAXVAL),MINVAL)
% The first argument can also specify both min and max, as a 2-vector.
% If only one argument is passed, the range defaults to [0,1].
function res = clip(im, minValOrRange, maxVal)
if (exist('minValOrRange') ~= 1)
minVal = 0;
maxVal = 1;
elseif (length(minValOrRange) == 2)
minVal = minValOrRange(1);
maxVal = minValOrRange(2);
elseif (length(minValOrRange) == 1)
minVal = minValOrRange;
if (exist('maxVal') ~= 1)
maxVal=minVal+1;
end
else
error('MINVAL must be a scalar or a 2-vector');
end
if ( maxVal < minVal )
error('MAXVAL should be less than MINVAL');
end
res = im;
res(find(im < minVal)) = minVal;
res(find(im > maxVal)) = maxVal;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.