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
|
matrix2angleaxis.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Rotations/matrix2angleaxis.m
| 2,499 |
utf_8
|
c9fc88c002549f547352b67cc8689c21
|
% MATRIX2ANGLEAXIS - Homogeneous matrix to angle-axis description
%
% Usage: t = matrix2angleaxis(T)
%
% Argument: T - 4x4 Homogeneous transformation matrix, or 3x3 rotation matrix.
% Returns: t - 3x1 column vector giving rotation axis with magnitude equal
% to the rotation angle in radians.
%
% Note that only the top left 3x3 rotation component of T is used, any
% translation component in T is ignored.
%
% See also: ANGLEAXIS2MATRIX, ANGLEAXIS2MATRIX2, ANGLEAXISROTATE, NEWANGLEAXIS,
% NORMALISEANGLEAXIS
% Copyright (c) 2008 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% 2008 - Original version
% May 2013 - Code to trap small rotations added
function t = matrix2angleaxis(T)
% This code follows the implementation suggested by Hartley and Zisserman
R = T(1:3, 1:3); % Extract rotation part of T
% Trap case where rotation is very small. (See angleaxis2matrix.m)
Reye = R-eye(3);
if norm(Reye) < 1e-8
t = [T(3,2); T(1,3); T(2,1)];
return
end
% Otherwise find rotation axis as the eigenvector having unit eigenvalue
% Solve (R-I)v = 0;
[v,d] = eig(Reye);
% The following code assumes the eigenvalues returned are not necessarily
% sorted by size. This may be overcautious on my part.
d = diag(abs(d)); % Extract eigenvalues
[s, ind] = sort(d); % Find index of smallest one
if d(ind(1)) > 0.001 % Hopefully it is close to 0
warning('Rotation matrix is dubious');
end
axis = v(:,ind(1)); % Extract appropriate eigenvector
if abs(norm(axis) - 1) > .0001 % Debug
warning('non unit rotation axis');
end
% Now determine the rotation angle
twocostheta = trace(R)-1;
twosinthetav = [R(3,2)-R(2,3), R(1,3)-R(3,1), R(2,1)-R(1,2)]';
twosintheta = axis'*twosinthetav;
theta = atan2(twosintheta, twocostheta);
t = theta*axis;
|
github
|
jacksky64/imageProcessing-master
|
quaternionproduct.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Rotations/quaternionproduct.m
| 818 |
utf_8
|
bcfe792d9518a1c110b9957970f4f7c8
|
% QUATERNIONPRODUCT - Computes product of two quaternions
%
% Usage: Q = quaternionproduct(A, B)
%
% Arguments: A, B - Quaternions assumed to be 4-vectors in the
% form A = [Aw Ai Aj Ak]
% Returns: Q - Quaternion product
%
% See also: NEWQUATERNION, QUATERNIONROTATE, QUATERNIONCONJUGATE
% Copyright (c) 2008 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/
function Q = quaternionproduct(A, B)
Q = zeros(4,1);
Q(1) = A(1)*B(1) - A(2)*B(2) - A(3)*B(3) - A(4)*B(4);
Q(2) = A(1)*B(2) + A(2)*B(1) + A(3)*B(4) - A(4)*B(3);
Q(3) = A(1)*B(3) - A(2)*B(4) + A(3)*B(1) + A(4)*B(2);
Q(4) = A(1)*B(4) + A(2)*B(3) - A(3)*B(2) + A(4)*B(1);
|
github
|
jacksky64/imageProcessing-master
|
quaternion2matrix.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Rotations/quaternion2matrix.m
| 1,413 |
utf_8
|
7296cadf62f6ca9273e726ffd7e19d95
|
% QUATERNION2MATRIX - Quaternion to a 4x4 homogeneous transformation matrix
%
% Usage: T = quaternion2matrix(Q)
%
% Argument: Q - a quaternion in the form [w xi yj zk]
% Returns: T - 4x4 Homogeneous rotation matrix
%
% See also MATRIX2QUATERNION, NEWQUATERNION, QUATERNIONROTATE
% Copyright (c) 2008 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
function T = quaternion2matrix(Q)
Q = Q/norm(Q); % Ensure Q has unit norm
% Set up convenience variables
w = Q(1); x = Q(2); y = Q(3); z = Q(4);
w2 = w^2; x2 = x^2; y2 = y^2; z2 = z^2;
xy = x*y; xz = x*z; yz = y*z;
wx = w*x; wy = w*y; wz = w*z;
T = [w2+x2-y2-z2 , 2*(xy - wz) , 2*(wy + xz) , 0
2*(wz + xy) , w2-x2+y2-z2 , 2*(yz - wx) , 0
2*(xz - wy) , 2*(wx + yz) , w2-x2-y2+z2 , 0
0 , 0 , 0 , 1];
|
github
|
jacksky64/imageProcessing-master
|
newquaternion.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Rotations/newquaternion.m
| 652 |
utf_8
|
57135243008eb6d8ae64557d2f013e6f
|
% NEWQUATERNION - Construct quaternion
%
% Q = newquaternion(theta, axis)
%
% Arguments: theta - angle of rotation
% axis - 3-vector defining axis of rotation
% Returns: Q - a quaternion in the form [w xi yj zk]
%
% See Also: QUATERNION2MATRIX, MATRIX2QUATERNION, QUATERNIONROTATE
% Copyright (c) 2008 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/
function Q = newquaternion(theta, axis)
axis = axis(:)/norm(axis(:));
Q = zeros(4,1);
Q(1) = cos(theta/2);
Q(2:4) = sin(theta/2)*axis;
|
github
|
jacksky64/imageProcessing-master
|
quaternionrotate.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Rotations/quaternionrotate.m
| 2,026 |
utf_8
|
e0b6a4a18c8be41ee01226e17cbd83e8
|
% QUATERNIONROTATE - Rotates a 3D vector by a quaternion
%
% Usage: vnew = quaternionrotate(Q, v)
%
% Arguments: Q - a quaternion in the form [w xi yj zk]
% v - a vector to rotate, either an inhomogeneous 3-vector or a
% homogeneous 4-vector
% Returns: vnew - rotated vector
%
% See also MATRIX2QUATERNION, QUATERNION2MATRIX, NEWQUATERNION
% Copyright (c) 2008 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% Code forms the equivalent 3x3 rotation matrix from the quaternion and
% applies it to a vector
%
% Note that Qw^2 + Qi^2 + Qj^2 + Qk^2 = 1
% So the top-left entry of the rotation matrix of
% Qw^2 + Qi^2 - Qj^2 - Qk^2
% can be rewritten as
% Qw^2 + Qi^2 + Qj^2 + Qk^2 - 2Qj^2 - 2Qk^2
% = 1 - 2Qj^2 - 2Qk^2
%
% Similar optimization applies to the other diagonal elements
function vnew = quaternionrotate(Q, v)
% Copy v to vnew to allocate space. If v is a 4 element homogeneous
% vector this also sets the homogeneous scale factor of vnew
vnew = v;
Qw = Q(1); Qi = Q(2); Qj = Q(3); Qk = Q(4);
t2 = Qw*Qi;
t3 = Qw*Qj;
t4 = Qw*Qk;
t5 = -Qi*Qi;
t6 = Qi*Qj;
t7 = Qi*Qk;
t8 = -Qj*Qj;
t9 = Qj*Qk;
t10 = -Qk*Qk;
vnew(1) = 2*( (t8 + t10)*v(1) + (t6 - t4)*v(2) + (t3 + t7)*v(3) ) + v(1);
vnew(2) = 2*( (t4 + t6)*v(1) + (t5 + t10)*v(2) + (t9 - t2)*v(3) ) + v(2);
vnew(3) = 2*( (t7 - t3)*v(1) + (t2 + t9)*v(2) + (t5 + t8)*v(3) ) + v(3);
|
github
|
jacksky64/imageProcessing-master
|
inveuler.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Rotations/inveuler.m
| 1,296 |
utf_8
|
68fbee86dde87b43540b185a69fd8bfe
|
% INVEULER - inverse of Euler transform
%
% Usage: [euler1, euler2] = inveuler(T)
%
% Argument: T - 4x4 Homogeneous transformation matrix or 3x3 rotation matrix
% Returns: euler1 = [phi1, theta1, psi1] - the 1st solution and,
% euler2 = [phi2, theta2, psi2] - the 2nd solution
%
% rotz(phi1) * roty(theta1) * rotz(psi1) = T
% rotz(euler1(1)) * roty(euler1(2)) * rotz(euler1(3)) = T
%
% See also: INVRPY, INVHT, ROTX, ROTY, ROTZ
% Reference: Richard P. Paul Robot Manipulators: Mathematics, Programming and Control.
% MIT Press 1981. Page 68
%
% Copyright (c) 2001 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/
function [euler1, euler2] = inveuler(T)
phi1 = atan2(T(2,3), T(1,3));
phi2 = phi1 + pi;
theta1 = atan2(cos(phi1)*T(1,3) + sin(phi1)*T(2,3), T(3,3));
theta2 = atan2(cos(phi2)*T(1,3) + sin(phi2)*T(2,3), T(3,3));
psi1 = atan2(-sin(phi1)*T(1,1) + cos(phi1)*T(2,1), ...
-sin(phi1)*T(1,2) + cos(phi1)*T(2,2));
psi2 = atan2(-sin(phi2)*T(1,1) + cos(phi2)*T(2,1), ...
-sin(phi2)*T(1,2) + cos(phi2)*T(2,2));
euler1 = [phi1, theta1, psi1];
euler2 = [phi2, theta2, psi2];
|
github
|
jacksky64/imageProcessing-master
|
ternarymix.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Blender/ternarymix.m
| 13,368 |
utf_8
|
53527c33bc58e77326e03f0354a5bbb6
|
% TERNARYMIX Image blending and swiping over three images
%
% Function uses Barycentric coordinates over a triangle to interpolate/blend
% three images. You can also switch to a swiping mode of display between the
% three images.
%
% Usage: ternarymix(im, nodeLabel, normBlend, figNo)
%
% Arguments: im - 3-element cell array of images to blend. If omitted or
% empty a file selection dialog box is presented.
% nodeLabel - Optional cell array of strings for labeling the 3 nodes
% of the interface.
% normBlend - Sets the image normalisation that is used.
% 0 - No normalisation applied other than image clamping.
% 1 - Image is normalised so that max value in any
% channel is 1. This is the default
% 2 - Normalise to have fixed mean grey value.
% (This is hard-wired at 0.2 . Edit function wbmcb
% below to change)
% 3 - Normalise so that max grey value is a fixed value
% (This is hard-wired at 0.6 . Edit function wbmcb
% below to change)
% figNo - Optional figure number to use.
%
% This function sets up an interface consisting of a triangle with nodes
% corresponding to the three input images. Positioning the cursor within the
% triangle produces an interactive blend of the images formed from a weighted
% sum of the images. The weights correspond to the barycentric coordinates of
% the cursor within the triangle. The program starts out assigning a lightness
% matched basis colour to each image. These colours are nominally red, green
% and blue but have been constructed so that they are matched in lightness
% values and also have secondary colours that are closely matched.
% Unfortunately the normalisation of the blended image undoes some of this
% lightness matching but I am not sure there is a good way around this.
%
% Hitting 'c' cycles the basis colours between the set of lightness matched
% Isoluminant colours, the RGB primaries, and grey scale images.
%
% Hitting 's' toggles between blending and swiping mode.
%
% See also: LINIMIX, BILINIMIX, CLIQUEMIX, CYCLEMIX, BINARYMIX
% Reference:
% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.
% "Interactive Multi-Image Blending for Visualization and Interpretation",
% Computers & Geosciences 72 (2014) 147-155.
% http://doi.org/10.1016/j.cageo.2014.07.010
%
% For information about the construction of the lighness matched basis
% colours see:
% http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary
% Copyright (c) 2012-2014 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% May 2012 - Original version
% March 2014 - General cleanup and added option to specify colours associated
% with each image when using the RGB option.
% Dec 2014 - Updated isoluminant basis colours. Added interactive colour
% mode section and swiping.
function ternarymix(im, nodeLabel, normBlend, figNo)
if ~exist('im', 'var'), im = []; end
if ~exist('normBlend', 'var') || isempty(normBlend), normBlend = 1; end
if ~exist('figNo', 'var') || isempty(figNo)
fig = figure;
else
fig = figure(figNo);
end
[im, nImages, fname] = collectncheckimages(im);
assert(nImages == 3, 'Three images must be supplied');
[rows,cols] = size(im{1});
if ~exist('nodeLabel', 'var') || isempty(nodeLabel)
for n = 1:3
nodeLabel{n} = namenpath(fname{n});
end
end
% Set up three 'basis' images from the three input images and their
% corresponding basis colours.
colourdisplay = 'ISO';
imcol = {[0.90 0.17 0.00], [0.00 0.50 0.00], [0.10 0.33 1.00]};
for n = 1:3
% It is useful to truncate extreme image values that are at the ends
% of the histogram. Here we remove the 0.25% extremes of the histogram.
im{n} = histtruncate(im{n}, 0.25, 0.25);
im{n} = normalise(im{n}); % Renormalise 0-1
basis{n} = applycolour(im{n}, imcol{n});
end
% Display 1st image and get handle to Cdata in the figure
% Suppress display warnings for images that are large
S = warning('off');
figure(fig); clf,
imposition = [0.35 0.0 0.65 1.0];
subplot('position', imposition);
imshow(basis{1}); drawnow
imHandle = get(gca,'Children');
warning(S)
% Set up interface figure
ah = subplot('position',[0.0 0.4 0.35 0.35]);
% Draw triangle interface and label vertices
theta = [0 2/3*pi 4/3*pi]+pi/2;
v = [cos(theta)
sin(theta)];
hold on;
plot([v(1,:) 0], [v(2,:) 0], 'k.', 'markersize',40)
plot([v(1,:) 0], [v(2,:) 0], '.', 'markersize',20, 'Color', [.8 .8 .8])
line([v(1,:) v(1,1)], [v(2,:) v(2,1)], 'LineWidth', 2)
for n = 1:nImages
text(v(1,n)*1.2, v(2, n)*1.2, nodeLabel{n}, ...
'HorizontalAlignment','center', 'FontWeight', 'bold', 'FontSize', 16);
end
coltxt = text(-1,-1,'ISO','FontWeight', 'bold', 'FontSize', 16);
r = 1.1;
axis ([-r r -r r]), axis off, axis equal
% Set callback function and window title
setwindowsize(fig, [rows cols], imposition);
set(fig, 'WindowButtonDownFcn',@wbdcb);
set(fig, 'KeyReleaseFcn', @keyreleasecb);
set(fig, 'NumberTitle', 'off')
set(fig, 'name', ' Ternary Mix')
set(fig, 'Menubar','none');
% Set up custom pointer
myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];
myPointer(~myPointer) = NaN;
fprintf('\nClick and move the mouse within the triangle interface.\n');
fprintf('Left-click to toggle blending on and off.\n');
fprintf('Hit ''c'' to cycle between isoluminant colours, RGB and grey.\n');
fprintf('Hit ''s'' to toggle between swiping and blending modes.\n\n');
blending = 0;
hspot = 0;
blendswipe = 'blend'; % Start in blending mode
%--------------------------------------------------------------------
% Window button down callback
function wbdcb(src,evnt)
if strcmp(get(src,'SelectionType'),'normal')
if ~blending % Turn blending on
blending = 1;
set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...
'PointerShapeHotSpot',[9 9])
set(src,'WindowButtonMotionFcn',@wbmcb)
if hspot % For paper illustration
delete(hspot);
end
else % Turn blending off
blending = 0;
set(src,'Pointer','arrow')
set(src,'WindowButtonMotionFcn','')
% For paper illustration
cp = get(ah,'CurrentPoint');
x = cp(1,1);
y = cp(1,2);
if gca == ah
hspot = plot(x, y, '.', 'color', [0 0 0], 'Markersize', 40');
end
end
end
end
%--------------------------------------------------------------------
% Window button move call back
function wbmcb(src,evnt)
cp = get(ah,'CurrentPoint');
xy = [cp(1,1); cp(1,2)];
if strcmp(blendswipe, 'swipe')
swipe(xy);
else % Blend
[w1,w2,w3] = barycentriccoords(xy, v(:,1), v(:,2), v(:,3));
blend = w1*basis{1} + w2*basis{2} + w3*basis{3};
% Various normalisation options
if normBlend == 0 % No normalisation
blend(blend>1) = 1; % but clamp values to 1
elseif normBlend == 1 || strcmpi(colourdisplay, 'GREY') % Normalise by max value in blend
blend = blend/max(blend(:));
elseif normBlend == 2 % Normalise to have fixed mean grey value
g = 0.299*blend(:,:,1) + 0.587*blend(:,:,2) + 0.114*blend(:,:,3);
g(isnan(g(:))) = [];
meang = mean(g(:));
blend = blend/meang*0.2; % Mean grey value of 0.2
blend(blend>1) = 1; % Clamp values to 1
elseif normBlend == 3 % Normalise so that max grey value is a fixed value
g = 0.299*blend(:,:,1) + 0.587*blend(:,:,2) + 0.114*blend(:,:,3);
blend = blend/max(g(:))*0.6; % Max grey of 0.6
blend(blend>1) = 1; % Clamp values to 1
end
set(imHandle,'CData', blend);
end
end
%-----------------------------------------------------------------------
% Key Release callback
% If 'c' is pressed the display cycles between using Lightness matched
% colours, RGB and Grey. If 's' is pressed we toggle between swiping and
% blending.
function keyreleasecb(src,evnt)
if evnt.Character == 'c'
if strcmp(colourdisplay, 'ISO')
colourdisplay = 'RGB';
set(coltxt, 'String', 'RGB');
imcol = {[1 0 0], [0 1 0], [0 0 1]};
for n = 1:3
basis{n} = applycolour(im{n}, imcol{n});
end
elseif strcmp(colourdisplay, 'RGB')
colourdisplay = 'GREY';
set(coltxt, 'String', 'Grey');
for n = 1:3
basis{n} = applycolour(im{n}, [1 1 1]);
end
elseif strcmp(colourdisplay, 'GREY')
colourdisplay = 'ISO';
set(coltxt, 'String', 'ISO');
imcol = {[0.90 0.17 0.00], [0.00 0.50 0.00], [0.10 0.33 1.00]};
for n = 1:3
basis{n} = applycolour(im{n}, imcol{n});
end
end
elseif evnt.Character == 's' % Swipe/Blend toggle
if strcmp(blendswipe, 'swipe')
blendswipe = 'blend';
else
blendswipe = 'swipe';
end
end
wbmcb(src,evnt); % update the display
end
%-----------------------------------------------------------------------
% Generate swipe image given xy which has its origin at the centre of the
% triangle with vertices at a radius of 1
function swipe(xy)
% Convert cursor position to row and col coords
x = round(( xy(1) + 1) * cols/2);
y = round((-xy(2) + 1) * rows/2);
% Clamp x and y to image limits
x = max(1,x); x = min(cols,x);
y = max(1,y); y = min(rows,y);
% Three images. 1st image occupies top half, swiped vertically. 2nd and
% 3rd images share bottom half and are swiped horizontally.
swipeim = [ basis{1}(1:y, :, :)
basis{2}(y+1:end, 1:x, :) basis{3}(y+1:end, x+1:end, :)];
set(imHandle,'CData', swipeim);
end
%------------------------------------------------------------------------
end % of main function and its nested functions
%------------------------------------------------------------------------
% Given 3 vertices and a point convert the xy coordinates of the point to
% Barycentric coordinates with respect to vertices v1, v2 and v3.
% Assumes all arguements are 2-element column vectors.
% Returns 3 barycentric coordinates / weights.
function [l1,l2,l3] = barycentriccoords(p, v1, v2, v3)
l = [v1-v3, v2-v3]\(p-v3);
l1 = l(1);
l2 = l(2);
l3 = 1 - l1 - l2;
% Simple clamping of resulting coords to range [0 1]
l1 = min(max(l1,0),1);
l2 = min(max(l2,0),1);
l3 = min(max(l3,0),1);
% Perhaps ideally if p is outside triangle p should be projected to the
% closest point on the triangle before computing barycentric coords
end
%------------------------------------------------------------------------
% Function to set up window size nicely
function setwindowsize(fig, imsze, imposition)
screen = get(0,'ScreenSize');
scsze = [screen(4) screen(3)];
window = get(fig, 'Position');
% Set window height to match image height
window(4) = imsze(1);
% Set window width to match image width allowing for fractional width of
% image specified in imposition
window(3) = imsze(2)/imposition(3);
% Check size of window relative to screen. If larger rescale the window
% size to fit 80% of screen dimension.
winsze = [window(4) window(3)];
ratio = max(winsze./scsze);
if ratio > 1
winsze = winsze/ratio * 0.8;
end
window(3:4) = [winsze(2) winsze(1)];
set(fig, 'Position', window);
end
%----------------------------------------------------------------------------------
% Apply a colour to a scalar image
function rgbim = applycolour(im, col)
[rows,cols] = size(im);
rgbim = zeros(rows,cols,3);
for r = 1:rows
for c = 1:cols
rgbim(r,c,:) = im(r,c)*col(:);
end
end
end
|
github
|
jacksky64/imageProcessing-master
|
binarymix.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Blender/binarymix.m
| 11,564 |
utf_8
|
53c5c89d010c8dc56ca1daef824526f9
|
% BINARYMIX Image blending and swiping between two images
%
% Function blends two images. Each image is coloured with two lightness
% matched colours that sum to white. Like a ternary image but binary!
% You can also switch between blending and swiping.
%
% Usage: binarymix(im, nodeLabel, normBlend, figNo)
%
% Arguments: im - 2-element cell array of images to blend. If omitted or
% empty a file selection dialog box is presented.
% nodeLabel - Optional cell array of strings for labeling the 2 nodes
% of the interface.
% normBlend - Sets the image normalisation that is used.
% 0 - No normalisation applied other than image clamping.
% 1 - Image is normalised so that max value in any
% channel is 1. This is the default
% 2 - Normalise to have fixed mean grey value.
% (This is hard-wired at 0.2 . Edit function wbmcb
% below to change)
% 3 - Normalise so that max grey value is a fixed value
% (This is hard-wired at 0.6 . Edit function wbmcb
% below to change)
% figNo - Optional figure number to use.
%
% This function sets up an interface consisting of a line with nodes at each end
% corresponding to the two input images. Positioning the cursor along the line
% produces an interactive blend of the images formed from a weighted sum of the
% images.
%
% Hitting 'c' cycles the display between two choices for the image basis colours
% and grey scale images. Each set of two basis colours sum to white. Where your
% two images/data sets are in agreement, and you are at the blend mid-point, you
% will see achromatic regions in the blended result.
%
% Hitting 's' toggles between blending and swiping mode.
%
% See also: TERNARYMIX, LINIMIX, BILINIMIX, CLIQUEMIX, CYCLEMIX
% Reference:
% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.
% "Interactive Multi-Image Blending for Visualization and Interpretation",
% Computers & Geosciences 72 (2014) 147-155.
% http://doi.org/10.1016/j.cageo.2014.07.010
%
% For information about the construction of the lighness matched basis
% colours see:
% http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary
% Copyright (c) 2012-2014 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% Dec 2014 - Adapted from TERNARYMIX
% [0.00 0.71 0.00], [1.00 0.29 1.00]; % Green - Magenta
% [1 0.4 0]; b = [0 0.6 1]; % Red/Orange - Blue/Cyan
function binarymix(im, nodeLabel, normBlend, figNo)
if ~exist('im', 'var'), im = []; end
if ~exist('normBlend', 'var') || isempty(normBlend), normBlend = 1; end
if ~exist('figNo', 'var') || isempty(figNo)
fig = figure;
else
fig = figure(figNo);
end
[im, nImages, fname] = collectncheckimages(im);
assert(nImages == 2, 'Three images must be supplied');
[rows,cols] = size(im{1});
if ~exist('nodeLabel', 'var') || isempty(nodeLabel)
for n = 1:2
nodeLabel{n} = namenpath(fname{n});
end
end
% Set up two 'basis' images from the two input images and their
% corresponding basis colours.
% Set up initial lightness matched colours
colourdisplay = 'COL1';
imcol = {[0.00 0.71 0.00], [1.00 0.29 1.00]};
for n = 1:2
% It is useful to truncate extreme image values that are at the ends
% of the histogram. Here we remove the 0.25% extremes of the histogram.
im{n} = histtruncate(im{n}, 0.25, 0.25);
im{n} = normalise(im{n}); % Renormalise 0-1
basis{n} = applycolour(im{n}, imcol{n});
end
% Display 1st image and get handle to Cdata in the figure
% Suppress display warnings for images that are large
S = warning('off');
figure(fig); clf,
imposition = [0.35 0.0 0.65 1.0];
subplot('position', imposition);
imshow(basis{1}); drawnow
imHandle = get(gca,'Children');
warning(S)
% Set up interface figure
ah = subplot('position',[0.0 0.4 0.35 0.35]);
% Draw slider interface and label vertices
theta = [0 pi];
v = [cos(theta)
sin(theta)];
hold on;
plot(v(1,:), v(2,:), 'k.', 'markersize',40)
plot(v(1,:), v(2,:), '.', 'markersize',20, 'Color', [.8 .8 .8])
line(v(1,:), v(2,:), 'LineWidth', 2)
for n = 1:nImages
text(v(1,n)*1.2, v(2, n)*1.2, nodeLabel{n}, ...
'HorizontalAlignment','center', 'FontWeight', 'bold', 'FontSize', 16);
end
r = 1.1;
axis ([-r r -r r]), axis off, axis equal
% Set callback function and window title
setwindowsize(fig, [rows cols], imposition);
set(fig, 'WindowButtonDownFcn',@wbdcb);
set(fig, 'KeyReleaseFcn', @keyreleasecb);
set(fig, 'NumberTitle', 'off')
set(fig, 'name', ' Binary Mix')
set(fig, 'Menubar','none');
% Set up custom pointer
myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];
myPointer(~myPointer) = NaN;
fprintf('\nClick and move the mouse on the slider.\n');
fprintf('Left-click to toggle blending on and off.\n');
fprintf('Hit ''c'' to cycle between two colour choices and grey .\n');
fprintf('Hit ''s'' to toggle between swiping and blending modes.\n\n');
blending = 0;
hspot = 0;
blendswipe = 'blend'; % Start in blending mode
%--------------------------------------------------------------------
% Window button down callback
function wbdcb(src,evnt)
if strcmp(get(src,'SelectionType'),'normal')
if ~blending % Turn blending on
blending = 1;
set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...
'PointerShapeHotSpot',[9 9])
set(src,'WindowButtonMotionFcn',@wbmcb)
if hspot % For paper illustration
delete(hspot);
end
else % Turn blending off
blending = 0;
set(src,'Pointer','arrow')
set(src,'WindowButtonMotionFcn','')
% For paper illustration
cp = get(ah,'CurrentPoint');
x = cp(1,1);
y = cp(1,2);
if gca == ah
hspot = plot(x, y, '.', 'color', [0 0 0], 'Markersize', 40');
end
end
end
end
%--------------------------------------------------------------------
% Window button move call back
function wbmcb(src,evnt)
cp = get(ah,'CurrentPoint');
xy = [cp(1,1); cp(1,2)];
% Project xy onto segment v1 v2
L = norm(v(:,2) - v(:,1));
v1v2 = (v(:,2) - v(:,1))/L;
w = dot( xy - v(:,1), v1v2) / L;
if w < 0, w = 0; end
if w > 1, w = 1; end
if strcmp(blendswipe, 'swipe')
swipe(1-w);
else % Blend
blend = (1-w)*basis{1} + w*basis{2};
% Various normalisation options
if normBlend == 0 % No normalisation
blend(blend>1) = 1; % but clamp values to 1
elseif normBlend == 1 || strcmpi(col, 'grey') % Normalise by max value in blend
blend = blend/max(blend(:));
elseif normBlend == 2 % Normalise to have fixed mean grey value
g = 0.299*blend(:,:,1) + 0.587*blend(:,:,2) + 0.114*blend(:,:,3);
g(isnan(g(:))) = [];
meang = mean(g(:));
blend = blend/meang*0.2; % Mean grey value of 0.2
blend(blend>1) = 1; % Clamp values to 1
elseif normBlend == 3 % Normalise so that max grey value is a fixed value
g = 0.299*blend(:,:,1) + 0.587*blend(:,:,2) + 0.114*blend(:,:,3);
blend = blend/max(g(:))*0.6; % Max grey of 0.6
blend(blend>1) = 1; % Clamp values to 1
end
set(imHandle,'CData', blend);
end
end
%-----------------------------------------------------------------------
% Key Release callback
% If 'c' is pressed the display cycles between two choices of Lightness matched
% colours and Grey.
% Pressing 's' toggles between swiping and blending modes
function keyreleasecb(src,evnt)
if evnt.Character == 'c' % Toggle colours
if strcmp(colourdisplay, 'COL1')
colourdisplay = 'COL2';
imcol = {[1.0 0.4 0.0], [0.0 0.6 1.0]};
for n = 1:2
basis{n} = applycolour(im{n}, imcol{n});
end
elseif strcmp(colourdisplay, 'COL2')
colourdisplay = 'GREY';
for n = 1:2
basis{n} = applycolour(im{n}, [1 1 1]);
end
elseif strcmp(colourdisplay, 'GREY')
colourdisplay = 'COL1';
imcol = {[0.00 0.71 0.00], [1.00 0.29 1.00]};
for n = 1:2
basis{n} = applycolour(im{n}, imcol{n});
end
end
elseif evnt.Character == 's' % Swipe/Blend toggle
if strcmp(blendswipe, 'swipe')
blendswipe = 'blend';
else
blendswipe = 'swipe';
end
end
wbmcb(src,evnt); % update the display
end
%-----------------------------------------------------------------------
% Generate swipe image given value of w between 0 and 1
function swipe(w)
x = round(w*(cols-1));
% Construct swipe image from the input images
swipeim = [basis{1}(:, 1:x, :) basis{2}(:, x+1:end, :)];
set(imHandle,'CData', swipeim);
end
%------------------------------------------------------------------------
end % of main function and its nested functions
%------------------------------------------------------------------------
% Function to set up window size nicely
function setwindowsize(fig, imsze, imposition)
screen = get(0,'ScreenSize');
scsze = [screen(4) screen(3)];
window = get(fig, 'Position');
% Set window height to match image height
window(4) = imsze(1);
% Set window width to match image width allowing for fractional width of
% image specified in imposition
window(3) = imsze(2)/imposition(3);
% Check size of window relative to screen. If larger rescale the window
% size to fit 80% of screen dimension.
winsze = [window(4) window(3)];
ratio = max(winsze./scsze);
if ratio > 1
winsze = winsze/ratio * 0.8;
end
window(3:4) = [winsze(2) winsze(1)];
set(fig, 'Position', window);
end
%----------------------------------------------------------------------------------
% Apply a colour to a scalar image
function rgbim = applycolour(im, col)
[rows,cols] = size(im);
rgbim = zeros(rows,cols,3);
for r = 1:rows
for c = 1:cols
rgbim(r,c,:) = im(r,c)*col(:);
end
end
end
|
github
|
jacksky64/imageProcessing-master
|
logisticweighting.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Blender/logisticweighting.m
| 3,064 |
utf_8
|
2896739e6134ef8ef15bfd4bc3726f12
|
% LOGISTICWEIGHTING Weighting function based on the logistics function
%
% Adaptation of the generalised logistics function for defining the variation of
% a weighting function for blending images
%
% Usage: w = logisticweighting(x, b, R)
%
% Arguments: x - Value, or array of values at which to evaluate the weighting
% function.
% b - Parameter specifying the growth rate of the logistics function.
% This controls the slope of the weighting function at its
% midpoint. Probably most convenient to specify this as a
% power of 2.
% b = 0 Perfect linear transition from wmin to wmax.
% b = 2^0 Near linear transition from wmin to wmax.
% b = 2^4 Sigmoidal transition.
% b = 2^10 Near step-like transition at midpoint.
% R - 4-vector specifying [xmin, xmax, wmin, wmax] the minimum and
% maximum weights over the minimum and maximum x values that
% will be used. The midpoint of the sigmoidal weighting
% function will occur at (xmin+xmax)/2 at a value of
% (wmin+wmax)/2. Note that if an x value outside of this range
% is supplied the resulting weight will also be outside of the
% desired range. Defaults to R = [-1 1 -1 1]
%
% Returns: w - Weight values for each supplied x-coordinate.
%
% Copyright (c) 2012 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% May 2012
function w = logisticweighting(x, b, R)
if ~exist('R', 'var'), R = [-1 1 -1 1]; end
b = max(b, 1e-10); % Constrain b to a small value that does not cause
% numerical problems
[xmin xmax wmin wmax] = deal(R(1), R(2), R(3), R(4));
xHalfRange = (xmax-xmin)/2;
wHalfRange = (wmax-wmin)/2;
M = (xmin+xmax)/2; % Midpoint of curve
% We use a form of the generalised logistics function with asymptotes -A and
% +A, and growth rate b.
%
% W(x) = A - 2*A/(1 + e^(-b*x))
%
% First, given the desired value of b, we solve for the value of A that will
% generate a generalised logistics curve centred on (0,0) and passing
% through (-xrange/2, -wrange/2) and (+xrange/2, +wrange/2)
A = wHalfRange/(1 - 2/(1+exp(-b*xHalfRange)));
% Apply an offset of M to x to shift the curve to the desired position
% and add a vertical offset to obtain the desired weighting range
w = A - 2*A./(1 + exp(-b*(x-M))) + (wmin+wHalfRange);
|
github
|
jacksky64/imageProcessing-master
|
cyclemix.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Blender/cyclemix.m
| 9,035 |
utf_8
|
3290a5ce842ce329f1eb6607a37fd6af
|
% CYCLEMIX Multi-image blending over a cyclic sequence of images
%
% Usage: cyclemix(im, figNo, nodeLabel)
%
% Arguments:
% im - A cell array of images to be blended. If omitted, or
% empty, the user is prompted to select images via a file
% dialog.
% figNo - Optional figure number.
% nodeLabel - Optional cell array of strings specifying the labels to
% be associated with the nodes on the blending interface.
%
% This function sets up an interface consisting of a circle with equispaced
% nodes around it corresponding to the input images to be blended. An
% additional virtual node corresponding to the average of all the images is
% placed at the centre of the circle. Positioning the mouse at some location
% within the circle generates an interactive blend formed from the weighted sum
% of the two image nodes that the mouse is between (in an angular sense) and
% between the central average image according to the radial position of the
% mouse.
%
% An application where this blending tool can be useful is to blend between a
% sequence of images that have been filtered according to a parameter that is
% cyclic, say an orientation filter.
%
% See also: LINIMIX, BILINIMIX, CLIQUEMIX, TERNARYMIX
% Reference:
% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.
% "Interactive Multi-Image Blending for Visualization and Interpretation",
% Computers & Geosciences 72 (2014) 147-155.
% http://doi.org/10.1016/j.cageo.2014.07.010
% Copyright (c) 2011-2014 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% August 2011 Original version
% March 2014 Cleanup and documentation
function cyclemix(im, figNo)
if ~exist('im', 'var'), im = []; end
if ~exist('figNo', 'var') || isempty(figNo)
fig = figure;
else
fig = figure(figNo);
end
[im, nImages, fname] = collectncheckimages(im);
% Compute average image
avim = zeros(size(im{1}));
for n = 1:nImages
avim = avim + im{n};
end
avim = avim/nImages;
% Generate vertices of blending polygon interface
deltaTheta = 2*pi/nImages;
theta = [0:(nImages-1)] * deltaTheta;
v = [cos(theta)
sin(theta)];
% Display 1st image and get handle to Cdata in the figure
% Suppress display warnings for images that are large
S = warning('off');
figure(fig), clf,
imposition = [0.35 0.0 0.65 1.0];
subplot('position', imposition);
imshow(normalise(im{1}), 'border', 'tight');
set(fig, 'NumberTitle', 'off')
set(fig, 'name', ' CycleMix')
set(fig, 'Menubar','none');
imHandle = get(gca,'Children');
warning(S);
% Set up interface figure
ah = subplot('position',[0.0 0.4 0.35 0.35]);
h = circle([0 0], 1, 36, [0 0 1]);
set(h,'linewidth',2)
hold on
plot(v(1,:), v(2,:), '.', 'color', [0 0 0], 'markersize', 40')
plot(v(1,:), v(2,:), '.', 'color',[.9 .9 .9], 'markersize',20)
radsc = 1.2;
for n = 1:nImages
if v(1,n) < -0.1
text(v(1,n)*radsc, v(2, n)*radsc, namenpath(fname{n}), ...
'FontSize', 16, 'FontWeight', 'bold',...
'HorizontalAlignment','right');
elseif v(1,n) > 0.1
text(v(1,n)*radsc, v(2, n)*radsc, namenpath(fname{n}), ...
'FontSize', 16, 'FontWeight', 'bold',...
'HorizontalAlignment','left');
else
text(v(1,n)*radsc, v(2, n)*radsc, namenpath(fname{n}), ...
'FontSize', 16, 'FontWeight', 'bold',...
'HorizontalAlignment','center');
end
end
r = 1.25;
axis ([-r r -r r]), axis off, axis equal
% Set callback function
set(fig,'WindowButtonDownFcn',@wbdcb);
[rows, cols, ~] = size(im{1});
setwindowsize(fig, [rows cols], imposition);
% Set up custom pointer
myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];
myPointer(~myPointer) = NaN;
fprintf('\nLeft-click to toggle blending on and off.\n');
blending = 0;
hspot = 0;
%----------------------------------------------------------------
% Window button down callback
function wbdcb(src,evnt)
if strcmp(get(src,'SelectionType'),'normal')
if ~blending % Turn blending on
blending = 1;
set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...
'PointerShapeHotSpot',[9 9])
set(src,'WindowButtonMotionFcn',@wbmcb)
if hspot % For paper illustration
delete(hspot);
end
else % Turn blending off
blending = 0;
set(src,'Pointer','arrow')
set(src,'WindowButtonMotionFcn','')
% For paper illustration
cp = get(ah,'CurrentPoint');
x = cp(1,1);
y = cp(1,2);
if gca == ah
hspot = plot(x, y, '.', 'color', [0 0 0], 'Markersize', 40');
end
end
end
end
%----------------------------------------------------------------
% Window button move call back
function wbmcb(src,evnt)
cp = get(ah,'CurrentPoint');
x = cp(1,1);
y = cp(1,2);
blend(x,y)
end
%-------------------------------------------------------------------
function blend(x,y)
% Get radius and angle of cursor relative to centre of circle
radius = min(norm([x y]), .999); % Clamp radius to a max of 1
ang = atan2(y,x);
% Define a sigmoidal weighting function for radius values ranging from 0 to
% 1 yielding weights that range from 1 to 0. This is the weighting that is
% applied to the average image associated with the centre of the circular
% interface. Using a sigmoidal function provides a slight 'flat spot' at
% the centre (and edges) of the interface where the weights do not change
% much. This makes the interface a bit easier to use near the centre
% which otherwise forms a singularity with respect to cursor movements.
radialWeight = logisticweighting(radius, 2^4, [0 1 1 0]);
% Compute angular distance to all vertices
ds = sin(theta) * cos(ang) - cos(theta) * sin(ang); % Difference in sine.
dc = cos(theta) * cos(ang) + sin(theta) * sin(ang); % Difference in cosine.
distTheta = abs(atan2(ds,dc)); % Absolute angular distance.
% First form a 2-image blend from the two images that are on each side of
% the cursor in an angular sense
% Zero out angular distances > deltaTheta, these will correspond to nodes
% that are not on each side of the cursor in an angular sense. There should
% be only two non-zero elements after this.
distTheta(distTheta > deltaTheta) = 0;
% Form normalised angular blending weights.
angularWeight = (deltaTheta-distTheta)/deltaTheta;
% Identify the indices of the non-zero weights
ind = find(distTheta);
if length(ind) == 2
blend = angularWeight(ind(1))*im{ind(1)} + angularWeight(ind(2))*im{ind(2)};
elseif length(ind) == 1 % Unlikely, but possible.
blend = angularWeight(ind(1))*im{ind(1)};
end
% Now form a 2-image blend between this image and the centre, average image.
blend = (1-radialWeight)*blend + radialWeight*avim;
blend = normalise(blend);
set(imHandle,'CData', blend);
end % end of blend
%---------------------------------------------------------------------
end % of main function and nested functions
%------------------------------------------------------------------------
% Function to set up window size nicely
function setwindowsize(fig, imsze, imposition)
screen = get(0,'ScreenSize');
scsze = [screen(4) screen(3)];
window = get(fig, 'Position');
% Set window height to match image height
window(4) = imsze(1);
% Set window width to match image width allowing for fractional width of
% image specified in imposition
window(3) = imsze(2)/imposition(3);
% Check size of window relative to screen. If larger rescale the window
% size to fit 80% of screen dimension.
winsze = [window(4) window(3)];
ratio = max(winsze./scsze);
if ratio > 1
winsze = winsze/ratio * 0.8;
end
window(3:4) = [winsze(2) winsze(1)];
set(fig, 'Position', window);
end
|
github
|
jacksky64/imageProcessing-master
|
swipe.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Blender/swipe.m
| 4,265 |
utf_8
|
127b092d90f1b8edeb9f165489e6bcb0
|
% SWIPE Interactive image swiping between 2, 3 or 4 images.
%
% Usage swipe(im, figNo)
%
% Arguments: im - 2D Cell array of images to be blended. Two, three or four
% images can be blended.
% figNo - Optional figure window number to use.
%
% Click in the image to toggle in/out of swiping mode. Move the cursor
% within the image to swipe between the input images.
%
% See also: TERNARYMIX, CYCLEMIX, CLIQUEMIX, LINIMIX, BILINIMIX
%
% Copyright (c) 2013 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% June 2013
function swipe(im, figNo)
if ~exist('im', 'var'), im = []; end
[im, nImages, fname] = collectncheckimages(im);
if isempty(im) % Cancel
return;
end
if length(im) < 2 || length(im) > 4
error('Can only swipe between 2, 3 or 4 images');
end
[rows,cols,~] = size(im{1});
fprintf('\nClick in the image to toggle in/out of swiping mode \n');
fprintf('Move the cursor within the image to \n');
fprintf('swipe between the input images\n\n');
% Set up figure and handles to image data
if exist('figNo','var')
fig = figure(figNo); clf;
else
fig = figure;
end
S = warning('off');
imshow(im{1});
% imshow(im{1}, 'border', 'tight');
drawnow
warning(S)
set(fig, 'name', 'CET Image Swiper')
set(fig,'Menubar','none');
ah = get(fig,'CurrentAxes');
imHandle = get(ah,'Children');
% Set up button down callback
set(fig,'WindowButtonDownFcn',@wbdcb);
swiping = 0;
% Set up custom pointer
myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];
myPointer(~myPointer) = NaN;
%-----------------------------------------------------------------------
% Window button down callback. This toggles swiping on and off changing the
% cursor appropriately.
function wbdcb(src,evnt)
if strcmp(get(src,'SelectionType'),'normal')
if ~swiping % Turn swiping on
swiping = 1;
set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...
'PointerShapeHotSpot',[8 8])
set(src,'WindowButtonMotionFcn',@wbmcb)
else % Turn swiping off
swiping = 0;
set(src,'Pointer','arrow')
set(src,'WindowButtonMotionFcn','')
end
end
end
%-----------------------------------------------------------------------
% Window button move call back
function wbmcb(src,evnt)
cp = round(get(ah,'CurrentPoint'));
x = cp(1,1); y = cp(1,2);
swipe(x, y)
end
%-----------------------------------------------------------------------
function swipe(x, y)
% Clamp x and y to image limits
x = max(1,x); x = min(cols,x);
y = max(1,y); y = min(rows,y);
% Construct swipe image from the input images
if length(im) == 2; % Vertical swipe between 2 images
swipeim = [im{1}(1:y, :, :)
im{2}(y+1:end, :, :)];
% Three images. 1st image occupies top half, swiped vertically. 2nd and
% 3rd images share bottom half and are swiped horizontally.
elseif length(im) == 3;
swipeim = [ im{1}(1:y, :, :)
im{2}(y+1:end, 1:x, :) im{3}(y+1:end, x+1:end, :)];
% Four input images placed in quadrants
elseif length(im) == 4;
swipeim = [im{1}(1:y, 1:x, :) im{2}(1:y, x+1:end, :)
im{3}(y+1:end, 1:x, :) im{4}(y+1:end, x+1:end, :)];
end
set(imHandle,'CData', swipeim);
set(fig, 'name', 'CET Image Swiper')
end
%---------------------------------------------------------------------------
end % of swipe
|
github
|
jacksky64/imageProcessing-master
|
cliquemix.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Blender/cliquemix.m
| 15,564 |
utf_8
|
8d782463d2676131bc2e13681c3bd26e
|
% CLIQUEMIX Multi-image blending and swiping over a clique
%
% Function allows blending and swiping between any pair within a collection of images
%
% Usage: cliquemix(im, B, figNo, nodeLabel)
%
% Arguments:
% im - A cell array of images to be blended. If omitted, or
% empty, the user is prompted to select images via a file
% dialog.
% B - Parameter controlling the weighting function when
% blending between two images.
% B = 0 Linear transition between images (default)
% B = 2^4 Sigmoidal transition at midpoint.
% B = 2^10 Near step-like transition at midpoint.
% figNo - Optional figure number.
% nodeLabel - Optional cell array of strings specifying the labels to
% be associated with the nodes on the blending interface.
%
% This function sets up an interface consisting of a regular polygon with nodes
% corresponding to the input images to be blended. Each node is conected to
% every other node forming a clique. Positioning the cursor along any of the
% edges joining two nodes will generate an interactive blend formed from the
% 2-image blend of the images connected by the edge. As the mouse is moved
% around the interface the blend snaps to the edge closest to the mouse position
% (with some hysteresis to reduce unwanted transitions). A right-click on any
% edge will lock the blending to that edge irrespective of the mouse position.
% A second right-click will unlock the edge.
%
% Hitting 's' toggles between blending and swiping mode.
%
% This tool allows you to compare any image with any other image in a collection
% with ease. However once you go beyond about 8 images the difference in edge
% lengths on the interface starts to make the tool less natural to use.
%
% See also: LINIMIX, BILINIMIX, TERNARYMIX, BINARYMIX, CYCLEMIX, LOGISTICWEIGHTING
% Reference:
% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.
% "Interactive Multi-Image Blending for Visualization and Interpretation",
% Computers & Geosciences 72 (2014) 147-155.
% http://doi.org/10.1016/j.cageo.2014.07.010
% Copyright (c) 2011-2014 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% August 2011 - Original version
% May 2012 - General rework and cleanup
% March 2014 - More tidying up
% December 2014 - Incorporation of swiping option
function cliquemix(im, B, figNo, nodeLabel)
if ~exist('B', 'var') || isempty(B), B = 0; end % linear blending
if ~exist('im', 'var'), im = []; end
if ~exist('figNo', 'var') || isempty(figNo)
fig = figure;
else
fig = figure(figNo);
end
[im, nImages, fname] = collectncheckimages(im);
% If interface node names have not been supplied use default image names
if ~exist('nodeLabel', 'var')
nodeLabel = fname;
end
% Display 1st image and get handle to Cdata in figure(2)
% Suppress display warnings for images that are large
S = warning('off');
figure(fig), clf;
imposition = [0.35 0.0 0.65 1.0];
subplot('position', imposition);
imshow(im{1},'border', 'tight'); drawnow
imHandle = get(gca,'Children');
warning(S)
% Draw the interface clique and label vertices
ah = subplot('position',[0.0 0.4 0.35 0.35]);
% Generate vertices of blending polygon interface
deltaTheta = 2*pi/nImages;
theta = [0:(nImages-1)] * deltaTheta + pi/2;
v = [cos(theta)
sin(theta)];
% Construct list of edges that link the vertices
eNo = 0;
for n = 1:(nImages-1)
for m = (n+1):nImages
eNo = eNo+1;
edge{eNo}.n1 = n;
edge{eNo}.n2 = m;
edge{eNo}.v1 = v(:,n);
edge{eNo}.v2 = v(:,m);
edge{eNo}.h = ...
line([edge{eNo}.v1(1) edge{eNo}.v2(1)], ...
[edge{eNo}.v1(2) edge{eNo}.v2(2)], ...
'LineWidth', 2);
end
end
hold on
plot(v(1,:), v(2,:), '.', 'color', [0 0 0], 'Markersize', 30')
hold off
radsc = 1.2;
for n = 1:nImages
if v(1,n) < -0.1
text(v(1,n)*radsc, v(2, n)*radsc, namenpath(nodeLabel{n}), ...
'FontSize', 16, 'FontWeight', 'bold',...
'HorizontalAlignment','right');
elseif v(1,n) > 0.1
text(v(1,n)*radsc, v(2, n)*radsc, namenpath(nodeLabel{n}), ...
'FontSize', 16, 'FontWeight', 'bold',...
'HorizontalAlignment','left');
else
text(v(1,n)*radsc, v(2, n)*radsc, namenpath(nodeLabel{n}), ...
'FontSize', 16, 'FontWeight', 'bold',...
'HorizontalAlignment','center');
end
end
r = 1.2; axis ([-r r -r r]), axis off, axis equal
% Set callback function and window title
[rows,cols,chan] = size(im{1});
setwindowsize(fig, [rows cols], imposition);
set(fig, 'WindowButtonDownFcn',@wbdcb);
set(fig, 'KeyReleaseFcn', @keyreleasecb);
set(fig, 'NumberTitle', 'off')
set(fig, 'name', ' CliqueMix')
set(fig, 'Menubar','none');
% Set up custom pointer
myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];
myPointer(~myPointer) = NaN;
blending = 0;
locked = 0;
currentEdge = 1;
blendswipe = 'blend'; % Start in blending mode
fprintf('\nLeft-click to toggle blending on and off.\n');
fprintf('Right-click to toggle edge locking on and off.\n');
fprintf('A right-click will also turn blending on if it was off\n');
fprintf('Hit ''s'' to toggle between swiping and blending modes.\n\n');
%--------------------------------------------------------------------
% Window button down callback
function wbdcb(src,evnt)
click = get(src,'SelectionType');
% Left click toggles blending
if strcmp(click,'normal')
if ~blending % Turn blending on
blending = 1;
set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...
'PointerShapeHotSpot',[9 9])
set(src,'WindowButtonMotionFcn',@wbmcb)
else % Turn blending off and unlock
blending = 0;
locked = 0;
set(src,'Pointer','arrow')
set(src,'WindowButtonMotionFcn','')
set(edge{currentEdge}.h, 'color', [0 0 1]);
end
% Right click toggles edge locking
elseif strcmp(click,'alt')
if blending && ~locked
% Lock to closest edge
e = closestedge;
if e ~= currentEdge
set(edge{currentEdge}.h, 'color', [0 0 1]);
currentEdge = e;
end
set(edge{currentEdge}.h, 'color', [1 0 0]);
locked = 1;
elseif ~blending && ~locked
% Turn blending on and lock to closest edge
blending = 1;
locked = 1;
set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...
'PointerShapeHotSpot',[9 9])
set(src,'WindowButtonMotionFcn',@wbmcb)
currentEdge = closestedge;
set(edge{currentEdge}.h, 'color', [1 0 0]);
elseif locked % Unlock
locked = 0;
set(edge{currentEdge}.h, 'color', [0 0.5 0]);
end
end
end
%--------------------------------------------------------------------
% Window button move call back
function wbmcb(src,evnt)
cp = get(ah,'CurrentPoint');
x = cp(1,1); y = cp(1,2);
[e, n1, n2, frac] = activeedge(x,y);
if strcmp(blendswipe, 'blend')
w = logisticweighting(frac, B,[0 1 0 1]);
blend = w*im{n1} + (1-w)*im{n2};
else
blend = swipe(n1, n2, frac);
end
set(imHandle,'CData', blend);
end
%---------------------------------------------------------------------
% ACTIVEEDGE
% Establish the edge in the graph that is currently 'active'. Return the node
% numbers, n1 and n2, that define the edge and the fractional distance of the
% projected cursor point along the edge from n1 to n2
%
% This version maintains a ring buffer that records the edge that the cursor
% is closest to for the last N instantiations of this function. The 'active'
% edge is set to the edge number that appears most frequently in the ring
% buffer (the mode). Seems to work quite well however the bahaviour is
% dependent on the speed of the computer. It would be good to have something
% that was tied to actual time.
function [e, n1, n2, frac] = activeedge(x,y)
N = 30; % Buffer size
persistent ebuf; % Buffer for recording which edge we have been on
persistent ptr; % Pointer into buffer.
if isempty(ebuf), ebuf = currentEdge*ones(1,N); end
if isempty(ptr), ptr = 0; end
if locked
v1 = edge{currentEdge}.v1; v2 = edge{currentEdge}.v2;
[eDist, pfrac] = dist2segment(v1, v2, x, y);
e = currentEdge;
n1 = edge{currentEdge}.n1;
n2 = edge{currentEdge}.n2;
frac = 1-pfrac;
else % Not locked. Find edge closest to x,y
eDist = zeros(1,length(edge));
pfrac = zeros(1,length(edge));
for n = 1:length(edge)
v1 = edge{n}.v1; v2 = edge{n}.v2;
[eDist(n), pfrac(n)] = dist2segment(v1, v2, x, y);
end
[minDist, ind] = min(eDist);
ptr = mod(ptr+1,N-1);
ebuf(ptr+1) = ind;
% Set edge to be the one which is most common within ebuf
e = mode(ebuf);
if e ~= currentEdge
set(edge{currentEdge}.h, 'color', [0 0 1]);
currentEdge = e;
end
set(edge{currentEdge}.h, 'color', [0 0.5 0]);
% Identify the indices of the images associated with this edge and
% also calculate the fractional position we are along this edge for
% the blending
n1 = edge{e}.n1;
n2 = edge{e}.n2;
frac = 1-pfrac(e);
end
end % of activeedge
%------------------------------------------------------------------------
% Find edge closest to cursor
function e = closestedge
cp = get(ah,'CurrentPoint');
x = cp(1,1); y = cp(1,2);
eDist = zeros(1,length(edge));
for n = 1:length(edge)
v1 = edge{n}.v1; v2 = edge{n}.v2;
eDist(n) = dist2segment(v1, v2, x, y);
end
[~, e] = min(eDist);
end
%------------------------------------------------------------------------
% Given an x,y coordinate and a line segment with end points v1 and v2. Find the
% closest point on the line segment. Return the distance to the line segment
% and the fractional distance of the closest point on the segment from v1 to v2.
function [d, frac] = dist2segment(v1, v2, x, y)
xy = [x;y];
v1v2 = v2-v1; % Vector from v1 to v2
D = norm(v1v2); % Distance v1 to v2
v1xy = xy-v1; % Vector from v1 to xy
% projection of v1xy on unit vector v1v2
proj = dot(v1v2/D, v1xy);
if proj < 0 % Closest point is v1
d = norm(v1xy);
frac = 0;
elseif proj > D % Closest point is v2
d = norm(xy-v2);
frac = 1;
else % Somewhere in the middle
pt = v1 + proj*v1v2/D;
d = norm(xy-pt);
frac = proj/D;
end
end % of dist2segment
%------------------------------------------------------------------------
% Function to set up window size nicely
function setwindowsize(fig, imsze, imposition)
screen = get(0,'ScreenSize');
scsze = [screen(4) screen(3)];
window = get(fig, 'Position');
% Set window height to match image height
window(4) = imsze(1);
% Set window width to match image width allowing for fractional width of
% image specified in imposition
window(3) = imsze(2)/imposition(3);
% Check size of window relative to screen. If larger rescale the window
% size to fit 80% of screen dimension.
winsze = [window(4) window(3)];
ratio = max(winsze./scsze);
if ratio > 1
winsze = winsze/ratio * 0.8;
end
window(3:4) = [winsze(2) winsze(1)];
set(fig, 'Position', window);
end
%-----------------------------------------------------------------------
% Generate swipe image given the two end nodes of the active edge and the
% fractional distance along the edge.
function swipeim = swipe(n1, n2, frac)
% Form vectors from the centre of the image to the corners and construct
% the dot product between v(:,n2)-v(:,n1) to determine the extreme
% corners of the image that are relevant
corner = [1 cols cols 1
1 1 rows rows];
% Vectors from centre of image to top-left, top-right, bottom-right,
% bottom-left corners.
c = corner - repmat([cols/2; rows/2], 1, 4);
% Vector from node 1 to node 2
d = v(:,n2) - v(:,n1);
d(2) = -d(2); % Negate y to match image coordinate frame
d1 = d/norm(d);
% Find c2, the index of corner direction maximally alligned with d
dotcd = c'*d; % Dot product between c and d
[~,c1] = max(dotcd);
c2 = mod((c1-1)-2, 4) + 1; % Opposite corner to c2
c1c2 = corner(:,c2)-corner(:,c1);
% Compute distance from c1 to c2 in the direction of d
dist = dot(c1c2, d1);
% Construct location that is 'frac' units along line parallel to
% v(:,n2)-v(:,n1) between the two extreme image corners
% This has to be frac*dist from c1 to c2
p = corner(:,c1) + frac*dist*d1;
% Cut the image in two at the point along a line perpendicular to
% v(:,n2)-v(:,n1) and construct a mask for defining the image parts to be
% combined.
% Form equation (p - [c;r]).d
% mask is where this value is > 0 giving all image points closest to n2
[x,y] = meshgrid(1:cols, 1:rows);
x = p(1) - x;
y = p(2) - y;
mask = (x*d(1) + y*d(2)) < 0;
swipeim = im{n2};
if chan == 1
swipeim(mask) = im{n1}(mask);
else % Colour
swipeim = zeros(rows,cols,chan);
for ch = 1:chan
swipeim(:,:,ch) = im{n1}(:,:,ch) .* mask + im{n2}(:,:,ch) .* ~mask;
end
end
end
%-----------------------------------------------------------------------
% Key Release callback
% If 's' is pressed system toggles between swiping and blending modes
function keyreleasecb(src,evnt)
if evnt.Character == 's' % Swipe/Blend toggle
if strcmp(blendswipe, 'swipe')
blendswipe = 'blend';
else
blendswipe = 'swipe';
end
end
wbmcb(src,evnt); % update the display
end
%------------------------------------------------------------------------
end % of everything
|
github
|
jacksky64/imageProcessing-master
|
collectncheckimages.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Blender/collectncheckimages.m
| 5,392 |
utf_8
|
7f3d2bd790c314d39156748f34dce0ed
|
% COLLECTNCHECKIMAGES Collects and checks images prior to blending
%
% Usage: [im, nImages, fname, pathname] = collectncheckimages(im)
%
% Used by image blending functions
%
% Argument: im - Cell arry of images. If omitted a dialog box is
% presented so that images can be selected interactively.
%
% Returns: im - Cell array of images of consistent size and colour class.
% If input images are of different sizes the images are
% trimmed to the size of the smallest image. If some
% images are colour any greyscale images are converted to
% colour by copying the image to the R G and B channels.
% nImages - Number of images in the cell array.
% fname - A cell array of the filenames of the images if they were
% interactively selected via a dialog box.
% pathname - The file path if the images were selected via a dialog
% box.
%
% If the image selection via a dialog box is cancelled all values are returned
% as empty cell arrays or 0
%
% See also: LINIMIX, BILINIMIX, TERNARYMIX, CLIQUEMIX, CYCLEMIX
% Copyright (c) 2012-2014 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% May 2012 - Original version
% March 2014 - Provison for 'im' being a 2D cell array
% August 2014 - Fix to avoid normalisation of colour images
function [im, nImages, fname, pathname] = collectncheckimages(im)
if ~exist('im', 'var') | isempty(im) % We need to select several images
fprintf('Select several images...\n');
[fname, pathname] = uigetfile({'*.png';'*.tiff';'*.jpg'},...
'MultiSelect','on');
if isnumeric(fname) && fname == 0 % Selection was cancelled
im = {};
nImages = 0;
fname = {};
pathname = {};
return
end
% If single file has been selected place its name in a single element
% cell array so that it is consistent with the rest of the code.
if isa(fname, 'char')
tmp = fname;
fname = {};
fname{1} = tmp;
end
nImages = length(fname);
im = cell(1,nImages);
for n = 1:nImages
im{n} = double(imread([pathname fname{n}]));
end
elseif iscell(im) % A cell array of images to blend has been supplied.
% Give each image a nominal name
nImages = prod(size(im)); % (im might be a 2D cell array of images)
fname = cell(1,nImages);
for n = 1:nImages
fname{n} = sprintf('%d', n);
end
pathname = '';
end
if nImages == 1 % See if we have a multi-channel image
[rows, cols, chan] = size(im{1});
assert(chan > 1, ...
'Input must be a cell arrayof images, or a multi-channel image');
% Copy the channels out into a cell array of separate images and
% generate nominal names.
nImages = chan;
tmp = im{1};
im = cell(1,nImages);
fname = cell(1,nImages);
for n = 1:nImages
im{n} = tmp(:,:,n);
fname{n} = sprintf('Band %d', n);
end
pathname = '';
end
% Check sizes of images
rows = zeros(nImages,1); cols = zeros(nImages,1); chan = zeros(nImages,1);
for n = 1:nImages
[rows(n) cols(n), chan(n)] = size(im{n});
end
% If necessary trim all images down to the size of the smallest image and
% give a warning. Given that the imput images need to be registered this
% should perhaps be classed as an error.
if ~all(rows == rows(1)) || ~all(cols == cols(1))
fprintf('Not all images are the same size\n');
fprintf('Trimming images to the match the smallest\n');
minrows = min(rows); mincols = min(cols);
for n = 1:nImages
im{n} = im{n}(1:minrows, 1:mincols, :);
end
end
% If one image is RGB ensure every image is stored as rgb, even if it
% is greyscale.
if ~(all(chan == 3) || all(chan == 1))
for n = 1:nImages
if chan(n) == 1
% Replicate image in R, G and B channels
im{n} = repmat(im{n},[1 1 3]);
end
end
end
% Finally normalise images as needed and ensure class is double. Note that
% if an input image had three channels we assume it is already normalised
% 0-255 (if uint8) or 0-1 (if double) hence we only normalise a double image
% if it originally only had one channel.
for n = 1:nImages
if strcmp(class(im{n}),'uint8')
im{n} = double(im{n})/255;
elseif chan(n) == 1
im{n} = normalise(double(im{n}));
end
end
|
github
|
jacksky64/imageProcessing-master
|
linimix.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Blender/linimix.m
| 6,641 |
utf_8
|
e8891cc28a8631536ebbdaae2a9dd1a2
|
% LINIMIX An Interactive Image for viewing multiple images
%
% Usage: linimix(im, B, figNo, XY)
%
% Arguments: im - 1D Cell array of images to be blended. If this is not
% supplied, or is empty, the user is prompted with a file
% dialog to select a series of images.
% B - Parameter controlling the weighting function when
% blending between two images.
% B = 0 Linear transition between images (default)
% B = 2^4 Sigmoidal transition at midpoint.
% B = 2^10 Near step-like transition at midpoint.
% figNo - Optional figure window number to use.
% XY - Character 'X' or 'Y' indicating whether x or y movements
% of the cursor controls the blending. Defaults to 'Y'.
%
% This function provides an 'Interactive Image'. It is intended to allow
% efficient visual exploration of a sequence of images that have been processed
% with a series of different parameter values, for example, scale. The vertical
% position of the cursor within the image controls the linear blend between
% images. With the cursor at the top the first image is displayed, at the
% bottom the last image is displayed. At positions in between blends of
% intermediate images are dislayed.
%
% Click in the image to toggle in/out of blending mode. Move the cursor up and
% down within the image to blend between the input images.
%
% Use BILINIMIX if you want the horizontal position of the cursor to be used
% too. This will allow visual exploration of a sequence of images controlled by
% two different processing parameters. Alternatively one could blend between
% images of two different modalities over some varing parameter, say scale.
%
% See also: BILINIMIX, TERNARYMIX, CLIQUEMIX, CYCLEMIX, LOGISTICWEIGHTING
% Reference:
% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.
% "Interactive Multi-Image Blending for Visualization and Interpretation",
% Computers & Geosciences 72 (2014) 147-155.
% http://doi.org/10.1016/j.cageo.2014.07.010
% Copyright (c) 2012-2014 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% March 2012
% March 2014 - Allow horizontal or vertical mouse movements to control blending
function linimix(im, B, figNo, XY)
if ~exist('im', 'var'), im = []; end
[im, nImages, fname] = collectncheckimages(im);
if ~exist('B', 'var') || isempty(B), B = 0; end
if exist('figNo','var')
fig = figure(figNo); clf;
else
fig = figure;
end
if ~exist('XY', 'var'), XY = 'Y'; end
XY = upper(XY);
% Generate nodes for the multi-image linear blending
[rows,cols,~] = size(im{1});
if XY == 'Y'
v = round([0:1/(nImages-1):1] * rows);
elseif XY == 'X'
v = round([0:1/(nImages-1):1] * cols);
else
error('XY must be ''x'' or ''y'' ')
end
fprintf('\nClick in the image to toggle in/out of blending mode \n');
fprintf('Move the cursor within the image to blend between the input images.\n\n');
S = warning('off');
imshow(im{ max(1,fix(nImages/2)) }, 'border', 'tight');
% imshow(im{ max(1,fix(nImages/2)) });
% Uncomment the following line if you want axes displayed
% imagesc(im{ max(1,fix(nImages/2)) }); colormap(gray(256))
drawnow
warning(S)
ah = get(fig,'CurrentAxes');
imHandle = get(ah,'Children'); % Handle to image data
% Set up button down callback and window title
set(fig, 'WindowButtonDownFcn',@wbdcb);
set(fig, 'NumberTitle', 'off')
set(fig, 'name', 'CET Linear Image Blender')
set(fig, 'Menubar','none');
blending = 0;
% Set up custom pointer
myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];
myPointer(~myPointer) = NaN;
hspot = 0;
hold on
%-----------------------------------------------------------------------
% Window button down callback. This toggles blending on and off changing the
% cursor appropriately.
function wbdcb(src,evnt)
if strcmp(get(src,'SelectionType'),'normal')
if ~blending % Turn blending on
blending = 1;
set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...
'PointerShapeHotSpot',[9 9])
set(src,'WindowButtonMotionFcn',@wbmcb)
if hspot % For paper illustration
delete(hspot);
end
else % Turn blending off
blending = 0;
set(src,'Pointer','arrow')
set(src,'WindowButtonMotionFcn','')
% For paper illustration (need marker size of 95 if using export_fig)
cp = get(ah,'CurrentPoint');
x = cp(1,1);
y = cp(1,2);
hspot = plot(x, y, '.', 'color', [0 0 0], 'Markersize', 50');
end
end
end
%-----------------------------------------------------------------------
% Window button move call back
function wbmcb(src,evnt)
cp = get(ah,'CurrentPoint');
if XY == 'Y'
p = cp(1,2);
p = max(0,p); p = min(rows,p); % clamp to range 0-rows
else
p = cp(1,1);
p = max(0,p); p = min(cols,p); % clamp to range 0-cols
end
blend(p)
end
%-----------------------------------------------------------------------
function blend(p)
% Find distance from each of the vertices v
dist = abs(v - p);
% Find the two closest vertices
[dist, ind] = sort(dist);
% w1 is the fractional distance from the cursor to the 2nd image
% relative to the distance between the 1st and 2nd images
w1 = dist(2)/(dist(1)+dist(2));
% Apply the logistics wighting function to w1 to obtain the desired
% transition weighting
w = logisticweighting(w1, B, [0 1 0 1]);
blendim = w*im{ind(1)} + (1-w)*im{ind(2)};
set(imHandle,'CData', blendim);
set(fig, 'name', 'CET Image Blender');
end
%---------------------------------------------------------------------------
end % of linimix
|
github
|
jacksky64/imageProcessing-master
|
bilinimix.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Blender/bilinimix.m
| 5,635 |
utf_8
|
f1768150812e05ba0dbf1f8ac2b8e2ec
|
% BILINIMIX An Interactive Image for viewing multiple images
%
% Usage: bilinimix(im, figNo)
%
% Arguments: im - 2D Cell array of greyscale images to be blended.
% figNo - Optional figure window number to use.
%
% This function provides an 'Interactive Image'. It is intended to allow
% efficient visual exploration of a sequence of images that have been processed
% with a series of two different parameter values, for example, scale and image
% mix. The horizontal and vertical position of the cursor within the image
% controls the bilinear blend of the two parameters over the images.
%
% To achieve this you need to prepare a set of images that cover a coarsely
% quantized range of properties you want to view. Think of these images as
% being arranged in a 2D grid corresponding to the 2D cell array of images
% supplied to the function. Positioning the cursor at some location within the
% grid will result in a blended image being constructed from the bilinear
% interpolation of the 4 images surrounding the cursor position.
%
% Click in the image to toggle in/out of blending mode. Move the cursor
% within the image to blend between the input images.
%
% See also: LINIMIX, TERNARYMIX, CLIQUEMIX, CYCLEMIX, LOGISTICWEIGHTING
%
% Note this code is a bit rough in places but is still reasonably useful at this
% stage. I suggest you stick with greyscale images at this stage.
% Reference:
% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.
% "Interactive Multi-Image Blending for Visualization and Interpretation",
% Computers & Geosciences 72 (2014) 147-155.
% http://doi.org/10.1016/j.cageo.2014.07.010
% Copyright (c) 2012-2014 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% April 2012 - Original version
% March 2014 - General cleanup
function bilinimix(im, figNo)
assert(iscell(im), 'Input images must be in a cell array');
[gridRows gridCols] = size(im);
[im, nImages, fname] = collectncheckimages(im);
[minrows,mincols,~] = size(im{1,1});
fprintf('\nClick in the image to toggle in/out of blending mode \n');
fprintf('Move the cursor up-down and left-right within the image to \n');
fprintf('blend between the input images\n\n');
if exist('figNo','var')
fig = figure(figNo); clf
else
fig = figure;
end
S = warning('off');
imshow(im{ max(1,fix(nImages/2)) }, 'border', 'tight');
drawnow
warning(S)
ah = get(fig,'CurrentAxes');
imHandle = get(ah,'Children'); % Gives access to Cdata in the figure
% Set up button down callback and window title
set(fig, 'WindowButtonDownFcn',@wbdcb);
set(fig, 'NumberTitle', 'off')
set(fig, 'name', 'CET Bilinear Image Blender')
set(fig, 'Menubar','none');
blending = 0;
% Set up custom pointer
myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];
myPointer(~myPointer) = NaN;
hspot = 0;
hold on
%-----------------------------------------------------------------------
% Window button down callback
function wbdcb(src,evnt)
if strcmp(get(src,'SelectionType'),'normal')
if ~blending % Turn blending on
blending = 1;
set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...
'PointerShapeHotSpot',[9 9])
set(src,'WindowButtonMotionFcn',@wbmcb)
if hspot % For paper illustration
delete(hspot);
end
else % Turn blending off
blending = 0;
set(src,'Pointer','arrow')
set(src,'WindowButtonMotionFcn','')
% For paper illustration (need marker size of 95 if using export_fig)
cp = get(ah,'CurrentPoint');
x = cp(1,1);
y = cp(1,2);
hspot = plot(x, y, '.', 'color', [0 0 0], 'Markersize', 50');
end
end
end
%-----------------------------------------------------------------------
% Window button move call back
function wbmcb(src,evnt)
cp = get(ah,'CurrentPoint');
x = cp(1,1); y = cp(1,2);
blend(x, y)
end
%-----------------------------------------------------------------------
function blend(x, y)
% Clamp x and y to image limits
x = max(0,x); x = min(mincols,x);
y = max(0,y); y = min(minrows,y);
% Compute grid coodinates of (x,y)
% im{1,1} im{1,2} ... im{1, gridCols}
% .. .. ..
% im{gridRows,1} .. ... im{gridRows, gridCols}
gx = x/mincols * (gridCols-1) + 1;
gy = y/minrows * (gridRows-1) + 1;
% Compute bilinear interpolation between the images
gxf = floor(gx); gxc = ceil(gx);
gyf = floor(gy); gyc = ceil(gy);
frac = gxc-gx;
blendyf = (frac)*im{gyf,gxf} + (1-frac)*im{gyf,gxc};
blendyc = (frac)*im{gyc,gxf} + (1-frac)*im{gyc,gxc};
frac = gyc-gy;
blendim = (frac)*blendyf + (1-frac)*blendyc;
set(imHandle,'CData', blendim);
end
%---------------------------------------------------------------------------
end % of bilinimix
|
github
|
jacksky64/imageProcessing-master
|
findendsjunctions.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/LineSegments/findendsjunctions.m
| 3,885 |
utf_8
|
1c766254222e0b8fd5326786249247bf
|
% FINDENDSJUNCTIONS - find junctions and endings in a line/edge image
%
% Usage: [rj, cj, re, ce] = findendsjunctions(edgeim, disp)
%
% Arguments: edgeim - A binary image marking lines/edges in an image. It is
% assumed that this is a thinned or skeleton image
% disp - An optional flag 0/1 to indicate whether the edge
% image should be plotted with the junctions and endings
% marked. This defaults to 0.
%
% Returns: rj, cj - Row and column coordinates of junction points in the
% image.
% re, ce - Row and column coordinates of end points in the
% image.
%
% See also: EDGELINK
%
% Note I am not sure if using bwmorph's 'thin' or 'skel' is best for finding
% junctions. Skel can result in an image where multiple adjacent junctions are
% produced (maybe this is more a problem with this junction detection code).
% Thin, on the other hand, can produce different output when you rotate an image
% by 90 degrees. On balance I think using 'thin' is better. Skeletonisation and
% thinning is surprisingly awkward.
% Copyright (c) 2006-2013 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% November 2006 - Original version
% May 2013 - Call to bwmorph to ensure image is thinned was removed as
% this might cause problems if the image used to find
% junctions is different from the image used for, say,
% edgelinking
function [rj, cj, re, ce] = findendsjunctions(b, disp)
if nargin == 1
disp = 0;
end
% Set up look up table to find junctions. To do this we use the function
% defined at the end of this file to test that the centre pixel within a 3x3
% neighbourhood is a junction.
lut = makelut(@junction, 3);
junctions = applylut(b, lut);
[rj,cj] = find(junctions);
% Set up a look up table to find endings.
lut = makelut(@ending, 3);
ends = applylut(b, lut);
[re,ce] = find(ends);
if disp
show(edgeim,1), hold on
plot(cj,rj,'r+')
plot(ce,re,'g+')
end
%----------------------------------------------------------------------
% Function to test whether the centre pixel within a 3x3 neighbourhood is a
% junction. The centre pixel must be set and the number of transitions/crossings
% between 0 and 1 as one traverses the perimeter of the 3x3 region must be 6 or
% 8.
%
% Pixels in the 3x3 region are numbered as follows
%
% 1 4 7
% 2 5 8
% 3 6 9
function b = junction(x)
a = [x(1) x(2) x(3) x(6) x(9) x(8) x(7) x(4)]';
b = [x(2) x(3) x(6) x(9) x(8) x(7) x(4) x(1)]';
crossings = sum(abs(a-b));
b = x(5) && crossings >= 6;
%----------------------------------------------------------------------
% Function to test whether the centre pixel within a 3x3 neighbourhood is an
% ending. The centre pixel must be set and the number of transitions/crossings
% between 0 and 1 as one traverses the perimeter of the 3x3 region must be 2.
%
% Pixels in the 3x3 region are numbered as follows
%
% 1 4 7
% 2 5 8
% 3 6 9
function b = ending(x)
a = [x(1) x(2) x(3) x(6) x(9) x(8) x(7) x(4)]';
b = [x(2) x(3) x(6) x(9) x(8) x(7) x(4) x(1)]';
crossings = sum(abs(a-b));
b = x(5) && crossings == 2;
|
github
|
jacksky64/imageProcessing-master
|
selectseg.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/LineSegments/selectseg.m
| 3,097 |
utf_8
|
bdbe2a909309c465b0131e308d8ddc32
|
% SELECTSEG - Interactive selection of linesegments with mouse.
%
% Usage: segs = selectseg(seglist);
%
% seglist - an Nx4 array storing line segments in the form
% [x1 y1 x2 y2
% x1 y1 x2 y2
% . . ] etc
%
%
% See also: EDGELINK, LINESEG, MAXLINEDEV, MERGESEG
%
% Copyright (c) 2000-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% December 2000
function segs = selectseg(seglist);
segs = [];
selectedSegs = [NaN];
figure(1), clf, drawseg(seglist,1);
Nseg = size(seglist,1);
fprintf('Select segments by clicking with the left mouse button\n');
fprintf('Last segment is indicated by clicking with any other mouse button\n');
count = 0;
but = 1;
while but==1 & count < Nseg
[xp,yp,but] = ginput(1); % Get digitised point
count = count + 1;
rmin = Inf;
for s = 1:Nseg
r = segdist(xp,yp,seglist(s,:));
% if distance is closest so far and segment is not already
% selected...
if r < rmin & ~any(selectedSegs==s)
rmin = r;
closestseg = seglist(s,:);
smin = s;
end
end
segs = [segs; closestseg]; % Build up list of segments
selectedSegs = [selectedSegs smin]; % Remeber selected seg Nos
line([closestseg(1) closestseg(3)], [closestseg(2) closestseg(4)], ...
'Color',[1 0 0]);
text((closestseg(1)+closestseg(3))/2, ...
(closestseg(2)+closestseg(4))/2, sprintf('%d',count));
end
function r = segdist(xp,yp,seg)
% Function returns distance from point (xp,yp) to line defined by end
% points (x1,y1) (x2,y2)
%
%
% Eqn of line joining end pts (x1 y1) and (x2 y2) can be parameterised by
%
% x*(y1-y2) + y*(x2-x1) + y2*x1 - y1*x2 = 0
%
% (See Jain, Rangachar and Schunck, "Machine Vision", McGraw-Hill
% 1996. pp 194-196)
x1=seg(1);y1=seg(2);
x2=seg(3);y2=seg(4);
y1my2 = y1-y2; % Pre-compute parameters
x2mx1 = x2-x1;
C = y2*x1 - y1*x2;
D = norm([x1 y1] - [x2 y2]); % Distance between end points
r = abs(xp*y1my2 + yp*x2mx1 + C)/D; % Perp. distance from line to (xp,yp)
% Correct the distance if (xp,yp) is `outside' the ends of the segment
d1 = [xp yp]-[x1 y1];
d2 = [xp yp]-[x2 y2];
if dot(d1,d2) > 0 % (xp,yp) is not `between' the end points of the
% segment
r = min(norm(d1),norm(d2)); % return distance to closest end
% point
end
|
github
|
jacksky64/imageProcessing-master
|
maxlinedev.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/LineSegments/maxlinedev.m
| 2,478 |
utf_8
|
64cc6d88009aa2a148c843e2d4041218
|
% MAXLINEDEV - Find max deviation from a line in an edge contour.
%
% Function finds the point of maximum deviation from a line joining the
% endpoints of an edge contour.
%
% Usage: [maxdev, index, D, totaldev] = maxlinedev(x,y)
%
% Arguments:
% x, y - arrays of x,y (col,row) indicies of connected pixels
% on the contour.
% Returns:
% maxdev - Maximum deviation of contour point from the line
% joining the end points of the contour (pixels).
% index - Index of the point having maxdev.
% D - Distance between end points of the contour so that
% one can calculate maxdev/D - the normalised error.
% totaldev - Sum of the distances of all the pixels from the
% line joining the endpoints.
%
% See also: EDGELINK, LINESEG
%
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% December 2000 - Original version
% February 2003 - Added calculation of total deviation
% August 2006 - Avoid degeneracy when endpoints are coincident
% February 2007 - Corrected distance calculation when endpoints are
% coincident.
function [maxdev, index, D, totaldev] = maxlinedev(x,y)
Npts = length(x);
if Npts == 1
warning('Contour of length 1');
maxdev = 0; index = 1;
D = 1; totaldev = 0;
return;
elseif Npts == 0
error('Contour of length 0');
end
% D = norm([x(1) y(1)] - [x(Npts) y(Npts)]); % Distance between end points
D = sqrt((x(1)-x(Npts))^2 + (y(1)-y(Npts))^2); % This runs much faster
if D > eps
% Eqn of line joining end pts (x1 y1) and (x2 y2) can be parameterised by
%
% x*(y1-y2) + y*(x2-x1) + y2*x1 - y1*x2 = 0
%
% (See Jain, Rangachar and Schunck, "Machine Vision", McGraw-Hill
% 1996. pp 194-196)
y1my2 = y(1)-y(Npts); % Pre-compute parameters
x2mx1 = x(Npts)-x(1);
C = y(Npts)*x(1) - y(1)*x(Npts);
% Calculate distance from line segment for each contour point
d = abs(x*y1my2 + y*x2mx1 + C)/D;
else % End points are coincident, calculate distances from 1st point
d = sqrt((x - x(1)).^2 + (y - y(1)).^2);
D = 1; % Now set D to 1 so that normalised error can be used
end
[maxdev, index] = max(d);
if nargout == 4
totaldev = sum(d.^2);
end
|
github
|
jacksky64/imageProcessing-master
|
findisolatedpixels.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/LineSegments/findisolatedpixels.m
| 1,342 |
utf_8
|
e3a3768f5d589a865aa10a992e5197e2
|
% FINDENDSJUNCTIONS - find isolated pixels in a binary image
%
% Usage: [r, c] = findisolatedpixels(b)
%
% Argument: b - A binary image
%
% Returns: r, c - Row and column coordinates of isolated pixels in the
% image.
%
% See also: FINDENDSJUNCTIONS
%
% Copyright (c) 2013 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% May 2013
function [r, c] = findisolatedpixels(b)
lut = makelut(@isolated, 3);
isolated = applylut(b, lut);
[r, c] = find(isolated);
%----------------------------------------------------------------------
% Function to test whether the centre pixel within a 3x3 neighbourhood is
% isolated.
%
% Pixels in the 3x3 region are numbered as follows
%
% 1 4 7
% 2 5 8
% 3 6 9
function b = isolated(x)
b = x(5) && sum(x(:)) == 1;
|
github
|
jacksky64/imageProcessing-master
|
drawedgelist.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/LineSegments/drawedgelist.m
| 5,139 |
utf_8
|
37224c54b8034d4fadf13c9b60861db5
|
% DRAWEDGELIST - plots pixels in edgelists
%
% Usage: h = drawedgelist(edgelist, rowscols, lw, col, figno, mid)
%
% Arguments:
% edgelist - Cell array of edgelists in the form
% { [r1 c1 [r1 c1 etc }
% ...
% rN cN] ....]
% rowscols - Optional 2 element vector [rows cols] specifying the size
% of the image from which edges were detected (used to set
% size of plotted image). If omitted or specified as [] this
% defaults to the bounds of the linesegment points
% lw - Optional line width specification. If omitted or specified
% as [] it defaults to a value of 1;
% col - Optional colour specification. Eg [0 0 1] for blue. This
% can also be specified as the string 'rand' to generate a
% random color coding for each edgelist so that it is easier
% to see how the edges have been broken up into separate
% lists. If omitted or specified as [] it defaults to blue.
% col can also be a N x 3 array of colours where N is the
% length of edgelist, thus specifying a particulr colour for
% each edge.
% figno - Optional figure number in which to display image.
% mid - Optional flag 0/1. If set each edge is drawn by joining
% the mid points betwen points along the edge lists. This is
% intended only to be used for edgelists at pixel resolution.
% It reduces staircasing on diagonal lines giving nicer output.
%
% Returns:
% h - Array of handles to each plotted edgelist
%
% See also: EDGELINK, LINESEG
% Copyright (c) 2003-2013 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% February 2003 - Original version
% September 2004 - Revised and updated
% December 2006 - Colour and linewidth specification updated
% January 2011 - Axis setting corrected (thanks to Stzpz)
% July 2013 - Colours can be specified for each edge
% Feb 2014 - Code cleanup + mid segment drawing option
function h = drawedgelist(edgelist, rowscols, lw, col, figno, mid)
if ~exist('rowscols', 'var') | isempty(rowscols), rowscols = [1 1]; end
if ~exist('lw', 'var') | isempty(lw), lw = 1; end
if ~exist('col', 'var') | isempty(col), col = [0 0 1]; end
if exist('figno', 'var'), figure(figno); end
if ~exist('mid', 'var'), mid = 0; end
debug = 0;
Nedge = length(edgelist);
h = zeros(length(edgelist),1);
% Set up edge colours
if strcmp(col,'rand')
col = hsv(Nedge); % HSV colour map with Nedge entries
col = col(randperm(Nedge),:); % Form random permutation of colours
elseif all(size(col) == [1 3]) % Single colour for all edges
col = repmat(col,[Nedge 1]);
elseif all(size(col) == [Nedge 3]) % Colour for each edge specified
; % we do not need to do anything
else
error('Colour not specified properly');
end
if mid
for I = 1:Nedge
melist = midedge(edgelist{I});
h(I) = line(melist(:,2), melist(:,1),...
'LineWidth', lw, 'Color', col(I,:));
end
else
for I = 1:Nedge
h(I) = line(edgelist{I}(:,2), edgelist{I}(:,1),...
'LineWidth', lw, 'Color', col(I,:));
end
end
if debug
for I = 1:Nedge
mid = fix(length(edgelist{I})/2);
text(edgelist{I}(mid,2), edgelist{I}(mid,1),sprintf('%d',I))
end
end
% Check whether we need to expand bounds
minx = 1; miny = 1;
maxx = rowscols(2); maxy = rowscols(1);
for I = 1:Nedge
minx = min(min(edgelist{I}(:,2)),minx);
miny = min(min(edgelist{I}(:,1)),miny);
maxx = max(max(edgelist{I}(:,2)),maxx);
maxy = max(max(edgelist{I}(:,1)),maxy);
end
axis('equal'); axis('ij');
axis([minx maxx miny maxy]);
if nargout == 0
clear h
end
%------------------------------------------------------------------------
% Function to construct a new edge list formed by stepping through the mid
% points of each segment of the edgelist. The idea is to form a smoother path
% along the edgelist. This is intended for edgelists formed at pixel
% resolution.
function melist = midedge(elist)
melist = [elist(1,:); (elist(1:end-1, :) + elist(2:end, :))/2; elist(end,:)];
|
github
|
jacksky64/imageProcessing-master
|
lineseg.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/LineSegments/lineseg.m
| 3,017 |
utf_8
|
ff2e4a5d3f9faabdf548561ed00b22b6
|
% LINESEG - Form straight line segements from an edge list.
%
% Usage: seglist = lineseg(edgelist, tol)
%
% Arguments: edgelist - Cell array of edgelists where each edgelist is an
% Nx2 array of (row col) coords.
% tol - Maximum deviation from straight line before a
% segment is broken in two (measured in pixels).
% Returns:
% seglist - A cell array of in the same format of the input
% edgelist but each seglist is a subsampling of its
% corresponding edgelist such that straight line
% segments between these subsampled points do not
% deviate from the original points by more than tol.
%
% This function takes each array of edgepoints in edgelist, finds the
% size and position of the maximum deviation from the line that joins the
% endpoints, if the maximum deviation exceeds the allowable tolerance the
% edge is shortened to the point of maximum deviation and the test is
% repeated. In this manner each edge is broken down to line segments,
% each of which adhere to the original data with the specified tolerance.
%
% See also: EDGELINK, MAXLINEDEV, DRAWEDGELIST
%
% Copyright (c) 2000-2006 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% December 2000 - Original version
% February 2003 - Added the returning of nedgelist data.
% December 2006 - Changed so that separate cell arrays of line segments are
% formed, in the same format used for edgelists
function seglist = lineseg(edgelist, tol)
Nedge = length(edgelist);
seglist = cell(1,Nedge);
for e = 1:Nedge
y = edgelist{e}(:,1); % Note that (col, row) corresponds to (x,y)
x = edgelist{e}(:,2);
fst = 1; % Indices of first and last points in edge
lst = length(x); % segment being considered.
Npts = 1;
seglist{e}(Npts,:) = [y(fst) x(fst)];
while fst<lst
[m,i] = maxlinedev(x(fst:lst),y(fst:lst)); % Find size & posn of
% maximum deviation.
while m > tol % While deviation is > tol
lst = i+fst-1; % Shorten line to point of max deviation by adjusting lst
[m,i] = maxlinedev(x(fst:lst),y(fst:lst));
end
Npts = Npts+1;
seglist{e}(Npts,:) = [y(lst) x(lst)];
fst = lst; % reset fst and lst for next iteration
lst = length(x);
end
end
|
github
|
jacksky64/imageProcessing-master
|
filledgegaps.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/LineSegments/filledgegaps.m
| 3,911 |
utf_8
|
f36cafd2cfd5507602b58f0ebfc6f549
|
% FILLEDGEGAPS Fills small gaps in a binary edge map image
%
% Usage: bw2 = filledgegaps(bw, gapsize)
%
% Arguments: bw - Binary edge image
% gapsize - The edge gap size that you wish to be able to fill.
% Use the smallest value you can. (Odd values work best).
%
% Returns: bw2 - The binary edge image with gaps filled.
%
%
% Strategy: A binary circular blob of radius = gapsize/2 is placed at the end of
% every edge segment. If the ends of two edge segments are in close proximity
% the circular blobs will overlap. The image is then thinned. Where circular
% blobs at end points overlap the thinning process will leave behind a line of
% pixels linking the two end points. Where an end point is isolated the
% thinning process will erode the circular blob away so that the original edge
% segment is restored.
%
% Use the smallest gapsize value you can. With large values all sorts of
% unwelcome linking can occur.
%
% The circular blobs are generated using the function CIRCULARSTRUCT which,
% unlike MATLAB's STREL, will accept real valued radius values. Note that I
% suggest that you use an odd value for 'gapsize'. This results in a radius
% value of the form x.5 being passed to CIRCULARSTRUCT which results in discrete
% approximation to a circle that seems to respond to thinning in a 'good'
% way. With integer radius values CIRCULARSTRUCT can produce circles that
% result in minor artifacts being generated by the thinning process.
%
% See also: FINDENDSJUNCTIONS, FINDISOLATEDPIXELS, CIRCULARSTRUCT, EDGELINK
% Copyright (c) 2013 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% PK May 2013
function bw = filledgegaps(bw, gapsize)
[rows, cols] = size(bw);
% Generate a binary circle with radius gapsize/2 (but not less than 1)
blob = circularstruct(max(gapsize/2, 1));
rad = (size(blob,1)-1)/2; % Radius of resulting blob matrix. Note
% circularstruct returns an odd sized matrix
% Get coordinates of end points and of isolated pixels
[~, ~, re, ce] = findendsjunctions(bw);
[ri, ci] = findisolatedpixels(bw);
re = [re;ri];
ce = [ce;ci];
% Place a circular blob at every endpoint and isolated pixel
for n = 1:length(re)
if (re(n) > rad) && (re(n) < rows-rad) && ...
(ce(n) > rad) && (ce(n) < cols-rad)
bw(re(n)-rad:re(n)+rad, ce(n)-rad:ce(n)+rad) = ...
bw(re(n)-rad:re(n)+rad, ce(n)-rad:ce(n)+rad) | blob;
end
end
bw = bwmorph(bw, 'thin', inf); % Finally thin
% At this point, while we may have joined endpoints that were close together
% we typically have also generated a number of small loops where there were
% more than one endpoint close to an edge. To address this we identfy the
% loops by finding 4-connected blobs in the inverted image. Blobs that are
% less than or equal to the size of the blobs we used to link edges are
% filled in, the image reinverted and then rethinned.
L = bwlabel(~bw,4);
stats = regionprops(L, 'Area');
% Get blobs with areas <= pi* (gapsize/2)^2
ar = cat(1,stats.Area);
ind = find(ar <= pi*(gapsize/2)^2);
% Fill these blobs in image bw
for n = ind'
bw(L==n) = 1;
end
bw = bwmorph(bw, 'thin', inf); % thin again
|
github
|
jacksky64/imageProcessing-master
|
cleanedgelist.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/LineSegments/cleanedgelist.m
| 13,314 |
utf_8
|
a79468f2b92f2ce262730a04d766d643
|
% CLEANEDGELIST - remove short edges from a set of edgelists
%
% Function to clean up a set of edge lists generated by EDGELINK so that
% isolated edges and spurs that are shorter that a minimum length are removed.
% This code can also be use with a set of line segments generated by LINESEG.
%
% Usage: nedgelist = cleanedgelist(edgelist, minlength)
%
% Arguments:
% edgelist - a cell array of edge lists in row,column coords in
% the form
% { [r1 c1 [r1 c1 etc }
% r2 c2 ...
% ...
% rN cN] ....]
% minlength - minimum edge length of interest
%
% Returns:
% nedgelist - the new, cleaned up set of edgelists
%
% See also: EDGELINK, DRAWEDGELIST, LINESEG
% Copyright (c) 2006-2007 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% December 2006 Original version
% February 2007 A major rework to fix several problems, hope they really are
% fixed!
function nedgelist = cleanedgelist(edgelist, minlength)
Nedges = length(edgelist);
Nnodes = 2*Nedges;
% Each edgelist has two end nodes - the starting point and the ending point.
% We build up an adjacency/connection matrix for each node so that we can
% determine which, if any, edgelists are connected to a node. We also
% maintain an adjacency matrix for the edges themselves.
%
% It is tricky maintaining all this information but it does allow the
% code to run much faster.
% First extract the end nodes from each edgelist. The nodes are numbered
% so that the start node has number 2*edgenumber-1 and the end node has
% number 2*edgenumber
node = zeros(Nnodes, 2);
for n = 1:Nedges
node(2*n-1,:) = edgelist{n}(1,:);
node(2*n ,:) = edgelist{n}(end,:);
end
% Now build the adjacency/connection matrices.
A = zeros(Nnodes); % Adjacency matrix for nodes
B = zeros(Nedges); % Adjacency matrix for edges
for n = 1:Nnodes-1
for m = n+1:Nnodes
% If nodes m & n are connected
A(n,m) = node(n,1)==node(m,1) && node(n,2)==node(m,2);
A(m,n) = A(n,m);
if A(n,m)
edgen = fix((n+1)/2);
edgem = fix((m+1)/2);
B(edgen, edgem) = 1;
B(edgem, edgen) = 1;
end
end
end
% If we sum the columns of the adjacency matrix we get the number of
% other edgelists that are connected to an edgelist
Nconnections = sum(A); % Connection count array for nodes
Econnections = sum(B); % Connection count array for edges
% Check every edge to see if any of its ends are connected to just one edge.
% This should not happen, but occasionally does due to a problem in
% EDGELINK. Here we simply merge it with the edge it is connected to.
% Ultimately I want to be able to remove this block of code.
% I think there are also some cases that are (still) not properly handled
% by CLEANEDGELIST and there may be a case for repeating this block of
% code at the end for another final cleanup pass
for n = 1:Nedges
if ~B(n,n) && ~isempty(edgelist{n}) % if edge is not connected to itself
[spurdegree, spurnode, startnode, sconns, endnode, econns] = connectioninfo(n);
if sconns == 1
node2merge = find(A(startnode,:));
mergenodes(node2merge,startnode);
end
if ~isempty(edgelist{n}) % If we have not removed this edge in
% the code above check the other end.
if econns == 1
node2merge = find(A(endnode,:));
mergenodes(node2merge,endnode);
end
end
end
end
% Now check every edgelist, if the edgelength is below the minimum length
% check if we should remove it.
if minlength > 0
for n = 1:Nedges
[spurdegree, spurnode] = connectioninfo(n);
if ~isempty(edgelist{n}) && edgelistlength(edgelist{n}) < minlength
% Remove unconnected lists, or lists that are only connected to
% themselves.
if ~Econnections(n) || (Econnections(n)==1 && B(n,n) == 1)
removeedge(n);
% Process edges that are spurs coming from a 3-way junction.
elseif spurdegree == 2
%fprintf('%d is a spur\n',n) %%debug
linkingedges = find(B(n,:));
if length(linkingedges) == 1 % We have a loop with a spur
% coming from the join in the
% loop
% Just remove the spur, leaving the loop intact.
removeedge(n);
else % Check the other edges coming from this point. If any
% are also spurs make sure we remove the shortest one
spurs = n;
len = edgelistlength(edgelist{n});
for i = 1:length(linkingedges)
spurdegree = connectioninfo(linkingedges(i));
if spurdegree
spurs = [spurs linkingedges(i)];
len = [len edgelistlength(edgelist{linkingedges(i)})];
end
end
linkingedges = [linkingedges n];
[mn,i] = min(len);
edge2delete = spurs(i);
[spurdegree, spurnode] = connectioninfo(edge2delete);
nodes2merge = find(A(spurnode,:));
if length(nodes2merge) ~= 2
error('attempt to merge other than 2 nodes');
end
removeedge(edge2delete);
mergenodes(nodes2merge(1),nodes2merge(2))
end
% Look for spurs coming from 4-way junctions that are below the minimum length
elseif spurdegree == 3
removeedge(n); % Just remove it, no subsequent merging needed.
end
end
end
% Final cleanup of any new isolated edges that might have been created by
% removing spurs. An edge is isolated if it has no connections to other
% edges, or is only connected to itself (in a loop).
for n = 1:Nedges
if ~isempty(edgelist{n}) && edgelistlength(edgelist{n}) < minlength
if ~Econnections(n) || (Econnections(n)==1 && B(n,n) == 1)
removeedge(n);
end
end
end
end % if minlength > 0
% Run through the edgelist and extract out the non-empty lists
m = 0;
for n = 1:Nedges
if ~isempty(edgelist{n})
m = m+1;
nedgelist{m} = edgelist{n};
end
end
%----------------------------------------------------------------------
% Internal function to merge 2 edgelists together at the specified nodes and
% perform the necessary updates to the edge adjacency and node adjacency
% matrices and the connection count arrays
function mergenodes(n1,n2)
edge1 = fix((n1+1)/2); % Indices of the edges associated with the nodes
edge2 = fix((n2+1)/2);
% Get indices of nodes at each end of the two edges
s1 = 2*edge1-1; e1 = 2*edge1;
s2 = 2*edge2-1; e2 = 2*edge2;
if edge1==edge2
% We should not get here, but somehow we occasionally do
% fprintf('Nodes %d %d\n',n1,n2) %% debug
% warning('Attempt to merge an edge with itself')
return
end
if ~A(n1,n2)
error('Attempt to merge nodes that are not connected');
end
if mod(n1,2) % node n1 is the start of edge1
flipedge1 = 1; % edge1 will need to be reversed in order to join edge2
else
flipedge1 = 0;
end
if mod(n2,2) % node n2 is the start of edge2
flipedge2 = 0;
else
flipedge2 = 1;
end
% Join edgelists together - with appropriate reordering depending on which
% end is connected to which. The result is stored in edge1
if ~flipedge1 && ~flipedge2
edgelist{edge1} = [edgelist{edge1}; edgelist{edge2}];
A(e1,:) = A(e2,:); A(:,e1) = A(:,e2);
Nconnections(e1) = Nconnections(e2);
elseif ~flipedge1 && flipedge2
edgelist{edge1} = [edgelist{edge1}; flipud(edgelist{edge2})];
A(e1,:) = A(s2,:); A(:,e1) = A(:,s2);
Nconnections(e1) = Nconnections(s2);
elseif flipedge1 && ~flipedge2
edgelist{edge1} = [flipud(edgelist{edge1}); edgelist{edge2}];
A(s1,:) = A(e1,:); A(:,s1) = A(:,e1);
A(e1,:) = A(e2,:); A(:,e1) = A(:,e2);
Nconnections(s1) = Nconnections(e1);
Nconnections(e1) = Nconnections(e2);
elseif flipedge1 && flipedge2
edgelist{edge1} = [flipud(edgelist{edge1}); flipud(edgelist{edge2})];
A(s1,:) = A(e1,:); A(:,s1) = A(:,e1);
A(e1,:) = A(s2,:); A(:,e1) = A(:,s2);
Nconnections(s1) = Nconnections(e1);
Nconnections(e1) = Nconnections(s2);
else
fprintf('merging edges %d and %d\n',edge1, edge2); %%debug
error('We should not have got here - edgelists cannot be merged');
end
% Now correct the edge adjacency matrix to reflect the new arrangement
% The edges that the new edge1 is connected to is all the edges that
% edge1 and edge2 were connected to
B(edge1,:) = B(edge1,:) | B(edge2,:);
B(:,edge1) = B(:,edge1) | B(:,edge2);
B(edge1, edge1) = 0;
% Recompute connection counts because we have shuffled the adjacency matrices
Econnections = sum(B);
Nconnections = sum(A);
removeedge(edge2); % Finally discard edge2
end % end of mergenodes
%--------------------------------------------------------------------
% Function to provide information about the connections at each end of an
% edgelist
%
% [spurdegree, spurnode, startnode, sconns, endnode, econns] = connectioninfo(n)
%
% spurdegree - If this is non-zero it indicates this edgelist is a spur, the
% value is the number of edges this spur is connected to.
% spurnode - If this is a spur spurnode is the index of the node that is
% connected to other edges, 0 otherwise.
% startnode - index of starting node of edgelist.
% endnode - index of end node of edgelist.
% sconns - number of connections to start node.
% econns - number of connections to end node.
function [spurdegree, spurnode, startnode, sconns, endnode, econns] = connectioninfo(n)
if isempty(edgelist{n})
spurdegree = 0; spurnode = 0;
startnode = 0; sconns = 0; endnode = 0; econns = 0;
return
end
startnode = 2*n-1;
endnode = 2*n;
sconns = Nconnections(startnode); % No of connections to start node
econns = Nconnections(endnode); % No of connections to end node
if sconns == 0 && econns >= 1
spurdegree = econns;
spurnode = endnode;
elseif sconns >= 1 && econns == 0
spurdegree = sconns;
spurnode = startnode;
else
spurdegree = 0;
spurnode = 0;
end
end
%--------------------------------------------------------------------
% Function to remove an edgelist and perform the necessary updates to the edge
% adjacency and node adjacency matrices and the connection count arrays
function removeedge(n)
edgelist{n} = [];
Econnections = Econnections - B(n,:);
Econnections(n) = 0;
B(n,:) = 0;
B(:,n) = 0;
nodes2delete = [2*n-1, 2*n];
Nconnections = Nconnections - A(nodes2delete(1),:);
Nconnections = Nconnections - A(nodes2delete(2),:);
A(nodes2delete, :) = 0;
A(:, nodes2delete) = 0;
end
%--------------------------------------------------------------------
% Function to compute the path length of an edgelist
function l = edgelistlength(edgelist)
l = sum(sqrt(sum((edgelist(1:end-1,:)-edgelist(2:end,:)).^2, 2)));
end
%--------------------------------------------------------------------
end % End of cleanedgelists
|
github
|
jacksky64/imageProcessing-master
|
edgelink.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/LineSegments/edgelink.m
| 21,107 |
utf_8
|
25bee720223bdbc51946de674aa2d085
|
% EDGELINK - Link edge points in an image into lists
%
% Usage: [edgelist edgeim, etypr] = edgelink(im, minlength, location)
%
% **Warning** 'minlength' is ignored at the moment because 'cleanedgelist'
% has some bugs and can be memory hungry
%
% Arguments: im - Binary edge image, it is assumed that edges
% have been thinned (or are nearly thin).
% minlength - Optional minimum edge length of interest, defaults
% to 1 if omitted or specified as []. Ignored at the
% moment.
% location - Optional complex valued image holding subpixel
% locations of edge points. For any pixel the
% real part holds the subpixel row coordinate of
% that edge point and the imaginary part holds
% the column coordinate. See NONMAXSUP. If
% this argument is supplied the edgelists will
% be formed from the subpixel coordinates,
% otherwise the the integer pixel coordinates of
% points in 'im' are used.
%
% Returns: edgelist - a cell array of edge lists in row,column coords in
% the form
% { [r1 c1 [r1 c1 etc }
% r2 c2 ...
% ...
% rN cN] ....]
%
% edgeim - Image with pixels labeled with edge number.
% Note that junctions in the labeled edge image will be
% labeled with the edge number of the last edge that was
% tracked through it. Note that this image also includes
% edges that do not meet the minimum length specification.
% If you want to see just the edges that meet the
% specification you should pass the edgelist to
% DRAWEDGELIST.
%
% etype - Array of values, one for each edge segment indicating
% its type
% 0 - Start free, end free
% 1 - Start free, end junction
% 2 - Start junction, end free (should not happen)
% 3 - Start junction, end junction
% 4 - Loop
%
% This function links edge points together into lists of coordinate pairs.
% Where an edge junction is encountered the list is terminated and a separate
% list is generated for each of the branches.
%
% Note I am not sure if using bwmorph's 'thin' or 'skel' is best for
% preprocessing the edge image prior to edgelinking. The main issue is the
% treatment of junctions. Skel can result in an image where multiple adjacent
% junctions are produced (maybe this is more a problem with my junction
% detection code). Thin, on the other hand, can produce different output when
% you rotate an image by 90 degrees. On balance I think using 'thin' is better.
% Note, however, the input image should be 'nearly thin' otherwise the thinning
% operation could shorten the ends of structures. Skeletonisation and thinning
% is surprisingly awkward.
%
% See also: DRAWEDGELIST, LINESEG, MAXLINEDEV, CLEANEDGELIST,
% FINDENDSJUNCTIONS, FILLEDGEGAPS
% Copyright (c) 1996-2013 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% February 2001 - Original version
% September 2004 - Revised to allow subpixel edge data to be used
% November 2006 - Changed so that edgelists start and stop at every junction
% January 2007 - Trackedge modified to discard isolated pixels and the
% problems they cause (thanks to Jeff Copeland)
% January 2007 - Fixed so that closed loops are closed!
% May 2013 - Completely redesigned with a new linking strategy that
% hopefully handles adjacent junctions correctly. It runs
% about twice as fast too.
function [edgelist, edgeim, etype] = edgelink(im, minlength, location)
% Set up some global variables to avoid passing (and copying) of arguments,
% this improves speed.
global EDGEIM;
global ROWS;
global COLS;
global JUNCT;
if ~exist('minlength','var') || isempty(minlength), minlength = 0; end
EDGEIM = im ~= 0; % Make sure image is binary.
EDGEIM = bwmorph(EDGEIM,'clean'); % Remove isolated pixels
% Make sure edges are thinned. Use 'thin' rather than 'skel', see
% comments in header.
EDGEIM = bwmorph(EDGEIM,'thin',Inf);
[ROWS, COLS] = size(EDGEIM);
% Find endings and junctions in edge data
[RJ, CJ, re, ce] = findendsjunctions(EDGEIM);
Njunct = length(RJ);
Nends = length(re);
% Create a sparse matrix to mark junction locations. This makes junction
% testing much faster. A value of 1 indicates a junction, a value of 2
% indicates we have visited the junction.
JUNCT = spalloc(ROWS,COLS, Njunct);
for n = 1:Njunct
JUNCT(RJ(n),CJ(n)) = 1;
end
% ? Think about using labels >= 2 so that EDGEIM can be uint16, say. %
EDGEIM = double(EDGEIM); % Cast to double to allow the use of -ve labelings
edgeNo = 0;
% Summary of strategy:
% 1) From every end point track until we encounter an end point or
% junction. As we track points along an edge image pixels are labeled with
% the -ve of their edge No.
% 2) From every junction track out on any edges that have not been
% labeled yet.
% 3) Scan through the image looking for any unlabeled pixels. These
% correspond to isolated loops that have no junctions.
%% 1) Form tracks from each unlabeled endpoint until we encounter another
% endpoint or junction.
for n = 1:Nends
if EDGEIM(re(n),ce(n)) == 1 % Endpoint is unlabeled
edgeNo = edgeNo + 1;
[edgelist{edgeNo} endType] = trackedge(re(n), ce(n), edgeNo);
etype(edgeNo) = endType;
end
end
%% 2) Handle junctions.
% Junctions are awkward when they are adjacent to other junctions. We
% start by looking at all the neighbours of a junction.
% If there is an adjacent junction we first create a 2-element edgetrack
% that links the two junctions together. We then look to see if there are
% any non-junction edge pixels that are adjacent to both junctions. We then
% test to see which of the two junctions is closest to this common pixel and
% initiate an edge track from the closest of the two junctions through this
% pixel. When we do this we set the 'avoidJunction' flag in the call to
% trackedge so that the edge track does not immediately loop back and
% terminate on the other adjacent junction.
% Having checked all the common neighbours of both junctions we then
% track out on any remaining untracked neighbours of the junction
for j = 1:Njunct
if JUNCT(RJ(j),CJ(j)) ~= 2; % We have not visited this junction
JUNCT(RJ(j),CJ(j)) = 2;
% Call availablepixels with edgeNo = 0 so that we get a list of
% available neighbouring pixels that can be linked to and a list of
% all neighbouring pixels that are also junctions.
[ra, ca, rj, cj] = availablepixels(RJ(j), CJ(j), 0);
for k = 1:length(rj) % For all adjacent junctions...
% Create a 2-element edgetrack to each adjacent junction
edgeNo = edgeNo + 1;
edgelist{edgeNo} = [RJ(j) CJ(j); rj(k) cj(k)];
etype(edgeNo) = 3; % Edge segment is junction-junction
EDGEIM(RJ(j), CJ(j)) = -edgeNo;
EDGEIM(rj(k), cj(k)) = -edgeNo;
% Check if the adjacent junction has some untracked pixels that
% are also adjacent to the initial junction. Thus we need to
% get available pixels adjacent to junction (rj(k) cj(k))
[rak, cak] = availablepixels(rj(k), cj(k));
% If both junctions have untracked neighbours that need checking...
if ~isempty(ra) && ~isempty(rak)
% Find untracked neighbours common to both junctions.
commonrc = intersect([ra ca], [rak cak], 'rows');
for n = 1:size(commonrc, 1);
% If one of the junctions j or k is closer to this common
% neighbour use that as the start of the edge track and the
% common neighbour as the 2nd element. When we call
% trackedge we set the avoidJunction flag to prevent the
% track immediately connecting back to the other junction.
distj = norm(commonrc(n,:) - [RJ(j) CJ(j)]);
distk = norm(commonrc(n,:) - [rj(k) cj(k)]);
edgeNo = edgeNo + 1;
if distj < distk
edgelist{edgeNo} = trackedge(RJ(j), CJ(j), edgeNo, ...
commonrc(n,1), commonrc(n,2), 1);
else
edgelist{edgeNo} = trackedge(rj(k), cj(k), edgeNo, ...
commonrc(n,1), commonrc(n,2), 1);
end
etype(edgeNo) = 3; % Edge segment is junction-junction
end
end
% Track any remaining unlabeled pixels adjacent to this junction k
for m = 1:length(rak)
if EDGEIM(rak(m), cak(m)) == 1
edgeNo = edgeNo + 1;
edgelist{edgeNo} = trackedge(rj(k), cj(k), edgeNo, rak(m), cak(m));
etype(edgeNo) = 3; % Edge segment is junction-junction
end
end
% Mark that we have visited junction (rj(k) cj(k))
JUNCT(rj(k), cj(k)) = 2;
end % for all adjacent junctions
% Finally track any remaining unlabeled pixels adjacent to original junction j
for m = 1:length(ra)
if EDGEIM(ra(m), ca(m)) == 1
edgeNo = edgeNo + 1;
edgelist{edgeNo} = trackedge(RJ(j), CJ(j), edgeNo, ra(m), ca(m));
etype(edgeNo) = 3; % Edge segment is junction-junction
end
end
end % If we have not visited this junction
end % For each junction
%% 3) Scan through the image looking for any unlabeled pixels. These
% should correspond to isolated loops that have no junctions or endpoints.
for ru = 1:ROWS
for cu = 1:COLS
if EDGEIM(ru,cu) == 1 % We have an unlabeled edge
edgeNo = edgeNo + 1;
[edgelist{edgeNo} endType] = trackedge(ru, cu, edgeNo);
etype(edgeNo) = endType;
end
end
end
edgeim = -EDGEIM; % Finally negate image to make edge encodings +ve.
% Eliminate isolated edges and spurs that are below the minimum length
% ** DISABLED for the time being **
% if nargin >= 2 && ~isempty(minlength)
% edgelist = cleanedgelist2(edgelist, minlength);
% end
% If subpixel edge locations are supplied upgrade the integer precision
% edgelists that were constructed with data from 'location'.
if nargin == 3
for I = 1:length(edgelist)
ind = sub2ind(size(im),edgelist{I}(:,1),edgelist{I}(:,2));
edgelist{I}(:,1) = real(location(ind))';
edgelist{I}(:,2) = imag(location(ind))';
end
end
clear global EDGEIM;
clear global ROWS;
clear global COLS;
clear global JUNCT;
%----------------------------------------------------------------------
% TRACKEDGE
%
% Function to track all the edge points starting from an end point or junction.
% As it tracks it stores the coords of the edge points in an array and labels the
% pixels in the edge image with the -ve of their edge number. This continues
% until no more connected points are found, or a junction point is encountered.
%
% Usage: edgepoints = trackedge(rstart, cstart, edgeNo, r2, c2, avoidJunction)
%
% Arguments: rstart, cstart - Row and column No of starting point.
% edgeNo - The current edge number.
% r2, c2 - Optional row and column coords of 2nd point.
% avoidJunction - Optional flag indicating that (r2,c2)
% should not be immediately connected to a
% junction (if possible).
%
% Returns: edgepoints - Nx2 array of row and col values for
% each edge point.
% endType - 0 for a free end
% 1 for a junction
% 5 for a loop
function [edgepoints endType] = trackedge(rstart, cstart, edgeNo, r2, c2, avoidJunction)
global EDGEIM;
global JUNCT;
if ~exist('avoidJunction', 'var'), avoidJunction = 0; end
edgepoints = [rstart cstart]; % Start a new list for this edge.
EDGEIM(rstart,cstart) = -edgeNo; % Edge points in the image are
% encoded by -ve of their edgeNo.
preferredDirection = 0; % Flag indicating we have/not a
% preferred direction.
% If the second point has been supplied add it to the track and set the
% path direction
if exist('r2', 'var') && exist('c2', 'var')
edgepoints = [edgepoints
r2 c2 ];
EDGEIM(r2, c2) = -edgeNo;
% Initialise direction vector of path and set the current point on
% the path
dirn = unitvector([r2-rstart c2-cstart]);
r = r2;
c = c2;
preferredDirection = 1;
else
dirn = [0 0];
r = rstart;
c = cstart;
end
% Find all the pixels we could link to
[ra, ca, rj, cj] = availablepixels(r, c, edgeNo);
while ~isempty(ra) || ~isempty(rj)
% First see if we can link to a junction. Choose the junction that
% results in a move that is as close as possible to dirn. If we have no
% preferred direction, and there is a choice, link to the closest
% junction
% We enter this block:
% IF there are junction points and we are not trying to avoid a junction
% OR there are junction points and no non-junction points, ie we have
% to enter it even if we are trying to avoid a junction
if (~isempty(rj) && ~avoidJunction) || (~isempty(rj) && isempty(ra))
% If we have a prefered direction choose the junction that results
% in a move that is as close as possible to dirn.
if preferredDirection
dotp = -inf;
for n = 1:length(rj)
dirna = unitvector([rj(n)-r cj(n)-c]);
dp = dirn*dirna';
if dp > dotp
dotp = dp;
rbest = rj(n); cbest = cj(n);
dirnbest = dirna;
end
end
% Otherwise if we have no established direction, we should pick a
% 4-connected junction if possible as it will be closest. This only
% affects tracks of length 1 (Why do I worry about this...?!).
else
distbest = inf;
for n = 1:length(rj)
dist = sum([rj(n)-r; cj(n)-c]);
if dist < distbest
rbest = rj(n); cbest = cj(n);
distbest = dist;
dirnbest = unitvector([rj(n)-r cj(n)-c]);
end
end
preferredDirection = 1;
end
% If there were no junctions to link to choose the available
% non-junction pixel that results in a move that is as close as possible
% to dirn
else
dotp = -inf;
for n = 1:length(ra)
dirna = unitvector([ra(n)-r ca(n)-c]);
dp = dirn*dirna';
if dp > dotp
dotp = dp;
rbest = ra(n); cbest = ca(n);
dirnbest = dirna;
end
end
avoidJunction = 0; % Clear the avoidJunction flag if it had been set
end
% Append the best pixel to the edgelist and update the direction and EDGEIM
r = rbest; c = cbest;
edgepoints = [edgepoints
r c ];
dirn = dirnbest;
EDGEIM(r, c) = -edgeNo;
% If this point is a junction exit here
if JUNCT(r, c);
endType = 1; % Mark end as being a junction
return;
else
% Get the next set of available pixels to link.
[ra, ca, rj, cj] = availablepixels(r, c, edgeNo);
end
end
% If we get here we are at an endpoint or our sequence of pixels form a
% loop. If it is a loop the edgelist should have start and end points
% matched to form a loop. If the number of points in the list is four or
% more (the minimum number that could form a loop), and the endpoints are
% within a pixel of each other, append a copy of the first point to the end
% to complete the loop
endType = 0; % Mark end as being free, unless it is reset below
if length(edgepoints) >= 4
if abs(edgepoints(1,1) - edgepoints(end,1)) <= 1 && ...
abs(edgepoints(1,2) - edgepoints(end,2)) <= 1
edgepoints = [edgepoints
edgepoints(1,:)];
endType = 5; % Mark end as being a loop
end
end
%----------------------------------------------------------------------
% AVAILABLEPIXELS
%
% Find all the pixels that could be linked to point r, c
%
% Arguments: rp, cp - Row, col coordinates of pixel of interest.
% edgeNo - The edge number of the edge we are seeking to
% track. If not supplied its value defaults to 0
% resulting in all adjacent junctions being returned,
% (see note below)
%
% Returns: ra, ca - Row and column coordinates of available non-junction
% pixels.
% rj, cj - Row and column coordinates of available junction
% pixels.
%
% A pixel is avalable for linking if it is:
% 1) Adjacent, that is it is 8-connected.
% 2) Its value is 1 indicating it has not already been assigned to an edge
% 3) or it is a junction that has not been labeled -edgeNo indicating we have
% not already assigned it to the current edge being tracked. If edgeNo is
% 0 all adjacent junctions will be returned
function [ra, ca, rj, cj] = availablepixels(rp, cp, edgeNo)
global EDGEIM;
global JUNCT;
global ROWS;
global COLS;
% If edgeNo not supplied set to 0 to allow all adjacent junctions to be returned
if ~exist('edgeNo', 'var'), edgeNo = 0; end
ra = []; ca = [];
rj = []; cj = [];
% row and column offsets for the eight neighbours of a point
roff = [-1 0 1 1 1 0 -1 -1];
coff = [-1 -1 -1 0 1 1 1 0];
r = rp+roff;
c = cp+coff;
% Find indices of arrays of r and c that are within the image bounds
ind = find((r>=1 & r<=ROWS) & (c>=1 & c<=COLS));
% A pixel is avalable for linking if its value is 1 or it is a junction
% that has not been labeled -edgeNo
for i = ind
if EDGEIM(r(i),c(i)) == 1 && ~JUNCT(r(i), c(i));
ra = [ra; r(i)];
ca = [ca; c(i)];
elseif (EDGEIM(r(i),c(i)) ~= -edgeNo) && JUNCT(r(i), c(i));
rj = [rj; r(i)];
cj = [cj; c(i)];
end
end
%---------------------------------------------------------------------
% UNITVECTOR Normalises a vector to unit magnitude
%
function nv = unitvector(v)
nv = v./sqrt(v(:)'*v(:));
|
github
|
jacksky64/imageProcessing-master
|
edgelist2image.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/LineSegments/edgelist2image.m
| 2,027 |
utf_8
|
5c5436b3f23a712f883ddb43a21e1d1c
|
% EDGELIST2IMAGE - transfers edgelist data back into a 2D image array
%
% Usage: im = edgelist2image(edgelist, rowscols)
%
% edgelist - Cell array of edgelists in the form
% { [r1 c1 [r1 c1 etc }
% ...
% rN cN] ....]
% rowscols - Optional 2 element vector [rows cols] specifying the size
% of the image from which edges were detected (used to set
% size of plotted image). If omitted or specified as [] this
% defaults to the bounds of the linesegment points
%
% Note this function will only work effectively on 'dense' edgelist data
% obtained, say, directly from edgelink. If you have subsequently fitted
% line segments to the edgelist data this function will only mark the endpoints
% of the segments, use DRAWEDGELIST instead.
%
% See also: EDGELINK, DRAWEDGELIST
% Copyright (c) 2007 Peter Kovesi
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% September 2007
function im = edgelist2image(edgelist, rowscols)
if nargin < 2, rowscols = [1 1]; end
Nedge = length(edgelist);
% Establish bounds of image
minx = 1; miny = 1;
maxx = rowscols(2); maxy = rowscols(1);
for I = 1:Nedge
minx = min(min(edgelist{I}(:,2)),minx);
miny = min(min(edgelist{I}(:,1)),miny);
maxx = max(max(edgelist{I}(:,2)),maxx);
maxy = max(max(edgelist{I}(:,1)),maxy);
end
% Draw the edgelist data into an image array
im = zeros(maxy,maxx);
for I = 1:Nedge
ind = sub2ind([maxy maxx], edgelist{I}(:,1), edgelist{I}(:,2));
im(ind) = 1;
end
|
github
|
jacksky64/imageProcessing-master
|
bandpassfilter.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/bandpassfilter.m
| 1,514 |
utf_8
|
d98c0b715b1b05c4e8c5e415a260dd2c
|
% BANDPASSFILTER - Constructs a band-pass butterworth filter
%
% usage: f = bandpassfilter(sze, cutin, cutoff, n)
%
% where: sze is a two element vector specifying the size of filter
% to construct [rows cols].
% cutin and cutoff are the frequencies defining the band pass 0 - 0.5
% n is the order of the filter, the higher n is the sharper
% the transition is. (n must be an integer >= 1).
%
% The frequency origin of the returned filter is at the corners.
%
% See also: LOWPASSFILTER, HIGHPASSFILTER, HIGHBOOSTFILTER
%
% Copyright (c) 1999 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% October 1999
function f = bandpassfilter(sze, cutin, cutoff, n)
if cutin < 0 | cutin > 0.5 | cutoff < 0 | cutoff > 0.5
error('frequencies must be between 0 and 0.5');
end
if rem(n,1) ~= 0 | n < 1
error('n must be an integer >= 1');
end
f = lowpassfilter(sze, cutoff, n) - lowpassfilter(sze, cutin, n);
|
github
|
jacksky64/imageProcessing-master
|
upwardcontinue.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/upwardcontinue.m
| 4,042 |
utf_8
|
c50e198c0e568fd171e5713d3d05342b
|
% UPWARDCONTINUE Upward continuation for magnetic or gravity potential field data
%
% Usage: [up, pim, psf] = upwardcontinue(im, h, dx, dy)
%
% Arguments: im - Input potential field image
% h - Height to upward continue to (+ve)
% dx, dy - Grid spacing in x and y. The upward continuation height
% is computed relative to the grid spacing. If omitted dx =
% dy = 1, that is, the value of h is in grid spacing units.
% If dy is omitted it is assumed dy = dx.
%
% Returns: up - The upward continued field image
% pim - The periodic component of the input potential field
% image. See note below.
% psf - The point spread function corresponding to the upward
% continuation height.
%
% Upward continuation filtering is done in the frequency domain whereby the
% Fourier transform of the upward continued image F(Up) is obtained from the
% Fourier transform of the input image F(U) using
% F(Up) = e^(-2*pi*h * sqrt(u^2 + v^2)) * F(U)
% where u and v are the spatial frequencies over the input grid.
%
% To minimise edge effect problems Moisan's Periodic FFT is used. This avoids
% the need for data tapering. Moisan's "Periodic plus Smooth Image
% Decomposition" decomposes an image into two components
% im = p + s
% where s is the 'smooth' component with mean 0 and p is the 'periodic'
% component which has no sharp discontinuities when one moves cyclically across
% the image boundaries.
%
% Accordingly if you are doing residual analysis you should subtract the upward
% continued image from the periodic component of the input image 'pim' rather
% than from the raw input image 'im'.
%
% References:
% Richard Blakely, "Potential Theory in Gravity and Magnetic Applications"
% Cambridge University Press, 1996, pp 315-319
%
% L. Moisan, "Periodic plus Smooth Image Decomposition", Journal of
% Mathematical Imaging and Vision, vol 39:2, pp. 161-179, 2011.
%
% See also: PERFFT2
% Copyright (c) Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% June 2012 - Original version
% June 2014 - Tidied up and documented
function [up, pim, psf] = upwardcontinue(im, h, dx, dy)
if ~exist('dx', 'var'), dx = 1; end
if ~exist('dy', 'var'), dy = dx; end
[rows,cols,chan] = size(im);
assert(chan == 1, 'Image must be single channel');
mask = ~isnan(im);
% Use Periodic FFT rather than data tapering to minimise edge effects.
[IM,~,pim] = perfft2(fillnan(im));
% Generate horizontal and vertical frequency grids that vary from
% -0.5 to 0.5
[u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ...
([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2)));
% Quadrant shift to put 0 frequency at the corners. Also, divide by grid
% size to get correct spatial frequencies
u1 = ifftshift(u1)/dx;
u2 = ifftshift(u2)/dy;
freq = sqrt(u1.^2 + u2.^2); % Matrix values contain spatial frequency
% values as a radius from centre (but
% quadrant shifted)
% Continuation filter in the frequency domain
W = exp(-2*pi*h*freq);
% Apply filter to obtain upward continuation
up = real(ifft2(IM.*W)) .* double(mask);
% Reconstruct the spatial representation of the point spread function
% corresponding to the upward continuation height
psf = real(fftshift(ifft2(W)));
|
github
|
jacksky64/imageProcessing-master
|
highboostfilter.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/highboostfilter.m
| 1,962 |
utf_8
|
ada657e25d617c134fb03bf410b0be5b
|
% HIGHBOOSTFILTER - Constructs a high-boost Butterworth filter.
%
% usage: f = highboostfilter(sze, cutoff, n, boost)
%
% where: sze is a two element vector specifying the size of filter
% to construct [rows cols].
% cutoff is the cutoff frequency of the filter 0 - 0.5.
% n is the order of the filter, the higher n is the sharper
% the transition is. (n must be an integer >= 1).
% boost is the ratio that high frequency values are boosted
% relative to the low frequency values. If boost is less
% than one then a 'lowboost' filter is generated
%
%
% The frequency origin of the returned filter is at the corners.
%
% See also: LOWPASSFILTER, HIGHPASSFILTER, BANDPASSFILTER
%
% Copyright (c) 1999-2001 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% October 1999
% November 2001 modified so that filter is specified in terms of high to
% low boost rather than a zero frequency offset.
function f = highboostfilter(sze, cutoff, n, boost)
if cutoff < 0 | cutoff > 0.5
error('cutoff frequency must be between 0 and 0.5');
end
if rem(n,1) ~= 0 | n < 1
error('n must be an integer >= 1');
end
if boost >= 1 % high-boost filter
f = (1-1/boost)*highpassfilter(sze, cutoff, n) + 1/boost;
else % low-boost filter
f = (1-boost)*lowpassfilter(sze, cutoff, n) + boost;
end
|
github
|
jacksky64/imageProcessing-master
|
invfft2.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/invfft2.m
| 250 |
utf_8
|
41b97c8ab7dc15522b2c5a414bf55b38
|
% INVFFT2 - takes inverse fft and returns real part
%
% Function to `wrap up' taking the inverse Fourier transform
% and extracting the real part into the one operation
% Peter Kovesi October 1999
function ift = invfft2(ft)
ift = real(ifft2(ft));
|
github
|
jacksky64/imageProcessing-master
|
lowpassfilter.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/lowpassfilter.m
| 2,448 |
utf_8
|
1bdb6b9b70b06af9d2bc12b6b877da54
|
% LOWPASSFILTER - Constructs a low-pass butterworth filter.
%
% usage: f = lowpassfilter(sze, cutoff, n)
%
% where: sze is a two element vector specifying the size of filter
% to construct [rows cols].
% cutoff is the cutoff frequency of the filter 0 - 0.5
% n is the order of the filter, the higher n is the sharper
% the transition is. (n must be an integer >= 1).
% Note that n is doubled so that it is always an even integer.
%
% 1
% f = --------------------
% 2n
% 1.0 + (w/cutoff)
%
% The frequency origin of the returned filter is at the corners.
%
% See also: HIGHPASSFILTER, HIGHBOOSTFILTER, BANDPASSFILTER
%
% Copyright (c) 1999 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% October 1999
% August 2005 - Fixed up frequency ranges for odd and even sized filters
% (previous code was a bit approximate)
function f = lowpassfilter(sze, cutoff, n)
if cutoff < 0 | cutoff > 0.5
error('cutoff frequency must be between 0 and 0.5');
end
if rem(n,1) ~= 0 | n < 1
error('n must be an integer >= 1');
end
if length(sze) == 1
rows = sze; cols = sze;
else
rows = sze(1); cols = sze(2);
end
% Set up X and Y matrices with ranges normalised to +/- 0.5
% The following code adjusts things appropriately for odd and even values
% of rows and columns.
if mod(cols,2)
xrange = [-(cols-1)/2:(cols-1)/2]/(cols-1);
else
xrange = [-cols/2:(cols/2-1)]/cols;
end
if mod(rows,2)
yrange = [-(rows-1)/2:(rows-1)/2]/(rows-1);
else
yrange = [-rows/2:(rows/2-1)]/rows;
end
[x,y] = meshgrid(xrange, yrange);
radius = sqrt(x.^2 + y.^2); % A matrix with every pixel = radius relative to centre.
f = ifftshift( 1.0 ./ (1.0 + (radius ./ cutoff).^(2*n)) ); % The filter
|
github
|
jacksky64/imageProcessing-master
|
imspect.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/imspect.m
| 4,926 |
utf_8
|
1567515542e483c4deb2ccc804ff7ac9
|
% IMSPECT - Plots image amplitude spectrum averaged over all orientations.
%
% Usage: [amp, f, slope] = imspect(im, nbins, lowcut)
% \ /
% optional
% Arguments:
% im - Image to be analysed.
% nbins - No of frequency bins to use (defaults to 100).
% lowcut - Percentage of lower frequencies to ignore when
% finding line of best fit. This avoids problems
% with amplitude spikes at low frequencies.
% (defaults to 2%) .
%
% Returns:
% amp - 1D array of amplitudes.
% f - Corresponding array of frequencies.
% slope - Slope of line of best fit to the log-log data
%
% Be wary of using too many frequency bins. With more bins there will be
% fewer elements per bin, or even none, producing a very noisy result.
%
% See also: PERFFT2
% Copyright (c) 2001-2003 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% July 2001 - original version.
% May 2003 - correction of frequency origin for even and odd size images.
% - corrections to allow for non-square images.
% - extra commenting
% August 2014 - Changed to use perfft2 rather than fft2 to minimise edge effects
function [amp, f, slope] = imspect(im, nbins, lowcut)
if nargin < 2
nbins = 100; % Default No of frequency 'bins'
end
if nargin < 3
lowcut = 2; % Ignore lower 2% of curve when finding
end % line of best fit.
amp = zeros(1, nbins); % preallocate some memory
fcount = ones(1, nbins);
mag = fftshift(abs(perfft2(double(im)))); % Amplitude spectrum
% Generate a matrix 'radius' every element of which has a value
% given by its distance from the centre. This is used to index
% the frequency values in the spectrum.
[rows, cols] = size(im);
[x,y] = meshgrid([1:cols],[1:rows]);
% The following fiddles the origin to the correct position
% depending on whether we have and even or odd size.
% In addition the values of x and y are normalised to +- 0.5
if mod(cols,2) == 0
x = (x-cols/2-1)/cols;
else
x = (x-(cols+1)/2)/(cols-1);
end
if mod(rows,2) == 0
y = (y-rows/2-1)/rows;
else
y = (y-(rows+1)/2)/(rows-1);
end
radius = sqrt(x.^2 + y.^2);
% Quantise radius to the desired number of frequency bins
radius = round(radius/max(max(radius))*(nbins-1)) + 1;
% Now go through the spectrum and build the histogram of amplitudes
% vs frequences.
for r = 1:rows
for c = 1:cols
ind = radius(r,c);
amp(ind) = amp(ind)+mag(r,c);
fcount(ind) = fcount(ind)+1;
end
end
% Average the amplitude at each frequency bin. We also add 'eps'
% to avoid potential problems later on in taking logs.
amp = amp./fcount + eps;
% Generate corrected frequency scale for each quantised frequency bin.
% Note that the maximum frequency is sqrt(0.5) corresponding to the
% points in the corners of the spectrum
f = [1:nbins]/nbins*sqrt(.5);
% Plots
% Find first index value beyond the specified histogram cutoff
fst = round(nbins*lowcut/100 + 1);
figure(1), clf
lw = 2; % Line width
fs = 16; % Font size
plot(f(fst:end),amp(fst:end), 'Linewidth', lw)
xlabel('frequency'), ylabel('amplitude');
title('Histogram of amplitude vs frequency');
figure(2), % clf
loglog(f(fst:end),amp(fst:end), 'Linewidth', lw)
xlabel('log frequency', 'Fontsize', fs, 'Fontweight', 'bold');
ylabel('log amplitude', 'Fontsize', fs, 'Fontweight', 'bold');
% Find line of best fit (ignoring specified fraction of low frequency values)
p = polyfit(log(f(fst:end)), log(amp(fst:end)),1);
slope = p(1);
y = exp(p(1)*log(f(fst:end)) + p(2)); % log(y) = p(1)*log(f) + p(2)
hold on
loglog(f(fst:end), y,'Color',[1 0 0], 'Linewidth', lw)
n = round(nbins/5);
text(f(n), amp(n)*2, sprintf('Slope = %.2f',p(1)), ...
'Fontsize', fs, 'Fontweight', 'bold');
% title('Histogram of log amplitude vs log frequency');
set(gca, 'FontSize', 14);
set(gca, 'FontWeight', 'bold');
set(gca, 'LineWidth', 1.5);
|
github
|
jacksky64/imageProcessing-master
|
psf.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/psf.m
| 2,323 |
utf_8
|
de5c27f8dd4eb69a3ae36c1be3f20990
|
% PSF - Generates point spread functions for use with deconvolution fns.
%
% This function can generate a variety function shapes based around the
% Butterworth filter. In plan view the filter can be elliptical and at
% any orientation. The `squareness/roundness' of the shape can also be
% manipulated.
%
% Usage: h = psf(sze, order, ang, eccen, rc, sqrness)
%
% sze - two element array specifying size of filter [rows cols]
% order - an even integer specifying the order of the Butterworth filter.
% This controls the sharpness of the cutoff.
% ang - angle of rotation of the filter in radians
% eccen - ratio of eccentricity of the filter shape (major/minor axis ratio)
% rc - mean radius of the filter in pixels
% sqrness - even integer specifying `squareness' of the filter shape
% a value of 2 gives a circular filter (if eccen = 1), higher
% values make the shape squarer.
% Copyright (c) 1999 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% June 1999
function h = psf(sze, order, ang, eccen, rc, sqrness)
if mod(sqrness,2) ~=0
error('squareness parameter must be an even integer');
end
rows = sze(1);
cols = sze(2);
x = ones(rows,1) * [1:cols] - (fix(cols/2)+1);
y = [1:rows]' * ones(1,cols) - (fix(rows/2)+1);
xp = x*cos(ang) - y*sin(ang); % Rotate axes by specified angle.
yp = x*sin(ang) + y*cos(ang);
x = sqrt(eccen)*xp; % Distort x and y according to eccentricity.
y = yp/sqrt(eccen);
radius = (x.^sqrness + y.^sqrness).^(1/sqrness); % Distort distance metric
% by squareness measure.
h = 1./(1+(radius./rc).^order); % Butterworth filter
h = h./(sum(sum(h))); % and normalise.
|
github
|
jacksky64/imageProcessing-master
|
filtergrid.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/filtergrid.m
| 2,441 |
utf_8
|
a196e165846902098ffcbc16ddf71f6c
|
% FILTERGRID Generates grid for constructing frequency domain filters
%
% Usage: [radius, u1, u2] = filtergrid(rows, cols)
% [radius, u1, u2] = filtergrid([rows, cols])
%
% Arguments: rows, cols - Size of image/filter
%
% Returns: radius - Grid of size [rows cols] containing normalised
% radius values from 0 to 0.5. Grid is quadrant
% shifted so that 0 frequency is at radius(1,1)
% u1, u2 - Grids containing normalised frequency values
% ranging from -0.5 to 0.5 in x and y directions
% respectively. u1 and u2 are quadrant shifted.
%
% Used by PHASECONGMONO, PHASECONG3 etc etc
%
% Copyright (c) 1996-2013 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% May 2013
function [radius, u1, u2] = filtergrid(rows, cols)
% Handle case where rows, cols has been supplied as a 2-vector
if nargin == 1 & length(rows) == 2
tmp = rows;
rows = tmp(1);
cols = tmp(2);
end
% Set up X and Y spatial frequency matrices, u1 and u2, with ranges
% normalised to +/- 0.5 The following code adjusts things appropriately for
% odd and even values of rows and columns so that the 0 frequency point is
% placed appropriately.
if mod(cols,2)
u1range = [-(cols-1)/2:(cols-1)/2]/(cols-1);
else
u1range = [-cols/2:(cols/2-1)]/cols;
end
if mod(rows,2)
u2range = [-(rows-1)/2:(rows-1)/2]/(rows-1);
else
u2range = [-rows/2:(rows/2-1)]/rows;
end
[u1,u2] = meshgrid(u1range, u2range);
% Quadrant shift so that filters are constructed with 0 frequency at
% the corners
u1 = ifftshift(u1);
u2 = ifftshift(u2);
% Construct spatial frequency values in terms of normalised radius from
% centre.
radius = sqrt(u1.^2 + u2.^2);
|
github
|
jacksky64/imageProcessing-master
|
highpassfilter.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/highpassfilter.m
| 1,443 |
utf_8
|
78f60a0dd6f0ef66653d547868fad1f9
|
% HIGHPASSFILTER - Constructs a high-pass butterworth filter.
%
% usage: f = highpassfilter(sze, cutoff, n)
%
% where: sze is a two element vector specifying the size of filter
% to construct [rows cols].
% cutoff is the cutoff frequency of the filter 0 - 0.5
% n is the order of the filter, the higher n is the sharper
% the transition is. (n must be an integer >= 1).
%
% The frequency origin of the returned filter is at the corners.
%
% See also: LOWPASSFILTER, HIGHBOOSTFILTER, BANDPASSFILTER
%
% Copyright (c) 1999 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% October 1999
function f = highpassfilter(sze, cutoff, n)
if cutoff < 0 | cutoff > 0.5
error('cutoff frequency must be between 0 and 0.5');
end
if rem(n,1) ~= 0 | n < 1
error('n must be an integer >= 1');
end
f = 1.0 - lowpassfilter(sze, cutoff, n);
|
github
|
jacksky64/imageProcessing-master
|
circsine.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/circsine.m
| 4,364 |
utf_8
|
4b2d3f6974bd3cd11dde7d3b2a600790
|
% CIRCSINE Generates circular sine wave grating
% Can also be use to construct phase congruent patterns
%
% Usage: im = circsine(sze, wavelength, nScales, ampExponent, offset, p, trim)
%
% Arguments:
% sze - The size of the square image to be produced.
% wavelength - The wavelength in pixels of the sine wave.
% nScales - No of fourier components used to construct the
% signal. This is typically 1, if you want a simple sine
% wave, or >50 if you want to build a phase congruent
% waveform. Defaults to 1.
% ampExponent - Decay exponent of amplitude with frequency.
% A value of -1 will produce amplitude inversely
% proportional to frequency (this will produce a step
% feature if offset is 0)
% A value of -2 with an offset of pi/2 will result in a
% triangular waveform.
% Defaults to -1;
% offset - Phase offset to apply to circular pattern.
% This controls the feature type, see examples below.
% Defaults to pi/2 if nScales is 1, else, 0
% p - Optional parameter specifying the norm to use in
% calculating the radius from the centre. This defaults to
% 2, resulting in a circular pattern. Large values gives
% a square pattern
% trim - Optional flag indicating whether you want the
% circular pattern trimmed from the corners leaving
% only complete cicles. Defaults to 0.
%
% Examples:
% nScales = 1 - You get a simple circular sine wave pattern
% nScales 50, ampExponent -1, offset 0 - Square waveform
% nScales 50, ampExponent -2, offset pi/2 - Triangular waveform
% nScales 50, ampExponent -1.5, offset pi/4 - Something in between square and
% triangular
% nScales 50, ampExponent -1.5, offset 0 - Looks like a square but is not.
%
% See also: STARSINE, STEP2LINE
% Copyright (c) 2003-2010 Peter Kovesi
% Centre for Exploration Targeting
% School of Earth and Environment
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% May 2003 - Original version
% Nov 2006 - Trim flag added
% Dec 2010 - Ability to construct phase congruent patterns, order of argument
% list changed
function im = circsine(sze, wavelength, nScales, ampExponent, offset, p, trim)
if ~exist('trim', 'var'), trim = 0; end
if ~exist('p', 'var'), p = 2; end
if ~exist('ampExponent', 'var'), ampExponent = -1; end
if ~exist('nScales', 'var'), nScales = 1; end
% If we have one scale, hence just making a sine wave, and offset is not
% specified set it to pi/2 to give cintinuity at the centre
if nScales == 1 && ~exist('offset', 'var')
offset = pi/2;
elseif ~exist('offset', 'var')
offset = 0;
end
if mod(p,2)
error('p should be an even number');
end
% Place origin at centre for odd sized image, and below and the the
% right of centre for an even sized image
if mod(sze,2) == 0 % even sized image
l = -sze/2;
u = sze/2-1;
else
l = -(sze-1)/2;
u = (sze-1)/2;
end
[x,y] = meshgrid(l:u);
r = (x.^p + y.^p).^(1/p);
im = zeros(size(r));
for scale = 1:2:(2*nScales-1)
im = im + scale^ampExponent* sin(scale* r * 2*pi/wavelength + offset);
end
if trim % Remove circular pattern from the 'corners'
cycles = fix(sze/2/wavelength); % No of complete cycles within sze/2
im = im.* (r < cycles*wavelength) + (r>= cycles*wavelength);
end
|
github
|
jacksky64/imageProcessing-master
|
starsine.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/starsine.m
| 2,906 |
utf_8
|
929263192b6c499585f5af175f649a83
|
% STARSINE Generates phase congruent star shaped sine wave grating
%
% Usage: im = starsine(sze, nCycles, nScales, ampExponent, offset)
%
% Arguments:
% sze - The size of the square image to be produced.
% nCycles - The number of sine wave cycles around centre point.
% Typically an integer, but any value can be used.
% nScales - No of fourier components used to construct the
% signal. This is typically 1, if you want a simple sine
% wave, or >50 if you want to build a phase congruent
% waveform.
% ampExponent - Decay exponent of amplitude with frequency.
% A value of -1 will produce amplitude inversely
% proportional to frequency (this will produce a step
% feature if offset is 0)
% A value of -2 with an offset of pi/2 will result in a
% triangular waveform.
% offset - Phase offset to apply to star pattern.
%
% Examples:
% nScales = 1 - You get a simple sine wave pattern radiating out
% from the centre. Use 'offset' if you wish to
% rotate it a bit.
% nScales 50, ampExponent -1, offset 0 - Square waveform
% nScales 50, ampExponent -2, offset pi/2 - Triangular waveform
% nScales 50, ampExponent -1.5, offset pi/4 - Something in between square and
% triangular
% nScales 50, ampExponent -1.5, offset 0 - Looks like a square but is not.
%
% See also: CIRCSINE, STEP2LINE
% Copyright (c) 2010 Peter Kovesi
% Centre for Exploration Targeting
% School of Earth and Enironment
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% December 2010
function im = starsine(sze, nCycles, nScales, ampExponent, offset)
if ~exist('offset', 'var')
offset = 0;
end
% Place origin at centre for odd sized image, and below and the the
% right of centre for an even sized image
if mod(sze,2) == 0 % even sized image
l = -sze/2;
u = sze/2-1;
else
l = -(sze-1)/2;
u = (sze-1)/2;
end
[x,y] = meshgrid(l:u);
theta = atan2(y,x);
im = zeros(size(theta));
for scale = 1:2:(nScales*2 - 1)
im = im + scale^ampExponent*sin(scale*nCycles*theta + offset);
end
|
github
|
jacksky64/imageProcessing-master
|
freqcomp.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/freqcomp.m
| 5,474 |
utf_8
|
58a18bdbdc50fca6a82844487445c5ad
|
% FREQCOMP - Demonstrates image reconstruction from Fourier components
%
% Usage: recon = freqcomp(im, Npts, delay)
%
% Arguments: im - Image to be reconstructed.
% Npts - Number of frequency components to consider
% (defaults to 50).
% delay - Optional time delay between animations of the
% reconstruction. If this is omitted the function
% waits for a key to be pressed before moving to
% the next component.
%
% Returns: recon - The image reconstructed from the specified
% number of components
%
% This program displays:
%
% * The image.
% * The Fourier transform (spectrum) of the image with a conjugate
% pair of Fourier components marked with red dots.
% * The sine wave basis function that corresponds to the Fourier
% transform pair marked in the image above.
% * The reconstruction of the image generated from the sum of the sine
% wave basis functions considered so far.
% Copyright (c) 2002-2003 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% March 2002 - Original version
% April 2003 - General cleanup of code
function recon = freqcomp(im, Npts, delay)
if ndims(im) == 3
im = rgb2gray(im);
warning('converting colour image to greyscale');
end
if nargin < 2
Npts = 50;
end
[rows,cols] = size(im);
% If necessary crop one row and/or column so that there are an even
% number of rows and columns, this makes things easier later.
if mod(rows,2) % odd
rows = rows-1;
end
if mod(cols,2) % odd
cols = cols-1;
end
im = im(1:rows,1:cols);
rc = fix(rows/2)+1; % Centre point
cc = fix(cols/2)+1;
% The following code constructs two arrays of coordinates within the FFT
% of the image that correspond to complex conjugate pairs of points that
% spiral out from the centre visiting every frequency component on
% the way.
p1 = zeros(Npts,2); % Path 1
p2 = zeros(Npts,2); % Path 2
m = zeros(rows,cols); % Matrix for marking visited points
m(rc,cc) = 1;
m(rc,cc-1) = 1;
m(rc,cc+1) = 1;
p1(1,:) = [rc cc-1];
p2(1,:) = [rc cc+1];
d1 = [0 -1]; % initial directions of the paths
d2 = [0 1];
% Mark out two symmetric spiral paths out from the centre (I wish I
% could think of a neater way of doing this)
for n = 2:Npts
l1 = [-d1(2) d1(1)]; % left direction
l2 = [-d2(2) d2(1)];
lp1 = p1(n-1,:) + l1; % coords of point in left direction
lp2 = p2(n-1,:) + l2;
if ~m(lp1(1), lp1(2)) % go left
p1(n,:) = lp1;
d1 = l1;
m(p1(n,1), p1(n,2)) = 1; % mark point as visited
else % go sraight ahead
p1(n,:) = p1(n-1,:) + d1;
m(p1(n,1), p1(n,2)) = 1; % mark point as visited
end
if ~m(lp2(1), lp2(2)) % go left
p2(n,:) = lp2;
d2 = l2;
m(p2(n,1), p2(n,2)) = 1; % mark point as visited
else % go sraight ahead
p2(n,:) = p2(n-1,:) + d2;
m(p2(n,1), p2(n,2)) = 1; % mark point as visited
end
end
% Having constructed the path of frequency components to be visited
% we take the FFT of the image and then enter a loop that
% incrementally reconstructs the image from its components.
IM = fftshift(fft2(im));
recon = zeros(rows,cols); % Initialise reconstruction matrix
if max(rows,cols) < 150
fontsze = 7;
else
fontsze = 10;
end
figure(1), clf
subplot(2,2,1),imagesc(im),colormap gray, axis image, axis off
title('Original Image','FontSize',fontsze);
subplot(2,2,2),imagesc(log(abs(IM))),colormap gray, axis image
axis off, title('Fourier Transform + frequency component pair','FontSize',fontsze);
warning off % Turn off warnings that might arise if the images cannot be
% displayed full size
truesize(1)
for n = 1:Npts
% Extract the pair of Fourier components
F = zeros(rows,cols);
F(p1(n,1), p1(n,2)) = IM(p1(n,1), p1(n,2));
F(p2(n,1), p2(n,2)) = IM(p2(n,1), p2(n,2));
% Invert and add to reconstruction
f = real(ifft2(fftshift(F)));
recon = recon+f;
% Display results
subplot(2,2,2),imagesc(log(abs(IM))),colormap gray, axis image
axis off, title('Fourier Transform + frequency component pair','FontSize',fontsze);
hold on, plot([p1(n,2), p2(n,2)], [p1(n,1), p2(n,1)],'r.'); hold off
subplot(2,2,3),imagesc(recon),colormap gray, axis image, axis off, title('Reconstruction','FontSize',fontsze);
subplot(2,2,4),imagesc(f),colormap gray, axis image, axis off
title('Basis function corresponding to frequency component pair','FontSize',fontsze);
if nargin == 3
pause(delay);
else
fprintf('Hit any key to continue \n'); pause
end
end
warning on % Restore warnings
|
github
|
jacksky64/imageProcessing-master
|
psf2.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/psf2.m
| 3,000 |
utf_8
|
20d5aff861110c5341b9d6fec90f8007
|
% PSF2 - Generates point spread functions for use with deconvolution fns.
%
% This function can generate a variety function shapes based around the
% Butterworth filter. In plan view the filter can be elliptical and at
% any orientation. The 'squareness/roundness' of the shape can also be
% manipulated.
%
% Usage: h = psf2(sze, order, ang, lngth, width, sqrness)
%
% sze - two element array specifying size of filter [rows cols]
% order - an even integer specifying the order of the Butterworth filter.
% This controls the sharpness of the cutoff.
% ang - angle of rotation of the filter in radians.
% lngth - length of the filter in pixels along its major axis.
% width - width of the filter in pixels along its minor axis.
% sqrness - even integer specifying 'squareness' of the filter shape
% a value of 2 gives a circular filter (if lngth == width), higher
% values make the shape squarer.
%
% This function is almost identical to psf, it just has a different way of
% specifying the function shape whereby length and width are defined
% explicitly (rather than an average radius), this may be more convenient for
% some applications.
% Copyright (c) 1999-2003 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% June 1999
% May 2003 - Changed arguments so that psf is specified in terms of a length
% and width rather than an average radius.
function h = psf2(sze, order, ang, lngth, width, sqrness)
if mod(sqrness,2) ~=0
error('squareness parameter must be an even integer');
end
rows = sze(1);
cols = sze(2);
[x,y] = meshgrid([1:cols],[1:rows]);
% The following fiddles the origin to the correct position
% depending on whether we have and even or odd size
if mod(cols,2) == 0
x = x-cols/2-1;
else
x = x-(cols+1)/2;
end
if mod(rows,2) == 0
y = y-rows/2-1;
else
y = y-(rows+1)/2;
end
xp = x*cos(ang) - y*sin(ang); % Rotate axes by specified angle.
yp = x*sin(ang) + y*cos(ang);
rc = lngth/2; % Set cutoff radius to half the length
yp = yp*lngth/width; % Adjust y measure to give appropriate relative width.
radius = (xp.^sqrness + yp.^sqrness).^(1/sqrness); % Distort distance metric
% by squareness measure.
h = 1./(1+(radius./rc).^order); % Butterworth filter
h = h./(sum(sum(h))); % and normalise.
|
github
|
jacksky64/imageProcessing-master
|
perfft2.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/perfft2.m
| 3,150 |
utf_8
|
8216912bde513f4fbc7b59635da9d870
|
% PERFFT2 2D Fourier transform of Moisan's periodic image component
%
% Usage: [P, S, p, s] = perfft2(im)
%
% Argument: im - Image to be transformed
% Returns: P - 2D fft of periodic image component
% S - 2D fft of smooth component
% p - Periodic component (spatial domain)
% s - Smooth component (spatial domain)
%
% Moisan's "Periodic plus Smooth Image Decomposition" decomposes an image
% into two components
% im = p + s
% where s is the 'smooth' component with mean 0 and p is the 'periodic'
% component which has no sharp discontinuities when one moves cyclically across
% the image boundaries.
%
% This wonderful decomposition is very useful when one wants to obtain an FFT of
% an image with minimal artifacts introduced from the boundary discontinuities.
% The image p gathers most of the image information but avoids periodization
% artifacts.
%
% The typical use of this function is to obtain a 'periodic only' fft of an
% image
% >> P = perfft2(im);
%
% Displaying the amplitude spectrum of P will yield a clean spectrum without the
% typical vertical-horizontal 'cross' arising from the image boundaries that you
% would normally see.
%
% Note if you are using the function to perform filtering in the frequency
% domain you may want to retain s (the smooth component in the spatial domain)
% and add it back to the filtered result at the end.
%
% The computational cost of obtaining the 'periodic only' FFT involves taking an
% additional FFT.
%
%
% Reference:
% This code is adapted from Lionel Moisan's Scilab function 'perdecomp.sci'
% "Periodic plus Smooth Image Decomposition" 07/2012 available at
%
% http://www.mi.parisdescartes.fr/~moisan/p+s
%
% Paper:
% L. Moisan, "Periodic plus Smooth Image Decomposition", Journal of
% Mathematical Imaging and Vision, vol 39:2, pp. 161-179, 2011.
% Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
% September 2012
function [P, S, p, s] = perfft2(im)
if ~isa(im, 'double'), im = double(im); end
[rows,cols] = size(im);
% Compute the boundary image which is equal to the image discontinuity
% values across the boundaries at the edges and is 0 elsewhere
s = zeros(size(im));
s(1,:) = im(1,:) - im(end,:);
s(end,:) = -s(1,:);
s(:,1) = s(:,1) + im(:,1) - im(:,end);
s(:,end) = s(:,end) - im(:,1) + im(:,end);
% Generate grid upon which to compute the filter for the boundary image in
% the frequency domain. Note that cos() is cyclic hence the grid values can
% range from 0 .. 2*pi rather than 0 .. pi and then pi .. 0
[cx, cy] = meshgrid(2*pi*[0:cols-1]/cols, 2*pi*[0:rows-1]/rows);
% Generate FFT of smooth component
S = fft2(s)./(2*(2 - cos(cx) - cos(cy)));
% The (1,1) element of the filter will be 0 so S(1,1) may be Inf or NaN
S(1,1) = 0; % Enforce 0 mean
P = fft2(im) - S; % FFT of periodic component
if nargout > 2 % Generate spatial domain results
s = real(ifft2(S));
p = im - s;
end
|
github
|
jacksky64/imageProcessing-master
|
invfft2shft.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/invfft2shft.m
| 308 |
utf_8
|
1ee9d3b8e1e84f25b0fb5503595f7bfa
|
% INVFFT2SHFT - takes inverse fft, quadrant shifts and returns real part.
%
% Function to `wrap up' taking the inverse Fourier transform
% quadrant shifting and extraction of the real part into the one operation
% Peter Kovesi October 1999
function ift = invfft2shft(ft)
ift = fftshift(real(ifft2(ft)));
|
github
|
jacksky64/imageProcessing-master
|
quantizephase.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/quantizephase.m
| 1,944 |
utf_8
|
c4d5690a2daf54b63e4c2fd0ccecb488
|
% QUANTIZEPHASE Quantize phase values in an image
%
% Usage: qim = quantizephase(im, N)
%
% Arguments: im - Image to be processed
% N - Desired number of quantized phase values
%
% Returns: qim - Phase quantized image
%
% Phase values in an image are important. However, despite this, they can be
% quantized very heavily with little perceptual loss. The value of N can be
% as low as 4, or even 3! Using N = 2 is also worth a look.
%
%
% Copyright (c) 2011 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% http://www.csse.uwa.edu.au/~pk/research/matlabfns/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% The software is provided "as is", without warranty of any kind.
% May 2011
function qim = quantizephase(im, N)
IM = fft2(im);
amp = abs(IM);
phase = angle(IM);
% Quantize the phase values as follows:
% Add pi - .001 so that values range [0 - 2pi)
% Divide by 2pi so that values range [0 - 1)
% Scale by N so that values range [0 - N)
% Round twoards 0 using fix giving integers [0 - N-1]
% Scale by 2*pi/N to give N discrete phase values [0 - 2*pi)
% Subtract pi so that discrete values range [-pi - pi)
% Add pi/N to counteract the phase shift induced by rounding towards 0
% using fix.
phase = fix( (phase+pi-.001)/(2*pi) * N) * (2*pi)/N - pi + pi/N ;
% figure, hist(phase(:),100)
% Reconstruct Fourier transform with quantized phase values and take inverse
% to obtain the new image.
QIM = amp.*(cos(phase) + i*sin(phase));
qim = real(ifft2(QIM));
|
github
|
jacksky64/imageProcessing-master
|
homomorphic.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FrequencyFilt/homomorphic.m
| 5,424 |
utf_8
|
51155a84aab5eba10f502eb788a81b16
|
% HOMOMORPHIC - Performs homomorphic filtering on an image.
%
% Function performs homomorphic filtering on an image. This form of
% filtering sharpens features and flattens lighting variantions in an image.
% It usually is very effective on images which have large variations in
% lighting, for example when a subject appears against strong backlighting.
%
%
% Usage: newim =
% homomorphic(inimage,boost,CutOff,order,lhistogram_cut,uhistogram_cut, hndl)
% homomorphic(inimage,boost,CutOff,order,lhistogram_cut,uhistogram_cut)
% homomorphic(inimage,boost,CutOff,order,hndl)
% homomorphic(inimage,boost,CutOff,order)
%
% Parameters: (suggested values are in brackets)
% boost - The ratio that high frequency values are boosted
% relative to the low frequency values (2).
% CutOff - Cutoff frequency of the filter (0 - 0.5)
% order - Order of the modified Butterworth style filter that
% is used, this must be an integer > 1 (2)
% lhistogram_cut - Percentage of the lower end of the filtered image's
% histogram to be truncated, this eliminates extreme
% values in the image from distorting the final result. (0)
% uhistogram_cut - Percentage of upper end of histogram to truncate. (5)
% hndl - Optional handle to text box for updating
% messages to be sent to a GUI interface.
%
% If lhistogram_cut and uhistogram_cut are not specified no histogram truncation will be
% applied.
%
%
% Suggested values: newim = homomorphic(im, 2, .25, 2, 0, 5);
%
% homomorphic called with no arguments invokes GUI interface.
%
% or simply homomorphic to invoke the GUI - GUI version does not work!
% Copyright (c) 1999-2001 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% June 1999
% December 2001 cleaned up and modified to work with colour images
function him = homomorphic(im, boost, CutOff, order, varargin)
% if nargin == 0 % invoke GUI if it exists
% if exist('homomorphicGUI.m');
% homomorphicGUI;
% return;
% else
% error('homomorphicGUI does not exist');
% end
%
% else
if ndims(im) == 2 % Greyscale image
him = Ihomomorphic(im, boost, CutOff, order, varargin);
else % Assume colour image in RGB format
hsv = rgb2hsv(im); % Convert to HSV and apply homomorphic
% filtering to just the intensity component.
hsv(:,:,3) = Ihomomorphic(hsv(:,:,3), boost, CutOff, order, varargin);
him = hsv2rgb(hsv); % Convert back to RGB
end
% end
%------------------------------------------------------------------------
% Internal function that does the real work
%------------------------------------------------------------------------
function him = Ihomomorphic(im, boost, CutOff, order, varargin)
% The possible elements in varargin are:
% {lhistogram_cut, uhistogram_cut, hndl}
varargin = varargin{:};
if nargin == 5
nopparams = length(varargin);
end
if (nopparams == 3)
dispStatus = 1;
truncate = 1;
lhistogram_cut = varargin{1};
uhistogram_cut = varargin{2};
hndl = varargin{3};
elseif (nopparams == 2)
dispStatus = 0;
truncate = 1;
lhistogram_cut = varargin{1};
uhistogram_cut = varargin{2};
elseif (nopparams == 1)
dispStatus = 1;
truncate = 0;
hndl = varargin{1};
elseif (nopparams == 0)
dispStatus = 0;
truncate = 0;
else
disp('Usage: newim = homomorphic(inimage,LowGain,HighGain,CutOff,order,lhistogram_cut,uhistogram_cut)');
error('or newim = homomorphic(inimage,LowGain,HighGain,CutOff,order)');
end
[rows,cols] = size(im);
im = normalise(im); % Rescale values 0-1 (and cast
% to `double' if needed).
FFTlogIm = fft2(log(im+.01)); % Take FFT of log (with offset
% to avoid log of 0).
h = highboostfilter([rows cols], CutOff, order, boost);
him = exp(real(ifft2(FFTlogIm.*h))); % Apply the filter, invert
% fft, and invert the log.
if truncate
% Problem:
% The extreme bright values in the image are exaggerated by the filtering.
% These (now very) bright values have the overall effect of darkening the
% whole image when we rescale values to 0-255.
%
% Solution:
% Construct a histogram of the image. Find the level below which a high
% percentage of the image lies (say 95%). Saturate the grey levels in
% the image to this level.
if dispStatus
set(hndl,'String','Calculating histogram and truncating...');
drawnow;
else
disp('Calculating histogram and truncating...');
end
him = histtruncate(him, lhistogram_cut, uhistogram_cut);
else
him = normalise(him); % No truncation, but fix range 0-1
end
|
github
|
jacksky64/imageProcessing-master
|
animateHessianGaussian.m
|
.m
|
imageProcessing-master/gaussdiff/animateHessianGaussian.m
| 3,651 |
utf_8
|
232429d2012a4e02b1901c352a995c5f
|
function animateHessianGaussian(fname)
%animate HessianGaussian - creates a figure with a rotationg second order
%derivative. It is calculated each frame by combining the three kernels of
%the Hessian matrix: Lxx, Lyy and Lxy. Using these three kernels, the
%second order derivative can be calculated in any direction!
%
% animateHessianGaussian() displays the animation
%
% animateHessianGaussian(fname) makes an animated gif of the animation, and
% writes it to fname.
if nargin==0; fname=[]; end;
H = []; % data container
H.fname = fname;
% create figure
H.hf = figure(100202); clf;
set(H.hf,'MenuBar','none','position',[500 500 400 300],'NumberTitle','off','color','k');
if ~isempty(H.fname); set(H.hf,'name','Waiting one round before creating AVI...');
else; set(H.hf,'name','Rotating second order Gaussian derivative');
end;
colormap winter;
shading faceted;
% create timer
H.ht = timer( 'TimerFcn',@animateHessianGaussian_nextAngle,...
'period',0.05,...
'ExecutionMode','fixedSpacing',...
'TasksToExecute',inf);
% create kernels
sig = 6;
H.Kxx = gaussiankernel2(sig,2,0,4);
H.Kyy = gaussiankernel2(sig,0,2,4);
H.Kxy = gaussiankernel2(sig,1,1,4);
% initialise angle, and set delta-angle
H.phi = 0.01; % start slightly more. So animation starts writing to gif after one round
H.dphi = 0.05;
% init surface plot and axes
H.hsurf = surf(H.Kxx);
axis([0 40 0 40 -0.0001 0.0001]);
axis off;
shg;
% set axes nice
set(gca,'units','normalized','position',[0 0 1 1]);
rotate3d on;
% store data in the timer object.
set(H.ht,'UserData',H);
% start timer
start(H.ht);
end % of main
function animateHessianGaussian_nextAngle(hObject,events)
try
% get data
H = get(hObject,'UserData');
% if figure or surfplot gone, stop alltogeher
if ~ishandle(H.hf) || ~ishandle(H.hsurf)
stop(hObject);
delete(hObject);
return;
end
% increase angle
H.phi = H.phi + H.dphi;
if H.phi>2*pi; H.phi = 0; end;
% create kernel from the three base kernels
a = cos(H.phi);
b = sin(H.phi);
patch = a*a*H.Kxx + b*b*H.Kyy + 2*a*b*H.Kxy;
% show kernel
set(H.hsurf,'CData',patch,'Zdata',patch); drawnow;
% make animation? AVI
if ~isempty(H.fname)
% make screenshot
H.movie(1) = getframe(H.hf);
if H.phi==0
if ~strcmp( get(H.hf,'name') , 'Creating AVI...' )
set(H.hf,'name','Creating AVI...');
H.movie = getframe(H.hf);
else
movie2avi(H.movie,H.fname); % write file
H.fname=[]; % go to normal mode
set(H.hf,'name','Done...');
end
elseif strcmp( get(H.hf,'name') , 'Creating AVI...' )
H.movie(end+1) = getframe(H.hf);
end
end
% store data back
set(H.ht,'UserData',H);
catch
disp(lasterr);
stop(hObject);
delete(hObject);
return;
end
end
|
github
|
jacksky64/imageProcessing-master
|
sphere_sampling.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_alpert/sphere_sampling.m
| 4,426 |
utf_8
|
73ce1de08ecf14075f7fc2425b75c030
|
function [Points,L,diam,topcol,botcol] = sphere_sampling(N,lrounded,angles,mrounded,ipl)
% sphere_sampling - sample points on a sphere.
%
% [Points,L,diam] = sphere_sampling(N,lrounded,angles,mrounded,ipl)
% $Revision: 1.1 $ Paul Leopardi 2003-10-13
% Make angles=1 the default
% $Revision: 1.1 $ Paul Leopardi 2003-09-18
% Correct calculation of diameters
% Return topcol and botcol: number of regions in top and bottom collars
% $Revision: 1.1 $ Paul Leopardi 2003-09-13
% Parameter angles controls whether to locate points via angle or height average
% Match twist and offset to Maple version of the algorithm
% $Revision: 1.1 $ Paul Leopardi 2003-09-09
% Parameters lrounded and mrounded control rounding of L and m
% $Revision: 1.1 $ Paul Leopardi 2003-09-08
% Return diameters
% $Revision: 1.1 $ Paul Leopardi 2003-09-08
% for UNSW School of Mathematics
global area;
if nargin < 2
lrounded = 0;
end
if nargin < 3
angles = 1;
end
if nargin < 4
mrounded = 0;
end
if nargin < 5
ipl = 0;
end
if N == 1
Points = zeros(3,N);
Points(:,1)=[0,0,1]';
L = 1;
diam = 2*pi;
topcol = 0;
botcol = 0;
else
area = 4*pi/N;
% [A,val,exitflag,output] = fsolve(@square,sqrt(area),optimset(optimset('fsolve'),'Display','off'));
% A = real(A);
A = sqrt(area);
Beta = acos(1-2/N);
fuzz = eps*2*N;
if lrounded == 1
L = 2+max(1,round((pi-2*Beta)/A));
else
L = 2+max(1,ceil((pi-2*Beta)/A-fuzz));
end
Theta = (pi-2*Beta)/(L-2);
mbar = zeros(1,L);
mbar(1) = 1;
for i = 2:L-1
mbar(i) = N*(cos(Theta*(i-2)+Beta)-cos(Theta*(i-1)+Beta))/2;
end
mbar(L) = 1;
alpha = 0;
m = zeros(1,L);
m(1) = 1;
diam = zeros(1,L);
diam(1) = 2*Beta;
for i = 2:L
if mrounded == 1
m(i) = round(mbar(i)+alpha);
else
if (mbar(i)-floor(mbar(i)+alpha+fuzz)) < 0.5
m(i) = floor(mbar(i)+alpha+fuzz);
else
m(i) = ceil(mbar(i)+alpha-fuzz);
end
end
alpha = alpha + mbar(i)-m(i);
end
if ipl > 0
fprintf('For N=%d, the number of levels cuts L=%d\n', N, L);
fprintf('--------------------------------------------------\n');
end
Points = zeros(3,N);
Points(:,1) = [0,0,1]';
z = 1-(2+m(2))/N;
Format = 'Level %3d: mbar(%2d) =%12.8f m(%2d) =%4d diff=%12.8f; Area= %9.5f\n';
i = 1;
Area = 1;
if ipl > 0
fprintf(Format,i,i,mbar(i),i,m(i),mbar(i)-m(i),Area);
end
offset = zeros(1,L-1);
offset(1) = 0;
n=1;
for i = 2:L-1
twist=4;
if m(i-1) ~= 0 & m(i) ~= 0
offset(i) = offset(i-1)+gcd(m(i),m(i-1))/(2*m(i)*m(i-1))+min(twist,floor(m(i-1)/twist))/m(i-1);
else
offset(i) = 0;
end
top = z+m(i)/N;
rtop = sqrt(1-top^2);
bot = z-m(i)/N;
rbot = sqrt(1-bot^2);
if m(i) > 1
angle = 2*pi/m(i);
if rtop > rbot
rside = rtop;
hside = top;
else
rside = rbot;
hside = bot;
end
side = acos([rside,0,hside]*[rside*cos(angle),rside*sin(angle),hside]');
diag = acos([rtop,0,top]*[rbot*cos(angle),rbot*sin(angle),bot]');
diam(i) = max(side,diag);
else
diam(i) = acos([rtop,0,top]*[-rbot,0,bot]');
end
if angles
h = cos((acos(top)+acos(bot))/2);
else
h = z;
end
r = sqrt(1-h^2);
for j = 0:m(i)-1
s = offset(i)+j/m(i);
n = n+1;
Points(:,n) = [r*cos(2*pi*s),r*sin(2*pi*s),h]';
end
Area = 1;
if ipl > 0
fprintf(Format,i,i,mbar(i),i,m(i),mbar(i)-m(i),Area);
end
z = z-(m(i)+m(i+1))/N;
end
i = L;
Area = 1;
if ipl > 0
fprintf(Format,i,i,mbar(i),i,m(i),mbar(i)-m(i),Area);
end
Points(:,N) = [0,0,-1]';
diam(L) = 2*Beta;
if L < 3
topcol = 0;
botcol = 0;
else
topcol = m(2);
botcol = m(L-1);
end
end
function v=square(A)
global area;
v=8*asin(sqrt(2)*sin(A/2)/sin(A))-2*pi-area;
|
github
|
jacksky64/imageProcessing-master
|
perform_farthest_point_sampling.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_fast_marching/perform_farthest_point_sampling.m
| 3,382 |
utf_8
|
31f78420f1ab221fe7646f584f5d980e
|
function [points,D] = perform_farthest_point_sampling( W, points, npoints, options )
% perform_farthest_point_sampling - samples points using farthest seeding strategy
%
% points = perform_farthest_point_sampling( W, points, npoints );
%
% points can be [] or can be a (2,npts) matrix of already computed
% sampling locations.
%
% Copyright (c) 2005 Gabriel Peyre
options.null = 0;
if nargin<3
npoints = 1;
end
if nargin<2
points = [];
end
n = size(W,1);
aniso = 0;
d = nb_dims(W);
if d==4
aniso = 1;
d = 2; % tensor field
elseif d==5
aniso = 1;
d = 3; % tensor field
end
s = size(W);
s = s(1:d);
% domain constraints (for shape meshing)
L1 = getoptions(options, 'constraint_map', zeros(s) + Inf );
verb = getoptions(options, 'verb', 1);
mask = not(L1==-Inf);
if isempty(points)
% initialize farthest points at random
points = round(rand(d,1)*(n-1))+1;
% replace by farthest point
[points,L] = perform_farthest_point_sampling( W, points, 1 );
Q = ones(size(W));
points = points(:,end);
npoints = npoints-1;
else
% initial distance map
[L,Q] = my_eval_distance(W, points, options);
% L = min(zeros(s) + Inf, L1);
% Q = zeros(s);
end
for i=1:npoints
if npoints>5 && verb==1
progressbar(i,npoints);
end
options.nb_iter_max = Inf;
options.Tmax = Inf; % sum(size(W));
% [D,S] = perform_fast_marching(W, points, options);
options.constraint_map = L;
pts = points;
if not(aniso)
pts = pts(:,end);
end
D = my_eval_distance(W, pts, options);
Dold = D;
D = min(D,L); % known distance map to lanmarks
L = min(D,L1); % cropp with other constraints
if not(isempty(Q))
% update Voronoi
Q(Dold==D) = size(points,2);
end
% remove away data
D(D==Inf) = 0;
if isempty(Q)
% compute farthest points
[tmp,I] = max(D(:));
[a,b,c] = ind2sub(size(W),I(1));
else
% compute farthest steiner point
[pts,faces] = compute_saddle_points(Q,D,mask);
a = pts(1,1); b = pts(2,1); c = [];
if d==3
c = pts(3,1);
end
end
if d==2 % 2D
points = [points,[a;b]];
else % 3D
points = [points,[a;b;c]];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [D,Q] = my_eval_distance(W, x, options)
% D is distance
% Q is voronoi segmentation
options.null = 0;
n = size(W,1);
d = nb_dims(W);
if std(W(:))<eps
% euclidean distance
if size(x,2)>1
D = zeros(n)+Inf;
Q = zeros(n);
for i=1:size(x,2)
Dold = D; Qold = Q;
D = min(Dold, my_eval_distance(W,x(:,i)));
% update voronoi segmentation
Q(:) = i;
Q(D==Dold) = Qold(D==Dold);
end
return;
end
if d==2
[Y,X] = meshgrid(1:n,1:n);
D = 1/W(1) * sqrt( (X-x(1)).^2 + (Y-x(2)).^2 );
else
[X,Y,Z] = ndgrid(1:n,1:n,1:n);
D = 1/W(1) * sqrt( (X-x(1)).^2 + (Y-x(2)).^2 + (Z-x(3)).^2 );
end
Q = D*0+1;
else
[D,S,Q] = perform_fast_marching(W, x, options);
end
|
github
|
jacksky64/imageProcessing-master
|
perform_farthest_point_sampling_mesh.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_fast_marching/perform_farthest_point_sampling_mesh.m
| 1,797 |
utf_8
|
3e863c0d0d0a4b012240b09688d4c8ef
|
function [points,D] = perform_farthest_point_sampling_mesh( vertex,faces, points, nbr_iter, options )
% perform_farthest_point_sampling - samples points using farthest seeding strategy
%
% [points,D] = perform_farthest_point_sampling_mesh( vertex,faces, points, nbr_iter, options );
%
% points can be [] or can be a (nb.points,1) matrix of already computed
% sampling locations.
%
% See also: perform_fast_marching_mesh.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
if nargin<3
nb_iter = 1;
end
[vertex,faces] = check_face_vertex(vertex,faces);
n = size(vertex,2);
L1 = getoptions(options, 'constraint_map', zeros(n,1) + Inf );
if nargin<2 || isempty(points)
% initialize farthest points at random
points = round(rand(1,1)*(n-1))+1;
% replace by farthest point
[points,L] = perform_farthest_point_sampling_mesh( vertex,faces, points, 1, options );
points = points(end);
nbr_iter = nbr_iter-1;
else
% initial distance map
L = min(zeros(n,1) + Inf, L1);
end
for i=1:nbr_iter
if nbr_iter>5
progressbar( i, nbr_iter );
end
options.nb_iter_max = Inf;
options.constraint_map = L;
D = my_eval_distance(vertex,faces, points(end), options);
D = min(D,L); % known distance map to lanmarks
L = min(D,L1); % cropp with other constraints
% remove away data
D(D==Inf) = 0;
% compute farhtest points
[tmp,I] = max(D(:));
points = [points,I(1)];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function D = my_eval_distance(vertex,faces,x, options)
options.null = 0;
if length(x)>1
D = zeros(n)+Inf;
for i=1:length(x)
D = min(D, my_eval_distance(vertex,faces,x(i)));
end
return;
end
[D,Z,Q] = perform_fast_marching_mesh(vertex, faces, x, options);
|
github
|
jacksky64/imageProcessing-master
|
divgrad.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_fast_marching/divgrad.m
| 1,749 |
utf_8
|
531f368d44593d78a30eea65ad3a8134
|
function G = divgrad(M,options)
% divgrad - compute either gradient or divergence.
%
% G = divgrad(M);
%
% if M is a 2D array, compute gradient,
% if M is a 3D array, compute divergence.
% Use centered finite differences.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
if size(M,3)==2
G = mydiv(M,options);
else
G = mygrad(M,options);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d = mydiv(g,options)
bound = getoptions(options, 'bound', 'sym');
n = size(g,1);
d = zeros(n);
if strcmp(bound,'sym')
d(2:end-1,:) = d(2:end-1,:) + ( g(3:end,:,1)-g(1:end-2,:,1) )/2;
d(1,:) = d(1,:) + g(2,:,1)-g(1,:,1);
d(end,:) = d(end,:) + g(end,:,1)-g(end-1,:,1);
d(:,2:end-1) = d(:,2:end-1) + ( g(:,3:end,2)-g(:,1:end-2,2) )/2;
d(:,1) = d(:,1) + g(:,2,2)-g(:,1,2);
d(:,end) = d(:,end) + g(:,end,2)-g(:,end-1,2);
else
sel1 = [2:n 1];
sel2 = [n 1:n-1];
d = g(sel1,:,1)-g(sel2,:,1) + g(:,sel1,2)-g(:,sel2,2);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function g = mygrad(M,options)
bound = getoptions(options, 'bound', 'sym');
n = size(M,1);
g = zeros(n,n,2);
if strcmp(bound,'sym')
% on x
g(2:end-1,:,1) = ( M(3:end,:)-M(1:end-2,:) )/2;
g(1,:,1) = M(2,:)-M(1,:);
g(end,:,1) = M(end,:)-M(end-1,:);
% on y
g(:,2:end-1,2) = ( M(:,3:end)-M(:,1:end-2,:) )/2;
g(:,1,1) = M(2,:)-M(1,:);
g(:,end,1) = M(:,end)-M(:,end-1);
else
sel1 = [2:n 1];
sel2 = [n 1:n-1];
g = cat( 3, M(sel1,:)-M(sel2,:), M(:,sel1)-M(:,sel2) )/2;
end
|
github
|
jacksky64/imageProcessing-master
|
compute_voronoi_triangulation.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_fast_marching/compute_voronoi_triangulation.m
| 2,806 |
utf_8
|
6ed546707daebe1eb6f945f8834ceb61
|
function faces = compute_voronoi_triangulation(Q, vertex)
% compute_voronoi_triangulation - compute a triangulation
%
% face = compute_voronoi_triangulation(Q);
%
% Q is a Voronoi partition function, computed using
% perform_fast_marching.
% face(:,i) is the ith face.
%
% Works in 2D and in 3D.
%
% Copyright (c) 2008 Gabriel Peyre
d = nb_dims(Q);
if d==2
faces = compute_voronoi_triangulation_2d(Q, vertex);
elseif d==3
faces = compute_voronoi_triangulation_3d(Q, vertex);
else
error('Works only for 2D or 3D data.');
end
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function faces = compute_voronoi_triangulation_3d(Q, vertex)
[dx dy dz] = meshgrid(0:1,0:1,0:1);
V = [];
for i=1:8
v = Q(1+dx(i):end-1+dx(i),1+dy(i):end-1+dy(i),1+dz(i):end-1+dz(i));
V = [V v(:)];
end
V = sort(V,2);
V = unique(V, 'rows');
V = V( prod(V,2)>0 ,:);
d = V(:,1)*0;
for i=1:7
d = d+(V(:,i)~=V(:,i+1));
end
if sum(d==4)>1
% warning('Problem with triangulation.');
end
% split 5 folds into 2
I = find(d==4);
faces = [];
for i=1:length(I)
v = unique(V(I(i),:));
x = vertex(:,v); % points
% barycenter
a = sum( x, 2 ) / 5;
x = x-repmat(a, [1 size(x,2)]);
t = atan2(x(2,:),x(1,:));
[tmp,s] = sort(t);
faces = [faces v( s([1 2 3 5]))'];
faces = [faces v( s([3 4 1 5]))'];
end
% faces = [V(I,1:3);V(I,[3 4 1])];
% remaining triangles
V = V( d==3 ,:);
for i=1:size(V,1)
V(i,1:4) = unique(V(i,:));
end
faces = [faces, V(:,1:4)'];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function faces = compute_voronoi_triangulation_2d(Q, vertex)
V = [];
v = Q(1:end-1,1:end-1); V = [V v(:)];
v = Q(2:end,1:end-1); V = [V v(:)];
v = Q(1:end-1,2:end); V = [V v(:)];
v = Q(2:end,2:end); V = [V v(:)];
V = sort(V,2);
V = unique(V, 'rows');
V = V( prod(V,2)>0 ,:);
d = (V(:,1)~=V(:,2)) + (V(:,2)~=V(:,3)) + (V(:,3)~=V(:,4));
if sum(d==3)>1
warning('Problem with triangulation.');
end
% split squares into 2 triangles
I = find(d==3);
faces = [];
for i=1:length(I)
v = V(I(i),:);
x = vertex(:,v); % points
% barycenter
a = sum( x, 2 ) / 4;
x = x-repmat(a, [1 size(x,2)]);
t = atan2(x(2,:),x(1,:));
[tmp,s] = sort(t);
faces = [faces; v( s([1 2 3]))];
faces = [faces; v( s([3 4 1]))];
end
% faces = [V(I,1:3);V(I,[3 4 1])];
% remaining triangles
V = V( d==2 ,:);
for i=1:size(V,1)
V(i,1:3) = unique(V(i,:));
end
faces = [faces; V(:,1:3)];
% return in correct format
faces = faces';
|
github
|
jacksky64/imageProcessing-master
|
vol3d.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_fast_marching/vol3d.m
| 5,899 |
utf_8
|
9ce5b72520d76d1225023aa3732b653d
|
function [model] = vol3d(varargin)
%H = VOL3D Volume render 3-D data.
% VOL3D uses the orthogonal plane 2-D texture mapping technique for
% volume rending 3-D data in OpenGL. Use the 'texture' option to fine
% tune the texture mapping technique. This function is best used with
% fast OpenGL hardware.
%
% H = vol3d('CData',data) Create volume render object from input
% 3-D data. Use interp3 on data to increase volume
% rendering resolution. Returns a struct
% encapsulating the pseudo-volume rendering object.
%
% vol3d(...'Parent',axH) Specify parent axes
%
% vol3d(...,'texture','2D') Default. Only render texture planes parallel
% to nearest orthogonal viewing plane. Requires
% doing vol3d(h) to refresh if the view is
% rotated (i.e. using cameratoolbar).
%
% vol3d(...,'texture','3D') Render x,y,z texture planes simultaneously.
% This avoids the need to refresh the view but
% requires faster OpenGL hardware peformance.
%
% vol3d(H) Refresh view. Updates rendering of texture planes
% to reduce visual aliasing when using the 'texture'='2D'
% option.
%
% NOTES
% Use vol3dtool for editing the colormap and alphamap.
% Adjusting these maps will allow you to explore your 3-D volume
% data at various intensity levels. See documentation on
% alphamap and colormap for more information.
%
% Use interp3 on input date to increase/decrease resolution of data
%
% Examples:
%
% % Visualizing fluid flow
% v = flow(50);
% h = vol3d('cdata',v,'texture','2D');
% view(3);
% % Update view since 'texture' = '2D'
% vol3d(h);
% alphamap('rampdown'), alphamap('decrease'), alphamap('decrease')
%
% % Visualizing MRI data
% load mri.mat
% D = squeeze(D);
% h = vol3d('cdata',D,'texture','2D');
% view(3);
% % Update view since 'texture' = '2D'
% vol3d(h);
% axis tight; daspect([1 1 .4])
% alphamap('rampup');
% alphamap(.06 .* alphamap);
%
% See also vol3dtool, alphamap, colormap, opengl, isosurface
% Copyright Joe Conti, 2004
if isstruct(varargin{1})
model = varargin{1};
if length(varargin) > 1
varargin = {varargin{2:end}};
end
else
model = localGetDefaultModel;
end
if length(varargin)>1
for n = 1:2:length(varargin)
switch(lower(varargin{n}))
case 'cdata'
model.cdata = varargin{n+1};
case 'parent'
model.parent = varargin{n+1};
case 'texture'
model.texture = varargin{n+1};
end
end
end
if isempty(model.parent)
model.parent = gca;
end
% choose default 3-D view
ax = model.parent;
axis(ax,'vis3d');
axis(ax,'tight');
[model] = local_draw(model);
%------------------------------------------%
function [model] = localGetDefaultModel
model.cdata = [];
model.xdata = [];
model.ydata = [];
model.zdata = [];
model.parent = [];
model.handles = [];
model.texture = '2D';
%------------------------------------------%
function [model,ax] = local_draw(model)
cdata = model.cdata;
siz = size(cdata);
% Define [x,y,z]data
if isempty(model.xdata)
model.xdata = [0 siz(2)];
end
if isempty(model.ydata)
model.ydata = [0 siz(1)];
end
if isempty(model.zdata)
model.zdata = [0 siz(3)];
end
try,
delete(model.handles);
end
ax = model.parent;
cam_dir = camtarget(ax) - campos(ax);
[m,ind] = max(abs(cam_dir));
h = findobj(ax,'type','surface','tag','vol3d');
for n = 1:length(h)
try,
delete(h(n));
end
end
is3DTexture = strcmpi(model.texture,'3D');
handle_ind = 1;
% Create z-slice
if(ind==3 || is3DTexture )
x = [model.xdata(1), model.xdata(2); model.xdata(1), model.xdata(2)];
y = [model.ydata(1), model.ydata(1); model.ydata(2), model.ydata(2)];
z = [model.zdata(1), model.zdata(1); model.zdata(1), model.zdata(1)];
diff = model.zdata(2)-model.zdata(1);
delta = diff/size(cdata,3);
for n = 1:size(cdata,3)
slice = double(squeeze(cdata(:,:,n)));
h(handle_ind) = surface(x,y,z,'Parent',ax);
set(h(handle_ind),'cdatamapping','scaled','facecolor','texture','cdata',slice,...
'edgealpha',0,'alphadata',double(slice),'facealpha','texturemap','tag','vol3d');
z = z + delta;
handle_ind = handle_ind + 1;
end
end
% Create x-slice
if (ind==1 || is3DTexture )
x = [model.xdata(1), model.xdata(1); model.xdata(1), model.xdata(1)];
y = [model.ydata(1), model.ydata(1); model.ydata(2), model.ydata(2)];
z = [model.zdata(1), model.zdata(2); model.zdata(1), model.zdata(2)];
diff = model.xdata(2)-model.xdata(1);
delta = diff/size(cdata,2);
for n = 1:size(cdata,2)
slice = double(squeeze(cdata(:,n,:)));
h(handle_ind) = surface(x,y,z,'Parent',ax);
set(h(handle_ind),'cdatamapping','scaled','facecolor','texture','cdata',slice,...
'edgealpha',0,'alphadata',double(slice),'facealpha','texturemap','tag','vol3d');
x = x + delta;
handle_ind = handle_ind + 1;
end
end
% Create y-slice
if (ind==2 || is3DTexture)
x = [model.xdata(1), model.xdata(1); model.xdata(2), model.xdata(2)];
y = [model.ydata(1), model.ydata(1); model.ydata(1), model.ydata(1)];
z = [model.zdata(1), model.zdata(2); model.zdata(1), model.zdata(2)];
diff = model.ydata(2)-model.ydata(1);
delta = diff/size(cdata,1);
for n = 1:size(cdata,1)
slice = double(squeeze(cdata(n,:,:)));
h(handle_ind) = surface(x,y,z,'Parent',ax);
set(h(handle_ind),'cdatamapping','scaled','facecolor','texture','cdata',slice,...
'edgealpha',0,'alphadata',double(slice),'facealpha','texturemap','tag','vol3d');
y = y + delta;
handle_ind = handle_ind + 1;
end
end
model.handles = h;
|
github
|
jacksky64/imageProcessing-master
|
compute_geodesic_mesh.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_fast_marching/compute_geodesic_mesh.m
| 4,234 |
utf_8
|
f3e2ddf4b7d47f9f8d9226288e74c5d7
|
function [path,vlist,plist] = compute_geodesic_mesh(D, vertex, face, x, options)
% compute_geodesic_mesh - extract a discrete geodesic on a mesh
%
% [path,vlist,plist] = compute_geodesic_mesh(D, vertex, face, x, options);
%
% D is the set of geodesic distances.
%
% path is a 3D curve that is the shortest path starting at x.
% You can force to use a fully discrete descent using
% options.method='discrete'.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
verb = getoptions(options, 'verb', 1);
if length(x)>1
path = {}; vlist = {}; plist = {};
for i=1:length(x)
if length(x)>5
if verb
progressbar(i,length(x));
end
end
[path{i},vlist{i},plist{i}] = compute_geodesic_mesh(D, vertex, face, x(i), options);
end
return;
end
method = getoptions(options, 'method', 'continuous');
[vertex,face] = check_face_vertex(vertex,face);
if strcmp(method, 'discrete')
if isfield(options, 'v2v')
vring = options.v2v;
else
vring = compute_vertex_ring(face);
end
% path purely on edges
vlist = x;
vprev = D(x);
while true
x0 = vlist(end);
r = vring{x0};
[v,J] = min(D(r));
x = r(J);
if v>=vprev || v==0
break;
end
vprev = v;
vlist(end+1) = x;
end
path = vertex(:,vlist);
plist = vlist*0+1;
return;
end
%%% gradient descent on edges
% retrieve adjacency lists
m = size(face,2); n = size(vertex,2);
% precompute the adjacency datasets
if isfield(options, 'e2f')
e2f = options.e2f;
else
e2f = compute_edge_face_ring(face);
end
if isfield(options, 'v2v')
v2v = options.v2v;
else
v2v = compute_vertex_ring(face);
end
% initialize the paths
[w,f] = vertex_stepping(face, x, e2f, v2v, D);
vlist = [x;w];
plist = [1];
Dprev = D(x);
while true;
% current triangle
i = vlist(1,end);
j = vlist(2,end);
k = get_vertex_face(face(:,f),i,j);
a = D(i); b = D(j); c = D(k);
% adjacent faces
f1 = get_face_face(e2f, f, i,k);
f2 = get_face_face(e2f, f, j,k);
% compute gradient in local coordinates
x = plist(end); y = 1-x;
gr = [a-c;b-c];
% twist the gradient
u = vertex(:,i) - vertex(:,k);
v = vertex(:,j) - vertex(:,k);
A = [u v]; A = (A'*A)^(-1);
gr = A*gr;
nx = gr(1); ny = gr(2);
% compute intersection point
etas = -y/ny;
etat = -x/nx;
s = x + etas*nx;
t = y + etat*ny;
if etas<0 && s>=0 && s<=1 && f1>0
%%% CASE 1 %%%
plist(end+1) = s;
vlist(:,end+1) = [i k];
% next face
f = f1;
elseif etat<0 && t>=0 && t<=1 && f2>0
%%% CASE 2 %%%
plist(end+1) = t;
vlist(:,end+1) = [j k];
% next face
f = f2;
else
%%% CASE 3 %%%
if a<=b
z = i;
else
z = j;
end
[w,f] = vertex_stepping( face, z, e2f, v2v, D);
vlist(:,end+1) = [z w];
plist(end+1) = 1;
end
Dnew = D(vlist(1,end))*plist(end) + D(vlist(2,end))*(1-plist(end));
if Dnew==0 || (Dprev==Dnew && length(plist)>1)
break;
end
Dprev=Dnew;
end
v1 = vertex(:,vlist(1,:));
v2 = vertex(:,vlist(2,:));
path = v1.*repmat(plist, [3 1]) + v2.*repmat(1-plist, [3 1]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [w,f] = vertex_stepping(face, v, e2f, v2v, D)
% adjacent vertex with minimum distance
[tmp,I] = min( D(v2v{v}) ); w = v2v{v}(I);
f1 = e2f(v,w);
f2 = e2f(w,v);
if f1<0
f = f2; return;
end
if f2<0
f = f1; return;
end
z1 = get_vertex_face(face(:,f1),v,w);
z2 = get_vertex_face(face(:,f2),v,w);
if D(z1)<D(z2);
f = f1;
else
f = f2;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function k = get_vertex_face(f,v1,v2)
if nargin==2
v2 = v1(2); v1 = v1(1);
end
k = setdiff(f, [v1 v2]);
if length(k)~=1
error('Error in get_vertex_face');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = get_face_face(e2f, f, i,j)
f1 = e2f(i,j); f2 = e2f(j,i);
if f==f1
f = f2;
else
f = f1;
end
|
github
|
jacksky64/imageProcessing-master
|
load_image.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_fast_marching/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_fast_marching/toolbox/check_face_vertex.m
| 630 |
utf_8
|
5112ad0482fa3700123a6c770f8eb622
|
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
error('face or vertex is not of correct size');
end
|
github
|
jacksky64/imageProcessing-master
|
load_signal.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/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
|
perform_kmeans.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/perform_kmeans.m
| 15,880 |
utf_8
|
889e597cbf17eb5c230a7d0c9963d860
|
function [B,seeds,E] = perform_kmeans(X,nbCluster,options)
% perform_kmeans - perform the k-means clustering algorithm.
%
% [B,seeds] = perform_kmeans(X,nbCluster,options);
%
% 'X' is a [d,n] matrix where d is the dimension of the space
% and n is the number of points (that live in R^d).
% 'nbCluster' is the number of wanted clusters.
%
% 'B' is a vector that contain the class membership
% of each point.
% 'seeds' is the current center of each region.
% 'E' is the energy of the segmentation (the lowest, the better).
%
% You can provide optional parameter in a structure options:
% - options.seeds : You can provide initial guess for the centers of the regions
% via a [d,nbCluster] matrix 'seeds', where seeds(:,i)
% is the ith center point in R^d.
% - options.intialization : if you don't provide 'seeds', then
% the algorithm will use a initialization depending on 'options.intialization':
% * If options.intialization='random' : random choice of centers.
% * If options.intialization='greedy' : greedy intialization via
% farthest point sampling.
% - options.nb_iter is the number of iterations of the Lloyd algorithm.
%
% Copyright (c) 2004 Gabriel Peyr?
if size(X,1)>size(X,2)
X = X';
end
if nargin<2
nbCluster = 4;
end
options.null = 1;
if isfield(options,'nb_iter')
nb_iter = options.nb_iter;
else
nb_iter = 5;
end
if isfield(options,'kmeans_code')
kmeans_code = options.kmeans_code;
else
kmeans_code = 2;
end
if isfield(options,'etol')
etol = options.etol;
else
etol = 0.02;
end
if kmeans_code==1
[B,seeds,E] = perform_kmeans_old(X,nbCluster,options);
elseif kmeans_code==2
[B,seeds,E] = kmeansML(nbCluster,X,'maxiter',nb_iter, 'etol', etol);
else
[B,seeds,E] = kmeans_light(X', nbCluster, etol);
seeds = seeds';
end
[membership,E] = computeMembership(X,seeds);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [B,seeds,E] = perform_kmeans_old(X,nbCluster,options);
options.null = 1;
if isfield(options,'nb_iter')
nb_iter = options.nb_iter;
else
nb_iter = 5;
end
if isfield(options,'initialization')
initialization = options.initialization;
else
initialization = 'random';
end
n = size(X,2);
d = size(X,1); % = (2*k+1)^2
if isfield(options,'seeds') && not(isempty(options.seeds))
seeds = options.seeds;
else
seeds = zeros(d,nbCluster);
if strcmp(initialization,'random')
% original centers (selected at random)
seed_num = floor(rand(nbCluster,1)*n)+1;
seeds = X(:,seed_num);
elseif strcmp(initialization,'greedy')
% select first point at random
seeds(:,1) = X(:,floor(rand*n)+1);
% replace by farthest point
D = compute_distance_to_points(X,seeds(:,1));
[tmp,I] = max(D); I = I(1);
seeds(:,1) = X(:,I);
for i=2:nbCluster
D = compute_distance_to_points(X,seeds(:,1:i-1));
if i>2
D = sum(D);
end
[tmp,I] = max(D); I = I(1);
seeds(:,i) = X(:,I);
end
else
error('Unknown intialization type (should be random/greedy).');
end
end
D = compute_distance_to_points(X,seeds);
% compute region of influence
[tmp,B] = min(D);
for i=1:nb_iter
% compute region center
for k=1:nbCluster
I = find(B==k); % points belonging to cluster k
% geometric barycenter
Xk = X(:,I);
if ~isempty(I)
seeds(:,k) = sum(Xk,2)/length(I);
else
% warning('Empty cluster created.');
end
end
% update distance to seed
D = compute_distance_to_points(X,seeds);
% compute region of influence
[tmp,B] = min(D);
end
if nargout==3
% compute the energy
E = 0;
for k=1:nbCluster
I = find(B==k); % points belonging to cluster k
D = compute_distance_to_points(X(:,I),seeds(:,k));
E = E+sum(D);
end
E = E/( n*d );
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Auxiliary function
function D = compute_distance_to_points(X,seeds)
nbCluster = size(seeds,2);
n = size(X,2);
D = zeros(nbCluster,n);
d = size(X,1);
for k=1:nbCluster
% distance to seed
D(k,:) = sum( (X - repmat(seeds(:,k),1,n)).^2 );
end
% kmeans_light: K-means clustering using euclid distance.
%
% [dataCluster codebook] = kmeans_light(data, K, stopIter)
%
% Input and output arguments ([]'s are optional):
% data (matrix) of size NxD. N is the number of data (classifiee)
% vectors,and D is the dimension of each vector.
% K (scalar) The number of clusters.
% stopIter (scalar) The threshold [0, 1] to stop learning iterations.
% Default is .05, and smaller makes continue interations.
% dataCluster (matrix) of size Nx1: integers indicating the cluster indicies.
% dataCluster(i) is the cluster id for data item i.
% codebook (matrix) of size KxD: set of cluster centroids, VQ codewords.
%
% See also: autolabel.m
%
% Author : Naotoshi Seo
% Date : April, 2006
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dataCluster codebook distortion] = kmeans_light(data, K, stopIter)
if nargin < 3,
stopIter = .05;
end
[N dim] = size(data);
if K > N,
error('K must be less than or equal to the # of data');
end
% Initial codebook
codebook = data(randsample(N, K), :);
improvedRatio = Inf;
distortion = Inf;
iter = 0;
while true
% Calculate euclidean distances between each sample and each codeword
d = eucdist2(data, codebook);
% Assign each sample to the nearest codeword (centroid)
[dataNearClusterDist, dataCluster] = min(d, [], 2);
% distortion. If centroids are unchanged, distortion is also unchanged.
% smaller distortion is better
old_distortion = distortion;
distortion = mean(dataNearClusterDist);
% If no more improved, break;
improvedRatio = 1 - (distortion / old_distortion);
% fprintf('%d: improved ratio = %f\n', iter, improvedRatio); iter = iter + 1;
if improvedRatio <= stopIter, break, end;
% Renew codebook
for i=1:K
% Get the id of samples which were clusterd into cluster i.
idx = find(dataCluster == i);
% Calculate centroid of each cluter, and replace codebook
codebook(i, :) = mean(data(idx, :));
end
end
%%%% Euclidean distance matrix between row vectors in X and Y %%%%%%%
% Input and output arguments
% X: NxDim matrix
% Y: PxDim matrix
% d: distance matrix of size NxP
function d=eucdist2(X,Y);
U=~isnan(Y); Y(~U)=0;
V=~isnan(X); X(~V)=0;
d=abs(X.^2*U'+V*Y'.^2-2*X*Y');
function y = randsample(n, k, replace, w)
%RANDSAMPLE Random sample, with or without replacement.
% Y = RANDSAMPLE(N,K) returns Y as a 1-by-K vector of values sampled
% uniformly at random, without replacement, from the integers 1:N.
%
% Y = RANDSAMPLE(POPULATION,K) returns K values sampled uniformly at
% random, without replacement, from the values in the vector POPULATION.
%
% Y = RANDSAMPLE(...,REPLACE) returns a sample taken with replacement if
% REPLACE is true, or without replacement if REPLACE is false (the default).
%
% Y = RANDSAMPLE(...,true,W) returns a weighted sample, using positive
% weights W, taken with replacement. W is often a vector of probabilities.
% This function does not support weighted sampling without replacement.
%
% Example: Generate a random sequence of the characters ACGT, with
% replacement, according to specified probabilities.
%
% R = randsample('ACGT',48,true,[0.15 0.35 0.35 0.15])
%
% See also RAND, RANDPERM.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 1.1.4.1 $ $Date: 2003/11/01 04:28:51 $
if nargin < 2
error('stats:randsample:TooFewInputs','Requires two input arguments.');
elseif numel(n) == 1
population = [];
else
population = n;
n = numel(population);
if length(population)~=n
error('stats:randsample:BadPopulation','POPULATION must be a vector.');
end
end
if nargin < 3
replace = false;
end
if nargin < 4
w = [];
elseif ~isempty(w)
if length(w) ~= n
if isempty(population)
error('stats:randsample:InputSizeMismatch',...
'W must have length equal to N.');
else
error('stats:randsample:InputSizeMismatch',...
'W must have the same length as the population.');
end
else
p = w(:)' / sum(w);
end
end
switch replace
% Sample with replacement
case {true, 'true', 1}
if isempty(w)
y = ceil(n .* rand(k,1));
else
[dum, y] = histc(rand(k,1),[0 cumsum(p)]);
end
% Sample without replacement
case {false, 'false', 0}
if k > n
if isempty(population)
error('stats:randsample:SampleTooLarge',...
'K must be less than or equal to N for sampling without replacement.');
else
error('stats:randsample:SampleTooLarge',...
'K must be less than or equal to the population size.');
end
end
if isempty(w)
% If the sample is a sizeable fraction of the population,
% just randomize the whole population (which involves a full
% sort of n random values), and take the first k.
if 4*k > n
rp = randperm(n);
y = rp(1:k);
% If the sample is a small fraction of the population, a full sort
% is wasteful. Repeatedly sample with replacement until there are
% k unique values.
else
x = zeros(1,n); % flags
sumx = 0;
while sumx < k
x(ceil(n * rand(1,k-sumx))) = 1; % sample w/replacement
sumx = sum(x); % count how many unique elements so far
end
y = find(x > 0);
y = y(randperm(k));
end
else
error('stats:randsample:NoWeighting',...
'Weighted sampling without replacement is not supported.');
end
otherwise
error('stats:randsample:BadReplaceValue',...
'REPLACE must be either true or false.');
end
if ~isempty(population)
y = population(y);
else
y = y(:);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [membership,means,rms] = kmeansML(k,data,varargin)
% [membership,means,rms] = kmeansML(k,data,...)
%
% Multi-level kmeans.
% Tries very hard to always return k clusters.
%
% INPUT
% k Number of clusters
% data dxn matrix of data points
% 'maxiter' Max number of iterations. [30]
% 'dtol' Min change in center locations. [0]
% 'etol' Min percent change in RMS error. [0]
% 'ml' Multi-level? [true]
% 'verbose' Verbose level. [0]
% 0 = none
% 1 = textual
% 2 = visual
%
% OUTPUT
% membership 1xn cluster membership vector
% means dxk matrix of cluster centroids
% rms RMS error of model
%
% October 2002
% David R. Martin <[email protected]>
% process options
maxIter = 30;
dtol = 0;
etol = 0;
ml = true;
verbose = 0;
for i = 1:2:numel(varargin),
opt = varargin{i};
if ~ischar(opt), error('option names not a string'); end
if i==numel(varargin), error(sprintf('option ''%s'' has no value',opt)); end
val = varargin{i+1};
switch opt,
case 'maxiter', maxIter = max(1,val);
case 'dtol', dtol = max(0,val);
case 'etol', etol = max(0,val);
case 'ml', ml = val;
case 'verbose', verbose = val;
otherwise, error(sprintf('invalid option ''%s''',opt));
end
end
[membership,means,rms] = ...
kmeansInternal(k,data,maxIter,dtol,etol,ml,verbose,1);
function [membership,means,rms] = kmeansInternal(...
k,data,maxIter,dtol,etol,ml,verbose,retry)
[d,n] = size(data);
perm = randperm(n);
% compute initial means
rate = 3;
minN = 50;
coarseN = round(n/rate);
if ~ml | coarseN < k | coarseN < minN,
% pick random points as means
means = data(:,perm(1:k));
else
% recurse on random subsample to get means
coarseData = data(:,perm(1:coarseN));
[coarseMem,means] = ...
kmeansInternal(k,coarseData,maxIter,dtol,etol,ml,verbose,0);
end
% Iterate.
iter = 0;
rms = inf;
if verbose>0, fwrite(2,sprintf('kmeansML: n=%d d=%d k=%d [',n,d,k)); end
while iter < maxIter,
if verbose>0, fwrite(2,'.'); end
iter = iter + 1;
% Compute cluster membership and RMS error.
rmsPrev = rms;
[membership,rms] = computeMembership(data,means);
% Compute new means and cluster counts.
prevMeans = means;
[means,counts] = computeMeans(k,data,membership);
% The error should always decrease.
if rms > rmsPrev, error('bug: rms > rmsPrev'); end
% Check for convergence.
rmsPctChange = 2 * (rmsPrev - rms) / (rmsPrev + rms + eps);
maxMoved = sqrt(max(sum((prevMeans-means).^2)));
if rmsPctChange <= etol & maxMoved <= dtol,
break;
end
% Visualize.
if verbose>1,
kmeansVis(data,membership,means);
end
end
[membership,rms] = computeMembership(data,means);
if verbose>0, fwrite(2,sprintf('] rms=%.3g\n',rms)); end
% If there's an empty cluster, then re-run kmeans.
% Retry a fixed number of times.
maxRetries = 3;
if find(counts==0),
if retry < maxRetries,
disp('Warning: Re-runing kmeans due to empty cluster.');
[membership,means] = kmeansInternal( ...
k,data,maxIter,dtol,etol,ml,verbose,retry+1);
else
disp('Warning: There is an empty cluster.');
end
end
function [membership,rms] = computeMembership(data,means)
z = distSqr(data,means);
[d2,membership] = min(z,[],2);
rms = sqrt(mean(d2));
function [means,counts] = computeMeans(k,data,membership)
[d,n] = size(data);
means = zeros(d,k);
counts = zeros(1,k);
for i = 1:k,
ind = find(membership==i);
counts(i) = length(ind);
means(:,i) = sum(data(:,ind),2) / max(1,counts(i));
end
% for i = 1:n,
% j = membership(i);
% means(:,j) = means(:,j) + data(:,i);
% counts(j) = counts(j) + 1;
% end
% for j = 1:k,
% means(:,j) = means(:,j) / max(1,counts(j));
% end
function z = distSqr(x,y)
% function z = distSqr(x,y)
%
% Return matrix of all-pairs squared distances between the vectors
% in the columns of x and y.
%
% INPUTS
% x dxn matrix of vectors
% y dxm matrix of vectors
%
% OUTPUTS
% z nxm matrix of squared distances
%
% This routine is faster when m<n than when m>n.
%
% David Martin <[email protected]>
% March 2003
% Based on dist2.m code,
% Copyright (c) Christopher M Bishop, Ian T Nabney (1996, 1997)
if size(x,1)~=size(y,1),
error('size(x,1)~=size(y,1)');
end
[d,n] = size(x);
[d,m] = size(y);
% z = repmat(sum(x.^2)',1,m) ...
% + repmat(sum(y.^2),n,1) ...
% - 2*x'*y;
z = x'*y;
x2 = sum(x.^2)';
y2 = sum(y.^2);
for i = 1:m,
z(:,i) = x2 + y2(i) - 2*z(:,i);
end
|
github
|
jacksky64/imageProcessing-master
|
perform_dct_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/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
|
compute_skewness.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/compute_skewness.m
| 2,386 |
utf_8
|
d4d80af526ebb3b179c6b16cd6e2a4e3
|
function s = compute_skewness(x,center_mean)
% compute_skewness compute the Skewness.
% returns the sample skewness of the values in X. For a
% vector input, S is the third central moment of X, divided by the cube
% of its standard deviation. For a matrix input, S is a row vector
% containing the sample skewness of each column of X. For N-D arrays,
% SKEWNESS operates along the first non-singleton dimension.
%
% s = compute_skewness(x,center_mean);
% The output size for [] is a special case, handle it here.
if isequal(x,[])
s = NaN;
return;
end;
if nargin<2
center_mean = 1;
end
% Figure out which dimension nanmean will work along.
sz = size(x);
dim = find(sz ~= 1, 1);
if isempty(dim)
dim = 1;
end
% Need to tile the output of nanmean to center X.
tile = ones(1,ndims(x));
tile(dim) = sz(dim);
% Center X, compute its third and second moments, and compute the
% uncorrected skewness.
if center_mean
x0 = x - repmat(nanmean(x), tile);
else
x0 = x;
end
s2 = nanmean(x0.^2); % this is the biased variance estimator
m3 = nanmean(x0.^3);
denom = s2.^(1.5);
denom(abs(denom)<eps) = 1;
s = m3 ./ denom;
function m = nanmean(x,dim)
%NANMEAN Mean value, ignoring NaNs.
% M = NANMEAN(X) returns the sample mean of X, treating NaNs as missing
% values. For vector input, M is the mean value of the non-NaN elements
% in X. For matrix input, M is a row vector containing the mean value of
% non-NaN elements in each column. For N-D arrays, NANMEAN operates
% along the first non-singleton dimension.
%
% NANMEAN(X,DIM) takes the mean along the dimension DIM of X.
%
% See also MEAN, NANMEDIAN, NANSTD, NANVAR, NANMIN, NANMAX, NANSUM.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.13.4.2 $ $Date: 2004/01/24 09:34:32 $
% Find NaNs and set them to zero
nans = isnan(x);
x(nans) = 0;
if nargin == 1 % let sum deal with figuring out which dimension to use
% Count up non-NaNs.
n = sum(~nans);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x) ./ n;
else
% Count up non-NaNs.
n = sum(~nans,dim);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x,dim) ./ n;
end
|
github
|
jacksky64/imageProcessing-master
|
compute_kurtosis.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/compute_kurtosis.m
| 2,498 |
utf_8
|
36e9c2e951aed214419c3eaccfcdcf44
|
function k = compute_kurtosis(x, center_mean)
%compute_kurtosis - compute the Kurtosis.
%
% returns the sample kurtosis of the values in X. For a
% vector input, K is the fourth central moment of X, divided by fourth
% power of its standard deviation. For a matrix input, K is a row vector
% containing the sample kurtosis of each column of X. For N-D arrays,
% KURTOSIS operates along the first non-singleton dimension.
%
% K = compute_kurtosis(X, center_mean);
%
% Set center_mean=0 if you do not want to remove the mean before
% computing the kurtosis.
% The output size for [] is a special case, handle it here.
if isequal(x,[])
k = NaN;
return;
end;
if nargin<2
center_mean = 1;
end
% Figure out which dimension nanmean will work along.
sz = size(x);
dim = find(sz ~= 1, 1);
if isempty(dim)
dim = 1;
end
% Need to tile the output of nanmean to center X.
tile = ones(1,ndims(x));
tile(dim) = sz(dim);
% Center X, compute its fourth and second moments, and compute the
% uncorrected kurtosis.
if center_mean
x0 = x - repmat(nanmean(x), tile);
else
x0 = x;
end
s2 = nanmean(x0.^2); % this is the biased variance estimator
m4 = nanmean(x0.^4);
denom = s2.^2;
denom(abs(denom)<eps) = 1;
k = m4 ./ denom;
function m = nanmean(x,dim)
%NANMEAN Mean value, ignoring NaNs.
% M = NANMEAN(X) returns the sample mean of X, treating NaNs as missing
% values. For vector input, M is the mean value of the non-NaN elements
% in X. For matrix input, M is a row vector containing the mean value of
% non-NaN elements in each column. For N-D arrays, NANMEAN operates
% along the first non-singleton dimension.
%
% NANMEAN(X,DIM) takes the mean along the dimension DIM of X.
%
% See also MEAN, NANMEDIAN, NANSTD, NANVAR, NANMIN, NANMAX, NANSUM.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.13.4.2 $ $Date: 2004/01/24 09:34:32 $
% Find NaNs and set them to zero
nans = isnan(x);
x(nans) = 0;
if nargin == 1 % let sum deal with figuring out which dimension to use
% Count up non-NaNs.
n = sum(~nans);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x) ./ n;
else
% Count up non-NaNs.
n = sum(~nans,dim);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x,dim) ./ n;
end
|
github
|
jacksky64/imageProcessing-master
|
compute_histogram_distance.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/compute_histogram_distance.m
| 1,926 |
utf_8
|
8d2e4fb98f34f913571462dc3fec7fe2
|
function D = compute_histogram_distance(H, options)
% compute_histogram_distance - compute distance between histograms
%
% D = compute_histogram_distance(H, options);
%
% H(:,i) is the ith histogram.
% D(i,g) is the distance between histogram i and j.
%
% options.histmetric is the metric used to compute the distance d(g,h) between two histograms.
% We denote by G and H the cumulative distribution, i.e. G=cumsum(g)
% 'l2' -> d(g,h)^2 = sum_i (g(i)-h(i))^2
% 'l1' -> d(g,h) = sum_i abs(g(i)-h(i))
% 'cl2' -> d(g,h)^2 = sum_i (G(i)-H(i))^2
% 'cl1' -> d(g,h) = sum_i abs(G(i)-H(i))
% 'chi2' -> d(g,h) = sum_i (G(i)-H(i))^2 / (G(i)+H(i))
% 'bhatta' -> d(g,h) = 1 - sum_i sqrt(G(i)*H(i))
% options.sigma is a pre-smoothing factor, counted in pixels.
%
% Copyright (c) 2007 Gabriel Peyre
if isfield(options, 'sigma')
sigma = options.sigma;
else
sigma = 1.2;
end
if isfield(options, 'histmetric')
histmetric = options.histmetric;
else
histmetric = 'histmetric';
end
%% smooth the histograms
n = size(H,1);
m = size(H,2);
h = compute_gaussian_filter( 21,sigma/(2*n),n);
for i=1:m
H(:,i) = perform_convolution(H(:,i),h);
end
% make them sum to 1
H = max(H,0);
H = H ./ repmat( sum(H,1), [n 1] );
%% compute distance
switch lower(histmetric)
case {'cl2' 'cl1'}
D = distance_matrix(cumsum(H), histmetric(2:end) );
otherwise
D = distance_matrix(H, histmetric );
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function D = distance_matrix(X,metric)
n = size(X,1); % dimension
p = size(X,2);
A = repmat( reshape(X', [p 1 n] ), [1 p]);
B = permute(A, [2 1 3]);
switch metric
case 'l1'
D = sum( abs(A-B), 3 );
case 'l2'
D = sqrt( sum( (A-B).^2, 3 ) );
case 'chi2'
a = A+B; a(a<eps) = 1;
D = sum( ((A-B).^2) ./ a, 3 );
case 'bhatta'
D = 1 - sum( sqrt(A.*B), 3 );
otherwise
error('Unknown method');
end
|
github
|
jacksky64/imageProcessing-master
|
compute_histogram_rbf.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/compute_histogram_rbf.m
| 2,360 |
utf_8
|
db90055f55a69747e4b061c873ac0365
|
function h = compute_histogram_rbf(f, sigma, x, options)
% compute_histogram_rbf - parzen windows density estimation
%
% h = compute_histogram_rbf(f, sigma, x);
%
% f is the signal, h is an estimate of the histogram,
% where h(i) is the density of the estimation around value x(i).
%
% sigma is the bandwidth used to estimate the histogram (approx. size of
% the bins).
%
% If f is (n,2) matrix, then a joint histogram is estimated.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
if size(f,1)<size(f,2)
f = f';
end
if size(x,1)<size(x,2)
x = x';
end
nb_samples = Inf;
if isfield(options, 'nb_samples')
nb_samples = options.nb_samples;
end
nb_samples = min(nb_samples,size(f,1));
sel = randperm(size(f,1)); sel = sel(1:nb_samples);
f = f(sel,:);
if size(f,2)==2
h = compute_histogram_rbf_2d(f, sigma, x, options);
return;
end
if isfield(options, 'renormalize')
renormalize = options.renormalize;
else
renormalize = 0;
end
n = length(x);
p = length(f); % number of samples
f = f(:); x = x(:);
% h is of size p x n
h = repmat(f, [1 n]) - repmat( x(:)', [p 1] );
h = exp( -h.^2/(2*sigma^2) );
if renormalize
d = repmat( sum(h,2), [1 n] );
d(d<eps) = 1;
end
h = h./d;
h = sum(h,1);
h = h(:)/sum(h(:));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = compute_histogram_rbf_2d(f, sigma, x, options)
options.null = 0;
if isfield(options, 'nb_max')
nb_max = options.nb_max;
else
nb_max = 0;
end
if isfield(options, 'renormalize')
renormalize = options.renormalize;
else
renormalize = 0;
end
n = size(x,1);
p = size(f,1);
if p>nb_max
h = zeros(n);
niter = ceil(p/nb_max);
for i=1:niter
progressbar(i,niter);
sel = (i-1)*nb_max+1:min(i*nb_max,p);
h = h + compute_histogram_rbf_2d( f(sel,:) , sigma, x, options);
end
h = h/sum(h(:));
return;
end
% hx is of size p x n x n
hx = repmat( f(:,1), [1 n n]) - repmat( reshape(x(:,1),[1 n 1]),[p 1 n] );
hy = repmat( f(:,2), [1 n n]) - repmat( reshape(x(:,2),[1 1 n]),[p n 1] );
h = exp( -(hx.^2/(2*sigma(1)^2)+hy.^2/(2*sigma(2)^2)) );
if renormalize
d = repmat( sum(sum(h,2),3), [1 n n] );
d(d<eps) = 1;
h = h./d;
end
h = sum(h,1);
h = reshape(h,n,n);
h = h./sum(sum(h));
|
github
|
jacksky64/imageProcessing-master
|
compute_distance_matrix.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/compute_distance_matrix.m
| 2,330 |
utf_8
|
027fcf29f3d2a1b697af4bbb4d809c77
|
function dist = compute_distance_matrix(X,x)
% compute_distance_matrix - compute pairwise distance matrix.
%
% D = compute_distance_matrix(X);
% or
% D = compute_distance_matrix(X,x, metric);
% (set x=X)
%
% We have D(i,j)=|X(:,i)-x(:,j)|^2.
%
% Copyright (c) 2004 Gabriel Peyre
[D,N] = size(X);
try
if(nargin>=2)
% PAIRWISE DISTANCES
[d,n] = size(x);
if(D~=d)
error('Both sets of vectors must have same dimensionality!\n');
end;
X2 = sum(X.^2,1);
x2 = sum(x.^2,1);
if(exist('addchv')==3 & isreal(X))
dist=addchv(X.'*x,-2,x2,X2);
else
dist = repmat(x2,N,1)+repmat(X2.',1,n)-2*X.'*x;
end;
else
[D,N] = size(X);
if(exist('addchv')==3 & isreal(X))
X2 = sum(X.^2,1);
dist=addchv(X.'*X,-2,X2,X2);
else
X2 = repmat(sum(X.^2,1),N,1);
dist = X2+X2.'-2*X.'*X;
% fprintf('Please install addv and addh.\n');
end;
end;
% zeros the diagonal
dist = dist - diag(diag(dist));
dist = abs( dist );
catch
if(nargin==1)
dist=distanceBlock(X);
else
dist=distanceBlock(X,x);
end;
end;
function dist=distanceBlock(X,x);
% dist=distance(X,x)
%
% computes the pairwise squared distance matrix between any column vectors in X and
% in x
%
% INPUT:
%
% X dxN matrix consisting of N column vectors
% x dxn matrix consisting of n column vectors
%
% OUTPUT:
%
% dist Nxn matrix
%
% Example:
% Dist=distance(X,X);
% is equivalent to
% Dist=distance(X);
%
[D,N] = size(X);
if(nargin==1)
dist=zeros(N);
else
dist=zeros(N,size(x,2));
end;
B=round(0.1*N);
fprintf('Blocksize:%i\n',B);
dist=zeros(N);
for i=1:B:N
bi=min(B,N-i);
for j=1:B:N
bj=min(B,N-j);
dist([i,j]);
if(nargin>1)
dist(i:i+bi,j:j+bj)=distance(X(:,i:i+bi),x(:,j:j+bj));
else
dist(i:i+bi,j:j+bj)=distance(X(:,i:i+bi),X(:,j:j+bj));
end;
dist(j:j+bj,i:i+bi)=dist(i:i+bi,j:j+bj).';
end;
end;
fprintf('\n');
return;
%%%% OLD CODE %%%
[m,p] = size(X);
X2 = sum(X.^2,1);
D = repmat(X2,p,1)+repmat(X2',1,p)-2*X'*X;
|
github
|
jacksky64/imageProcessing-master
|
mad.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/mad.m
| 7,921 |
utf_8
|
6d4949e64f7802d97e068c87415b0460
|
function y = mad(x,flag)
%MAD Mean/median absolute deviation.
% Y = MAD(X) returns the mean absolute deviation of the values in X. For
% vector input, Y is MEAN(ABS(X-MEAN(X)). For a matrix input, Y is a row
% vector containing the mean absolute deviation of each column of X. For
% N-D arrays, MAD operates along the first non-singleton dimension.
%
% MAD(X,1) computes Y based on medians, i.e. MEDIAN(ABS(X-MEDIAN(X)).
% MAD(X,0) is the same as MAD(X), and uses means.
%
% MAD treats NaNs as missing values, and removes them.
%
% See also VAR, STD, IQR.
% References:
% [1] L. Sachs, "Applied Statistics: A Handbook of Techniques",
% Springer-Verlag, 1984, page 253.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.10.2.2 $ $Date: 2004/01/24 09:34:28 $
% The output size for [] is a special case, handle it here.
if isequal(x,[])
y = NaN;
return;
end;
if nargin < 2
flag = 0;
end
% Figure out which dimension nanmean will work along.
sz = size(x);
dim = find(sz ~= 1, 1);
if isempty(dim)
dim = 1;
end
% Need to tile the output of nanmean to center X.
tile = ones(1,ndims(x));
tile(dim) = sz(dim);
if flag
% Compute the median of the absolute deviations from the median.
y = nanmedian(abs(x - repmat(nanmedian(x), tile)));
else
% Compute the mean of the absolute deviations from the mean.
y = nanmean(abs(x - repmat(nanmean(x), tile)));
end
function y = nanmedian(x,dim)
%NANMEDIAN Median value, ignoring NaNs.
% M = NANMEDIAN(X) returns the sample median of X, treating NaNs as
% missing values. For vector input, M is the median value of the non-NaN
% elements in X. For matrix input, M is a row vector containing the
% median value of non-NaN elements in each column. For N-D arrays,
% NANMEDIAN operates along the first non-singleton dimension.
%
% NANMEDIAN(X,DIM) takes the median along the dimension DIM of X.
%
% See also MEDIAN, NANMEAN, NANSTD, NANVAR, NANMIN, NANMAX, NANSUM.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.12.2.2 $ $Date: 2004/01/24 09:34:33 $
if nargin == 1
y = prctile(x, 50);
else
y = prctile(x, 50,dim);
end
function m = nanmean(x,dim)
%NANMEAN Mean value, ignoring NaNs.
% M = NANMEAN(X) returns the sample mean of X, treating NaNs as missing
% values. For vector input, M is the mean value of the non-NaN elements
% in X. For matrix input, M is a row vector containing the mean value of
% non-NaN elements in each column. For N-D arrays, NANMEAN operates
% along the first non-singleton dimension.
%
% NANMEAN(X,DIM) takes the mean along the dimension DIM of X.
%
% See also MEAN, NANMEDIAN, NANSTD, NANVAR, NANMIN, NANMAX, NANSUM.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.13.4.2 $ $Date: 2004/01/24 09:34:32 $
% Find NaNs and set them to zero
nans = isnan(x);
x(nans) = 0;
if nargin == 1 % let sum deal with figuring out which dimension to use
% Count up non-NaNs.
n = sum(~nans);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x) ./ n;
else
% Count up non-NaNs.
n = sum(~nans,dim);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x,dim) ./ n;
end
function y = prctile(x,p,dim)
%PRCTILE Percentiles of a sample.
% Y = PRCTILE(X,P) returns percentiles of the values in X. P is a scalar
% or a vector of percent values. When X is a vector, Y is the same size
% as P, and Y(i) contains the P(i)-th percentile. When X is a matrix,
% the i-th row of Y contains the P(i)-th percentiles of each column of X.
% For N-D arrays, PRCTILE operates along the first non-singleton
% dimension.
%
% Y = PRCTILE(X,P,DIM) calculates percentiles along dimension DIM. The
% DIM'th dimension of Y has length LENGTH(P).
%
% Percentiles are specified using percentages, from 0 to 100. For an N
% element vector X, PRCTILE computes percentiles as follows:
% 1) The sorted values in X are taken as the 100*(0.5/N), 100*(1.5/N),
% ..., 100*((N-0.5)/N) percentiles.
% 2) Linear interpolation is used to compute percentiles for percent
% values between 100*(0.5/N) and 100*((N-0.5)/N)
% 3) The minimum or maximum values in X are assigned to percentiles
% for percent values outside that range.
%
% PRCTILE treats NaNs as missing values, and removes them.
%
% Examples:
% y = prctile(x,50); % the median of x
% y = prctile(x,[2.5 25 50 75 97.5]); % a useful summary of x
%
% See also IQR, MEDIAN, NANMEDIAN, QUANTILE.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.12.4.4 $ $Date: 2004/01/24 09:34:55 $
if ~isvector(p) || numel(p) == 0
error('stats:prctile:BadPercents', ...
'P must be a scalar or a non-empty vector.');
elseif any(p < 0 | p > 100)
error('stats:prctile:BadPercents', ...
'P must take values between 0 and 100');
end
% Figure out which dimension prctile will work along.
sz = size(x);
if nargin < 3
dim = find(sz ~= 1,1);
if isempty(dim)
dim = 1;
end
dimArgGiven = false;
else
% Permute the array so that the requested dimension is the first dim.
nDimsX = ndims(x);
perm = [dim:max(nDimsX,dim) 1:dim-1];
x = permute(x,perm);
% Pad with ones if dim > ndims.
if dim > nDimsX
sz = [sz ones(1,dim-nDimsX)];
end
sz = sz(perm);
dim = 1;
dimArgGiven = true;
end
% If X is empty, return all NaNs.
if isempty(x)
if isequal(x,[]) && ~dimArgGiven
y = nan(size(p),class(x));
else
szout = sz; szout(dim) = numel(p);
y = nan(szout,class(x));
end
else
% Drop X's leading singleton dims, and combine its trailing dims. This
% leaves a matrix, and we can work along columns.
nrows = sz(dim);
ncols = prod(sz) ./ nrows;
x = reshape(x, nrows, ncols);
x = sort(x,1);
nonnans = ~isnan(x);
% If there are no NaNs, do all cols at once.
if all(nonnans(:))
n = sz(dim);
if isequal(p,50) % make the median fast
if rem(n,2) % n is odd
y = x((n+1)/2,:);
else % n is even
y = (x(n/2,:) + x(n/2+1,:))/2;
end
else
q = [0 100*(0.5:(n-0.5))./n 100]';
xx = [x(1,:); x(1:n,:); x(n,:)];
y = zeros(numel(p), ncols, class(x));
y(:,:) = interp1q(q,xx,p(:));
end
% If there are NaNs, work on each column separately.
else
% Get percentiles of the non-NaN values in each column.
y = nan(numel(p), ncols, class(x));
for j = 1:ncols
nj = find(nonnans(:,j),1,'last');
if nj > 0
if isequal(p,50) % make the median fast
if rem(nj,2) % nj is odd
y(:,j) = x((nj+1)/2,j);
else % nj is even
y(:,j) = (x(nj/2,j) + x(nj/2+1,j))/2;
end
else
q = [0 100*(0.5:(nj-0.5))./nj 100]';
xx = [x(1,j); x(1:nj,j); x(nj,j)];
y(:,j) = interp1q(q,xx,p(:));
end
end
end
end
% Reshape Y to conform to X's original shape and size.
szout = sz; szout(dim) = numel(p);
y = reshape(y,szout);
end
% undo the DIM permutation
if dimArgGiven
y = ipermute(y,perm);
end
% If X is a vector, the shape of Y should follow that of P, unless an
% explicit DIM arg was given.
if ~dimArgGiven && isvector(x)
y = reshape(y,size(p));
end
|
github
|
jacksky64/imageProcessing-master
|
perform_moment_equalization.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/perform_moment_equalization.m
| 11,991 |
utf_8
|
cd7ec09148f7192b3fda19ca178088e1
|
function x = perform_moment_equalization(x,y,numdim, options)
% perform_kurtosis_equalization - equalize moments of order 1,2,3,4.
%
% x = perform_moment_equalization(x,y,numdim,options);
%
% (numdim=1 by default).
%
% Equalizes the mean, variance, skewness and kurtosis.
% Set options.xx=0 to avoid equalizing one of the moment, where
% xx='skewness' or 'kurtosis'.
%
% For 2D arrays, operates along columns unless you specify
% x = perform_kurtosis_equalization(x,y,2);
%
% Copyright (c) 2006 Gabriel Peyr?
% mem=mean2(chm);
% sk2 = mean2((chm-mem).^3)/mean2((chm-mem).^2).^(3/2);
options.null = 0;
if nargin<3
numdim = 1;
end
if size(x,1)>1 && size(x,2)>1
if numdim>1
x = x'; y = y';
end
p = size(x,2);
for i=1:p
if p>100
progressbar(i,p);
end
x(:,i) = perform_moment_equalization( x(:,i),y(:,i),1,options );
end
if numdim>1
x = x';
end
return;
end
dokurt = 1;
doskew = 1;
if isfield(options, 'kurtosis')
dokurt = options.kurtosis;
end
if isfield(options, 'skewness')
doskew = options.skewness;
end
niter = 1;
if std(x(:))<eps && std(y(:))>eps
% regenerate random noise ...
x = randn(size(x)) * std(y(:)) + mean(y(:));
end
if std(y(:))>eps
sk = skew2(y);
k = kurt2(y);
for i=1:niter
if dokurt
[x, snrk] = modkurt(x,k);
end
if doskew
[x, snrk] = modskew(x,sk);
end
end
end
% correct mean and variance
if std(x(:))>1e-9
x = (x-mean(x(:))) * std(y(:))/std(x(:)) + mean(y(:));
end
function [chm, snrk] = modkurt(ch,k,p);
% Modify the kurtosis in one step, by moving in gradient direction until
% reaching the desired kurtosis value.
% It does not affect the mean nor the variance, but it affects the skewness.
% This operation is not an orthogonal projection, but the projection angle is
% near pi/2 when k is close to the original kurtosis, which is a realistic assumption
% when doing iterative projections in a pyramid, for example (small corrections
% to the channels' statistics).
%
% [chm, snrk] = modkurt(ch,k,p);
% ch: channel
% k: desired kurtosis (k=M4/M2^2)
% p [OPTIONAL]: mixing proportion between k0 and k
% it imposes (1-p)*k0 + p*k,
% being k0 the current kurtosis.
% DEFAULT: p = 1;
% Javier Portilla, Oct.12/97, NYU
Warn = 0; % Set to 1 if you want to see warning messages
if ~exist('p'),
p = 1;
end
me=mean2(ch);
ch=ch-me;
% Compute the moments
m=zeros(12,1);
for n=2:12,
m(n)=mean2(ch.^n);
end
% The original kurtosis
k0=m(4)/m(2)^2;
snrk = snr(k, k-k0);
if snrk > 60,
chm = ch+me;
return
end
k = k0*(1-p) + k*p;
% Some auxiliar variables
a=m(4)/m(2);
% Coeficients of the numerator (A*lam^4+B*lam^3+C*lam^2+D*lam+E)
A=m(12)-4*a*m(10)-4*m(3)*m(9)+6*a^2*m(8)+12*a*m(3)*m(7)+6*m(3)^2*m(6)-...
4*a^3*m(6)-12*a^2*m(3)*m(5)+a^4*m(4)-12*a*m(3)^2*m(4)+...
4*a^3*m(3)^2+6*a^2*m(3)^2*m(2)-3*m(3)^4;
B=4*(m(10)-3*a*m(8)-3*m(3)*m(7)+3*a^2*m(6)+6*a*m(3)*m(5)+3*m(3)^2*m(4)-...
a^3*m(4)-3*a^2*m(3)^2-3*m(4)*m(3)^2);
C=6*(m(8)-2*a*m(6)-2*m(3)*m(5)+a^2*m(4)+2*a*m(3)^2+m(3)^2*m(2));
D=4*(m(6)-a^2*m(2)-m(3)^2);
E=m(4);
% Define the coefficients of the denominator (F*lam^2+G)^2
F=D/4;
G=m(2);
% test
test = 0;
if test,
grd = ch.^3 - a*ch - m(3);
lam = -0.001:0.00001:0.001;
k = (A*lam.^4+B*lam.^3+C*lam.^2+D*lam+E)./...
(F*lam.^2 + G).^2;
for lam = -0.001:0.00001:0.001,
n = lam*100000+101;
chp = ch + lam*grd;
k2(n) = mean2(chp.^4)/mean2(chp.^2)^2;
%k2(n) = mean2(chp.^4);
end
lam = -0.001:0.00001:0.001;
snr(k2, k-k2)
end % test
% Now I compute its derivative with respect to lambda
% (only the roots of derivative = 0 )
d(1) = B*F;
d(2) = 2*C*F - 4*A*G;
d(3) = 4*F*D -3*B*G - D*F;
d(4) = 4*F*E - 2*C*G;
d(5) = -D*G;
mMlambda = roots(d);
tg = imag(mMlambda)./real(mMlambda);
mMlambda = mMlambda(find(abs(tg)<1e-6));
lNeg = mMlambda(find(mMlambda<0));
if length(lNeg)==0,
lNeg = -1/eps;
end
lPos = mMlambda(find(mMlambda>=0));
if length(lPos)==0,
lPos = 1/eps;
end
lmi = max(lNeg);
lma = min(lPos);
lam = [lmi lma];
mMnewKt = polyval([A B C D E],lam)./(polyval([F 0 G],lam)).^2;
kmin = min(mMnewKt);
kmax = max(mMnewKt);
% Given a desired kurtosis, solves for lambda
if k<=kmin
lam = lmi;
if Warn
warning('Saturating (down) kurtosis!');
kmin
end
elseif k>=kmax
lam = lma;
if Warn
warning('Saturating (up) kurtosis!');
kmax
end
else
% Coeficients of the algebraic equation
c0 = E - k*G^2;
c1 = D;
c2 = C - 2*k*F*G;
c3 = B;
c4 = A - k*F^2;
% Solves the equation
r=roots([c4 c3 c2 c1 c0]);
% Chose the real solution with minimum absolute value with the rigth sign
denom = real(r);
denom(abs(denom)<eps) = 1;
tg = imag(r)./denom;
%lambda = real(r(find(abs(tg)<1e-6)));
lambda = real(r(find(abs(tg)==0)));
if length(lambda)>0,
lam = lambda(find(abs(lambda)==min(abs(lambda))));
lam = lam(1);
else
lam = 0;
end
end % if ... else
% Modify the channel
chm=ch+lam*(ch.^3-a*ch-m(3)); % adjust the kurtosis
chm=chm*sqrt(m(2)/mean2(chm.^2)); % adjust the variance
chm=chm+me; % adjust the mean
% Check the result
%k2=mean2((chm-me).^4)/(mean2((chm-me).^2))^2;
%SNR=snr(k,k-k2)
function [chm, snrk] = modskew(ch,sk,p);
% Adjust the sample skewness of a vector/matrix, using gradient projection,
% without affecting its sample mean and variance.
%
% This operation is not an orthogonal projection, but the projection angle is
% near pi/2 when sk is close to the original skewness, which is a realistic
% assumption when doing iterative projections in a pyramid, for example
% (small corrections to the channels' statistics).
%
% [xm, snrk] = modskew(x,sk,p);
% sk: new skweness
% p [OPTIONAL]: mixing proportion between sk0 and sk
% it imposes (1-p)*sk0 + p*sk,
% being sk0 the current skewness.
% DEFAULT: p = 1;
%
% JPM. 2/98, IODV, CSIC
% 4/00, CNS, NYU
Warn = 0; % Set to 1 if you want to see warning messages
if ~exist('p'),
p = 1;
end
N=prod(size(ch)); % number of samples
me=mean2(ch);
ch=ch-me;
for n=2:6,
m(n)=mean2(ch.^n);
end
sd=sqrt(m(2)); % standard deviation
s=m(3)/sd^3; % original skewness
snrk = snr(sk, sk-s);
sk = s*(1-p) + sk*p;
% Define the coefficients of the numerator (A*lam^3+B*lam^2+C*lam+D)
A=m(6)-3*sd*s*m(5)+3*sd^2*(s^2-1)*m(4)+sd^6*(2+3*s^2-s^4);
B=3*(m(5)-2*sd*s*m(4)+sd^5*s^3);
C=3*(m(4)-sd^4*(1+s^2));
D=s*sd^3;
a(7)=A^2;
a(6)=2*A*B;
a(5)=B^2+2*A*C;
a(4)=2*(A*D+B*C);
a(3)=C^2+2*B*D;
a(2)=2*C*D;
a(1)=D^2;
% Define the coefficients of the denominator (A2+B2*lam^2)
A2=sd^2;
B2=m(4)-(1+s^2)*sd^4;
b=zeros(1,7);
b(7)=B2^3;
b(5)=3*A2*B2^2;
b(3)=3*A2^2*B2;
b(1)=A2^3;
if 0, % test
lam = -2:0.02:2;
S = (A*lam.^3+B*lam.^2+C*lam+D)./...
sqrt(b(7)*lam.^6 + b(5)*lam.^4 + b(3)*lam.^2 + b(1));
% grd = ch.^2 - m(2) - sd * s * ch;
% for lam = -1:0.01:1,
% n = lam*100+101;
% chp = ch + lam*grd;
% S2(n) = mean2(chp.^3)/abs(mean2(chp.^2))^(1.5);
% end
lam = -2:0.02:2;
figure(1);plot(lam,S);grid;drawnow
% snr(S2, S-S2)
end % test
% Now I compute its derivative with respect to lambda
d(8) = B*b(7);
d(7) = 2*C*b(7) - A*b(5);
d(6) = 3*D*b(7);
d(5) = C*b(5) - 2*A*b(3);
d(4) = 2*D*b(5) - B*b(3);
d(3) = -3*A*b(1);
d(2) = D*b(3) - 2*B*b(1);
d(1) = -C*b(1);
d = d(8:-1:1);
mMlambda = roots(d);
denom = real(mMlambda);
[tmp,I] = find( min(abs(denom))<eps );
denom(I) = 1;
tg = imag(mMlambda)./denom;
mMlambda = real(mMlambda(find(abs(tg)<1e-6)));
lNeg = mMlambda(find(mMlambda<0));
if length(lNeg)==0,
lNeg = -1/eps;
end
lPos = mMlambda(find(mMlambda>=0));
if length(lPos)==0,
lPos = 1/eps;
end
lmi = max(lNeg);
lma = min(lPos);
lam = [lmi lma];
denom = (polyval(b(7:-1:1),lam)).^0.5;
if 0
[tmp,I] = find( min(abs(denom))<eps );
denom(I) = 1;
end
denom(abs(denom)<eps) = 1;
mMnewSt = polyval([A B C D],lam)./denom;
skmin = min(mMnewSt);
skmax = max(mMnewSt);
% Given a desired skewness, solves for lambda
if sk<=skmin
lam = lmi;
if Warn
warning('Saturating (down) skewness!');
skmin
end
elseif sk>=skmax & Warn,
lam = lma;
if Warn
warning('Saturating (up) skewness!');
skmax
end
else
% The equation is sum(c.*lam.^(0:6))=0
c=a-b*sk^2;
c=c(7:-1:1);
r=roots(c);
% Chose the real solution with minimum absolute value with the rigth sign
lam=-Inf;
co=0;
for n=1:min(6,length(r)),
denom = real(r(n));
[tmp,I] = find( min(abs(denom))<eps );
denom(I) = 1;
tg = imag(r(n))/denom;
if (abs(tg)<1e-6)&(sign(real(r(n)))==sign(sk-s)),
co=co+1;
lam(co)=real(r(n));
end
end
if min(abs(lam))==Inf
if Warn
display('Warning: Skew adjustment skipped!');
end
lam=0;
end
p=[A B C D];
if length(lam)>1,
foo=sign(polyval(p,lam));
if any(foo==0),
lam = lam(find(foo==0));
else
lam = lam(find(foo==sign(sk))); % rejects the symmetric solution
end
if length(lam)>0,
lam=lam(find(abs(lam)==min(abs(lam)))); % the smallest that fix the skew
lam=lam(1);
else
lam = 0;
end
end
end % if else
% Modify the channel
chm=ch+lam*(ch.^2-sd^2-sd*s*ch); % adjust the skewness
chm=chm*sqrt(m(2)/mean2(chm.^2)); % adjust the variance
chm=chm+me; % adjust the mean
% (These don't affect the skewness)
% Check the result
%mem=mean2(chm);
%sk2=mean2((chm-mem).^3)/mean2((chm-mem).^2).^(3/2);
%sk - sk2
%SNR=snr(sk,sk-sk2)
% S = SKEW2(MTX,MEAN,VAR)
%
% Sample skew (third moment divided by variance^3/2) of a matrix.
% MEAN (optional) and VAR (optional) make the computation faster.
function res = skew2(mtx, mn, v)
if (exist('mn') ~= 1)
mn = mean2(mtx);
end
if (exist('v') ~= 1)
v = var2(mtx,mn);
end
if (isreal(mtx))
res = mean(mean((mtx-mn).^3)) / (v^(3/2));
else
res = mean(mean(real(mtx-mn).^3)) / (real(v)^(3/2)) + ...
i * mean(mean(imag(mtx-mn).^3)) / (imag(v)^(3/2));
end
% 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
% M = MEAN2(MTX)
%
% Sample mean of a matrix.
function res = mean2(mtx)
res = mean(mean(mtx));
% 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
function X=snr(s,n);
% Compute the signal-to-noise ratio in dB
% X=SNR(signal,noise);
% (it does not subtract the means).
es=sum(sum(abs(s).^2));
en=sum(sum(abs(n).^2));
if en<eps
X = en;
else
X=10*log10(es/en);
end
|
github
|
jacksky64/imageProcessing-master
|
perform_histogram_matching.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/perform_histogram_matching.m
| 6,400 |
utf_8
|
60f90bff8d6cd335507795f1602dafad
|
function x = perform_histogram_matching(x, y, options)
% perform_histogram_matching - match the histogram of two image.
%
% x = perform_histogram_matching(x, y, nb_bins);
% or
% x = perform_histogram_matching(x, y, options);
%
% Perform an equalization of x so that it histogram
% matches the histogram of y.
%
% Works also for vector valued (ie 3D matrix) images.
% For color images, ie (n,p,3) sized image, the matching is performed
% * in RVB space if options.match_ycbcr=0
% * in YcBCr space if options.match_ycbcr=1 (default, works better)
%
% Copyright (c) 2005 Gabriel Peyre
if nargin>2 && not(isstruct(options))
opt = options;
clear options;
options.nb_bins = opt;
end
options.null = 0;
nb_bins = getoptions(options, 'nb_bins', 100);
match_ycbcr = getoptions(options, 'match_ycbcr', 1);
absval = getoptions(options, 'absval', 0);
cols = getoptions(options, 'cols', 0);
rows = getoptions(options, 'rows', 0);
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
if size(x,3)>1 || size(y,3)>1
error('options.cols does not works for color images');
end
for i=1:size(x,2)
x(:,i) = perform_histogram_matching(x(:,i),y(:,i),options);
end
return;
end
if cols && size(x,1)>1
if not(size(x,1)==size(y,1))
error('x and y must have same number of rows');
end
if size(x,3)>1 || size(y,3)>1
error('options.rows does not works for color images');
end
for i=1:size(x,1)
x(i,:) = perform_histogram_matching(x(i,:),y(i,:),options);
end
return;
end
if iscell(x)
if ~(length(x)==length(y))
error('For cell arrays, src and tgt must have the same length.');
end
for i=1:length(x)
if length(find(isinf(x{i})))==0
x{i} = perform_histogram_matching(x{i}, y{i}, options);
else
x{i} = x{i};
end
end
return;
end
if size(x,3)>1
if size(x,3)~=size(y,3)
error('Src and tgt 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:size(y,3)
x(:,:,i) = perform_histogram_matching(x(:,:,i), y(:,:,i), options);
end
if size(x,3)==3 && match_ycbcr
x = ycbcr2rgb(x);
end
return;
end
if sum(abs(y(:) - mean(y(:))))<1e-8
% histo is crashing for constant signals
x = x*0 + mean(y(:));
return;
end
sx = size(x);
x = x(:);
y = y(:);
if absval
s = sign(x);
x = abs(x);
y = abs(y);
end
% compute transformed histograms
% [N,X] = histo(y, nb_bins);
[N,X] = histo_slow(y, nb_bins);
x = histoMatch(x, N, X);
I = find(isnan(x(:)));
x(I) = max(y(:));
if absval
x = x .* s;
end
x = reshape(x,sx);
% [N,X] = histo_slow(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_slow(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);
% RES = histoMatch(MTX, N, X)
%
% Modify elements of MTX so that normalized histogram matches that
% specified by vectors X and N, where N contains the histogram counts
% and X the histogram bin positions (see histo).
% Eero Simoncelli, 7/96.
function res = histoMatch(mtx, N, X)
if ( exist('histo') == 3 )
[oN, oX] = histo(mtx(:), size(X(:),1));
else
[oN, oX] = hist(mtx(:), size(X(:),1));
end
oStep = oX(2) - oX(1);
oC = [0, cumsum(oN)]/sum(oN);
oX = [oX(1)-oStep/2, oX+oStep/2];
N = N(:)';
X = X(:)';
N = N + mean(N)/(1e8); %% HACK: no empty bins ensures nC strictly monotonic
nStep = X(2) - X(1);
nC = [0, cumsum(N)]/sum(N);
nX = [X(1)-nStep/2, X+nStep/2];
nnX = interp1(nC, nX, oC, 'linear');
if ( exist('pointOp') == 3 )
res = pointOp(mtx, nnX, oX(1), oStep);
else
res = reshape(interp1(oX, nnX, mtx(:)),size(mtx,1),size(mtx,2));
end
% [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
|
load_image.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_signal/toolbox/load_image.m
| 15,910 |
utf_8
|
f5a8233f70450d4ce607431750bcffda
|
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 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 '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');
|
github
|
jacksky64/imageProcessing-master
|
perform_bregman_l1.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/perform_bregman_l1.m
| 30,356 |
utf_8
|
9b24d52e8a09ba53a227bc8fbc8a08d8
|
function Out = perform_bregman_l1(n,A,b,mu,M,opts,varargin)
% Solve the problem
% min ||x||_1, subject to Ax = b
% by calling the solver FPC for solving multiple instances of
% min mu*||x||_1 + 0.5*||Ax-b^k||^2 .
% (FPC can be substituted by other solvers for the same subproblem)
%
% Technical Report:
% W. Yin, S. Osher, D. Goldfarb, and J. Darbon.
% Bregman Iterative Algorithms for l1-Minimization with Applications to Compressed Sensing.
% Rice CAAM TR07-13 or UCLA CAM 07-37
%
% INPUT ARGUMENTS:
% n, A, b, mu: as shown above
% M: see fpc solver
% if M=[], use 2-norm for A*x-b;
% if M is not empty, use M-norm for A*x-b
% (If you don't want how to use M, just let M=[])
% opts:
% a structure of options, see l1_Bregman_opts.m
% varargin:
% placeholder for additional parameters that are passed to FPC
% (If you don't want how to use varargin, just ignore it)
%
% Basic Output:
% Out.x the last iterate x^k
% Out.dual an approx. dual solution, i.e., a solution for
% max_y <b,y>, subject to norm(A'y,'inf') <= 1
% Out.Bregman_itr number of total Bregman iterations
% =inf if the max # of iterations is reached before convergence
% Out.Out_fpc the output of last call to FPC (see fpc.m or fpc_bb.m)
%
% Copyright 2007. Wotao Yin, CAAM, Rice University
%
%% define constants
inv_norm_b = 1/norm(b);
if (any(opts.disp & [1 0 0 0 0]) || any(opts.record & [0 1 0 0 0 0])) && ~isempty(opts.fpc_opts.xs);
inv_norm_xs = 1/norm(opts.fpc_opts.xs);
nz_tol=norm(opts.fpc_opts.xs,inf)*opts.rel_nz_eps;
nz_xs=abs(opts.fpc_opts.xs)>nz_tol;
end
if strcmp(opts.fpc,'std'); fpc_solver = @fpc;
elseif strcmp(opts.fpc,'bb'); fpc_solver = @fpc_bb;
else error('no fpc solver'); end
if (opts.inv_mu); mu = 1/mu; end;
if (opts.use_rel_tol); tol = opts.rel_res_tol*norm(b); else tol = opts.abs_res_tol; end
if (opts.var_fpc_gtol); opts.fpc_opts.gtol = opts.var_fpc_gtol_max; end
% data recording initialization
if any(opts.record)
if any(opts.record & [0 0 0 0 0 1]); Out.fpc_itrs = zeros(opts.itr_max,1); Out.fpc_time = zeros(opts.itr_max,1); end
if any(opts.record & [0 0 0 0 1 0]); Out.fpc_res = zeros(opts.itr_max,1); Out.fpc_res_abs = zeros(opts.itr_max,1); end
if any(opts.record & [0 0 0 1 0 0]); Out.fpc_gap = zeros(opts.itr_max,1); Out.fpc_res_err1 = zeros(opts.itr_max,1); Out.fpc_res_err2 = zeros(opts.itr_max,1); end
if any(opts.record & [0 0 1 0 0 0]); Out.fpc_gtol = zeros(opts.itr_max,1); end
if any(opts.record & [0 1 0 0 0 0]); Out.fpc_err = zeros(opts.itr_max,1); Out.fpc_err_abs = zeros(opts.itr_max,1); end
if any(opts.record & [1 0 0 0 0 0]); Out.fpc_xk = []; Out.fpc_bk = []; end
end
% data dimension
m = length(b);
% implicit or explicit A
imp_A = isa(A,'function_handle');
if ~imp_A && isempty(M) && opts.check_eigmax
eigs_opts.tol = 1E-4; eigs_opts.disp = 0; eigs_opts.issym = true;
fprintf(1, 'checking the eigenvalue of AA''==1...');
if abs(eigs(A*A',1,'lm',eigs_opts)-1)>1e-4; error('AA'' does not have eigenvalue 1, not satisfying the requirement by the subproblem solver FPC.'); end
fprintf(1, 'OK!\n\n');
end
% main Bregman iterations
redo = false;
bk = b;
for k=1:opts.itr_max
% solve the subproblem by calling fpc
fpc_t = cputime;
Out_fpc = fpc_solver(n,A,bk,mu,M,opts.fpc_opts,varargin{:});
fpc_t = cputime - fpc_t;
% data process
if (imp_A); Axk = A(false,m,n,Out_fpc.x,[],varargin{:}); else Axk = A*Out_fpc.x; end
b_Axk = b - Axk; bk_Axk = bk - Axk;
res_norm = norm(b_Axk,2);
xk_norm_1 = norm(Out_fpc.x,1);
xk_norm_inf = norm(Out_fpc.x,inf);
gap = abs((b'*bk_Axk)*mu - xk_norm_1);
err1 = (b_Axk'*bk_Axk)*mu;
err2 = (bk_Axk'*Axk)*mu - xk_norm_1;
if (any(opts.disp & [1 0 0 0 0]) || any(opts.record & [0 1 0 0 0 0]))...
&& ~isempty(opts.fpc_opts.xs); err=norm(opts.fpc_opts.xs-Out_fpc.x); end
% display
if any(opts.disp)
fprintf(1,'Itr %d:',k);
if any(opts.disp & [0 0 0 0 1]); fprintf(1,' itr=%3d time=%.2fs',Out_fpc.itr,fpc_t); end
if any(opts.disp & [0 0 0 1 0]); fprintf(1,' l1=%.2e res=%.2e (%.3e)',norm(Out_fpc.x,1),res_norm,res_norm*inv_norm_b); end
if any(opts.disp & [0 0 1 0 0]); fprintf(1,' gap=%.2e e1=%+.2e e2=%+.2e',gap,err1,err2); end
if any(opts.disp & [0 1 0 0 0]); fprintf(1,' gtol=%.2e',opts.fpc_opts.gtol); end
if any(opts.disp & [1 0 0 0 0]) && exist('err','var')
nz_xk = abs(Out_fpc.x)>nz_tol;
fprintf(1,' err=%.2e (rel=%.2e) miss=%d over=%d',err,err*inv_norm_xs,nnz(nz_xs & (~nz_xk)),nnz(nz_xk & (~nz_xs)));
end
fprintf(1,'.\n\n');
end
% data recording
if any(opts.record)
if any(opts.record & [0 0 0 0 0 1]); Out.fpc_itrs(k) = Out_fpc.itr; Out.fpc_time(k) = fpc_t; end
if any(opts.record & [0 0 0 0 1 0]); Out.fpc_res(k) = res_norm; Out.fpc_res_abs(k) = res_norm*inv_norm_b; end
if any(opts.record & [0 0 0 1 0 0]); Out.fpc_gap(k) = gap; Out.fpc_res_err1(k) = err1; Out.fpc_res_err2(k) = err2; end
if any(opts.record & [0 0 1 0 0 0]); Out.fpc_gtol(k) = opts.fpc_opts.gtol; end
if any(opts.record & [0 1 0 0 0 0]) && exist('err','var'); Out.fpc_err(k) = err; Out.fpc_err_abs(k) = err*inv_norm_xs; end
if any(opts.record & [1 0 0 0 0 0]); Out.fpc_xk = [Out.fpc_xk Out_fpc.x]; Out.fpc_bk = [Out.fpc_bk bk]; end
end
% convergence test
if (res_norm<tol); break; end
% failure test
if (Out_fpc.itr == inf); disp('FPC fail to converge; please use larger mu or allow more FPC iterations.'); break; end
if (Out_fpc.itr == 0); disp('mu is too large; FPC returns the solution 0; please reduce mu.'); break; end
% data update
if abs(err2) <= abs(err1)*5;
% proceed to next iteration
redo = false;
bk = b + bk_Axk;
if (opts.use_last); opts.fpc_opts.x0 = Out_fpc.x; end
if (opts.var_fpc_gtol);
opts.fpc_opts.gtol = max(min( abs(err1/mu)/(nnz(Out_fpc.x)*xk_norm_inf), opts.var_fpc_gtol_max),opts.var_fpc_gtol_min);
end
else
% need to redo last step
if redo; disp('Fail to decrease error. Exiting...'); break; end
redo = true; disp('Rerun last step with smaller gtol.');
opts.fpc_opts.gtol = opts.fpc_opts.gtol*abs(err1/err2);
if Out_fpc.itr == inf; opts.fpc_opts.mxitr = min(round(opts.fpc_opts.mxitr*abs(err2/err1)),opts.fpc_max_mxitr); end
end
end
% save output
if (res_norm<tol); Out.Bregman_itr = k; else Out.Bregman_itr = inf; end
Out.dual = bk_Axk*mu;
Out.Out_fpc = Out_fpc;
Out.x = Out_fpc.x;
end
% Options for l1 Bregman iterations
% opts:
% opts.fpc % fpc solver selection: 'std', 'bb'
% opts.fpc_opts % options passed to fpc
% opts.check_eigmax % checking max eigenvale of AA' == 1 or nor (to satisfy FPC's requirement)
% opts.fpc_max_mxitr % the ceiling of mxitr for fpc
% opts.itr_max % maximum Bregman iterations. Default: 50
% opts.use_rel_tol % true: use opts.rel_res_tol; false; use abs_res_tol. Default: true
% opts.rel_res_tol % tolerance of relative residual in 2-norm, ||Au-f||/||f||
% opts.abs_res_tol % tolerance of absolute residual in 2-norm, ||Au-f||
% opts.inv_mu % need to invert mu for the subproblem solver
% opts.var_fpc_gtol % varying gtol. Default: true
% opts.var_fpc_gtol_max % max gtol if var_fpc_gtol == true. Default: 1e-2
% opts.var_fpc_gtol_min % min gtol if var_fpc_gtol == true. Default: 1e-10
% opts.use_last % use last solution as next starting point, suggest: false (not improvement observed with "true")
% opts.rel_nz_eps % used to determine zeros in x^k relative to norm(x^k,inf). Default: 1e-3;
% opts.disp % display options (see below). Default: no display
% opts.record % data recording options (see below). Default: bin 000001
%
%
% Display options:
% bit 0 right - basic information: fpc_itr, fpc_time
% bit 1 - norm(x,1) and residual info: norm(A*x^k-b), norm(A*x^k-b)/norm(b)
% bit 2 - accuracy info: gap abs(||x^k||_1 - <b^k-A*x^k,b>/mu), err1 <b^k-A*x^k,b-A*x^k>/mu, err2 <b^k-A*x^k,A*x^k>/mu - ||x^k||_1
% bit 3 - gtol
% bit 4 - error. if opts.fpc.xs exists, norm(xs-x^k), norm(xs-x^k)/norm(xs), missed nz, over nz
% Data recording options:
% bit 0 right - basic information: fpc_itr, fpc_time
% bit 1 - residual info
% bit 2 - accuracy info
% bit 3 - gtol
% bit 4 - error
% bit 5 - A, b, x^k, b^k
%
% Copyright 2007. Wotao Yin, CAAM, Rice University
function opts = l1_Bregman_opts(opts)
%% default values
fpc_default = 'bb';
fpc_max_mxitr_default = 1e4;
itr_max_default = 50;
check_eigmax_default = true;
use_rel_tol_default = true;
rel_res_tol_default = 1e-5;
abs_res_tol_default = 1e-5;
inv_mu_default = true;
var_fpc_gtol_default = true;
var_fpc_gtol_max_default = 1e-2;
var_fpc_gtol_min_default = 1e-10;
fix_fpc_gtol_default = 1e-5;
use_last_default = false;
rel_nz_eps_default = 1e-3;
disp_default = [0 0 0 0 0];
record_default = [0 0 0 0 0 1];
err_msg=[];
%% option assignment
if ~exist('opts','var'); opts = []; end
if ~isfield(opts,'fpc'); opts.fpc = fpc_default; end
if ~isfield(opts,'fpc_opts') && strcmp(opts.fpc,'std'); opts.fpc_opts = fpc_opts([]); end
if ~isfield(opts,'fpc_opts') && strcmp(opts.fpc,'bb'); opts.fpc_opts = fpc_bb_opts([]); end
if ~isfield(opts,'check_eigmax'); opts.check_eigmax = check_eigmax_default; end
if ~isfield(opts,'fpc_max_mxitr'); opts.fpc_max_mxitr = fpc_max_mxitr_default; end
if ~isfield(opts,'itr_max'); opts.itr_max = itr_max_default; end
if ~isfield(opts,'opts.use_rel_tol'); opts.use_rel_tol = use_rel_tol_default; end
if opts.use_rel_tol == true && ~isfield(opts,'rel_res_tol'); opts.rel_res_tol=rel_res_tol_default; end
if opts.use_rel_tol == false && ~isfield(opts,'abs_res_tol'); opts.abs_res_tol=abs_res_tol_default; end
if ~isfield(opts,'inv_mu'); opts.inv_mu = inv_mu_default; end
if ~isfield(opts,'var_fpc_gtol'); opts.var_fpc_gtol = var_fpc_gtol_default; end
if (opts.var_fpc_gtol == true && ~isfield(opts,'var_fpc_gtol_max')); opts.var_fpc_gtol_max=var_fpc_gtol_max_default; end
if (opts.var_fpc_gtol == true && ~isfield(opts,'var_fpc_gtol_min')); opts.var_fpc_gtol_min=var_fpc_gtol_min_default; end
if opts.var_fpc_gtol == false
if ~isfield(opts,'fix_fpc_gtol'); opts.fpc_opts.gtol = fix_fpc_gtol_default;
else opts.fpc_opts.gtol = opts.fix_fpc_gtol; end
end
if ~isfield(opts,'use_last'); opts.use_last = use_last_default; end
if ~isfield(opts,'rel_nz_eps'); opts.rel_nz_eps = rel_nz_eps_default; end
if ~isfield(opts,'disp'); opts.disp = disp_default; end
if ~isfield(opts,'record'); opts.record = record_default; end
% if ~isempty(err_msg)
% disp([err_msg(3:end) '.']);
% error('Error in opts.');
% end
% Options for Fixed Point Continuation (FPC)
%
%--------------------------------------------------------------------------
% DESCRIPTION
%--------------------------------------------------------------------------
%
% opts = fpc_opts(opts)
%
% If opts is empty upon input, opts will be returned containing the default
% options for fpc.m.
%
% Alternatively, if opts is passed with some fields already defined, those
% fields will be checked for errors, and the remaining fields will be added
% and initialized to their default values.
%
% Table of Options. ** indicates default value.
%
% FIELD OPTIONAL DESCRIPTION
% .x0 YES Initial value of x. If not defined, x will be
% initialized according to .init.
% .xs YES Original signal xs. If passed, fpc will calculate and
% output ||x - xs||/||xs|| in vector Out.n2re.
% .init YES If .x0 is not defined, .init specifies how x is to be
% initialized.
% 0 -> zeros(n,1)
% 1 -> x = tau*||AtMb||_Inf * ones(n,1)
% ** 2 -> x = tau*AtMb **
% .tau YES 0 < .tau < 2. If not specified, tau is initialized
% using a piecewise linear function of delta = m/n.
% .mxitr NO Maximum number of inner iterations.
% ** 1000 **
% .eta NO Ratio of current ||b - Ax|| to approx. optimal
% ||b - Ax|| for next mu value.
% ** 4 **
% .fullMu NO If true, then mu = eta*sqrt(n*kap)/phi, where phi =
% ||Ax - b||_M, which guarantees that phi(now)/phi(next)
% >= eta. Otherwise mu = eta*mu.
% ** false **
% .kappa YES Required if fullMu. Is ratio of max and min
% eigenvalues of M^{1/2}AA'M^{1/2} (before scaling).
% ** not supplied **
% .xtol NO Tolerance on norm(x - xp)/norm(xp).
% ** 1E-4 **
% .gtol NO Tolerance on mu*norm(g,'inf') - 1
% ** 0.2 **
%--------------------------------------------------------------------------
function opts = fpc_opts(opts)
if isfield(opts,'x0')
if ~isvector(opts.x0) || ~min(isfinite(opts.x0))
error('If used, opts.x0 should be an n x 1 vector of finite numbers.');
end
elseif isfield(opts,'init')
if (opts.init < 0) || (opts.init > 2) || opts.init ~= floor(opts.init)
error('opts.init must be an integer between 0 and 2, inclusive.');
end
else
opts.init = 2;
end
if isfield(opts,'xs')
if ~isvector(opts.xs) || ~min(isfinite(opts.xs))
error('If passed, opts.xs should be an n x 1 vector of finite numbers.');
end
end
if isfield(opts,'tau')
if (opts.tau <= 0) || (opts.tau >= 2)
error('If used, opts.tau must be in (0,2).');
end
end
if isfield(opts,'mxitr')
if opts.mxitr < 1 || opts.mxitr ~= floor(opts.mxitr)
error('opts.mxitr should be a positive integer.');
end
else
opts.mxitr = 1000;
end
if isfield(opts,'xtol')
if (opts.xtol < 0) || (opts.xtol > 1)
error('opts.xtol is tolerance on norm(x - xp)/norm(xp). Should be in (0,1).');
end
else
opts.xtol = 1E-4;
end
if isfield(opts,'gtol')
if (opts.gtol < 0) || (opts.gtol > 1)
error('opts.gtol is tolerance on mu*norm(g,''inf'') - 1. Should be in (0,1).');
end
else
opts.gtol = 0.2;
end
if isfield(opts,'eta')
if opts.eta <= 1
error('opts.eta must be greater than one.');
end
else
opts.eta = 4;
end
if isfield(opts,'fullMu')
if ~islogical(opts.fullMu)
error('fullMu should be true or false.');
end
else
opts.fullMu = false;
end
if isfield(opts,'kappa')
if opts.kappa < 1
error('opts.kappa is a condition number and so should be >= 1.');
end
end
return
% Copyright (c) 2007. Elaine Hale, Wotao Yin, and Yin Zhang
%
% Last modified 28 August 2007.
% Fixed Point Continuation (FPC) for l1 Regularized Least Squares
%
%--------------------------------------------------------------------------
% GENERAL DESCRIPTION & INPUTS
%--------------------------------------------------------------------------
%
% Out = fpc(n,A,b,mu,M,opts,varargin)
%
% Solves
%
% min ||x||_1 + (mu/2)*||Ax - b||_M^2.
%
% A may be an explicit m x n matrix, or a function handle that implements
% A*x and A'*x. If the latter, this function must have the form
%
% function y = name(trans,m,n,x,inds,varargin)
%
% where
%
% trans - if false then y = A(:,inds)*x, if true then y = A(:,inds)'*x
% m, n - A is m x n
% x - length(inds) x 1 vector if ~trans; m x 1 vector if trans
% inds - vector of indices; if empty the function should return A*x
% or A'*x, as appropriate
% varargin - placeholder for additional parameters
%
% b must be an m x 1 vector.
%
% M can be any m x m positive definite matrix, or the empty matrix. If M
% is empty, fpc assumes M = I, which reduces the second term of the
% objective to (mu/2)*||Ax - b||_2^2 (standard least squares).
%
% This function assumes that the maximum eigenvalue of A^T M A is less
% than or equal to 1. If your initial problem does not satisfy this
% condition, an equivalent problem may be constructed by setting:
% sigma^2 = max eigenvalue of A^T M A
% mu = mu*sigma^2
% A = A/sigma
% b = b/sigma
% Also see getM_mu.m.
%
% fpc_opts.m describes the available options. If opts is passed as empty,
% fpc_opts will be called to obtain the default values.
%
% All variables in varargin are passed to A if A is a function handle.
%
%--------------------------------------------------------------------------
% OUTPUTS
%--------------------------------------------------------------------------
%
% Out.x - x at last iteration
% Out.f - vector of function values
% Out.lam - vector of ||x||_1
% Out.step - vector of norm(x - xp)
% Out.mus - vector of mu values for each outer iteration
% Out.itr - number of iterations to convergence (or Inf if reach mxitr)
% Out.itrs - vector of number of inner iterations completed during each
% outer iteration
% Out.tau - value of tau
% Out.n2re - if opts.xs exists, is vector of norm(x - xs)/norm(xs).
% starts with 0th iteration.
%--------------------------------------------------------------------------
function Out = fpc(n,A,b,mu,M,opts,varargin)
% problem dimension
m = length(b);
% implicit or explicit A
imp = isa(A,'function_handle');
% calculate AtMb
if imp
if isempty(M), AtMb = A(true,m,n,b,[],varargin{:});
else AtMb = A(true,m,n,M*b,[],varargin{:}); end
else
if isempty(M), AtMb = A'*b;
else AtMb = A'*(M*b); end
end
% check for 0 solution
if mu <= 1/norm(AtMb,'inf');
Out.x = zeros(n,1); Out.itr = 0; Out.itrs = 0;
Out.tau = 0; Out.mus = mu; Out.lam = 0; Out.step = [];
if isempty(M), Out.f = (mu/2)*(b'*b);
else Out.f = (mu/2)*(b'*(M*b)); end
if isfield(opts,'xs'), Out.n2re = 1; end
return
end
% get opts
if isempty(opts), opts = fpc_opts([]); end
% initialize x, nu, tau, mu
muf = mu; % final value of mu
[x,nu,tau,mu] = fpc_init(n,m,b,AtMb,M,opts);
if mu > muf, mu = muf; nu = tau/mu; end
Out.mus = mu; Out.tau = tau;
% initialize Out.n2re
if isfield(opts,'xs'), xs = opts.xs; else xs = []; end
if ~isempty(xs), Out.n2re = norm(x - xs)/norm(xs); end
xtol = opts.xtol;
gtol = opts.gtol;
% prepare for iterations
Out.step = []; Out.itrs = []; Out.f = []; Out.lam = [];
Out.itr = Inf; oitr = 0; Ax = [];
% main loop
for i = 1:opts.mxitr
% store old point
xp = x;
% get gradient at x and store objective function
[g,f,lam] = get_g(x,imp,m,n,mu,A,b,M,AtMb,varargin{:});
Out.f = [Out.f; f]; Out.lam = [Out.lam; lam];
% take fixed-point step
y = x - tau*g;
x = sign(y).*max(0,abs(y)-nu);
nrmxxp = norm(x - xp);
Out.step = [Out.step; nrmxxp];
if ~isempty(xs), Out.n2re = [Out.n2re; norm(x - xs)/norm(xs)]; end
crit1 = nrmxxp/max(norm(xp),1);
crit2 = mu*norm(g,'inf') - 1;
if (crit1 < xtol*sqrt(muf/mu)) && (crit2 < gtol)
oitr = oitr + 1;
if isempty(Out.itrs), Out.itrs = i;
else Out.itrs = [Out.itrs; i - sum(Out.itrs)]; end
% stop if reached muf
if mu == muf
Out.x = x; Out.itr = i;
[g,f,lam] = get_g(x,imp,m,n,mu,A,b,M,AtMb,varargin{:});
Out.f = [Out.f; f]; Out.lam = [Out.lam; lam];
return
end
% update mu
if opts.fullMu
phi = sqrt((2/mu)*(f - lam));
mu = getNextMu(n,phi,opts.eta,opts.kappa);
else
mu = opts.eta*mu;
end
mu = min(mu,muf); nu = tau/mu;
Out.mus = [Out.mus; mu];
end
end
% did not converge within opts.mxitr
Out.x = x;
if isempty(Out.itrs), Out.itrs = i;
else Out.itrs = [Out.itrs; i - sum(Out.itrs)]; end
end % fpc
%--------------------------------------------------------------------------
% SUBFUNCTION FOR INITIALIZATION
%--------------------------------------------------------------------------
%
% OUTPUTS -----------------------------------------------------------------
% x - initialized based on opts.x0 and opts.init. if opts.x0 exists,
% x = opts.x0, otherwise, opts.init determines x:
% 0 - x = zeros(n,1)
% 1 - x = tau*||AtMb||_Inf * ones(n,1)
% 2 - x = tau*AtMb
% nu - equals tau/mu
% tau - equals opts.tau if exists, otherwise min(1.999,-1.665*m/n+2.665)
% mu - set based on x = 0, mu = 1/norm(AtMb,inf), and getNextMu
%--------------------------------------------------------------------------
function [x,nu,tau,mu] = fpc_init(n,m,b,AtMb,M,opts)
% initialize tau
if isfield(opts,'tau'), tau = opts.tau;
else tau = min(1.999,-1.665*m/n + 2.665); end
% initialize x
if isfield(opts,'x0')
x = opts.x0;
if length(x) ~= n, error('User supplied x0 is wrong size.'); end
else
switch opts.init
case 0, x = zeros(n,1);
case 1, x = tau*norm(AtMb,inf)*ones(n,1);
case 2, x = tau*AtMb;
end
end
% initialize mu
if opts.fullMu && isfield(opts,'kappa')
if isempty(M), phi = norm(b); % phi = ||Ax - b||_M
else phi = sqrt(b'*(M*b)); end
mu = getNextMu(n,phi,opts.eta,opts.kappa);
else
if opts.fullMu
warning('opts.fullMu = true, but opts.kappa is not supplied. Switching to opts.fullMu = false.');
opts.fullMu = false;
end
mu = opts.eta/norm(AtMb,inf);
end
% initialize nu
nu = tau/mu;
end % fpc_init
%--------------------------------------------------------------------------
% SUBFUNCTION FOR CALCULATING NEXT mu
%--------------------------------------------------------------------------
%
% Calculates the next value of mu based on taking a predictor step along
% the pareto curve phi(lam). The derivative of this curve is derived in
%
% van den Berg, E. and M. Friedlander. In pursuit of a root. Preprint,
% 2007.
%
% The steplength is chosen so that phi(current)/phi(next) \approx eta.
% Mu is chosen so that the true phi(next) is guaranteed to be <= the
% predicted value.
%
% INPUTS ------------------------------------------------------------------
% n - length of x
% phi - ||Ax - b||_M
% g - A'M(Ax - b)
% eta - parameter for choosing how much phi should decrease during next
% outer iteration. getNextMu is approximately the same as choosing
% mu = eta*mu.
% kap - condition number of A'MA. See getM_mu.
%--------------------------------------------------------------------------
function mu = getNextMu(n,phi,eta,kap)
mu = eta*sqrt(n*kap)/phi;
end % getNextMu
%--------------------------------------------------------------------------
% SUBFUNCTION FOR CALCULATING g
%--------------------------------------------------------------------------
function [g,f,lam] = get_g(x,imp,m,n,mu,A,b,M,AtMb,varargin)
% get A*x
if imp
Ax = A(false,m,n,x,[],varargin{:});
else
Ax = A*x;
end
% calc g
if imp
if isempty(M)
g = A(true,m,n,Ax,[],varargin{:})-AtMb;
else
g = A(true,m,n,M*Ax,[],varargin{:})-AtMb;
end
elseif isempty(M)
g = A'*Ax - AtMb;
else
g = A'*(M*Ax) - AtMb;
end
% calc f
r = Ax - b; lam = sum(abs(x));
if isempty(M)
f = 0.5*mu*norm(r)^2 + lam;
else
f = 0.5*mu*r'*(M*r) + lam;
end
end % get_g
% Copyright (c) 2007. Elaine Hale, Wotao Yin, and Yin Zhang
%
% Last modified 28 August 2007.
% RECOMMENDED M AND mu FOR l1-REGULARIZED WEIGHTED LEAST SQUARES
%
%--------------------------------------------------------------------------
% DESCRIPTION AND INPUTS
%--------------------------------------------------------------------------
%
% [M,mu,A,b,sig,kap,tau,M12] = getM_mu(full,mu,m,n,Ameth,A,b,sig1,sig2,alpha)
%
% Constructs M and mu as described in Hale, Yin and Zhang 2007, based
% on the noise estimates sig1 and sig2, and the statistical parameter
% alpha.
%
% full - only relevant if sig1 > 0 and AA' is not a multiple of I. In
% this case, and if full == true, then the full estimate for M,
% M = (sig1^2 AA' + sig2^2 I)^{-1} is calculated. Otherwise M is
% estimated to be (sig1^2 lam_max(AA') + sig2^2)^{-1} I. The
% constant is then moved to mu so that M is returned as [].
%
% mu - if empty, then recommended mu value is calculated.
%
% m,n - A is an m x n matrix.
%
% Ameth - indicates what type of A matrix is being passed. values >= 0
% correspond to indices from getData.m.
% -1 - generic A matrix
% 0 - randn(m,n) (uses analytic bound on min and max
% eigenvalues of AA')
% 1 - 0 and then columns are scaled to unit norm
% 2 - 0 and then QR factorization to obtain orthonormal rows
% (AA' = I)
% 3 - bernoulli +/- 1 distribution
% 4 - partial Hadamard matrix (AA' = nI)
% 5 - partial fourier matrix (implicit,AA'=nI,ifft = A'/n)
% 6 - partial discrete cosine matrix (implicit,AA'=I)
% 7 - partial 2-d fourier matrix (as 5,but AA'=n^2*I)
% 8 - partial 2-d discrete cosine matrix (as 6)
% Codes -1, 1, and 3 are equivalent; 2, 6 and 8 are equivalent; 4
% and 5 are equivalent.
%
% A,b - problem data. Only accessed if Ameth <= 4 (A is explicit).
%
% sig1, sig2 - noise level estimates. In particular we assume that
% b = A*(xs + epsilon1) + epsilon2, where epsiloni is iid Gaussian
% noise with standard deviation sigi.
%
% alpha - mu estimate uses 1-alpha chi^2 critial value. mu is not very
% sensitive to alpha and alternative is provided in case the
% statistics toolbox is not available. Results in Hale, Yin and
% Zhang 2007 used alpha = 0.5.
%
%--------------------------------------------------------------------------
% OUTPUTS
%--------------------------------------------------------------------------
%
% M - recommended value of M. Returned as [] if M = I.
%
% mu - if input mu is the empty matrix, output mu is the recommended
% value. otherwise, mu is untouched.
%
% A,b - problem data. Untouched if AA' = I or A is implicit. Otherwise,
% A and b are scaled so that the maximum eigenvalue of A'*M*A = 1.
%
% sig - approximate noise level (standard deviation) of least squares
% solution. equal to sqrt(sig1^2 + sig2^2/(min eig of AA')).
%
% kap - condition number of M12*AA'*M12.
%
% tau - if AtMA is not well conditioned, tau is returned as 2-eps.
% otherwise, tau is returned empty to signal that fpc default
% should be used.
%
% M12 - equal to M^(1/2) if ~isempty(M).
%--------------------------------------------------------------------------
function [M,mu,A,b,sig,kap,tau,M12] = getM_mu(full,mu,m,n,Ameth,A,b,sig1,sig2,alpha)
tau = []; M12 = [];
% options for eigs
opts.tol = 1E-4;
opts.disp = 0;
opts.issym = true;
% calculate M, mu, sig, kap, tau, M12
if full && sig1 > 0 && ismember(Ameth,[-1 0 1 3])
% most general case--must calculate full M matrix
AAt = A*A';
M = sig1^2*AAt; M(1:m+1:m^2) = M(1:m+1:m^2) + sig2^2;
% invert to get M
lsopts.SYM = true; lsopts.POSDEF = true;
M = linsolve(M,eye(m),lsopts);
% need matrix square root
M12 = sqrtm(M);
M12AAtM12 = M12*AAt*M12;
% get eigenvalues
smax = sqrt(eigs(M12AAtM12,1,'lm',opts));
smin = sqrt(eigs(M12AAtM12,1,0,opts));
if Ameth == 0
sig = sqrt(sig1^2 + sig2^2/max((1 - sqrt(m/n))^2*n,eps^2));
else
sig = sqrt(sig1^2 + sig2^2/max(eigs(AAt,1,0,opts),eps^2));
end
kap = smax^2/smin^2;
% no tau because full M means well-conditioned AtMA
if isempty(mu)
if strcmp(which('chi2inv'),'');
% avoids chi2inv, is good approximation for large n
mu = smax*sqrt(n*kap/m);
else
mu = smax*sqrt(n*kap/chi2inv(1-alpha,m));
end
end
else
% M is a multiple of I
M = [];
switch Ameth
case {-1,1,3}
% unknown eigenvalues
AAt = A*A';
smax = sqrt(eigs(AAt,1,'lm',opts));
smin = sqrt(eigs(AAt,1,0,opts));
muSig = sqrt(sig1^2*smax^2 + sig2^2);
sig = sqrt(sig1^2 + sig2^2/smin^2);
kap = smax^2/smin^2;
tau = 2-eps;
case 0
% have tight bounds
delta = m/n;
smax = (1 + sqrt(delta))*sqrt(n);
smin = max((1 - sqrt(delta))*sqrt(n),eps);
muSig = sqrt(sig1^2*smax^2 + sig2^2);
sig = sqrt(sig1^2 + sig2^2/smin^2);
kap = smax^2/smin^2;
tau = 2-eps;
case {2,6,8}
% AAt = I
smin = 1; smax = 1;
sig = sqrt(sig1^2 + sig2^2);
muSig = sig;
kap = 1;
case {4,5}
% AAt = nI
smin = sqrt(n); smax = sqrt(n);
muSig = sqrt(sig1^2*n + sig2^2);
sig = sqrt(sig1^2 + sig2^2/n);
kap = 1;
% if Ameth = 5, b was already scaled by getData since A scaling
% is implemented in pfft_wrap_part
case 7
smin = n; smax = n;
muSig = sqrt(sig1^2*n^2 + sig2^2);
sig = sqrt(sig1^2 + sig2^2/n^2);
kap = 1;
% b was already scaled by getData since A scaling is
% implemented in pfft2_wrap_part
end
% calculate recommended mu if required
if isempty(mu)
if strcmp(which('chi2inv'),'');
% avoids chi2inv, is good approximation for large n
mu = (smax/muSig)*sqrt(n*kap/m);
else
mu = (smax/muSig)*sqrt(n*kap/chi2inv(1-alpha,m));
end
end
end
% scale A and b if required
if ismember(Ameth,[-1,0,1,3,4])
A = (1/smax)*A; b = (1/smax)*b;
end
return
% Copyright (c) 2007. Elaine Hale, Wotao Yin, and Yin Zhang
%
% Last modified 28 August 2007.
|
github
|
jacksky64/imageProcessing-master
|
callback_fft.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/callback_fft.m
| 1,815 |
utf_8
|
d2cbd486232bc3f7a4a6e537092d87a1
|
function y = callback_fft(x,dir,options)
% callback_fft - callback for sparsity with FFT
%
% y = callback_fft(x,dir,options);
%
% Works in 1D and 2D. Orthogonal transforms.
%
% Copyright (c) 2008 Gabriel Peyre
options.null = 0;
%% Detect dimension
if size(x,1)==1 || size(x,2)==1
ndims = 1;
else
ndims = 2;
end
ndims = getoptions(options, 'ndims', ndims);
isreal = getoptions(options, 'isreal', +1);
remove_high_freq = getoptions(options, 'remove_high_freq', 0);
%% Transform
if ndims==1
%% 1D
n = length(x);
if dir==1
y = ifft(x) * sqrt(n);
if isreal
y = real(y);
end
else
y = fft(x) / sqrt(n);
end
else
n = size(x,1); p = size(x,2);
%% 2D
if dir==1
if remove_high_freq>0
x = remove_freq(x,remove_high_freq,dir);
end
y = ifft2(x) * sqrt(n*p);
if isreal
y = real(y);
end
else
y = fft2(x) / sqrt(n*p);
if remove_high_freq>0
y = remove_freq(y,remove_high_freq,dir);
end
end
end
%%
function y = remove_freq(y,s,dir)
%y = fftshift(y);
% y(1:s,:) = 0; y(:,1:s) = 0;
% y(end-s+2:end,:) = 0; y(:,end-s+2:end) = 0;
% y = fftshift(y);
% remove only corners
y([end-s+2:end 1:s], end/2-s:end/2+s) = 0;
y(end/2-s:end/2+s, [end-s+2:end 1:s]) = 0;
y(end/2-s:end/2+s, end/2-s:end/2+s) = 0;
return;
global Qshuf;
global Ishuf;
if size(Qshuf)~=3*(2*s-1)^2
A = zeros(size(y));
n = size(y,1);
s1 = n/2-s+1:n/2+s-1;
s2 = [n-s+2:n 1:s];
A(s2, s1) = 1;
A(s1, s2) = 1;
A(s1,s1) = 1;
Ishuf = find(A==1);
rand('state', 123456);
[Qshuf,R] = qr(rand(length(Ishuf)));
end
if dir==1
y(Ishuf) = Qshuf*y(Ishuf);
else
y(Ishuf) = Qshuf'*y(Ishuf);
end
return;
|
github
|
jacksky64/imageProcessing-master
|
perform_analysis_regularization.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/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_dictionary_learning.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/perform_dictionary_learning.m
| 11,227 |
utf_8
|
7d719ce3e479bb813629d6651d16f2a3
|
function [D,X,E] = perform_dictionary_learning(Y,options)
% perform_dictionary_learning - learn a dictionnary using K-SVD algorithm
%
% [D,X,E] = perform_dictionary_learning(Y,options)
%
% Y is a matrix of size (n,m) containing m column examplar
% vector in R^n.
%
% D is a dictionnary matrix of size (n,K) of K vectors in R^n
% that should approximate well the vectors of Y
% with few components.
% K is given by options.K
%
% The algorihtm perform the folowing optimization jointly on D and X
% min_{D,X} |Y-D*X|^2 subject to |X_k|_0<=s
% subject to columns of D having unit norm.
% where s=options.nbr_max_atoms.
%
% It does this optimisation using block coordinate descent.
% * Optimization of X knowing D amount to sparse coding, solved using
% iterative thresholding:
% X <- Thresh_lambda( X + D'*( Y - D*X ) )
% This step is repeated options.niter_inversion times.
% * Optimization of D knowing X amount to L2 best fit:
% D <- Y*X^+ where X^+ = X'*(X*X')^{-1}
%
% This algorithm is very much inspired by the MOD algorithm
% for dictionary design.
%
% The number of iteration of the algorithm is given in
% options.niter_learning.
% The number of iteration for sparse coding during each step of learning
% is given by options.niter_inversion.
% The sparse coder used is set in options.sparse_coder to either 'omp' or
% 'mp' or 'itthresh'.
%
% options.learning_method can be set to:
% 'ksvd': in this case, the dictionary update is computed using the
% K-SVD algorithm explained in
% "K-SVD: An Algorithm for Designing Overcomplete Dictionaries
% for Sparse Representation"
% Michal Aharon Michael Elad Alfred Bruckstein, 2006
% 'mod': in this case, the dictionary update is computed using the L2
% best fit as proposed by
% "Method of optimal directions for frame design",
% K. Engan, S. O. Aase, and J. H. Hus?y,
% in Proc. ICASSP, Phoenix, AZ, Mar. 1999, pp. 2443?2446.
% 'randomized': apply randomly one or the other algorithm.
% 'modortho' same as mod, but the dictionary is constrained to be
% orthogonal. In this case, the dictionary must be square. The
% idea is taken from
% "Learning Unions of Orthonormal Bases with Thresholded Singular Value Decomposition"
% S Lesage, R Gribonval, F Bimbot, and L Benaroya
% in Proc. ICASSP'05, vol. V, p. 293--296
% 'grad': same as MOD but with a pojected gradient descent.
%
% If you work with missing data, then you need to provide
% mask=options.mask which should a matrix of the same size as Y and
% mask(i,j)=0 whenever an entry Y(i,j) is missing (should be Y(i,j)=0)
% and mask(i,j)=1 for valid data.
%
% MOD is usualy faster but KSVD gives a better optimization of the energy.
% KSVD is very efficient when a very low sparsity is required (set options.nbr_max_atoms to a small constant).
%
% Copyright (c) 2007 Gabriel Peyre
[n,m] = size(Y);
options.null = 0;
niter = getoptions(options, 'niter_learning', 10);
K = getoptions(options, 'K', n);
niter_inversion = getoptions(options, 'niter_inversion', 4);
lambda = getoptions(options, 'lambda', mean( sqrt( sum( Y.^2, 1 ) ) ) / 50);
sparse_coder = getoptions(options, 'sparse_coder', 'omp');
mu = getoptions(options, 'mu', 1/K);
init_dico = getoptions(options, 'init_dico', 'input');
mu_dampling = getoptions(options, 'mu_dampling', 1);
lambda_min = getoptions(options, 'lambda_min', lambda);
lambda_max = getoptions(options, 'lambda_max', lambda_min*4);
mask = getoptions(options, 'mask', []);
use_bootstrapping = getoptions(options, 'use_bootstrapping', 0);
verb = getoptions(options, 'verb', 1);
learning_method = getoptions(options, 'learning_method', 'mod');
if not(isfield(options, 'nbr_max_atoms'))
warning('You should set the sparsity options.nbr_max_atoms.');
options.nbr_max_atoms = 4;
end
if niter>1
options.niter_learning = 1;
E = [];
for i=1:niter
options.lambda = lambda_max - (i-1)/(niter-1)*(lambda_max-lambda_min);
if verb
progressbar(i,niter);
end
[D,X] = perform_dictionary_learning(Y,options);
options.D = D;
options.X = X;
if strcmp(sparse_coder, 'strict') || strcmp(sparse_coder, 'omp') || strcmp(sparse_coder, 'mp')
if isempty(mask)
E(end+1) = norm( Y-D*X, 'fro');
else
E(end+1) = norm( (Y-D*X).*mask, 'fro');
end
else
E(end+1) = 1/2*norm( Y-D*X, 'fro')^2 + lambda_min * sum( abs(X(:)) );
end
end
% sort the basis vector according to energy
e = sum( X.^2, 2 );
[tmp,I] = sort(e); I = I(end:-1:1);
D = D(:,I); X = X(I,:);
return;
end
if isfield(options, 'D') && not(isempty(options.D))
D = options.D;
else
% intialize dictionary
switch init_dico
case 'input'
sel = randperm(m); sel = sel(1:K);
D = Y(:,sel);
case 'haar1d'
D = compute_haar_matrix(n,1);
case 'haar2d'
D = compute_haar_matrix([sqrt(n) sqrt(n)],1);
case 'rand'
D = randn(n,K);
end
if size(D,2)<K
D = [D; randn(n,K-size(D,2))];
elseif size(D,2)>K
D = D(:,1:K);
end
D = D - repmat( mean(D), n,1 );
D(:,1) = 1; % enforce low pass
D = D ./ repmat( sqrt(sum(D.^2,1)), n,1 );
end
if isfield(options, 'X') && not(isempty(options.X))
X = options.X;
else
X = zeros(size(D,2), size(Y,2));
end
% sparse inversion
if isempty(mask)
if not(strcmp(sparse_coder, 'omp')) && not(strcmp(sparse_coder, 'mp'))
% sparse code wiht iterative thresholdings
% compute condition number
if isfield(options, 'mu')
mu = options.mu;
else
[a,s,b] = svd(D);
mu = 1/max(diag(s))^2;
end
E = [];
for i=1:niter_inversion
X = X + mu * mu_dampling * D'*( Y - D*X );
if strcmp(sparse_coder, 'soft')
t = lambda*mu_dampling*mu;
elseif strcmp(sparse_coder, 'hard')
% for hard thresholding, the scaling is different
t = lambda*sqrt(mu_dampling*mu);
end
X = perform_thresholding( X, t, sparse_coder);
E(end+1) = 1/2*norm( Y-D*X, 'fro')^2 + lambda * sum( abs(X(:)) );
end
if E(end)>E(1)
warning('Iterative thresholding did not converge, you should lower options.mu_dampling.');
end
else
% sparse code with matching pursuit
if not(isfield(options, 'use_mex'))
options.use_mex = 0;
end
if strcmp(learning_method, 'modortho')
M = options.nbr_max_atoms; % number of coefficients to keep
p = size(Y,2); % number of signals
d = size(Y,1);
% use simple best k-term in ortho-basis
X = D'*Y; % coefficients
[tmp,I] = sort(abs(X));
I = I(end-M,:) + (0:p-1)*d;
T = repmat( abs(X(I)), [d 1] );
X = X.*(abs(X)>T);
else
options.verb = 0;
X = perform_omp(D, Y, options);
if issparse(X)
X = full(X);
end
end
end
else
if use_bootstrapping
% fill-in the missing values
Y0 = Y; Y = D*X;
Y(mask==1) = Y0(mask==1);
% sparse code
% options.learning_method = 'mod';
options.verb = 0;
X = full( perform_omp(D, Y, options) );
else
% sparse code with atom with missing information
for k=1:size(Y,2)
% progressbar(k,size(Y,2));
I = find(mask(:,k));
X(:,k) = full( perform_omp( D(I,:), Y(I,k), options) );
end
options.learning_method = 'grad';
end
end
if strcmp(learning_method, 'randomized')
randomized_ksvd_proportion = getoptions(options, 'randomized_ksvd_proportion', .3);
if rand<randomized_ksvd_proportion
learning_method = 'ksvd';
else
learning_method = 'mod';
end
end
if strcmp(learning_method, 'ksvd')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% KSVD algorithm
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
T = 1e-3;
% the first atoms is supposed to be constant
for k=2:K
% find the exemplar that are using dictionnary basis k
I = find( abs(X(k,:))>T );
if ~isempty(I)
% compute redisual
if 0
D0 = D; D0(:,k) = 0;
E0 = Y - D0*X;
% restrict to element actually using k
E0 = E0(:,I);
else
S = X(:,I);
S(k,:) = 0;
E = Y(:,I) - D*S;
end
% perform SVD
[U,S,V] = svd(E);
D(:,k) = U(:,1);
X(k,I) = S(1) * V(:,1)';
end
end
elseif strcmp(learning_method, 'mod')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MOD algorithm
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% dictionary fit
warning off;
% D = Y * X'*(X*X')^(-1);
D = Y * pinv(X);
warning on;
elseif strcmp(learning_method, 'grad')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Gradient descent of the MOD energy
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isempty(mask)
mask = Y*0+1;
end
if isfield(options, 'niter_grad')
niter_grad = options.niter_grad;
else
niter_grad = 30;
end
if isfield(options, 'lambda_grad')
lambda_grad = options.lambda_grad;
else
lambda_grad = .01;
end
% dictionary update by gradient descent
Res = (Y-D*X).*mask;
errg = [];
for it=1:niter_grad
D = D + lambda_grad*Res*X';
% normalize
D = normalize_dictionary(D);
% error
Res = (Y-D*X).*mask;
errg(end+1) = norm(Res,'fro');
end
if errg(end)>errg(1)
warning('Gradient descent did not converged');
end
elseif strcmp(learning_method, 'modortho')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Orthogonal MOD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if n~=K
error('For modortho learning, n=K is required.');
end
[U,S,V] = svd(Y*X');
D = U*V';
else
error('Unknown learning method');
end
D = normalize_dictionary(D);
E = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function D = normalize_dictionary(D)
n = size(D,1);
D = D - repmat( mean(D),[n 1] );
D(:,1) = 1; % enforce low pass
% Normalize
d = sqrt(sum(D.^2,1));
I = find(d<1e-9); d(I) = 1;
D(:,I) = randn(size(D,1),length(I));
d = sqrt(sum(D.^2,1));
D = D ./ repmat( d, n,1 );
|
github
|
jacksky64/imageProcessing-master
|
callback_sensing_rand.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/callback_sensing_rand.m
| 8,894 |
utf_8
|
903359765b01d21f154c6259c5c0c98d
|
function y = callback_sensing_rand(x, dir, options)
% callback_sensing_rand - perform random sensing
%
% y = callback_sensing_rand(x, dir, options);
%
% compute y=K*x (dir=1) or y=K^{*}*x (dir=-1) or y=K^{+}*x (pseudo inverse)
% where K is a random matrix.
%
% You need to set options.n and options.p the dimension
% of the (p,n) matrix K (P=#measurements)
%
% options.cs_type selects different kinds of matrix
% 'user' : you provide your own matrix
% 'fourier' : random sub-selection of frequencies
% 'fourier-scramb' : random sub-selection of frequencies of scrambled signal
% 'hadamard' : random sub-selection of hadamard projections
% 'fourier-scramb' : random sub-selection of hadamard projections of scrambled signal
% 'noiselets' : random sub-selection of noiselets projections
% 'noiselets-scramb' : random sub-selection of noiselets projections of scrambled signal
% 'sinus' : random sub-selection of discrete sinus transform projections
% 'sinus-scramb' : random sub-selection of discrete sinus transform projectionsof scrambled signal
%
% options.rand_matrix (for using your own matrix)
% or options.n (size of the signal) and options.p
% (number of measurements) for automatic generation.
%
% Copyright (c) 2008 Gabriel Peyre
options.null = 0;
cs_type = getoptions(options, 'cs_type', 'sinus');
cs_matrix = getoptions(options, 'cs_matrix', []);
csndims = getoptions(options, 'csndims', 1);
if csndims==2
options.csndims = 1;
if dir==1
y = callback_sensing_rand(x(:), dir, options);
else
y = callback_sensing_rand(x(:), dir, options);
y = reshape(y, sqrt(length(y))*[1 1]);
end
return;
end
if not(isempty(cs_matrix))
n = size(cs_matrix, 2);
p = size(cs_matrix, 1);
else
n = getoptions(options, 'n', 0, 1);
p = getoptions(options, 'p', 0, 1);
end
switch lower(cs_type)
case {'sinus' 'hadamard' 'fourier' 'sinus-scramb' 'hadamard-scramb' 'fourier-scramb' }
y = cs_operator(x, p,n, dir, cs_type);
case 'user'
if isempty(cs_matrix)
error('You must provide options.cs_matrix');
end
if dir==1
y = cs_matrix*x;
elseif dir==-1
y = cs_matrix'*x;
elseif dir==-2
cs_matrix_pinv = getoptions(options, 'cs_matrix_pinv', []);
if isempty(cs_matrix_pinv)
warning('You should provide options.cs_matrix_pinv');
cs_matrix_pinv = pinv(cs_matrix);
end
y = cs_matrix_pinv*x;
else
error('dir should be +1,-1 or -2');
end
otherwise
error('Unknown CS operator');
end
function y = cs_operator(x, m,n, dir, type)
% FastCSOperator: The operator form of a random sampling matrix for the
% compressed sensing problem.
% Specifically, it returns y = A(:,I)*x (mode = 1) or y = A(:,I)'*x (mode = 2),
% where A is an mxdim random sampling matrix defined as
% A = P*H*Q, where P,Q are random permutation matrices,
% H is a fast Hadamard/Fourier operator, and I is
% a subset of the columns of A, i.e. a subset of 1:dim of length n.
% Pstate - state of random generator for P matrix
% Qstate - state of random generator for Q matrix
Pstate = 4972169;
Qstate = 7256157;
do_scramb = 0;
if strcmp(type, 'sinus-scramb') || strcmp(type, 'hadamard-scramb') || strcmp(type, 'fourier-scramb')
do_scramb = 1;
end
ntest = size(x,2);
if (dir == +1) % analysis
% Apply matrix Q
rand('state', Qstate);
if do_scramb
x = x( randperm(n),: );
end
% Apply matrix H
switch type
case {'sinus' 'sinus-scramb'}
x = RST(x);
case {'hadamard' 'hadamard-scramb'}
x = FHT(x);
case {'fourier' 'fourier-scramb'}
x = fft(x)/sqrt(n);
otherwise
error('Unknown CS operator');
end
% Apply matrix P
rand('state', Pstate);
sel = randperm(n);
y = x(sel(1:m),:);
else % Adjoint operator
% Apply matrix P^T
rand('state', Pstate);
sel = randperm(n);
y = zeros(n,ntest);
y( sel(1:m),: ) = x;
% Apply matrix H^T
switch type
case {'sinus' 'sinus-scramb'}
y = Inv_RST(y);
case {'hadamard' 'hadamard'}
y = Inv_FHT(y);
case {'fourier' 'fourier-scramb'}
y = ifft(y)*sqrt(n);
otherwise
error('Unknown CS operator');
end
% Apply matrix Q^T
if do_scramb
rand('state', Qstate);
y(randperm(n),:) = y;
end
end
function S = RST(X)
% RST: Real Sinusoid Transform of an n-vector
% Usage:
% S = RST(X);
% Inputs:
% X input n-vector
% Outputs:
% S output vector which contains the transform coeffs.
%
% Description
% RST computes a 1-D real sinusoid transform of an n vector, n dyadic,
% by taking the fft of X and using conjugate symmetry to eliminate
% complex values.
% See Also
% Inv_RST, RST2
n = size(X,1);
S = fft_mid0(X) ./ sqrt(n);
n2 = n/2 + 1; % Center point
S(2:(n2-1),:) = sqrt(2) .* real(S(2:(n2-1),:));
S((n2+1):n,:) = -sqrt(2) .* imag(S((n2+1):n,:));
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function X = Inv_RST(S)
% Inv_RST: Inverse Real Sinusoid Transform of an n vector
% Usage:
% X = Inv_RST(S);
% Inputs:
% S n vector
% Outputs:
% X reconstructed vector.
%
% Description
% Inv_RST computes the inverse of RST by rearranging frequencies and
% taking the inverse 1-D fft.
% See Also
% RST
n = size(S,1);
n2 = n/2 + 1; % Center point
isqrt2 = 1./sqrt(2);
X = S;
% Top row
X(2:(n2-1),:) = isqrt2 .* (S(2:(n2-1),:) + i .* S(n:-1:(n2+1),:));
X(n:-1:(n2+1),:) = isqrt2 .* (S(2:(n2-1),:) - i .* S(n:-1:(n2+1),:));
X = real(ifft_mid0(X)) .* sqrt(n);
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y=fft_mid0(x)
% fftmid0 -- 1d fft with argument [-pi,pi] (instead of [0,2pi])
% Usage:
% Y = fft_mid0(X)
% Inputs:
% X Array(n)
% Outputs:
% Y Array(n)
% Description:
% Performs 1d fft with grid (-n/2):(n/2-1) on both time
% and frequency side.
% y(k) = sum_{t=-n/2}^{n/2-1} exp(i 2pi/n kt) x(t) , (-n/2) <= k < n/2
%
y = fftshift(fft(fftshift(x,1)),1);
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y=ifft_mid0(x)
% ifft_mid0 -- 1d fft with argument [-pi,pi] (instead of [0,2pi])
% Usage:
% Y = ifft_mid0(X)
% Inputs:
% X Array(n)
% Outputs:
% Y Array(n)
% Description:
% Performs 1d fft with grid (-n/2):(n/2-1) on both time
% and frequency side.
% y(k) = sum_{t=-n/2}^{n/2-1} exp(i 2pi/n kt) x(t) , (-n/2) <= k < n/2
%
y = fftshift(ifft(fftshift(x,1)),1);
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = FHT(x)
% FHT: Computes the Hadamard transform of a signal
% Usage:
% y = FHT(x);
% Inputs:
% x signal of dyadic length
% Outputs:
% y Hadamard transform coefficients
%
% Description
% FHT computes the Fast Hadamard transform of the signal x.
% See Also
% IFHT
%x = x(:);
n = size(x,1);
y = x;
t = zeros(n,size(x,2));
odds = 1:2:n;
evens = 2:2:n;
for ii = 1:log2(n)
t(odds,:) = y(odds,:) + y(evens,:);
t(evens,:) = y(odds,:) - y(evens,:);
y(1:(n/2),:) = t(odds,:);
y((n/2+1):n,:) = t(evens,:);
end
y = y ./ sqrt(n);
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function y = Inv_FHT(x)
% Inv_FHT: Computes the inverse Hadamard transform of a signal
% Usage:
% y = Inv_FHT(x);
% Inputs:
% x Hadamard transform coefficients
% Outputs:
% y signal
%
% Description
% Inv_FHT applies the forward Hadamard transform, since it is a self-adjoint operator.
% See Also
% FHT
y = FHT(x);
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
|
github
|
jacksky64/imageProcessing-master
|
compute_redundant_dictionary.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/compute_redundant_dictionary.m
| 3,651 |
utf_8
|
873380c9481c36f5a06629f27c1719b4
|
function [D,info] = compute_redundant_dictionary(name,n,options)
% compute_redundant_dictionary - compute several redundant dictionaries (matrices)
%
% [D,info] = compute_redundant_dictionary(name,n,options);
%
% n is the dimension
% options.q controls the redundancy
% info is a struct continaining information about the dictionary.
%
% name can be 'wavelets' (with redundant translation)
% 'cosine' (with redundant frequencies)
% 'gabor'
%
% for Gabor, you can select options.gaborloc which controls the ratio of
% frequency/time localization. gaborloc==2 means that the gabor atoms are
% 2x larger localization in frequencies.
%
% Copyright (c) 2008 Gabriel Peyre
q = getoptions(options, 'q', 4);
options.null = 0;
switch name
case 'wavelets'
[D,info.sel] = compute_wav_dictionary(n,q,options);
case 'cosine'
D = compute_cosine_dictionary(n,q,options);
info.sel = 1:size(D,2);
case 'gabor'
[D,info] = compute_gabor_dictionary(n,q,options);
info.sel = 1:size(D,2);
otherwise
error('Unknown dictionary.');
end
%%%
function [D,info] = compute_gabor_dictionary(n,q,options)
%% compute the freq/time localization factor
gaborloc = getoptions(options, 'gaborloc', 1);
gaborcpx = getoptions(options, 'gaborcpx', 0);
[sigma,sigmaf] = compute_gabor_sigma(n, gaborloc);
info.sigma = sigma;
info.sigmaf = sigmaf;
%% build the windowing functions
t = [0:n/2 -n/2+1:-1];
g = exp(-t.^2 / (2*sigma^2) );
sf = sqrt( sigmaf/sigma *n/q ); % spacing in time
sx = sqrt( sigma /sigmaf*n/q ); % spacing in frequency
x = ( 0:sx:n-1 );
if gaborcpx
f = ( 0:sf:n-1 );
else
f = ( 0:sf:n/2-1 );
end
t = 0:n-1;
nx = length(x);
nf = length(f);
p = nx*nf; % number of atoms
%% compute gabor atoms
[T,F,X] = ndgrid( t, f, x );
TX = T-X; % shifted
if gaborcpx
D = exp( -TX.^2 / (2*sigma^2) ) .* exp( 2i*pi/n * TX .* F );
else
D = exp( -TX.^2 / (2*sigma^2) ) .* cos( 2*pi/n * TX .* F );
end
D = reshape(D, [n p]);
D = D ./ repmat( sqrt(sum(abs(D).^2)), [n 1] );
% frequency index
F = F(1,:,:); info.F = F(:);
% spacial index
X = X(1,:,:); info.X = X(:);
info.nx = nx; info.nf = nf;
%% select the sigma so that the localization freq/time
function [sigma,sigmaf] = compute_gabor_sigma(n, gaborloc)
% is gaborloc
ns = 400;
slist = linspace(1,n/8,ns);
t = [0:n/2 -n/2+1:-1];
[S,T] = meshgrid( slist,t );
% generate gaussians
G = exp(-T.^2 ./ (2*S.^2) );
G = G ./ repmat( sqrt(sum(G.^2)), [n 1] );
% compute FFT
GF = real(fft(G));
GF = GF ./ repmat( sqrt(sum(GF.^2)), [n 1] );
% correlation
C = G'*GF;
% C(i,j) : correlation space_i / freq_j
[tmp,I] = max(C, [], 2);
slistf = slist(I);
r = slistf./slist;
[tmp,I] = min(abs(r-gaborloc)); I = I(1);
if I==1 || I==ns
warning('Problem in detecting Gabor scale');
end
sigma = slist(I);
sigmaf = slistf(I);
%%%
function D = compute_cosine_dictionary(n,q,options)
s = 0:1/q:n/2; s(end) = [];
[F,X] = meshgrid(s,0:n-1);
D = cos( 2*pi/n * F.*X);
%%%
function [D,selj] = compute_wav_dictionary(n,q,options)
Jmax = log2(n);
Jmin = 2;
options.wavelet_type = 'biorthogonal_swapped';
options.wavelet_vm = 4;
D = [];
sel = [n/2+1:n];
selj = {};
for j=Jmax-2:-1:Jmin
y = zeros(n,1);
y(sel(end/2)) = 1;
psi = perform_wavelet_transform(y, Jmin-1, -1, options);
sel = sel(1:end/2); sel = sel-length(sel);
% translate
qj = max(1/q*n/2^j,1);
[Y,X] = meshgrid(1:qj:n,1:n);
D = [D psi(mod(X-Y,n)+1)];
selj{j} = size(D,2)-n/qj+1:size(D,2);
end
|
github
|
jacksky64/imageProcessing-master
|
perform_omp.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/perform_omp.m
| 9,857 |
utf_8
|
84fa05746f22e0ac58735d2c53b486f1
|
function X = perform_omp(D,Y,options)
% perform_omp - perform orthogonal matching pursuit
%
% X = perform_omp(D,Y,options);
%
% D is the dictionary of size (n,p) of p atoms
% Y are the m vectors to decompose of size (n,m)
% X are the m coefficients of the decomposition of size (p,m).
%
% Orthogonal matching pursuit is a greedy procedure to minimise
% |x|_0 under the constraint that D*x=y.
% (maximum sparsity).
% You can stop the iteration after |x|_0=k by setting options.nbr_max_atoms=k
% You can set relative tolerance options.tol so that iterations stops when
% |Y-D*X| < tol*|Y|
%
% This code calls the fast mex version of Antoine Grolleau
% when possible.
%
% Copyright (c) 2006 Gabriel Peyre
if isfield(options, 'sparse_coder') && strcmp(options.sparse_coder, 'mp')
X = perform_mp(D,Y,options);
return;
end
options.null = 0;
nbr_max_atoms = getoptions(options, 'nbr_max_atoms', 50);
tol = getoptions(options, 'tol', 1e-3);
use_slow_code = getoptions(options, 'use_slow_code', 0);
verb = getoptions(options, 'verb', 1);
% P : number of signals, n dimension
[n,P]=size(Y);
% K : size of the dictionary
[n,K]=size(D);
if isfield(options, 'use_mex') && options.use_mex==1 && exist('perform_omp_mex')==3
% use fast mex interface
X = zeros(K,P);
for k=1:P
X(:,k) = perform_omp_mex(D,Y(:,k),nbr_max_atoms);
end
return;
end
if use_slow_code
X = perform_omp_other(Y,D,tol,nbr_max_atoms);
return;
end
for k=1:1:P,
if P>20 && verb==1
progressbar(k,P);
end
a=[];
x = Y(:,k);
r = x; % residual
I = zeros(nbr_max_atoms,1); % index of the chosen atoms
% norm of the original signal
e0 = sqrt( sum( r.^2 ) );
for j=1:1:nbr_max_atoms,
proj = D'*r;
pos = find(abs(proj)==max(abs(proj)));
pos = pos(1);
I(j) = pos;
a=pinv(D(:,I(1:j)))*x;
r=x-D(:,I(1:j))*a;
% compute error
e = sqrt( sum( r.^2 ) );
if e/e0 < tol
break;
end
end;
temp=zeros(K,1);
temp(I(1:length(a)))=a;
X(:,k)=sparse(temp);
end;
return;
function [D,Di,Q,beta,c] = perform_omp_other(f,D,tol,No,ind)
% perform_omp - Optimized Orthogonal Matching Pursuit
%
% It creates an atomic decomposition of a signal using OOMP method. You can choose a
% tolerance, the number of atoms to take in or an initial subspace to influence the OOMP
% algorithm. Non-selected atoms subtracted by their component in the chosen space are also
% available.
%
% Usage:
% x = perform_omp_other(f,D,tol,No,ind);
%
% Inputs:
% f analyzing signal of size (n,s) where s is the number of signals.
% D dictionary of normalized atoms of size (n,d) where d is the number
% of atoms.
% tol desired distance between f and its approximation
% the routine will stop if norm(f'-Dsub*(f*beta)')*sqrt(delta)<tol
% where delta=1/nbr_max_atoms, nbr_max_atoms is number of points in a sample
% No (optional) maximal number of atoms to choose, if the number of chosen
% atoms equals to No, routine will stop (default No=size(D,2)
% ind (optional) indices determining the initial subspace,
%
% Outputs:
% x coefficients of the decomposition such that f \approx D*x of size (p,s)
%
% References:
% nbr_max_atoms. Rebollo-Neira and D. Lowe, "Optimized Orthogonal Matching Pursuit Approach",
% IEEE Signal Processing Letters, Vol(9,4), 137-140, (2002).
%
% See also OMPF.
% [Dnew,Di]=oompf(f,D,tol);
% [Dnew,Di,Q,beta,c]=oompf(f,D,tol,No,ind);
% D the dictionary D rearranged according to the selection process
% D(:,1:k) contains the atoms chosen into the atomic decomposition
% Di indices of atoms in new D written w.r.t the original D
% Q Q(:,1:k) contains orthonormal functions spanning new D(:,1:k)
% Q(:,k+1:N) contains new D(:,k+1:N) subtracted by the projection
% onto the space generated by Q(:,1:k) (resp. D(:,1:k))
% beta 'k' biorthogonal functions corresponding to new D(:,1:k)
% c 'k' coefficients of the atomic decomposition
% See http://www.ncrg.aston.ac.uk/Projects/BiOrthog/ for more details
% verbosity
verb = 0;
name='OOMPF'; %name of routine
% get inputs and setup parameters
[nbr_max_atoms,N]=size(D);
beta=[];
Di=1:N; % index vector of full-dictionary
Q=D;
%delta=1/nbr_max_atoms; %uncomment in the case of analytical norm
delta=1; %uncomment in the case of discrete norm
if nargin<5 ind=[];end
if nargin<4 No=N;end
if nargin<3 tol=0.01;end;
if size(f,2)>1
% code several vectors
s = size(f,2);
x = zeros(size(D,2),s);
for i=1:s
if s>20
progressbar(i,s);
end
x(:,i) = perform_omp_other(f(:,i),D,tol,No,ind);
end
D = x;
return;
end
% the code use transposed data
f = f';
numind=length(ind);
%atoms having smaller norm than tol1 are supposed be zero ones
tol1=1e-7; %1e-5
%threshold for coefficients
tol2=1e-10; %0.0001 %1e-5
if verb
tic;
fprintf('\n%s is running for tol=%g, tol1=%g and tol2=%g.\n',name,tol,tol1,tol2);
fprintf('tol -> required precision, distance ||f-f_approx||\n')
fprintf('tol1 -> atoms having smaller norm are supposed to be zero ones.\n');
fprintf('tol2 -> algorithm stops if max(|<f,q>|/||q||)<= tol2.\n');
end
%===============================
% Main algorithm: at kth iteration
%===============================
H=min(No,N); %maximal number of function in sub-dictionary
for k=1:H
%finding of maximal coefficient
c=zeros(1,N);cc=zeros(1,N);
if k<=numind
[test,q]=ismember(ind(k),Di);
if test~=1 error('Demanded index %d is out of dictionary',ind(k));end
c(k)=norm(Q(:,q));
if c(k)<tol1
error('Demanded atom with index %d is dependent on the others.',ind(k));
end;
else
for p=k:N, c(p)=norm(Q(:,p));
if c(p)>tol1 cc(p)=abs(f*Q(:,p))/c(p);end;
end
[max_c,q]=max(cc);
%stopping criterion (coefficient)
if max_c<tol2
k=k-1;
if verb
fprintf('%s stopped, max(|<f,q>|/||q||)<= tol2=%g.\n',name,tol2);
end
break;
end
end
if q~=k
Q(:,[k q])=Q(:,[q k]); % swap k-th and q-th columns
D(:,[k q])=D(:,[q k]);
Di([k q])=Di([q k]);
end
%re-orthogonalization of Q(:,k) w.r.t Q(:,1),..., Q(:,k-1)
if k>1
for p=1:k-1
Q(:,k)=Q(:,k)-(Q(:,p)'*Q(:,k))*Q(:,p);
end
end
nork=norm(Q(:,k));
Q(:,k)=Q(:,k)/nork; %normalization
% compute biorthogonal functions beta from 1 to k-1
if k>1
beta=beta-Q(:,k)*(D(:,k)'*beta)/nork;
end
beta(:,k)=Q(:,k)/nork; % kth biorthogonal function
%orthogonalization of Q(:,k+1:n) wrt Q(:,k)
if k==N, break; end
for p=k+1:N
% orthogonalization of Q(:,p) wrt Q(:,k)
Q(:,p)=Q(:,p)-(Q(:,k)'*Q(:,p))*Q(:,k);
end
%stopping criterion (distance)
if (tol~= 0) & (norm(f'-D(:,1:k)*(f*beta)')*sqrt(delta) < tol) break;end;
end
c=f*beta;
normf=norm(f'-D(:,1:k)*c')*sqrt(delta);
if verb
fprintf('From %d atoms in this dictionary %s has chosen %d atoms.\n',N,name,k);
fprintf('\n%s lasted %g seconds\n',name,toc);
fprintf('\nNorm ||f-f_approx|| is %g. \n',normf);
end
% error testing
% orthogonality
errortest(Q(:,1:k));
% biorthogonality
errortest(D(:,1:k),beta);
if nargout==1
x = zeros( size(D,2),1 );
Di = Di(1:length(c));
x(Di(:)) = c(:);
D = x;
end
%Copyright (C) 2006 Miroslav ANDRLE and Laura REBOLLO-NEIRA
%
%This program is free software; you can redistribute it and/or modify it under the terms
%of the GNU General Public License as published by the Free Software Foundation; either
%version 2 of the License, or (at your option) any later version.
%
%This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
%without even the implied warranty of MERCHANTABILITY or FITNESS FOR X PARTICULAR PURPOSE.
%See the GNU General Public License for more details.
%
%You should have received a copy of the GNU General Public License along with this program;
%if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
%Boston, MA 02110-1301, USA.
function f=errortest(D,beta);
% ERRORTEST tests orthogonality of a sequence or biorthogonality of two sequences.
%
% Usage: errortest(D,beta);
% errortest(Q);
%
% Inputs:
% D sequence of vectors
% beta (optional) biorthogonal sequence
%
% Output:
% f orthogonality of D or biorthogonality D w.r.t beta
% See http://www.ncrg.aston.ac.uk/Projects/BiOrthog/ for more details
name='ERRORTEST';
verb = 0;
if nargin==1
% orthogonality
PP=D'*D;f=norm(eye(size(PP))-PP);
if verb
fprintf('Orthogonality: %g \n',f);
end
elseif nargin==2
% biorthogonality
PP=beta'*D;f=norm(eye(size(PP))-PP);
if verb
fprintf('Biorthogonality: %g \n',f);
end
else
if verb
fprintf('%s: Wrong number of arguments',name);
end
end
%Copyright (C) 2006 Miroslav ANDRLE and Laura REBOLLO-NEIRA
%
%This program is free software; you can redistribute it and/or modify it under the terms
%of the GNU General Public License as published by the Free Software Foundation; either
%version 2 of the License, or (at your option) any later version.
%
%This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
%without even the implied warranty of MERCHANTABILITY or FITNESS FOR X PARTICULAR PURPOSE.
%See the GNU General Public License for more details.
%
%You should have received a copy of the GNU General Public License along with this program;
%if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
%Boston, MA 02110-1301, USA.
|
github
|
jacksky64/imageProcessing-master
|
perform_mca.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/perform_mca.m
| 6,874 |
utf_8
|
f5c4b3fc3e6b267294c05d8f6ec46911
|
function ML = perform_mca(M, components, options)
% perform_mca - perform MCA decomposition
%
% ML = perform_mca(M, components, options);
%
% ML(:,:,i) is the layer optained by sparse decomposition in
% dictionary Di described by components{i}.
%
% components is a cell array of structure.
% cpt = components{i) discribe the ith transform used.
%
% It must contains:
% cpt.callback: a function of the type
% y = function(x,dir,options);
% for instance you can set cpt.callback=@callback_atrou
%
% It can contains:
% cpt.options: the options given to the callback
% cpt.threshold_factor: an amplification factor for the thresholding.
% cpt.tv_correction and cpt.tv_weight: the MCA will perform an
% additional TV minimization (usefull for the cartoon layer).
%
% options contains options for the MCA process such as:
% options.niter: number of iterations.
% options.saverep: directory to save iterations
% options.Tmax and options.Tmin: maximum and minimum threshold
% values. Set Tmin=0 if there is no noise in the problem
% (decomposition will be exact i.e. M=sum(ML,3)
% Set Tmax to approximately the maximum value of the
% coefficients of all the transforms of M.
%
% The references for the Morphological Components Analysis are
%
% J. Bobin, Y. Moudden, J.-L. Starck and M. Elad,
% "Morphological Diversity and Source Separation",
% IEEE Transaction on Signal Processing , Vol 13, 7, pp 409--412, 2006.
%
% M. Elad, J.-L Starck, D. Donoho and P. Querre,
% "Simultaneous Cartoon and Texture Image Inpainting using Morphological Component Analysis (MCA)",
% Journal on Applied and Computational Harmonic Analysis ACHA , Vol. 19, pp. 340-358, November 2005.
%
% J.-L. Starck, M. Elad, and D.L. Donoho,
% "Image Decomposition Via the Combination of Sparse Representation and a Variational Approach",
% IEEE Transaction on Image Processing , 14, 10, 2005.
%
% J.-L. Starck, M. Elad, and D.L. Donoho,
% "Redundant Multiscale Transforms and their Application for Morphological Component Analysis",
% Advances in Imaging and Electron Physics , 132, 2004.
%
% See also: perform_iterative_thresholding.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
if isfield(options, 'niter')
niter = options.niter;
else
niter = 20;
end
if isfield(options, 'Tmax')
Tmax = options.Tmax;
else
Tmax = 0.2*max(abs(M(:)));
end
if isfield(options, 'Tmin')
Tmin = options.Tmin;
else
Tmin = 0;
end
if isfield(options, 'threshold')
threshold = options.threshold;
else
threshold = 'hard';
end
if isfield(options, 'saverep')
saverep = options.saverep;
else
saverep = [];
end
if isfield(options, 'InpaintingMask')
InpaintingMask = options.InpaintingMask;
else
InpaintingMask = [];
end
s = length(components);
% init the residual
n = size(M,1);
ML = zeros(n,n,s);
if not(isempty(InpaintingMask))
q = sum(InpaintingMask(:)==Inf);
for k=1:s
Mk = ML(:,:,k);
Mk(InpaintingMask==Inf) = rand( q,1 ) * max( M(InpaintingMask~=Inf) );
ML(:,:,k) = Mk;
end
end
MLsave = [];
for i=1:niter
progressbar(i,niter);
% current threshold
T0 = Tmax + (i-1)/(niter-1)*(Tmin-Tmax);
for k=1:s
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% current component
cpt = components{k};
% callback function
callback = cpt.callback;
% options
clear opt; opt.null = 0;
if isfield(cpt, 'options')
opt = cpt.options;
end
% threshold factor amplification
threshold_factor = 1;
if isfield(cpt, 'threshold_factor')
threshold_factor = cpt.threshold_factor;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute residual
T = T0 * threshold_factor;
opt.T = T;
% compute residual
sel = 1:s; sel(k) = [];
R = M - sum( ML(:,:,sel), 3);
if not(isempty(InpaintingMask))
% enforce known values only outside
Mk = ML(:,:,k);
R(InpaintingMask==Inf) = Mk(InpaintingMask==Inf);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% perform forward transform
RW = feval(callback, R,+1,opt);
% perform thresholding
if strcmp(cpt.name, 'wav')
% do not threshold the low frequency
RW1 = perform_thresholding({RW{1:end-1}},T, threshold);
RW = {RW1{:}, RW{end}};
else
RW = perform_thresholding(RW,T, threshold);
end
% perform backward transform
ML(:,:,k) = feval(callback, RW,-1,opt);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TV additional sparsening
if isfield(cpt, 'tv_correction') && cpt.tv_correction==1
if isfield(options, 'tv_weight')
tv_weight = options.tv_weight;
else
tv_weight = 2.5*max(abs(M(:)))/256;
end
ML(:,:,k) = perform_tv_correction(ML(:,:,k),tv_weight);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% save result
if not(isempty(saverep))
MLsave(:,:,:,i) = ML;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% save all the data
if not(isempty(saverep))
% normalize the evolution
vmax = max(max(max(MLsave,[],1),[],2),[],4);
vmax = repmat(vmax, [n n 1 niter]);
vmin = min(min(min(MLsave,[],1),[],2),[],4);
vmin = repmat(vmin, [n n 1 niter]);
MLsave = (MLsave-vmin) ./ (vmax-vmin);
for k=1:s
cpt = components{k};
for i=1:niter
if isfield(cpt, 'name')
str = cpt.name;
else
str = ['layer' num2str(k)];
end
str = [str '-iter' num2string_fixeddigit(i,2)];
warning off;
imwrite( MLsave(:,:,k,i), [saverep str '.png'], 'png' );
warning on;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_hard_tresholding(x,t)
if iscell(x)
for i=1:length(x)
y{i} = perform_hard_tresholding(x{i},t);
end
return;
end
y = x .* (abs(x) > t);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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_synthetic_dictionary.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/compute_synthetic_dictionary.m
| 5,246 |
utf_8
|
30de6dc1f7a7b49db0d9b4ae9489fb86
|
function D = compute_synthetic_dictionary(name, w, options)
% compute_synthetic_dictionary - compute a synthetic dictionary
%
% D = compute_synthetic_dictionary(name, w, options);
%
% w is the width of the patches.
% names is 'edges', 'oscillations', 'lines' or 'crossings'.
%
% Copyright (c) 2007 Gabriel Peyre
options.rescale = 0;
options.manifold_type = name;
switch lower(name)
case {'edges', 'lines'}
D = compute_edge_patches(w, options);
case 'crossings'
D = compute_crossing_patches(w, options);
case 'oscillations'
D = compute_oscillations_patches(w, options);
otherwise
error('Unknown type.');
end
p = size(D,3);
% normalize
rescale = getoptions(options, 'rescale', 0);
bell = getoptions(options, 'bell', 'constant');
if rescale
B = compute_bell_shape(bell, w);
B = repmat(B,[1,1,p]);
s = sqrt( sum( sum(B .* (D.^2),1), 2) );
D = D ./ repmat(s,[w,w,1]);
else
D = (D+1)/2;
end
% shuffle
D = reshape(D, w^2, p);
D = D(:,randperm(p));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [M,delta_list,theta_list,freq_list] = compute_oscillations_patches(w, options)
% [M,delta_list,theta_list] = compute_edge_patches(w, options);
options.null = 0;
n_theta = getoptions(options, 'n_theta', 12);
n_freq = getoptions(options, 'n_freq', 6);
t = linspace(0,pi,n_theta+1); t(end) = [];
f = linspace(3,8,n_freq);
[theta_list,freq_list] = meshgrid( t, f );
theta_list = theta_list(:);
freq_list = freq_list(:);
p = length(freq_list);
x = linspace( -(w-1)/2,(w-1)/2, w );
[Y,X] = meshgrid(x,x);
M = []; % zeros(w,w,p*);
% compute images
for k=1:p
t = theta_list(k);
f = freq_list(k);
y = cos(t)*X + sin(t)*Y;
nbt = round(f*2);
d = linspace(0,f,nbt+1); d(end)=0;
for t=1:nbt
M(:,:,k) = cos( 2*pi* (y+d(t))/f );
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [M,delta_list,theta_list] = compute_edge_patches(w, options)
% [M,delta_list,theta_list] = compute_edge_patches(w, options);
options.null = 0;
n_delta = getoptions(options, 'n_delta', 11);
n_theta = getoptions(options, 'n_theta', 12);
sigma = getoptions(options, 'sigma', .1);
manifold_type = getoptions(options, 'manifold_type', 'edges');
sigma = sigma*w;
dmax = sqrt(2)*w/2+2*sigma;
eta = 2;
t = linspace(0,2*pi-2*pi/n_theta,n_theta); t = t(:);
d = linspace(-1,1,n_delta);
d = sign(d).*abs(d).^eta;
d = d(:)*dmax;
[theta_list,delta_list] = meshgrid( t, d );
theta_list = theta_list(:);
delta_list = delta_list(:);
p = length(delta_list);
x = linspace( -(w-1)/2,(w-1)/2, w );
[Y,X] = meshgrid(x,x);
M = zeros(w,w,p);
% compute images
for k=1:p
t = theta_list(k);
d = delta_list(k);
y = cos(t)*X + sin(t)*Y - d;
switch manifold_type
case 'edges'
A = tanh(y/sigma);
case 'lines'
A = 2*( 1 - exp( -y.^2 / (2*sigma^2) ) ) - 1;
case 'oscillations'
if isfield(options, 'freq')
freq = options.freq;
end
A = cos( y*2*pi/freq );
end
M(:,:,k) = A;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [M, delta1_list,theta1_list, delta2_list,theta2_list] = compute_crossing_patches(w, options)
% [M, delta1_list,theta1_list, delta2_list,theta2_list] = compute_crossing_patches(w, options);
options.null = 0;
n_delta = getoptions(options, 'n_delta', 11);
n_theta = getoptions(options, 'n_theta', 12);
sigma = getoptions(options, 'sigma', .1);
sigma = sigma*w;
dmax = sqrt(2)*w/2+2*sigma;
eta = 2;
t = linspace(0,pi-pi/n_theta,n_theta); t = t(:);
d = linspace(-1,1,n_delta);
d = sign(d).*abs(d).^eta;
d = d(:)*dmax;
[delta1_list,theta1_list,delta2_list,theta2_list] = ndgrid( d, t, d, t );
theta1_list = theta1_list(:);
delta1_list = delta1_list(:);
theta2_list = theta2_list(:);
delta2_list = delta2_list(:);
p = length(delta1_list);
x = linspace( -(w-1)/2,(w-1)/2, w );
[Y,X] = meshgrid(x,x);
c1 = repmat( reshape(cos(theta1_list),[1 1 p]), [w w 1] );
s1 = repmat( reshape(sin(theta1_list),[1 1 p]), [w w 1] );
c2 = repmat( reshape(cos(theta2_list),[1 1 p]), [w w 1] );
s2 = repmat( reshape(sin(theta2_list),[1 1 p]), [w w 1] );
d1 = repmat( reshape(delta1_list,[1 1 p]), [w w 1] );
d2 = repmat( reshape(delta2_list,[1 1 p]), [w w 1] );
X = repmat( X, [1 1 p] );
Y = repmat( Y, [1 1 p] );
A1 = c1.*X + s1.*Y - d1;
A1 = 2*( 1 - exp( -A1.^2 / (2*sigma^2) ) ) - 1;
A2 = c2.*X + s2.*Y - d2;
A2 = 2*( 1 - exp( -A2.^2 / (2*sigma^2) ) ) - 1;
M = min(A1,A2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function B = compute_bell_shape(bell, w)
switch lower(bell)
case 'constant'
B = ones(w);
case 'sine'
x = linspace(0,1,w);
x = (1-cos(2*pi*x))/2;
B = x'*x;
otherwise
error('Unknown bell shape');
end
|
github
|
jacksky64/imageProcessing-master
|
perform_debiasing.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/perform_debiasing.m
| 2,313 |
utf_8
|
89cb6ddcc4c67a5af08b981e00c08149
|
function [x1,err] = perform_debiasing(A,x,y, options)
% perform_debiasing - remove bias by orthogonal projection
%
% x1 = perform_debiasing(A,x,y, options);
%
% Compute x1 with same support I=find(abs(x)>Thresh) as x that minimize
% min | y - A(:,I)*x(I) |
% Thresh is set in options.Thresh
%
% Usefull to remove some bias after L1 minimization.
%
% If A is an implicit callback function or if options.use_pinv=0, then it
% used an itertive gradient descent.
%
% Copyright (c) 2008 Gabriel Peyre
options.null = 0;
use_pinv = getoptions(options, 'use_pinv', 1);
Thresh = getoptions(options, 'Thresh', 1e-5);
verb = getoptions(options, 'verb', 1);
if isnumeric(A) && use_pinv
if size(x,2)>1
% multiple signals
x1 = x*0;
for i=1:size(x,2)
[x1(:,i),err] = perform_debiasing(A,x(:,i),y(:,i), options);
end
return;
end
% use explicit pseudo inverse
I = find(abs(x)>Thresh);
x1 = x*0;
x1(I) = A(:,I)\y;
err = [];
return;
end
niter = getoptions(options, 'niter_debiasing', 100);
tau = getoptions(options, 'tau', 1);
x1 = getoptions(options, 'xguess', x);
err = [];
x1 = perform_support_projection(x1,x,Thresh);
for i=1:niter
if verb
progressbar(i,niter);
end
% gradient descent
% x <- x + 1/tau * A'*( y-A*x )
r = y - applyop_single( A, x1,+1,options );
err(i) = norm(r, 'fro');
if not(iscell(x))
x1 = x1 + 1/tau * applyop_single( A, r,-1,options );
else
xx = applyop_single( A, r,-1,options );
for k=1:length(x)
x1{k} = x1{k} + 1/tau * xx{k};
end
end
% project on support
x1 = perform_support_projection(x1,x,Thresh);
end
%%
function x = perform_support_projection(x,x0,Thresh)
if iscell(x)
for i=1:length(x)
x{i} = perform_support_projection(x{i},x0{i},Thresh);
end
return;
end
% impose same support
x(abs(x0)<Thresh) = 0;
%%
function y = applyop_single(A,x,dir,options, pA)
if isempty(A)
y = x;
return;
end
if isnumeric(A)
if dir==1
y = A*x;
elseif dir==-1
y = A'*x;
else
if exist('pA') && not(isempty(pA))
y = pA*x;
else
y = pinv(A)*x;
end
end
else
y = feval( A, x, dir, options );
end
|
github
|
jacksky64/imageProcessing-master
|
perform_windowed_fourier_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/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_image.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/load_image.m
| 15,910 |
utf_8
|
f5a8233f70450d4ce607431750bcffda
|
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 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 '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');
|
github
|
jacksky64/imageProcessing-master
|
grab_inpainting_mask.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/grab_inpainting_mask.m
| 3,553 |
utf_8
|
e1b2c4077e57645a8b91a2bc47fd1245
|
function [U,point_list] = grab_inpainting_mask(M, options, mode)
% grab_inpainting_mask - create a mask from user input
%
% U = grab_inpainting_mask(M, options);
%
% options.r is the radius for selection (default r=5).
%
% Selection stops with right click.
%
% Copyright (c) 2006 Gabriel Peyre
if nargin==3 && mode==1
U = grab_inpainting_mask_old(M, options);
return;
end
options.null = 0;
if isfield(options, 'r')
r = options.r;
else
r = 5;
end
if isfield(options, 'mode')
mode = options.mode;
else
mode = 'points';
end
if strcmp(mode, '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
|
perform_atrou_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/perform_atrou_transform.m
| 23,360 |
utf_8
|
ff914c13e923fce2f63396a7faa47d26
|
function y = perform_atrou_transform(x,Jmin,options)
% perform_atrou_transform - compute the "a trou" wavelet transform,
% i.e. without subsampling.
%
% w_list = perform_atrou_transform(M,Jmin,options);
%
% 'w_list' is a cell array, w_list{ 3*(j-Jmin)+q }
% is an imagette of same size as M containing the full transform
% at scale j and quadrant q.
% The lowest resolution image is in w_list{3*(Jmax-Jmin)+4} =
% w_list{end}.
%
% The ordering is :
% { H_j,V_j,D_j, H_{j-1},V_{j-1},D_{j-1}, ..., H_1,V_1,D_1, C }
%
% 'options' is an (optional) structure that may contains:
% options.wavelet_type: kind of wavelet used (see perform_wavelet_transform)
% options.wavelet_vm: the number of vanishing moments of the wavelet transform.
%
% When possible, this code tries to use the following fast mex implementation:
% * Rice Wavelet Toolbox : for Daubechies filters, ie when options.wavelet_type='daubechies'.
% Only the Windows binaries are included, please refer to
% http://www-dsp.rice.edu/software/rwt.shtml
% to install on other OS.
%
% You can set decomp_type = 'quad' or 'tri' for the 7-9 transform.
%
% Copyright (c) 2006 Gabriel Peyr?
% add let it wave a trou transform to the path
% path('./cwpt2/',path);
% add Rice Wavelet Toolbox transform to the path
% path('./rwt/',path);
if nargin<3
options.null = 0;
end
if isfield(options, 'wavelet_type')
wavelet_type = options.wavelet_type;
wavelet_vm = 4;
else
wavelet_type = 'biorthogonal';
wavelet_vm = 3;
end
if isfield(options, 'wavelet_vm')
wavelet_vm = options.wavelet_vm;
end
if isfield(options, 'bound')
bound = options.bound;
else
bound = 'sym';
end
% first check for LIW interface, since it's the best code
if exist('cwpt2_interface') && ~strcmp(wavelet_type, 'daubechies') && ~strcmp(wavelet_type, 'symmlet')
if strcmp(wavelet_type, 'biorthogonal') || strcmp(wavelet_type, 'biorthogonal_swapped')
if wavelet_vm~=3
warning('Works only for 7-9 wavelets.');
end
wavelet_types = '7-9';
elseif strcmp(wavelet_type, 'battle')
if wavelet_vm~=3
warning('Works only for cubic spline wavelets.');
end
wavelet_types = 'spline';
else
error('Unknown transform.');
end
if isfield(options, 'decomp_type')
decomp_type = options.decomp_type;
else
decomp_type = 'quad'; % either 'quad' or 'tri'
end
if ~iscell(x)
dirs = 'forward';
J = log2(size(x,1)) - Jmin;
M = x;
else
dirs = 'inverse';
if strcmp(decomp_type, 'tri')
x = { x{1:end-3}, x{end}, x{end-2:end-1} };
else
x = { x{1:end-4}, x{end}, x{end-3:end-1} };
end
J = 0;
M = zeros(size(x{1},1), size(x{1},2), J);
for i=1:length(x)
M(:,:,i) = x{i};
end
end
y = cwpt2_interface(M, dirs, wavelet_types, decomp_type, J);
if ~iscell(x)
M = y; y = {};
for i=1:size(M,3)
y{i} = M(:,:,i);
end
% put low frequency at the end
if strcmp(decomp_type, 'tri')
y = { y{1:end-3}, y{end-1:end}, y{end-2} };
else
y = { y{1:end-4}, y{end-2:end}, y{end-3} };
end
end
return;
end
% precompute filters
if strcmp(wavelet_type, 'daubechies')
fname = 'Daubechies';
if wavelet_vm==1
fname = 'Haar';
end
qmf = MakeONFilter(fname,wavelet_vm*2); % in Wavelab, 2nd argument is VM*2 for Daubechies... no comment ...
elseif strcmp(wavelet_type, 'symmlet')
qmf = MakeONFilter('Symmlet',wavelet_vm);
elseif strcmp(wavelet_type, 'battle')
qmf = MakeONFilter('Battle',wavelet_vm-1);
elseif strcmp(wavelet_type, 'biorthogonal')
[qmf,dqmf] = MakeBSFilter( 'CDF', [wavelet_vm,wavelet_vm] );
elseif strcmp(wavelet_type, 'biorthogonal_swapped')
[dqmf,qmf] = MakeBSFilter( 'CDF', [wavelet_vm,wavelet_vm] );
else
error('Unknown transform.');
end
g = qmf; % for phi
gg = g;
if exist('mirdwt') & exist('mrdwt') & strcmp(wavelet_type, 'daubechies')
%%% USING RWT %%%
if ~iscell(x)
n = length(x);
Jmax = log2(n)-1;
%%% FORWARD TRANSFORM %%%
L = Jmax-Jmin+1;
[yl,yh,L] = mrdwt(x,g,L);
for j=Jmax:-1:Jmin
for q=1:3
s = 3*(Jmax-j)+q-1;
M = yh(:,s*n+1:(s+1)*n);
y{ 3*(j-Jmin)+q } = M;
end
end
y{ 3*(Jmax-Jmin)+4 } = yl;
else
n = length(x{1});
Jmax = log2(n)-1;
%%% BACKWARD TRANSFORM %%%
L = Jmax-Jmin+1;
if L ~= (length(x)-1)/3
warning('Jmin is not correct.');
L = (length(x)-1)/3;
end
yl = x{ 3*(Jmax-Jmin)+4 };
yh = zeros( n,3*L*n );
for j=Jmax:-1:Jmin
for q=1:3
s = 3*(Jmax-j)+q-1;
yh(:,s*n+1:(s+1)*n) = x{ 3*(j-Jmin)+q };
end
end
[y,L] = mirdwt(yl,yh,gg,L);
end
return;
end
warning('This code is depreciated.');
% for reconstruction
h = mirror_filter(g); % for psi
hh = g;
if exist('dqmf')
gg = dqmf;
hh = mirror_filter(gg);
end
n = length(x);
Jmax = log2(n)-1;
if iscell(x)
error('reverse transform is not yet implemented.');
end
M = x;
Mj = M; % image at current scale (low pass filtered)
nh = length(h);
ng = length(g);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute the transform
wb = waitbar(0,'Computing a trou transform.');
for j=Jmax:-1:Jmin
waitbar((Jmax-j)/(Jmax-Jmin),wb);
% 1st put some zeros in between g and h
nz = 2^(Jmax-j); % space between coefs
hj = zeros(nz*(nh-1)+1, 1);
gj = zeros(nz*(ng-1)+1, 1);
hj( 1 + (0:nh-1)*nz ) = h;
gj( 1 + (0:ng-1)*nz ) = g;
%%%% filter on X %%%%
Mjh = zeros(n,n);
Mjg = zeros(n,n);
for i=1:n
Mjh(:,i) = perform_convolution( Mj(:,i), hj, bound );
Mjg(:,i) = perform_convolution( Mj(:,i), gj, bound );
end
%%%% filter on Y %%%%
Mjhh = zeros(n,n);
Mjhg = zeros(n,n);
Mjgh = zeros(n,n);
Mjgg = zeros(n,n);
for i=1:n
Mjhh(i,:) = perform_convolution( Mjh(i,:)', hj, bound )';
Mjhg(i,:) = perform_convolution( Mjh(i,:)', gj, bound )';
Mjgh(i,:) = perform_convolution( Mjg(i,:)', hj, bound )';
Mjgg(i,:) = perform_convolution( Mjg(i,:)', gj, bound )';
end
Mj = Mjgg;
w_list{ 3*(j-Jmin)+1 } = Mjgh;
w_list{ 3*(j-Jmin)+2 } = Mjhg;
w_list{ 3*(j-Jmin)+3 } = Mjhh;
end
close(wb);
w_list{ 3*(Jmax-Jmin)+4 } = Mj;
y = w_list;
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
%
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]
%
function y = mirror_filter(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
%
|
github
|
jacksky64/imageProcessing-master
|
perform_dct_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/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
|
perform_thresholding.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/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
|
cgsolve.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/cgsolve.m
| 1,626 |
utf_8
|
144fb53044ae853bc0d1d7f6cf8f8f3d
|
% cgsolve.m
%
% Solve a symmetric positive definite system Ax = b via conjugate gradients.
%
% Usage: [x, res, iter] = cgsolve(A, b, tol, maxiter, verbose)
%
% A - Either an NxN matrix, or a function handle.
%
% b - N vector
%
% tol - Desired precision. Algorithm terminates when
% norm(Ax-b)/norm(b) < tol .
%
% maxiter - Maximum number of iterations.
%
% verbose - If 0, do not print out progress messages.
% Default = 1.
%
% Written by: Justin Romberg, Caltech
% Email: [email protected]
% Created: October 2005
%
function [x, res, iter] = cgsolve(A, b, tol, maxiter, verbose)
if (nargin < 5), verbose = 1; end
implicit = isa(A,'function_handle');
x = zeros(length(b),1);
r = b;
d = r;
delta = r'*r;
delta0 = b'*b;
numiter = 0;
bestx = x;
bestres = sqrt(delta/delta0);
while ((numiter < maxiter) & (delta > tol^2*delta0))
% q = A*d
if (implicit), q = A(d); else, q = A*d; end
alpha = delta/(d'*q);
x = x + alpha*d;
if (mod(numiter+1,50) == 0)
% r = b - Aux*x
if (implicit), r = b - A(x); else, r = b - A*x; end
else
r = r - alpha*q;
end
deltaold = delta;
delta = r'*r;
beta = delta/deltaold;
d = r + beta*d;
numiter = numiter + 1;
if (sqrt(delta/delta0) < bestres)
bestx = x;
bestres = sqrt(delta/delta0);
end
if ((verbose) & (mod(numiter,50)==0))
disp(sprintf('cg: Iter = %d, Best residual = %8.3e, Current residual = %8.3e', ...
numiter, bestres, sqrt(delta/delta0)));
end
end
if (verbose)
disp(sprintf('cg: Iterations = %d, best residual = %14.8e', numiter, bestres));
end
x = bestx;
res = bestres;
iter = numiter;
|
github
|
jacksky64/imageProcessing-master
|
SolveOMP.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/SolveOMP.m
| 5,517 |
utf_8
|
f4e04a5fa97a57fc5a3f3cebae686a5e
|
function [sols, iters, activationHist] = SolveOMP(A, y, N, maxIters, lambdaStop, solFreq, verbose, OptTol)
% SolveOMP: Orthogonal Matching Pursuit
% Usage
% [sols, iters, activationHist] = SolveOMP(A, y, N, maxIters, lambdaStop, solFreq, verbose, OptTol)
% Input
% A Either an explicit nxN matrix, with rank(A) = min(N,n)
% by assumption, or a string containing the name of a
% function implementing an implicit matrix (see below for
% details on the format of the function).
% y vector of length n.
% N length of solution vector.
% maxIters maximum number of iterations to perform. If not
% specified, runs to stopping condition (default)
% lambdaStop If specified, the algorithm stops when the last coefficient
% entered has residual correlation <= lambdaStop.
% solFreq if =0 returns only the final solution, if >0, returns an
% array of solutions, one every solFreq iterations (default 0).
% verbose 1 to print out detailed progress at each iteration, 0 for
% no output (default)
% OptTol Error tolerance, default 1e-5
% Outputs
% sols solution(s) of OMP
% iters number of iterations performed
% activationHist Array of indices showing elements entering
% the solution set
% Description
% SolveOMP is a greedy algorithm to estimate the solution
% of the sparse approximation problem
% min ||x||_0 s.t. A*x = b
% The implementation implicitly factors the active set matrix A(:,I)
% using Cholesky updates.
% The matrix A can be either an explicit matrix, or an implicit operator
% implemented as an m-file. If using the implicit form, the user should
% provide the name of a function of the following format:
% y = OperatorName(mode, m, n, x, I, dim)
% This function gets as input a vector x and an index set I, and returns
% y = A(:,I)*x if mode = 1, or y = A(:,I)'*x if mode = 2.
% A is the m by dim implicit matrix implemented by the function. I is a
% subset of the columns of A, i.e. a subset of 1:dim of length n. x is a
% vector of length n is mode = 1, or a vector of length m is mode = 2.
% See Also
% SolveLasso, SolveBP, SolveStOMP
%
if nargin < 8,
OptTol = 1e-5;
end
if nargin < 7,
verbose = 0;
end
if nargin < 6,
solFreq = 0;
end
if nargin < 5,
lambdaStop = 0;
end
if nargin < 4,
maxIters = length(y);
end
explicitA = ~(ischar(A) || isa(A, 'function_handle'));
n = length(y);
% Parameters for linsolve function
% Global variables for linsolve function
global opts opts_tr machPrec
opts.UT = true;
opts_tr.UT = true; opts_tr.TRANSA = true;
machPrec = 1e-5;
% Initialize
x = zeros(N,1);
k = 1;
R_I = [];
activeSet = [];
sols = [];
res = y;
normy = norm(y);
resnorm = normy;
done = 0;
while ~done
if (explicitA)
corr = A'*res;
else
corr = feval(A,2,n,N,res,1:N,N); % = A'*y
end
[maxcorr i] = max(abs(corr));
newIndex = i(1);
% Update Cholesky factorization of A_I
[R_I, flag] = updateChol(R_I, n, N, A, explicitA, activeSet, newIndex);
if flag==0
activeSet = [activeSet newIndex];
end
% Solve for the least squares update: (A_I'*A_I)dx_I = corr_I
dx = zeros(N,1);
if k==27
a = 1;
end
z = linsolve(R_I,corr(activeSet),opts_tr);
dx(activeSet) = linsolve(R_I,z,opts);
x(activeSet) = x(activeSet) + dx(activeSet);
% Compute new residual
if (explicitA)
res = y - A(:,activeSet) * x(activeSet);
else
Ax = feval(A,1,n,N,x,1:N,N);
res = y - Ax;
end
resnorm = norm(res);
if ((resnorm <= OptTol*normy) | ((lambdaStop > 0) & (maxcorr <= lambdaStop)))
done = 1;
end
if verbose
fprintf('Iteration %d: Adding variable %d\n', k, newIndex);
end
k = k+1;
if k >= maxIters
done = 1;
end
if done | ((solFreq > 0) & (~mod(k,solFreq)))
sols = [sols x];
end
end
iters = k;
activationHist = activeSet;
clear opts opts_tr machPrec
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [R, flag] = updateChol(R, n, N, A, explicitA, activeSet, newIndex)
% updateChol: Updates the Cholesky factor R of the matrix
% A(:,activeSet)'*A(:,activeSet) by adding A(:,newIndex)
% If the candidate column is in the span of the existing
% active set, R is not updated, and flag is set to 1.
global opts_tr machPrec
flag = 0;
if (explicitA)
newVec = A(:,newIndex);
else
e = zeros(N,1);
e(newIndex) = 1;
newVec = feval(A,1,n,N,e,1:N,N);
end
if length(activeSet) == 0,
R = sqrt(sum(newVec.^2));
else
if (explicitA)
p = linsolve(R,A(:,activeSet)'*A(:,newIndex),opts_tr);
else
AnewVec = feval(A,2,n,length(activeSet),newVec,activeSet,N);
p = linsolve(R,AnewVec,opts_tr);
end
q = sum(newVec.^2) - sum(p.^2);
if (q <= machPrec) % Collinear vector
flag = 1;
else
R = [R p; zeros(1, size(R,2)) sqrt(q)];
end
end
%
% Copyright (c) 2006. Yaakov Tsaig
%
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
|
github
|
jacksky64/imageProcessing-master
|
l1eq_pd.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/l1eq_pd.m
| 5,308 |
utf_8
|
c2d14a529c067d730ebee8140ec5ecc4
|
% l1eq_pd.m
%
% Solve
% min_x ||x||_1 s.t. Ax = b
%
% Recast as linear program
% min_{x,u} sum(u) s.t. -u <= x <= u, Ax=b
% and use primal-dual interior point method
%
% Usage: xp = l1eq_pd(x0, A, At, b, pdtol, pdmaxiter, cgtol, cgmaxiter)
%
% x0 - Nx1 vector, initial point.
%
% A - Either a handle to a function that takes a N vector and returns a K
% vector , or a KxN matrix. If A is a function handle, the algorithm
% operates in "largescale" mode, solving the Newton systems via the
% Conjugate Gradients algorithm.
%
% At - Handle to a function that takes a K vector and returns an N vector.
% If A is a KxN matrix, At is ignored.
%
% b - Kx1 vector of observations.
%
% pdtol - Tolerance for primal-dual algorithm (algorithm terminates if
% the duality gap is less than pdtol).
% Default = 1e-3.
%
% pdmaxiter - Maximum number of primal-dual iterations.
% Default = 50.
%
% cgtol - Tolerance for Conjugate Gradients; ignored if A is a matrix.
% Default = 1e-8.
%
% cgmaxiter - Maximum number of iterations for Conjugate Gradients; ignored
% if A is a matrix.
% Default = 200.
%
% Written by: Justin Romberg, Caltech
% Email: [email protected]
% Created: October 2005
%
function xp = l1eq_pd(x0, A, At, b, pdtol, pdmaxiter, cgtol, cgmaxiter)
largescale = isa(A,'function_handle');
if (nargin < 5), pdtol = 1e-3; end
if (nargin < 6), pdmaxiter = 50; end
if (nargin < 7), cgtol = 1e-8; end
if (nargin < 8), cgmaxiter = 200; end
N = length(x0);
alpha = 0.01;
beta = 0.5;
mu = 10;
gradf0 = [zeros(N,1); ones(N,1)];
x = x0;
u = 1.01*max(abs(x))*ones(N,1) + 1e-2;
fu1 = x - u;
fu2 = -x - u;
lamu1 = -1./fu1;
lamu2 = -1./fu2;
if (largescale)
v = -A(lamu1-lamu2);
Atv = At(v);
rpri = A(x) - b;
else
v = -A*(lamu1-lamu2);
Atv = A'*v;
rpri = A*x - b;
end
sdg = -(fu1'*lamu1 + fu2'*lamu2);
tau = mu*2*N/sdg;
rcent = [-lamu1.*fu1; -lamu2.*fu2] - (1/tau);
rdual = gradf0 + [lamu1-lamu2; -lamu1-lamu2] + [Atv; zeros(N,1)];
resnorm = norm([rdual; rcent; rpri]);
pditer = 0;
done = (sdg < pdtol) | (pditer >= pdmaxiter);
while (~done)
pditer = pditer + 1;
w1 = -1/tau*(-1./fu1 + 1./fu2) - Atv;
w2 = -1 - 1/tau*(1./fu1 + 1./fu2);
w3 = -rpri;
sig1 = -lamu1./fu1 - lamu2./fu2;
sig2 = lamu1./fu1 - lamu2./fu2;
sigx = sig1 - sig2.^2./sig1;
if (largescale)
w1p = w3 - A(w1./sigx - w2.*sig2./(sigx.*sig1));
h11pfun = @(z) -A(1./sigx.*At(z));
[dv, cgres, cgiter] = cgsolve(h11pfun, w1p, cgtol, cgmaxiter, 0);
if (cgres > 1/2)
disp('Primal-dual: Cannot solve system. Returning previous iterate.');
xp = x;
return
end
dx = (w1 - w2.*sig2./sig1 - At(dv))./sigx;
Adx = A(dx);
Atdv = At(dv);
else
H11p = -A*diag(1./sigx)*A';
w1p = w3 - A*(w1./sigx - w2.*sig2./(sigx.*sig1));
[dv,hcond] = linsolve(H11p,w1p);
if (hcond < 1e-14)
disp('Primal-dual: Matrix ill-conditioned. Returning previous iterate.');
xp = x;
return
end
dx = (w1 - w2.*sig2./sig1 - A'*dv)./sigx;
Adx = A*dx;
Atdv = A'*dv;
end
du = (w2 - sig2.*dx)./sig1;
dlamu1 = (lamu1./fu1).*(-dx+du) - lamu1 - (1/tau)*1./fu1;
dlamu2 = (lamu2./fu2).*(dx+du) - lamu2 - 1/tau*1./fu2;
% make sure that the step is feasible: keeps lamu1,lamu2 > 0, fu1,fu2 < 0
indp = find(dlamu1 < 0); indn = find(dlamu2 < 0);
s = min([1; -lamu1(indp)./dlamu1(indp); -lamu2(indn)./dlamu2(indn)]);
indp = find((dx-du) > 0); indn = find((-dx-du) > 0);
s = (0.99)*min([s; -fu1(indp)./(dx(indp)-du(indp)); -fu2(indn)./(-dx(indn)-du(indn))]);
% backtracking line search
backiter = 0;
xp = x + s*dx; up = u + s*du;
vp = v + s*dv; Atvp = Atv + s*Atdv;
lamu1p = lamu1 + s*dlamu1; lamu2p = lamu2 + s*dlamu2;
fu1p = xp - up; fu2p = -xp - up;
rdp = gradf0 + [lamu1p-lamu2p; -lamu1p-lamu2p] + [Atvp; zeros(N,1)];
rcp = [-lamu1p.*fu1p; -lamu2p.*fu2p] - (1/tau);
rpp = rpri + s*Adx;
while(norm([rdp; rcp; rpp]) > (1-alpha*s)*resnorm)
s = beta*s;
xp = x + s*dx; up = u + s*du;
vp = v + s*dv; Atvp = Atv + s*Atdv;
lamu1p = lamu1 + s*dlamu1; lamu2p = lamu2 + s*dlamu2;
fu1p = xp - up; fu2p = -xp - up;
rdp = gradf0 + [lamu1p-lamu2p; -lamu1p-lamu2p] + [Atvp; zeros(N,1)];
rcp = [-lamu1p.*fu1p; -lamu2p.*fu2p] - (1/tau);
rpp = rpri + s*Adx;
backiter = backiter+1;
if (backiter > 32)
disp('Stuck backtracking, returning last iterate.')
xp = x;
return
end
end
% next iteration
x = xp; u = up;
v = vp; Atv = Atvp;
lamu1 = lamu1p; lamu2 = lamu2p;
fu1 = fu1p; fu2 = fu2p;
% surrogate duality gap
sdg = -(fu1'*lamu1 + fu2'*lamu2);
tau = mu*2*N/sdg;
rpri = rpp;
rcent = [-lamu1.*fu1; -lamu2.*fu2] - (1/tau);
rdual = gradf0 + [lamu1-lamu2; -lamu1-lamu2] + [Atv; zeros(N,1)];
resnorm = norm([rdual; rcent; rpri]);
done = (sdg < pdtol) | (pditer >= pdmaxiter);
disp(sprintf('Iteration = %d, tau = %8.3e, Primal = %8.3e, PDGap = %8.3e, Dual res = %8.3e, Primal res = %8.3e',...
pditer, tau, sum(u), sdg, norm(rdual), norm(rpri)));
if (largescale)
disp(sprintf(' CG Res = %8.3e, CG Iter = %d', cgres, cgiter));
else
disp(sprintf(' H11p condition number = %8.3e', hcond));
end
end
|
github
|
jacksky64/imageProcessing-master
|
perform_tv_correction.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/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
|
perform_windowed_dct_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/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
|
mad.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/mad.m
| 7,921 |
utf_8
|
6d4949e64f7802d97e068c87415b0460
|
function y = mad(x,flag)
%MAD Mean/median absolute deviation.
% Y = MAD(X) returns the mean absolute deviation of the values in X. For
% vector input, Y is MEAN(ABS(X-MEAN(X)). For a matrix input, Y is a row
% vector containing the mean absolute deviation of each column of X. For
% N-D arrays, MAD operates along the first non-singleton dimension.
%
% MAD(X,1) computes Y based on medians, i.e. MEDIAN(ABS(X-MEDIAN(X)).
% MAD(X,0) is the same as MAD(X), and uses means.
%
% MAD treats NaNs as missing values, and removes them.
%
% See also VAR, STD, IQR.
% References:
% [1] L. Sachs, "Applied Statistics: A Handbook of Techniques",
% Springer-Verlag, 1984, page 253.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.10.2.2 $ $Date: 2004/01/24 09:34:28 $
% The output size for [] is a special case, handle it here.
if isequal(x,[])
y = NaN;
return;
end;
if nargin < 2
flag = 0;
end
% Figure out which dimension nanmean will work along.
sz = size(x);
dim = find(sz ~= 1, 1);
if isempty(dim)
dim = 1;
end
% Need to tile the output of nanmean to center X.
tile = ones(1,ndims(x));
tile(dim) = sz(dim);
if flag
% Compute the median of the absolute deviations from the median.
y = nanmedian(abs(x - repmat(nanmedian(x), tile)));
else
% Compute the mean of the absolute deviations from the mean.
y = nanmean(abs(x - repmat(nanmean(x), tile)));
end
function y = nanmedian(x,dim)
%NANMEDIAN Median value, ignoring NaNs.
% M = NANMEDIAN(X) returns the sample median of X, treating NaNs as
% missing values. For vector input, M is the median value of the non-NaN
% elements in X. For matrix input, M is a row vector containing the
% median value of non-NaN elements in each column. For N-D arrays,
% NANMEDIAN operates along the first non-singleton dimension.
%
% NANMEDIAN(X,DIM) takes the median along the dimension DIM of X.
%
% See also MEDIAN, NANMEAN, NANSTD, NANVAR, NANMIN, NANMAX, NANSUM.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.12.2.2 $ $Date: 2004/01/24 09:34:33 $
if nargin == 1
y = prctile(x, 50);
else
y = prctile(x, 50,dim);
end
function m = nanmean(x,dim)
%NANMEAN Mean value, ignoring NaNs.
% M = NANMEAN(X) returns the sample mean of X, treating NaNs as missing
% values. For vector input, M is the mean value of the non-NaN elements
% in X. For matrix input, M is a row vector containing the mean value of
% non-NaN elements in each column. For N-D arrays, NANMEAN operates
% along the first non-singleton dimension.
%
% NANMEAN(X,DIM) takes the mean along the dimension DIM of X.
%
% See also MEAN, NANMEDIAN, NANSTD, NANVAR, NANMIN, NANMAX, NANSUM.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.13.4.2 $ $Date: 2004/01/24 09:34:32 $
% Find NaNs and set them to zero
nans = isnan(x);
x(nans) = 0;
if nargin == 1 % let sum deal with figuring out which dimension to use
% Count up non-NaNs.
n = sum(~nans);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x) ./ n;
else
% Count up non-NaNs.
n = sum(~nans,dim);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x,dim) ./ n;
end
function y = prctile(x,p,dim)
%PRCTILE Percentiles of a sample.
% Y = PRCTILE(X,P) returns percentiles of the values in X. P is a scalar
% or a vector of percent values. When X is a vector, Y is the same size
% as P, and Y(i) contains the P(i)-th percentile. When X is a matrix,
% the i-th row of Y contains the P(i)-th percentiles of each column of X.
% For N-D arrays, PRCTILE operates along the first non-singleton
% dimension.
%
% Y = PRCTILE(X,P,DIM) calculates percentiles along dimension DIM. The
% DIM'th dimension of Y has length LENGTH(P).
%
% Percentiles are specified using percentages, from 0 to 100. For an N
% element vector X, PRCTILE computes percentiles as follows:
% 1) The sorted values in X are taken as the 100*(0.5/N), 100*(1.5/N),
% ..., 100*((N-0.5)/N) percentiles.
% 2) Linear interpolation is used to compute percentiles for percent
% values between 100*(0.5/N) and 100*((N-0.5)/N)
% 3) The minimum or maximum values in X are assigned to percentiles
% for percent values outside that range.
%
% PRCTILE treats NaNs as missing values, and removes them.
%
% Examples:
% y = prctile(x,50); % the median of x
% y = prctile(x,[2.5 25 50 75 97.5]); % a useful summary of x
%
% See also IQR, MEDIAN, NANMEDIAN, QUANTILE.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.12.4.4 $ $Date: 2004/01/24 09:34:55 $
if ~isvector(p) || numel(p) == 0
error('stats:prctile:BadPercents', ...
'P must be a scalar or a non-empty vector.');
elseif any(p < 0 | p > 100)
error('stats:prctile:BadPercents', ...
'P must take values between 0 and 100');
end
% Figure out which dimension prctile will work along.
sz = size(x);
if nargin < 3
dim = find(sz ~= 1,1);
if isempty(dim)
dim = 1;
end
dimArgGiven = false;
else
% Permute the array so that the requested dimension is the first dim.
nDimsX = ndims(x);
perm = [dim:max(nDimsX,dim) 1:dim-1];
x = permute(x,perm);
% Pad with ones if dim > ndims.
if dim > nDimsX
sz = [sz ones(1,dim-nDimsX)];
end
sz = sz(perm);
dim = 1;
dimArgGiven = true;
end
% If X is empty, return all NaNs.
if isempty(x)
if isequal(x,[]) && ~dimArgGiven
y = nan(size(p),class(x));
else
szout = sz; szout(dim) = numel(p);
y = nan(szout,class(x));
end
else
% Drop X's leading singleton dims, and combine its trailing dims. This
% leaves a matrix, and we can work along columns.
nrows = sz(dim);
ncols = prod(sz) ./ nrows;
x = reshape(x, nrows, ncols);
x = sort(x,1);
nonnans = ~isnan(x);
% If there are no NaNs, do all cols at once.
if all(nonnans(:))
n = sz(dim);
if isequal(p,50) % make the median fast
if rem(n,2) % n is odd
y = x((n+1)/2,:);
else % n is even
y = (x(n/2,:) + x(n/2+1,:))/2;
end
else
q = [0 100*(0.5:(n-0.5))./n 100]';
xx = [x(1,:); x(1:n,:); x(n,:)];
y = zeros(numel(p), ncols, class(x));
y(:,:) = interp1q(q,xx,p(:));
end
% If there are NaNs, work on each column separately.
else
% Get percentiles of the non-NaN values in each column.
y = nan(numel(p), ncols, class(x));
for j = 1:ncols
nj = find(nonnans(:,j),1,'last');
if nj > 0
if isequal(p,50) % make the median fast
if rem(nj,2) % nj is odd
y(:,j) = x((nj+1)/2,j);
else % nj is even
y(:,j) = (x(nj/2,j) + x(nj/2+1,j))/2;
end
else
q = [0 100*(0.5:(nj-0.5))./nj 100]';
xx = [x(1,j); x(1:nj,j); x(nj,j)];
y(:,j) = interp1q(q,xx,p(:));
end
end
end
end
% Reshape Y to conform to X's original shape and size.
szout = sz; szout(dim) = numel(p);
y = reshape(y,szout);
end
% undo the DIM permutation
if dimArgGiven
y = ipermute(y,perm);
end
% If X is a vector, the shape of Y should follow that of P, unless an
% explicit DIM arg was given.
if ~dimArgGiven && isvector(x)
y = reshape(y,size(p));
end
|
github
|
jacksky64/imageProcessing-master
|
perform_wavelet_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/perform_wavelet_transform.m
| 61,619 |
utf_8
|
9e8ee118ad0e2225d236b242630cc67a
|
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 Peyre
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
|
pdco.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_sparsity/toolbox/pdco.m
| 54,786 |
utf_8
|
24b840a986d1c21cadf453a476c677e6
|
function [x,y,z,inform,PDitns,CGitns,time] = ...
pdco( Fname,Aname,b,bl,bu,d1,d2,options,x0,y0,z0,xsize,zsize )
%-----------------------------------------------------------------------
% pdco.m: Primal-Dual Barrier Method for Convex Objectives (23 Sep 2003)
%-----------------------------------------------------------------------
% [x,y,z,inform,PDitns,CGitns,time] = ...
% pdco(Fname,Aname,b,bl,bu,d1,d2,options,x0,y0,z0,xsize,zsize);
%
% solves optimization problems of the form
%
% minimize phi(x) + 1/2 norm(D1*x)^2 + 1/2 norm(r)^2
% x,r
% subject to A*x + D2*r = b, bl <= x <= bu, r unconstrained,
%
% where
% phi(x) is a smooth convex function defined by function Fname;
% A is an m x n matrix defined by matrix or function Aname;
% b is a given m-vector;
% D1, D2 are positive-definite diagonal matrices defined from d1, d2.
% In particular, d2 indicates the accuracy required for
% satisfying each row of Ax = b.
%
% D1 and D2 (via d1 and d2) provide primal and dual regularization
% respectively. They ensure that the primal and dual solutions
% (x,r) and (y,z) are unique and bounded.
%
% A scalar d1 is equivalent to d1 = ones(n,1), D1 = diag(d1).
% A scalar d2 is equivalent to d2 = ones(m,1), D2 = diag(d2).
% Typically, d1 = d2 = 1e-4.
% These values perturb phi(x) only slightly (by about 1e-8) and request
% that A*x = b be satisfied quite accurately (to about 1e-8).
% Set d1 = 1e-4, d2 = 1 for least-squares problems with bound constraints.
% The problem is then equivalent to
%
% minimize phi(x) + 1/2 norm(d1*x)^2 + 1/2 norm(A*x - b)^2
% subject to bl <= x <= bu.
%
% More generally, d1 and d2 may be n and m vectors containing any positive
% values (preferably not too small, and typically no larger than 1).
% Bigger elements of d1 and d2 improve the stability of the solver.
%
% At an optimal solution, if x(j) is on its lower or upper bound,
% the corresponding z(j) is positive or negative respectively.
% If x(j) is between its bounds, z(j) = 0.
% If bl(j) = bu(j), x(j) is fixed at that value and z(j) may have
% either sign.
%
% Also, r and y satisfy r = D2 y, so that Ax + D2^2 y = b.
% Thus if d2(i) = 1e-4, the i-th row of Ax = b will be satisfied to
% approximately 1e-8. This determines how large d2(i) can safely be.
%
%
% EXTERNAL FUNCTIONS:
% options = pdcoSet; provided with pdco.m
% [obj,grad,hess] = Fname( x ); provided by user
% y = Aname( name,mode,m,n,x ); provided by user if pdMat
% is a string, not a matrix
%
% INPUT ARGUMENTS:
% Fname may be an explicit n x 1 column vector c,
% or a string containing the name of a function Fname.m
%%%!!! Revised 12/16/04 !!!
% (Fname cannot be a function handle)
% such that [obj,grad,hess] = Fname(x) defines
% obj = phi(x) : a scalar,
% grad = gradient of phi(x) : an n-vector,
% hess = diag(Hessian of phi): an n-vector.
% Examples:
% If phi(x) is the linear function c'*x, Fname could be
% be the vector c, or the name or handle of a function
% that returns
% [obj,grad,hess] = [c'*x, c, zeros(n,1)].
% If phi(x) is the entropy function E(x) = sum x(j) log x(j),
% Fname should return
% [obj,grad,hess] = [E(x), log(x)+1, 1./x].
% Aname may be an explicit m x n matrix A (preferably sparse!),
% or a string containing the name of a function Aname.m
%%%!!! Revised 12/16/04 !!!
% (Aname cannot be a function handle)
% such that y = aname( name,mode,m,n,x )
% returns y = A*x (mode=1) or y = A'*x (mode=2).
% The input parameter "name" will be the string 'Aname'
% or whatever the name of the actual function is.
% b is an m-vector.
% bl is an n-vector of lower bounds. Non-existent bounds
% may be represented by bl(j) = -Inf or bl(j) <= -1e+20.
% bu is an n-vector of upper bounds. Non-existent bounds
% may be represented by bu(j) = Inf or bu(j) >= 1e+20.
% d1, d2 may be positive scalars or positive vectors (see above).
% options is a structure that may be set and altered by pdcoSet
% (type help pdcoSet).
% x0, y0, z0 provide an initial solution.
% xsize, zsize are estimates of the biggest x and z at the solution.
% They are used to scale (x,y,z). Good estimates
% should improve the performance of the barrier method.
%
%
% OUTPUT ARGUMENTS:
% x is the primal solution.
% y is the dual solution associated with Ax + D2 r = b.
% z is the dual solution associated with bl <= x <= bu.
% inform = 0 if a solution is found;
% = 1 if too many iterations were required;
% = 2 if the linesearch failed too often.
% = 3 if the step lengths became too small.
% PDitns is the number of Primal-Dual Barrier iterations required.
% CGitns is the number of Conjugate-Gradient iterations required
% if an iterative solver is used (LSQR).
% time is the cpu time used.
%----------------------------------------------------------------------
% PRIVATE FUNCTIONS:
% pdxxxbounds
% pdxxxdistrib
% pdxxxlsqr
% pdxxxlsqrmat
% pdxxxmat
% pdxxxmerit
% pdxxxresid1
% pdxxxresid2
% pdxxxstep
%
% GLOBAL VARIABLES:
% global pdDDD1 pdDDD2 pdDDD3
%
%
% NOTES:
% The matrix A should be reasonably well scaled: norm(A,inf) =~ 1.
% The vector b and objective phi(x) may be of any size, but ensure that
% xsize and zsize are reasonably close to norm(x,inf) and norm(z,inf)
% at the solution.
%
% The files defining Fname and Aname
% must not be called Fname.m or Aname.m!!
%
%
% AUTHOR:
% Michael Saunders, Systems Optimization Laboratory (SOL),
% Stanford University, Stanford, California, USA.
% [email protected]
%
% CONTRIBUTORS:
% Byunggyoo Kim, Samsung, Seoul, Korea.
% [email protected]
%
% DEVELOPMENT:
% 20 Jun 1997: Original version of pdsco.m derived from pdlp0.m.
% 29 Sep 2002: Original version of pdco.m derived from pdsco.m.
% Introduced D1, D2 in place of gamma*I, delta*I
% and allowed for general bounds bl <= x <= bu.
% 06 Oct 2002: Allowed for fixed variabes: bl(j) = bu(j) for any j.
% 15 Oct 2002: Eliminated some work vectors (since m, n might be LARGE).
% Modularized residuals, linesearch
% 16 Oct 2002: pdxxx..., pdDDD... names rationalized.
% pdAAA eliminated (global copy of A).
% Aname is now used directly as an explicit A or a function.
% NOTE: If Aname is a function, it now has an extra parameter.
% 23 Oct 2002: Fname and Aname can now be function handles.
% 01 Nov 2002: Bug fixed in feval in pdxxxmat.
% 19 Apr 2003: Bug fixed in pdxxxbounds.
% 07 Aug 2003: Let d1, d2 be scalars if input that way.
% 10 Aug 2003: z isn't needed except at the end for output.
% 10 Aug 2003: mu0 is now an absolute value -- the initial mu.
% 13 Aug 2003: Access only z1(low) and z2(upp) everywhere.
% stepxL, stepxU introduced to keep x within bounds.
% (With poor starting points, dx may take x outside,
% where phi(x) may not be defined.
% Entropy once gave complex values for the gradient!)
% 16 Sep 2003: Fname can now be a vector c, implying a linear obj c'*x.
% 19 Sep 2003: Large system K4 dv = rhs implemented.
% 23 Sep 2003: Options LSproblem and LSmethod replaced by Method.
% 18 Nov 2003: stepxL, stepxU gave trouble on lptest (see 13 Aug 2003).
% Disabled them for now. Nonlinear problems need good x0.
% 19 Nov 2003: Bugs with x(fix) and z(fix).
% In particular, x(fix) = bl(fix) throughout, so Objective
% in iteration log is correct for LPs with explicit c vector.
%-----------------------------------------------------------------------
global pdDDD1 pdDDD2 pdDDD3
if 0
myprintf('\n --------------------------------------------------------')
myprintf('\n pdco.m Version of 19 Nov 2003')
myprintf('\n Primal-dual barrier method to minimize a convex function')
myprintf('\n subject to linear constraints Ax + r = b, bl <= x <= bu')
myprintf('\n --------------------------------------------------------\n')
end
m = length(b);
n = length(bl);
%---------------------------------------------------------------------
% Decode Fname.
%---------------------------------------------------------------------
%%%!!! Revised 12/16/04 !!!
% Fname cannot be a function handle
operator = ischar(Fname);
explicitF = ~operator;
if explicitF
myprintf('\n')
mydisp('The objective is linear')
else
fname = Fname;
myprintf('\n')
mydisp(['The objective function is named ' fname])
end
%---------------------------------------------------------------------
% Decode Aname.
%---------------------------------------------------------------------
%%%!!! Revised 12/16/04 !!!
% Aname cannot be a function handle
operator = ischar(Aname) || isa(Aname, 'function_handle');
explicitA = ~operator;
if explicitA % assume Aname is an explicit matrix A.
nnzA = nnz(Aname);
if issparse(Aname)
myprintf('The matrix A is an explicit sparse matrix')
else
myprintf('The matrix A is an explicit dense matrix' )
end
myprintf('\n\nm = %8g n = %8g nnz(A) =%9g', m,n,nnzA)
else
if ischar(Aname)
mydisp(['The matrix A is an operator defined by ' Aname])
end
myprintf('\nm = %8g n = %8g', m,n)
end
normb = norm(b ,inf); normx0 = norm(x0,inf);
normy0 = norm(y0,inf); normz0 = norm(z0,inf);
myprintf('\nmax |b | = %8g max |x0| = %8.1e', normb , normx0)
myprintf( ' xsize = %8.1e', xsize)
myprintf('\nmax |y0| = %8g max |z0| = %8.1e', normy0, normz0)
myprintf( ' zsize = %8.1e', zsize)
%---------------------------------------------------------------------
% Initialize.
%---------------------------------------------------------------------
true = 1;
false = 0;
zn = zeros(n,1);
nb = n + m;
nkkt = nb;
CGitns = 0;
inform = 0;
% 07 Aug 2003: No need for next lines.
%if length(d1)==1, d1 = d1*ones(n,1); end % Allow scalar d1, d2
%if length(d2)==1, d2 = d2*ones(m,1); end % to mean d1*e, d2*e
%---------------------------------------------------------------------
% Grab input options.
%---------------------------------------------------------------------
maxitn = options.MaxIter;
featol = options.FeaTol;
opttol = options.OptTol;
steptol = options.StepTol;
stepSame = options.StepSame; % 1 means stepx==stepz
x0min = options.x0min;
z0min = options.z0min;
mu0 = options.mu0;
Method = options.Method;
itnlim = options.LSQRMaxIter * min(m,n);
atol1 = options.LSQRatol1; % Initial atol
atol2 = options.LSQRatol2; % Smallest atol, unless atol1 is smaller
conlim = options.LSQRconlim;
wait = options.wait;
%---------------------------------------------------------------------
% Set other parameters.
%---------------------------------------------------------------------
kminor = 0; % 1 stops after each iteration
eta = 1e-4; % Linesearch tolerance for "sufficient descent"
maxf = 10; % Linesearch backtrack limit (function evaluations)
maxfail = 1; % Linesearch failure limit (consecutive iterations)
bigcenter = 1e+3; % mu is reduced if center < bigcenter
thresh = 1e-8; % For sparse LU with Method=41
% Parameters for LSQR.
atolmin = eps; % Smallest atol if linesearch back-tracks
btol = 0; % Should be small (zero is ok)
show = false; % Controls LSQR iteration log
gamma = max(d1);
delta = max(d2);
myprintf('\n\nx0min = %8g featol = %8.1e', x0min, featol)
myprintf( ' d1max = %8.1e', gamma)
myprintf( '\nz0min = %8g opttol = %8.1e', z0min, opttol)
myprintf( ' d2max = %8.1e', delta)
myprintf( '\nmu0 = %8.1e steptol = %8g', mu0 , steptol)
myprintf( ' bigcenter= %8g' , bigcenter)
myprintf('\n\nLSQR:')
myprintf('\natol1 = %8.1e atol2 = %8.1e', atol1 , atol2 )
myprintf( ' btol = %8.1e', btol )
myprintf('\nconlim = %8.1e itnlim = %8g' , conlim, itnlim)
myprintf( ' show = %8g' , show )
% Method = 3; %%% Hardwire LSQR
% Method = 41; %%% Hardwire K4 and sparse LU
myprintf('\n\nMethod = %8g (1=chol 2=QR 3=LSQR 41=K4)', Method)
if wait
myprintf('\n\nReview parameters... then type "return"\n')
keyboard
end
if eta < 0
myprintf('\n\nLinesearch disabled by eta < 0')
end
%---------------------------------------------------------------------
% All parameters have now been set.
% Check for valid Method.
%---------------------------------------------------------------------
time = cputime;
if operator
if Method==3
% relax
else
myprintf('\n\nWhen A is an operator, we have to use Method = 3')
Method = 3;
end
end
if Method== 1, solver = ' Chol'; head3 = ' Chol';
elseif Method== 2, solver = ' QR'; head3 = ' QR';
elseif Method== 3, solver = ' LSQR'; head3 = ' atol LSQR Inexact';
elseif Method==41, solver = ' LU'; head3 = ' L U res';
else error('Method must be 1, 2, 3, or 41')
end
%---------------------------------------------------------------------
% Categorize bounds and allow for fixed variables by modifying b.
%---------------------------------------------------------------------
[low,upp,fix] = pdxxxbounds( bl,bu );
nfix = length(fix);
if nfix > 0
x1 = zn; x1(fix) = bl(fix);
r1 = pdxxxmat( Aname, 1, m, n, x1 );
b = b - r1;
% At some stage, might want to look at normfix = norm(r1,inf);
end
%---------------------------------------------------------------------
% Scale the input data.
% The scaled variables are
% xbar = x/beta,
% ybar = y/zeta,
% zbar = z/zeta.
% Define
% theta = beta*zeta;
% The scaled function is
% phibar = ( 1 /theta) fbar(beta*xbar),
% gradient = (beta /theta) grad,
% Hessian = (beta2/theta) hess.
%---------------------------------------------------------------------
beta = xsize; if beta==0, beta = 1; end % beta scales b, x.
zeta = zsize; if zeta==0, zeta = 1; end % zeta scales y, z.
theta = beta*zeta; % theta scales obj.
% (theta could be anything, but theta = beta*zeta makes
% scaled grad = grad/zeta = 1 approximately if zeta is chosen right.)
bl(fix)= bl(fix)/beta;
bu(fix)= bu(fix)/beta;
bl(low)= bl(low)/beta;
bu(upp)= bu(upp)/beta;
d1 = d1*( beta/sqrt(theta) );
d2 = d2*( sqrt(theta)/beta );
beta2 = beta^2;
b = b /beta; y0 = y0/zeta;
x0 = x0/beta; z0 = z0/zeta;
%---------------------------------------------------------------------
% Initialize vectors that are not fully used if bounds are missing.
%---------------------------------------------------------------------
rL = zn; rU = zn;
cL = zn; cU = zn;
x1 = zn; x2 = zn;
z1 = zn; z2 = zn;
dx1 = zn; dx2 = zn;
dz1 = zn; dz2 = zn;
clear zn
%---------------------------------------------------------------------
% Initialize x, y, z1, z2, objective, etc.
% 10 Aug 2003: z isn't needed here -- just at end for output.
%---------------------------------------------------------------------
x = x0;
y = y0;
x(fix) = bl(fix);
x(low) = max( x(low) , bl(low));
x(upp) = min( x(upp) , bu(upp));
x1(low)= max( x(low) - bl(low), x0min );
x2(upp)= max(bu(upp) - x(upp), x0min );
z1(low)= max( z0(low) , z0min );
z2(upp)= max(-z0(upp) , z0min );
clear x0 y0 z0
%%%%%%%%%% Assume hess is diagonal for now. %%%%%%%%%%%%%%%%%%
if explicitF
obj = (Fname'*x)*beta; grad = Fname; hess = zeros(n,1);
else
[obj,grad,hess] = feval( Fname, (x*beta) );
end
obj = obj /theta; % Scaled obj.
grad = grad*(beta /theta) + (d1.^2).*x;% grad includes x regularization.
H = hess*(beta2/theta) + (d1.^2); % H includes x regularization.
%---------------------------------------------------------------------
% Compute primal and dual residuals:
% r1 = b - A*x - d2.^2*y
% r2 = grad - A'*y + (z2-z1)
% rL = bl - x + x1
% rU = -bu + x + x2
%---------------------------------------------------------------------
[r1,r2,rL,rU,Pinf,Dinf] = ...
pdxxxresid1( Aname,fix,low,upp, ...
b,bl,bu,d1,d2,grad,rL,rU,x,x1,x2,y,z1,z2 );
%---------------------------------------------------------------------
% Initialize mu and complementarity residuals:
% cL = mu*e - X1*z1.
% cU = mu*e - X2*z2.
%
% 25 Jan 2001: Now that b and obj are scaled (and hence x,y,z),
% we should be able to use mufirst = mu0 (absolute value).
% 0.1 worked poorly on StarTest1 with x0min = z0min = 0.1.
% 29 Jan 2001: We might as well use mu0 = x0min * z0min;
% so that most variables are centered after a warm start.
% 29 Sep 2002: Use mufirst = mu0*(x0min * z0min),
% regarding mu0 as a scaling of the initial center.
% 07 Aug 2003: mulast is controlled by opttol.
% mufirst should not be smaller.
% 10 Aug 2003: Revert to mufirst = mu0 (absolute value).
%---------------------------------------------------------------------
% mufirst = mu0*(x0min * z0min);
mufirst = mu0;
mulast = 0.1 * opttol;
mufirst = max( mufirst, mulast );
mu = mufirst;
[cL,cU,center,Cinf,Cinf0] = ...
pdxxxresid2( mu,low,upp,cL,cU,x1,x2,z1,z2 );
fmerit = pdxxxmerit( low,upp,r1,r2,rL,rU,cL,cU );
% Initialize other things.
PDitns = 0;
converged = 0;
atol = atol1;
atol2 = max( atol2, atolmin );
atolmin = atol2;
pdDDD2 = d2; % Global vector for diagonal matrix D2
% Iteration log.
stepx = 0;
stepz = 0;
nf = 0;
itncg = 0;
nfail = 0;
head1 = '\n\nItn mu stepx stepz Pinf Dinf';
head2 = ' Cinf Objective nf center';
myprintf([ head1 head2 head3 ])
regterm = norm(d1.*x)^2 + norm(d2.*y)^2;
objreg = obj + 0.5*regterm;
objtrue = objreg * theta;
myprintf('\n%3g ', PDitns )
myprintf('%6.1f%6.1f' , log10(Pinf ), log10(Dinf))
myprintf('%6.1f%15.7e', log10(Cinf0), objtrue )
myprintf(' %8.1f' , center )
if Method==41
myprintf(' thresh=%7.1e', thresh)
end
if kminor
myprintf('\n\nStart of first minor itn...\n')
keyboard
end
%---------------------------------------------------------------------
% Main loop.
%---------------------------------------------------------------------
while ~converged
PDitns = PDitns + 1;
% 31 Jan 2001: Set atol according to progress, a la Inexact Newton.
% 07 Feb 2001: 0.1 not small enough for Satellite problem. Try 0.01.
% 25 Apr 2001: 0.01 seems wasteful for Star problem.
% Now that starting conditions are better, go back to 0.1.
r3norm = max([Pinf Dinf Cinf]);
atol = min([atol r3norm*0.1]);
atol = max([atol atolmin ]);
if Method<=3
%-----------------------------------------------------------------
% Solve (*) for dy.
%-----------------------------------------------------------------
% Define a damped Newton iteration for solving f = 0,
% keeping x1, x2, z1, z2 > 0. We eliminate dx1, dx2, dz1, dz2
% to obtain the system
%
% [-H2 A' ] [dx] = [w ], H2 = H + D1^2 + X1inv Z1 + X2inv Z2,
% [ A D2^2] [dy] = [r1] w = r2 - X1inv(cL + Z1 rL)
% + X2inv(cU + Z2 rU),
%
% which is equivalent to the least-squares problem
%
% min || [ D A']dy - [ D w ] ||, D = H2^{-1/2}. (*)
% || [ D2 ] [D2inv r1] ||
%-----------------------------------------------------------------
H(low) = H(low) + z1(low)./x1(low);
H(upp) = H(upp) + z2(upp)./x2(upp);
w = r2;
w(low) = w(low) - (cL(low) + z1(low).*rL(low))./x1(low);
w(upp) = w(upp) + (cU(upp) + z2(upp).*rU(upp))./x2(upp);
H = 1./H; % H is now Hinv (NOTE!)
H(fix) = 0;
D = sqrt(H);
pdDDD1 = D;
rw = [explicitA Method m n 0 0 0]; % Passed to LSQR.
if Method==1
% --------------------------------------------------------------
% Use chol to get dy
% --------------------------------------------------------------
AD = Aname*sparse( 1:n, 1:n, D, n, n );
ADDA = AD*AD' + sparse( 1:m, 1:m, (d2.^2), m, m );
if PDitns==1, P = symamd(ADDA); end % Do ordering only once.
[R,indef] = chol(ADDA(P,P));
if indef
myprintf('\n\n chol says AD^2A'' is not pos def')
myprintf('\n Use bigger d2, or set options.Method = 2 or 3')
break
end
% dy = ADDA \ rhs;
rhs = Aname*(H.*w) + r1;
dy = R \ (R'\rhs(P));
dy(P) = dy;
elseif Method==2
% --------------------------------------------------------------
% Use QR to get dy
% --------------------------------------------------------------
DAt = sparse( 1:n, 1:n, D, n, n )*(Aname');
if PDitns==1, P = colamd(DAt); end % Do ordering only once.
if length(d2)==1
D2 = d2*speye(m);
else
D2 = spdiags(d2,0,m,m);
end
DAt = [ DAt; D2 ];
rhs = [ D.*w; r1./d2 ];
% dy = DAt \ rhs;
[rhs,R] = qr(DAt(:,P),rhs,0);
dy = R \ rhs;
dy(P) = dy;
else
% --------------------------------------------------------------
% Method=3. Use LSQR (iterative solve) to get dy
% --------------------------------------------------------------
rhs = [ D.*w; r1./d2 ];
damp = 0;
if explicitA % A is a sparse matrix.
precon = true;
if precon % Construct diagonal preconditioner for LSQR
AD = Aname*sparse( 1:n, 1:n, D, n, n );
AD = AD.^2;
wD = sum(AD,2); % Sum of sqrs of each row of AD. %(Sparse)
wD = sqrt( full(wD) + (d2.^2) ); %(Dense)
pdDDD3 = 1./wD;
clear AD wD
end
else % A is an operator
precon = false;
end
rw(7) = precon;
info.atolmin = atolmin;
info.r3norm = fmerit; % Must be the 2-norm here.
[ dy, istop, itncg, outfo ] = ...
pdxxxlsqr( nb,m,'pdxxxlsqrmat',Aname,rw,rhs,damp, ...
atol,btol,conlim,itnlim,show,info );
if precon, dy = pdDDD3 .* dy; end
if istop==3 | istop==7 % conlim or itnlim
myprintf('\n LSQR stopped early: istop = %3d', istop)
end
atolold = outfo.atolold;
atol = outfo.atolnew;
r3ratio = outfo.r3ratio;
CGitns = CGitns + itncg;
end % computation of dy
% dy is now known. Get dx, dx1, dx2, dz1, dz2.
grad = pdxxxmat( Aname,2,m,n,dy ); % grad = A'dy
grad(fix) = 0; % Is this needed? % grad is a work vector
dx = H .* (grad - w);
dx1(low) = - rL(low) + dx(low);
dx2(upp) = - rU(upp) - dx(upp);
dz1(low) = (cL(low) - z1(low).*dx1(low)) ./ x1(low);
dz2(upp) = (cU(upp) - z2(upp).*dx2(upp)) ./ x2(upp);
elseif Method==41
%-----------------------------------------------------------------
% Solve the symmetric-structure 4 x 4 system K4 dv = t:
%
% ( X1 Z1 ) [dz1] = [tL], tL = cL + Z1 rL
% ( X2 -Z2 ) [dz2] [tU] tU = cU + Z2 rU
% ( I -I -H1 A' ) [dx ] [r2]
% ( A D2^2 ) [dy ] [r1]
%-----------------------------------------------------------------
X1 = ones(n,1); X1(low) = x1(low);
X2 = ones(n,1); X2(upp) = x2(upp);
if length(d2)==1
D22 = d2^2*speye(m);
else
D22 = spdiags(d2.^2,0,m,m);
end
Onn = sparse(n,n);
Omn = sparse(m,n);
if PDitns==1 % First time through: Choose LU ordering from
% lower-triangular part of dummy K4
I1 = sparse( low, low, ones(length(low),1), n, n );
I2 = sparse( upp, upp, ones(length(upp),1), n, n );
K4 =[speye(n) Onn Onn Omn'
Onn speye(n) Onn Omn'
I1 I2 speye(n) Omn'
Omn Omn Aname speye(m)];
p = symamd(K4);
% mydisp(' '); keyboard
end
K4 = [spdiags(X1,0,n,n) Onn spdiags(z1,0,n,n) Omn'
Onn spdiags(X2,0,n,n) -spdiags(z2,0,n,n) Omn'
I1 -I2 -spdiags(H,0,n,n) Aname'
Omn Omn Aname D22];
tL = zeros(n,1); tL(low) = cL(low) + z1(low).*rL(low);
tU = zeros(n,1); tU(upp) = cU(upp) + z2(upp).*rU(upp);
rhs = [tL; tU; r2; r1];
% dv = K4 \ rhs; % BIG SYSTEM!
[L,U,P] = lu( K4(p,p), thresh ); % P K4 = L U
dv = U \ (L \ (P*rhs(p)));
dv(p) = dv;
resK4 = norm((K4*dv - rhs),inf) / norm(rhs,inf);
dz1 = dv( 1: n);
dz2 = dv( n+1:2*n);
dx = dv(2*n+1:3*n);
dy = dv(3*n+1:3*n+m);
dx1(low) = - rL(low) + dx(low);
dx2(upp) = - rU(upp) - dx(upp);
end
%-------------------------------------------------------------------
% Find the maximum step.
% 13 Aug 2003: We need stepxL, stepxU also to keep x feasible
% so that nonlinear functions are defined.
% 18 Nov 2003: But this gives stepx = 0 for lptest. (??)
%--------------------------------------------------------------------
stepx1 = pdxxxstep( x1(low), dx1(low) );
stepx2 = pdxxxstep( x2(upp), dx2(upp) );
stepz1 = pdxxxstep( z1(low), dz1(low) );
stepz2 = pdxxxstep( z2(upp), dz2(upp) );
% stepxL = pdxxxstep( x(low), dx(low) );
% stepxU = pdxxxstep( x(upp), dx(upp) );
% stepx = min( [stepx1, stepx2, stepxL, stepxU] );
stepx = min( [stepx1, stepx2] );
stepz = min( [stepz1, stepz2] );
stepx = min( [steptol*stepx, 1] );
stepz = min( [steptol*stepz, 1] );
if stepSame % For NLPs, force same step
stepx = min( stepx, stepz ); % (true Newton method)
stepz = stepx;
end
%-------------------------------------------------------------------
% Backtracking linesearch.
%-------------------------------------------------------------------
fail = true;
nf = 0;
while nf < maxf
nf = nf + 1;
x = x + stepx * dx;
y = y + stepz * dy;
x1(low) = x1(low) + stepx * dx1(low);
x2(upp) = x2(upp) + stepx * dx2(upp);
z1(low) = z1(low) + stepz * dz1(low);
z2(upp) = z2(upp) + stepz * dz2(upp);
if explicitF
obj = (Fname'*x)*beta; grad = Fname; hess = zeros(n,1);
else
[obj,grad,hess] = feval( Fname, (x*beta) );
end
obj = obj /theta;
grad = grad*(beta /theta) + (d1.^2).*x;
H = hess*(beta2/theta) + (d1.^2);
[r1,r2,rL,rU,Pinf,Dinf] = ...
pdxxxresid1( Aname,fix,low,upp, ...
b,bl,bu,d1,d2,grad,rL,rU,x,x1,x2,y,z1,z2 );
[cL,cU,center,Cinf,Cinf0] = ...
pdxxxresid2( mu,low,upp,cL,cU,x1,x2,z1,z2 );
fmeritnew = pdxxxmerit( low,upp,r1,r2,rL,rU,cL,cU );
step = min( stepx, stepz );
if fmeritnew <= (1 - eta*step)*fmerit
fail = false;
break;
end
% Merit function didn't decrease.
% Restore variables to previous values.
% (This introduces a little error, but save lots of space.)
x = x - stepx * dx;
y = y - stepz * dy;
x1(low) = x1(low) - stepx * dx1(low);
x2(upp) = x2(upp) - stepx * dx2(upp);
z1(low) = z1(low) - stepz * dz1(low);
z2(upp) = z2(upp) - stepz * dz2(upp);
% Back-track.
% If it's the first time,
% make stepx and stepz the same.
if nf==1 & stepx~=stepz
stepx = step;
elseif nf < maxf
stepx = stepx/2;
end;
stepz = stepx;
end
if fail
myprintf('\n Linesearch failed (nf too big)');
nfail = nfail + 1;
else
nfail = 0;
end
%-------------------------------------------------------------------
% Set convergence measures.
%--------------------------------------------------------------------
regterm = norm(d1.*x)^2 + norm(d2.*y)^2;
objreg = obj + 0.5*regterm;
objtrue = objreg * theta;
primalfeas = Pinf <= featol;
dualfeas = Dinf <= featol;
complementary = Cinf0 <= opttol;
enough = PDitns>= 4; % Prevent premature termination.
converged = primalfeas & dualfeas & complementary & enough;
%-------------------------------------------------------------------
% Iteration log.
%-------------------------------------------------------------------
str1 = sprintf('\n%3g%5.1f' , PDitns , log10(mu) );
str2 = sprintf('%6.3f%6.3f' , stepx , stepz );
if stepx < 0.001 | stepz < 0.001
str2 = sprintf('%6.1e%6.1e' , stepx , stepz );
end
str3 = sprintf('%6.1f%6.1f' , log10(Pinf) , log10(Dinf));
str4 = sprintf('%6.1f%15.7e', log10(Cinf0), objtrue );
str5 = sprintf('%3g%8.1f' , nf , center );
if center > 99999
str5 = sprintf('%3g%8.1e' , nf , center );
end
myprintf([str1 str2 str3 str4 str5])
if Method== 1
if PDitns==1, myprintf(' %8g', nnz(R)); end
elseif Method== 2
if PDitns==1, myprintf(' %8g', nnz(R)); end
elseif Method== 3
myprintf(' %5.1f%7g%7.3f', log10(atolold), itncg, r3ratio)
elseif Method==41,
resK4 = max( resK4, 1e-99 );
myprintf(' %8g%8g%6.1f', nnz(L),nnz(U),log10(resK4))
end
%-------------------------------------------------------------------
% Test for termination.
%-------------------------------------------------------------------
if kminor
myprintf( '\nStart of next minor itn...\n')
keyboard
end
if converged
myprintf('\nConverged')
elseif PDitns >= maxitn
myprintf('\nToo many iterations')
inform = 1;
break
elseif nfail >= maxfail
myprintf('\nToo many linesearch failures')
inform = 2;
break
elseif step <= 1e-10
myprintf('\nStep lengths too small')
inform = 3;
break
else
% Reduce mu, and reset certain residuals.
stepmu = min( stepx , stepz );
stepmu = min( stepmu, steptol );
muold = mu;
mu = mu - stepmu * mu;
if center >= bigcenter, mu = muold; end
% mutrad = mu0*(sum(Xz)/n); % 24 May 1998: Traditional value, but
% mu = min(mu,mutrad ); % it seemed to decrease mu too much.
mu = max(mu,mulast); % 13 Jun 1998: No need for smaller mu.
[cL,cU,center,Cinf,Cinf0] = ...
pdxxxresid2( mu,low,upp,cL,cU,x1,x2,z1,z2 );
fmerit = pdxxxmerit( low,upp,r1,r2,rL,rU,cL,cU );
% Reduce atol for LSQR (and SYMMLQ).
% NOW DONE AT TOP OF LOOP.
atolold = atol;
% if atol > atol2
% atolfac = (mu/mufirst)^0.25;
% atol = max( atol*atolfac, atol2 );
% end
% atol = min( atol, mu ); % 22 Jan 2001: a la Inexact Newton.
% atol = min( atol, 0.5*mu ); % 30 Jan 2001: A bit tighter
% If the linesearch took more than one function (nf > 1),
% we assume the search direction needed more accuracy
% (though this may be true only for LPs).
% 12 Jun 1998: Ask for more accuracy if nf > 2.
% 24 Nov 2000: Also if the steps are small.
% 30 Jan 2001: Small steps might be ok with warm start.
% 06 Feb 2001: Not necessarily. Reinstated tests in next line.
if nf > 2 | step <= 0.01
atol = atolold*0.1;
end
end
end
%---------------------------------------------------------------------
% End of main loop.
%---------------------------------------------------------------------
% Print statistics.
x(fix) = 0; % Exclude x(fix) temporarily from |x|.
z = zeros(n,1); % Exclude z(fix) also.
z(low) = z1(low);
z(upp) = z(upp) - z2(upp);
myprintf('\n\nmax |x| =%10.3f', norm(x,inf))
myprintf(' max |y| =%10.3f', norm(y,inf))
myprintf(' max |z| =%10.3f', norm(z,inf)) % excludes z(fix)
myprintf(' scaled')
bl(fix)= bl(fix)*beta; % Unscale bl, bu, x, y, z.
bu(fix)= bu(fix)*beta;
bl(low)= bl(low)*beta;
bu(upp)= bu(upp)*beta;
x = x*beta; y = y*zeta; z = z*zeta;
myprintf( '\nmax |x| =%10.3f', norm(x,inf))
myprintf(' max |y| =%10.3f', norm(y,inf))
myprintf(' max |z| =%10.3f', norm(z,inf)) % excludes z(fix)
myprintf(' unscaled')
x(fix) = bl(fix); % Reinstate x(fix).
% Reconstruct b.
b = b *beta;
if nfix > 0
x1 = zeros(n,1); x1(fix) = bl(fix);
r1 = pdxxxmat( Aname, 1, m, n, x1 );
b = b + r1;
myprintf('\nmax |x| and max |z| exclude fixed variables')
end
% Evaluate function at final point.
% Reconstruct z. This finally defines z(fix).
if explicitF
obj = (Fname'*x); grad = Fname; hess = zeros(n,1);
else
[obj,grad,hess] = feval( Fname, x );
end
z = grad - pdxxxmat( Aname,2,m,n,y ); % z = grad - A'y
time = cputime - time;
str1 = sprintf('\nPDitns =%10g', PDitns );
str2 = sprintf( 'itns =%10g', CGitns );
myprintf( [str1 ' ' solver str2] )
myprintf(' time =%10.1f', time);
pdxxxdistrib( abs(x),abs(z) ); % Private function
if wait
keyboard
end
%-----------------------------------------------------------------------
% End function pdco.m
%-----------------------------------------------------------------------
function [low,upp,fix] = pdxxxbounds( bl,bu )
% Categorize various types of bounds.
% pos overlaps with low.
% neg overlaps with upp.
% two overlaps with low and upp.
% fix and free are disjoint from all other sets.
bigL = -9.9e+19;
bigU = 9.9e+19;
pos = find( bl==0 & bu>=bigU );
neg = find( bl<=bigL & bu==0 );
low = find( bl> bigL & bl< bu );
upp = find( bu< bigU & bl< bu );
two = find( bl> bigL & bu< bigU & bl< bu );
fix = find( bl==bu );
free = find( bl<=bigL & bu>=bigU );
myprintf('\n\nBounds:\n [0,inf] [-inf,0]')
myprintf(' Finite bl Finite bu Two bnds Fixed Free')
myprintf('\n %8g %9g %10g %10g %9g %7g %7g', ...
length(pos), length(neg), length(low), ...
length(upp), length(two), length(fix), length(free))
%-----------------------------------------------------------------------
% End private function pdxxxbounds
%-----------------------------------------------------------------------
function pdxxxdistrib( x,z )
% pdxxxdistrib(x) or pdxxxdistrib(x,z) prints the
% distribution of 1 or 2 vectors.
%
% 18 Dec 2000. First version with 2 vectors.
two = nargin > 1;
myprintf('\n\nDistribution of vector x')
if two, myprintf(' z'); end
x1 = 10^(floor(log10(max(x)+eps)) + 1);
z1 = 10^(floor(log10(max(z)+eps)) + 1);
x1 = max(x1,z1);
kmax = 10;
for k = 1:kmax
x2 = x1; x1 = x1/10;
if k==kmax, x1 = 0; end
nx = length(find(x>=x1 & x<x2));
myprintf('\n[%7.3g,%7.3g )%10g', x1, x2, nx);
if two
nz = length(find(z>=x1 & z<x2));
myprintf('%10g', nz);
end
end
mydisp(' ')
%-----------------------------------------------------------------------
% End private function pdxxxdistrib
%-----------------------------------------------------------------------
function [ x, istop, itn, outfo ] = ...
pdxxxlsqr( m, n, aprodname, iw, rw, b, damp, ...
atol, btol, conlim, itnlim, show, info )
% Special version of LSQR for use with pdco.m.
% It continues with a reduced atol if a pdco-specific test isn't
% satisfied with the input atol.
%
% LSQR solves Ax = b or min ||b - Ax||_2 if damp = 0,
% or min || (b) - ( A )x || otherwise.
% || (0) (damp I) ||2
% A is an m by n matrix defined by y = aprod( mode,m,n,x,iw,rw ),
% where the parameter 'aprodname' refers to a function 'aprod' that
% performs the matrix-vector operations.
% If mode = 1, aprod must return y = Ax without altering x.
% If mode = 2, aprod must return y = A'x without altering x.
% WARNING: The file containing the function 'aprod'
% must not be called aprodname.m !!!!
%-----------------------------------------------------------------------
% LSQR uses an iterative (conjugate-gradient-like) method.
% For further information, see
% 1. C. C. Paige and M. A. Saunders (1982a).
% LSQR: An algorithm for sparse linear equations and sparse least squares,
% ACM TOMS 8(1), 43-71.
% 2. C. C. Paige and M. A. Saunders (1982b).
% Algorithm 583. LSQR: Sparse linear equations and least squares problems,
% ACM TOMS 8(2), 195-209.
% 3. M. A. Saunders (1995). Solution of sparse rectangular systems using
% LSQR and CRAIG, BIT 35, 588-604.
%
% Input parameters:
% iw, rw are not used by lsqr, but are passed to aprod.
% atol, btol are stopping tolerances. If both are 1.0e-9 (say),
% the final residual norm should be accurate to about 9 digits.
% (The final x will usually have fewer correct digits,
% depending on cond(A) and the size of damp.)
% conlim is also a stopping tolerance. lsqr terminates if an estimate
% of cond(A) exceeds conlim. For compatible systems Ax = b,
% conlim could be as large as 1.0e+12 (say). For least-squares
% problems, conlim should be less than 1.0e+8.
% Maximum precision can be obtained by setting
% atol = btol = conlim = zero, but the number of iterations
% may then be excessive.
% itnlim is an explicit limit on iterations (for safety).
% show = 1 gives an iteration log,
% show = 0 suppresses output.
% info is a structure special to pdco.m, used to test if
% was small enough, and continuing if necessary with smaller atol.
%
%
% Output parameters:
% x is the final solution.
% istop gives the reason for termination.
% istop = 1 means x is an approximate solution to Ax = b.
% = 2 means x approximately solves the least-squares problem.
% rnorm = norm(r) if damp = 0, where r = b - Ax,
% = sqrt( norm(r)**2 + damp**2 * norm(x)**2 ) otherwise.
% xnorm = norm(x).
% var estimates diag( inv(A'A) ). Omitted in this special version.
% outfo is a structure special to pdco.m, returning information
% about whether atol had to be reduced.
%
% Other potential output parameters:
% anorm, acond, arnorm, xnorm
%
% 1990: Derived from Fortran 77 version of LSQR.
% 22 May 1992: bbnorm was used incorrectly. Replaced by anorm.
% 26 Oct 1992: More input and output parameters added.
% 01 Sep 1994: Matrix-vector routine is now a parameter 'aprodname'.
% Print log reformatted.
% 14 Jun 1997: show added to allow printing or not.
% 30 Jun 1997: var added as an optional output parameter.
% It returns an estimate of diag( inv(A'A) ).
% 12 Feb 2001: atol can now be reduced and iterations continued if necessary.
% info, outfo are new problem-dependent parameters for such purposes.
% In this version they are specialized for pdco.m.
%-----------------------------------------------------------------------
% Initialize.
msg=['The exact solution is x = 0 '
'Ax - b is small enough, given atol, btol '
'The least-squares solution is good enough, given atol '
'The estimate of cond(Abar) has exceeded conlim '
'Ax - b is small enough for this machine '
'The least-squares solution is good enough for this machine'
'Cond(Abar) seems to be too large for this machine '
'The iteration limit has been reached '];
% wantvar= nargout >= 6;
% if wantvar, var = zeros(n,1); end
itn = 0; istop = 0; nstop = 0;
ctol = 0; if conlim > 0, ctol = 1/conlim; end;
anorm = 0; acond = 0;
dampsq = damp^2; ddnorm = 0; res2 = 0;
xnorm = 0; xxnorm = 0; z = 0;
cs2 = -1; sn2 = 0;
% Set up the first vectors u and v for the bidiagonalization.
% These satisfy beta*u = b, alfa*v = A'u.
u = b(1:m); x = zeros(n,1);
alfa = 0; beta = norm( u );
if beta > 0
u = (1/beta) * u; v = feval( aprodname, 2, m, n, u, iw, rw );
alfa = norm( v );
end
if alfa > 0
v = (1/alfa) * v; w = v;
end
arnorm = alfa * beta; if arnorm==0, mydisp(msg(1,:)); return, end
rhobar = alfa; phibar = beta; bnorm = beta;
rnorm = beta;
head1 = ' Itn x(1) Function';
head2 = ' Compatible LS Norm A Cond A';
if show
mydisp(' ')
mydisp([head1 head2])
test1 = 1; test2 = alfa / beta;
str1 = sprintf( '%6g %12.5e %10.3e', itn, x(1), rnorm );
str2 = sprintf( ' %8.1e %8.1e', test1, test2 );
mydisp([str1 str2])
end
%----------------------------------------------------------------
% Main iteration loop.
%----------------------------------------------------------------
while itn < itnlim
itn = itn + 1;
% Perform the next step of the bidiagonalization to obtain the
% next beta, u, alfa, v. These satisfy the relations
% beta*u = A*v - alfa*u,
% alfa*v = A'*u - beta*v.
u = feval( aprodname, 1, m, n, v, iw, rw ) - alfa*u;
beta = norm( u );
if beta > 0
u = (1/beta) * u;
anorm = norm([anorm alfa beta damp]);
v = feval( aprodname, 2, m, n, u, iw, rw ) - beta*v;
alfa = norm( v );
if alfa > 0, v = (1/alfa) * v; end
end
% Use a plane rotation to eliminate the damping parameter.
% This alters the diagonal (rhobar) of the lower-bidiagonal matrix.
rhobar1 = norm([rhobar damp]);
cs1 = rhobar / rhobar1;
sn1 = damp / rhobar1;
psi = sn1 * phibar;
phibar = cs1 * phibar;
% Use a plane rotation to eliminate the subdiagonal element (beta)
% of the lower-bidiagonal matrix, giving an upper-bidiagonal matrix.
rho = norm([rhobar1 beta]);
cs = rhobar1/ rho;
sn = beta / rho;
theta = sn * alfa;
rhobar = - cs * alfa;
phi = cs * phibar;
phibar = sn * phibar;
tau = sn * phi;
% Update x and w.
t1 = phi /rho;
t2 = - theta/rho;
dk = (1/rho)*w;
x = x + t1*w;
w = v + t2*w;
ddnorm = ddnorm + norm(dk)^2;
% if wantvar, var = var + dk.*dk; end
% Use a plane rotation on the right to eliminate the
% super-diagonal element (theta) of the upper-bidiagonal matrix.
% Then use the result to estimate norm(x).
delta = sn2 * rho;
gambar = - cs2 * rho;
rhs = phi - delta * z;
zbar = rhs / gambar;
xnorm = sqrt(xxnorm + zbar^2);
gamma = norm([gambar theta]);
cs2 = gambar / gamma;
sn2 = theta / gamma;
z = rhs / gamma;
xxnorm = xxnorm + z^2;
% Test for convergence.
% First, estimate the condition of the matrix Abar,
% and the norms of rbar and Abar'rbar.
acond = anorm * sqrt( ddnorm );
res1 = phibar^2;
res2 = res2 + psi^2;
rnorm = sqrt( res1 + res2 );
arnorm = alfa * abs( tau );
% Now use these norms to estimate certain other quantities,
% some of which will be small near a solution.
test1 = rnorm / bnorm;
test2 = arnorm/( anorm * rnorm );
test3 = 1 / acond;
t1 = test1 / (1 + anorm * xnorm / bnorm);
rtol = btol + atol * anorm * xnorm / bnorm;
% The following tests guard against extremely small values of
% atol, btol or ctol. (The user may have set any or all of
% the parameters atol, btol, conlim to 0.)
% The effect is equivalent to the normal tests using
% atol = eps, btol = eps, conlim = 1/eps.
if itn >= itnlim, istop = 7; end
if 1 + test3 <= 1, istop = 6; end
if 1 + test2 <= 1, istop = 5; end
if 1 + t1 <= 1, istop = 4; end
% Allow for tolerances set by the user.
if test3 <= ctol, istop = 3; end
if test2 <= atol, istop = 2; end
if test1 <= rtol, istop = 1; end
%-------------------------------------------------------------------
% SPECIAL TEST THAT DEPENDS ON pdco.m.
% Aname in pdco is iw in lsqr.
% dy is x
% Other stuff is in info.
% We allow for diagonal preconditioning in pdDDD3.
%-------------------------------------------------------------------
if istop > 0
r3new = arnorm;
r3ratio = r3new / info.r3norm;
atolold = atol;
atolnew = atol;
if atol > info.atolmin
if r3ratio <= 0.1 % dy seems good
% Relax
elseif r3ratio <= 0.5 % Accept dy but make next one more accurate.
atolnew = atolnew * 0.1;
else % Recompute dy more accurately
myprintf('\n ')
myprintf(' ')
myprintf(' %5.1f%7g%7.3f', log10(atolold), itn, r3ratio)
atol = atol * 0.1;
atolnew = atol;
istop = 0;
end
end
outfo.atolold = atolold;
outfo.atolnew = atolnew;
outfo.r3ratio = r3ratio;
end
%-------------------------------------------------------------------
% See if it is time to print something.
%-------------------------------------------------------------------
prnt = 0;
if n <= 40 , prnt = 1; end
if itn <= 10 , prnt = 1; end
if itn >= itnlim-10, prnt = 1; end
if rem(itn,10)==0 , prnt = 1; end
if test3 <= 2*ctol , prnt = 1; end
if test2 <= 10*atol , prnt = 1; end
if test1 <= 10*rtol , prnt = 1; end
if istop ~= 0 , prnt = 1; end
if prnt==1
if show
str1 = sprintf( '%6g %12.5e %10.3e', itn, x(1), rnorm );
str2 = sprintf( ' %8.1e %8.1e', test1, test2 );
str3 = sprintf( ' %8.1e %8.1e', anorm, acond );
mydisp([str1 str2 str3])
end
end
if istop > 0, break, end
end
% End of iteration loop.
% Print the stopping condition.
if show
mydisp(' ')
mydisp('LSQR finished')
mydisp(msg(istop+1,:))
mydisp(' ')
str1 = sprintf( 'istop =%8g itn =%8g', istop, itn );
str2 = sprintf( 'anorm =%8.1e acond =%8.1e', anorm, acond );
str3 = sprintf( 'rnorm =%8.1e arnorm =%8.1e', rnorm, arnorm );
str4 = sprintf( 'bnorm =%8.1e xnorm =%8.1e', bnorm, xnorm );
mydisp([str1 ' ' str2])
mydisp([str3 ' ' str4])
mydisp(' ')
end
%-----------------------------------------------------------------------
% End private function pdxxxlsqr
%-----------------------------------------------------------------------
function y = pdxxxlsqrmat( mode, mlsqr, nlsqr, x, Aname, rw )
% pdxxxlsqrmat is required by pdco.m (when it calls pdxxxlsqr.m).
% It forms Mx or M'x for some operator M that depends on Method below.
%
% mlsqr, nlsqr are the dimensions of the LS problem that lsqr is solving.
%
% Aname is pdco's Aname.
%
% rw contains parameters [explicitA Method LSdamp]
% from pdco.m to say which least-squares subproblem is being solved.
%
% global pdDDD1 pdDDD3 provides various diagonal matrices
% for each value of Method.
%-----------------------------------------------------------------------
% 17 Mar 1998: First version to go with pdsco.m and lsqr.m.
% 01 Apr 1998: global pdDDD1 pdDDD3 now used for efficiency.
% 11 Feb 2000: Added diagonal preconditioning for LSQR, solving for dy.
% 14 Dec 2000: Added diagonal preconditioning for LSQR, solving for dx.
% 12 Feb 2001: Included in pdco.m as private function.
% Specialized to allow only solving for dy.
% 03 Oct 2002: First version to go with pdco.m with general H2 and D2.
% 16 Oct 2002: Aname is now the user's Aname.
%-----------------------------------------------------------------------
global pdDDD1 pdDDD2 pdDDD3
Method = rw(2);
precon = rw(7);
if Method==3
% The operator M is [ D1 A'; D2 ].
m = nlsqr;
n = mlsqr - m;
if mode==1
if precon, x = pdDDD3.*x; end
t = pdxxxmat( Aname, 2, m, n, x ); % Ask 'aprod' to form t = A'x.
y = [ (pdDDD1.*t); (pdDDD2.*x) ];
else
t = pdDDD1.*x(1:n);
y = pdxxxmat( Aname, 1, m, n, t ); % Ask 'aprod' to form y = A t.
y = y + pdDDD2.*x(n+1:mlsqr);
if precon, y = pdDDD3.*y; end
end
else
error('Error in pdxxxlsqrmat: Only Method = 3 is allowed at present')
end
%-----------------------------------------------------------------------
% End private function pdxxxlsqrmat
%-----------------------------------------------------------------------
function y = pdxxxmat( Aname, mode, m, n, x )
% y = pdxxxmat( Aname, mode, m, n, x )
% computes y = Ax (mode=1) or A'x (mode=2)
% for a matrix A defined by pdco's input parameter Aname.
%-----------------------------------------------------------------------
% 04 Apr 1998: Default A*x and A'*y function for pdco.m.
% Assumed A was a global matrix pdAAA created by pdco.m
% from the user's input parameter A.
% 16 Oct 2002: pdAAA eliminated to save storage.
% User's parameter Aname is now passed thru to here.
% 01 Nov 2002: Bug: feval had one too many parameters.
%-----------------------------------------------------------------------
if (ischar(Aname) || isa(Aname, 'function_handle'))
y = feval( Aname, mode, m, n, x );
else
if mode==1, y = Aname*x; else y = Aname'*x; end
end
%-----------------------------------------------------------------------
% End private function pdxxxmat
%-----------------------------------------------------------------------
function fmerit = pdxxxmerit( low,upp,r1,r2,rL,rU,cL,cU )
% Evaluate the merit function for Newton's method.
% It is the 2-norm of the three sets of residuals.
f = [norm(r1)
norm(r2)
norm(rL(low))
norm(rU(upp))
norm(cL(low))
norm(cU(upp))];
fmerit = norm(f);
%-----------------------------------------------------------------------
% End private function pdxxxmerit
%-----------------------------------------------------------------------
function [r1,r2,rL,rU,Pinf,Dinf] = ...
pdxxxresid1( Aname,fix,low,upp, ...
b,bl,bu,d1,d2,grad,rL,rU,x,x1,x2,y,z1,z2 )
% Form residuals for the primal and dual equations.
% rL, rU are output, but we input them as full vectors
% initialized (permanently) with any relevant zeros.
% 13 Aug 2003: z2-z1 coded more carefully
% (although MATLAB was doing the right thing).
% 19 Nov 2003: r2(fix) = 0 has to be done after r2 = grad - r2;
m = length(b);
n = length(bl);
x(fix) = 0;
r1 = pdxxxmat( Aname, 1, m, n, x );
r2 = pdxxxmat( Aname, 2, m, n, y );
r1 = b - r1 - (d2.^2).*y;
r2 = grad - r2; % + (z2-z1); % grad includes (d1.^2)*x
r2(fix) = 0;
r2(upp) = r2(upp) + z2(upp);
r2(low) = r2(low) - z1(low);
rL(low) = ( bl(low) - x(low)) + x1(low);
rU(upp) = (- bu(upp) + x(upp)) + x2(upp);
Pinf = max([norm(r1,inf) norm(rL(low),inf) norm(rU(upp),inf)]);
Dinf = norm(r2,inf);
Pinf = max( Pinf, 1e-99 );
Dinf = max( Dinf, 1e-99 );
%-----------------------------------------------------------------------
% End private function pdxxxresid1
%-----------------------------------------------------------------------
function [cL,cU,center,Cinf,Cinf0] = ...
pdxxxresid2( mu,low,upp,cL,cU,x1,x2,z1,z2 )
% Form residuals for the complementarity equations.
% cL, cU are output, but we input them as full vectors
% initialized (permanently) with any relevant zeros.
% Cinf is the complementarity residual for X1 z1 = mu e, etc.
% Cinf0 is the same for mu=0 (i.e., for the original problem).
x1z1 = x1(low).*z1(low);
x2z2 = x2(upp).*z2(upp);
cL(low) = mu - x1z1;
cU(upp) = mu - x2z2;
maxXz = max( [max(x1z1) max(x2z2)] );
minXz = min( [min(x1z1) min(x2z2)] );
maxXz = max( maxXz, 1e-99 );
minXz = max( minXz, 1e-99 );
center = maxXz / minXz;
Cinf = max([norm(cL(low),inf) norm(cU(upp),inf)]);
Cinf0 = maxXz;
%-----------------------------------------------------------------------
% End private function pdxxxresid2
%-----------------------------------------------------------------------
function step = pdxxxstep( x, dx )
% Assumes x > 0.
% Finds the maximum step such that x + step*dx >= 0.
step = 1e+20;
blocking = find( dx < 0 );
if length( blocking ) > 0
steps = x(blocking) ./ (- dx(blocking));
step = min( steps );
end
%
% Copyright (c) 2006. Michael Saunders
%
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function myprintf(s,a,b,c,d,e,f,g,h,i,j,k,l,m,n)
function mydisp(s)
|
github
|
jacksky64/imageProcessing-master
|
perform_lifting_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/perform_lifting_transform.m
| 5,259 |
utf_8
|
10f0ac03e72e5bb21bb572abfb21eceb
|
function x = perform_lifting_transform(x, Jmin, dir, options)
% perform_lifting_transform - peform fast lifting transform
%
% y = perform_lifting_transform(x, Jmin, dir, options);
%
% Implement 1D and 2D symmetric wavelets with symmetric boundary treatements, using
% a lifting implementation.
%
% h = options.filter gives the coefficients of the lifting filter.
% You can use h='linear' or h='7-9' to select automatically biorthogonal
% transform with 2 and 4 vanishing moments.
%
% You can set options.ti=1 to compute a translation invariant wavelet
% transform.
%
% Copyright (c) 2008 Gabriel Peyre
options.null = 0;
h = getoptions(options, 'filter', 'linear');
if isstr(h)
% P/U/P/U/etc the last coefficient is scaling
switch lower(h)
case {'linear' '5-3'}
h = [1/2 1/4 sqrt(2)];
case {'9-7' '7-9'}
h = [1.586134342 -.05298011854 -.8829110762 .4435068522 1.149604398];
otherwise
error('Unknown filter');
end
end
% detect dimensionality
% d = getoptions(options,'ndims',-1);
d = -1;
if isfield(options, 'ndims')
ndims = options.ndims;
end
if d<0
if size(x,1)==1 || size(x,2)==1
d = 1;
else
d = 2;
end
end
ti = getoptions(options, 'ti', 0);
% number of lifting steps
n = size(x,1);
m = (length(h)-1)/2;
Jmax = log2(n)-1;
jlist = Jmax:-1:Jmin;
if dir==-1
jlist = jlist(end:-1:1);
end
if ti==0
% subsampled
for j=jlist
if d==1
x(1:2^(j+1),:) = lifting_step( x(1:2^(j+1),:), h, dir);
else
x(1:2^(j+1),1:2^(j+1)) = lifting_step( x(1:2^(j+1),1:2^(j+1)), h, dir);
x(1:2^(j+1),1:2^(j+1)) = lifting_step( x(1:2^(j+1),1:2^(j+1))', h, dir)';
end
end
else
% TI
nJ = Jmax-Jmin+1;
if dir==1 && d==1
x = repmat(x,[1 1 nJ+1]);
elseif dir==1 && d==2
x = repmat(x,[1 1 3*nJ+1]);
end
for j=jlist
dist = 2^(Jmax-j);
if d==1
if dir==1
x(:,:,[1 j-Jmin+2]) = lifting_step_ti( x(:,:,1), h, dir, dist);
else
x(:,:,1) = lifting_step_ti( x(:,:,[1 j-Jmin+2]), h, dir, dist);
end
else
dj = 3*(j-Jmin);
if dir==1
x(:,:,[1 dj+2]) = lifting_step_ti( x(:,:,1), h, dir, dist);
x(:,:,[1 dj+3]) = lifting_step_ti( x(:,:,1)', h, dir, dist);
x(:,:,1) = x(:,:,1)'; x(:,:,dj+3) = x(:,:,dj+3)';
x(:,:,[dj+[2 4]]) = lifting_step_ti( x(:,:,dj+2)', h, dir, dist);
x(:,:,dj+2) = x(:,:,dj+2)';
x(:,:,dj+4) = x(:,:,dj+4)';
else
x(:,:,dj+2) = x(:,:,dj+2)';
x(:,:,dj+4) = x(:,:,dj+4)';
x(:,:,dj+2) = lifting_step_ti( x(:,:,[dj+[2 4]]), h, dir, dist)';
x(:,:,1) = x(:,:,1)';
x(:,:,dj+3) = x(:,:,dj+3)';
x(:,:,1) = lifting_step_ti( x(:,:,[1 dj+3]), h, dir, dist)';
x(:,:,1) = lifting_step_ti( x(:,:,[1 dj+2]), h, dir, dist);
end
end
end
if dir==-1
x = x(:,:,1);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = lifting_step(x, h, dir)
% number of lifting steps
m = (length(h)-1)/2;
if dir==1
% split
d = x(2:2:end,:);
x = x(1:2:end,:);
for i=1:m
d = d - h(2*i-1) * ( x + x([2:end end],:) );
x = x + h(2*i ) * ( d + d([1 1:end-1],:) );
end
x = [x*h(end);d/h(end)];
else
% retrieve detail coefs
d = x(end/2+1:end,:)*h(end);
x = x(1:end/2,:)/h(end);
for i=m:-1:1
x = x - h(2*i ) * ( d + d([1 1:end-1],:) );
d = d + h(2*i-1) * ( x + x([2:end end],:) );
end
% merge
x1 = zeros(size(x,1)*2,size(x,2));
x1(1:2:end,:) = x;
x1(2:2:end,:) = d;
x = x1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = lifting_step_ti(x, h, dir, dist)
% number of lifting steps
m = (length(h)-1)/2;
n = size(x,1);
s1 = (1:n)+dist;
s2 = (1:n)-dist;
% boundary conditions
s1(s1>n) = 2*n-s1(s1>n); s1(s1<1) = 2-s1(s1<1);
s2(s2>n) = 2*n-s2(s2>n); s2(s2<1) = 2-s2(s2<1);
% s1 = [2 1:n-1]; s2 = [2:n n-1];
if dir==1
% split
d = x;
for i=1:m
d = d - h(2*i-1) * ( x(s1,:) + x(s2,:) );
x = x + h(2*i ) * ( d(s1,:) + d(s2,:) );
end
x = cat(3,x*h(end),d/h(end));
else
% retrieve detail coefs
d = x(:,:,2)*h(end);
x = x(:,:,1)/h(end);
for i=m:-1:1
x = x - h(2*i ) * ( d(s1,:) + d(s2,:) );
d = d + h(2*i-1) * ( x(s1,:) + x(s2,:) );
end
% merge
x = (x+d)/2;
end
|
github
|
jacksky64/imageProcessing-master
|
perform_wavelet_matching.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/perform_wavelet_matching.m
| 5,655 |
utf_8
|
ce80d6388fa6824a0f269c8a29c4f023
|
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
%
% The transform used for synthesis is options.synthesis_method, which can
% be either 'steerable' 'wavelets-ortho' 'quincunx-ti' 'wavelets-ti'
% 'wavelets-circle'.
%
% See also perform_wavelet_transform, perform_histogram_equalization
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
niter_synthesis = getoptions(options, 'niter_synthesis', 1);
verb = getoptions(options, 'verb', 0);
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;
options.verb = 0;
for iter=1:niter_synthesis
if verb
progressbar(iter, niter_synthesis);
end
% 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, m, +1, options);
for iter=1:niter_synthesis
if verb
progressbar(iter, niter_synthesis);
end
% spatial equalization
M1 = my_equalization(M1,M);
% forward transforms
MW1 = my_transform(M1, m1, +1, options);
% wavelet domain equalization
MW1 = my_equalization(MW1,MW);
% backward transform
M1 = my_transform(MW1, m1, -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, n, dir, options)
synthesis_method = getoptions(options, 'synthesis_method', 'steerable');
deltaJ = 5;
if strcmp(synthesis_method, 'steerable')
deltaJ = 3;
end
Jmax = log2(n)-1;
Jmin = max(Jmax-deltaJ+1,3);
% 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);
case 'wavelets-circle'
if dir==-1
M = wavecircle2list(M,Jmin);
end
wavelet_modulo = getoptions(options, 'wavelet_modulo', 2*pi);
M = perform_circle_haar_transform(M, Jmin, dir, wavelet_modulo, options);
if dir==1
M = wavecircle2list(M,Jmin);
end
otherwise
error('Unknown transform.');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MW = wavecircle2list(M,Jmin)
if not(iscell(M))
n = size(M,1); Jmax = log2(n)-1;
MW = {};
for j=Jmax:-1:Jmin
MW{end+1} = M(end/2+1:end,:); M(end/2+1:end,:) = [];
MW{end+1} = M(:,end/2+1:end); M(:,end/2+1:end) = [];
end
MW{end+1} = M;
else
n = size(M{1},1)*2;
MW = M{end};
for i=length(M)-1:-1:1
if mod(i,2)==0
MW = [MW, M{i}];
else
MW = [MW; M{i}];
end
end
end
|
github
|
jacksky64/imageProcessing-master
|
perform_quicunx_wavelet_transform_ti.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/perform_quicunx_wavelet_transform_ti.m
| 3,927 |
utf_8
|
b81d7eec362739361304b4e77817f9d6
|
function M = perform_quicunx_wavelet_transform_ti(M,Jmin,options)
% perform_quicunx_wavelet_transform_ti - translation invariant quincunx wavelets
%
% Forward
% MW = perform_quicunx_wavelet_transform_ti(M,Jmin,options);
% Backward
% M = perform_quicunx_wavelet_transform_ti(MW,Jmin,options);
%
% The implementation is based on lifting.
%
% You can set the number of primal (analysis) and dual (synthesis)
% vanishing moments
% options.primal_vm (only 2/4 is supported).
% options.dual_vm (only 2/4 is supported).
%
% You can set the boundary conditions to
% options.bound = 'per' (periodic)
% options.bound = 'sym' (symmetric)
%
% This transform (but not TI) is described in
% Wavelet Families of Increasing Order in Arbitrary Dimensions
% Jelena Kovacevic, Wim Sweldens
% IEEE Trans. Image Proc, 2000.
%
%
% Copyright (c) 2008 Gabriel Peyre
options.null = 0;
n = size(M,1);
Jmax = log2(n)-1;
% number of scales
J = (Jmax-Jmin+1)*2;
bound = getoptions(options, 'bound', 'per');
primal_vm = getoptions(options, 'primal_vm', 4);
dual_vm = getoptions(options, 'dual_vm', 4);
[dX,dY,w] = get_quincunx_filter(primal_vm);
[dX1,dY1,w1] = get_quincunx_filter(dual_vm);
dir = +1;
if size(M,3)>1
dir=-1;
end
if dir==1
M0 = M;
else
M0 = M(:,:,end);
end
[Y,X] = meshgrid(1:n,1:n);
jlist = 0:J-1;
if dir==-1
jlist = jlist(end:-1:1);
end
W_ini = repmat( reshape(w,1,1,length(w)), n,n );
W1_ini = repmat( reshape(w1,1,1,length(w1)), n,n )/2;
Xn = W_ini; Yn = W_ini;
Xn1 = W_ini; Yn1 = W_ini;
for j=jlist
j1 = floor(j/2);
dj = 2^j1;
% rotate the filters
[dXj,dYj] = rotate_quincunx(dX,dY, j);
[dXj1,dYj1] = rotate_quincunx(dX1,dY1, j);
% build set of indices
for k=1:length(dX)
Xn(:,:,k) = X+dXj(k);
Yn(:,:,k) = Y+dYj(k);
end
for k=1:length(dX1)
Xn1(:,:,k) = X+dXj1(k);
Yn1(:,:,k) = Y+dYj1(k);
end
% boundary conditions
W = W_ini; W1 = W1_ini;
if strcmp(bound,'sym')
I = find( Xn>n | Xn<1 |Yn>n | Yn<1 ); W(I) = 0;
I = find( Xn1>n | Xn1<1 |Yn1>n | Yn1<1 ); W1(I) = 0;
end
Xn = mod(Xn-1,n)+1; Yn = mod(Yn-1,n)+1;
Xn1 = mod(Xn1-1,n)+1; Yn1 = mod(Yn1-1,n)+1;
% linear indexes
In = Xn+(Yn-1)*n; In1 = Xn1+(Yn1-1)*n;
if dir==1
% detail coefficients
d = sum(W,3); d(d==0) = 1; % 0 should not happend anyway
D = M0 - sum(M0(In).*W,3) ./ d;
M(:,:,j+1) = D;
% update coarse
d = sum(W1,3); d(d==0) = 1;
M0 = M0 + .5 * sum(D(In1).*W1,3) ./ d;
else
%% NB : since we are in TI mode, needs to be carefull and mix 2
%% retrieves
% retrieve coarse
D = M(:,:,j+1);
d = sum(W1,3); d(d==0) = 1;
M0a = M0 - .5 * sum(D(In1).*W1,3) ./ d;
% other retrieve
d = sum(W,3); d(d==0) = 1;
M0 = M(:,:,j+1) + sum(M0a(In).*W,3) ./ d;
M0 = (M0+M0a)/2;
end
end
if dir==1
% record coarse
M(:,:,end+1) = M0;
else
M = M0;
end
%%%%%%%%%%%%%%%%%
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 vanishing moments are supported.');
end
w = w/sum(w);
%%%%%%%%%%%%%%%%%
function [dXj,dYj] = rotate_quincunx(dX,dY, j)
A = [1 1;-1 1]; A = A^j;
dXj = A(1,1)*dX + A(1,2)*dY;
dYj = A(2,1)*dX + A(2,2)*dY;
|
github
|
jacksky64/imageProcessing-master
|
perform_curvelet_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/perform_curvelet_transform.m
| 33,957 |
utf_8
|
63811c4cedefc4b0a5ede5a2b3269c54
|
function y = perform_curvelet_transform(x,options)
% perform_curvelet_transform - a wrapper to curvlab
%
% M = perform_curvelet_transform(MW,options);
%
% Forward and backward curvelet transform
% You must provide options.n (width of the image).
%
% Visit www.curvelab.org for the full code.
options.null = 0;
finest = getoptions(options, 'finest',1) ; % =1(curv) =2(wav)
nbscales = getoptions(options, 'nbscales', 5); % log2(size(M,1))-2;
nbangles_coarse = getoptions(options, 'nbangles_coarse', 16);
is_real = getoptions(options, 'is_real', 0);
n = getoptions(options, 'n', 1,1);
if not(iscell(x))
% fwd transform
y = fdct_wrapping(x, is_real, finest, nbscales, nbangles_coarse);
else
y = real( ifdct_wrapping(x, is_real, n,n ) );
end
%%
function C = fdct_wrapping(x, is_real, finest, nbscales, nbangles_coarse)
% fdct_wrapping.m - Fast Discrete Curvelet Transform via wedge wrapping - Version 1.0
%
% Inputs
% x M-by-N matrix
%
% Optional Inputs
% is_real Type of the transform
% 0: complex-valued curvelets
% 1: real-valued curvelets
% [default set to 0]
% finest Chooses one of two possibilities for the coefficients at the
% finest level:
% 1: curvelets
% 2: wavelets
% [default set to 2]
% nbscales number of scales including the coarsest wavelet level
% [default set to ceil(log2(min(M,N)) - 3)]
% nbangles_coarse
% number of angles at the 2nd coarsest level, minimum 8,
% must be a multiple of 4. [default set to 16]
%
% Outputs
% C Cell array of curvelet coefficients.
% C{j}{l}(k1,k2) is the coefficient at
% - scale j: integer, from finest to coarsest scale,
% - angle l: integer, starts at the top-left corner and
% increases clockwise,
% - position k1,k2: both integers, size varies with j
% and l.
% If is_real is 1, there are two types of curvelets,
% 'cosine' and 'sine'. For a given scale j, the 'cosine'
% coefficients are stored in the first two quadrants (low
% values of l), the 'sine' coefficients in the last two
% quadrants (high values of l).
%
% See also ifdct_wrapping.m, fdct_wrapping_param.m
%
% By Laurent Demanet, 2004
X = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)));
[N1,N2] = size(X);
if nargin < 2, is_real = 0; end;
if nargin < 3, finest = 2; end;
if nargin < 4, nbscales = ceil(log2(min(N1,N2)) - 3); end;
if nargin < 5, nbangles_coarse = 16; end;
% Initialization: data structure
nbangles = [1, nbangles_coarse .* 2.^(ceil((nbscales-(nbscales:-1:2))/2))];
if finest == 2, nbangles(nbscales) = 1; end;
C = cell(1,nbscales);
for j = 1:nbscales
C{j} = cell(1,nbangles(j));
end;
% Loop: pyramidal scale decomposition
M1 = N1/3;
M2 = N2/3;
if finest == 1,
% Initialization: smooth periodic extension of high frequencies
bigN1 = 2*floor(2*M1)+1;
bigN2 = 2*floor(2*M2)+1;
equiv_index_1 = 1+mod(floor(N1/2)-floor(2*M1)+(1:bigN1)-1,N1);
equiv_index_2 = 1+mod(floor(N2/2)-floor(2*M2)+(1:bigN2)-1,N2);
X = X(equiv_index_1,equiv_index_2);
% Invariant: equiv_index_1(floor(2*M1)+1) == (N1 + 2 - mod(N1,2))/2
% is the center in frequency. Same for M2, N2.
window_length_1 = floor(2*M1) - floor(M1) - 1 - (mod(N1,3)==0);
window_length_2 = floor(2*M2) - floor(M2) - 1 - (mod(N2,3)==0);
% Invariant: floor(M1) + floor(2*M1) == N1 - (mod(M1,3)~=0)
% Same for M2, N2.
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
if mod(N1,3)==0, lowpass_1 = [0, lowpass_1, 0]; end;
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
if mod(N2,3)==0, lowpass_2 = [0, lowpass_2, 0]; end;
lowpass = lowpass_1'*lowpass_2;
Xlow = X .* lowpass;
scales = nbscales:-1:2;
else
M1 = M1/2;
M2 = M2/2;
window_length_1 = floor(2*M1) - floor(M1) - 1;
window_length_2 = floor(2*M2) - floor(M2) - 1;
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
lowpass = lowpass_1'*lowpass_2;
hipass = sqrt(1 - lowpass.^2);
Xlow_index_1 = ((-floor(2*M1)):floor(2*M1)) + ceil((N1+1)/2);
Xlow_index_2 = ((-floor(2*M2)):floor(2*M2)) + ceil((N2+1)/2);
Xlow = X(Xlow_index_1, Xlow_index_2) .* lowpass;
Xhi = X;
Xhi(Xlow_index_1, Xlow_index_2) = Xhi(Xlow_index_1, Xlow_index_2) .* hipass;
C{nbscales}{1} = fftshift(ifft2(ifftshift(Xhi)))*sqrt(prod(size(Xhi)));
if is_real, C{nbscales}{1} = real(C{nbscales}{1}); end;
scales = (nbscales-1):-1:2;
end;
for j = scales,
M1 = M1/2;
M2 = M2/2;
window_length_1 = floor(2*M1) - floor(M1) - 1;
window_length_2 = floor(2*M2) - floor(M2) - 1;
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
lowpass = lowpass_1'*lowpass_2;
hipass = sqrt(1 - lowpass.^2);
Xhi = Xlow; % size is 2*floor(4*M1)+1 - by - 2*floor(4*M2)+1
Xlow_index_1 = ((-floor(2*M1)):floor(2*M1)) + floor(4*M1) + 1;
Xlow_index_2 = ((-floor(2*M2)):floor(2*M2)) + floor(4*M2) + 1;
Xlow = Xlow(Xlow_index_1, Xlow_index_2);
Xhi(Xlow_index_1, Xlow_index_2) = Xlow .* hipass;
Xlow = Xlow .* lowpass; % size is 2*floor(2*M1)+1 - by - 2*floor(2*M2)+1
% Loop: angular decomposition
l = 0;
nbquadrants = 2 + 2*(~is_real);
nbangles_perquad = nbangles(j)/4;
for quadrant = 1:nbquadrants
M_horiz = M2 * (mod(quadrant,2)==1) + M1 * (mod(quadrant,2)==0);
M_vert = M1 * (mod(quadrant,2)==1) + M2 * (mod(quadrant,2)==0);
if mod(nbangles_perquad,2),
wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);
wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;
wedge_ticks = [wedge_ticks_left, wedge_ticks_right(end:-1:1)];
else
wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);
wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;
wedge_ticks = [wedge_ticks_left, wedge_ticks_right((end-1):-1:1)];
end;
wedge_endpoints = wedge_ticks(2:2:(end-1)); % integers
wedge_midpoints = (wedge_endpoints(1:(end-1)) + wedge_endpoints(2:end))/2;
% integers or half-integers
% Left corner wedge
l = l+1;
first_wedge_endpoint_vert = round(2*floor(4*M_vert)/(2*nbangles_perquad) + 1);
length_corner_wedge = floor(4*M_vert) - floor(M_vert) + ceil(first_wedge_endpoint_vert/4);
Y_corner = 1:length_corner_wedge;
[XX,YY] = meshgrid(1:(2*floor(4*M_horiz)+1),Y_corner);
width_wedge = wedge_endpoints(2) + wedge_endpoints(1) - 1;
slope_wedge = (floor(4*M_horiz) + 1 - wedge_endpoints(1))/floor(4*M_vert);
left_line = round(2 - wedge_endpoints(1) + slope_wedge*(Y_corner - 1));
% integers
[wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));
first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...
mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
% Coordinates of the top-left corner of the wedge wrapped
% around the origin. Some subtleties when the wedge is
% even-sized because of the forthcoming 90 degrees rotation
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
admissible_cols = round(1/2*(cols+1+abs(cols-1)));
new_row = 1 + mod(row - first_row, length_corner_wedge);
wrapped_data(new_row,:) = Xhi(row,admissible_cols) .* (cols > 0);
wrapped_XX(new_row,:) = XX(row,admissible_cols);
wrapped_YY(new_row,:) = YY(row,admissible_cols);
end;
slope_wedge_right = (floor(4*M_horiz)+1 - wedge_midpoints(1))/floor(4*M_vert);
mid_line_right = wedge_midpoints(1) + slope_wedge_right*(wrapped_YY - 1);
% not integers in general
coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(2) - wedge_endpoints(1)) * ...
(wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);
C2 = 1/(1/(2*(floor(4*M_horiz))/(wedge_endpoints(1) - 1) - 1) + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));
C1 = C2 / (2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1);
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) = ...
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) + 1;
coord_corner = C1 + C2 * ((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert))) ./ ...
(2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert))));
wl_left = fdct_wrapping_window(coord_corner);
[wl_right,wr_right] = fdct_wrapping_window(coord_right);
wrapped_data = wrapped_data .* (wl_left .* wr_right);
switch is_real
case 0
wrapped_data = rot90(wrapped_data,-(quadrant-1));
C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
case 1
wrapped_data = rot90(wrapped_data,-(quadrant-1));
x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
C{j}{l} = sqrt(2)*real(x);
C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);
end;
% Regular wedges
length_wedge = floor(4*M_vert) - floor(M_vert);
Y = 1:length_wedge;
first_row = floor(4*M_vert)+2-ceil((length_wedge+1)/2)+...
mod(length_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
for subl = 2:(nbangles_perquad-1);
l = l+1;
width_wedge = wedge_endpoints(subl+1) - wedge_endpoints(subl-1) + 1;
slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(subl))/floor(4*M_vert);
left_line = round(wedge_endpoints(subl-1) + slope_wedge*(Y - 1));
[wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_wedge,width_wedge));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
for row = Y
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
new_row = 1 + mod(row - first_row, length_wedge);
wrapped_data(new_row,:) = Xhi(row,cols);
wrapped_XX(new_row,:) = XX(row,cols);
wrapped_YY(new_row,:) = YY(row,cols);
end;
slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(subl-1))/floor(4*M_vert);
mid_line_left = wedge_midpoints(subl-1) + slope_wedge_left*(wrapped_YY - 1);
coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl) - wedge_endpoints(subl-1)) * ...
(wrapped_XX - mid_line_left)./(floor(4*M_vert)+1 - wrapped_YY);
slope_wedge_right = ((floor(4*M_horiz)+1) - wedge_midpoints(subl))/floor(4*M_vert);
mid_line_right = wedge_midpoints(subl) + slope_wedge_right*(wrapped_YY - 1);
coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl+1) - wedge_endpoints(subl)) * ...
(wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);
wl_left = fdct_wrapping_window(coord_left);
[wl_right,wr_right] = fdct_wrapping_window(coord_right);
wrapped_data = wrapped_data .* (wl_left .* wr_right);
switch is_real
case 0
wrapped_data = rot90(wrapped_data,-(quadrant-1));
C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
case 1
wrapped_data = rot90(wrapped_data,-(quadrant-1));
x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
C{j}{l} = sqrt(2)*real(x);
C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);
end;
end;
% Right corner wedge
l = l+1;
width_wedge = 4*floor(4*M_horiz) + 3 - wedge_endpoints(end) - wedge_endpoints(end-1);
slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(end))/floor(4*M_vert);
left_line = round(wedge_endpoints(end-1) + slope_wedge*(Y_corner - 1));
[wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));
first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...
mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
admissible_cols = round(1/2*(cols+2*floor(4*M_horiz)+1-abs(cols-(2*floor(4*M_horiz)+1))));
new_row = 1 + mod(row - first_row, length_corner_wedge);
wrapped_data(new_row,:) = Xhi(row,admissible_cols) .* (cols <= (2*floor(4*M_horiz)+1));
wrapped_XX(new_row,:) = XX(row,admissible_cols);
wrapped_YY(new_row,:) = YY(row,admissible_cols);
end;
slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(end))/floor(4*M_vert);
mid_line_left = wedge_midpoints(end) + slope_wedge_left*(wrapped_YY - 1);
coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(end) - wedge_endpoints(end-1)) * ...
(wrapped_XX - mid_line_left)./(floor(4*M_vert) + 1 - wrapped_YY);
C2 = -1/(2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1 + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));
C1 = -C2 * (2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1);
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY - 1)/floor(4*M_vert)) = ...
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY - 1)/floor(4*M_vert)) - 1;
coord_corner = C1 + C2 * (2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert)))) ./ ...
((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert)));
wl_left = fdct_wrapping_window(coord_left);
[wl_right,wr_right] = fdct_wrapping_window(coord_corner);
wrapped_data = wrapped_data .* (wl_left .* wr_right);
switch is_real
case 0
wrapped_data = rot90(wrapped_data,-(quadrant-1));
C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
case 1
wrapped_data = rot90(wrapped_data,-(quadrant-1));
x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
C{j}{l} = sqrt(2)*real(x);
C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);
end;
if quadrant < nbquadrants, Xhi = rot90(Xhi); end;
end;
end;
% Coarsest wavelet level
C{1}{1} = fftshift(ifft2(ifftshift(Xlow)))*sqrt(prod(size(Xlow)));
if is_real == 1,
C{1}{1} = real(C{1}{1});
end;
function x = ifdct_wrapping(C, is_real, M, N)
% ifdct_wrapping.m - Inverse Fast Discrete Curvelet Transform via wedge wrapping - Version 1.0
% This is in fact the adjoint, also the pseudo-inverse
%
% Inputs
% C Cell array containing curvelet coefficients (see
% description in fdct_wrapping.m)
% is_real As used in fdct_wrapping.m
% M, N Size of the image to be recovered (not necessary if finest
% = 2)
%
% Outputs
% x M-by-N matrix
%
% See also fdct_wrapping.m
%
% By Laurent Demanet, 2004
% Initialization
nbscales = length(C);
nbangles_coarse = length(C{2});
nbangles = [1, nbangles_coarse .* 2.^(ceil((nbscales-(nbscales:-1:2))/2))];
if length(C{end}) == 1, finest = 2; else finest = 1; end;
if finest == 2, nbangles(nbscales) = 1; end;
if nargin < 2, is_real = 0; end;
if nargin < 4,
if finest == 1, error('Syntax: IFCT_wrapping(C,M,N) where the matrix to be recovered is M-by-N'); end;
[N1,N2] = size(C{end}{1});
else
N1 = M;
N2 = N;
end;
M1 = N1/3;
M2 = N2/3;
if finest == 1;
bigN1 = 2*floor(2*M1)+1;
bigN2 = 2*floor(2*M2)+1;
X = zeros(bigN1,bigN2);
% Initialization: preparing the lowpass filter at finest scale
window_length_1 = floor(2*M1) - floor(M1) - 1 - (mod(N1,3)==0);
window_length_2 = floor(2*M2) - floor(M2) - 1 - (mod(N2,3)==0);
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
if mod(N1,3)==0, lowpass_1 = [0, lowpass_1, 0]; end;
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
if mod(N2,3)==0, lowpass_2 = [0, lowpass_2, 0]; end;
lowpass = lowpass_1'*lowpass_2;
scales = nbscales:-1:2;
else
M1 = M1/2;
M2 = M2/2;
bigN1 = 2*floor(2*M1)+1;
bigN2 = 2*floor(2*M2)+1;
X = zeros(bigN1,bigN2);
window_length_1 = floor(2*M1) - floor(M1) - 1;
window_length_2 = floor(2*M2) - floor(M2) - 1;
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
lowpass = lowpass_1'*lowpass_2;
hipass_finest = sqrt(1 - lowpass.^2);
scales = (nbscales-1):-1:2;
end;
% Loop: pyramidal reconstruction
Xj_topleft_1 = 1;
Xj_topleft_2 = 1;
for j = scales,
M1 = M1/2;
M2 = M2/2;
window_length_1 = floor(2*M1) - floor(M1) - 1;
window_length_2 = floor(2*M2) - floor(M2) - 1;
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
lowpass_next = lowpass_1'*lowpass_2;
hipass = sqrt(1 - lowpass_next.^2);
Xj = zeros(2*floor(4*M1)+1,2*floor(4*M2)+1);
% Loop: angles
l = 0;
nbquadrants = 2 + 2*(~is_real);
nbangles_perquad = nbangles(j)/4;
for quadrant = 1:nbquadrants
M_horiz = M2 * (mod(quadrant,2)==1) + M1 * (mod(quadrant,2)==0);
M_vert = M1 * (mod(quadrant,2)==1) + M2 * (mod(quadrant,2)==0);
if mod(nbangles_perquad,2),
wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);
wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;
wedge_ticks = [wedge_ticks_left, wedge_ticks_right(end:-1:1)];
else
wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);
wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;
wedge_ticks = [wedge_ticks_left, wedge_ticks_right((end-1):-1:1)];
end;
wedge_endpoints = wedge_ticks(2:2:(end-1)); % integers
wedge_midpoints = (wedge_endpoints(1:(end-1)) + wedge_endpoints(2:end))/2;
% Left corner wedge
l = l+1;
first_wedge_endpoint_vert = round(2*floor(4*M_vert)/(2*nbangles_perquad) + 1);
length_corner_wedge = floor(4*M_vert) - floor(M_vert) + ceil(first_wedge_endpoint_vert/4);
Y_corner = 1:length_corner_wedge;
[XX,YY] = meshgrid(1:(2*floor(4*M_horiz)+1),Y_corner);
width_wedge = wedge_endpoints(2) + wedge_endpoints(1) - 1;
slope_wedge = (floor(4*M_horiz) + 1 - wedge_endpoints(1))/floor(4*M_vert);
left_line = round(2 - wedge_endpoints(1) + slope_wedge*(Y_corner - 1));
[wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));
first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...
mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
new_row = 1 + mod(row - first_row, length_corner_wedge);
admissible_cols = round(1/2*(cols+1+abs(cols-1)));
wrapped_XX(new_row,:) = XX(row,admissible_cols);
wrapped_YY(new_row,:) = YY(row,admissible_cols);
end;
slope_wedge_right = (floor(4*M_horiz)+1 - wedge_midpoints(1))/floor(4*M_vert);
mid_line_right = wedge_midpoints(1) + slope_wedge_right*(wrapped_YY - 1);
% not integers
% in general
coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(2) - wedge_endpoints(1)) * ...
(wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);
C2 = 1/(1/(2*(floor(4*M_horiz))/(wedge_endpoints(1) - 1) - 1) + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));
C1 = C2 / (2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1);
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) = ...
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) + 1;
coord_corner = C1 + C2 * ((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert))) ./ ...
(2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert))));
wl_left = fdct_wrapping_window(coord_corner);
[wl_right,wr_right] = fdct_wrapping_window(coord_right);
switch is_real
case 0
wrapped_data = fftshift(fft2(ifftshift(C{j}{l})))/sqrt(prod(size(C{j}{l})));
wrapped_data = rot90(wrapped_data,(quadrant-1));
case 1
x = C{j}{l} + sqrt(-1)*C{j}{l+nbangles(j)/2};
wrapped_data = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)))/sqrt(2);
wrapped_data = rot90(wrapped_data,(quadrant-1));
end;
wrapped_data = wrapped_data .* (wl_left .* wr_right);
% Unwrapping data
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
admissible_cols = round(1/2*(cols+1+abs(cols-1)));
new_row = 1 + mod(row - first_row, length_corner_wedge);
Xj(row,admissible_cols) = Xj(row,admissible_cols) + wrapped_data(new_row,:);
% We use the following property: in an assignment
% A(B) = C where B and C are vectors, if
% some value x repeats in B, then the
% last occurrence of x is the one
% corresponding to the eventual assignment.
end;
% Regular wedges
length_wedge = floor(4*M_vert) - floor(M_vert);
Y = 1:length_wedge;
first_row = floor(4*M_vert)+2-ceil((length_wedge+1)/2)+...
mod(length_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
for subl = 2:(nbangles_perquad-1);
l = l+1;
width_wedge = wedge_endpoints(subl+1) - wedge_endpoints(subl-1) + 1;
slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(subl))/floor(4*M_vert);
left_line = round(wedge_endpoints(subl-1) + slope_wedge*(Y - 1));
[wrapped_XX, wrapped_YY] = deal(zeros(length_wedge,width_wedge));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
for row = Y
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
new_row = 1 + mod(row - first_row, length_wedge);
wrapped_XX(new_row,:) = XX(row,cols);
wrapped_YY(new_row,:) = YY(row,cols);
end;
slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(subl-1))/floor(4*M_vert);
mid_line_left = wedge_midpoints(subl-1) + slope_wedge_left*(wrapped_YY - 1);
coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl) - wedge_endpoints(subl-1)) * ...
(wrapped_XX - mid_line_left)./(floor(4*M_vert)+1 - wrapped_YY);
slope_wedge_right = ((floor(4*M_horiz)+1) - wedge_midpoints(subl))/floor(4*M_vert);
mid_line_right = wedge_midpoints(subl) + slope_wedge_right*(wrapped_YY - 1);
coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl+1) - wedge_endpoints(subl)) * ...
(wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);
wl_left = fdct_wrapping_window(coord_left);
[wl_right,wr_right] = fdct_wrapping_window(coord_right);
switch is_real
case 0
wrapped_data = fftshift(fft2(ifftshift(C{j}{l})))/sqrt(prod(size(C{j}{l})));
wrapped_data = rot90(wrapped_data,(quadrant-1));
case 1
x = C{j}{l} + sqrt(-1)*C{j}{l+nbangles(j)/2};
wrapped_data = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)))/sqrt(2);
wrapped_data = rot90(wrapped_data,(quadrant-1));
end;
wrapped_data = wrapped_data .* (wl_left .* wr_right);
% Unwrapping data
for row = Y
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
new_row = 1 + mod(row - first_row, length_wedge);
Xj(row,cols) = Xj(row,cols) + wrapped_data(new_row,:);
end;
end; % for subl
% Right corner wedge
l = l+1;
width_wedge = 4*floor(4*M_horiz) + 3 - wedge_endpoints(end) - wedge_endpoints(end-1);
slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(end))/floor(4*M_vert);
left_line = round(wedge_endpoints(end-1) + slope_wedge*(Y_corner - 1));
[wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));
first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...
mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
admissible_cols = round(1/2*(cols+2*floor(4*M_horiz)+1-abs(cols-(2*floor(4*M_horiz)+1))));
new_row = 1 + mod(row - first_row, length_corner_wedge);
wrapped_XX(new_row,:) = XX(row,admissible_cols);
wrapped_YY(new_row,:) = YY(row,admissible_cols);
end;
YY = Y_corner'*ones(1,width_wedge);
slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(end))/floor(4*M_vert);
mid_line_left = wedge_midpoints(end) + slope_wedge_left*(wrapped_YY - 1);
coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(end) - wedge_endpoints(end-1)) * ...
(wrapped_XX - mid_line_left)./(floor(4*M_vert)+1 - wrapped_YY);
C2 = -1/(2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1 + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));
C1 = -C2 * (2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1);
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY-1)/floor(4*M_vert)) = ...
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY-1)/floor(4*M_vert)) - 1;
coord_corner = C1 + C2 * (2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert)))) ./ ...
((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert)));
wl_left = fdct_wrapping_window(coord_left);
[wl_right,wr_right] = fdct_wrapping_window(coord_corner);
switch is_real
case 0
wrapped_data = fftshift(fft2(ifftshift(C{j}{l})))/sqrt(prod(size(C{j}{l})));
wrapped_data = rot90(wrapped_data,(quadrant-1));
case 1
x = C{j}{l} + sqrt(-1)*C{j}{l+nbangles(j)/2};
wrapped_data = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)))/sqrt(2);
wrapped_data = rot90(wrapped_data,(quadrant-1));
end;
wrapped_data = wrapped_data .* (wl_left .* wr_right);
% Unwrapping data
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
admissible_cols = round(1/2*(cols+2*floor(4*M_horiz)+1-abs(cols-(2*floor(4*M_horiz)+1))));
new_row = 1 + mod(row - first_row, length_corner_wedge);
Xj(row,fliplr(admissible_cols)) = Xj(row,fliplr(admissible_cols)) + wrapped_data(new_row,end:-1:1);
% We use the following property: in an assignment
% A(B) = C where B and C are vectors, if
% some value x repeats in B, then the
% last occurrence of x is the one
% corresponding to the eventual assignment.
end;
Xj = rot90(Xj);
end; % for quadrant
Xj = Xj .* lowpass;
Xj_index1 = ((-floor(2*M1)):floor(2*M1)) + floor(4*M1) + 1;
Xj_index2 = ((-floor(2*M2)):floor(2*M2)) + floor(4*M2) + 1;
Xj(Xj_index1, Xj_index2) = Xj(Xj_index1, Xj_index2) .* hipass;
loc_1 = Xj_topleft_1 + (0:(2*floor(4*M1)));
loc_2 = Xj_topleft_2 + (0:(2*floor(4*M2)));
X(loc_1,loc_2) = X(loc_1,loc_2) + Xj;
% Preparing for loop reentry or exit
Xj_topleft_1 = Xj_topleft_1 + floor(4*M1) - floor(2*M1);
Xj_topleft_2 = Xj_topleft_2 + floor(4*M2) - floor(2*M2);
lowpass = lowpass_next;
end; % for j
if is_real
Y = X;
X = rot90(X,2);
X = X + conj(Y);
end
% Coarsest wavelet level
M1 = M1/2;
M2 = M2/2;
Xj = fftshift(fft2(ifftshift(C{1}{1})))/sqrt(prod(size(C{1}{1})));
loc_1 = Xj_topleft_1 + (0:(2*floor(4*M1)));
loc_2 = Xj_topleft_2 + (0:(2*floor(4*M2)));
X(loc_1,loc_2) = X(loc_1,loc_2) + Xj .* lowpass;
% Finest level
M1 = N1/3;
M2 = N2/3;
if finest == 1,
% Folding back onto N1-by-N2 matrix
shift_1 = floor(2*M1)-floor(N1/2);
shift_2 = floor(2*M2)-floor(N2/2);
Y = X(:,(1:N2)+shift_2);
Y(:,N2-shift_2+(1:shift_2)) = Y(:,N2-shift_2+(1:shift_2)) + X(:,1:shift_2);
Y(:,1:shift_2) = Y(:,1:shift_2) + X(:,N2+shift_2+(1:shift_2));
X = Y((1:N1)+shift_1,:);
X(N1-shift_1+(1:shift_1),:) = X(N1-shift_1+(1:shift_1),:) + Y(1:shift_1,:);
X(1:shift_1,:) = X(1:shift_1,:) + Y(N1+shift_1+(1:shift_1),:);
else
% Extension to a N1-by-N2 matrix
Y = fftshift(fft2(ifftshift(C{nbscales}{1})))/sqrt(prod(size(C{nbscales}{1})));
X_topleft_1 = ceil((N1+1)/2) - floor(M1);
X_topleft_2 = ceil((N2+1)/2) - floor(M2);
loc_1 = X_topleft_1 + (0:(2*floor(M1)));
loc_2 = X_topleft_2 + (0:(2*floor(M2)));
Y(loc_1,loc_2) = Y(loc_1,loc_2) .* hipass_finest + X;
X = Y;
end;
x = fftshift(ifft2(ifftshift(X)))*sqrt(prod(size(X)));
if is_real, x = real(x); end;
function [wl,wr] = fdct_wrapping_window(x)
% fdct_wrapping_window.m - Creates the two halves of a C^inf compactly supported window
%
% Inputs
% x vector or matrix of abscissae, the relevant ones from 0 to 1
%
% Outputs
% wl,wr vector or matrix containing samples of the left, resp. right
% half of the window
%
% Used at least in fdct_wrapping.m and ifdct_wrapping.m
%
% By Laurent Demanet, 2004
wr = zeros(size(x));
wl = zeros(size(x));
x(abs(x) < 2^-52) = 0;
wr((x > 0) & (x < 1)) = exp(1-1./(1-exp(1-1./x((x > 0) & (x < 1)))));
wr(x <= 0) = 1;
wl((x > 0) & (x < 1)) = exp(1-1./(1-exp(1-1./(1-x((x > 0) & (x < 1))))));
wl(x >= 1) = 1;
normalization = sqrt(wl.^2 + wr.^2);
wr = wr ./ normalization;
wl = wl ./ normalization;
|
github
|
jacksky64/imageProcessing-master
|
perform_atrou_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/perform_atrou_transform.m
| 23,527 |
utf_8
|
4cde4e609d6784e61c27a06afbba626b
|
function y = perform_atrou_transform(x,Jmin,options)
% perform_atrou_transform - compute the "a trou" wavelet transform,
%
% This function is depreciated, use perform_wavelet_transform instead.
%
% Copyright (c) 2006 Gabriel Peyre
% w_list = perform_atrou_transform(M,Jmin,options);
%
% 'w_list' is a cell array, w_list{ 3*(j-Jmin)+q }
% is an imagette of same size as M containing the full transform
% at scale j and quadrant q.
% The lowest resolution image is in w_list{3*(Jmax-Jmin)+4} =
% w_list{end}.
%
% The ordering is :
% { H_j,V_j,D_j, H_{j-1},V_{j-1},D_{j-1}, ..., H_1,V_1,D_1, C }
%
% 'options' is an (optional) structure that may contains:
% options.wavelet_type: kind of wavelet used (see perform_wavelet_transform)
% options.wavelet_vm: the number of vanishing moments of the wavelet transform.
%
% When possible, this code tries to use the following fast mex implementation:
% * Rice Wavelet Toolbox : for Daubechies filters, ie when options.wavelet_type='daubechies'.
% Only the Windows binaries are included, please refer to
% http://www-dsp.rice.edu/software/rwt.shtml
% to install on other OS.
%
% You can set decomp_type = 'quad' or 'tri' for the 7-9 transform.
%
% Copyright (c) 2006 Gabriel Peyre
% warning('This function is depreciated, use perform_wavelet_transform instead.');
% add let it wave a trou transform to the path
% path('./cwpt2/',path);
% add Rice Wavelet Toolbox transform to the path
% path('./rwt/',path);
if nargin<3
options.null = 0;
end
wavelet_type = getoptions(options, 'wavelet_type', 'biorthogonal');
wavelet_vm = getoptions(options, 'wavelet_vm', 3);
bound = getoptions(options, 'bound', 'sym');
% first check for LIW interface, since it's the best code
if exist('cwpt2_interface') && ~strcmp(wavelet_type, 'daubechies') && ~strcmp(wavelet_type, 'symmlet')
if strcmp(wavelet_type, 'biorthogonal') || strcmp(wavelet_type, 'biorthogonal_swapped')
if wavelet_vm~=3
warning('Works only for 7-9 wavelets.');
end
wavelet_types = '7-9';
elseif strcmp(wavelet_type, 'battle')
if wavelet_vm~=3
warning('Works only for cubic spline wavelets.');
end
wavelet_types = 'spline';
else
error('Unknown transform.');
end
if isfield(options, 'decomp_type')
decomp_type = options.decomp_type;
else
decomp_type = 'quad'; % either 'quad' or 'tri'
end
if ~iscell(x)
dirs = 'forward';
J = log2(size(x,1)) - Jmin;
M = x;
else
dirs = 'inverse';
if strcmp(decomp_type, 'tri')
x = { x{1:end-3}, x{end}, x{end-2:end-1} };
else
x = { x{1:end-4}, x{end}, x{end-3:end-1} };
end
J = 0;
M = zeros(size(x{1},1), size(x{1},2), J);
for i=1:length(x)
M(:,:,i) = x{i};
end
end
y = cwpt2_interface(M, dirs, wavelet_types, decomp_type, J);
if ~iscell(x)
M = y; y = {};
for i=1:size(M,3)
y{i} = M(:,:,i);
end
% put low frequency at the end
if strcmp(decomp_type, 'tri')
y = { y{1:end-3}, y{end-1:end}, y{end-2} };
else
y = { y{1:end-4}, y{end-2:end}, y{end-3} };
end
end
return;
end
% precompute filters
if strcmp(wavelet_type, 'daubechies')
fname = 'Daubechies';
if wavelet_vm==1
fname = 'Haar';
end
qmf = MakeONFilter(fname,wavelet_vm*2); % in Wavelab, 2nd argument is VM*2 for Daubechies... no comment ...
elseif strcmp(wavelet_type, 'symmlet')
qmf = MakeONFilter('Symmlet',wavelet_vm);
elseif strcmp(wavelet_type, 'battle')
qmf = MakeONFilter('Battle',wavelet_vm-1);
elseif strcmp(wavelet_type, 'biorthogonal')
[qmf,dqmf] = MakeBSFilter( 'CDF', [wavelet_vm,wavelet_vm] );
elseif strcmp(wavelet_type, 'biorthogonal_swapped')
[dqmf,qmf] = MakeBSFilter( 'CDF', [wavelet_vm,wavelet_vm] );
else
error('Unknown transform.');
end
g = qmf; % for phi
gg = g;
if exist('mirdwt') & exist('mrdwt') & strcmp(wavelet_type, 'daubechies')
%%% USING RWT %%%
if ~iscell(x)
n = length(x);
Jmax = log2(n)-1;
%%% FORWARD TRANSFORM %%%
L = Jmax-Jmin+1;
[yl,yh,L] = mrdwt(x,g,L);
for j=Jmax:-1:Jmin
for q=1:3
s = 3*(Jmax-j)+q-1;
M = yh(:,s*n+1:(s+1)*n);
y{ 3*(j-Jmin)+q } = M;
end
end
y{ 3*(Jmax-Jmin)+4 } = yl;
% reverse the order of the frequencies
y = { y{end-1:-1:1} y{end} };
else
n = length(x{1});
Jmax = log2(n)-1;
% reverse the order of the frequencies
x = { x{end-1:-1:1} x{end} };
%%% BACKWARD TRANSFORM %%%
L = Jmax-Jmin+1;
if L ~= (length(x)-1)/3
warning('Jmin is not correct.');
L = (length(x)-1)/3;
end
yl = x{ 3*(Jmax-Jmin)+4 };
yh = zeros( n,3*L*n );
for j=Jmax:-1:Jmin
for q=1:3
s = 3*(Jmax-j)+q-1;
yh(:,s*n+1:(s+1)*n) = x{ 3*(j-Jmin)+q };
end
end
[y,L] = mirdwt(yl,yh,gg,L);
end
return;
end
%%
error('This code is depreciated.');
% for reconstruction
h = mirror_filter(g); % for psi
hh = g;
if exist('dqmf')
gg = dqmf;
hh = mirror_filter(gg);
end
n = length(x);
Jmax = log2(n)-1;
if iscell(x)
error('reverse transform is not yet implemented.');
end
M = x;
Mj = M; % image at current scale (low pass filtered)
nh = length(h);
ng = length(g);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute the transform
wb = waitbar(0,'Computing a trou transform.');
for j=Jmax:-1:Jmin
waitbar((Jmax-j)/(Jmax-Jmin),wb);
% 1st put some zeros in between g and h
nz = 2^(Jmax-j); % space between coefs
hj = zeros(nz*(nh-1)+1, 1);
gj = zeros(nz*(ng-1)+1, 1);
hj( 1 + (0:nh-1)*nz ) = h;
gj( 1 + (0:ng-1)*nz ) = g;
%%%% filter on X %%%%
Mjh = zeros(n,n);
Mjg = zeros(n,n);
for i=1:n
Mjh(:,i) = perform_convolution( Mj(:,i), hj, bound );
Mjg(:,i) = perform_convolution( Mj(:,i), gj, bound );
end
%%%% filter on Y %%%%
Mjhh = zeros(n,n);
Mjhg = zeros(n,n);
Mjgh = zeros(n,n);
Mjgg = zeros(n,n);
for i=1:n
Mjhh(i,:) = perform_convolution( Mjh(i,:)', hj, bound )';
Mjhg(i,:) = perform_convolution( Mjh(i,:)', gj, bound )';
Mjgh(i,:) = perform_convolution( Mjg(i,:)', hj, bound )';
Mjgg(i,:) = perform_convolution( Mjg(i,:)', gj, bound )';
end
Mj = Mjgg;
w_list{ 3*(j-Jmin)+1 } = Mjgh;
w_list{ 3*(j-Jmin)+2 } = Mjhg;
w_list{ 3*(j-Jmin)+3 } = Mjhh;
end
close(wb);
w_list{ 3*(Jmax-Jmin)+4 } = Mj;
y = w_list;
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
%
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]
%
function y = mirror_filter(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
%
|
github
|
jacksky64/imageProcessing-master
|
perform_spiht_coding.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/perform_spiht_coding.m
| 16,676 |
utf_8
|
887f72ff117400ec78d7f4bd15f07015
|
function [y,nbr_bits] = perform_spiht_coding(x,options)
% perform_spiht_coding - SPIHT coding of wavelet coefficients
%
% Coding :
% options.Jmin = ??; % minimum scale of the transform
% options.nb_bits = ??; % target number of bits
% [stream,nbr_bits] = perform_spiht_coding(MW,options);
% Decoding :
% MW = perform_spiht_coding(stream);
%
% This is a simple wrapper of the code of Jing Tian
% <scuteejtian at hotmail.com>
options.null = 0;
if isfield(options, 'arithmetic_coding')
arithmetic_coding = options.arithmetic_coding;
else
arithmetic_coding = 1;
end
if size(x,1)>1 && size(x,2)>1
if isfield(options, 'Jmin')
Jmin = options.Jmin;
else
warning('You should provide options.Jmin');
Jmin = 4;
end
if isfield(options, 'nb_bits')
nb_bits = options.nb_bits;
else
nb_bits = floor( prod(size(x))*0.1 );
end
%----------- Coding ----------------
Jmax = log2(size(x,1))-1;
level = Jmax-Jmin+1;
y = func_SPIHT_Enc(x, nb_bits, level); y = y(:);
if arithmetic_coding
% remove trailing 2
I = find(y==2); y(I) = [];
% the 3 first entry are [size nb_bitsplanes level]
[z,nbr_bits] = perform_arithmetic_coding(y(4:end), +1, options);
y = [y(1:3); z];
nbr_bits = nbr_bits + 16; % approx 16 bits
else
nbr_bits = nb_bits;
end
else
%----------- Decoding ----------------
if arithmetic_coding
x = x(:);
% the 3 first entry are [size nb_bitsplanes level]
z = perform_arithmetic_coding(x(4:end), -1, options);
x = [x(1:3); z];
nbr_bits = -1;
end
y = func_SPIHT_Dec(x(:)');
end
function out = func_SPIHT_Enc(m, max_bits, level)
% Matlab implementation of SPIHT (without Arithmatic coding stage)
%
% Encoder
%
% input: m : input image in wavelet domain
% max_bits : maximum bits can be used
% level : wavelet decomposition level
%
% output: out : bit stream
%
% Jing Tian
% Contact me : [email protected]
% This program is part of my undergraduate project in GuangZhou, P. R. China.
% April - July 1999
%----------- Initialization -----------------
bitctr = 0;
out = 2*ones(1,max_bits - 14);
n_max = floor(log2(abs(max(max(m)'))));
Bits_Header = 0;
Bits_LSP = 0;
Bits_LIP = 0;
Bits_LIS = 0;
%----------- output bit stream header ----------------
% image size, number of bit plane, wavelet decomposition level should be
% written as bit stream header.
out(1,[1 2 3]) = [size(m,1) n_max level]; bitctr = bitctr + 24;
index = 4;
Bits_Header = Bits_Header + 24;
%----------- Initialize LIP, LSP, LIS ----------------
temp = [];
bandsize = 2.^(log2(size(m, 1)) - level + 1);
temp1 = 1 : bandsize;
for i = 1 : bandsize
temp = [temp; temp1];
end
LIP(:, 1) = temp(:);
temp = temp';
LIP(:, 2) = temp(:);
LIS(:, 1) = LIP(:, 1);
LIS(:, 2) = LIP(:, 2);
LIS(:, 3) = zeros(length(LIP(:, 1)), 1);
pstart = 1;
pend = bandsize / 2;
for i = 1 : bandsize / 2
LIS(pstart : pend, :) = [];
pdel = pend - pstart + 1;
pstart = pstart + bandsize - pdel;
pend = pend + bandsize - pdel;
end
LSP = [];
n = n_max;
%----------- coding ----------------
while(bitctr < max_bits)
% Sorting Pass
LIPtemp = LIP; temp = 0;
for i = 1:size(LIPtemp,1)
temp = temp+1;
if (bitctr + 1) >= max_bits
if (bitctr < max_bits)
out(length(out))=[];
end
return
end
if abs(m(LIPtemp(i,1),LIPtemp(i,2))) >= 2^n % 1: positive; 0: negative
out(index) = 1; bitctr = bitctr + 1;
index = index +1; Bits_LIP = Bits_LIP + 1;
sgn = m(LIPtemp(i,1),LIPtemp(i,2))>=0;
out(index) = sgn; bitctr = bitctr + 1;
index = index +1; Bits_LIP = Bits_LIP + 1;
LSP = [LSP; LIPtemp(i,:)];
LIP(temp,:) = []; temp = temp - 1;
else
out(index) = 0; bitctr = bitctr + 1;
index = index +1;
Bits_LIP = Bits_LIP + 1;
end
end
LIStemp = LIS; temp = 0; i = 1;
while ( i <= size(LIStemp,1))
temp = temp + 1;
if LIStemp(i,3) == 0
if bitctr >= max_bits
return
end
max_d = func_MyDescendant(LIStemp(i,1),LIStemp(i,2),LIStemp(i,3),m);
if max_d >= 2^n
out(index) = 1; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
x = LIStemp(i,1); y = LIStemp(i,2);
if (bitctr + 1) >= max_bits
if (bitctr < max_bits)
out(length(out))=[];
end
return
end
if abs(m(2*x-1,2*y-1)) >= 2^n
LSP = [LSP; 2*x-1 2*y-1];
out(index) = 1; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
sgn = m(2*x-1,2*y-1)>=0;
out(index) = sgn; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
else
out(index) = 0; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
LIP = [LIP; 2*x-1 2*y-1];
end
if (bitctr + 1) >= max_bits
if (bitctr < max_bits)
out(length(out))=[];
end
return
end
if abs(m(2*x-1,2*y)) >= 2^n
LSP = [LSP; 2*x-1 2*y];
out(index) = 1; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
sgn = m(2*x-1,2*y)>=0;
out(index) = sgn; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
else
out(index) = 0; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
LIP = [LIP; 2*x-1 2*y];
end
if (bitctr + 1) >= max_bits
if (bitctr < max_bits)
out(length(out))=[];
end
return
end
if abs(m(2*x,2*y-1)) >= 2^n
LSP = [LSP; 2*x 2*y-1];
out(index) = 1; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
sgn = m(2*x,2*y-1)>=0;
out(index) = sgn; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
else
out(index) = 0; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
LIP = [LIP; 2*x 2*y-1];
end
if (bitctr + 1) >= max_bits
if (bitctr < max_bits)
out(length(out))=[];
end
return
end
if abs(m(2*x,2*y)) >= 2^n
LSP = [LSP; 2*x 2*y];
out(index) = 1; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
sgn = m(2*x,2*y)>=0;
out(index) = sgn; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
else
out(index) = 0; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
LIP = [LIP; 2*x 2*y];
end
if ((2*(2*x)-1) < size(m) & (2*(2*y)-1) < size(m))
LIS = [LIS; LIStemp(i,1) LIStemp(i,2) 1];
LIStemp = [LIStemp; LIStemp(i,1) LIStemp(i,2) 1];
end
LIS(temp,:) = []; temp = temp-1;
else
out(index) = 0; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
end
else
if bitctr >= max_bits
return
end
max_d = func_MyDescendant(LIStemp(i,1),LIStemp(i,2),LIStemp(i,3),m);
if max_d >= 2^n
out(index) = 1; bitctr = bitctr + 1;
index = index +1;
x = LIStemp(i,1); y = LIStemp(i,2);
LIS = [LIS; 2*x-1 2*y-1 0; 2*x-1 2*y 0; 2*x 2*y-1 0; 2*x 2*y 0];
LIStemp = [LIStemp; 2*x-1 2*y-1 0; 2*x-1 2*y 0; 2*x 2*y-1 0; 2*x 2*y 0];
LIS(temp,:) = []; temp = temp - 1;
else
out(index) = 0; bitctr = bitctr + 1;
index = index +1; Bits_LIS = Bits_LIS + 1;
end
end
i = i+1;
end
% Refinement Pass
temp = 1;
value = floor(abs(2^(n_max-n+1)*m(LSP(temp,1),LSP(temp,2))));
while (value >= 2^(n_max+2) & (temp <= size(LSP,1)))
if bitctr >= max_bits
return
end
s = bitget(value,n_max+2);
out(index) = s; bitctr = bitctr + 1;
index = index +1; Bits_LSP = Bits_LSP + 1;
temp = temp + 1;
if temp <= size(LSP,1)
value = floor(abs(2^(n_max-n+1)*m(LSP(temp,1),LSP(temp,2))));
end
end
n = n - 1;
end
function m = func_SPIHT_Dec(in)
% Matlab implementation of SPIHT (without Arithmatic coding stage)
%
% Decoder
%
% input: in : bit stream
%
% output: m : reconstructed image in wavelet domain
%
% Jing Tian
% Contact me : [email protected]
% This program is part of my undergraduate project in GuangZhou, P. R. China.
% April - July 1999
%----------- Initialization -----------------
% image size, number of bit plane, wavelet decomposition level should be
% written as bit stream header.
m = zeros(in(1,1));
n_max = in(1,2);
level = in(1,3);
ctr = 4;
%----------- Initialize LIP, LSP, LIS ----------------
temp = [];
bandsize = 2.^(log2(in(1,1)) - level + 1);
temp1 = 1 : bandsize;
for i = 1 : bandsize
temp = [temp; temp1];
end
LIP(:, 1) = temp(:);
temp = temp';
LIP(:, 2) = temp(:);
LIS(:, 1) = LIP(:, 1);
LIS(:, 2) = LIP(:, 2);
LIS(:, 3) = zeros(length(LIP(:, 1)), 1);
pstart = 1;
pend = bandsize / 2;
for i = 1 : bandsize / 2
LIS(pstart : pend, :) = [];
pdel = pend - pstart + 1;
pstart = pstart + bandsize - pdel;
pend = pend + bandsize - pdel;
end
LSP = [];
%----------- coding ----------------
n = n_max;
while (ctr <= size(in,2))
%Sorting Pass
LIPtemp = LIP; temp = 0;
for i = 1:size(LIPtemp,1)
temp = temp+1;
if ctr > size(in,2)
return
end
if in(1,ctr) == 1
ctr = ctr + 1;
if in(1,ctr) > 0
m(LIPtemp(i,1),LIPtemp(i,2)) = 2^n + 2^(n-1);
else
m(LIPtemp(i,1),LIPtemp(i,2)) = -2^n - 2^(n-1);
end
LSP = [LSP; LIPtemp(i,:)];
LIP(temp,:) = []; temp = temp - 1;
end
ctr = ctr + 1;
end
LIStemp = LIS; temp = 0; i = 1;
while ( i <= size(LIStemp,1))
temp = temp + 1;
if ctr > size(in,2)
return
end
if LIStemp(i,3) == 0
if in(1,ctr) == 1
ctr = ctr + 1;
x = LIStemp(i,1); y = LIStemp(i,2);
if ctr > size(in,2)
return
end
if in(1,ctr) == 1
LSP = [LSP; 2*x-1 2*y-1];
ctr = ctr + 1;
if in(1,ctr) == 1
m(2*x-1,2*y-1) = 2^n + 2^(n-1);
else
m(2*x-1,2*y-1) = -2^n - 2^(n-1);
end
ctr = ctr + 1;
else
LIP = [LIP; 2*x-1 2*y-1];
ctr = ctr + 1;
end
if ctr > size(in,2)
return
end
if in(1,ctr) == 1
ctr = ctr + 1;
LSP = [LSP; 2*x-1 2*y];
if in(1,ctr) == 1;
m(2*x-1,2*y) = 2^n + 2^(n-1);
else
m(2*x-1,2*y) = -2^n - 2^(n-1);
end
ctr = ctr + 1;
else
LIP = [LIP; 2*x-1 2*y];
ctr = ctr + 1;
end
if ctr > size(in,2)
return
end
if in(1,ctr) == 1
ctr = ctr + 1;
LSP = [LSP; 2*x 2*y-1];
if in(1,ctr) == 1
m(2*x,2*y-1) = 2^n + 2^(n-1);
else
m(2*x,2*y-1) = -2^n - 2^(n-1);
end
ctr = ctr + 1;
else
LIP = [LIP; 2*x 2*y-1];
ctr = ctr + 1;
end
if ctr > size(in,2)
return
end
if in(1,ctr) == 1
ctr = ctr + 1;
LSP = [LSP; 2*x 2*y];
if in(1,ctr) == 1
m(2*x,2*y) = 2^n + 2^(n-1);
else
m(2*x,2*y) = -2^n - 2^(n-1);
end
ctr = ctr + 1;
else
LIP = [LIP; 2*x 2*y];
ctr = ctr + 1;
end
if ((2*(2*x)-1) < size(m) & (2*(2*y)-1) < size(m))
LIS = [LIS; LIStemp(i,1) LIStemp(i,2) 1];
LIStemp = [LIStemp; LIStemp(i,1) LIStemp(i,2) 1];
end
LIS(temp,:) = []; temp = temp-1;
else
ctr = ctr + 1;
end
else
if in(1,ctr) == 1
x = LIStemp(i,1); y = LIStemp(i,2);
LIS = [LIS; 2*x-1 2*y-1 0; 2*x-1 2*y 0; 2*x 2*y-1 0; 2*x 2*y 0];
LIStemp = [LIStemp; 2*x-1 2*y-1 0; 2*x-1 2*y 0; 2*x 2*y-1 0; 2*x 2*y 0];
LIS(temp,:) = []; temp = temp - 1;
end
ctr = ctr + 1;
end
i = i+1;
end
% Refinement Pass
temp = 1;
value = m(LSP(temp,1), LSP(temp,2));
while (abs(value) >= 2^(n+1) & (temp <= size(LSP,1)))
if ctr > size(in,2)
return
end
value = value + ((-1)^(in(1,ctr) + 1)) * (2^(n-1))*sign(m(LSP(temp,1),LSP(temp,2)));
m(LSP(temp,1),LSP(temp,2)) = value;
ctr = ctr + 1;
temp = temp + 1;
if temp <= size(LSP,1)
value = m(LSP(temp,1),LSP(temp,2));
end
end
n = n-1;
end
function value = func_MyDescendant(i, j, type, m)
% Matlab implementation of SPIHT (without Arithmatic coding stage)
%
% Find the descendant with largest absolute value of pixel (i,j)
%
% input: i : row coordinate
% j : column coordinate
% type : type of descendant
% m : whole image
%
% output: value : largest absolute value
%
% Jing Tian
% Contact me : [email protected]
% This program is part of my undergraduate project in GuangZhou, P. R. China.
% April - July 1999
s = size(m,1);
S = [];
index = 0; a = 0; b = 0;
while ((2*i-1)<s & (2*j-1)<s)
a = i-1; b = j-1;
mind = [2*(a+1)-1:2*(a+2^index)];
nind = [2*(b+1)-1:2*(b+2^index)];
chk = mind <= s;
len = sum(chk);
if len < length(mind)
mind(len+1:length(mind)) = [];
end
chk = nind <= s;
len = sum(chk);
if len < length(nind)
nind(len+1:length(nind)) = [];
end
S = [S reshape(m(mind,nind),1,[])];
index = index + 1;
i = 2*a+1; j = 2*b+1;
end
if type == 1
S(:,1:4) = [];;
end
value = max(abs(S));
|
github
|
jacksky64/imageProcessing-master
|
perform_blsgsm_denoising.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/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_segmentation.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/perform_segmentation.m
| 5,024 |
utf_8
|
838e39d3911cf7fa55e00ec1a6c11952
|
function [B,err] = perform_segmentation(E,options)
% perform_segmentation - perform image segmentation
%
% B = perform_segmentation(E,options);
%
% E is an (n,n,k) set of k dimensional features vectors (one per pixel in
% the image).
%
% options.segmentation_method can be
% 'simple': E(:,:,k) should be minimum in area where texture i is
% present. The algorithm uses a simple filtering.
% 'chan-vese': E(:,:,k) should be minimum in area where texture i is
% present. The algorithm uses a Chan-Vese active contour.
% 'kmeans': E(i,j,:) is a feature vector around pixel (i,j).
% the algorithm compute feature center for each texture using
% k-means and then perform nearest-neighbors classification.
%
% Copyright (c) 2007 Gabriel Peyre
n = size(E,1);
ntextures = size(E,3);
segmentation_method = getoptions(options, 'segmentation_method', 'simple');
oracle = getoptions(options, 'oracle', []);
lambda = getoptions(options, 'lambda', 1.2);
% for testing various filtering sizes
if isempty(oracle)
nmu = 1;
mu = getoptions(options, 'mu', 4);
mu_list = mu;
else
nmu = getoptions(options, 'nmu', 18);
mumax = getoptions(options, 'mumax', 10);
mu_list = linspace( 0.1,mumax,nmu );
end
% best dictionary
switch segmentation_method
case 'simple'
q = size(E,3);
q1 = min(20,q); % PCA dimension
err_list = []; B1 = {};
for i=1:nmu
progressbar(i,nmu);
EE = perform_blurring(E,mu_list(i));
[tmp,B1{i}] = min(EE,[],3);
if not(isempty(oracle))
err_list(i) = 1 - sum( B1{i}(:)~=oracle(:) )/n^2;
else
err_list(i) = 0;
end
end
[err,i] = max(err_list);
B = B1{i};
case 'kmeans'
%% perform clustering via Kmeans
ntextures = getoptions(options, 'ntextures',[],1);
q = size(E,3);
q1 = min(20,q); % PCA dimension
err_list = []; B1 = {};
for i=1:nmu
progressbar(i,nmu);
% apply non-linearity + smoothing
E1 = perform_blurring(E,mu_list(i));
E1 = reshape(E1,[n^2 q])';
% add spacial relationship
% rescale the features
E1 = E1 - repmat(min(E1,[],2),[1 n^2]);
E1 = E1 ./ repmat( median(E1,2),[1 n^2]);
% dimension reduction
[Y,E1] = pca(E1,q1);
% do k-means on a subset
options.nb_iter = 50;
options.kmeans_code = 3;
[B1{i},seeds,rms] = perform_kmeans(E1,ntextures,options);
B1{i} = reshape(B1{i},n,n);
[B1{i},err_list(end+1)] = fit_segmentation(B1{i},oracle);
end
[err,i] = max(err_list);
B = B1{i};
case 'chan-vese'
% active contours
En = zeros(n,n,ntextures);
if ntextures==2
En = E(:,:,1)-E(:,:,2);
elseif ntextures==4
v = {[4 2] [3 1] [4 3] [2 1] };
for k=1:4
En(:,:,k) = E(:,:,v{k}(1))-E(:,:,v{k}(2)); a = En(:,:,k);
% En(:,:,k) = En(:,:,k)-median(a(:)); a = En(:,:,k);
% En(:,:,k) = lambda * En(:,:,k)/std( a(:) );
end
else
error('Works only for 2/4 textures');
end
% normalize
options.E = lambda * En/sqrt( mean(En(:).^2) );
if not(isfield(options, 'Tmax'))
options.Tmax = 180;
end
options.redistance_freq = 10;
options.dt = 0.5;
options.display_freq = 10;
if not(isfield(options, 'nb_svg'))
options.nb_svg = 0;
end
options.solver = 'grad';
namec = 'small-disks'; % initial shape
Dist0 = compute_levelset_shape(namec, n);
if ntextures==4 % shift this function for the other phase
sel = mod( (1:n) + 8,n )+1;
Dist0 = cat(3,Dist0,Dist0(sel,sel));
end
fprintf('Active contours:');
Dist = perform_active_contour(Dist0, 'chan-vese-user', options);
if ntextures==2
B = (Dist>0)+1;
else
B = zeros(n); D1 = Dist(:,:,1); D2 = Dist(:,:,2);
B(D1<0 & D2<0) = 1;
B(D1<0 & D2>=0) = 2;
B(D1>=0 & D2<0) = 3;
B(D1>=0 & D2>=0) = 4;
end
end
err = 0;
if not(isempty(oracle))
[B,err] = fit_segmentation(B,oracle);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [B,err] = fit_segmentation(B,B0)
if isempty(B0)
return;
end
n = size(B,1);
% check for optimal permutation to fit B0
ntextures = max(B(:));
P = perms(1:ntextures);
err1 = [];
for k=1:size(P,1)
pp = P(k,:)';
err1(k) = sum( P(k,B(:))'==B0(:) )/n^2;
end
[err,k] = max(err1);
B = reshape( P(k,B), size(B) );
|
github
|
jacksky64/imageProcessing-master
|
perform_histogram_matching_wavelet.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/perform_histogram_matching_wavelet.m
| 4,495 |
utf_8
|
2583a784c610f9a09bd02673493e83f1
|
function MW_src = perform_histogram_matching_wavelet(MW_src,MW_tgt, Jmin, options)
% perform_histogram_matching_wavelet - match the histogram of a wavelet transform
%
% Matching of wavelet coefficients only:
% options.dotransform=0
% MW_src = perform_histogram_matching_wavelet(MW_src,MW_tgt,Jmin,options);
% Matching of image + wavelet coefficients:
% options.dotransform=1
% M_src = perform_histogram_matching_wavelet(M_src,M_tgt,Jmin,options);
%
% Match the spacial histogram of the image and the histogram of each
% wavelet sub-band.
%
% Works also for color images.
%
% You can set options.use_histomatching=0 if you want to equalize the
% kurtosis and skewness of subbands and not their histograms
% (works well for natural images).
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin>=4
if ~isstruct(options)
error('options should be a structure.');
end
end
options.null = 0;
dotransform = getoptions(options, 'dotransform', 1);
niter_synthesis = getoptions(options, 'niter_synthesis', 1);
if nargin<3
Jmin = 3;
end
if niter_synthesis>1
options.niter_synthesis = 1;
for i=1:niter_synthesis
MW_src = perform_histogram_matching_wavelet(MW_src,MW_tgt, Jmin, options);
end
return;
end
if size(MW_src,3)==3
options.color_mode = 'pca';
[MW_src,options.ColorP] = change_color_mode(MW_src,+1,options);
[MW_tgt,options.ColorP] = change_color_mode(MW_tgt,+1,options);
for i=1:size(MW_src,3)
MW_src(:,:,i) = perform_histogram_matching_wavelet(MW_src(:,:,i),MW_tgt(:,:,i),Jmin, options);
end
[MW_src,options.ColorP] = change_color_mode(MW_src,-1,options);
return;
end
if size(MW_src,3)>1
for i=1:size(MW_src,3)
MW_src(:,:,i) = perform_histogram_matching_wavelet(MW_src(:,:,i),MW_tgt(:,:,i),Jmin, options);
end
return;
end
% for spacial histogram, do not consider absval
options.absval = 0;
options.rows = 0;
options.cols = 0;
if dotransform == 1
% perform image extension
n1 = size(MW_src,1);
n2 = size(MW_tgt,1);
n = max(n1,n2);
n = 2^( ceil(log2(n)) );
MW_src = perform_image_extension(MW_src,n);
MW_tgt = perform_image_extension(MW_tgt,n);
options.wavelet_type = 'biorthogonal_swapped';
options.wavelet_vm = 4;
% perform spacial matching
MW_src = perform_matching(MW_src, MW_tgt, options);
% compute transform
MW_src = perform_wavelet_transform(MW_src, Jmin, +1, options);
MW_tgt = perform_wavelet_transform(MW_tgt, Jmin, +1, options);
% perform coefficients matching
options.dotransform = 0;
MW_src = perform_histogram_matching_wavelet(MW_src,MW_tgt,Jmin, options);
% undo transforms
MW_src = perform_wavelet_transform(MW_src, Jmin, -1, options);
MW_tgt = perform_wavelet_transform(MW_tgt, Jmin, -1, options);
% perform spacial matching
MW_src = perform_matching(MW_src, MW_tgt, options);
MW_src = MW_src(1:n1,1:n1);
return;
end
if size(MW_src,1)~=size(MW_tgt,1)
error('Wavelets coefficients should be of the same size.');
end
mm = size(MW_src);
Jmax = log2(mm)-1;
for j=Jmax:-1:Jmin
for q=1:3
[selx,sely] = compute_quadrant_selection(j,q);
MW_src(selx,sely) = match_statistics(MW_src(selx,sely), MW_tgt(selx,sely), options);
end
end
% match low scales
selx = 1:2^Jmin; sely = 1:2^Jmin;
MW_src(selx,sely) = perform_matching(MW_src(selx,sely), MW_tgt(selx,sely), options);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = perform_matching(x,y, options)
% x = perform_histogram_matching(x,y, options);
x = perform_histogram_equalization(x,y, options);
function M = perform_image_extension(M,n)
m = size(M,1);
k = n-m;
while k>size(M,1)
M = perform_image_extension(M,size(M,1)*2);
k = k - size(M,1)/2;
end
M = [M; M(end:-1:end-k+1,:)];
M = [M, M(:,end:-1:end-k+1)];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = match_statistics(x,y, options)
options.null = 0;
if isfield(options, 'use_histomatching')
use_histomatching = options.use_histomatching;
else
use_histomatching = 1;
end
if isfield(options, 'nb_bins')
nb_bins = options.nb_bins;
else
nb_bins = 100;
end
if use_histomatching
options.absval = 1;
x = perform_matching(x, y, options);
else
x = perform_kurtosis_equalization(x,y);
end
|
github
|
jacksky64/imageProcessing-master
|
perform_steerable_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/perform_steerable_transform.m
| 62,306 |
utf_8
|
8682ba128191ecc103c6b02364081a6e
|
function y = perform_steerable_transform(x, Jmin,options)
% perform_steerable_transform - steerable pyramidal transform
%
% y = perform_steerable_transform(x, Jmin,options);
%
% This is just a convenient wrapper to the original steerable
% matlab toolbox of Simoncelli that can be downloaded from
% http://www.cns.nyu.edu/~eero/STEERPYR/
%
% It provide a simpler interface that directly output a cell
% array of images. Usage :
%
% M = load_image('lena');
% MS = perform_steerable_transform(M, 3); % synthesis
% M1 = perform_steerable_transform(MS); % reconstruction
%
% options.nb_orientations : number of orientation of the pyramid (1/2/4/6)
%
% Copyright (c) 2005 Gabriel Peyr?
if nargin<3
options.null = 0;
end
if nargin<2
Jmin = 4;
end
if isfield(options, 'nb_orientations')
nb_orientations = options.nb_orientations;
else
nb_orientations = 4; % can be 1/2/4/6
end
if nb_orientations~=1 && nb_orientations~=2 && nb_orientations~=4 && nb_orientations~=6
error('The number of orientation should be 1,2,4 or 6.');
end
filts = ['sp' num2str(nb_orientations-1) 'Filters'];
if ~iscell(x)
Jmax = log2(size(x,1))-1;
if Jmax-Jmin+1>5
warning('Cannot construct pyramid higher than 5 levels');
Jmin = Jmax-4;
end
nbr_bands = Jmax - Jmin + 1;
% fwd transform
[pyr,pind] = buildSpyr(x, nbr_bands, filts);
% copy into cell array
y = {};
for k=1:size(pind, 1)
indices = pyrBandIndices(pind,k);
L = length(indices); % length of this scale
y{k} = reshape( pyr(indices), sqrt(L), sqrt(L) );
end
else
n = size(x{1},1);
Jmax = log2(n)-1;
nbr_bands = Jmax - Jmin + 1;
% copy from cell array
pind = n ./ 2.^(0:nbr_bands-1);
pind = repmat(pind, nb_orientations, 1);
pind = [pind(:), pind(:)];
pind = [pind(1,:); pind];
pind = [pind; pind(end,:)/2];
% build the matrix
n = sum( prod(pind,2) );
pyr = zeros(n, 1);
for k=1:size(pind, 1)
indices = pyrBandIndices(pind,k);
L = length(indices); % length of this scale
pyr(indices) = x{k}(:);
end
% bwd transform
y = reconSpyr(pyr, pind, filts);
end
% [PYR, INDICES, STEERMTX, HARMONICS] = buildSpyr(IM, HEIGHT, FILTFILE, EDGES)
%
% Construct a steerable pyramid on matrix IM.
%
% 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];
% [PYR, INDICES, STEERMTX, HARMONICS] = buildSFpyr(IM, HEIGHT, ORDER, TWIDTH)
%
% Construct a steerable pyramid on matrix IM, in the Fourier domain.
% This is similar to buildSpyr, except that:
%
% + Reconstruction is exact (within floating point errors)
% + It can produce any number of orientation bands.
% - Typically slower, especially for non-power-of-two sizes.
% - Boundary-handling is circular.
%
% HEIGHT (optional) specifies the number of pyramid levels to build. Default
% is maxPyrHt(size(IM),size(FILT));
%
% The squared radial functions tile the Fourier plane, with a raised-cosine
% falloff. Angular functions are cos(theta-k\pi/(K+1))^K, where K is
% the ORDER (one less than the number of orientation bands, default= 3).
%
% 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).
%
% 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, 5/97.
% See http://www.cns.nyu.edu/~eero/STEERPYR/ for more
% information about the Steerable Pyramid image decomposition.
function [pyr,pind,steermtx,harmonics] = buildSFpyr(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] = buildSFpyrLevs(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];
% 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] = sp0Filters();
harmonics = [ 0 ];
lo0filt = [ ...
-4.514000e-04 -1.137100e-04 -3.725800e-04 -3.743860e-03 -3.725800e-04 -1.137100e-04 -4.514000e-04
-1.137100e-04 -6.119520e-03 -1.344160e-02 -7.563200e-03 -1.344160e-02 -6.119520e-03 -1.137100e-04
-3.725800e-04 -1.344160e-02 6.441488e-02 1.524935e-01 6.441488e-02 -1.344160e-02 -3.725800e-04
-3.743860e-03 -7.563200e-03 1.524935e-01 3.153017e-01 1.524935e-01 -7.563200e-03 -3.743860e-03
-3.725800e-04 -1.344160e-02 6.441488e-02 1.524935e-01 6.441488e-02 -1.344160e-02 -3.725800e-04
-1.137100e-04 -6.119520e-03 -1.344160e-02 -7.563200e-03 -1.344160e-02 -6.119520e-03 -1.137100e-04
-4.514000e-04 -1.137100e-04 -3.725800e-04 -3.743860e-03 -3.725800e-04 -1.137100e-04 -4.514000e-04];
lofilt = [ ...
-2.257000e-04 -8.064400e-04 -5.686000e-05 8.741400e-04 -1.862800e-04 -1.031640e-03 -1.871920e-03 -1.031640e-03 -1.862800e-04 8.741400e-04 -5.686000e-05 -8.064400e-04 -2.257000e-04
-8.064400e-04 1.417620e-03 -1.903800e-04 -2.449060e-03 -4.596420e-03 -7.006740e-03 -6.948900e-03 -7.006740e-03 -4.596420e-03 -2.449060e-03 -1.903800e-04 1.417620e-03 -8.064400e-04
-5.686000e-05 -1.903800e-04 -3.059760e-03 -6.401000e-03 -6.720800e-03 -5.236180e-03 -3.781600e-03 -5.236180e-03 -6.720800e-03 -6.401000e-03 -3.059760e-03 -1.903800e-04 -5.686000e-05
8.741400e-04 -2.449060e-03 -6.401000e-03 -5.260020e-03 3.938620e-03 1.722078e-02 2.449600e-02 1.722078e-02 3.938620e-03 -5.260020e-03 -6.401000e-03 -2.449060e-03 8.741400e-04
-1.862800e-04 -4.596420e-03 -6.720800e-03 3.938620e-03 3.220744e-02 6.306262e-02 7.624674e-02 6.306262e-02 3.220744e-02 3.938620e-03 -6.720800e-03 -4.596420e-03 -1.862800e-04
-1.031640e-03 -7.006740e-03 -5.236180e-03 1.722078e-02 6.306262e-02 1.116388e-01 1.348999e-01 1.116388e-01 6.306262e-02 1.722078e-02 -5.236180e-03 -7.006740e-03 -1.031640e-03
-1.871920e-03 -6.948900e-03 -3.781600e-03 2.449600e-02 7.624674e-02 1.348999e-01 1.576508e-01 1.348999e-01 7.624674e-02 2.449600e-02 -3.781600e-03 -6.948900e-03 -1.871920e-03
-1.031640e-03 -7.006740e-03 -5.236180e-03 1.722078e-02 6.306262e-02 1.116388e-01 1.348999e-01 1.116388e-01 6.306262e-02 1.722078e-02 -5.236180e-03 -7.006740e-03 -1.031640e-03
-1.862800e-04 -4.596420e-03 -6.720800e-03 3.938620e-03 3.220744e-02 6.306262e-02 7.624674e-02 6.306262e-02 3.220744e-02 3.938620e-03 -6.720800e-03 -4.596420e-03 -1.862800e-04
8.741400e-04 -2.449060e-03 -6.401000e-03 -5.260020e-03 3.938620e-03 1.722078e-02 2.449600e-02 1.722078e-02 3.938620e-03 -5.260020e-03 -6.401000e-03 -2.449060e-03 8.741400e-04
-5.686000e-05 -1.903800e-04 -3.059760e-03 -6.401000e-03 -6.720800e-03 -5.236180e-03 -3.781600e-03 -5.236180e-03 -6.720800e-03 -6.401000e-03 -3.059760e-03 -1.903800e-04 -5.686000e-05
-8.064400e-04 1.417620e-03 -1.903800e-04 -2.449060e-03 -4.596420e-03 -7.006740e-03 -6.948900e-03 -7.006740e-03 -4.596420e-03 -2.449060e-03 -1.903800e-04 1.417620e-03 -8.064400e-04
-2.257000e-04 -8.064400e-04 -5.686000e-05 8.741400e-04 -1.862800e-04 -1.031640e-03 -1.871920e-03 -1.031640e-03 -1.862800e-04 8.741400e-04 -5.686000e-05 -8.064400e-04 -2.257000e-04];
mtx = [ 1.000000 ];
hi0filt = [...
5.997200e-04 -6.068000e-05 -3.324900e-04 -3.325600e-04 -2.406600e-04 -3.325600e-04 -3.324900e-04 -6.068000e-05 5.997200e-04
-6.068000e-05 1.263100e-04 4.927100e-04 1.459700e-04 -3.732100e-04 1.459700e-04 4.927100e-04 1.263100e-04 -6.068000e-05
-3.324900e-04 4.927100e-04 -1.616650e-03 -1.437358e-02 -2.420138e-02 -1.437358e-02 -1.616650e-03 4.927100e-04 -3.324900e-04
-3.325600e-04 1.459700e-04 -1.437358e-02 -6.300923e-02 -9.623594e-02 -6.300923e-02 -1.437358e-02 1.459700e-04 -3.325600e-04
-2.406600e-04 -3.732100e-04 -2.420138e-02 -9.623594e-02 8.554893e-01 -9.623594e-02 -2.420138e-02 -3.732100e-04 -2.406600e-04
-3.325600e-04 1.459700e-04 -1.437358e-02 -6.300923e-02 -9.623594e-02 -6.300923e-02 -1.437358e-02 1.459700e-04 -3.325600e-04
-3.324900e-04 4.927100e-04 -1.616650e-03 -1.437358e-02 -2.420138e-02 -1.437358e-02 -1.616650e-03 4.927100e-04 -3.324900e-04
-6.068000e-05 1.263100e-04 4.927100e-04 1.459700e-04 -3.732100e-04 1.459700e-04 4.927100e-04 1.263100e-04 -6.068000e-05
5.997200e-04 -6.068000e-05 -3.324900e-04 -3.325600e-04 -2.406600e-04 -3.325600e-04 -3.324900e-04 -6.068000e-05 5.997200e-04 ];
bfilts = [ ...
-9.066000e-05 -1.738640e-03 -4.942500e-03 -7.889390e-03 -1.009473e-02 -7.889390e-03 -4.942500e-03 -1.738640e-03 -9.066000e-05 ...
-1.738640e-03 -4.625150e-03 -7.272540e-03 -7.623410e-03 -9.091950e-03 -7.623410e-03 -7.272540e-03 -4.625150e-03 -1.738640e-03 ...
-4.942500e-03 -7.272540e-03 -2.129540e-02 -2.435662e-02 -3.487008e-02 -2.435662e-02 -2.129540e-02 -7.272540e-03 -4.942500e-03 ...
-7.889390e-03 -7.623410e-03 -2.435662e-02 -1.730466e-02 -3.158605e-02 -1.730466e-02 -2.435662e-02 -7.623410e-03 -7.889390e-03 ...
-1.009473e-02 -9.091950e-03 -3.487008e-02 -3.158605e-02 9.464195e-01 -3.158605e-02 -3.487008e-02 -9.091950e-03 -1.009473e-02 ...
-7.889390e-03 -7.623410e-03 -2.435662e-02 -1.730466e-02 -3.158605e-02 -1.730466e-02 -2.435662e-02 -7.623410e-03 -7.889390e-03 ...
-4.942500e-03 -7.272540e-03 -2.129540e-02 -2.435662e-02 -3.487008e-02 -2.435662e-02 -2.129540e-02 -7.272540e-03 -4.942500e-03 ...
-1.738640e-03 -4.625150e-03 -7.272540e-03 -7.623410e-03 -9.091950e-03 -7.623410e-03 -7.272540e-03 -4.625150e-03 -1.738640e-03 ...
-9.066000e-05 -1.738640e-03 -4.942500e-03 -7.889390e-03 -1.009473e-02 -7.889390e-03 -4.942500e-03 -1.738640e-03 -9.066000e-05 ]';
% 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] = sp1Filters();
harmonics = [ 1 ];
%% filters only contain first harmonic.
mtx = eye(2);
lo0filt = [ ...
-8.701000e-05 -1.354280e-03 -1.601260e-03 -5.033700e-04 2.524010e-03 -5.033700e-04 -1.601260e-03 -1.354280e-03 -8.701000e-05
-1.354280e-03 2.921580e-03 7.522720e-03 8.224420e-03 1.107620e-03 8.224420e-03 7.522720e-03 2.921580e-03 -1.354280e-03
-1.601260e-03 7.522720e-03 -7.061290e-03 -3.769487e-02 -3.297137e-02 -3.769487e-02 -7.061290e-03 7.522720e-03 -1.601260e-03
-5.033700e-04 8.224420e-03 -3.769487e-02 4.381320e-02 1.811603e-01 4.381320e-02 -3.769487e-02 8.224420e-03 -5.033700e-04
2.524010e-03 1.107620e-03 -3.297137e-02 1.811603e-01 4.376250e-01 1.811603e-01 -3.297137e-02 1.107620e-03 2.524010e-03
-5.033700e-04 8.224420e-03 -3.769487e-02 4.381320e-02 1.811603e-01 4.381320e-02 -3.769487e-02 8.224420e-03 -5.033700e-04
-1.601260e-03 7.522720e-03 -7.061290e-03 -3.769487e-02 -3.297137e-02 -3.769487e-02 -7.061290e-03 7.522720e-03 -1.601260e-03
-1.354280e-03 2.921580e-03 7.522720e-03 8.224420e-03 1.107620e-03 8.224420e-03 7.522720e-03 2.921580e-03 -1.354280e-03
-8.701000e-05 -1.354280e-03 -1.601260e-03 -5.033700e-04 2.524010e-03 -5.033700e-04 -1.601260e-03 -1.354280e-03 -8.701000e-05
];
lofilt = [ ...
-4.350000e-05 1.207800e-04 -6.771400e-04 -1.243400e-04 -8.006400e-04 -1.597040e-03 -2.516800e-04 -4.202000e-04 1.262000e-03 -4.202000e-04 -2.516800e-04 -1.597040e-03 -8.006400e-04 -1.243400e-04 -6.771400e-04 1.207800e-04 -4.350000e-05 ; ...
1.207800e-04 4.460600e-04 -5.814600e-04 5.621600e-04 -1.368800e-04 2.325540e-03 2.889860e-03 4.287280e-03 5.589400e-03 4.287280e-03 2.889860e-03 2.325540e-03 -1.368800e-04 5.621600e-04 -5.814600e-04 4.460600e-04 1.207800e-04 ; ...
-6.771400e-04 -5.814600e-04 1.460780e-03 2.160540e-03 3.761360e-03 3.080980e-03 4.112200e-03 2.221220e-03 5.538200e-04 2.221220e-03 4.112200e-03 3.080980e-03 3.761360e-03 2.160540e-03 1.460780e-03 -5.814600e-04 -6.771400e-04 ; ...
-1.243400e-04 5.621600e-04 2.160540e-03 3.175780e-03 3.184680e-03 -1.777480e-03 -7.431700e-03 -9.056920e-03 -9.637220e-03 -9.056920e-03 -7.431700e-03 -1.777480e-03 3.184680e-03 3.175780e-03 2.160540e-03 5.621600e-04 -1.243400e-04 ; ...
-8.006400e-04 -1.368800e-04 3.761360e-03 3.184680e-03 -3.530640e-03 -1.260420e-02 -1.884744e-02 -1.750818e-02 -1.648568e-02 -1.750818e-02 -1.884744e-02 -1.260420e-02 -3.530640e-03 3.184680e-03 3.761360e-03 -1.368800e-04 -8.006400e-04 ; ...
-1.597040e-03 2.325540e-03 3.080980e-03 -1.777480e-03 -1.260420e-02 -2.022938e-02 -1.109170e-02 3.955660e-03 1.438512e-02 3.955660e-03 -1.109170e-02 -2.022938e-02 -1.260420e-02 -1.777480e-03 3.080980e-03 2.325540e-03 -1.597040e-03 ; ...
-2.516800e-04 2.889860e-03 4.112200e-03 -7.431700e-03 -1.884744e-02 -1.109170e-02 2.190660e-02 6.806584e-02 9.058014e-02 6.806584e-02 2.190660e-02 -1.109170e-02 -1.884744e-02 -7.431700e-03 4.112200e-03 2.889860e-03 -2.516800e-04 ; ...
-4.202000e-04 4.287280e-03 2.221220e-03 -9.056920e-03 -1.750818e-02 3.955660e-03 6.806584e-02 1.445500e-01 1.773651e-01 1.445500e-01 6.806584e-02 3.955660e-03 -1.750818e-02 -9.056920e-03 2.221220e-03 4.287280e-03 -4.202000e-04 ; ...
1.262000e-03 5.589400e-03 5.538200e-04 -9.637220e-03 -1.648568e-02 1.438512e-02 9.058014e-02 1.773651e-01 2.120374e-01 1.773651e-01 9.058014e-02 1.438512e-02 -1.648568e-02 -9.637220e-03 5.538200e-04 5.589400e-03 1.262000e-03 ; ...
-4.202000e-04 4.287280e-03 2.221220e-03 -9.056920e-03 -1.750818e-02 3.955660e-03 6.806584e-02 1.445500e-01 1.773651e-01 1.445500e-01 6.806584e-02 3.955660e-03 -1.750818e-02 -9.056920e-03 2.221220e-03 4.287280e-03 -4.202000e-04 ; ...
-2.516800e-04 2.889860e-03 4.112200e-03 -7.431700e-03 -1.884744e-02 -1.109170e-02 2.190660e-02 6.806584e-02 9.058014e-02 6.806584e-02 2.190660e-02 -1.109170e-02 -1.884744e-02 -7.431700e-03 4.112200e-03 2.889860e-03 -2.516800e-04 ; ...
-1.597040e-03 2.325540e-03 3.080980e-03 -1.777480e-03 -1.260420e-02 -2.022938e-02 -1.109170e-02 3.955660e-03 1.438512e-02 3.955660e-03 -1.109170e-02 -2.022938e-02 -1.260420e-02 -1.777480e-03 3.080980e-03 2.325540e-03 -1.597040e-03 ; ...
-8.006400e-04 -1.368800e-04 3.761360e-03 3.184680e-03 -3.530640e-03 -1.260420e-02 -1.884744e-02 -1.750818e-02 -1.648568e-02 -1.750818e-02 -1.884744e-02 -1.260420e-02 -3.530640e-03 3.184680e-03 3.761360e-03 -1.368800e-04 -8.006400e-04 ; ...
-1.243400e-04 5.621600e-04 2.160540e-03 3.175780e-03 3.184680e-03 -1.777480e-03 -7.431700e-03 -9.056920e-03 -9.637220e-03 -9.056920e-03 -7.431700e-03 -1.777480e-03 3.184680e-03 3.175780e-03 2.160540e-03 5.621600e-04 -1.243400e-04 ; ...
-6.771400e-04 -5.814600e-04 1.460780e-03 2.160540e-03 3.761360e-03 3.080980e-03 4.112200e-03 2.221220e-03 5.538200e-04 2.221220e-03 4.112200e-03 3.080980e-03 3.761360e-03 2.160540e-03 1.460780e-03 -5.814600e-04 -6.771400e-04 ; ...
1.207800e-04 4.460600e-04 -5.814600e-04 5.621600e-04 -1.368800e-04 2.325540e-03 2.889860e-03 4.287280e-03 5.589400e-03 4.287280e-03 2.889860e-03 2.325540e-03 -1.368800e-04 5.621600e-04 -5.814600e-04 4.460600e-04 1.207800e-04 ; ...
-4.350000e-05 1.207800e-04 -6.771400e-04 -1.243400e-04 -8.006400e-04 -1.597040e-03 -2.516800e-04 -4.202000e-04 1.262000e-03 -4.202000e-04 -2.516800e-04 -1.597040e-03 -8.006400e-04 -1.243400e-04 -6.771400e-04 1.207800e-04 -4.350000e-05 ];
hi0filt = [...
-9.570000e-04 -2.424100e-04 -1.424720e-03 -8.742600e-04 -1.166810e-03 -8.742600e-04 -1.424720e-03 -2.424100e-04 -9.570000e-04 ; ...
-2.424100e-04 -4.317530e-03 8.998600e-04 9.156420e-03 1.098012e-02 9.156420e-03 8.998600e-04 -4.317530e-03 -2.424100e-04 ; ...
-1.424720e-03 8.998600e-04 1.706347e-02 1.094866e-02 -5.897780e-03 1.094866e-02 1.706347e-02 8.998600e-04 -1.424720e-03 ; ...
-8.742600e-04 9.156420e-03 1.094866e-02 -7.841370e-02 -1.562827e-01 -7.841370e-02 1.094866e-02 9.156420e-03 -8.742600e-04 ; ...
-1.166810e-03 1.098012e-02 -5.897780e-03 -1.562827e-01 7.282593e-01 -1.562827e-01 -5.897780e-03 1.098012e-02 -1.166810e-03 ; ...
-8.742600e-04 9.156420e-03 1.094866e-02 -7.841370e-02 -1.562827e-01 -7.841370e-02 1.094866e-02 9.156420e-03 -8.742600e-04 ; ...
-1.424720e-03 8.998600e-04 1.706347e-02 1.094866e-02 -5.897780e-03 1.094866e-02 1.706347e-02 8.998600e-04 -1.424720e-03 ; ...
-2.424100e-04 -4.317530e-03 8.998600e-04 9.156420e-03 1.098012e-02 9.156420e-03 8.998600e-04 -4.317530e-03 -2.424100e-04 ; ...
-9.570000e-04 -2.424100e-04 -1.424720e-03 -8.742600e-04 -1.166810e-03 -8.742600e-04 -1.424720e-03 -2.424100e-04 -9.570000e-04 ];
bfilts = -[ ...
6.125880e-03 -8.052600e-03 -2.103714e-02 -1.536890e-02 -1.851466e-02 -1.536890e-02 -2.103714e-02 -8.052600e-03 6.125880e-03 ...
-1.287416e-02 -9.611520e-03 1.023569e-02 6.009450e-03 1.872620e-03 6.009450e-03 1.023569e-02 -9.611520e-03 -1.287416e-02 ...
-5.641530e-03 4.168400e-03 -2.382180e-02 -5.375324e-02 -2.076086e-02 -5.375324e-02 -2.382180e-02 4.168400e-03 -5.641530e-03 ...
-8.957260e-03 -1.751170e-03 -1.836909e-02 1.265655e-01 2.996168e-01 1.265655e-01 -1.836909e-02 -1.751170e-03 -8.957260e-03 ...
0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ...
8.957260e-03 1.751170e-03 1.836909e-02 -1.265655e-01 -2.996168e-01 -1.265655e-01 1.836909e-02 1.751170e-03 8.957260e-03 ...
5.641530e-03 -4.168400e-03 2.382180e-02 5.375324e-02 2.076086e-02 5.375324e-02 2.382180e-02 -4.168400e-03 5.641530e-03 ...
1.287416e-02 9.611520e-03 -1.023569e-02 -6.009450e-03 -1.872620e-03 -6.009450e-03 -1.023569e-02 9.611520e-03 1.287416e-02 ...
-6.125880e-03 8.052600e-03 2.103714e-02 1.536890e-02 1.851466e-02 1.536890e-02 2.103714e-02 8.052600e-03 -6.125880e-03; ...
...
-6.125880e-03 1.287416e-02 5.641530e-03 8.957260e-03 0.000000e+00 -8.957260e-03 -5.641530e-03 -1.287416e-02 6.125880e-03 ...
8.052600e-03 9.611520e-03 -4.168400e-03 1.751170e-03 0.000000e+00 -1.751170e-03 4.168400e-03 -9.611520e-03 -8.052600e-03 ...
2.103714e-02 -1.023569e-02 2.382180e-02 1.836909e-02 0.000000e+00 -1.836909e-02 -2.382180e-02 1.023569e-02 -2.103714e-02 ...
1.536890e-02 -6.009450e-03 5.375324e-02 -1.265655e-01 0.000000e+00 1.265655e-01 -5.375324e-02 6.009450e-03 -1.536890e-02 ...
1.851466e-02 -1.872620e-03 2.076086e-02 -2.996168e-01 0.000000e+00 2.996168e-01 -2.076086e-02 1.872620e-03 -1.851466e-02 ...
1.536890e-02 -6.009450e-03 5.375324e-02 -1.265655e-01 0.000000e+00 1.265655e-01 -5.375324e-02 6.009450e-03 -1.536890e-02 ...
2.103714e-02 -1.023569e-02 2.382180e-02 1.836909e-02 0.000000e+00 -1.836909e-02 -2.382180e-02 1.023569e-02 -2.103714e-02 ...
8.052600e-03 9.611520e-03 -4.168400e-03 1.751170e-03 0.000000e+00 -1.751170e-03 4.168400e-03 -9.611520e-03 -8.052600e-03 ...
-6.125880e-03 1.287416e-02 5.641530e-03 8.957260e-03 0.000000e+00 -8.957260e-03 -5.641530e-03 -1.287416e-02 6.125880e-03 ...
]';
% 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 ...
]';
% 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] = sp5Filters();
harmonics = [1 3 5];
mtx = [ ...
0.3333 0.2887 0.1667 0.0000 -0.1667 -0.2887
0.0000 0.1667 0.2887 0.3333 0.2887 0.1667
0.3333 -0.0000 -0.3333 -0.0000 0.3333 -0.0000
0.0000 0.3333 0.0000 -0.3333 0.0000 0.3333
0.3333 -0.2887 0.1667 -0.0000 -0.1667 0.2887
-0.0000 0.1667 -0.2887 0.3333 -0.2887 0.1667];
hi0filt = [
-0.00033429 -0.00113093 -0.00171484 -0.00133542 -0.00080639 -0.00133542 -0.00171484 -0.00113093 -0.00033429
-0.00113093 -0.00350017 -0.00243812 0.00631653 0.01261227 0.00631653 -0.00243812 -0.00350017 -0.00113093
-0.00171484 -0.00243812 -0.00290081 -0.00673482 -0.00981051 -0.00673482 -0.00290081 -0.00243812 -0.00171484
-0.00133542 0.00631653 -0.00673482 -0.07027679 -0.11435863 -0.07027679 -0.00673482 0.00631653 -0.00133542
-0.00080639 0.01261227 -0.00981051 -0.11435863 0.81380200 -0.11435863 -0.00981051 0.01261227 -0.00080639
-0.00133542 0.00631653 -0.00673482 -0.07027679 -0.11435863 -0.07027679 -0.00673482 0.00631653 -0.00133542
-0.00171484 -0.00243812 -0.00290081 -0.00673482 -0.00981051 -0.00673482 -0.00290081 -0.00243812 -0.00171484
-0.00113093 -0.00350017 -0.00243812 0.00631653 0.01261227 0.00631653 -0.00243812 -0.00350017 -0.00113093
-0.00033429 -0.00113093 -0.00171484 -0.00133542 -0.00080639 -0.00133542 -0.00171484 -0.00113093 -0.00033429];
lo0filt = [
0.00341614 -0.01551246 -0.03848215 -0.01551246 0.00341614
-0.01551246 0.05586982 0.15925570 0.05586982 -0.01551246
-0.03848215 0.15925570 0.40304148 0.15925570 -0.03848215
-0.01551246 0.05586982 0.15925570 0.05586982 -0.01551246
0.00341614 -0.01551246 -0.03848215 -0.01551246 0.00341614];
lofilt = 2*[
0.00085404 -0.00244917 -0.00387812 -0.00944432 -0.00962054 -0.00944432 -0.00387812 -0.00244917 0.00085404
-0.00244917 -0.00523281 -0.00661117 0.00410600 0.01002988 0.00410600 -0.00661117 -0.00523281 -0.00244917
-0.00387812 -0.00661117 0.01396746 0.03277038 0.03981393 0.03277038 0.01396746 -0.00661117 -0.00387812
-0.00944432 0.00410600 0.03277038 0.06426333 0.08169618 0.06426333 0.03277038 0.00410600 -0.00944432
-0.00962054 0.01002988 0.03981393 0.08169618 0.10096540 0.08169618 0.03981393 0.01002988 -0.00962054
-0.00944432 0.00410600 0.03277038 0.06426333 0.08169618 0.06426333 0.03277038 0.00410600 -0.00944432
-0.00387812 -0.00661117 0.01396746 0.03277038 0.03981393 0.03277038 0.01396746 -0.00661117 -0.00387812
-0.00244917 -0.00523281 -0.00661117 0.00410600 0.01002988 0.00410600 -0.00661117 -0.00523281 -0.00244917
0.00085404 -0.00244917 -0.00387812 -0.00944432 -0.00962054 -0.00944432 -0.00387812 -0.00244917 0.00085404];
bfilts = [...
0.00277643 0.00496194 0.01026699 0.01455399 0.01026699 0.00496194 0.00277643 ...
-0.00986904 -0.00893064 0.01189859 0.02755155 0.01189859 -0.00893064 -0.00986904 ...
-0.01021852 -0.03075356 -0.08226445 -0.11732297 -0.08226445 -0.03075356 -0.01021852 ...
0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 ...
0.01021852 0.03075356 0.08226445 0.11732297 0.08226445 0.03075356 0.01021852 ...
0.00986904 0.00893064 -0.01189859 -0.02755155 -0.01189859 0.00893064 0.00986904 ...
-0.00277643 -0.00496194 -0.01026699 -0.01455399 -0.01026699 -0.00496194 -0.00277643;
...
-0.00343249 -0.00640815 -0.00073141 0.01124321 0.00182078 0.00285723 0.01166982 ...
-0.00358461 -0.01977507 -0.04084211 -0.00228219 0.03930573 0.01161195 0.00128000 ...
0.01047717 0.01486305 -0.04819057 -0.12227230 -0.05394139 0.00853965 -0.00459034 ...
0.00790407 0.04435647 0.09454202 -0.00000000 -0.09454202 -0.04435647 -0.00790407 ...
0.00459034 -0.00853965 0.05394139 0.12227230 0.04819057 -0.01486305 -0.01047717 ...
-0.00128000 -0.01161195 -0.03930573 0.00228219 0.04084211 0.01977507 0.00358461 ...
-0.01166982 -0.00285723 -0.00182078 -0.01124321 0.00073141 0.00640815 0.00343249;
...
0.00343249 0.00358461 -0.01047717 -0.00790407 -0.00459034 0.00128000 0.01166982 ...
0.00640815 0.01977507 -0.01486305 -0.04435647 0.00853965 0.01161195 0.00285723 ...
0.00073141 0.04084211 0.04819057 -0.09454202 -0.05394139 0.03930573 0.00182078 ...
-0.01124321 0.00228219 0.12227230 -0.00000000 -0.12227230 -0.00228219 0.01124321 ...
-0.00182078 -0.03930573 0.05394139 0.09454202 -0.04819057 -0.04084211 -0.00073141 ...
-0.00285723 -0.01161195 -0.00853965 0.04435647 0.01486305 -0.01977507 -0.00640815 ...
-0.01166982 -0.00128000 0.00459034 0.00790407 0.01047717 -0.00358461 -0.00343249;
...
-0.00277643 0.00986904 0.01021852 -0.00000000 -0.01021852 -0.00986904 0.00277643 ...
-0.00496194 0.00893064 0.03075356 -0.00000000 -0.03075356 -0.00893064 0.00496194 ...
-0.01026699 -0.01189859 0.08226445 -0.00000000 -0.08226445 0.01189859 0.01026699 ...
-0.01455399 -0.02755155 0.11732297 -0.00000000 -0.11732297 0.02755155 0.01455399 ...
-0.01026699 -0.01189859 0.08226445 -0.00000000 -0.08226445 0.01189859 0.01026699 ...
-0.00496194 0.00893064 0.03075356 -0.00000000 -0.03075356 -0.00893064 0.00496194 ...
-0.00277643 0.00986904 0.01021852 -0.00000000 -0.01021852 -0.00986904 0.00277643;
...
-0.01166982 -0.00128000 0.00459034 0.00790407 0.01047717 -0.00358461 -0.00343249 ...
-0.00285723 -0.01161195 -0.00853965 0.04435647 0.01486305 -0.01977507 -0.00640815 ...
-0.00182078 -0.03930573 0.05394139 0.09454202 -0.04819057 -0.04084211 -0.00073141 ...
-0.01124321 0.00228219 0.12227230 -0.00000000 -0.12227230 -0.00228219 0.01124321 ...
0.00073141 0.04084211 0.04819057 -0.09454202 -0.05394139 0.03930573 0.00182078 ...
0.00640815 0.01977507 -0.01486305 -0.04435647 0.00853965 0.01161195 0.00285723 ...
0.00343249 0.00358461 -0.01047717 -0.00790407 -0.00459034 0.00128000 0.01166982;
...
-0.01166982 -0.00285723 -0.00182078 -0.01124321 0.00073141 0.00640815 0.00343249 ...
-0.00128000 -0.01161195 -0.03930573 0.00228219 0.04084211 0.01977507 0.00358461 ...
0.00459034 -0.00853965 0.05394139 0.12227230 0.04819057 -0.01486305 -0.01047717 ...
0.00790407 0.04435647 0.09454202 -0.00000000 -0.09454202 -0.04435647 -0.00790407 ...
0.01047717 0.01486305 -0.04819057 -0.12227230 -0.05394139 0.00853965 -0.00459034 ...
-0.00358461 -0.01977507 -0.04084211 -0.00228219 0.03930573 0.01161195 0.00128000 ...
-0.00343249 -0.00640815 -0.00073141 0.01124321 0.00182078 0.00285723 0.01166982]';
% HEIGHT = maxPyrHt(IMSIZE, FILTSIZE)
%
% Compute maximum pyramid height for given image and filter sizes.
% Specifically: the number of corrDn operations that can be sequentially
% performed when subsampling by a factor of 2.
% Eero Simoncelli, 6/96.
function height = maxPyrHt(imsz, filtsz)
imsz = imsz(:);
filtsz = filtsz(:);
if any(imsz == 1) % 1D image
imsz = prod(imsz);
filtsz = prod(filtsz);
elseif any(filtsz == 1) % 2D image, 1D filter
filtsz = [filtsz(1); filtsz(1)];
end
if any(imsz < filtsz)
height = 0;
else
height = 1 + maxPyrHt( floor(imsz/2), filtsz );
end
% RES = corrDn(IM, FILT, EDGES, STEP, START, STOP)
%
% Compute correlation of matrices IM with FILT, followed by
% downsampling. 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 input boundaries
%
% Downsampling factors are determined by STEP (optional, default=[1 1]),
% which should be a 2-vector [y,x].
%
% The window over which the convolution occurs is specfied by START
% (optional, default=[1,1], and STOP (optional, default=size(IM)).
%
% NOTE: this operation corresponds to multiplication of a signal
% vector by a matrix whose rows contain copies of the FILT shifted by
% multiples of STEP. See upConv.m for the operation corresponding to
% the transpose of this matrix.
% Eero Simoncelli, 6/96, revised 2/97.
function res = corrDn(im, filt, edges, step, start, stop)
%% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD)
% fprintf(1,'WARNING: You should compile the MEX version of "corrDn.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
if (exist('stop') ~= 1)
stop = size(im);
end
%------------------------------------------------------------
% Reverse order of taps in filt, to do correlation instead of convolution
filt = filt(size(filt,1):-1:1,size(filt,2):-1:1);
tmp = rconv2(im,filt);
res = tmp(start(1):step(1):stop(1),start(2):step(2):stop(2));
% 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');
% [PYR, INDICES] = buildSpyrLevs(LOIM, HEIGHT, LOFILT, BFILTS, EDGES)
%
% Recursive function for constructing levels of a steerable pyramid. This
% is called by buildSpyr, and is not usually called directly.
% Eero Simoncelli, 6/96.
function [pyr,pind] = buildSpyrLevs(lo0,ht,lofilt,bfilts,edges);
if (ht <= 0)
pyr = lo0(:);
pind = size(lo0);
else
% Assume square filters:
bfiltsz = round(sqrt(size(bfilts,1)));
bands = zeros(prod(size(lo0)),size(bfilts,2));
bind = zeros(size(bfilts,2),2);
for b = 1:size(bfilts,2)
filt = reshape(bfilts(:,b),bfiltsz,bfiltsz);
band = corrDn(lo0, filt, edges);
bands(:,b) = band(:);
bind(b,:) = size(band);
end
lo = corrDn(lo0, lofilt, edges, [2 2], [1 1]);
[npyr,nind] = buildSpyrLevs(lo, ht-1, lofilt, bfilts, edges);
pyr = [bands(:); npyr];
pind = [bind; nind];
end
% 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;
% RES = reconSpyr(PYR, INDICES, FILTFILE, EDGES, LEVS, BANDS)
%
% Reconstruct image from its steerable pyramid representation, as created
% by buildSpyr.
%
% 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.
%
% FILTFILE (optional) should be a string referring to an m-file that returns
% the rfilters. examples: sp0Filters, sp1Filters, sp3Filters
% (default = 'sp1Filters').
% EDGES specifies edge-handling, and defaults to 'reflect1' (see
% corrDn).
%
% 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.
% Eero Simoncelli, 6/96.
function res = reconSpyr(pyr, pind, filtfile, edges, levs, bands)
%%------------------------------------------------------------
%% DEFAULTS:
if (exist('filtfile') ~= 1)
filtfile = 'sp1Filters';
end
if (exist('edges') ~= 1)
edges= 'reflect1';
end
if (exist('levs') ~= 1)
levs = 'all';
end
if (exist('bands') ~= 1)
bands = 'all';
end
%%------------------------------------------------------------
if (isstr(filtfile) & (exist(filtfile) == 2))
[lo0filt,hi0filt,lofilt,bfilts,steermtx,harmonics] = eval(filtfile);
nbands = spyrNumBands(pind);
if ((nbands > 0) & (size(bfilts,2) ~= nbands))
error('Number of pyramid bands is inconsistent with filter file');
end
else
error('filtfile argument must be the name of an M-file containing SPYR filters.');
end
maxLev = 1+spyrHt(pind);
if strcmp(levs,'all')
levs = [0:maxLev]';
else
if (any(levs > maxLev) | any(levs < 0))
error(sprintf('Level numbers must be in the range [0, %d].', maxLev));
end
levs = levs(:);
end
if strcmp(bands,'all')
bands = [1:nbands]';
else
if (any(bands < 1) | any(bands > nbands))
error(sprintf('Band numbers must be in the range [1,3].', nbands));
end
bands = bands(:);
end
if (spyrHt(pind) == 0)
if (any(levs==1))
res1 = pyrBand(pyr,pind,2);
else
res1 = zeros(pind(2,:));
end
else
res1 = reconSpyrLevs(pyr(1+prod(pind(1,:)):size(pyr,1)), ...
pind(2:size(pind,1),:), ...
lofilt, bfilts, edges, levs, bands);
end
res = upConv(res1, lo0filt, edges);
%% residual highpass subband
if any(levs == 0)
upConv( subMtx(pyr, pind(1,:)), hi0filt, edges, [1 1], [1 1], size(res), res);
end
% [NBANDS] = spyrNumBands(INDICES)
%
% Compute number of orientation bands in a steerable pyramid with
% given index matrix. If the pyramid contains only the highpass and
% lowpass bands (i.e., zero levels), returns 0.
% Eero Simoncelli, 2/97.
function [nbands] = spyrNumBands(pind)
if (size(pind,1) == 2)
nbands = 0;
else
% Count number of orientation bands:
b = 3;
while ((b <= size(pind,1)) & all( pind(b,:) == pind(2,:)) )
b = b+1;
end
nbands = b-2;
end
% [HEIGHT] = spyrHt(INDICES)
%
% Compute height of steerable pyramid with given index matrix.
% Eero Simoncelli, 6/96.
function [ht] = spyrHt(pind)
nbands = spyrNumBands(pind);
% Don't count lowpass, or highpass residual bands
if (size(pind,1) > 2)
ht = (size(pind,1)-2)/nbands;
else
ht = 0;
end
% RES = reconSpyrLevs(PYR,INDICES,LOFILT,BFILTS,EDGES,LEVS,BANDS)
%
% Recursive function for reconstructing levels of a steerable pyramid
% representation. This is called by reconSpyr, and is not usually
% called directly.
% Eero Simoncelli, 6/96.
function res = reconSpyrLevs(pyr,pind,lofilt,bfilts,edges,levs,bands);
nbands = size(bfilts,2);
lo_ind = nbands+1;
res_sz = pind(1,:);
% Assume square filters:
bfiltsz = round(sqrt(size(bfilts,1)));
if any(levs > 1)
if (size(pind,1) > lo_ind)
nres = reconSpyrLevs( pyr(1+sum(prod(pind(1:lo_ind-1,:)')):size(pyr,1)), ...
pind(lo_ind:size(pind,1),:), ...
lofilt, bfilts, edges, levs-1, bands);
else
nres = pyrBand(pyr,pind,lo_ind); % lowpass subband
end
res = upConv(nres, lofilt, edges, [2 2], [1 1], res_sz);
else
res = zeros(res_sz);
end
if any(levs == 1)
ind = 1;
for b = 1:nbands
if any(bands == b)
bfilt = reshape(bfilts(:,b), bfiltsz, bfiltsz);
upConv(reshape(pyr(ind:ind+prod(res_sz)-1), res_sz(1), res_sz(2)), ...
bfilt, edges, [1 1], [1 1], res_sz, res);
end
ind = ind + prod(res_sz);
end
end
% 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 = 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 = OLD_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;
% MTX = subMtx(VEC, DIMENSIONS, START_INDEX)
%
% Reshape a portion of VEC starting from START_INDEX (optional,
% default=1) to the given dimensions.
% Eero Simoncelli, 6/96.
function mtx = subMtx(vec, sz, offset)
if (exist('offset') ~= 1)
offset = 1;
end
vec = vec(:);
sz = sz(:);
if (size(sz,1) ~= 2)
error('DIMENSIONS must be a 2-vector.');
end
mtx = reshape( vec(offset:offset+prod(sz)-1), sz(1), sz(2) );
|
github
|
jacksky64/imageProcessing-master
|
perform_quincunx_wavelet_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/perform_quincunx_wavelet_transform.m
| 23,730 |
utf_8
|
1adf6e891e72693338d272d2f7c03be8
|
function [y,quincunx_filters] = perform_quincunx_wavelet_transform(x,Jmin,dir,options)
% perform_quincunx_wavelet_transform - compute quincunx transform
%
% Forward transform
% [MW,options.quincunx_filters] = perform_quincunx_wavelet_transform(M,Jmin,+1,options);
% Backward transform
% M = perform_quincunx_wavelet_transform(MW,Jmin,-1,options);
%
% This is a simple wrapper to the code of
% Dimitri Van De Ville
% Biomedical Imaging Group, BIO-E/STI
% Swiss Federal Institute of Technology Lausanne
% CH-1015 Lausanne EPFL, Switzerland
%
% For more information, see
% Isotropic Polyharmonic B-Splines: Scaling Functions and Wavelets
% D. Van De Ville, T. Blu, M. Unser
% IEEE Transactions on Image Processing, vol. 14, no. 11, pp. 1798-1813, November 2005.
%
% options.type is the type of transform:
% - McClellan: O/B/D,
% - Polyharmonic Rabut: Po/Pb/Pd
% - Polyharmonic isotropic: PO/PB/PD
% options.gamma is the degree of the wavelet transform
options.null = 0;
% Setup parameters of wavelet transform
% -------------------------------------
% 1. Type of wavelet transform
% - McClellan: O/B/D,
% - Polyharmonic Rabut: Po/Pb/Pd
% - Polyharmonic isotropic: PO/PB/PD
if isfield(options, 'type')
type = options.type;
else
type='PO';
end
% 2. Degree of the wavelet transform
% (order gamma polyharmonic=degree alpha+2)
if isfield(options, 'gamma')
gamma = options.gamma;
else
gamma = 4;
end
alpha=gamma-2;
% 3. Number of iterations
n = size(x,1);
Jmax = log2(n)-1;
J = 2*(Jmax-Jmin+1);
% Precalculate filters
% --------------------
if isfield(options, 'quincunx_filters')
quincunx_filters = options.quincunx_filters;
FA = quincunx_filters{1};
FS = quincunx_filters{2};
else
[FA,FS]=FFTquincunxfilter2D([size(x)],alpha,type);
quincunx_filters{1} = FA;
quincunx_filters{2} = FS;
end
% Perform wavelet analysis
% ------------------------
if dir==1
y = FFTquin2D_analysis(x,J,FA); y=real(y);
else
y = FFTquin2D_synthesis(x,J,FS);
end
function A0=autocorr2d(H)
% AUTOCORR2D
% Iterative frequency domain calculation of the 2D autocorrelation
% function. A=autocorr2d(H) computes the frequency response of
% the autocorrelation filter A(exp(2*i*Pi*nu)) corresponding to the
% scaling function with refinement filter H.
% Please note that the 2D grid of the refinement filter (nu),
% corresponds to a uniformly sampled grid, twice as coarse
% (in each dimension) as the given filter H.
%
% Please treat this source code as confidential!
% Its content is part of work in preparation to be submitted:
%
% T. Blu, D. Van De Ville, M. Unser, ''Numerical methods for the computation
% of wavelet correlation sequences,'' SIAM Numerical Analysis.
%
% Biomedical Imaging Group, EPFL, Lausanne, Switzerland.
len1=size(H,1)/2;
len2=size(H,2)/2;
% stop criterion
crit=1e-4;
improvement=1.0;
% initial "guess"
A0=ones(len1,len2);
% calculation loop
while improvement>crit,
% sinc interpolation
if 1,
Af=fftshift(ifftn(A0));
Af(1,:)=Af(1,:)/2;
Af(:,1)=Af(:,1)/2;
Af(len1+1,1:len2)=Af(1,len2:-1:1);
Af(1:len1,len2+1)=Af(len1:-1:1,1);
Ai=zeros(2*len1,2*len2);
Ai(len1-len1/2+1:len1+len1/2+1,len2-len2/2+1:len2+len2/2+1)=Af;
Ai=fftn(ifftshift(Ai));
else
Ai=interp2(A0,1,'nearest'); Ai(:,end+1)=Ai(:,end); Ai(end+1,:)=Ai(end,:);
end;
% recursion
A1=Ai(1:len1,1:len2).*H(1:len1,1:len2)+Ai(len1+1:2*len1,1:len2).*H(len1+1:2*len1,1:len2)+Ai(1:len1,len2+1:2*len2).*H(1:len1,len2+1:2*len2)+Ai(len1+1:2*len1,len2+1:2*len2).*H(len1+1:2*len1,len2+1:2*len2);
improvement=mean(abs(A1(:)-A0(:)));
A0=A1;
end;
function y2=FFTquin2D_analysis(x,J,FA);
% FFTQUIN2D_ANALYSIS Perform 2D quincunx wavelet analysis
% y2 = FFTquin2D_analysis(x,J,FA)
%
% Input:
% x = input data
% J = number of iterations
% FA = analysis filters
%
% Output:
% y2 = result (folded)
%
% Dimitri Van De Ville
% Biomedical Imaging Group, BIO-E/STI
% Swiss Federal Institute of Technology Lausanne
% CH-1015 Lausanne EPFL, Switzerland
% Dimensions of data
[m,n]=size(x);
% Dimensions of remaining folded lowpass subband
cm=m; cn=n;
% Check dimensions of input data
for iter=1:2,
tmp=size(x,iter)/2^floor((J+2-iter)/2);
if round(tmp)~=tmp,
disp(' ')
disp('The size of the input signal must be a sufficient power of two!')
disp(' ')
y2=[];
return;
end;
end;
% Analysis filters:
% H1, G1 : filters for iterations with mod(j,2)=1
% H1D, G1D : filters for iterations with mod(j,2)=0
% (premultiply analysis filters by the downsampling factor; i.e., det(D)=2)
H1=FA(:,:,1)/2;
G1=FA(:,:,2)/2;
H1D=FA(:,:,3)/2;
G1D=FA(:,:,4)/2;
% Compute the FFT of the input data
X=fftn(x); clear x;
% Initialize cube for folded wavelet coefficients
y2=zeros(cm,cn);
for j=1:J,
mj=mod(j,2);
% Select filter
switch mj,
case 1,
H=H1;
G=G1;
case 0,
H=H1D;
G=G1D;
end;
% Filtering
Y1=H(1:size(X,1),1:size(X,2)).*X;
Y2=G(1:size(X,1),1:size(X,2)).*X;
% Downsampling & upsampling
switch mj,
case 1,
if j~=J,
% This operates like: Y1=Y1+fftshift(Y1); Y1=Y1(1:cm,1:cn/2);
Y1(1:cm/2,1:cn/2)=Y1(1:cm/2,1:cn/2)+Y1(cm/2+1:cm,cn/2+1:cn);
Y1(cm/2+1:cm,1:cn/2)=Y1(cm/2+1:cm,1:cn/2)+Y1(1:cm/2,cn/2+1:cn);
Y1=Y1(1:cm,1:cn/2);
else
Y1=Y1+fftshift(Y1);
end;
Y2=Y2 + fftshift(Y2);
%! y2(1:cm,cn/2+1:cn)=fold2D(real(ifftn(Y2)),mj,m,n);
y2(1:cm,cn/2+1:cn)=fold2D((ifftn(Y2)),mj,m,n);
cn=cn/2;
case 0,
m2=m/2;n2=n/2;
Y1=Y1(1:m2,1:n2)+Y1(m2+1:2*m2,1:n2);
Y2=Y2(1:m2,1:n2)+Y2(m2+1:2*m2,1:n2);
y2(cm/2+1:cm,1:cn)=real(ifftn(Y2));
cm=cm/2;
% Preparing filters for next three iterations
lm=1:2:m; ln=1:2:n;
H1=H1(lm,ln);
G1=G1(lm,ln);
H1D=H1D(lm,ln);
G1D=G1D(lm,ln);
m=m2; n=n2;
end;
X=Y1;
end;
% Insert folded lowpass subband
y2(1:cm,1:cn)=fold2D(real(ifftn(Y1)),mj,m,n);
return;
% ----------------------------------------------------------------------
% Fold 2D subband
% ----------------------------------------------------------------------
function f=fold2D(u,j,m,n)
switch j,
case 0,
f=u;
case 1,
f=u(:,1:2:n)+u(:,2:2:n);
end;
function x=FFTquin2D_synthesis(y2,J,FS);
% FFTQUIN2D_SYNTHESIS Perform 2D quincunx wavelet synthesis
% x = FFTquin2D_synthesis(y2,J,FS)
%
% Input:
% y2 = data (folded)
% J = number of interations
% FS = synthesis filters
%
% Output:
% x = result (unfolded)
%
% Dimitri Van De Ville
% Biomedical Imaging Group, BIO-E/STI
% Swiss Federal Institute of Technology Lausanne
% CH-1015 Lausanne EPFL, Switzerland
% Dimensions of input data
[m,n]=size(y2);
% Synthesis filters:
% H1, G1 : filters for iterations with mod(j,2)=1
% H1D, G1D : filters for iterations with mod(j,2)=0
H1=FS(:,:,1);
G1=FS(:,:,2);
H1D=FS(:,:,3);
G1D=FS(:,:,4);
% How many "double-iterations"?
l=2^((J-mod(J,2))/2);
M=m/l; N=n/l;
% Dimensions of full data
[M0,N0,P0]=size(H1);
% Dimensions of folded lowpass subband
cm=M0; cn=N0;
cn=cn/2^floor((J+1)/2);
cm=cm/2^floor((J)/2);
% Extract folded lowpass subband and unfold
y1=y2(1:cm,1:cn);
y1=unfold2D(y1,mod(J,2),M,N);
Y1=fftn(y1); clear y1;
j=J;
while j>0;
mj=mod(j,2);
% unfold highpass subband and select filters
switch mj,
case 1,
f=unfold2D(y2(1:M,N/2+1:N),mj,M,N);
H=H1(1:l:M0,1:l:N0);
G=G1(1:l:M0,1:l:N0);
case 0,
f=unfold2D(y2(M+1:2*M,1:N),mj,M,N);
l=l/2;
Y1=[Y1 Y1;Y1 Y1];
H=H1D(1:l:M0,1:l:N0);
G=G1D(1:l:M0,1:l:N0);
end;
Y2=fftn(f); clear f;
if mj==0,
Y2=[Y2 Y2;Y2 Y2];
M=2*M; N=2*N;
end;
% filter data
Y1=Y1.*H + Y2.*G;
j=j-1;
end;
x=real(ifftn(Y1));
return;
% ----------------------------------------------------------------------
% Unfold 2D subband
% ----------------------------------------------------------------------
function u=unfold2D(y,j,M,N)
switch j,
case 0,
u=y;
case 1,
u=zeros(M,N);
u(1:2:M,1:2:N)=y(1:2:M,:);
u(2:2:M,2:2:N)=y(2:2:M,:);
end;
return;
function [FA,FS]=FFTquincunxfilter2D(dim,alpha,type);
% FFTQUINCUNXFILTER2D Supplies filters for the 2D quincunx transform.
% [FFTanalysisfilters,FFTsynthesisfilters]=FFTquincunxfilter2D(dim,alpha,type)
% computes the frequency response of low- and high-pass filters.
%
% Input:
% dim = dimensions of the input signal
% alpha = degree of the filters, any real number >=0
% type =
% class I: McClellan-based filters
% o = orthogonal; b = discrete linear B-spline (synthesis); d = dual
% class II: Polyharmonic B-spline wavelets (Rabut-style localization)
% Po = orthogonal; Pb = B-spline; Pd = dual
% class III: Polyharmonic B-spline wavelets (isotropic-style
% localization)
% PO = orthogonal {=Po}; PB = B-spline; PD = dual
%
% Dimitri Van De Ville
% Biomedical Imaging Group, BIO-E/STI
% Swiss Federal Institute of Technology Lausanne
% CH-1015 Lausanne EPFL, Switzerland
m=dim(1);
n=dim(2);
gamma=alpha+2;
% Setup downsampling matrix
D=[1 1; 1 -1]';
% Coordinates in the Fourier domain
[xo,yo]=ndgrid(2*pi*([1:m]-1)/m,2*pi*([1:n]-1)/n);
for iter=0:1,
if iter==0, % First filter: no downsampling
x=xo;
y=yo;
end;
if iter>0, % Coordinates after downsampling
x=D(1,1)*xo+D(1,2)*yo;
y=D(2,1)*xo+D(2,2)*yo;
% D=D*D; % prepare filter for next iteration
end;
if lower(type(1)) == 'p', % Isotropic polyharmonic splines
if iter==0,
[ac,acD,loc,B] = FFTquincunxpolyfilter(x,y,gamma,type(2));
else
%ac = fftshift(interp2(xo,yo,ac,mod(x,2*pi),mod(y,2*pi),'*nearest'),1);
%acD= fftshift(interp2(xo,yo,acD,mod(x,2*pi),mod(y,2*pi),'*nearest'));
%loc= fftshift(interp2(xo,yo,loc,mod(x,2*pi),mod(y,2*pi),'*nearest'),1);
%B = fftshift(interp2(xo,yo,B,mod(x,2*pi),mod(y,2*pi),'*nearest'),1);
ac = interp2(xo,yo,ac0,mod(x,2*pi),mod(y,2*pi),'*nearest');
acD= interp2(xo,yo,acD0,mod(x,2*pi),mod(y,2*pi),'*nearest');
loc= interp2(xo,yo,loc0,mod(x,2*pi),mod(y,2*pi),'*nearest');
B = interp2(xo,yo,B0,mod(x,2*pi),mod(y,2*pi),'*nearest');
%[ac,acD,loc,B] = FFTquincunxpolyfilter(x,y,gamma,type(2));
end;
ortho = acD./ac;
else
[ortho,B] = FFTquincunxmcclellan(x,y,alpha);
end;
% Lowpass filter
[H,H1] = FFTquincunxfilter2D_lowpass(x,y,type,B,ortho);
% Reversed filter
B0 = B;
if iter==0,
B=fftshift(B); ortho=fftshift(ortho);
else
B=fftshift(B,1); ortho=fftshift(ortho,1);
end;
if lower(type(1)) == 'p',
ac0=ac; acD0=acD; loc0=loc;
if iter==0,
ac=fftshift(ac);
acD=fftshift(acD);
loc=fftshift(loc);
else
ac=fftshift(ac,1);
acD=fftshift(acD);
loc=fftshift(loc,1);
end;
else
ac=0; ac0=0; acD=0; acD0=0; loc=0; loc0=0;
end;
[Hd,H1d] = FFTquincunxfilter2D_highpass(x-pi,y-pi,type,B,ortho,ac,ac0,acD,acD0,loc,loc0);
% Highpass filters: modulation
G = exp(i*x).*H1d;
G1 = exp(-i*x).*Hd;
% Fill up array with analysis and synthesis filters
FA(:,:,iter*2+1) = H1;
FA(:,:,iter*2+2) = G1;
FS(:,:,iter*2+1) = H;
FS(:,:,iter*2+2) = G;
end;
function [H,H1]=FFTquincunxfilter2D_highpass(x,y,type,B,ortho,ac,ac0,acD,acD0,loc,loc0);
% FFTQUINCUNXFILTER2D_HIGHPASS Supplies highpass filters for 2D quincunx transform.
% [Hsynthesis,Hanalysis]=FFTquincunxfilter2D_highpass(x,y,alpha,type)
% computes the frequency response of highpass filters.
%
% Input:
% x,y = coordinates in the frequency domain
% alpha = degree of the filters, any real number >=0
% type = type of filter (ortho, dual, bspline)
%
% Dimitri Van De Ville
% Biomedical Imaging Group, BIO-E/STI
% Swiss Federal Institute of Technology Lausanne
% CH-1015 Lausanne EPFL, Switzerland
if lower(type(1))=='p', % Polyharmonic splines
type = [ type(2:length(type)) ];
switch lower(type(1)),
% Orthogonal filters
case 'o',
H = B*sqrt(2) ./ sqrt(ortho);
H1 = conj(H);
% Dual filters (B-spline at the analysis side)
case 'd',
H = sqrt(2)*conj(B).*ac;
H1 = sqrt(2)*B./acD;
% B-spline filters (B-spline at the synthesis side)
case 'b',
H1 = sqrt(2)*conj(B).*ac;
H = sqrt(2)*B./acD;
case 'i',
H = sqrt(2)*loc0./ac0;
H1 = sqrt(2)*(B.^2).*ac./acD.*ac0./loc0;
H1(find(isinf(H1)))=0;
end;
else % Simple fractional iterate with McClellan transform
[H,H1]=FFTquincunxfilter2D_lowpass(x,y,type,B,ortho);
end;
function [H,H1]=FFTquincunxfilter2D_lowpass(x,y,type,B,ortho);
% FFTQUINCUNXFILTER2D_LOWPASS Supplies lowpass filters for 2D quincunx transform.
% [Hsynthesis,Hanalysis]=FFTquincunxfilter2D_lowpass(x,y,alpha,type)
% computes the frequency response of lowpass filters.
%
% Input:
% x,y = coordinates in the frequency domain
% alpha = degree of the filters, any real number >=0
% type = type of filter (ortho, dual, bspline)
%
% Dimitri Van De Ville
% Biomedical Imaging Group, BIO-E/STI
% Swiss Federal Institute of Technology Lausanne
% CH-1015 Lausanne EPFL, Switzerland
H=B;
if lower(type(1)) == 'p',
type = [ type(2:length(type)) ];
end;
switch lower(type(1)),
% Orthogonal filters
case 'o',
H = H*sqrt(2) ./ sqrt(ortho);
H1 = conj(H);
% Dual filters (B-spline at the analysis side)
case 'd',
H1 = sqrt(2)*conj(H);
H = conj(H1./(ortho));
% B-spline filters (B-spline at the synthesis side)
case 'b',
H = sqrt(2)*H;
H1 = conj(H./(ortho));
% Isotropic wavelet filter
case 'i',
H1 = sqrt(2)*conj(H);
H = conj(H1./(ortho));
end;
function [ortho,H] = FFTquincunxmcclellan(x,y,alpha)
% FFTQUINCUNXMCCLELLAN Supplies orthonormalizing part of the 2D McClellan
% filters for 2D quincunx transform.
%
% v=FFTquincunmcclellan(x,y,alpha)
%
% Input:
% x,y = coordinates in the frequency domain
% alpha = degree of the filters, any real number >=1
%
% Dimitri Van De Ville
% Biomedical Imaging Group, BIO-E/STI
% Swiss Federal Institute of Technology Lausanne
% CH-1015 Lausanne EPFL, Switzerland
% McClellan transform filters
H = (2*ones(size(x)) + (cos(x) + cos(y))).^((alpha+1)/2);
H = H/4^((alpha+1)/2);
Hc = (2*ones(size(x)) - (cos(x) + cos(y))).^((alpha+1)/2);
Hc = Hc/4^((alpha+1)/2);
% Orthonormalizing denominator (l_2 dual)
ortho = H.*conj(H) + Hc.*conj(Hc);
function [ac,acD,loc,B] = FFTquincunxpolyfilter(x,y,gamma,type)
% FFTQUINCUNXPOLYFILTER Supplies orthonormalizing part of the 2D polyharmonic
% spline filters for 2D quincunx transform.
%
% v=FFTquincunxpolyfilter(x,y,gamma,type)
%
% Input:
% x,y = coordinates in the frequency domain
% gamma = order of the filters, any real number >=0
%
% Dimitri Van De Ville
% Biomedical Imaging Group, BIO-E/STI
% Swiss Federal Institute of Technology Lausanne
% CH-1015 Lausanne EPFL, Switzerland
% Get dimensions
[m n]=size(x);
m=2*m; n=2*n;
% Construct fine grid [0,2pi[ x [0,2pi[
[xo,yo]=ndgrid(2*pi*([1:m]-1)/m,2*pi*([1:n]-1)/n);
warning off MATLAB:divideByZero;
% Refinement filter for [2 0; 0 2]
if upper(type(1)) == type(1),
loc = 8/3*(sin(xo/2).^2+sin(yo/2).^2)+2/3*(sin((xo+yo)/2).^2+sin((xo-yo)/2).^2);
H = 2^(-gamma)*((8/3*(sin(xo).^2+sin(yo).^2)+2/3*(sin(xo+yo).^2+sin(xo-yo).^2))./loc).^(gamma/2);
else
loc = sin(xo/2).^2+sin(yo/2).^2;
H = 2^(-gamma)*((sin(xo).^2+sin(yo).^2)./loc).^(gamma/2);
end;
H(find(isnan(H))) = 1;
% Autocorrelation function
ac = autocorr2d(H.^2);
% Construct fine grid [0,2pi] x [0,2pi]
[xo2,yo2]=ndgrid(2*pi*([1:m/2+1]-1)/(m/2),2*pi*([1:n/2+1]-1)/(n/2));
% Extend autocorrelation function
ac(m/2+1,:)=ac(1,:);
ac(:,n/2+1)=ac(:,1);
% Compute autocorrelation function on subsampled grid; D=[1 1; 1 -1]
x2=mod(xo2+yo2,2*pi);
y2=mod(xo2-yo2,2*pi);
% Compute values on grid (x,y)
%------------------------------
% Autocorrelation filter
acD= interp2(xo2,yo2,ac,mod(x+y,2*pi),mod(x-y,2*pi),'*nearest');
ac = interp2(xo2,yo2,ac,mod(x,2*pi),mod(y,2*pi),'*nearest');
% Localization operator
loc = interp2(xo,yo,loc,mod(x,2*pi),mod(y,2*pi),'*nearest');
loc = loc.^(gamma/2);
% Scaling filter for quincunx lattice
if upper(type(1)) == type(1),
B = 2^(-gamma/2)*((8/3*(sin((x+y)/2).^2+sin((x-y)/2).^2)+2/3*(sin(x).^2+sin(y).^2))./(8/3*(sin(x/2).^2+sin(y/2).^2)+2/3*(sin((x+y)/2).^2+sin((x-y)/2).^2))).^(gamma/2);
else
B = 2^(-gamma/2)*((sin((x+y)/2).^2+sin((x-y)/2).^2)./(sin(x/2).^2+sin(y/2).^2)).^(gamma/2);
end;
B(find(isnan(B))) = 1;
function [v,fv] = poly(alpha,type)
% POLY - compute the polyharmonic B-spline
%
% Input:
% alpha = degree of the polyharmonic spline
% type = type of B-spline (b,d,o,B,D,O)
%
% Dimitri Van De Ville
% Biomedical Imaging Group, BIO-E/STI
% Swiss Federal Institute of Technology Lausanne
% CH-1015 Lausanne EPFL, Switzerland
warning off MATLAB:divideByZero;
N=16; % spatial support: [-N/4:N/4[
Z=16; % spatial zoom factor
%N=64;
%Z=2;
step=2*pi/N;
[x,y]=meshgrid(-Z*pi:step:Z*pi-step);
w1=x; w2=y;
% compute frequency response
gamma=alpha+2;
x = x/2; y = y/2;
loc = sin(x).^2+sin(y).^2;
% alternative localization
if upper(type(1)) == type(1),
loc = ( 8/3*loc + 2/3*(sin(x+y).^2+sin(x-y).^2) ) / 4;
end;
pow=(x.^2+y.^2);
loc=loc.^(gamma/2);
pow=pow.^(gamma/2);
fv = ( loc ./ pow );
fv(find(isnan(fv))) = 1;
% autocorrelation function
[xo,yo]=meshgrid(0:step/2:2*pi-step/2);
% refinement filter for [2 0; 0 2]
if upper(type(1)) == type(1),
H = 2^(-gamma)*((8/3*(sin(xo).^2+sin(yo).^2)+2/3*(sin(xo+yo).^2+sin(xo-yo).^2))./(8/3*(sin(xo/2).^2+sin(yo/2).^2)+2/3*(sin((xo+yo)/2).^2+sin((xo-yo)/2).^2))).^(gamma/2);
else
H = 2^(-gamma)*((sin(xo).^2+sin(yo).^2)./(sin(xo/2).^2+sin(yo/2).^2)).^(gamma/2);
end;
H(find(isnan(H))) = 1;
% autocorrelation function
ac0 = autocorr2d(H.^2);
sx = size(ac0,1); sy = size(ac0,2);
ac = zeros(size(fv));
for iterx=1:Z,
for itery=1:Z,
bx=(iterx-1)*sx+1;
by=(itery-1)*sy+1;
ac(bx:bx+sx-1,by:by+sy-1)=ac0;
end;
end;
ac = fftshift(ac);
if lower(type(1)) == 'o',
fv = fv ./ sqrt(ac);
end;
if lower(type(1)) == 'd',
fv = fv ./ ac;
end;
% compute spatial version
fv = ifftshift(fv); % shift to [0:2pi[
v = real((ifft2(fv)))*Z^2; % compensate for zooming
% only keep the half [-N/4:N/4[ instead of [-N/2:N/2[ (to avoid aliasing)
[x,y]=meshgrid(-N/4:1/Z:N/4-1/Z);
v=fftshift(v);
v=v((N*Z)/4:(N*Z)*3/4-1,(N*Z)/4:(N*Z)*3/4-1);
v=ifftshift(v);
% optional: normalize energy (for movies)
if length(type)>1 & type(2) == 'n',
s=sum(v(:).^2)/(Z*Z);
v=v*sqrt(1/s);
end;
% surface plot with lighting
surfl(x,y,fftshift(v)); shading flat; view(-26,44);
xlabel('x_1');
ylabel('x_2');
function [v,fv] = polyw(alpha,type)
% POLYW - polyharmonic B-spline wavelet
%
% Input:
%
% type
% lowercase - Rabut style
% uppercase - isotropic brand
%
% alpha = degree of the polyharmonic spline
%
% Dimitri Van De Ville
% Biomedical Imaging Group, BIO-E/STI
% Swiss Federal Institute of Technology Lausanne
% CH-1015 Lausanne EPFL, Switzerland
gamma=alpha+2;
warning off MATLAB:divideByZero;
N=16;
Z=16;
step=2*pi/N;
[w1,w2]=meshgrid(-Z*pi:step:Z*pi-step);
% downsampled grid
w1D=(w1+w2)/2;
w2D=(w1-w2)/2;
% scaling function
w1D = w1D/2; w2D = w2D/2;
loc = 4*sin(w1D).^2+4*sin(w2D).^2;
if upper(type(1)) == type(1),
loc = loc - 8/3*sin(w1D).^2.*sin(w2D).^2;
end;
pow = (2*w1D).^2+(2*w2D).^2;
loc=loc.^(gamma/2);
pow=pow.^(gamma/2);
fv1 = loc ./ pow;
fv1(find(isnan(fv1))) = 1;
w1D = 2*w1D; w2D = 2*w2D;
% autocorrelation function
[w1o,w2o]=meshgrid(0:step/4:2*pi-step/4);
% refinement filter for [2 0; 0 2]
if upper(type(1)) == type(1),
H = 2^(-gamma)*((8/3*(sin(w1o).^2+sin(w2o).^2)+2/3*(sin(w1o+w2o).^2+sin(w1o-w2o).^2))./(8/3*(sin(w1o/2).^2+sin(w2o/2).^2)+2/3*(sin((w1o+w2o)/2).^2+sin((w1o-w2o)/2).^2))).^(gamma/2);
else
H = 2^(-gamma)*((sin(w1o).^2+sin(w2o).^2)./(sin(w1o/2).^2+sin(w2o/2).^2)).^(gamma/2);
end;
H(find(isnan(H))) = 1;
% autocorrelation function
ac0 = autocorr2d(H.^2);
ac0(size(ac0,1)+1,:)=ac0(1,:);
ac0(:,size(ac0,2)+1)=ac0(:,1);
[w1o,w2o]=meshgrid(0:step/2:2*pi);
ac = interp2(w1o,w2o,ac0,mod(w1D,2*pi),mod(w2D,2*pi),'*linear');
if lower(type(1)) == 'o' || lower(type(1)) == 'j',
fv1 = fv1 ./ sqrt(ac);
end;
if lower(type(1)) == 'd',
fv1 = fv1 ./ ac;
end;
% wavelet filter
w1D = -w1D-pi; w2D = -w2D-pi;
acD = interp2(w1o,w2o,ac0,mod(w1D,2*pi),mod(w2D,2*pi),'*linear');
w1D = w1D/2; w2D = w2D/2;
% Quincunx scaling filter
if upper(type(1)) == type(1),
t1 = 8/3*(sin(w1D+w2D).^2 + sin(w1D-w2D).^2) + 2/3*(sin(2*w1D).^2 + sin(2*w2D).^2);
t2 = 8/3*(sin(w1D).^2 + sin(w2D).^2) + 2/3*(sin(w1D+w2D).^2 + sin(w1D-w2D).^2);
else
t1 = sin(w1D+w2D).^2 + sin(w1D-w2D).^2;
t2 = sin(w1D).^2 + sin(w2D).^2;
end;
% Dyadic scaling filter
if length(type)>1 & type(2)=='D',
t1 = sin(2*w1D).^2 + sin(2*w2D).^2;
t2 = sin(w1D).^2 + sin(w2D).^2;
end;
t=( 0.5 * t1./t2 ).^(gamma/2);
fv2 = conj(t);
fv2(find(isnan(fv2))) = 1;
w1D = 2*w1D; w2D = 2*w2D;
w1D = -w1D-pi; w2D = -w2D-pi;
if lower(type(1)) == 'i',
fv2 = loc;
end;
if lower(type(1)) == 'j',
fv2 = loc;
% fv2(find(isinf(abs(fv2)))) = 0;
end;
% shift
fv2 = fv2 .* exp(-i*w1D);
acD2 = interp2(w1o,w2o,ac0,mod(w1,2*pi),mod(w2,2*pi),'*linear');
if lower(type(1)) == 'o',
fv3 = sqrt(acD./acD2);
end;
if lower(type(1)) == 'b',
fv3 = acD;
end;
if lower(type(1)) == 'd',
fv3 = 1./acD2;
end;
if lower(type(1)) == 'i',
fv3 = 1./ac;
end;
% scale relation
fv = 2^(gamma/2-1)*fv1.*fv2.*fv3;
%fv=fv1;
fv = ifftshift(fv);
% compute spatial version
v = ifft2(fv)*Z^2;
[x1,x2]=meshgrid(-N/4:1/Z:N/4-1/Z);
v=fftshift(v);
v=v((N*Z)/4:(N*Z)*3/4-1,(N*Z)/4:(N*Z)*3/4-1);
v=ifftshift(v);
surfl(x1,x2,fftshift(real(v))); shading flat; view(-26,44);
xlabel('x_1');
ylabel('x_2');
|
github
|
jacksky64/imageProcessing-master
|
perform_waveatoms_transform.m
|
.m
|
imageProcessing-master/Matlab imaging/Matlab toolbox/toolbox_wavelets/perform_waveatoms_transform.m
| 24,620 |
utf_8
|
a14b7c361a63a2e3e55c96f6fbb09d09
|
function y = perform_waveatoms_transform(x,dir, options)
% perform_waveatoms_transform - interface to WaveAtom transform
%
% y = perform_waveatoms_transform(x,dir, options);
%
% The waveatom toolbox can be downloaded from
% http://www.waveatom.org/
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
issym = getoptions(options, 'issym', 0);
force_real = getoptions(options, 'force_real', 1);
if dir==1
d = nb_dims(x);
else
if iscell(x)
d = nb_dims(x{1});
else
d = nb_dims(x);
end
end
pat = 'p'; tp = 'ortho';
if d==1
if dir==1
if issym
y = fatom1sym(x,pat,[1 1]);
else
y = fwa1(x,pat,tp);
end
else
if issym
y = iatom1sym(x,pat,[1 1]);
else
y = iwa1(x,pat,tp);
end
end
else
if dir==1
if issym
y = fwa2sym(x,pat,[1 1]);
else
y = fwa2(x,pat,tp);
end
else
if issym
y = iwa2sym(x,pat,[1 1]);
else
y = iwa2(x,pat,tp);
end
end
end
if force_real && dir==-1
y = real(y);
end
function c = fwa2(x,pat,tp)
% fwa2 - 2D forward wave atom transform
% -----------------
% INPUT
% --
% x is a real N-by-N matrix. N is a power of 2.
% --
% pat specifies the type of frequency partition which satsifies
% parabolic scaling relationship. pat can either be 'p' or 'q'.
% --
% tp is the type of tranform.
% 'ortho': orthobasis
% 'directional': real-valued frame with single oscillation direction
% 'complex': complex-valued frame
% -----------------
% OUTPUT
% --
% c is a cell array which contains the wave atom coefficients. If
% tp=='ortho', then c{j}{m1,m2}(n1,n2) is the coefficient at scale j,
% frequency index (m1,m2) and spatial index (n1,n2). If
% tp=='directional', then c{j,d}{m1,m2}(n1,n2) with d=1,2 are the
% coefficients at scale j, frequency index (m1,m2) and spatial index
% (n1,n2). If tp=='complex', then c{j,d}{m1,m2)(n1,n2) with d=1,2,3,4
% are the coefficients at scale j, frequency index (m1,m2) and spatial
% index (n1,n2).
% -----------------
% Written by Lexing Ying and Laurent Demanet, 2007
if( ismember(tp, {'ortho','directional','complex'})==0 | ismember(pat, {'p','q','u'})==0 ) error('wrong'); end
if(strcmp(tp, 'ortho')==1)
%---------------------------------------------------------
N = size(x,1);
H = N/2;
lst = freq_pat(H,pat);
%------------------
f = fft2(x) / sqrt(prod(size(x)));
A = N;
c = cell(length(lst),1);
%------------------
for s=1:length(lst)
nw = length(lst{s});
c{s} = cell(nw,nw);
for I=0:nw-1
for J=0:nw-1
if(lst{s}(I+1)==0 & lst{s}(J+1)==0)
c{s}{I+1,J+1} = [];
else
B = 2^(s-1);
D = 2*B;
Ict = I*B; Jct = J*B; %starting position in freq
if(mod(I,2)==0)
Ifm = Ict-2/3*B; Ito = Ict+4/3*B;
else
Ifm = Ict-1/3*B; Ito = Ict+5/3*B;
end
if(mod(J,2)==0)
Jfm = Jct-2/3*B; Jto = Jct+4/3*B;
else
Jfm = Jct-1/3*B; Jto = Jct+5/3*B;
end
res = zeros(D,D);
for id=0:1
if(id==0)
Idx = [ceil(Ifm):floor(Ito)]; Icf = kf_rt(Idx/B*pi, I);
else
Idx = [ceil(-Ito):floor(-Ifm)]; Icf = kf_lf(Idx/B*pi, I);
end
for jd=0:1
if(jd==0)
Jdx = [ceil(Jfm):floor(Jto)]; Jcf = kf_rt(Jdx/B*pi, J);
else
Jdx = [ceil(-Jto):floor(-Jfm)]; Jcf = kf_lf(Jdx/B*pi, J);
end
res(mod(Idx,D)+1,mod(Jdx,D)+1) = res(mod(Idx,D)+1,mod(Jdx,D)+1) + conj( Icf.'*Jcf ) .* f(mod(Idx,A)+1,mod(Jdx,A)+1);
end
end
c{s}{I+1,J+1} = ifft2(res) * sqrt(prod(size(res)));
end
end
end
end
elseif(strcmp(tp, 'directional')==1)
%---------------------------------------------------------
N = size(x,1);
H = N/2;
lst = freq_pat(H,pat);
%------------------
f = fft2(x) / sqrt(prod(size(x)));
A = N;
c1 = cell(length(lst),1);
c2 = cell(length(lst),1);
%------------------
for s=1:length(lst)
nw = length(lst{s});
c1{s} = cell(nw,nw);
c2{s} = cell(nw,nw);
for I=0:nw-1
for J=0:nw-1
if(lst{s}(I+1)==0 & lst{s}(J+1)==0)
c1{s}{I+1,J+1} = [];
c2{s}{I+1,J+1} = [];
else
B = 2^(s-1);
D = 2*B;
res = zeros(D,D);
Ict = I*B; Jct = J*B; %starting position in freq
if(mod(I,2)==0)
Ifm = Ict-2/3*B; Ito = Ict+4/3*B;
else
Ifm = Ict-1/3*B; Ito = Ict+5/3*B;
end
if(mod(J,2)==0)
Jfm = Jct-2/3*B; Jto = Jct+4/3*B;
else
Jfm = Jct-1/3*B; Jto = Jct+5/3*B;
end
res = zeros(D,D);
Idx = [ceil(Ifm):floor(Ito)]; Icf = kf_rt(Idx/B*pi, I);
Jdx = [ceil(Jfm):floor(Jto)]; Jcf = kf_rt(Jdx/B*pi, J);
res(mod(Idx,D)+1,mod(Jdx,D)+1) = res(mod(Idx,D)+1,mod(Jdx,D)+1) + conj( Icf.'*Jcf ) .* f(mod(Idx,A)+1,mod(Jdx,A)+1);
Idx = [ceil(-Ito):floor(-Ifm)]; Icf = kf_lf(Idx/B*pi, I);
Jdx = [ceil(-Jto):floor(-Jfm)]; Jcf = kf_lf(Jdx/B*pi, J);
res(mod(Idx,D)+1,mod(Jdx,D)+1) = res(mod(Idx,D)+1,mod(Jdx,D)+1) + conj( Icf.'*Jcf ) .* f(mod(Idx,A)+1,mod(Jdx,A)+1);
c1{s}{I+1,J+1} = ifft2(res) * sqrt(prod(size(res)));
res = zeros(D,D);
Idx = [ceil(Ifm):floor(Ito)]; Icf = kf_rt(Idx/B*pi, I);
Jdx = [ceil(-Jto):floor(-Jfm)]; Jcf = kf_lf(Jdx/B*pi, J);
res(mod(Idx,D)+1,mod(Jdx,D)+1) = res(mod(Idx,D)+1,mod(Jdx,D)+1) + conj( Icf.'*Jcf ) .* f(mod(Idx,A)+1,mod(Jdx,A)+1);
Idx = [ceil(-Ito):floor(-Ifm)]; Icf = kf_lf(Idx/B*pi, I);
Jdx = [ceil(Jfm):floor(Jto)]; Jcf = kf_rt(Jdx/B*pi, J);
res(mod(Idx,D)+1,mod(Jdx,D)+1) = res(mod(Idx,D)+1,mod(Jdx,D)+1) + conj( Icf.'*Jcf ) .* f(mod(Idx,A)+1,mod(Jdx,A)+1);
c2{s}{I+1,J+1} = ifft2(res) * sqrt(prod(size(res)));
end
end
end
end
c = [c1 c2];
elseif(strcmp(tp, 'complex')==1)
%---------------------------------------------------------
N = size(x,1);
H = N/2;
lst = freq_pat(H,pat);
%------------------
f = fft2(x) / sqrt(prod(size(x)));
A = N;
c1 = cell(length(lst),1);
c2 = cell(length(lst),1);
c3 = cell(length(lst),1);
c4 = cell(length(lst),1);
%------------------
for s=1:length(lst)
nw = length(lst{s});
c1{s} = cell(nw,nw);
c2{s} = cell(nw,nw);
c3{s} = cell(nw,nw);
c4{s} = cell(nw,nw);
for I=0:nw-1
for J=0:nw-1
if(lst{s}(I+1)==0 & lst{s}(J+1)==0)
c1{s}{I+1,J+1} = [];
c2{s}{I+1,J+1} = [];
c3{s}{I+1,J+1} = [];
c4{s}{I+1,J+1} = [];
else
B = 2^(s-1);
D = 2*B;
res = zeros(D,D);
Ict = I*B; Jct = J*B; %starting position in freq
if(mod(I,2)==0)
Ifm = Ict-2/3*B; Ito = Ict+4/3*B;
else
Ifm = Ict-1/3*B; Ito = Ict+5/3*B;
end
if(mod(J,2)==0)
Jfm = Jct-2/3*B; Jto = Jct+4/3*B;
else
Jfm = Jct-1/3*B; Jto = Jct+5/3*B;
end
res = zeros(D,D);
Idx = [ceil(Ifm):floor(Ito)]; Icf = kf_rt(Idx/B*pi, I);
Jdx = [ceil(Jfm):floor(Jto)]; Jcf = kf_rt(Jdx/B*pi, J);
res(mod(Idx,D)+1,mod(Jdx,D)+1) = res(mod(Idx,D)+1,mod(Jdx,D)+1) + conj( Icf.'*Jcf ) .* f(mod(Idx,A)+1,mod(Jdx,A)+1);
c1{s}{I+1,J+1} = ifft2(res) * sqrt(prod(size(res)));
res = zeros(D,D);
Idx = [ceil(-Ito):floor(-Ifm)]; Icf = kf_lf(Idx/B*pi, I);
Jdx = [ceil(-Jto):floor(-Jfm)]; Jcf = kf_lf(Jdx/B*pi, J);
res(mod(Idx,D)+1,mod(Jdx,D)+1) = res(mod(Idx,D)+1,mod(Jdx,D)+1) + conj( Icf.'*Jcf ) .* f(mod(Idx,A)+1,mod(Jdx,A)+1);
c2{s}{I+1,J+1} = ifft2(res) * sqrt(prod(size(res)));
res = zeros(D,D);
Idx = [ceil(Ifm):floor(Ito)]; Icf = kf_rt(Idx/B*pi, I);
Jdx = [ceil(-Jto):floor(-Jfm)]; Jcf = kf_lf(Jdx/B*pi, J);
res(mod(Idx,D)+1,mod(Jdx,D)+1) = res(mod(Idx,D)+1,mod(Jdx,D)+1) + conj( Icf.'*Jcf ) .* f(mod(Idx,A)+1,mod(Jdx,A)+1);
c3{s}{I+1,J+1} = ifft2(res) * sqrt(prod(size(res)));
res = zeros(D,D);
Idx = [ceil(-Ito):floor(-Ifm)]; Icf = kf_lf(Idx/B*pi, I);
Jdx = [ceil(Jfm):floor(Jto)]; Jcf = kf_rt(Jdx/B*pi, J);
res(mod(Idx,D)+1,mod(Jdx,D)+1) = res(mod(Idx,D)+1,mod(Jdx,D)+1) + conj( Icf.'*Jcf ) .* f(mod(Idx,A)+1,mod(Jdx,A)+1);
c4{s}{I+1,J+1} = ifft2(res) * sqrt(prod(size(res)));
end
end
end
end
c = [c1 c2 c3 c4];
end
function x = iwa2(c,pat,tp)
% iwa2 - 2D inverse wave atom transform
% -----------------
% INPUT
% --
% c is a cell array which contains the wave atom coefficients. If
% tp=='ortho', then c{j}{m1,m2}(n1,n2) is the coefficient at scale j,
% frequency index (m1,m2) and spatial index (n1,n2). If
% tp=='directional', then c{j,d}{m1,m2}(n1,n2) with d=1,2 are the
% coefficients at scale j, frequency index (m1,m2) and spatial index
% (n1,n2). If tp=='complex', then c{j,d}{m1,m2)(n1,n2) with d=1,2,3,4
% are the coefficients at scale j, frequency index (m1,m2) and spatial
% index (n1,n2).
% --
% pat specifies the type of frequency partition which satsifies
% parabolic scaling relationship. pat can either be 'p' or 'q'.
% --
% tp is the type of tranform.
% 'ortho': orthobasis
% 'directional': real-valued frame with single oscillation direction
% 'complex': complex-valued frame
% -----------------
% OUTPUT
% --
% x is a real N-by-N matrix. N is a power of 2.
% -----------------
% Written by Lexing Ying and Laurent Demanet, 2007
if( ismember(tp, {'ortho','directional','complex'})==0 | ismember(pat, {'p','q','u'})==0 ) error('wrong'); end
if(strcmp(tp, 'ortho')==1)
%---------------------------------------------------------
T = 0;
for s=1:length(c)
nw = length(c{s});
for I=1:nw
for J=1:nw
T = T + prod(size(c{s}{I,J}));
end
end
end
N = sqrt(T);
H = N/2;
lst = freq_pat(H,pat);
A = N;
f = zeros(A,A);
%------------------
for s=1:length(lst)
nw = length(lst{s});
for I=0:nw-1
for J=0:nw-1
if(~isempty(c{s}{I+1,J+1}))
B = 2^(s-1);
D = 2*B;
Ict = I*B; Jct = J*B; %starting position in freq
if(mod(I,2)==0)
Ifm = Ict-2/3*B; Ito = Ict+4/3*B;
else
Ifm = Ict-1/3*B; Ito = Ict+5/3*B;
end
if(mod(J,2)==0)
Jfm = Jct-2/3*B; Jto = Jct+4/3*B;
else
Jfm = Jct-1/3*B; Jto = Jct+5/3*B;
end
res = fft2(c{s}{I+1,J+1}) / sqrt(prod(size(c{s}{I+1,J+1}))); %res = zeros(D,D);
for id=0:1
if(id==0)
Idx = [ceil(Ifm):floor(Ito)]; Icf = kf_rt(Idx/B*pi, I);
else
Idx = [ceil(-Ito):floor(-Ifm)]; Icf = kf_lf(Idx/B*pi, I);
end
for jd=0:1
if(jd==0)
Jdx = [ceil(Jfm):floor(Jto)]; Jcf = kf_rt(Jdx/B*pi, J);
else
Jdx = [ceil(-Jto):floor(-Jfm)]; Jcf = kf_lf(Jdx/B*pi, J);
end
f(mod(Idx,A)+1,mod(Jdx,A)+1) = f(mod(Idx,A)+1,mod(Jdx,A)+1) + ( Icf.'*Jcf ) .* res(mod(Idx,D)+1,mod(Jdx,D)+1);
end
end
end
end
end
end
%------------------
x = ifft2(f) * sqrt(prod(size(f)));
elseif(strcmp(tp, 'directional')==1)
%---------------------------------------------------------
c1 = c(:,1);
c2 = c(:,2);
T = 0;
for s=1:length(c1)
nw = length(c1{s});
for I=1:nw
for J=1:nw
T = T + prod(size(c1{s}{I,J}));
end
end
end
N = sqrt(T);
H = N/2;
lst = freq_pat(H,pat);
A = N;
f = zeros(A,A);
%------------------
for s=1:length(lst)
nw = length(lst{s});
for I=0:nw-1
for J=0:nw-1
if(~isempty(c1{s}{I+1,J+1}))
B = 2^(s-1);
D = 2*B;
Ict = I*B; Jct = J*B; %starting position in freq
if(mod(I,2)==0)
Ifm = Ict-2/3*B; Ito = Ict+4/3*B;
else
Ifm = Ict-1/3*B; Ito = Ict+5/3*B;
end
if(mod(J,2)==0)
Jfm = Jct-2/3*B; Jto = Jct+4/3*B;
else
Jfm = Jct-1/3*B; Jto = Jct+5/3*B;
end
res = fft2(c1{s}{I+1,J+1}) / sqrt(prod(size(c1{s}{I+1,J+1}))); %res = zeros(D,D);
Idx = [ceil(Ifm):floor(Ito)]; Icf = kf_rt(Idx/B*pi, I);
Jdx = [ceil(Jfm):floor(Jto)]; Jcf = kf_rt(Jdx/B*pi, J);
f(mod(Idx,A)+1,mod(Jdx,A)+1) = f(mod(Idx,A)+1,mod(Jdx,A)+1) + ( Icf.'*Jcf ) .* res(mod(Idx,D)+1,mod(Jdx,D)+1);
Idx = [ceil(-Ito):floor(-Ifm)]; Icf = kf_lf(Idx/B*pi, I);
Jdx = [ceil(-Jto):floor(-Jfm)]; Jcf = kf_lf(Jdx/B*pi, J);
f(mod(Idx,A)+1,mod(Jdx,A)+1) = f(mod(Idx,A)+1,mod(Jdx,A)+1) + ( Icf.'*Jcf ) .* res(mod(Idx,D)+1,mod(Jdx,D)+1);
res = fft2(c2{s}{I+1,J+1}) / sqrt(prod(size(c2{s}{I+1,J+1}))); %res = zeros(D,D);
Idx = [ceil(Ifm):floor(Ito)]; Icf = kf_rt(Idx/B*pi, I);
Jdx = [ceil(-Jto):floor(-Jfm)]; Jcf = kf_lf(Jdx/B*pi, J);
f(mod(Idx,A)+1,mod(Jdx,A)+1) = f(mod(Idx,A)+1,mod(Jdx,A)+1) + ( Icf.'*Jcf ) .* res(mod(Idx,D)+1,mod(Jdx,D)+1);
Idx = [ceil(-Ito):floor(-Ifm)]; Icf = kf_lf(Idx/B*pi, I);
Jdx = [ceil(Jfm):floor(Jto)]; Jcf = kf_rt(Jdx/B*pi, J);
f(mod(Idx,A)+1,mod(Jdx,A)+1) = f(mod(Idx,A)+1,mod(Jdx,A)+1) + ( Icf.'*Jcf ) .* res(mod(Idx,D)+1,mod(Jdx,D)+1);
end
end
end
end
x = ifft2(f) * sqrt(prod(size(f)));
elseif(strcmp(tp, 'complex')==1)
%---------------------------------------------------------
c1 = c(:,1);
c2 = c(:,2);
c3 = c(:,3);
c4 = c(:,4);
T = 0;
for s=1:length(c1)
nw = length(c1{s});
for I=1:nw
for J=1:nw
T = T + prod(size(c1{s}{I,J}));
end
end
end
N = sqrt(T);
H = N/2;
lst = freq_pat(H,pat);
A = N;
f = zeros(A,A);
%------------------
for s=1:length(lst)
nw = length(lst{s});
for I=0:nw-1
for J=0:nw-1
if(~isempty(c1{s}{I+1,J+1}))
B = 2^(s-1);
D = 2*B;
Ict = I*B; Jct = J*B; %starting position in freq
if(mod(I,2)==0)
Ifm = Ict-2/3*B; Ito = Ict+4/3*B;
else
Ifm = Ict-1/3*B; Ito = Ict+5/3*B;
end
if(mod(J,2)==0)
Jfm = Jct-2/3*B; Jto = Jct+4/3*B;
else
Jfm = Jct-1/3*B; Jto = Jct+5/3*B;
end
res = fft2(c1{s}{I+1,J+1}) / sqrt(prod(size(c1{s}{I+1,J+1}))); %res = zeros(D,D);
Idx = [ceil(Ifm):floor(Ito)]; Icf = kf_rt(Idx/B*pi, I);
Jdx = [ceil(Jfm):floor(Jto)]; Jcf = kf_rt(Jdx/B*pi, J);
f(mod(Idx,A)+1,mod(Jdx,A)+1) = f(mod(Idx,A)+1,mod(Jdx,A)+1) + ( Icf.'*Jcf ) .* res(mod(Idx,D)+1,mod(Jdx,D)+1);
res = fft2(c2{s}{I+1,J+1}) / sqrt(prod(size(c2{s}{I+1,J+1}))); %res = zeros(D,D);
Idx = [ceil(-Ito):floor(-Ifm)]; Icf = kf_lf(Idx/B*pi, I);
Jdx = [ceil(-Jto):floor(-Jfm)]; Jcf = kf_lf(Jdx/B*pi, J);
f(mod(Idx,A)+1,mod(Jdx,A)+1) = f(mod(Idx,A)+1,mod(Jdx,A)+1) + ( Icf.'*Jcf ) .* res(mod(Idx,D)+1,mod(Jdx,D)+1);
res = fft2(c3{s}{I+1,J+1}) / sqrt(prod(size(c3{s}{I+1,J+1}))); %res = zeros(D,D);
Idx = [ceil(Ifm):floor(Ito)]; Icf = kf_rt(Idx/B*pi, I);
Jdx = [ceil(-Jto):floor(-Jfm)]; Jcf = kf_lf(Jdx/B*pi, J);
f(mod(Idx,A)+1,mod(Jdx,A)+1) = f(mod(Idx,A)+1,mod(Jdx,A)+1) + ( Icf.'*Jcf ) .* res(mod(Idx,D)+1,mod(Jdx,D)+1);
res = fft2(c4{s}{I+1,J+1}) / sqrt(prod(size(c4{s}{I+1,J+1}))); %res = zeros(D,D);
Idx = [ceil(-Ito):floor(-Ifm)]; Icf = kf_lf(Idx/B*pi, I);
Jdx = [ceil(Jfm):floor(Jto)]; Jcf = kf_rt(Jdx/B*pi, J);
f(mod(Idx,A)+1,mod(Jdx,A)+1) = f(mod(Idx,A)+1,mod(Jdx,A)+1) + ( Icf.'*Jcf ) .* res(mod(Idx,D)+1,mod(Jdx,D)+1);
end
end
end
end
x = ifft2(f) * sqrt(prod(size(f)));
end
function lst = freq_pat(H,pat)
% freq_pat.m - generate frequency partition
%
% input:
% H: half length of the frequency span, H needs to be greater than 16
% pat: type of frequency partition which satsifies parabolic scaling relationship
% equal to 'p' or 'q'
%
% output:
% lst: data representing the partition of frequency
%
% Written by Lexing Ying and Laurent Demanet, 2006
if(H<16) error('H needs to be at least 16'); end
if( pat=='p') %parabolic scaling by lexing
len = ceil(log2(H)/2)+1;
lst = cell(len,1);
lst{1} = [1 1]; lst{2} = [0 1]; lst{3} = [0 1 1 1];
cnt = 16;
idx = 3; rad = 4;
while(cnt<H)
old = cnt;
lst{idx} = [lst{idx} 1 1];
cnt = cnt + 2*rad;
idx = idx+1;
rad = 2*rad;
trg = min(4*old,H);
lst{idx} = [zeros(1,cnt/rad), ones(1,(trg-cnt)/rad)];
cnt = trg;
end
elseif(pat=='q') %parabolic scaling by laurent
len = floor(log2(H)/2)+1;
lst = cell(len,1);
lst{1} = [1 1]; lst{2} = [0 1 1 1];
cnt = 8;
idx = 2; rad = 2;
while(cnt<H)
old = cnt;
lst{idx} = [lst{idx} 1 1];
cnt = cnt + 2*rad;
idx = idx+1;
rad = 2*rad;
trg = min(4*old,H);
lst{idx} = [zeros(1,cnt/rad), ones(1,(trg-cnt)/rad)];
cnt = trg;
end
elseif(pat=='u')
len = ceil(log2(H)/2)+1; %uniform partitioning
lst = cell(len,1);
B = 2^(len-1);
lst{end} = ones(1,H/B);
else
error('wrong pat');
end
function r = kf_rt(w,n)
% kf_rt.m - right bump
%
% Written by Lexing Ying and Laurent Demanet, 2006
r = zeros(size(w));
an = pi/2*(n+1/2);
en = (-1)^n;
en1 = (-1)^(n+1);
r = exp(-i*w/2) .* ( exp(i*an)*g(en*(w-pi*(n+1/2))) );
function r = g(w)
% g.m - 'g' function Villemoes's construction
%
% Written by Lexing Ying and Laurent Demanet, 2006
r = zeros(size(w));
gd = w<5*pi/6 & w>-7*pi/6;
r(gd) = abs(sf(w(gd)-3*pi/2));
%----------------------------------------------------------------------
function r = sf(w)
r = zeros(size(w));
aw = abs(w);
r(aw<=2*pi/3) = 0;
gd = aw>=2*pi/3 & aw<=4*pi/3;
r(gd) = 1/sqrt(2) * hf(w(gd)/2+pi);
gd = aw>=4*pi/3 & aw<=8*pi/3;
r(gd) = 1/sqrt(2) * hf(w(gd)/4);
r(aw>8*pi/2) = 0;
function r = hf(w)
w = mod(w+pi,2*pi) - pi;
r = zeros(size(w));
w = abs(w);
r = sqrt(2) * cos(pi/2 * beta(3*w/pi-1));
r(w<=pi/3) = sqrt(2);
r(w>=2*pi/3) = 0;
function r = beta(x)
r = x.^4 .*(35-84*x + 70*x.^2 -20*x.^3);
function r = kf_lf(w,n)
% kf_lf.m - left bump
%
% Written by Lexing Ying and Laurent Demanet, 2006
r = zeros(size(w));
an = pi/2*(n+1/2);
en = (-1)^n;
en1 = (-1)^(n+1);
r = exp(-i*w/2) .* ( exp(-i*an)*g(en1*(w+pi*(n+1/2))) );
function res = fwa2sym(x,pat,tp)
% fwa2sym - 2D forward wave atom transform (symmetric version)
% -----------------
% INPUT
% --
% x is a real N-by-N matrix. N is a power of 2.
% --
% pat specifies the type of frequency partition which satsifies
% parabolic scaling relationship. pat can either be 'p' or 'q'.
% --
% tp is the type of tranform.
% 'ortho': orthobasis
% 'directional': real-valued frame with single oscillation direction
% 'complex': complex-valued frame
% -----------------
% OUTPUT
% --
% res is an array containing all the wave atom coefficients. If
% tp=='ortho', then res is of size N-by-N. If tp=='
% If tp=='directional', then res is of size N-by-N-by-2. If tp=='complex',
% then res is of size N-by-N-by-4.
% -----------------
% Written by Lexing Ying and Laurent Demanet, 2007
if( ismember(tp, {'ortho','directional','complex'})==0 | ismember(pat, {'p','q','u'})==0 ) error('wrong'); end
call = fwa2(x,pat,tp);
N = size(x,1);
res = zeros(N,N,size(call,2));
for i=1:size(call,2)
c = call(:,i);
y = zeros(N,N);
for s=1:length(c)
D = 2^s;
nw = length(c{s});
for I=0:nw-1
for J=0:nw-1
if(~isempty(c{s}{I+1,J+1}))
y( I*D+[1:D], J*D+[1:D] ) = c{s}{I+1,J+1};
end
end
end
end
res(:,:,i) = y;
end
function x = iwa2sym(res,pat,tp)
% iwa2sym - 2D inverse wave atom transform (symmetric version)
% -----------------
% INPUT
% --
% res is an array containing all the wave atom coefficients. If
% tp=='ortho', then res is of size N-by-N. If tp=='
% If tp=='directional', then res is of size N-by-N-by-2. If tp=='complex',
% then res is of size N-by-N-by-4.
% --
% pat specifies the type of frequency partition which satsifies
% parabolic scaling relationship. pat can either be 'p' or 'q'.
% --
% tp is the type of tranform.
% 'ortho': orthobasis
% 'directional': real-valued frame with single oscillation direction
% 'complex': complex-valued frame
% -----------------
% OUTPUT
% --
% x is a real N-by-N matrix. N is a power of 2.
% -----------------
% Written by Lexing Ying and Laurent Demanet, 2007
if( ismember(tp, {'ortho','directional','complex'})==0 | ismember(pat, {'p','q','u'})==0 ) error('wrong'); end
N = size(res,1);
H = N/2;
lst = freq_pat(H,pat);
red = size(res,3);
call = cell(length(lst),red);
for i=1:red
y = res(:,:,i);
c = cell(length(lst),1);
for s=1:length(lst)
B = 2^(s-1); D = 2*B;
nw = length(lst{s});
c{s} = cell(nw,nw);
for I=0:nw-1
for J=0:nw-1
if(lst{s}(I+1)==0 & lst{s}(J+1)==0)
c{s}{I+1,J+1} = [];
else
c{s}{I+1,J+1} = y( I*D+[1:D], J*D+[1:D] );
end
end
end
end
call(:,i) = c;
end
x = iwa2(call,pat,tp);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.