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
|
namenpath.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/namenpath.m
| 921 |
utf_8
|
2f308fc4b71683904c79d16a0a402c8e
|
% NAMENPATH Returns filename and its path from a full filename
%
% Usage: [name, pth] = namenpath(fullfilename)
%
% Argument: fullfilename - filename specifier which may include directory
% path specification
%
% Returns: name - The filename without directory path specification
% pth - The directory path
% such that fullfilename = [pth name]
% Copyright (c) 2010 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
% July 2010
function [name, pth] = namenpath(fullfilename)
% Find the last instance of a forward or back slash in the full file name
ind = find(fullfilename == '/' | fullfilename =='\', 1, 'last');
if isempty(ind)
pth = './';
name = fullfilename;
else
pth = fullfilename(1:ind);
name = fullfilename(ind+1:end);
end
|
github
|
jacksky64/imageProcessing-master
|
rgb2cmyk.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/rgb2cmyk.m
| 1,000 |
utf_8
|
21df7ae00f80e81c2fb8577985fd5f65
|
% RGB2CMYK - Basic conversion of RGB colour table to cmyk
%
% Usage: cmyk = rgb2cmyk(map)
%
% Argument: map - N x 3 table of RGB values (assumed 0 - 1)
% Returns: cmyk - N x 4 table of cmyk values
%
% Note that you can use MATLAB's functions MAKECFORM and APPLYCFORM to
% perform the conversion. However I find that either the gamut mapping, or
% my incorrect use of these functions does not result in a reversable
% CMYK->RGB->CMYK conversion. Hence this simple function and its companion
% CMYK2RGB
%
% See also: CMYK2RGB, MAP2GEOSOFTTBL, GEOSOFTTBL2MAP
% Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
% July 2013
% Feb 2014 % Fix for divide by 0 problem for [0 0 0]
function cmyk = rgb2cmyk(map)
k = min(1-map,[],2);
denom = 1 - k + eps; % Add eps to avoid divide by 0
c = (1-map(:,1) - k)./denom;
m = (1-map(:,2) - k)./denom;
y = (1-map(:,3) - k)./denom;
cmyk = [c m y k];
|
github
|
jacksky64/imageProcessing-master
|
removenan.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/removenan.m
| 1,057 |
utf_8
|
69d193c99b44b881024b4b92777413b4
|
% REMOVENAN - removes NaNs from an array
%
% Usage: m = removenan(a, defaultval)
%
% a - The matrix containing NaN values
% defaultval - The default value to replace NaNs
% if omitted this defaults to 0
%
% See Also: FILLNAN
% Copyright (c) 2004 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.
% September 2004
function m = removenan(a, defaultval)
if nargin == 1
defaultval = 0;
end
valid = find(~isnan(a));
m = repmat(defaultval, size(a));
m(valid) = a(valid);
|
github
|
jacksky64/imageProcessing-master
|
rectintersect.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/rectintersect.m
| 605 |
utf_8
|
2f251c6700fc7ac087c802341994cf69
|
% RECTINTERSECT - Returns true if rectangles intersect
%
% Usage: intersect = rectintersect(r1, r2)
%
% Arguments: r1, r2 - The two rectangles to be tested where the
% rectangles are defined following the MATLAB
% convention of [left bottom width height]
%
% See also: RECTANGLE
% Peter Kovesi
% peterkovesi.com
% January 2016
function intersect = rectintersect(r1, r2)
intersect = (r1(1) <= r2(1)+r2(3) && ...
r2(1) <= r1(1)+r1(3) && ...
r1(2) <= r2(2)+r2(4) && ...
r2(2) <= r1(2)+r1(4));
|
github
|
jacksky64/imageProcessing-master
|
togglefigs.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/togglefigs.m
| 3,177 |
utf_8
|
fa815dc34f1c5f91ce9a79d45915bca9
|
% TOGGLEFIGS Convenient switching between figures to aid comparison
%
% Usage 1: togglefigs
%
% Use arrow keys to index through figures that are currently being displayed, or
% enter single digit figure numbers to select figures directly.
% Hit ''X'' to exit.
%
% Usage 2: togglefigs(figs)
% Argument: figs - figure numbers entered as an array or individually
% separated by commas, to toggle. Hitting
% any key will cycle to next figure.
%
% Example if you have 3 figures you wish to compare manually drag them until
% they are perfectly overlaid, then use
% >> togglefigs(1, 2, 3) or
% >> togglefigs(1:3)
% PK March 2010
% May 2011 Modified to automatically find all figures and allow you to
% use arrow keys and single digit figure numbers.
% Feb 2014 Automatically allign the positions of the specified figures
function togglefigs(varargin)
figs = getfigs(varargin(:));
if isempty(figs)
% No figure numbers were entered, find what figure windows are open
figs = sort(get(0,'Children'));
if isempty(figs)
fprintf('No figure windows to display\n');
return
else
fprintf('Use arrow keys to index through figures, or enter single\n');
fprintf('digit figure numbers to select figures directly, hit ''X'' to exit\n');
end
% Set figures so that they all have the same position
posn = get(figs(1),'Position');
for n = 2:length(figs)
set(figs(n),'Position',posn);
end
figIndex = 1;
figure(figs(figIndex));
while 1
pause;
ch = get(gcf,'CurrentCharacter');
val = uint8(ch);
numeral = val - uint8('0');
if lower(ch)=='x'
return
elseif ismember(numeral,figs)
[tf, figIndex] = ismember(numeral, figs);
elseif val == 29 || val == 31
figIndex = figIndex+1; if figIndex > length(figs), figIndex = 1; end
elseif val == 28 || val == 30
figIndex = figIndex-1; if figIndex < 1, figIndex = length(figs); end
end
figure(figs(figIndex));
end
else % Cycle through the list of figure numbers supplied in the argument list
fprintf('Hit any key to toggle figures, ''X'' to exit\n');
% Set figures so that they all have the same position
posn = get(figs(1),'Position');
for n = 2:length(figs)
set(figs(n),'Position',posn);
end
while 1
for n = 1:length(figs)
figure(figs(n));
pause;
ch = get(gcf,'CurrentCharacter');
if lower(ch)=='x'
return
end
end
end
end
%------------------------------------------
function figs = getfigs(arg)
% figs = zeros(size(arg));
figs = [];
for n = 1:length(arg)
% figs(n) = arg{n};
figs = [figs arg{n}];
end
|
github
|
jacksky64/imageProcessing-master
|
pointinconvexpoly.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/pointinconvexpoly.m
| 2,515 |
utf_8
|
2540c1eb544a1a7ed698bcd917996db6
|
% POINTINCONVEXPOLY Determine if a 2D point is within a convex polygon
%
% Usage: v = pointinconvexpoly(p, poly)
%
% Arguments: p - 2D point.
% poly - Convex polygon defined as a series of vertices in
% sequence, clockwise or anticlockwise around the polygon as
% a 2 x N array.
%
% Returns: v - +1 if within the polygon
% -1 if outside
% 0 if on the boundary
%
% Warning: There is no check to see if the polygon is indeed convex.
% Strategy: Determine whether, in traveling from p to a vertex and then to the
% following vertex, we turn clockwise or anticlockwise. If for every vertex we
% turn consistently clockwise, or consistently anticlockwise we are inside the
% polygon. If for one of the vertices we did not turn clockwise or
% anticlockwise then we must be on the boundary.
% Peter Kovesi
% [email protected]
% May 2015
function v = pointinconvexpoly(p, poly)
[dim, N] = size(poly);
if length(p) ~= 2 || dim ~= 2
error('Data must be 2D');
end
% Append a copy of the first vertex to the end for convenience
poly = [poly poly(:,1)]; % We now have N+1 vertices
% Determine whether, in traveling from p to a vertex and then to the
% following vertex, we turn clockwise or anticlockwise
c = zeros(N,1);
for n = 1:N
c(n) = clockwise(p, poly(:,n), poly(:,n+1));
end
% If for every vertex we turn consistently clockwise, or consistently
% anticlockwise we are inside the polygon. If for one of the vertices we
% did not turn clockwise or anticlockwise then we must be on the
% boundary.
if all(c >= 0) || all(c <= 0)
if any(c==0) % We are on the boundary
v = 0;
else % We are inside
v = 1;
end
else % We are outside
v = -1;
end
%----------------------------------------------------------------------
% Determine whether, in traveling from p1 to p2 to p3 we turn clockwise or
% anticlockwise. Returns +1 for clockwise, -1 for anticlockwise, and 0 for
% p1, p2, p3 in a straight line.
function v = clockwise(p1, p2, p3)
% Form vectors p1->p2 and p2->p3 with z component = 0, form cross product
% if the resulting z value is -ve the vectors turn clockwise, if +ve
% anticlockwise, and if 0 the points are in a line.
v = -sign((p2(1)-p1(1))*(p3(2)-p2(2)) - (p2(2)-p1(2))*(p3(1)-p2(1)));
|
github
|
jacksky64/imageProcessing-master
|
geosofttbl2map.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/geosofttbl2map.m
| 1,313 |
utf_8
|
97f965db62a9a1ea1d2d5bccb32bd608
|
% GEOSOFTTBL2MAP Converts Geosoft .tbl file to MATLAB colourmap
%
% Usage: geosofttbl2map(filename, map)
%
% Arguments: filename - Input filename of tbl file
% map - N x 3 rgb colourmap
%
%
% This function reads a Geosoft .tbl file and converts the KCMY values to a RGB
% colourmap.
%
% See also: MAP2GEOSOFTTBL, RGB2CMYK
% Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
% PK July 2013
function map = geosofttbl2map(filename)
% Read the file
[fid, msg] = fopen(filename, 'rt');
error(msg);
% Read, test and then discard first line
txt = strtrim(fgetl(fid));
% Very basic file check. Test that it starts with '{'
if txt(1) ~= '{'
error('This may not be a Geosoft tbl file')
end
% Read remaining lines containing the colour table
[data, count] = fscanf(fid, '%d');
if mod(count,4) % We expect 4 columns of data
error('Number of values read not a multiple of 4');
end
% Reshape data so that columns form kcmy tuples
kcmy = reshape(data, 4, count/4);
% Transpose so that the rows form kcmy tuples and normalise 0-1
kcmy = kcmy'/255;
cmyk = [kcmy(:,2:4) kcmy(:,1)];
map = cmyk2rgb(cmyk);
fclose(fid);
|
github
|
jacksky64/imageProcessing-master
|
matscii.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/matscii.m
| 3,441 |
utf_8
|
58129d6167a995d9b76c9cce83edd57a
|
% MATSCII - Function to generate ASCII images
%
% Usage: picci = matscii(im, width, gamma, filename)
%
% im - 2D array of image brightness colours.
% Image can be grey scale or colour.
% width - desired width of resulting character image.
% gamma - optional gamma value to enhance contrast,
% gamma > 1 increases contrast, < 1 decreases contrast.
% filename - optional filename in which to save the result.
%
% picci - the resulting 2D array of characters.
%
% 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.
% September 2000
% August 2005 tweaks for Octave
% September 2005 RBG conversion error fixed (thanks to Firas Zeineddine)
function picci = matscii(im, width, gamma, filename)
% ASCII grey scale
%g = '$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`''. ';
g = '#8XOHLTI)i=+;:,. '; % This seems to be a better `grey scale'
gmax = length(g);
charAspect = 0.55; % Width/height aspect ratio of characters
if nargin <=2
gamma = 1; % Default gamma value
end
im = double(im);
if ndims(im) == 3 % We have a colour image
im = (im(:,:,1) + im(:,:,2) + im(:,:,3))/3; % Grey value = (R+G+B)/3
end
[rows, cols] = size(im);
scale = width/cols;
rows = round(charAspect * scale * rows); % Rescaled rows and cols values
cols = round(scale * cols);
im = normalise(im).^gamma; % Rescale range 0-1 and apply gamma
im = imresize(im, [rows, cols]);
%im = myrescale(im, [rows, cols]); % Use this if you do not have the image
%toolbox
im = round(im*(gmax-1) + 1); % Rescale to range 1..gmax and round to ints.
picci = char(zeros(rows,cols)); % Preallocate memory for output image.
for r = 1: rows
for c = 1:cols
picci(r,c) = g(im(r,c));
end
end
if nargin == 4 % we have a filename
[fid, msg] = fopen(filename,'wt');
error(msg);
for r = 1: rows
fprintf(fid,'%s\n',picci(r,:));
end
fclose(fid);
end
%-------------------------------------------------------------------
% Internal function to rescale an image so that this code
% does not require the image processing toolbox to run.
%-------------------------------------------------------------------
function newim = myrescale(im, newRowsCols)
[rows,cols] = size(im);
newrows = newRowsCols(1);
newcols = newRowsCols(2);
rowScale = (newrows-1)/(rows-1); % Arrays start at 1 rather than 0
colScale = (newcols-1)/(cols-1);
newim = zeros(newrows, newcols);
% For each pixel in the final image find where that pixel `came from'
% in the source image - use this as the scaled image value
% Scaling eqns account for the fact that MATLAB arrays start at 1 rather than 0
for r = 1: newrows
for c = 1: newcols
sourceRow = round((r-1)/rowScale + 1);
sourceCol = round((c-1)/colScale + 1);
newim(r,c) = im(sourceRow, sourceCol);
end
end
|
github
|
jacksky64/imageProcessing-master
|
chirpexp.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/chirpexp.m
| 1,971 |
utf_8
|
9b0330d3aaf9432d3b2aa5f9322406b7
|
% CHIRPEXP Generates exponential chirp test image
%
% The test image consists of an exponential chirp signal in the horizontal
% direction with the amplitude of the chirp being modulated from 1 at the top of
% the image to 0 at the bottom.
%
% Usage: im = chirpexp(sze, w0, w1, p)
%
% Arguments: sze - [rows cols] specifying size of test image. If a
% single value is supplied the image is square.
% w0, w1 - Initial and final wavelengths of the chirp pattern.
% p - Power to which the linear attenuation of amplitude,
% from top to bottom, is raised. For no attenuation use
% p = 0. For contrast sensitivity experiments use larger
% values of p. The default value is 4.
%
% Example: im = chirpexp(800, 40, 4, 4)
%
% I have used this test image to evaluate the effectiveness of different
% colourmaps, and sections of colourmaps, over varying spatial frequencies and
% contrast.
%
% See also: CHIRPLIN, SINERAMP
% Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% March 2012
% February 2015 Changed the arguments so that the chirp is specifeied in
% terms of the initial and final wavelengths.
function im = chirpexp(sze, w0, w1, p)
if length(sze) == 1
rows = sze; cols = sze;
elseif length(sze) == 2
rows = sze(1); cols = sze(2);
else
error('size must be a 1 or 2 element vector');
end
if ~exist('p', 'var'), p = 4; end
x = 0:cols-1;
% Spatial frequency varies from f0 = 1/w0 to f1 = 1/w1 over the width of the
% image following the expression f(x) = f0*(k^x)
% We need to compute k given w0, w1 and width of the image.
f0 = 1/w0;
f1 = 1/w1;
k = exp((log(f1) - log(f0))/(cols-1));
fx = sin(f0*(k.^x).*x);
A = ([(rows-1):-1:0]/(rows-1)).^p;
im = A'*fx;
|
github
|
jacksky64/imageProcessing-master
|
geoseries.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/geoseries.m
| 1,666 |
utf_8
|
8235bdedc3251f7e5b688f27de734492
|
% GEOSERIES Generate geometric series
%
% Usage 1: s = geoseries(s1, mult, n)
%
% Arguments: s1 - The starting value in the series.
% mult - The scaling factor between succesive values.
% n - The desired number of elements in the series.
%
% Usage 2: s = geoseries([s1 sn], n)
%
% Arguments: [s1 sn] - Two-element vector specifying the 1st and nth values
% in the the series.
% n - The desired number of elements in the series.
%
%
% Example: s = geoseries(0.5, 2, 4)
% s = 0.5000 1.0000 2.0000 4.0000
%
% Alternatively obtain the same series using
% s = geoseries([0.5 4], 4)
% Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% March 2012
function s = geoseries(varargin)
[s1, mult, n] = checkargs(varargin(:));
s = s1 * mult.^[0:(n-1)];
%---------------------------------------------------------------
% Sort out arguments. If 1st and last values in series are specified compute
% the multiplier from the desired number of elements.
% max_val = s1*mult^(n-1)
% mult = exp(log(max_val/s1)/(n-1));
function [s1, mult, n] = checkargs(arg)
if length(arg) == 2 & length(arg{1}) == 2
s1 = arg{1}(1);
sn = arg{1}(2);
n = arg{2};
mult = exp(log(sn/s1)/(n-1));
elseif length(arg) == 3 & length(arg{1}) == 1
s1 = arg{1};
mult = arg{2};
n = arg{3};
else
error('Illegal input. Check usage');
end
assert(n == round(n) & n > 0, 'Number of elements must be a +ve integer')
|
github
|
jacksky64/imageProcessing-master
|
strstartswith.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/strstartswith.m
| 704 |
utf_8
|
7d481f98266b52e06c23ec8c2fc6265d
|
% STRSTARTSWITH - tests if a string starts with a specified substring
%
% Usage: b = strstartswith(str, substr)
%
% Arguments:
% str - string to be tested
% substr - starting string that we are hoping to find
%
% Returns: true/false. Note that case of strings is ignored
%
% See also: STRENDSWITH
% Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% http://www.csse.uwa.edu.au/~pk/research/matlabfns/
% June 2010
function b = strstartswith(str, substr)
l = length(substr);
% True if ssubstring not too long and all appropriate characters match
% (ignoring case)
b = l <= length(str) && strcmpi(str(1:l), substr);
|
github
|
jacksky64/imageProcessing-master
|
cubicroots.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/cubicroots.m
| 2,783 |
utf_8
|
88bc63423a4c8bcc0d94d2848fa6be1f
|
% CUBICROOTS - finds real valued roots of cubic
%
% Usage: root = cubicroots(a,b,c,d)
%
% Arguments:
% a, b, c, d - coeffecients of cubic defined as
% ax^3 + bx^2 + cx + d = 0
% Returns:
% root - an array of 1 or 3 real valued roots
%
% Reference: mathworld.wolfram.com/CubicFormula.html
% Code follows Cardano's formula
% 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.
% Nov 2008
function root = cubicroots(a,b,c,d)
if abs(a) < eps
error('this is a quadratic')
end
% Divide through by a to simplify things
b = b/a; c = c/a; d = d/a;
bOn3 = b/3;
q = (3*c - b^2)/9;
r = (9*b*c - 27*d - 2*b^3)/54;
discriminant = q^3 + r^2;
if discriminant >= 0 % We have 1 real root and 2 imaginary
s = realcuberoot(r + sqrt(discriminant));
t = realcuberoot(r - sqrt(discriminant));
root = s + t - bOn3; % Just calculate the real root
else % We have 3 real roots
% In this case (r + sqrt(discriminate)) is complex so the following
% code constructs the cube root of this complex quantity
rho = sqrt(r^2 - discriminant);
cubeRootrho = realcuberoot(rho); % Cube root of complex magnitude
thetaOn3 = acos(r/rho)/3; % Complex angle/3
crRhoCosThetaOn3 = cubeRootrho*cos(thetaOn3);
crRhoSinThetaOn3 = cubeRootrho*sin(thetaOn3);
root = zeros(1,3);
root(1) = 2*crRhoCosThetaOn3 - bOn3;
root(2) = -crRhoCosThetaOn3 - bOn3 - sqrt(3)*crRhoSinThetaOn3;
root(3) = -crRhoCosThetaOn3 - bOn3 + sqrt(3)*crRhoSinThetaOn3;
end
%-----------------------------------------------------------------------------
% REALCUBEROOT - computes real-valued cube root
%
% Usage: y = realcuberoot(x)
%
% In general there will be 3 solutions for the cube root of a number. Two
% will be complex and one will be real valued. When you raise a negative
% number to the power 1/3 in MATLAB you will not, by default, get the real
% valued solution. This function ensures you get the real one
function y = realcuberoot(x)
y = sign(x).*abs(x).^(1/3);
|
github
|
jacksky64/imageProcessing-master
|
findimage.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/findimage.m
| 1,030 |
utf_8
|
d22c0bf85ea1bee389ca4ca6abdc58f4
|
% FINDIMAGE - invokes image dialog box for interactive image loading
%
% Usage: [im, filename] = findimage(disp, c)
%
% Arguments:
% disp - optional flag 1/0 that results in image being displayed
% c - optional flag 1/0 that results in imcrop being invoked
% Returns:
% im - image
% filename - filename of image
%
% See Also: FINDIMAGES
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/~pk
%
% March 2010
function [im, filename] = findimage(disp, c)
if ~exist('disp','var'), disp = 0; end
if ~exist('c','var'), c = 0; end
[filename, user_canceled] = imgetfile;
if user_canceled
im = [];
filename = [];
return;
end
im = imread(filename);
if c
fprintf('Crop a section of the image\n')
figure(99), clf, im = imcrop(im); delete(99)
end
if disp
show(im, 99);
end
|
github
|
jacksky64/imageProcessing-master
|
strendswith.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/strendswith.m
| 1,172 |
utf_8
|
a53036600dfe2e1dfcf91ecf2909348b
|
% STRENDSWITH - tests if a string ends with a specified substring
%
% Usage: b = strendswith(str, substr)
%
% Arguments:
% str - string to be tested
% substr - ending of string that we are hoping to find.
% substr may be a cell array of string endings, in this case
% the function returns true if any of the endings match.
%
% Returns: true/false. Note that case of strings is ignored
%
% See also: STRSTARTSWITH
% Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% http://www.csse.uwa.edu.au/~pk/research/matlabfns/
% June 2010
% April 2011 Modified to allow substr to be a cell array
function b = strendswith(str, substr)
if ~iscell(substr)
tmp = substr;
clear substr;
substr{1} = tmp;
end
b = 0;
for n = 1:length(substr)
% Compute index of character in str that should match with the the first
% character of str
s = length(str) - length(substr{n}) + 1;
% True if s > 0 and all appropriate characters match (ignoring case)
b = b || (s > 0 && strcmpi(str(s:end), substr{n}));
end
|
github
|
jacksky64/imageProcessing-master
|
viewlabspace.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/viewlabspace.m
| 7,192 |
utf_8
|
cbfb89e9024d64a0fe77892badc56b0c
|
% VIEWLABSPACE Visualisation of L*a*b* space
%
% Usage: viewlabspace(dL)
%
% Argument: dL - Optional increment in lightness with each slice of L*a*b*
% space. Defaults to 5
%
% Function allows interactive viewing of a sequence of images corresponding to
% different slices of lightness in L*a*b* space. Lightness varies from 0 to
% 100. Initially a slice at a lightness of 50 is displayed.
% Pressing 'l' or arrow up/right will increase the lightness by dL.
% Pressing 'd' or arrow down/left will darken by dL.
% Press 'x' to exit.
%
% The CIELAB colour coordinates of the cursor position within the slice images
% is updated continuously. This is useful for determining suitable controls
% points for the definition of colourmap paths through CIELAB space.
%
% See also: COLOURMAPPATH, ISOCOLOURMAPPATH, CMAP
% 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.
% March 2013
% November 2013 Interactive CIELAB coordinate feedback from mouse position
function viewlabspace(dL, figNo)
if ~exist('dL', 'var'), dL = 5; end
if ~exist('figNo', 'var'), figNo = 100; end
% Define some reference colours in rgb
rgb = [1 0 0
0 1 0
0 0 1
1 1 0
0 1 1
1 0 1
1 .5 0
.5 0 1
0 .5 1
0 1 .5
1 0 .5];
colours = {'red '
'green '
'blue '
'yellow '
'cyan '
'magenta'
'orange '
'violet '
'blue-cyan'
'green-cyan'
'red-magenta'};
% ... and convert them to lab
% Use D65 whitepoint to match typical monitors.
wp = whitepoint('D65');
labv = applycform(rgb, makecform('srgb2lab', 'AdaptedWhitePoint', wp));
% Obtain cylindrical coordinates in lab space
labradius = sqrt(labv(:,2).^2+labv(:,3).^2);
labtheta = atan2(labv(:,3), labv(:,2));
% Define a*b* grid for image
scale = 2;
[a, b] = meshgrid([-127:1/scale:127]);
[rows,cols] = size(a);
% Scale and offset lab coords to fit image coords
labc = zeros(size(labv));
labc(:,1) = round(labv(:,1));
labc(:,2) = round(scale*labv(:,2) + cols/2);
labc(:,3) = round(scale*labv(:,3) + rows/2);
% Print out lab values
labv = round(labv);
fprintf('\nCoordinates of standard colours in L*a*b* space\n\n');
for n = 1:length(labv)
fprintf('%s L%3d a %4d b %4d angle %4.1f radius %4d\n',...
colours{n}, ...
labv(n,1), labv(n,2), ...
labv(n,3), labtheta(n), round(labradius(n)));
end
fprintf('\n\n')
% Generate axis tick values
tickval = [-100 -50 0 50 100];
tickcoords = scale*tickval + cols/2;
ticklabels = {'-100'; '-50'; '0'; '50'; '100'};
fig = figure(figNo);
set(fig, 'WindowButtonMotionFcn', @labcoords)
set(fig, 'KeyReleaseFcn', @keyreleasecb);
texth = text(50, 50,'', 'color', [1 1 1]); % Text area to display
% current a and b values
fprintf('Place cursor within figure\n');
fprintf('Press ''l'' to lighten, ''d'' to darken, or use arrow keys\n');
fprintf('''x'' to exit\n');
L = 50;
renderlabslice(L);
%------------------------------------------------------
% Window button move call back function
function labcoords(src, evnt)
cp = get(gca,'CurrentPoint');
x = cp(1,1); y = cp(1,2);
aval = round((x-(cols/2))/scale);
bval = round((y-(rows/2))/scale);
radius = sqrt(aval.^2 + bval.^2);
hue = atan2(bval, aval);
set(texth, 'String', sprintf('a %d b %d radius %d angle %d',...
aval, bval, round(radius), round(hue/pi*180)));
end
%-----------------------------------------------------------------------
% Key Release callback
% If '+' or up is pressed we move up in lighness
% '-' or down moves us down in lightness
function keyreleasecb(src,evnt)
if evnt.Character == 'l' | evnt.Character == 30
L = min(L + dL, 100);
elseif evnt.Character == 'd' | evnt.Character == 31
L = max(L - dL, 0);
elseif evnt.Character == 's' % Save slice as an image
tmp = rgb;
tmp(:,:,1) = flipud(tmp(:,:,1));
tmp(:,:,2) = flipud(tmp(:,:,2));
tmp(:,:,3) = flipud(tmp(:,:,3));
% Draw a red cross at the achromatic point
[r,c,~] = size(tmp);
tmp = imageline(tmp, [c/2-5, r/2], [c/2+5, r/2], [255, 0 0]);
tmp = imageline(tmp, [c/2, r/2-5], [c/2, r/2+5], [255, 0 0]);
imwrite(tmp, sprintf('LAB_slice_L_%d.png',L));
elseif evnt.Character == 'x'
delete(figNo);
return
end
renderlabslice(L); % Render a slice at this new lightness level
labcoords(src, evnt); % Regenerate the cursor coordinates
end
%--------------------------------------------------------
function renderlabslice(L)
% Build image in lab space
lab = zeros(rows,cols,3);
lab(:,:,1) = L;
lab(:,:,2) = a;
lab(:,:,3) = b;
wp = whitepoint('D65');
% Generate rgb values from lab
rgb = applycform(lab, makecform('lab2srgb', 'AdaptedWhitePoint', wp));
% Invert to reconstruct the lab values
lab2 = applycform(rgb, makecform('srgb2lab', 'AdaptedWhitePoint', wp));
% Where the reconstructed lab values differ from the specified values is
% an indication that we have gone outside of the rgb gamut. Apply a
% mask to the rgb values accordingly
mask = max(abs(lab-lab2),[],3);
for n = 1:3
rgb(:,:,n) = rgb(:,:,n).*(mask<2); % tolerance of 1
end
figure(figNo), image(rgb), title(sprintf('Lightness %d', L));
axis square, axis xy
% Recreate the text handle in the new image
texth = text(50, 50,'', 'color', [1 1 1]);
set(gca, 'xtick', tickcoords);
set(gca, 'ytick', tickcoords);
set(gca, 'xticklabel', ticklabels);
set(gca, 'yticklabel', ticklabels);
xlabel('a*'); ylabel('b*');
hold on,
plot(cols/2, rows/2, 'r+'); % Centre point for reference
% Plot reference colour positions
for n = 1:length(labc)
plot(labc(n,2), labc(n,3), 'w+')
text(labc(n,2), labc(n,3), ...
sprintf(' %s\n %d %d %d ',colours{n},...
labv(n,1), labv(n,2), labv(n,3)),...
'color', [1 1 1])
end
hold off
end
%--------------------------------------------------------
end % of viewlabspace
|
github
|
jacksky64/imageProcessing-master
|
circularstruct.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Misc/circularstruct.m
| 648 |
utf_8
|
aec494462bd52689db93faf1d6a9ea60
|
% CIRCULARSTRUCT
%
% Function to construct a circular structuring element
% for morphological operations.
%
% function strel = circularstruct(radius)
%
% Note radius can be a floating point value though the resulting
% circle will be a discrete approximation
%
% Peter Kovesi March 2000
function strel = circularstruct(radius)
if radius < 1
error('radius must be >= 1');
end
dia = ceil(2*radius); % Diameter of structuring element
if mod(dia,2) == 0 % If diameter is a odd value
dia = dia + 1; % add 1 to generate a `centre pixel'
end
r = fix(dia/2);
[x,y] = meshgrid(-r:r);
rad = sqrt(x.^2 + y.^2);
strel = rad <= radius;
|
github
|
jacksky64/imageProcessing-master
|
supertorus.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapes/supertorus.m
| 2,444 |
utf_8
|
91c1e7e27c0219d233582240dcb7c17e
|
% SUPERTORUS - generates a 'supertorus' surface
%
% Usage:
% [x,y,z] = supertorus(xscale, yscale, zscale, rad, e1, e2, n)
%
% Arguments:
% xscale, yscale, zscale - Scaling in the x, y and z directions.
% e1, e2 - Exponents of the x and y coords.
% rad - Mean radius of torus.
% n - Number of subdivisions of logitude and latitude on
% the surface.
%
% Returns: x,y,z - matrices defining paramteric surface of superquadratic
%
% If the result is not assigned to any output arguments the function
% plots the surface for you, otherwise the x, y and z parametric
% coordinates are returned for subsequent display using, say, SURFL.
%
% If rad is set to 0 the surface becomes a superquadratic
%
% Examples:
% supertorus(1, 1, 1, 2, 1, 1, 100) - classical torus 100 subdivisions
% supertorus(1, 1, 1, .8, 1, 1, 100) - an 'orange'
% supertorus(1, 1, 1, 2, .1, 1, 100) - a round 'washer'
% supertorus(1, 1, 1, 2, .1, 2, 100) - a square 'washer'
%
% See also: SUPERQUAD
% Copyright (c) 2000 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.
% September 2000
function [x,y,z] = supertorus(xscale,yscale,zscale,rad,e1,e2, n)
long = ones(n,1)*[-pi:2*pi/(n-1):pi];
lat = [-pi:2*pi/(n-1): pi]'*ones(1,n);
x = xscale * (rad + pow(cos(lat),e1)) .* pow(cos(long),e2);
y = yscale * (rad + pow(cos(lat),e1)) .* pow(sin(long),e2);
z = zscale * pow(sin(lat),e1);
if nargout == 0
surfl(x,y,z), shading interp, colormap(copper), axis equal
clear x y z % suppress output
end
%--------------------------------------------------------------------
% Internal function providing a modified definition of power whereby the
% sign of the result always matches the sign of the input value.
function r = pow(a,p)
r = sign(a).* abs(a.^p);
|
github
|
jacksky64/imageProcessing-master
|
superquad.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapes/superquad.m
| 2,798 |
utf_8
|
2dfc95eb41c2bf03bb78f5f0bb8b7c07
|
% SUPERQUAD - generates a superquadratic surface
%
% Usage: [x,y,z] = superquad(xscale, yscale, zscale, e1, e2, n)
%
% Arguments:
% xscale, yscale, zscale - Scaling in the x, y and z directions.
% e1, e2 - Exponents of the x and y coords.
% n - Number of subdivisions of logitude and latitude on
% the surface.
%
% Returns: x,y,z - matrices defining paramteric surface of superquadratic
%
% If the result is not assigned to any output arguments the function
% plots the surface for you, otherwise the x, y and z parametric
% coordinates are returned for subsequent display using, say, SURFL.
%
% Examples:
% superquad(1, 1, 1, 1, 1, 100) - sphere of radius 1 with 100 subdivisions
% superquad(1, 1, 1, 2, 2, 100) - octahedron of radius 1
% superquad(1, 1, 1, 3, 3, 100) - 'pointy' octahedron
% superquad(1, 1, 1, .1, .1, 100) - cube (with rounded edges)
% superquad(1, 1, .2, 1, .1, 100) - 'square cushion'
% superquad(1, 1, .2, .1, 1, 100) - cylinder
%
% See also: SUPERTORUS
% Copyright (c) 2000 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.
% September 2000
function [x,y,z] = superquad(xscale, yscale, zscale, e1, e2, n)
% Set up parameters of the parametric surface, in this case matrices
% corresponding to longitude and latitude on our superquadratic sphere.
long = ones(n,1)*[-pi:2*pi/(n-1):pi];
lat = [-pi/2:pi/(n-1): pi/2]'*ones(1,n);
x = xscale * pow(cos(lat),e1) .* pow(cos(long),e2);
y = yscale * pow(cos(lat),e1) .* pow(sin(long),e2);
z = zscale * pow(sin(lat),e1);
% Ensure top and bottom ends are closed. If we do not do this you find
% that due to numerical errors the ends may not be perfectly closed.
x(1,:) = 0; y(1,:) = 0;
x(end,:) = 0; y(end,:) = 0;
if nargout == 0
surfl(x,y,z), shading interp, colormap(copper), axis equal
clear x y z % suppress output
end
%--------------------------------------------------------------------
% Internal function providing a modified definition of power whereby the
% sign of the result always matches the sign of the input value.
function r = pow(a, p)
r = sign(a).* abs(a).^p;
|
github
|
jacksky64/imageProcessing-master
|
gplot3d.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapes/gplot3d.m
| 3,051 |
utf_8
|
023a1e53d0acecbb7ff057579a8854eb
|
function [Xout,Yout,Zout]=gplot3d(A,xyz,lc)
%GPLOT3D Plot graph, as in "graph theory".
% This is a modification of MATLAB's GPLOT function for vertices in 3D.
% GPLOT3D(A,xyz) plots the graph specified by A and xyz. A graph, G, is
% a set of nodes numbered from 1 to n, and a set of connections, or
% edges, between them.
%
% In order to plot G, two matrices are needed. The adjacency matrix,
% A, has a(i,j) nonzero if and only if node i is connected to node
% j. The coordinates array, xyz, is an n-by-3 matrix with the
% position for node i in the i-th row, xyz(i,:) = [x(i) y(i) z(i)].
%
% GPLOT(A,xyz,LineSpec) uses line type and color specified in the
% string LineSpec. See PLOT for possibilities.
%
% [X,Y] = GPLOT(A,xyz) returns the NaN-punctuated vectors
% X and Y without actually generating a plot. These vectors
% can be used to generate the plot at a later time if desired. As a
% result, the two argument output case is only valid when xyz is of type
% single or double.
%
% This code is MATLAB's GPLOT function modified so that it plots a graph
% where the vertices are defined in 3D
%
% See also SPY, TREEPLOT, GPLOT
%
% John Gilbert
% Copyright 1984-2009 The MathWorks, Inc.
% $Revision: 5.12.4.4 $ $Date: 2009/04/21 03:26:12 $
%
% 3D modifications by Peter Kovesi
% peter.kovesi at uwa edu au
[i,j] = find(A);
[~, p] = sort(max(i,j));
i = i(p);
j = j(p);
X = [ xyz(i,1) xyz(j,1)]';
Y = [ xyz(i,2) xyz(j,2)]';
Z = [ xyz(i,3) xyz(j,3)]';
if isfloat(xyz) || nargout ~= 0
X = [X; NaN(size(i))'];
Y = [Y; NaN(size(i))'];
Z = [Z; NaN(size(i))'];
end
if nargout == 0
if ~isfloat(xyz)
if nargin < 3
lc = '';
end
[lsty, csty, msty] = gplotGetRightLineStyle(gca,lc);
plot3(X,Y,Z,'LineStyle',lsty,'Color',csty,'Marker',msty);
else
if nargin < 3
plot3(X(:),Y(:),Z(:));
else
plot3(X(:),Y(:),Z(:),lc);
end
end
else
Xout = X(:);
Yout = Y(:);
Zout = Z(:);
end
function [lsty, csty, msty] = gplotGetRightLineStyle(ax, lc)
% gplotGetRightLineStyle
% Helper function which correctly sets the color, line style, and marker
% style when plotting the data above. This style makes sure that the
% plot is as conformant as possible to gplot from previous versions of
% MATLAB, even when the coordinates array is not a floating point type.
co = get(ax,'ColorOrder');
lo = get(ax,'LineStyleOrder');
holdstyle = getappdata(gca,'PlotHoldStyle');
if isempty(holdstyle)
holdstyle = 0;
end
lind = getappdata(gca,'PlotLineStyleIndex');
if isempty(lind) || holdstyle ~= 1
lind = 1;
end
cind = getappdata(gca,'PlotColorIndex');
if isempty(cind) || holdstyle ~= 1
cind = 1;
end
nlsty = lo(lind);
ncsty = co(cind,:);
nmsty = 'none';
% Get the linespec requested by the user.
[lsty,csty,msty] = colstyle(lc);
if isempty(lsty)
lsty = nlsty;
end
if isempty(csty)
csty = ncsty;
end
if isempty(msty)
msty = nmsty;
end
|
github
|
jacksky64/imageProcessing-master
|
icosahedron.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapes/icosahedron.m
| 3,196 |
utf_8
|
deced73cec8d737a7b03e362c983c1e5
|
% ICOSAHEDRON Generates vertices and graph of icosahedron
%
% Usage: [xyz, A, F] = icosahedron(radius)
%
% Argument: radius - Optional radius of icosahedron. Defaults to 1.
% Returns: xyz - 12x3 matrix of vertex coordinates.
% A - Adjacency matrix defining connectivity of vertices.
% F - 20x3 matrix specifying the 3 nodes that define each face.
%
% See also: GEODOME, GPLOT3D, DRAWFACES
% Copyright (c) 2009 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 2009
function [xyz, A, F] = icosahedron(radius)
if ~exist('radius','var')
radius = 1;
end
% Compute the 12 vertices
phi = (1+sqrt(5))/2; % Golden ratio
xyz = [0 1 phi
0 -1 phi
0 1 -phi
0 -1 -phi
1 phi 0
-1 phi 0
1 -phi 0
-1 -phi 0
phi 0 1
-phi 0 1
phi 0 -1
-phi 0 -1];
% Scale to required radius
xyz = xyz*radius/(sqrt(1+phi^2));
% Define the adjacency matrix
% 1 2 3 4 5 6 7 8 9 10 11 12
A = [0 1 0 0 1 1 0 0 1 1 0 0
1 0 0 0 0 0 1 1 1 1 0 0
0 0 0 1 1 1 0 0 0 0 1 1
0 0 1 0 0 0 1 1 0 0 1 1
1 0 1 0 0 1 0 0 1 0 1 0
1 0 1 0 1 0 0 0 0 1 0 1
0 1 0 1 0 0 0 1 1 0 1 0
0 1 0 1 0 0 1 0 0 1 0 1
1 1 0 0 1 0 1 0 0 0 1 0
1 1 0 0 0 1 0 1 0 0 0 1
0 0 1 1 1 0 1 0 1 0 0 0
0 0 1 1 0 1 0 1 0 1 0 0];
% Define nodes that make up each face
F = [1 2 9
1 9 5
1 5 6
1 6 10
1 10 2
2 7 9
9 7 11
9 11 5
5 11 3
5 3 6
6 3 12
6 12 10
10 12 8
10 8 2
2 8 7
4 7 8
4 8 12
4 12 3
4 3 11
4 11 7];
% The icosahedron defined above is oriented so that an edge is at the
% top. The following code transforms the vertex coordinates so that a
% vertex is at the top to give a more conventional view.
%
% Define coordinate frame where z passes through one of the vertices and
% transform the vertices so that one of the vertices is at the 'top'.
Z = xyz(1,:)'; % Z passes through vertex 1
X = xyz(2,:)'; % Choose adjacent vertex as an approximate X
Y = cross(Z,X); % Y is perpendicular to Z and this approx X
X = cross(Y,Z); % Final X is perpendicular to Y and Z
X = X/norm(X); Y = Y/norm(Y); Z = Z/norm(Z); % Ensure unit vectors
xyz = ([X Y Z]'*xyz')'; % Transform points;
|
github
|
jacksky64/imageProcessing-master
|
geodome.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapes/geodome.m
| 7,596 |
utf_8
|
d70bca00571f6191c84ac6221a8de9b3
|
% GEODOME Generates geodesic sphere
%
% Usage: [xyz, A, F] = geodome(frequency, radius)
%
% The sphere is generated from subdivisions of the faces of an icosahedron.
%
% Arguments:
% frequency - The number of subdivisions of each edge of an
% icosahedron. A frequency of 1 will give you an
% icosahedron. A high number will give you a more
% spherical shape. Defaults to 2.
% radius - Radius of the sphere. Defaults to 1.
% Returns:
% xyz - A nx3 matrix defining the vertex list, each row is the
% x,y,z coordinates of a vertex.
% A - Adjacency matrix defining the connectivity of the
% vertices
% F - A mx3 matrix defining the face list. Each row of F
% specifies the 3 vertices that make up the face.
%
% Example:
% [xyz, A, F] = geodome(3, 5); % Generate a 3-frequency sphere with
% % radius 5
% gplot3d(A, xyz); % Use adjacency matrix and vertex list to
% % generate a wireframe plot.
% drawfaces(xyz, F); % Use face and vertex lists to generate
% % surface patch plot.
% axis vis3d, axis off, rotate3d on
%
% See also: ICOSAHEDRON, GPLOT3D, DRAWFACES
% Copyright (c) 2009 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 2009
% April 2014 - Dome radius scaling fixed (thanks to Brad Keserich)
function [xyz, A, F] = geodome(frequency, radius)
if ~exist('frequency','var')
frequency = 2;
end
if ~exist('radius','var')
radius = 1;
end
if frequency < 1
error('Frequency must be an integer >= 1');
end
% Generate vertices of base icosahedron
[icosXYZ, icosA, icosF] = icosahedron(1);
% Compute number of vertices in geodesic sphere. This is the 12 vertices
% of the icosahedron + the extra vertices introduced on each of the 30
% edges + the extra vertices in the interior of the of each of the 20
% faces. This latter is a sum of an arithmetic series [1 .. (frequency-2)]
fm1 = frequency - 1;
fm2 = frequency - 2;
nVert = 12 + 30*fm1 + 20*fm2*fm1/2;
xyz = zeros(nVert,3);
if frequency == 1 % Just return the icosahedron
xyz = icosXYZ;
A = icosA;
F = icosF;
else % For all frequencies > 1
xyz(1:12,:) = icosXYZ; % Grab the vertices of the icosahedron
offset = 13;
% Find the nodes that connect edges. Note we use the upper triangular
% part of the adjacency matrix so that we only get each edge once.
[i,j] = find(triu(icosA));
% Generate extra vertices on every edge of the icoshedron.
for n = 1:length(i)
xyz(offset:(offset+fm2) ,:) = ...
divideEdge(icosXYZ(i(n),:), icosXYZ(j(n),:), frequency);
offset = offset+fm1;
end
% Generate the extra vertices within each face of the icoshedron.
for f = 1:length(icosF)
% Re subdivide two of the edges of the face and get the vertices
% (Yes, this is wasteful but it makes code logic easier)
V1 = divideEdge(icosXYZ(icosF(f,1),:), icosXYZ(icosF(f,2),:), frequency);
V2 = divideEdge(icosXYZ(icosF(f,1),:), icosXYZ(icosF(f,3),:), frequency);
% Now divide the edges that join the new vertices along the
% subdivided edges.
for v = 2:fm1
VF = divideEdge(V1(v,:), V2(v,:), v);
xyz(offset:(offset+v-2),:) = VF;
offset = offset+v-1;
end
end
end
xyz = xyz*radius; % Scale vertices to required radius
A = adjacency(xyz);
F = faces(A);
%---------------------------------------------------------------------
% Function to divide an edge defined between vertices V1 and V2 into nSeg
% segments and return the coordinates of the vertices.
% This function simplistically divides the distance between V1 and V2
function vert = divideEdgeOld(V1, V2, nSeg)
edge = V2 - V1; % Vector along edge
% Now add appropriate fractions of the edge length to the first node
vert = zeros(nSeg-1, 3);
for f = 1:(nSeg-1)
vert(f,:) = V1 + edge * f/nSeg;
vert(f,:) = vert(f,:)/norm(vert(f,:)); % Normalize to unit length
end
%---------------------------------------------------------------------
% Function to divide an edge defined between vertices V1 and V2 into nSeg
% segments and return the coordinates of the vertices.
% This function divides the *angle* between V1 and V2
% rather than the distance.
function vert = divideEdge(V1, V2, nSeg)
axis = cross(V1,V2);
angle = atan(norm(axis)/dot(V1,V2));
axis = axis/norm(axis);
% Now add appropriate fractions of the edge length to the first node
vert = zeros(nSeg-1, 3);
for f = 1:(nSeg-1)
Q = newquaternion(f*angle/nSeg, axis);
vert(f,:) = quaternionrotate(Q,V1);
vert(f,:) = vert(f,:)/norm(vert(f,:)); % Normalize to unit length
end
%-------------------------------------------------------------------------
% Function to build adjacency matrix for geodesic sphere by brute force
function A = adjacency(xyz)
nVert = length(xyz);
A = zeros(nVert);
% Find distances between all pairs of vertices
for n1 = 1:nVert-1
A(n1,n1) = Inf;
for n2 = n1+1:nVert
A(n1,n2) = norm(xyz(n2,:) - xyz(n1,:));
end
end
A(nVert,nVert) = Inf;
A = A+A'; % Make A symmetric
% Find min distance in first row.
minD = min(A(1,:)');
% Assume that no edge can be more than 1.5 times this minimum distance, use
% this to decide connectivity of nodes.
A = A < minD*1.5;
%-----------------------------------------------------------------------------
% Function to find the triplets of vertices that define the faces of the
% geodesic sphere
function F = faces(A)
% Strategy: We are only after cycles of length 3 in graph defined by A.
% For every node N0 (except the last two, which we will not need to visit)
% - Get list of neighbours, N1
% - For each neighbour N1i in N1 find its list of neighbours, N2.
% - Any neighbour in N2 that is in N1 must form a cycle of length 3 with N0
nVert = length(A);
F = [];
for N0 = 1:nVert-2
N1 = find(A(N0,:)); % Neighbours of N0
for N1i = N1
N2 = find(A(N1i,:));
cycle = intersect(N2,N1); % Find the 2 nodes of N2 that are in N1
F = [F; [N0 N1i cycle(1)]; [N0 N1i cycle(2)]];
end
end
% Each face will be found multiple times, eliminate duplicates.
F = sort(F,2); % Sort rows of face list
F = unique(F,'rows'); % ...then extract the unique rows.
|
github
|
jacksky64/imageProcessing-master
|
drawfaces.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapes/drawfaces.m
| 2,247 |
utf_8
|
5c8a03943a5894a51836931271cbc606
|
% DRAWFACES Draws triangular faces defined by vertices and face vertex lists
%
% Usage: drawfaces(xyz, F, col)
%
% Arguments:
% xyz - A nx3 matrix defining the vertex list, each row is the
% x,y,z coordinates of a vertex.
% F - A mx3 matrix defining the face list. Each row of F
% specifies the indices of the 3 vertices that make up the
% face.
% col - Optional colour specifier of the faces. This can be 'r',
% 'g', 'b' 'w', k' etc or a RGB 3-vector.
% Defaults to [1 1 1] (white). If col is specified as the
% string 'rand' each face is given a random colour.
% if col has n rows it is assumed that col specifies the
% colour to be used for each vertex, see documentation for
% PATCH.
%
% See also: GPLOT3D, ICOSAHEDRON, GEODOME
% Copyright (c) 2009 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 2009
function drawfaces(xyz, F, col)
if ~exist('col', 'var')
col = [1 1 1];
end
nPatch = size(F,1);
nVert = size(xyz,1);
if size(col,1) == nVert
for p = 1:nPatch
coords = xyz(F(p,:),:);
h = patch(coords(:,1), coords(:,2), coords(:,3), col(F(p,:),:));
% set(h,'EdgeColor','none');
end
elseif strcmpi(col,'rand')
for p = 1:nPatch
coords = xyz(F(p,:),:);
patch(coords(:,1), coords(:,2), coords(:,3),rand(1,3))
end
else
for p = 1:nPatch
coords = xyz(F(p,:),:);
patch(coords(:,1), coords(:,2), coords(:,3), col)
end
end
|
github
|
jacksky64/imageProcessing-master
|
matchbymonogenicphase.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Match/matchbymonogenicphase.m
| 9,328 |
utf_8
|
e63225faedcf391fb6411d27d71a208e
|
% MATCHBYMONOGENICPHASE - match image feature points using monogenic phase data
%
% Function generates putative matches between previously detected
% feature points in two images by looking for points that have minimal
% differences in monogenic phase data within windows surrounding each point.
% Only points that correlate most strongly with each other in *both*
% directions are returned. This is a simple-minded N^2 comparison.
%
% This matcher performs rather well relative to normalised greyscale
% correlation. Typically there are more putative matches found and fewer
% outliers. There is a greater computational cost in the pre-filtering stage
% but potentially the matching stage is much faster as each pixel is effectively
% encoded with only 3 bits. (Though this potential speed is not realized in this
% implementation)
%
% Usage: [m1,m2] = matchbymonogenicphase(im1, p1, im2, p2, w, dmax, ...
% nscale, minWaveLength, mult, sigmaOnf)
%
% Arguments:
% im1, im2 - Images containing points that we wish to match.
% p1, p2 - Coordinates of feature pointed detected in im1 and
% im2 respectively using a corner detector (say Harris
% or phasecong2). p1 and p2 are [2xnpts] arrays though
% p1 and p2 are not expected to have the same number
% of points. The first row of p1 and p2 gives the row
% coordinate of each feature point, the second row
% gives the column of each point.
% w - Window size (in pixels) over which the phase bit codes
% around each feature point are matched. This should
% be an odd number.
% dmax - Maximum search radius for matching points. Used to
% improve speed when there is little disparity between
% images. Even setting it to a generous value of 1/4 of
% the image size gives a useful speedup.
% nscale - Number of filter scales.
% minWaveLength - Wavelength of smallest scale filter.
% mult - Scaling factor between successive filters.
% sigmaOnf - Ratio of the standard deviation of the Gaussian
% describing the log Gabor filter's transfer function in
% the frequency domain to the filter center frequency.
%
%
% Returns:
% m1, m2 - Coordinates of points selected from p1 and p2
% respectively such that (putatively) m1(:,i) matches
% m2(:,i). m1 and m2 are [2xnpts] arrays defining the
% points in each of the images in the form [row;col].
%
%
% I have had good success with the folowing parameters:
%
% w = 11; Window size for correlation matching, 7 or greater
% seems fine.
% dmax = 50;
% nscale = 1; Just one scale can give very good results. Adding
% another scale doubles computation
% minWaveLength = 10;
% mult = 4; This is irrelevant if only one scale is used. If you do
% use more than one scale try values in the range 2-4.
% sigmaOnf = .2; This results in a *very* large bandwidth filter. A
% large bandwidth seems to be very important in the
% matching performance.
%
% See Also: MATCHBYCORRELATION, MONOFILT
% Copyright (c) 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.
% May 2005 - Original version adapted from matchbycorrelation.m
function [m1,m2,cormat] = matchbymonogenicphase(im1, p1, im2, p2, w, dmax, ...
nscale, minWaveLength, mult, sigmaOnf)
orientWrap = 0;
[f1, h1f1, h2f1, A1] = ...
monofilt(im1, nscale, minWaveLength, mult, sigmaOnf, orientWrap);
[f2, h1f2, h2f2, A2] = ...
monofilt(im2, nscale, minWaveLength, mult, sigmaOnf, orientWrap);
% Normalise filter outputs to unit vectors (should also have masking for
% unreliable filter outputs)
for s = 1:nscale
% f1{s} = f1{s}./A1{s}; f2{s} = f2{s}./A2{s};
% h1f1{s} = h1f1{s}./A1{s}; h1f2{s} = h1f2{s}./A2{s};
% h2f1{s} = h2f1{s}./A1{s}; h2f2{s} = h2f2{s}./A2{s};
% Try quantizing oriented phase vector to 8 octants to see what
% effect this has (Performance seems to be reduced only slightly)
f1{s} = sign(f1{s}); f2{s} = sign(f2{s});
h1f1{s} = sign(h1f1{s}); h1f2{s} = sign(h1f2{s});
h2f1{s} = sign(h2f1{s}); h2f2{s} = sign(h2f2{s});
end
% Generate correlation matrix
cormat = correlationmatrix(f1, h1f1, h2f1, p1, ...
f2, h1f2, h2f2, p2, w, dmax);
[corrows,corcols] = size(cormat);
% Find max along rows give strongest match in p2 for each p1
[mp2forp1, colp2forp1] = max(cormat,[],2);
% Find max down cols give strongest match in p1 for each p2
[mp1forp2, rowp1forp2] = max(cormat,[],1);
% Now find matches that were consistent in both directions
p1ind = zeros(1,length(p1)); % Arrays for storing matched indices
p2ind = zeros(1,length(p2));
indcount = 0;
for n = 1:corrows
if rowp1forp2(colp2forp1(n)) == n % consistent both ways
indcount = indcount + 1;
p1ind(indcount) = n;
p2ind(indcount) = colp2forp1(n);
end
end
% Trim arrays of indices of matched points
p1ind = p1ind(1:indcount);
p2ind = p2ind(1:indcount);
% Extract matched points from original arrays
m1 = p1(:,p1ind);
m2 = p2(:,p2ind);
%-------------------------------------------------------------------------
% Function that does the work. This function builds a 'correlation' matrix
% that holds the correlation strength of every point relative to every other
% point. While this seems a bit wasteful we need all this data if we want
% to find pairs of points that correlate maximally in both directions.
function cormat = correlationmatrix(f1, h1f1, h2f1, p1, ...
f2, h1f2, h2f2, p2, w, dmax)
if mod(w, 2) == 0 | w < 3
error('Window size should be odd and >= 3');
end
r = (w-1)/2; % 'radius' of correlation window
[rows1, npts1] = size(p1);
[rows2, npts2] = size(p2);
if rows1 ~= 2 | rows2 ~= 2
error('Feature points must be specified in 2xN arrays');
end
% Reorganize monogenic phase data into a 4D matrices for convenience
[im1rows,im1cols] = size(f1{1});
[im2rows,im2cols] = size(f2{1});
nscale = length(f1);
phase1 = zeros(im1rows,im1cols,nscale,3);
phase2 = zeros(im2rows,im2cols,nscale,3);
for s = 1:nscale
phase1(:,:,s,1) = f1{s}; phase1(:,:,s,2) = h1f1{s}; phase1(:,:,s,3) = h2f1{s};
phase2(:,:,s,1) = f2{s}; phase2(:,:,s,2) = h1f2{s}; phase2(:,:,s,3) = h2f2{s};
end
% Initialize correlation matrix values to -infinity
cormat = repmat(-inf, npts1, npts2);
% For every feature point in the first image extract a window of data
% and correlate with a window corresponding to every feature point in
% the other image. Any feature point less than distance 'r' from the
% boundary of an image is not considered.
% Find indices of points that are distance 'r' or greater from
% boundary on image1 and image2;
n1ind = find(p1(1,:)>r & p1(1,:)<im1rows+1-r & ...
p1(2,:)>r & p1(2,:)<im1cols+1-r);
n2ind = find(p2(1,:)>r & p2(1,:)<im2rows+1-r & ...
p2(2,:)>r & p2(2,:)<im2cols+1-r);
for n1 = n1ind
% Identify the indices of points in p2 that we need to consider.
if dmax == inf
n2indmod = n2ind; % We have to consider all of n2ind
else % Compute distances from p1(:,n1) to all available p2.
p1pad = repmat(p1(:,n1),1,length(n2ind));
dists2 = sum((p1pad-p2(:,n2ind)).^2);
% Find indices of points in p2 that are within distance dmax of
% p1(:,n1)
n2indmod = n2ind(find(dists2 < dmax^2));
end
% Generate window in 1st image
w1 = phase1(p1(1,n1)-r:p1(1,n1)+r, p1(2,n1)-r:p1(2,n1)+r, :, :);
for n2 = n2indmod
% Generate window in 2nd image
w2 = phase2(p2(1,n2)-r:p2(1,n2)+r, p2(2,n2)-r:p2(2,n2)+r, :, :);
% Compute dot product as correlation measure
cormat(n1,n2) = w1(:)'*w2(:);
% *** Need to add mask stuff
end
end
|
github
|
jacksky64/imageProcessing-master
|
matchbycorrelation.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Match/matchbycorrelation.m
| 7,076 |
utf_8
|
12d7e8d4ad6e140c94444ddc3682d518
|
% MATCHBYCORRELATION - match image feature points by correlation
%
% Function generates putative matches between previously detected
% feature points in two images by looking for points that are maximally
% correlated with each other within windows surrounding each point.
% Only points that correlate most strongly with each other in *both*
% directions are returned.
% This is a simple-minded N^2 comparison.
%
% Usage: [m1, m2, p1ind, p2ind, cormat] = ...
% matchbycorrelation(im1, p1, im2, p2, w, dmax)
%
% Arguments:
% im1, im2 - Images containing points that we wish to match.
% p1, p2 - Coordinates of feature pointed detected in im1 and
% im2 respectively using a corner detector (say Harris
% or phasecong2). p1 and p2 are [2xnpts] arrays though
% p1 and p2 are not expected to have the same number
% of points. The first row of p1 and p2 gives the row
% coordinate of each feature point, the second row
% gives the column of each point.
% w - Window size (in pixels) over which the correlation
% around each feature point is performed. This should
% be an odd number.
% dmax - (Optional) Maximum search radius for matching
% points. Used to improve speed when there is little
% disparity between images. Even setting it to a generous
% value of 1/4 of the image size gives a useful
% speedup. If this parameter is omitted it defaults to Inf.
%
%
% Returns:
% m1, m2 - Coordinates of points selected from p1 and p2
% respectively such that (putatively) m1(:,i) matches
% m2(:,i). m1 and m2 are [2xnpts] arrays defining the
% points in each of the images in the form [row;col].
% p1ind, p2ind - Indices of points in p1 and p2 that form a match. Thus,
% m1 = p1(:,p1ind) and m2 = p2(:,p2ind)
% cormat - Correlation matrix; rows correspond to points in p1,
% columns correspond to points in p2
% Copyright (c) 2004-2009 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.
% February 2004 - Original version
% May 2004 - Speed improvements + constraint on search radius for
% additional speed
% August 2004 - Vectorized distance calculation for more speed
% (thanks to Daniel Wedge)
% December 2009 - Added return of indices of matching points from original
% point arrays
function [m1, m2, p1ind, p2ind, cormat] = ...
matchbycorrelation(im1, p1, im2, p2, w, dmax)
if nargin == 5
dmax = Inf;
end
im1 = double(im1);
im2 = double(im2);
% Subtract image smoothed with an averaging filter of size wXw from
% each of the images. This compensates for brightness differences in
% each image. Doing it now allows faster correlation calculation.
im1 = im1 - filter2(fspecial('average',w),im1);
im2 = im2 - filter2(fspecial('average',w),im2);
% Generate correlation matrix
cormat = correlatiomatrix(im1, p1, im2, p2, w, dmax);
[corrows,corcols] = size(cormat);
% Find max along rows give strongest match in p2 for each p1
[mp2forp1, colp2forp1] = max(cormat,[],2);
% Find max down cols give strongest match in p1 for each p2
[mp1forp2, rowp1forp2] = max(cormat,[],1);
% Now find matches that were consistent in both directions
p1ind = zeros(1,length(p1)); % Arrays for storing matched indices
p2ind = zeros(1,length(p2));
indcount = 0;
for n = 1:corrows
if rowp1forp2(colp2forp1(n)) == n % consistent both ways
indcount = indcount + 1;
p1ind(indcount) = n;
p2ind(indcount) = colp2forp1(n);
end
end
% Trim arrays of indices of matched points
p1ind = p1ind(1:indcount);
p2ind = p2ind(1:indcount);
% Extract matched points from original arrays
m1 = p1(:,p1ind);
m2 = p2(:,p2ind);
%-------------------------------------------------------------------------
% Function that does the work. This function builds a correlation matrix
% that holds the correlation strength of every point relative to every
% other point. While this seems a bit wasteful we need all this data if
% we want to find pairs of points that correlate maximally in both
% directions.
%
% This code assumes im1 and im2 have zero mean. This speeds the
% calculation of the normalised correlation measure.
function cormat = correlatiomatrix(im1, p1, im2, p2, w, dmax)
if mod(w, 2) == 0
error('Window size should be odd');
end
[rows1, npts1] = size(p1);
[rows2, npts2] = size(p2);
% Initialize correlation matrix values to -infinty
cormat = -ones(npts1,npts2)*Inf;
if rows1 ~= 2 | rows2 ~= 2
error('Feature points must be specified in 2xN arrays');
end
[im1rows, im1cols] = size(im1);
[im2rows, im2cols] = size(im2);
r = (w-1)/2; % 'radius' of correlation window
% For every feature point in the first image extract a window of data
% and correlate with a window corresponding to every feature point in
% the other image. Any feature point less than distance 'r' from the
% boundary of an image is not considered.
% Find indices of points that are distance 'r' or greater from
% boundary on image1 and image2;
n1ind = find(p1(1,:)>r & p1(1,:)<im1rows+1-r & ...
p1(2,:)>r & p1(2,:)<im1cols+1-r);
n2ind = find(p2(1,:)>r & p2(1,:)<im2rows+1-r & ...
p2(2,:)>r & p2(2,:)<im2cols+1-r);
for n1 = n1ind
% Generate window in 1st image
w1 = im1(p1(1,n1)-r:p1(1,n1)+r, p1(2,n1)-r:p1(2,n1)+r);
% Pre-normalise w1 to a unit vector.
w1 = w1./sqrt(sum(sum(w1.*w1)));
% Identify the indices of points in p2 that we need to consider.
if dmax == inf
n2indmod = n2ind; % We have to consider all of n2ind
else % Compute distances from p1(:,n1) to all available p2.
p1pad = repmat(p1(:,n1),1,length(n2ind));
dists2 = sum((p1pad-p2(:,n2ind)).^2);
% Find indices of points in p2 that are within distance dmax of
% p1(:,n1)
n2indmod = n2ind(find(dists2 < dmax^2));
end
% Calculate noralised correlation measure. Note this gives
% significantly better matches than the unnormalised one.
for n2 = n2indmod
% Generate window in 2nd image
w2 = im2(p2(1,n2)-r:p2(1,n2)+r, p2(2,n2)-r:p2(2,n2)+r);
cormat(n1,n2) = sum(sum(w1.*w2))/sqrt(sum(sum(w2.*w2)));
end
end
|
github
|
jacksky64/imageProcessing-master
|
phasesym.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/phasesym.m
| 22,344 |
utf_8
|
fe0d5de58f828487776d00bfabd5f354
|
% PHASESYM - Function for computing phase symmetry on an image.
%
% This function calculates the phase symmetry of points in an image.
% This is a contrast invariant measure of symmetry. This function can be
% used as a line and blob detector. The greyscale 'polarity' of the lines
% that you want to find can be specified.
%
% There are potentially many arguments, here is the full usage:
%
% [phaseSym, orientation, totalEnergy, T] = ...
% phasesym(im, nscale, norient, minWaveLength, mult, ...
% sigmaOnf, k, polarity, noiseMethod)
%
% However, apart from the image, all parameters have defaults and the
% usage can be as simple as:
%
% phaseSym = phasesym(im);
%
% Arguments:
% Default values Description
%
% nscale 5 - Number of wavelet scales, try values 3-6
% norient 6 - Number of filter orientations.
% minWaveLength 3 - Wavelength of smallest scale filter.
% mult 2.1 - Scaling factor between successive filters.
% sigmaOnf 0.55 - Ratio of the standard deviation of the Gaussian
% describing the log Gabor filter's transfer function
% in the frequency domain to the filter center frequency.
% k 2.0 - No of standard deviations of the noise energy beyond
% the mean at which we set the noise threshold point.
% You may want to vary this up to a value of 10 or
% 20 for noisy images
% polarity 0 - Controls 'polarity' of symmetry features to find.
% 1 - just return 'bright' points
% -1 - just return 'dark' points
% 0 - return bright and dark points.
% noiseMethod -1 - Parameter specifies method used to determine
% noise statistics.
% -1 use median of smallest scale filter responses
% -2 use mode of smallest scale filter responses
% 0+ use noiseMethod value as the fixed noise threshold.
%
% Return values:
% phaseSym - Phase symmetry image (values between 0 and 1).
% orientation - Orientation image. Orientation in which local
% symmetry energy is a maximum, in degrees
% (0-180), angles positive anti-clockwise. Note
% the orientation info is quantized by the number
% of orientations
% totalEnergy - Un-normalised raw symmetry energy which may be
% more to your liking.
% T - Calculated noise threshold (can be useful for
% diagnosing noise characteristics of images). Once you know
% this you can then specify fixed thresholds and save some
% computation time.
%
% Notes on specifying parameters:
%
% The parameters can be specified as a full list eg.
% >> phaseSym = phasesym(im, 5, 6, 3, 2.5, 0.55, 2.0, 0);
%
% or as a partial list with unspecified parameters taking on default values
% >> phaseSym = phasesym(im, 5, 6, 3);
%
% or as a partial list of parameters followed by some parameters specified via a
% keyword-value pair, remaining parameters are set to defaults, for example:
% >> phaseSym = phasesym(im, 5, 6, 3, 'polarity',-1, 'k', 2.5);
%
% The convolutions are done via the FFT. Many of the parameters relate to the
% specification of the filters in the frequency plane. The values do not seem
% to be very critical and the defaults are usually fine. You may want to
% experiment with the values of 'nscales' and 'k', the noise compensation factor.
%
% Notes on filter settings to obtain even coverage of the spectrum
% sigmaOnf .85 mult 1.3
% sigmaOnf .75 mult 1.6 (filter bandwidth ~1 octave)
% sigmaOnf .65 mult 2.1
% sigmaOnf .55 mult 3 (filter bandwidth ~2 octaves)
%
% For maximum speed the input image should have dimensions that correspond to
% powers of 2, but the code will operate on images of arbitrary size.
%
% See Also: PHASECONG, PHASECONG2, GABORCONVOLVE, PLOTGABORFILTERS
% References:
% Peter Kovesi, "Symmetry and Asymmetry From Local Phase" AI'97, Tenth
% Australian Joint Conference on Artificial Intelligence. 2 - 4 December
% 1997. http://www.cs.uwa.edu.au/pub/robvis/papers/pk/ai97.ps.gz.
%
% Peter Kovesi, "Image Features From Phase Congruency". Videre: A
% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,
% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html
% April 1996 Original Version written
% August 1998 Noise compensation corrected.
% October 1998 Noise compensation corrected. - Again!!!
% September 1999 Modified to operate on non-square images of arbitrary size.
% February 2001 Specialised from phasecong.m to calculate phase symmetry
% July 2005 Better argument handling + general cleanup and speed improvements
% August 2005 Made Octave compatible.
% January 2007 Small correction and cleanup of radius calculation for odd
% image sizes.
% May 2009 Noise compensation simplified reducing memory and
% computation overhead. Spread function changed to a cosine
% eliminating parameter dThetaOnSigma and ensuring even
% angular coverage.
% Copyright (c) 1996-2009 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.
function[phaseSym, orientation, totalEnergy, T] = phasesym(varargin)
% Get arguments and/or default values
[im, nscale, norient, minWaveLength, mult, sigmaOnf, k, ...
polarity, noiseMethod] = checkargs(varargin(:));
epsilon = 1e-4; % Used to prevent division by zero.
[rows,cols] = size(im);
imagefft = fft2(im); % Fourier transform of image
zero = zeros(rows,cols);
totalEnergy = zero; % Matrix for accumulating weighted phase
% congruency values (energy).
totalSumAn = zero; % Matrix for accumulating filter response
% amplitude values.
orientation = zero; % Matrix storing orientation with greatest
% energy for each pixel.
% Pre-compute some stuff to speed up filter construction
% 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); % Matrix values contain *normalised* radius from centre.
theta = atan2(-y,x); % Matrix values contain polar angle.
% (note -ve y is used to give +ve
% anti-clockwise angles)
radius = ifftshift(radius); % Quadrant shift radius and theta so that filters
theta = ifftshift(theta); % are constructed with 0 frequency at the corners.
radius(1,1) = 1; % Get rid of the 0 radius value at the 0
% frequency point (now at top-left corner)
% so that taking the log of the radius will
% not cause trouble.
sintheta = sin(theta);
costheta = cos(theta);
clear x; clear y; clear theta; % save a little memory
% Filters are constructed in terms of two components.
% 1) The radial component, which controls the frequency band that the filter
% responds to
% 2) The angular component, which controls the orientation that the filter
% responds to.
% The two components are multiplied together to construct the overall filter.
% Construct the radial filter components...
% First construct a low-pass filter that is as large as possible, yet falls
% away to zero at the boundaries. All log Gabor filters are multiplied by
% this to ensure no extra frequencies at the 'corners' of the FFT are
% incorporated as this seems to upset the normalisation process when
% calculating phase congrunecy.
lp = lowpassfilter([rows,cols],.4,10); % Radius .4, 'sharpness' 10
logGabor = cell(1,nscale);
for s = 1:nscale
wavelength = minWaveLength*mult^(s-1);
fo = 1.0/wavelength; % Centre frequency of filter.
logGabor{s} = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2));
logGabor{s} = logGabor{s}.*lp; % Apply low-pass filter
logGabor{s}(1,1) = 0; % Set the value at the 0 frequency point of the filter
% back to zero (undo the radius fudge).
end
%% The main loop...
for o = 1:norient % For each orientation....
% Construct the angular filter spread function
angl = (o-1)*pi/norient; % Filter angle.
% For each point in the filter matrix calculate the angular distance from
% the specified filter orientation. To overcome the angular wrap-around
% problem sine difference and cosine difference values are first computed
% and then the atan2 function is used to determine angular distance.
ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.
dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.
dtheta = abs(atan2(ds,dc)); % Absolute angular distance.
% Scale theta so that cosine spread function has the right wavelength
% and clamp to pi.
dtheta = min(dtheta*norient/2,pi);
% The spread function is cos(dtheta) between -pi and pi. We add 1,
% and then divide by 2 so that the value ranges 0-1
spread = (cos(dtheta)+1)/2;
sumAn_ThisOrient = zero;
Energy_ThisOrient = zero;
for s = 1:nscale % For each scale....
filter = logGabor{s} .* spread; % Multiply radial and angular
% components to get filter.
% Convolve image with even and odd filters returning the result in EO
EO = ifft2(imagefft .* filter);
An = abs(EO); % Amplitude of even & odd filter response.
sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses.
% At the smallest scale estimate noise characteristics from the
% distribution of the filter amplitude responses stored in sumAn.
% tau is the Rayleigh parameter that is used to describe the
% distribution.
if s == 1
if noiseMethod == -1 % Use median to estimate noise statistics
tau = median(sumAn_ThisOrient(:))/sqrt(log(4));
elseif noiseMethod == -2 % Use mode to estimate noise statistics
tau = rayleighmode(sumAn_ThisOrient(:));
end
end
% Now calculate the phase symmetry measure.
if polarity == 0 % look for 'white' and 'black' spots
Energy_ThisOrient = Energy_ThisOrient ...
+ abs(real(EO)) - abs(imag(EO));
elseif polarity == 1 % Just look for 'white' spots
Energy_ThisOrient = Energy_ThisOrient ...
+ real(EO) - abs(imag(EO));
elseif polarity == -1 % Just look for 'black' spots
Energy_ThisOrient = Energy_ThisOrient ...
- real(EO) - abs(imag(EO));
end
end % ... and process the next scale
%% Automatically determine noise threshold
%
% Assuming the noise is Gaussian the response of the filters to noise will
% form Rayleigh distribution. We use the filter responses at the smallest
% scale as a guide to the underlying noise level because the smallest scale
% filters spend most of their time responding to noise, and only
% occasionally responding to features. Either the median, or the mode, of
% the distribution of filter responses can be used as a robust statistic to
% estimate the distribution mean and standard deviation as these are related
% to the median or mode by fixed constants. The response of the larger
% scale filters to noise can then be estimated from the smallest scale
% filter response according to their relative bandwidths.
%
% This code assumes that the expected reponse to noise on the phase congruency
% calculation is simply the sum of the expected noise responses of each of
% the filters. This is a simplistic overestimate, however these two
% quantities should be related by some constant that will depend on the
% filter bank being used. Appropriate tuning of the parameter 'k' will
% allow you to produce the desired output.
if noiseMethod >= 0 % We are using a fixed noise threshold
T = noiseMethod; % use supplied noiseMethod value as the threshold
else
% Estimate the effect of noise on the sum of the filter responses as
% the sum of estimated individual responses (this is a simplistic
% overestimate). As the estimated noise response at succesive scales
% is scaled inversely proportional to bandwidth we have a simple
% geometric sum.
totalTau = tau * (1 - (1/mult)^nscale)/(1-(1/mult));
% Calculate mean and std dev from tau using fixed relationship
% between these parameters and tau. See
% http://mathworld.wolfram.com/RayleighDistribution.html
EstNoiseEnergyMean = totalTau*sqrt(pi/2); % Expected mean and std
EstNoiseEnergySigma = totalTau*sqrt((4-pi)/2); % values of noise energy
% Noise threshold, make sure it is not less than epsilon.
T = max(EstNoiseEnergyMean + k*EstNoiseEnergySigma, epsilon);
end
% Apply noise threshold, this is effectively wavelet denoising via
% soft thresholding. Note 'Energy_ThisOrient' will have -ve values.
% These will be floored out at the final normalization stage.
Energy_ThisOrient = Energy_ThisOrient - T;
% Update accumulator matrix for sumAn and totalEnergy
totalSumAn = totalSumAn + sumAn_ThisOrient;
totalEnergy = totalEnergy + Energy_ThisOrient;
% Update orientation matrix by finding image points where the energy in
% this orientation is greater than in any previous orientation (the
% change matrix) and then replacing these elements in the orientation
% matrix with the current orientation number.
if(o == 1),
maxEnergy = Energy_ThisOrient;
else
change = Energy_ThisOrient > maxEnergy;
orientation = (o - 1).*change + orientation.*(~change);
maxEnergy = max(maxEnergy, Energy_ThisOrient);
end
end % For each orientation
% Normalize totalEnergy by the totalSumAn to obtain phase symmetry
% totalEnergy is floored at 0 to eliminate -ve values
phaseSym = max(totalEnergy, 0) ./ (totalSumAn + epsilon);
% Convert orientation matrix values to degrees
orientation = fix(orientation * (180 / norient));
%------------------------------------------------------------------
% CHECKARGS
%
% Function to process the arguments that have been supplied, assign
% default values as needed and perform basic checks.
function [im, nscale, norient, minWaveLength, mult, sigmaOnf, ...
k, polarity, noiseMethod] = checkargs(arg)
nargs = length(arg);
if nargs < 1
error('No image supplied as an argument');
end
% Set up default values for all arguments and then overwrite them
% with with any new values that may be supplied
im = [];
nscale = 5; % Number of wavelet scales.
norient = 6; % Number of filter orientations.
minWaveLength = 3; % Wavelength of smallest scale filter.
mult = 2.1; % Scaling factor between successive filters.
sigmaOnf = 0.55; % Ratio of the standard deviation of the
% Gaussian describing the log Gabor filter's
% transfer function in the frequency domain
% to the filter center frequency.
k = 2.0; % No of standard deviations of the noise
% energy beyond the mean at which we set the
% noise threshold point.
polarity = 0; % Look for both black and white spots of symmetrry
noiseMethod = -1; % Use median response of smallest scale filter
% to estimate noise characteristics.
% Allowed argument reading states
allnumeric = 1; % Numeric argument values in predefined order
keywordvalue = 2; % Arguments in the form of string keyword
% followed by numeric value
readstate = allnumeric; % Start in the allnumeric state
if readstate == allnumeric
for n = 1:nargs
if isa(arg{n},'char')
readstate = keywordvalue;
break;
else
if n == 1, im = arg{n};
elseif n == 2, nscale = arg{n};
elseif n == 3, norient = arg{n};
elseif n == 4, minWaveLength = arg{n};
elseif n == 5, mult = arg{n};
elseif n == 6, sigmaOnf = arg{n};
elseif n == 7, k = arg{n};
elseif n == 8, polarity = arg{n};
elseif n == 9,noiseMethod = arg{n};
end
end
end
end
% Code to handle parameter name - value pairs
if readstate == keywordvalue
while n < nargs
if ~isa(arg{n},'char') || ~isa(arg{n+1}, 'double')
error('There should be a parameter name - value pair');
end
if strncmpi(arg{n},'im' ,2), im = arg{n+1};
elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1};
elseif strncmpi(arg{n},'norient' ,4), norient = arg{n+1};
elseif strncmpi(arg{n},'minWaveLength',2), minWaveLength = arg{n+1};
elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1};
elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1};
elseif strncmpi(arg{n},'k' ,1), k = arg{n+1};
elseif strncmpi(arg{n},'polarity',2), polarity = arg{n+1};
elseif strncmpi(arg{n},'noiseMethod',4), noiseMethod = arg{n+1};
else error('Unrecognised parameter name');
end
n = n+2;
if n == nargs
error('Unmatched parameter name - value pair');
end
end
end
if isempty(im)
error('No image argument supplied');
end
if ~isa(im, 'double')
im = double(im);
end
if nscale < 1
error('nscale must be an integer >= 1');
end
if norient < 1
error('norient must be an integer >= 1');
end
if minWaveLength < 2
error('It makes little sense to have a wavelength < 2');
end
if polarity ~= -1 && polarity ~= 0 && polarity ~= 1
error('Allowed polarity values are -1, 0 and 1')
end
%%-------------------------------------------------------------------------
% RAYLEIGHMODE
%
% Computes mode of a vector/matrix of data that is assumed to come from a
% Rayleigh distribution.
%
% Usage: rmode = rayleighmode(data, nbins)
%
% Arguments: data - data assumed to come from a Rayleigh distribution
% nbins - Optional number of bins to use when forming histogram
% of the data to determine the mode.
%
% Mode is computed by forming a histogram of the data over 50 bins and then
% finding the maximum value in the histogram. Mean and standard deviation
% can then be calculated from the mode as they are related by fixed
% constants.
%
% mean = mode * sqrt(pi/2)
% std dev = mode * sqrt((4-pi)/2)
%
% See
% http://mathworld.wolfram.com/RayleighDistribution.html
% http://en.wikipedia.org/wiki/Rayleigh_distribution
%
function rmode = rayleighmode(data, nbins)
if nargin == 1
nbins = 50; % Default number of histogram bins to use
end
mx = max(data(:));
edges = 0:mx/nbins:mx;
n = histc(data(:),edges);
[dum,ind] = max(n); % Find maximum and index of maximum in histogram
rmode = (edges(ind)+edges(ind+1))/2;
|
github
|
jacksky64/imageProcessing-master
|
phasesymmono.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/phasesymmono.m
| 19,431 |
utf_8
|
30a844da3cb8a9df67b71b7235e99d8b
|
% PHASESYMMONO - phase symmetry of an image using monogenic filters
%
% This function calculates the phase symmetry of points in an image.
% This is a contrast invariant measure of symmetry. This function can be
% used as a line and blob detector. The greyscale 'polarity' of the lines
% that you want to find can be specified.
%
% This code is considerably faster than PHASESYM but you may prefer the
% output from PHASESYM's oriented filters.
%
% There are potentially many arguments, here is the full usage:
%
% [phaseSym, symmetryEnergy, T] = ...
% phasesymmono(im, nscale, minWaveLength, mult, ...
% sigmaOnf, k, polarity, noiseMethod)
%
% However, apart from the image, all parameters have defaults and the
% usage can be as simple as:
%
% phaseSym = phasesymmono(im);
%
% Arguments:
% Default values Description
%
% nscale 5 - Number of wavelet scales, try values 3-6
% minWaveLength 3 - Wavelength of smallest scale filter.
% mult 2.1 - Scaling factor between successive filters.
% sigmaOnf 0.55 - Ratio of the standard deviation of the Gaussian
% describing the log Gabor filter's transfer function
% in the frequency domain to the filter center frequency.
% k 2.0 - No of standard deviations of the noise energy beyond
% the mean at which we set the noise threshold point.
% You may want to vary this up to a value of 10 or
% 20 for noisy images
% polarity 0 - Controls 'polarity' of symmetry features to find.
% 1 - just return 'bright' points
% -1 - just return 'dark' points
% 0 - return bright and dark points.
% noiseMethod -1 - Parameter specifies method used to determine
% noise statistics.
% -1 use median of smallest scale filter responses
% -2 use mode of smallest scale filter responses
% 0+ use noiseMethod value as the fixed noise threshold
% A value of 0 will turn off all noise compensation.
%
% Return values:
% phaseSym - Phase symmetry image (values between 0 and 1).
% symmetryEnergy - Un-normalised raw symmetry energy which may be
% more to your liking.
% T - Calculated noise threshold (can be useful for
% diagnosing noise characteristics of images)
%
%
% Notes on specifying parameters:
%
% The parameters can be specified as a full list eg.
% >> phaseSym = phasesym(im, 5, 3, 2.5, 0.55, 2.0, 0);
%
% or as a partial list with unspecified parameters taking on default values
% >> phaseSym = phasesym(im, 5, 3);
%
% or as a partial list of parameters followed by some parameters specified via a
% keyword-value pair, remaining parameters are set to defaults, for example:
% >> phaseSym = phasesym(im, 5, 3, 'polarity',-1, 'k', 2.5);
%
% The convolutions are done via the FFT. Many of the parameters relate to the
% specification of the filters in the frequency plane. The values do not seem
% to be very critical and the defaults are usually fine. You may want to
% experiment with the values of 'nscales' and 'k', the noise compensation factor.
%
% Notes on filter settings to obtain even coverage of the spectrum
% sigmaOnf .85 mult 1.3
% sigmaOnf .75 mult 1.6 (filter bandwidth ~1 octave)
% sigmaOnf .65 mult 2.1
% sigmaOnf .55 mult 3 (filter bandwidth ~2 octaves)
%
% For maximum speed the input image should have dimensions that correspond to
% powers of 2, but the code will operate on images of arbitrary size.
%
% See Also: PHASESYM, PHASECONGMONO
% References:
% Peter Kovesi, "Symmetry and Asymmetry From Local Phase" AI'97, Tenth
% Australian Joint Conference on Artificial Intelligence. 2 - 4 December
% 1997. http://www.cs.uwa.edu.au/pub/robvis/papers/pk/ai97.ps.gz.
%
% Peter Kovesi, "Image Features From Phase Congruency". Videre: A
% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,
% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html
%
% Michael Felsberg and Gerald Sommer, "A New Extension of Linear Signal
% Processing for Estimating Local Properties and Detecting Features". DAGM
% Symposium 2000, Kiel
%
% Michael Felsberg and Gerald Sommer. "The Monogenic Signal" IEEE
% Transactions on Signal Processing, 49(12):3136-3144, December 2001
% July 2008 Code developed from phasesym where local phase information
% calculated using Monogenic Filters.
% April 2009 Noise compensation simplified to speedup execution.
% Options to calculate noise statistics via median or mode of
% smallest filter response. Option to use a fixed threshold.
% Return of T for 'instrumentation' of noise detection/compensation.
% Removal of orientation calculation from phasesym (not clear
% how best to calculate this from monogenic filter outputs)
% June 2009 Clean up
% Copyright (c) 1996-2009 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[phaseSym, symmetryEnergy, T] = phasesymmono(varargin)
% Get arguments and/or default values
[im, nscale, minWaveLength, mult, sigmaOnf, k, ...
polarity, noiseMethod] = checkargs(varargin(:));
epsilon = .0001; % Used to prevent division by zero.
[rows,cols] = size(im);
IM = fft2(im); % Fourier transform of image
zero = zeros(rows,cols);
symmetryEnergy = zero; % Matrix for accumulating weighted phase
% symmetry values (energy).
sumAn = zero; % Matrix for accumulating filter response
% amplitude values.
% Pre-compute some stuff to speed up filter construction
%
% Set up u1 and u2 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
[u1,u2] = meshgrid(xrange, yrange);
u1 = ifftshift(u1); % Quadrant shift to put 0 frequency at the corners
u2 = ifftshift(u2);
radius = sqrt(u1.^2 + u2.^2); % Matrix values contain frequency
% values as a radius from centre
% (but quadrant shifted)
% Get rid of the 0 radius value in the middle (at top left corner after
% fftshifting) so that taking the log of the radius, or dividing by the
% radius, will not cause trouble.
radius(1,1) = 1;
% Construct the monogenic filters in the frequency domain. The two
% filters would normally be constructed as follows
% H1 = i*u1./radius;
% H2 = i*u2./radius;
% However the two filters can be packed together as a complex valued
% matrix, one in the real part and one in the imaginary part. Do this by
% multiplying H2 by i and then adding it to H1 (note the subtraction
% because i*i = -1). When the convolution is performed via the fft the
% real part of the result will correspond to the convolution with H1 and
% the imaginary part with H2. This allows the two convolutions to be
% done as one in the frequency domain, saving time and memory.
H = (i*u1 - u2)./radius;
% The two monogenic filters H1 and H2 are not selective in terms of the
% magnitudes of the frequencies. The code below generates bandpass
% log-Gabor filters which are point-wise multiplied by IM to produce
% different bandpass versions of the image before being convolved with H1
% and H2
% First construct a low-pass filter that is as large as possible, yet falls
% away to zero at the boundaries. All filters are multiplied by
% this to ensure no extra frequencies at the 'corners' of the FFT are
% incorporated as this can upset the normalisation process when
% calculating phase symmetry
lp = lowpassfilter([rows,cols],.4,10); % Radius .4, 'sharpness' 10
for s = 1:nscale
wavelength = minWaveLength*mult^(s-1);
fo = 1.0/wavelength; % Centre frequency of filter.
logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2));
logGabor = logGabor.*lp; % Apply low-pass filter
logGabor(1,1) = 0; % Set the value at the 0 frequency point of the filter
% back to zero (undo the radius fudge).
IMF = IM.*logGabor; % Bandpassed image in the frequency domain
f = real(ifft2(IMF)); % Bandpassed image in spatial domain
h = ifft2(IMF.*H); % Bandpassed monogenic filtering, real part of h contains
% convolution result with h1, imaginary part
% contains convolution result with h2.
hAmp2 = real(h).^2 + imag(h).^2; % Squared amplitude of h1 h2 filter results
sumAn = sumAn + sqrt(f.^2 + hAmp2); % Magnitude of Energy.
% Now calculate the phase symmetry measure.
if polarity == 0 % look for 'white' and 'black' spots
symmetryEnergy = symmetryEnergy + abs(f) - sqrt(hAmp2);
elseif polarity == 1 % Just look for 'white' spots
symmetryEnergy = symmetryEnergy + f - sqrt(hAmp2);
elseif polarity == -1 % Just look for 'black' spots
symmetryEnergy = symmetryEnergy - f - sqrt(hAmp2);
end
% At the smallest scale estimate noise characteristics from the
% distribution of the filter amplitude responses stored in sumAn.
% tau is the Rayleigh parameter that is used to specify the
% distribution.
if s == 1
if noiseMethod == -1 % Use median to estimate noise statistics
tau = median(sumAn(:))/sqrt(log(4));
elseif noiseMethod == -2 % Use mode to estimate noise statistics
tau = rayleighmode(sumAn(:));
end
end
end % For each scale
% Compensate for noise
%
% Assuming the noise is Gaussian the response of the filters to noise will
% form Rayleigh distribution. We use the filter responses at the smallest
% scale as a guide to the underlying noise level because the smallest scale
% filters spend most of their time responding to noise, and only
% occasionally responding to features. Either the median, or the mode, of
% the distribution of filter responses can be used as a robust statistic to
% estimate the distribution mean and standard deviation as these are related
% to the median or mode by fixed constants. The response of the larger
% scale filters to noise can then be estimated from the smallest scale
% filter response according to their relative bandwidths.
%
% This code assumes that the expected reponse to noise on the phase symmetry
% calculation is simply the sum of the expected noise responses of each of
% the filters. This is a simplistic overestimate, however these two
% quantities should be related by some constant that will depend on the
% filter bank being used. Appropriate tuning of the parameter 'k' will
% allow you to produce the desired output. (though the value of k seems to
% be not at all critical)
if noiseMethod >= 0 % We are using a fixed noise threshold
T = noiseMethod; % use supplied noiseMethod value as the threshold
else
% Estimate the effect of noise on the sum of the filter responses as
% the sum of estimated individual responses (this is a simplistic
% overestimate). As the estimated noise response at succesive scales
% is scaled inversely proportional to bandwidth we have a simple
% geometric sum.
totalTau = tau * (1 - (1/mult)^nscale)/(1-(1/mult));
% Calculate mean and std dev from tau using fixed relationship
% between these parameters and tau. See
% http://mathworld.wolfram.com/RayleighDistribution.html
EstNoiseEnergyMean = totalTau*sqrt(pi/2); % Expected mean and std
EstNoiseEnergySigma = totalTau*sqrt((4-pi)/2); % values of noise energy
% Noise threshold, make sure it is not less than epsilon
T = max(EstNoiseEnergyMean + k*EstNoiseEnergySigma, epsilon);
end
% Apply noise threshold - effectively wavelet denoising soft thresholding
% and normalize symmetryEnergy by the sumAn to obtain phase symmetry.
% Note the max operation is not necessary if you are after speed, it is
% just 'tidy' not having -ve symmetry values
phaseSym = max(symmetryEnergy-T, zero) ./ (sumAn + epsilon);
%------------------------------------------------------------------
% CHECKARGS
%
% Function to process the arguments that have been supplied, assign
% default values as needed and perform basic checks.
function [im, nscale, minWaveLength, mult, sigmaOnf, ...
k, polarity, noiseMethod] = checkargs(arg)
nargs = length(arg);
if nargs < 1
error('No image supplied as an argument');
end
% Set up default values for all arguments and then overwrite them
% with with any new values that may be supplied
im = [];
nscale = 5; % Number of wavelet scales.
minWaveLength = 3; % Wavelength of smallest scale filter.
mult = 2.1; % Scaling factor between successive filters.
sigmaOnf = 0.55; % Ratio of the standard deviation of the
% Gaussian describing the log Gabor filter's
% transfer function in the frequency domain
% to the filter center frequency.
k = 2.0; % No of standard deviations of the noise
% energy beyond the mean at which we set the
% noise threshold point.
polarity = 0; % Look for both black and white spots of symmetry
noiseMethod = -1; % Use the median response of smallest scale
% filter to estimate noise statistics
% Allowed argument reading states
allnumeric = 1; % Numeric argument values in predefined order
keywordvalue = 2; % Arguments in the form of string keyword
% followed by numeric value
readstate = allnumeric; % Start in the allnumeric state
if readstate == allnumeric
for n = 1:nargs
if isa(arg{n},'char')
readstate = keywordvalue;
break;
else
if n == 1, im = arg{n};
elseif n == 2, nscale = arg{n};
elseif n == 3, minWaveLength = arg{n};
elseif n == 4, mult = arg{n};
elseif n == 5, sigmaOnf = arg{n};
elseif n == 6, k = arg{n};
elseif n == 7, polarity = arg{n};
elseif n == 8, noiseMethod = arg{n};
end
end
end
end
% Code to handle parameter name - value pairs
if readstate == keywordvalue
while n < nargs
if ~isa(arg{n},'char') || ~isa(arg{n+1}, 'double')
error('There should be a parameter name - value pair');
end
if strncmpi(arg{n},'im' ,2), im = arg{n+1};
elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1};
elseif strncmpi(arg{n},'minWaveLength',2), minWaveLength = arg{n+1};
elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1};
elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1};
elseif strncmpi(arg{n},'k' ,1), k = arg{n+1};
elseif strncmpi(arg{n},'polarity',2), polarity = arg{n+1};
elseif strncmpi(arg{n},'noisemethod',3), noiseMethod = arg{n+1};
else error('Unrecognised parameter name');
end
n = n+2;
if n == nargs
error('Unmatched parameter name - value pair');
end
end
end
if isempty(im)
error('No image argument supplied');
end
if ~isa(im, 'double')
im = double(im);
end
if nscale < 1
error('nscale must be an integer >= 1');
end
if minWaveLength < 2
error('It makes little sense to have a wavelength < 2');
end
if polarity ~= -1 && polarity ~= 0 && polarity ~= 1
error('Allowed polarity values are -1, 0 and 1')
end
%-------------------------------------------------------------------------
% RAYLEIGHMODE
%
% Computes mode of a vector/matrix of data that is assumed to come from a
% Rayleigh distribution.
%
% Usage: rmode = rayleighmode(data, nbins)
%
% Arguments: data - data assumed to come from a Rayleigh distribution
% nbins - Optional number of bins to use when forming histogram
% of the data to determine the mode.
%
% Mode is computed by forming a histogram of the data over 50 bins and then
% finding the maximum value in the histogram. Mean and standard deviation
% can then be calculated from the mode as they are related by fixed
% constants.
%
% mean = mode * sqrt(pi/2)
% std dev = mode * sqrt((4-pi)/2)
%
% See
% http://mathworld.wolfram.com/RayleighDistribution.html
% http://en.wikipedia.org/wiki/Rayleigh_distribution
%
function rmode = rayleighmode(data, nbins)
if nargin == 1
nbins = 50; % Default number of histogram bins to use
end
mx = max(data(:));
edges = 0:mx/nbins:mx;
n = histc(data(:),edges);
[dum,ind] = max(n); % Find maximum and index of maximum in histogram
rmode = (edges(ind)+edges(ind+1))/2;
|
github
|
jacksky64/imageProcessing-master
|
phasecong2.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/phasecong2.m
| 22,754 |
utf_8
|
4c97e691728c820aefd65a29a31d6dc5
|
% PHASECONG2 - Computes edge and corner phase congruency in an image.
%
% This function calculates the PC_2 measure of phase congruency.
% This function supersedes PHASECONG
%
% There are potentially many arguments, here is the full usage:
%
% [M m or ft pc EO] = phasecong2(im, nscale, norient, minWaveLength, ...
% mult, sigmaOnf, dThetaOnSigma, k, cutOff, g)
%
% However, apart from the image, all parameters have defaults and the
% usage can be as simple as:
%
% M = phasecong2(im);
%
% Arguments:
% Default values Description
%
% nscale 4 - Number of wavelet scales, try values 3-6
% norient 6 - Number of filter orientations.
% minWaveLength 3 - Wavelength of smallest scale filter.
% mult 2.1 - Scaling factor between successive filters.
% sigmaOnf 0.55 - Ratio of the standard deviation of the Gaussian
% describing the log Gabor filter's transfer function
% in the frequency domain to the filter center frequency.
% dThetaOnSigma 1.2 - Ratio of angular interval between filter orientations
% and the standard deviation of the angular Gaussian
% function used to construct filters in the
% freq. plane.
% k 2.0 - No of standard deviations of the noise energy beyond
% the mean at which we set the noise threshold point.
% You may want to vary this up to a value of 10 or
% 20 for noisy images
% cutOff 0.5 - The fractional measure of frequency spread
% below which phase congruency values get penalized.
% g 10 - Controls the sharpness of the transition in
% the sigmoid function used to weight phase
% congruency for frequency spread.
%
% Returned values:
% M - Maximum moment of phase congruency covariance.
% This is used as a indicator of edge strength.
% m - Minimum moment of phase congruency covariance.
% This is used as a indicator of corner strength.
% or - Orientation image in integer degrees 0-180,
% positive anticlockwise.
% 0 corresponds to a vertical edge, 90 is horizontal.
% ft - *Not correctly implemented at this stage*
% A complex valued image giving the weighted mean
% phase angle at every point in the image for each
% orientation.
% pc - Cell array of phase congruency images (values between 0 and 1)
% for each orientation
% EO - A 2D cell array of complex valued convolution results
%
% EO{s,o} = convolution result for scale s and orientation o. The real part
% is the result of convolving with the even symmetric filter, the imaginary
% part is the result from convolution with the odd symmetric filter.
%
% Hence:
% abs(EO{s,o}) returns the magnitude of the convolution over the
% image at scale s and orientation o.
% angle(EO{s,o}) returns the phase angles.
%
% Notes on specifying parameters:
%
% The parameters can be specified as a full list eg.
% >> [M m or ft pc EO] = phasecong2(im, 5, 6, 3, 2.5, 0.55, 1.2, 2.0, 0.4, 10);
%
% or as a partial list with unspecified parameters taking on default values
% >> [M m or ft pc EO] = phasecong2(im, 5, 6, 3);
%
% or as a partial list of parameters followed by some parameters specified via a
% keyword-value pair, remaining parameters are set to defaults, for example:
% >> [M m or ft pc EO] = phasecong2(im, 5, 6, 3, 'cutOff', 0.3, 'k', 2.5);
%
% The convolutions are done via the FFT. Many of the parameters relate to the
% specification of the filters in the frequency plane. The values do not seem
% to be very critical and the defaults are usually fine. You may want to
% experiment with the values of 'nscales' and 'k', the noise compensation factor.
%
% Notes on filter settings to obtain even coverage of the spectrum
% dthetaOnSigma 1.2 norient 6
% sigmaOnf .85 mult 1.3
% sigmaOnf .75 mult 1.6 (filter bandwidth ~1 octave)
% sigmaOnf .65 mult 2.1
% sigmaOnf .55 mult 3 (filter bandwidth ~2 octaves)
%
% For maximum speed the input image should have dimensions that correspond to
% powers of 2, but the code will operate on images of arbitrary size.
%
% See Also: PHASECONG, PHASESYM, GABORCONVOLVE, PLOTGABORFILTERS
% References:
%
% Peter Kovesi, "Image Features From Phase Congruency". Videre: A
% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,
% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html
%
% Peter Kovesi, "Phase Congruency Detects Corners and
% Edges". Proceedings DICTA 2003, Sydney Dec 10-12
% April 1996 Original Version written
% August 1998 Noise compensation corrected.
% October 1998 Noise compensation corrected. - Again!!!
% September 1999 Modified to operate on non-square images of arbitrary size.
% May 2001 Modified to return feature type image.
% July 2003 Altered to calculate 'corner' points.
% October 2003 Speed improvements and refinements.
% July 2005 Better argument handling, changed order of return values
% August 2005 Made Octave compatible
% May 2006 Bug in checkargs fixed
% Jan 2007 Bug in setting radius to 0 for odd sized images fixed.
% April 2009 Scaling of covariance values fixed. (Negligible change to results)
% Copyright (c) 1996-2009 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.
function [M, m, or, featType, PC, EO]=phasecong2(varargin)
% Get arguments and/or default values
[im, nscale, norient, minWaveLength, mult, sigmaOnf, ...
dThetaOnSigma,k, cutOff, g] = checkargs(varargin(:));
epsilon = .0001; % Used to prevent division by zero.
thetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the
% angular Gaussian function used to
% construct filters in the freq. plane.
[rows,cols] = size(im);
imagefft = fft2(im); % Fourier transform of image
zero = zeros(rows,cols);
totalEnergy = zero; % Total weighted phase congruency values (energy).
totalSumAn = zero; % Total filter response amplitude values.
orientation = zero; % Matrix storing orientation with greatest
% energy for each pixel.
EO = cell(nscale, norient); % Array of convolution results.
covx2 = zero; % Matrices for covariance data
covy2 = zero;
covxy = zero;
estMeanE2n = [];
ifftFilterArray = cell(1,nscale); % Array of inverse FFTs of filters
% Pre-compute some stuff to speed up filter construction
% 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); % Matrix values contain *normalised* radius from centre.
theta = atan2(-y,x); % Matrix values contain polar angle.
% (note -ve y is used to give +ve
% anti-clockwise angles)
radius = ifftshift(radius); % Quadrant shift radius and theta so that filters
theta = ifftshift(theta); % are constructed with 0 frequency at the corners.
radius(1,1) = 1; % Get rid of the 0 radius value at the 0
% frequency point (now at top-left corner)
% so that taking the log of the radius will
% not cause trouble.
sintheta = sin(theta);
costheta = cos(theta);
clear x; clear y; clear theta; % save a little memory
% Filters are constructed in terms of two components.
% 1) The radial component, which controls the frequency band that the filter
% responds to
% 2) The angular component, which controls the orientation that the filter
% responds to.
% The two components are multiplied together to construct the overall filter.
% Construct the radial filter components...
% First construct a low-pass filter that is as large as possible, yet falls
% away to zero at the boundaries. All log Gabor filters are multiplied by
% this to ensure no extra frequencies at the 'corners' of the FFT are
% incorporated as this seems to upset the normalisation process when
% calculating phase congrunecy.
lp = lowpassfilter([rows,cols],.45,15); % Radius .45, 'sharpness' 15
logGabor = cell(1,nscale);
for s = 1:nscale
wavelength = minWaveLength*mult^(s-1);
fo = 1.0/wavelength; % Centre frequency of filter.
logGabor{s} = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2));
logGabor{s} = logGabor{s}.*lp; % Apply low-pass filter
logGabor{s}(1,1) = 0; % Set the value at the 0 frequency point of the filter
% back to zero (undo the radius fudge).
end
% Then construct the angular filter components...
spread = cell(1,norient);
for o = 1:norient
angl = (o-1)*pi/norient; % Filter angle.
% For each point in the filter matrix calculate the angular distance from
% the specified filter orientation. To overcome the angular wrap-around
% problem sine difference and cosine difference values are first computed
% and then the atan2 function is used to determine angular distance.
ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.
dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.
dtheta = abs(atan2(ds,dc)); % Absolute angular distance.
spread{o} = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the
% angular filter component.
end
% The main loop...
for o = 1:norient % For each orientation.
% fprintf('Processing orientation %d\r',o);
angl = (o-1)*pi/norient; % Filter angle.
sumE_ThisOrient = zero; % Initialize accumulator matrices.
sumO_ThisOrient = zero;
sumAn_ThisOrient = zero;
Energy = zero;
for s = 1:nscale, % For each scale.
filter = logGabor{s} .* spread{o}; % Multiply radial and angular
% components to get the filter.
% if o == 1 % accumulate filter info for noise compensation (nominally the same
% for all orientations, hence it is only done once)
ifftFilt = real(ifft2(filter))*sqrt(rows*cols); % Note rescaling to match power
ifftFilterArray{s} = ifftFilt; % record ifft2 of filter
% end
% Convolve image with even and odd filters returning the result in EO
EO{s,o} = ifft2(imagefft .* filter);
An = abs(EO{s,o}); % Amplitude of even & odd filter response.
sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses.
sumE_ThisOrient = sumE_ThisOrient + real(EO{s,o}); % Sum of even filter convolution results.
sumO_ThisOrient = sumO_ThisOrient + imag(EO{s,o}); % Sum of odd filter convolution results.
if s==1 % Record mean squared filter value at smallest
EM_n = sum(sum(filter.^2)); % scale. This is used for noise estimation.
maxAn = An; % Record the maximum An over all scales.
else
maxAn = max(maxAn, An);
end
end % ... and process the next scale
% Get weighted mean filter response vector, this gives the weighted mean
% phase angle.
XEnergy = sqrt(sumE_ThisOrient.^2 + sumO_ThisOrient.^2) + epsilon;
MeanE = sumE_ThisOrient ./ XEnergy;
MeanO = sumO_ThisOrient ./ XEnergy;
% Now calculate An(cos(phase_deviation) - | sin(phase_deviation)) | by
% using dot and cross products between the weighted mean filter response
% vector and the individual filter response vectors at each scale. This
% quantity is phase congruency multiplied by An, which we call energy.
for s = 1:nscale,
E = real(EO{s,o}); O = imag(EO{s,o}); % Extract even and odd
% convolution results.
Energy = Energy + E.*MeanE + O.*MeanO - abs(E.*MeanO - O.*MeanE);
end
% Compensate for noise
% We estimate the noise power from the energy squared response at the
% smallest scale. If the noise is Gaussian the energy squared will have a
% Chi-squared 2DOF pdf. We calculate the median energy squared response
% as this is a robust statistic. From this we estimate the mean.
% The estimate of noise power is obtained by dividing the mean squared
% energy value by the mean squared filter value
medianE2n = median(reshape(abs(EO{1,o}).^2,1,rows*cols));
meanE2n = -medianE2n/log(0.5);
estMeanE2n(o) = meanE2n;
noisePower = meanE2n/EM_n; % Estimate of noise power.
% if o == 1
% Now estimate the total energy^2 due to noise
% Estimate for sum(An^2) + sum(Ai.*Aj.*(cphi.*cphj + sphi.*sphj))
EstSumAn2 = zero;
for s = 1:nscale
EstSumAn2 = EstSumAn2 + ifftFilterArray{s}.^2;
end
EstSumAiAj = zero;
for si = 1:(nscale-1)
for sj = (si+1):nscale
EstSumAiAj = EstSumAiAj + ifftFilterArray{si}.*ifftFilterArray{sj};
end
end
sumEstSumAn2 = sum(sum(EstSumAn2));
sumEstSumAiAj = sum(sum(EstSumAiAj));
% end % if o == 1
EstNoiseEnergy2 = 2*noisePower*sumEstSumAn2 + 4*noisePower*sumEstSumAiAj;
tau = sqrt(EstNoiseEnergy2/2); % Rayleigh parameter
EstNoiseEnergy = tau*sqrt(pi/2); % Expected value of noise energy
EstNoiseEnergySigma = sqrt( (2-pi/2)*tau^2 );
T = EstNoiseEnergy + k*EstNoiseEnergySigma; % Noise threshold
% The estimated noise effect calculated above is only valid for the PC_1 measure.
% The PC_2 measure does not lend itself readily to the same analysis. However
% empirically it seems that the noise effect is overestimated roughly by a factor
% of 1.7 for the filter parameters used here.
T = T/1.7; % Empirical rescaling of the estimated noise effect to
% suit the PC_2 phase congruency measure
Energy = max(Energy - T, zero); % Apply noise threshold
% Form weighting that penalizes frequency distributions that are
% particularly narrow. Calculate fractional 'width' of the frequencies
% present by taking the sum of the filter response amplitudes and dividing
% by the maximum amplitude at each point on the image.
width = sumAn_ThisOrient ./ (maxAn + epsilon) / nscale;
% Now calculate the sigmoidal weighting function for this orientation.
weight = 1.0 ./ (1 + exp( (cutOff - width)*g));
% Apply weighting to energy and then calculate phase congruency
PC{o} = weight.*Energy./sumAn_ThisOrient; % Phase congruency for this orientation
featType{o} = E+i*O;
% Build up covariance data for every point
covx = PC{o}*cos(angl);
covy = PC{o}*sin(angl);
covx2 = covx2 + covx.^2;
covy2 = covy2 + covy.^2;
covxy = covxy + covx.*covy;
end % For each orientation
fprintf(' \r');
% Edge and Corner calculations
% The following is optimised code to calculate principal vector
% of the phase congruency covariance data and to calculate
% the minimumum and maximum moments - these correspond to
% the singular values.
% First normalise covariance values by the number of orientations/2
covx2 = covx2/(norient/2);
covy2 = covy2/(norient/2);
covxy = 4*covxy/norient; % This gives us 2*covxy/(norient/2)
denom = sqrt(covxy.^2 + (covx2-covy2).^2)+epsilon;
sin2theta = covxy./denom;
cos2theta = (covx2-covy2)./denom;
or = atan2(sin2theta,cos2theta)/2; % Orientation perpendicular to edge.
or = round(or*180/pi); % Return result rounded to integer
% degrees.
neg = or < 0;
or = ~neg.*or + neg.*(or+180); % Adjust range from -90 to 90
% to 0 to 180.
M = (covy2+covx2 + denom)/2; % Maximum moment
m = (covy2+covx2 - denom)/2; % ... and minimum moment
%------------------------------------------------------------------
% CHECKARGS
%
% Function to process the arguments that have been supplied, assign
% default values as needed and perform basic checks.
function [im, nscale, norient, minWaveLength, mult, sigmaOnf, ...
dThetaOnSigma,k, cutOff, g] = checkargs(arg);
nargs = length(arg);
if nargs < 1
error('No image supplied as an argument');
end
% Set up default values for all arguments and then overwrite them
% with with any new values that may be supplied
im = [];
nscale = 4; % Number of wavelet scales.
norient = 6; % Number of filter orientations.
minWaveLength = 3; % Wavelength of smallest scale filter.
mult = 2.1; % Scaling factor between successive filters.
sigmaOnf = 0.55; % Ratio of the standard deviation of the
% Gaussian describing the log Gabor filter's
% transfer function in the frequency domain
% to the filter center frequency.
dThetaOnSigma = 1.5; % Ratio of angular interval between filter orientations
% and the standard deviation of the angular Gaussian
% function used to construct filters in the
% freq. plane.
k = 2.0; % No of standard deviations of the noise
% energy beyond the mean at which we set the
% noise threshold point.
cutOff = 0.5; % The fractional measure of frequency spread
% below which phase congruency values get penalized.
g = 10; % Controls the sharpness of the transition in
% the sigmoid function used to weight phase
% congruency for frequency spread.
% Allowed argument reading states
allnumeric = 1; % Numeric argument values in predefined order
keywordvalue = 2; % Arguments in the form of string keyword
% followed by numeric value
readstate = allnumeric; % Start in the allnumeric state
if readstate == allnumeric
for n = 1:nargs
if isa(arg{n},'char')
readstate = keywordvalue;
break;
else
if n == 1, im = arg{n};
elseif n == 2, nscale = arg{n};
elseif n == 3, norient = arg{n};
elseif n == 4, minWaveLength = arg{n};
elseif n == 5, mult = arg{n};
elseif n == 6, sigmaOnf = arg{n};
elseif n == 7, dThetaOnSigma = arg{n};
elseif n == 8, k = arg{n};
elseif n == 9, cutOff = arg{n};
elseif n == 10,g = arg{n};
end
end
end
end
% Code to handle parameter name - value pairs
if readstate == keywordvalue
while n < nargs
if ~isa(arg{n},'char') || ~isa(arg{n+1}, 'double')
error('There should be a parameter name - value pair');
end
if strncmpi(arg{n},'im' ,2), im = arg{n+1};
elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1};
elseif strncmpi(arg{n},'norient' ,2), norient = arg{n+1};
elseif strncmpi(arg{n},'minWaveLength',2), minWaveLength = arg{n+1};
elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1};
elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1};
elseif strncmpi(arg{n},'dThetaOnSigma',2), dThetaOnSigma = arg{n+1};
elseif strncmpi(arg{n},'k' ,1), k = arg{n+1};
elseif strncmpi(arg{n},'cutOff' ,2), cutOff = arg{n+1};
elseif strncmpi(arg{n},'g' ,1), g = arg{n+1};
else error('Unrecognised parameter name');
end
n = n+2;
if n == nargs
error('Unmatched parameter name - value pair');
end
end
end
if isempty(im)
error('No image argument supplied');
end
if ~isa(im, 'double')
im = double(im);
end
if nscale < 1
error('nscale must be an integer >= 1');
end
if norient < 1
error('norient must be an integer >= 1');
end
if minWaveLength < 2
error('It makes little sense to have a wavelength < 2');
end
if cutOff < 0 || cutOff > 1
error('Cut off value must be between 0 and 1');
end
|
github
|
jacksky64/imageProcessing-master
|
phasecong3.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/phasecong3.m
| 26,465 |
utf_8
|
0c014f3a3af8bd7658da095b5c402b61
|
% PHASECONG3 - Computes edge and corner phase congruency in an image.
%
% This function calculates the PC_2 measure of phase congruency.
% This function supersedes PHASECONG2 and PHASECONG being faster and requires
% less memory
%
% There are potentially many arguments, here is the full usage:
%
% [M m or ft pc EO, T] = phasecong3(im, nscale, norient, minWaveLength, ...
% mult, sigmaOnf, k, cutOff, g, noiseMethod)
%
% However, apart from the image, all parameters have defaults and the
% usage can be as simple as:
%
% M = phasecong3(im);
%
% Arguments:
% Default values Description
%
% nscale 4 - Number of wavelet scales, try values 3-6
% norient 6 - Number of filter orientations.
% minWaveLength 3 - Wavelength of smallest scale filter.
% mult 2.1 - Scaling factor between successive filters.
% sigmaOnf 0.55 - Ratio of the standard deviation of the Gaussian
% describing the log Gabor filter's transfer function
% in the frequency domain to the filter center frequency.
% k 2.0 - No of standard deviations of the noise energy beyond
% the mean at which we set the noise threshold point.
% You may want to vary this up to a value of 10 or
% 20 for noisy images
% cutOff 0.5 - The fractional measure of frequency spread
% below which phase congruency values get penalized.
% g 10 - Controls the sharpness of the transition in
% the sigmoid function used to weight phase
% congruency for frequency spread.
% noiseMethod -1 - Parameter specifies method used to determine
% noise statistics.
% -1 use median of smallest scale filter responses
% -2 use mode of smallest scale filter responses
% 0+ use noiseMethod value as the fixed noise threshold
%
% Returned values:
% M - Maximum moment of phase congruency covariance.
% This is used as a indicator of edge strength.
% m - Minimum moment of phase congruency covariance.
% This is used as a indicator of corner strength.
% or - Orientation image in integer degrees 0-180,
% positive anticlockwise.
% 0 corresponds to a vertical edge, 90 is horizontal.
% ft - Local weighted mean phase angle at every point in the
% image. A value of pi/2 corresponds to a bright line, 0
% corresponds to a step and -pi/2 is a dark line.
% pc - Cell array of phase congruency images (values between 0 and 1)
% for each orientation
% EO - A 2D cell array of complex valued convolution result
% T - Calculated noise threshold (can be useful for
% diagnosing noise characteristics of images). Once you know
% this you can then specify fixed thresholds and save some
% computation time.
%
% EO{s,o} = convolution result for scale s and orientation o. The real part
% is the result of convolving with the even symmetric filter, the imaginary
% part is the result from convolution with the odd symmetric filter.
%
% Hence:
% abs(EO{s,o}) returns the magnitude of the convolution over the
% image at scale s and orientation o.
% angle(EO{s,o}) returns the phase angles.
%
% Notes on specifying parameters:
%
% The parameters can be specified as a full list eg.
% >> [M m or ft pc EO] = phasecong3(im, 5, 6, 3, 2.5, 0.55, 2.0, 0.4, 10);
%
% or as a partial list with unspecified parameters taking on default values
% >> [M m or ft pc EO] = phasecong3(im, 5, 6, 3);
%
% or as a partial list of parameters followed by some parameters specified via a
% keyword-value pair, remaining parameters are set to defaults, for example:
% >> [M m or ft pc EO] = phasecong3(im, 5, 6, 3, 'cutOff', 0.3, 'k', 2.5);
%
% The convolutions are done via the FFT. Many of the parameters relate to the
% specification of the filters in the frequency plane. The values do not seem
% to be very critical and the defaults are usually fine. You may want to
% experiment with the values of 'nscales' and 'k', the noise compensation factor.
%
% Notes on filter settings to obtain even coverage of the spectrum
% sigmaOnf .85 mult 1.3
% sigmaOnf .75 mult 1.6 (filter bandwidth ~1 octave)
% sigmaOnf .65 mult 2.1
% sigmaOnf .55 mult 3 (filter bandwidth ~2 octaves)
%
% See Also: PHASECONG, PHASECONG2, PHASESYM, GABORCONVOLVE, PLOTGABORFILTERS
% References:
%
% Peter Kovesi, "Image Features From Phase Congruency". Videre: A
% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,
% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html
%
% Peter Kovesi, "Phase Congruency Detects Corners and
% Edges". Proceedings DICTA 2003, Sydney Dec 10-12
% April 1996 Original Version written
% August 1998 Noise compensation corrected.
% October 1998 Noise compensation corrected. - Again!!!
% September 1999 Modified to operate on non-square images of arbitrary size.
% May 2001 Modified to return feature type image.
% July 2003 Altered to calculate 'corner' points.
% October 2003 Speed improvements and refinements.
% July 2005 Better argument handling, changed order of return values
% August 2005 Made Octave compatible
% May 2006 Bug in checkargs fixed
% Jan 2007 Bug in setting radius to 0 for odd sized images fixed.
% April 2009 Scaling of covariance values fixed. (Negligible change to results)
% May 2009 Noise compensation simplified reducing memory and
% computation overhead. Spread function changed to a cosine,
% eliminating parameter dThetaOnSigma and ensuring even
% angular coverage. Frequency width measure slightly
% improved.
% November 2010 Cosine angular spread function corrected (it was 2x as wide
% as it should have been)
% Copyright (c) 1996-2010 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.
function [M, m, or, featType, PC, EO, T, pcSum] = phasecong3(varargin)
% Get arguments and/or default values
[im, nscale, norient, minWaveLength, mult, sigmaOnf, ...
k, cutOff, g, noiseMethod] = checkargs(varargin(:));
epsilon = .0001; % Used to prevent division by zero.
[rows,cols] = size(im);
imagefft = fft2(im); % Fourier transform of image
zero = zeros(rows,cols);
EO = cell(nscale, norient); % Array of convolution results.
PC = cell(norient,1);
covx2 = zero; % Matrices for covariance data
covy2 = zero;
covxy = zero;
EnergyV = zeros(rows,cols,3); % Matrix for accumulating total energy
% vector, used for feature orientation
% and type calculation
pcSum = zeros(rows,cols);
% Pre-compute some stuff to speed up filter construction
% 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); % Matrix values contain *normalised* radius from centre.
theta = atan2(-y,x); % Matrix values contain polar angle.
% (note -ve y is used to give +ve
% anti-clockwise angles)
radius = ifftshift(radius); % Quadrant shift radius and theta so that filters
theta = ifftshift(theta); % are constructed with 0 frequency at the corners.
radius(1,1) = 1; % Get rid of the 0 radius value at the 0
% frequency point (now at top-left corner)
% so that taking the log of the radius will
% not cause trouble.
sintheta = sin(theta);
costheta = cos(theta);
clear x; clear y; clear theta; % save a little memory
% Filters are constructed in terms of two components.
% 1) The radial component, which controls the frequency band that the filter
% responds to
% 2) The angular component, which controls the orientation that the filter
% responds to.
% The two components are multiplied together to construct the overall filter.
% Construct the radial filter components...
% First construct a low-pass filter that is as large as possible, yet falls
% away to zero at the boundaries. All log Gabor filters are multiplied by
% this to ensure no extra frequencies at the 'corners' of the FFT are
% incorporated as this seems to upset the normalisation process when
% calculating phase congrunecy.
lp = lowpassfilter([rows,cols],.45,15); % Radius .45, 'sharpness' 15
logGabor = cell(1,nscale);
for s = 1:nscale
wavelength = minWaveLength*mult^(s-1);
fo = 1.0/wavelength; % Centre frequency of filter.
logGabor{s} = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2));
logGabor{s} = logGabor{s}.*lp; % Apply low-pass filter
logGabor{s}(1,1) = 0; % Set the value at the 0 frequency point of the filter
% back to zero (undo the radius fudge).
end
%% The main loop...
for o = 1:norient % For each orientation...
% Construct the angular filter spread function
angl = (o-1)*pi/norient; % Filter angle.
% For each point in the filter matrix calculate the angular distance from
% the specified filter orientation. To overcome the angular wrap-around
% problem sine difference and cosine difference values are first computed
% and then the atan2 function is used to determine angular distance.
ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.
dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.
dtheta = abs(atan2(ds,dc)); % Absolute angular distance.
% Scale theta so that cosine spread function has the right wavelength and clamp to pi
dtheta = min(dtheta*norient/2,pi);
% The spread function is cos(dtheta) between -pi and pi. We add 1,
% and then divide by 2 so that the value ranges 0-1
spread = (cos(dtheta)+1)/2;
sumE_ThisOrient = zero; % Initialize accumulator matrices.
sumO_ThisOrient = zero;
sumAn_ThisOrient = zero;
Energy = zero;
for s = 1:nscale, % For each scale...
filter = logGabor{s} .* spread; % Multiply radial and angular
% components to get the filter.
% Convolve image with even and odd filters returning the result in EO
EO{s,o} = ifft2(imagefft .* filter);
An = abs(EO{s,o}); % Amplitude of even & odd filter response.
sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses.
sumE_ThisOrient = sumE_ThisOrient + real(EO{s,o}); % Sum of even filter convolution results.
sumO_ThisOrient = sumO_ThisOrient + imag(EO{s,o}); % Sum of odd filter convolution results.
% At the smallest scale estimate noise characteristics from the
% distribution of the filter amplitude responses stored in sumAn.
% tau is the Rayleigh parameter that is used to describe the
% distribution.
if s == 1
if noiseMethod == -1 % Use median to estimate noise statistics
tau = median(sumAn_ThisOrient(:))/sqrt(log(4));
elseif noiseMethod == -2 % Use mode to estimate noise statistics
tau = rayleighmode(sumAn_ThisOrient(:));
end
maxAn = An;
else
% Record maximum amplitude of components across scales. This is needed
% to determine the frequency spread weighting.
maxAn = max(maxAn,An);
end
end % ... and process the next scale
% Accumulate total 3D energy vector data, this will be used to
% determine overall feature orientation and feature phase/type
EnergyV(:,:,1) = EnergyV(:,:,1) + sumE_ThisOrient;
EnergyV(:,:,2) = EnergyV(:,:,2) + cos(angl)*sumO_ThisOrient;
EnergyV(:,:,3) = EnergyV(:,:,3) + sin(angl)*sumO_ThisOrient;
% Get weighted mean filter response vector, this gives the weighted mean
% phase angle.
XEnergy = sqrt(sumE_ThisOrient.^2 + sumO_ThisOrient.^2) + epsilon;
MeanE = sumE_ThisOrient ./ XEnergy;
MeanO = sumO_ThisOrient ./ XEnergy;
% Now calculate An(cos(phase_deviation) - | sin(phase_deviation)) | by
% using dot and cross products between the weighted mean filter response
% vector and the individual filter response vectors at each scale. This
% quantity is phase congruency multiplied by An, which we call energy.
for s = 1:nscale,
E = real(EO{s,o}); O = imag(EO{s,o}); % Extract even and odd
% convolution results.
Energy = Energy + E.*MeanE + O.*MeanO - abs(E.*MeanO - O.*MeanE);
end
%% Automatically determine noise threshold
%
% Assuming the noise is Gaussian the response of the filters to noise will
% form Rayleigh distribution. We use the filter responses at the smallest
% scale as a guide to the underlying noise level because the smallest scale
% filters spend most of their time responding to noise, and only
% occasionally responding to features. Either the median, or the mode, of
% the distribution of filter responses can be used as a robust statistic to
% estimate the distribution mean and standard deviation as these are related
% to the median or mode by fixed constants. The response of the larger
% scale filters to noise can then be estimated from the smallest scale
% filter response according to their relative bandwidths.
%
% This code assumes that the expected reponse to noise on the phase congruency
% calculation is simply the sum of the expected noise responses of each of
% the filters. This is a simplistic overestimate, however these two
% quantities should be related by some constant that will depend on the
% filter bank being used. Appropriate tuning of the parameter 'k' will
% allow you to produce the desired output.
if noiseMethod >= 0 % We are using a fixed noise threshold
T = noiseMethod; % use supplied noiseMethod value as the threshold
else
% Estimate the effect of noise on the sum of the filter responses as
% the sum of estimated individual responses (this is a simplistic
% overestimate). As the estimated noise response at succesive scales
% is scaled inversely proportional to bandwidth we have a simple
% geometric sum.
totalTau = tau * (1 - (1/mult)^nscale)/(1-(1/mult));
% Calculate mean and std dev from tau using fixed relationship
% between these parameters and tau. See
% http://mathworld.wolfram.com/RayleighDistribution.html
EstNoiseEnergyMean = totalTau*sqrt(pi/2); % Expected mean and std
EstNoiseEnergySigma = totalTau*sqrt((4-pi)/2); % values of noise energy
T = EstNoiseEnergyMean + k*EstNoiseEnergySigma; % Noise threshold
end
% Apply noise threshold, this is effectively wavelet denoising via
% soft thresholding.
Energy = max(Energy - T, 0);
% Form weighting that penalizes frequency distributions that are
% particularly narrow. Calculate fractional 'width' of the frequencies
% present by taking the sum of the filter response amplitudes and dividing
% by the maximum amplitude at each point on the image. If
% there is only one non-zero component width takes on a value of 0, if
% all components are equal width is 1.
width = (sumAn_ThisOrient./(maxAn + epsilon) - 1) / (nscale-1);
% Now calculate the sigmoidal weighting function for this orientation.
weight = 1.0 ./ (1 + exp( (cutOff - width)*g));
% Apply weighting to energy and then calculate phase congruency
PC{o} = weight.*Energy./sumAn_ThisOrient; % Phase congruency for this orientatio
pcSum = pcSum+PC{o};
% Build up covariance data for every point
covx = PC{o}*cos(angl);
covy = PC{o}*sin(angl);
covx2 = covx2 + covx.^2;
covy2 = covy2 + covy.^2;
covxy = covxy + covx.*covy;
end % For each orientation
%% Edge and Corner calculations
% The following is optimised code to calculate principal vector
% of the phase congruency covariance data and to calculate
% the minimumum and maximum moments - these correspond to
% the singular values.
% First normalise covariance values by the number of orientations/2
covx2 = covx2/(norient/2);
covy2 = covy2/(norient/2);
covxy = 4*covxy/norient; % This gives us 2*covxy/(norient/2)
denom = sqrt(covxy.^2 + (covx2-covy2).^2)+epsilon;
M = (covy2+covx2 + denom)/2; % Maximum moment
m = (covy2+covx2 - denom)/2; % ... and minimum moment
% Orientation and feature phase/type computation
or = atan2(EnergyV(:,:,3), EnergyV(:,:,2));
or(or<0) = or(or<0)+pi; % Wrap angles -pi..0 to 0..pi
or = round(or*180/pi); % Orientation in degrees between 0 and 180
OddV = sqrt(EnergyV(:,:,2).^2 + EnergyV(:,:,3).^2);
featType = atan2(EnergyV(:,:,1), OddV); % Feature phase pi/2 <-> white line,
% 0 <-> step, -pi/2 <-> black line
%%------------------------------------------------------------------
% CHECKARGS
%
% Function to process the arguments that have been supplied, assign
% default values as needed and perform basic checks.
function [im, nscale, norient, minWaveLength, mult, sigmaOnf, ...
k, cutOff, g, noiseMethod] = checkargs(arg)
nargs = length(arg);
if nargs < 1
error('No image supplied as an argument');
end
% Set up default values for all arguments and then overwrite them
% with with any new values that may be supplied
im = [];
nscale = 4; % Number of wavelet scales.
norient = 6; % Number of filter orientations.
minWaveLength = 3; % Wavelength of smallest scale filter.
mult = 2.1; % Scaling factor between successive filters.
sigmaOnf = 0.55; % Ratio of the standard deviation of the
% Gaussian describing the log Gabor filter's
% transfer function in the frequency domain
% to the filter center frequency.
k = 2.0; % No of standard deviations of the noise
% energy beyond the mean at which we set the
% noise threshold point.
cutOff = 0.5; % The fractional measure of frequency spread
% below which phase congruency values get penalized.
g = 10; % Controls the sharpness of the transition in
% the sigmoid function used to weight phase
% congruency for frequency spread.
noiseMethod = -1; % Choice of noise compensation method.
% Allowed argument reading states
allnumeric = 1; % Numeric argument values in predefined order
keywordvalue = 2; % Arguments in the form of string keyword
% followed by numeric value
readstate = allnumeric; % Start in the allnumeric state
if readstate == allnumeric
for n = 1:nargs
if isa(arg{n},'char')
readstate = keywordvalue;
break;
else
if n == 1, im = arg{n};
elseif n == 2, nscale = arg{n};
elseif n == 3, norient = arg{n};
elseif n == 4, minWaveLength = arg{n};
elseif n == 5, mult = arg{n};
elseif n == 6, sigmaOnf = arg{n};
elseif n == 7, k = arg{n};
elseif n == 8, cutOff = arg{n};
elseif n == 9, g = arg{n};
elseif n == 10,noiseMethod = arg{n};
end
end
end
end
% Code to handle parameter name - value pairs
if readstate == keywordvalue
while n < nargs
if ~isa(arg{n},'char') || ~isa(arg{n+1}, 'double')
error('There should be a parameter name - value pair');
end
if strncmpi(arg{n},'im' ,2), im = arg{n+1};
elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1};
elseif strncmpi(arg{n},'norient' ,4), norient = arg{n+1};
elseif strncmpi(arg{n},'minWaveLength',2), minWaveLength = arg{n+1};
elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1};
elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1};
elseif strncmpi(arg{n},'k' ,1), k = arg{n+1};
elseif strncmpi(arg{n},'cutOff' ,2), cutOff = arg{n+1};
elseif strncmpi(arg{n},'g' ,1), g = arg{n+1};
elseif strncmpi(arg{n},'noiseMethod' ,4), noiseMethod = arg{n+1};
else error('Unrecognised parameter name');
end
n = n+2;
if n == nargs
error('Unmatched parameter name - value pair');
end
end
end
if isempty(im)
error('No image argument supplied');
end
if ndims(im) == 3
warning('Colour image supplied: converting image to greyscale...')
im = double(rgb2gray(im));
end
if ~isa(im, 'double')
im = double(im);
end
if nscale < 1
error('nscale must be an integer >= 1');
end
if norient < 1
error('norient must be an integer >= 1');
end
if minWaveLength < 2
error('It makes little sense to have a wavelength < 2');
end
if cutOff < 0 || cutOff > 1
error('Cut off value must be between 0 and 1');
end
%%-------------------------------------------------------------------------
% RAYLEIGHMODE
%
% Computes mode of a vector/matrix of data that is assumed to come from a
% Rayleigh distribution.
%
% Usage: rmode = rayleighmode(data, nbins)
%
% Arguments: data - data assumed to come from a Rayleigh distribution
% nbins - Optional number of bins to use when forming histogram
% of the data to determine the mode.
%
% Mode is computed by forming a histogram of the data over 50 bins and then
% finding the maximum value in the histogram. Mean and standard deviation
% can then be calculated from the mode as they are related by fixed
% constants.
%
% mean = mode * sqrt(pi/2)
% std dev = mode * sqrt((4-pi)/2)
%
% See
% http://mathworld.wolfram.com/RayleighDistribution.html
% http://en.wikipedia.org/wiki/Rayleigh_distribution
%
function rmode = rayleighmode(data, nbins)
if nargin == 1
nbins = 50; % Default number of histogram bins to use
end
mx = max(data(:));
edges = 0:mx/nbins:mx;
n = histc(data(:),edges);
[dum,ind] = max(n); % Find maximum and index of maximum in histogram
rmode = (edges(ind)+edges(ind+1))/2;
|
github
|
jacksky64/imageProcessing-master
|
noisecomp.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/noisecomp.m
| 7,750 |
utf_8
|
9676f0608db5db81178e20d70f317783
|
% NOISECOMP - Function for denoising an image
%
% function cleanimage = noisecomp(image, k, nscale, mult, norient, softness)
%
% Parameters:
% k - No of standard deviations of noise to reject 2-3
% nscale - No of filter scales to use (5-7) - the more scales used
% the more low frequencies are covered
% mult - multiplying factor between scales (2.5-3)
% norient - No of orientations to use (6)
% softness - degree of soft thresholding (0-hard 1-soft)
%
% For maximum processing speed the input image should have a size that
% is a power of 2.
%
% The convolutions are done via the FFT. Many of the parameters relate
% to the specification of the filters in the frequency plane.
% The parameters are set within the file rather than being specified as
% arguments because they rarely need to be changed - nor are they very
% critical.
%
% Reference:
% Peter Kovesi, "Phase Preserving Denoising of Images".
% The Australian Pattern Recognition Society Conference: DICTA'99.
% December 1999. Perth WA. pp 212-217
% http://www.cs.uwa.edu.au/pub/robvis/papers/pk/denoise.ps.gz.
%
% Copyright (c) 1998-2000 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.
% September 1998 - original version
% May 1999 -
% May 2000 - modified to allow arbitrary size images
function cleanimage = noisecomp(image, k, nscale, mult, norient, softness)
%nscale = 6; % Number of wavelet scales.
%norient = 6; % Number of filter orientations.
minWaveLength = 2; % Wavelength of smallest scale filter.
%mult = 2; % Scaling factor between successive filters.
sigmaOnf = 0.55; % Ratio of the standard deviation of the Gaussian
% describing the log Gabor filter's transfer function
% in the frequency domain to the filter center frequency.
dThetaOnSigma = 1.; % Ratio of angular interval between filter orientations
% and the standard deviation of the angular Gaussian
% function used to construct filters in the freq. plane.
epsilon = .00001;% Used to prevent division by zero.
thetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the
% angular Gaussian function used to
% construct filters in the freq. plane.
imagefft = fft2(image); % Fourier transform of image
[rows,cols] = size(imagefft);
% Create two matrices, x and y. All elements of x have a value equal to its
% x coordinate relative to the centre, elements of y have values equal to
% their y coordinate relative to the centre.
x = ones(rows,1) * (-cols/2 : (cols/2 - 1))/(cols/2);
y = (-rows/2 : (rows/2 - 1))' * ones(1,cols)/(rows/2);
radius = sqrt(x.^2 + y.^2); % Matrix values contain normalised radius from centre.
radius(round(rows/2+1),round(cols/2+1)) = 1; % Get rid of the 0 radius value in the middle so that
% taking the log of the radius will not cause trouble.
theta = atan2(-y,x); % Matrix values contain polar angle.
% (note -ve y is used to give +ve anti-clockwise angles)
clear x; clear y; % save a little memory
sig = [];
estMeanEn = [];
aMean = [];
aSig = [];
totalEnergy = zeros(rows,cols); % response at each orientation.
for o = 1:norient, % For each orientation.
disp(['Processing orientation ' num2str(o)]);
angl = (o-1)*pi/norient; % Calculate filter angle.
wavelength = minWaveLength; % Initialize filter wavelength.
% Pre-compute filter data specific to this orientation
% For each point in the filter matrix calculate the angular distance from the
% specified filter orientation. To overcome the angular wrap-around problem
% sine difference and cosine difference values are first computed and then
% the atan2 function is used to determine angular distance.
ds = sin(theta) * cos(angl) - cos(theta) * sin(angl); % Difference in sine.
dc = cos(theta) * cos(angl) + sin(theta) * sin(angl); % Difference in cosine.
dtheta = abs(atan2(ds,dc)); % Absolute angular distance.
spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the angular filter component.
for s = 1:nscale, % For each scale.
% Construct the filter - first calculate the radial filter component.
fo = 1.0/wavelength; % Centre frequency of filter.
rfo = fo/0.5; % Normalised radius from centre of frequency plane
% corresponding to fo.
logGabor = exp((-(log(radius/rfo)).^2) / (2 * log(sigmaOnf)^2));
logGabor(round(rows/2+1),round(cols/2+1)) = 0; % Set the value at the center of the filter
% back to zero (undo the radius fudge).
filter = logGabor .* spread; % Multiply by the angular spread to get the filter.
filter = fftshift(filter); % Swap quadrants to move zero frequency
% to the corners.
% Convolve image with even an odd filters returning the result in EO
EOfft = imagefft .* filter; % Do the convolution.
EO = ifft2(EOfft); % Back transform.
aEO = abs(EO);
if s == 1
% Estimate the mean and variance in the amplitude response of the smallest scale
% filter pair at this orientation.
% If the noise is Gaussian the amplitude response will have a Rayleigh distribution.
% We calculate the median amplitude response as this is a robust statistic.
% From this we estimate the mean and variance of the Rayleigh distribution
medianEn = median(reshape(aEO,1,rows*cols));
meanEn = medianEn*.5*sqrt(-pi/log(0.5));
RayVar = (4-pi)*(meanEn.^2)/pi;
RayMean = meanEn;
estMeanEn = [estMeanEn meanEn];
sig = [sig sqrt(RayVar)];
%% May want to look at actual distribution on special images
% hist(reshape(aEO,1,rows*cols),100);
% pause(1);
end
% Now apply soft thresholding
T = (RayMean + k*sqrt(RayVar))/(mult^(s-1)); % Noise effect inversely proportional to
% bandwidth/centre frequency.
validEO = aEO > T; % Find where magnitude of energy exceeds noise.
V = softness*T*EO./(aEO + epsilon); % Calculate array of noise vectors to subtract.
V = ~validEO.*EO + validEO.*V; % Adjust noise vectors so that EO values will
% not be negated
EO = EO-V; % Subtract noise vector.
totalEnergy = totalEnergy + EO;
wavelength = wavelength * mult; % Wavelength of next filter
end
end % For each orientation
disp('Estimated mean noise in each orientation')
disp(estMeanEn);
cleanimage = real(totalEnergy);
%imagesc(cleanimage), title('denoised image'), axis image;
|
github
|
jacksky64/imageProcessing-master
|
loggabor.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/loggabor.m
| 1,707 |
utf_8
|
c15d2b1f67996d38d0003a5309d2f76f
|
% LOGGABOR
%
% Plots 1D log-Gabor functions
%
% Author: Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk @ csse uwa edu au http://www.csse.uwa.edu.au/~pk
function loggabor(nscale, wmin, mult, konwo)
Npts = 2048;
Nwaves = 1;
wmax = 0.5;
dw = wmax/(Npts-1);
w = [0: dw: wmax];
wo = wmin/2;
for s = 1:nscale
w(1) = 1; % fudge
Gw{s} = exp( (-(log(w/wo)).^2) ./ (2*(log(konwo)).^2) );
Gw{s}(1) = 0; % undo fudge
Wave{s} = fftshift(ifft(Gw{s}));
wavelength = 1/wo;
p = max(round(Npts/2 - Nwaves*wavelength),1);
q = min(round(Npts/2 + Nwaves*wavelength),Npts);
Wave{s} = Wave{s}(p:q);
wo = wo*mult;
end
w(1) = 0; % undo fudge
lw = 2; % linewidth
fs = 14; % font size
figure(1), clf
for s = 1:nscale
subplot(2,1,1), plot(w, Gw{s},'LineWidth',lw),
axis([0 0.5 0 1.1]), hold on
subplot(2,1,2), semilogx(w, Gw{s},'LineWidth',lw), axis([0 0.5 0 1.1]), hold on
end
subplot(2,1,1), title('Log-Gabor Transfer Functions','FontSize',fs);
xlabel('frequency','FontSize',fs)
subplot(2,1,2), xlabel('log frequency','FontSize',fs)
ymax = 1.05*max(abs(Wave{nscale}));
figure(2), clf
for s = 1:nscale
subplot(2,nscale,s), plot(real(Wave{s}),'LineWidth',lw),
axis([0 length(Wave{s}) -ymax ymax]), axis off
subplot(2,nscale,s+nscale), plot(imag(Wave{s}),'LineWidth',lw),
axis([0 length(Wave{s}) -ymax ymax]), axis off
end
subplot(2,nscale,1), title('even symmetric wavelets','FontSize',fs);
subplot(2,nscale,nscale+1), title('odd symmetric wavelets','FontSize',fs);
|
github
|
jacksky64/imageProcessing-master
|
phasecongmono.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/phasecongmono.m
| 22,519 |
utf_8
|
5d0d160cd66ce1b8ed2bc3db2d332a8f
|
% PHASECONGMONO - phase congruency of an image using monogenic filters
%
% This code is considerably faster than PHASECONG3 but you may prefer the
% output from PHASECONG3's oriented filters.
%
% There are potentially many arguments, here is the full usage:
%
% [PC or ft T] = ...
% phasecongmono(im, nscale, minWaveLength, mult, ...
% sigmaOnf, k, cutOff, g, deviationGain, noiseMethod)
%
% However, apart from the image, all parameters have defaults and the
% usage can be as simple as:
%
% phaseCong = phasecongmono(im);
%
% Arguments:
% Default values Description
%
% nscale 4 - Number of wavelet scales, try values 3-6
% A lower value will reveal more fine scale
% features. A larger value will highlight 'major'
% features.
% minWaveLength 3 - Wavelength of smallest scale filter.
% mult 2.1 - Scaling factor between successive filters.
% sigmaOnf 0.55 - Ratio of the standard deviation of the Gaussian
% describing the log Gabor filter's transfer function
% in the frequency domain to the filter center frequency.
% k 3.0 - No of standard deviations of the noise energy beyond
% the mean at which we set the noise threshold point.
% You may want to vary this up to a value of 10 or
% 20 for noisy images
% cutOff 0.5 - The fractional measure of frequency spread
% below which phase congruency values get penalized.
% g 10 - Controls the sharpness of the transition in
% the sigmoid function used to weight phase
% congruency for frequency spread.
% deviationGain 1.5 - Amplification to apply to the calculated phase
% deviation result. Increasing this sharpens the
% edge responses, but can also attenuate their
% magnitude if the gain is too large. Sensible
% values to use lie in the range 1-2.
% noiseMethod -1 - Parameter specifies method used to determine
% noise statistics.
% -1 use median of smallest scale filter responses
% -2 use mode of smallest scale filter responses
% 0+ use noiseMethod value as the fixed noise threshold
% A value of 0 will turn off all noise compensation.
%
% Returned values:
% PC - Phase congruency indicating edge significance
% or - Orientation image in integer degrees 0-180,
% positive anticlockwise.
% 0 corresponds to a vertical edge, 90 is horizontal.
% ft - Local weighted mean phase angle at every point in the
% image. A value of pi/2 corresponds to a bright line, 0
% corresponds to a step and -pi/2 is a dark line.
% T - Calculated noise threshold (can be useful for
% diagnosing noise characteristics of images). Once you know
% this you can then specify fixed thresholds and save some
% computation time.
%
% Notes on specifying parameters:
%
% The parameters can be specified as a full list eg.
% >> PC = phasecongmono(im, 5, 3, 2.5, 0.55, 2.0);
%
% or as a partial list with unspecified parameters taking on default values
% >> PC = phasecongmono(im, 5, 3);
%
% or as a partial list of parameters followed by some parameters specified via a
% keyword-value pair, remaining parameters are set to defaults, for example:
% >> PC = phasecongmono(im, 5, 3, 'k', 2.5);
%
% The convolutions are done via the FFT. Many of the parameters relate to the
% specification of the filters in the frequency plane. The values do not seem
% to be very critical and the defaults are usually fine. You may want to
% experiment with the values of 'nscales' and 'k', the noise compensation
% factor.
%
% Typical sequence of operations to obtain an edge image:
%
% >> [PC, or] = phasecongmono(imread('lena.tif'));
% >> nm = nonmaxsup(PC, or, 1.5); % nonmaxima suppression
% >> bw = hysthresh(nm, 0.1, 0.3); % hysteresis thresholding 0.1 - 0.3
% >> show(bw)
%
% Notes on filter settings to obtain even coverage of the spectrum
% sigmaOnf .85 mult 1.3
% sigmaOnf .75 mult 1.6 (filter bandwidth ~1 octave)
% sigmaOnf .65 mult 2.1
% sigmaOnf .55 mult 3 (filter bandwidth ~2 octaves)
%
% Note that better results are achieved using the large bandwidth filters.
% I generally use a sigmaOnf value of 0.55 or even smaller.
%
% See Also: PHASECONG, PHASECONG3, PHASESYMMONO, GABORCONVOLVE,
% PLOTGABORFILTERS, FILTERGRID
% References:
%
% Peter Kovesi, "Image Features From Phase Congruency". Videre: A
% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,
% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html
%
% Michael Felsberg and Gerald Sommer, "A New Extension of Linear Signal
% Processing for Estimating Local Properties and Detecting Features". DAGM
% Symposium 2000, Kiel
%
% Michael Felsberg and Gerald Sommer. "The Monogenic Signal" IEEE
% Transactions on Signal Processing, 49(12):3136-3144, December 2001
%
% Peter Kovesi, "Phase Congruency Detects Corners and Edges". Proceedings
% DICTA 2003, Sydney Dec 10-12
% August 2008 Initial version developed from phasesymmono and phasecong2
% where local phase information is calculated via Monogenic
% filters. Simplification of noise compensation to speedup
% execution. Options to calculate noise statistics via median
% or mode of smallest filter response.
% April 2009 Return of T for 'instrumentation' of noise
% detection/compensation. Option to use a fixed threshold.
% Frequency width measure slightly improved.
% June 2009 20% Speed improvement through calculating phase deviation via
% acos() rather than computing cos(theta)-|sin(theta)| via dot
% and cross products. Phase congruency is formed properly in
% 2D rather than as multiple 1D computations as in
% phasecong3. Also, much smaller memory footprint.
% May 2013 Some tidying up, corrections to defualt parameters, changes
% to reflect my latest thinking of the final phase congruency
% calculation and addition of phase deviation gain parameter to
% sharpen up the output. Use of periodic fft.
% 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.
function [PC, or, ft, T] = phasecongmono(varargin)
% Get arguments and/or default values
[im, nscale, minWaveLength, mult, sigmaOnf, k, ...
noiseMethod, cutOff, g, deviationGain] = checkargs(varargin(:));
epsilon = .0001; % Used to prevent division by zero.
[rows,cols] = size(im);
IM = perfft2(im); % Periodic Fourier transform of image
sumAn = zeros(rows,cols); % Matrix for accumulating filter response
% amplitude values.
sumf = zeros(rows,cols);
sumh1 = zeros(rows,cols);
sumh2 = zeros(rows,cols);
% Generate grid data for constructing filters in the frequency domain
[radius, u1, u2] = filtergrid(rows, cols);
% Get rid of the 0 radius value in the middle (at top left corner after
% fftshifting) so that taking the log of the radius, or dividing by the
% radius, will not cause trouble.
radius(1,1) = 1;
% Construct the monogenic filters in the frequency domain. The two
% filters would normally be constructed as follows
% H1 = i*u1./radius;
% H2 = i*u2./radius;
% However the two filters can be packed together as a complex valued
% matrix, one in the real part and one in the imaginary part. Do this by
% multiplying H2 by i and then adding it to H1 (note the subtraction
% because i*i = -1). When the convolution is performed via the fft the
% real part of the result will correspond to the convolution with H1 and
% the imaginary part with H2. This allows the two convolutions to be
% done as one in the frequency domain, saving time and memory.
H = (1i*u1 - u2)./radius;
% The two monogenic filters H1 and H2 are not selective in terms of the
% magnitudes of the frequencies. The code below generates bandpass
% log-Gabor filters which are point-wise multiplied by IM to produce
% different bandpass versions of the image before being convolved with H1
% and H2
% First construct a low-pass filter that is as large as possible, yet falls
% away to zero at the boundaries. All filters are multiplied by
% this to ensure no extra frequencies at the 'corners' of the FFT are
% incorporated as this can upset the normalisation process when
% calculating phase congruency
lp = lowpassfilter([rows,cols],.45,15); % Radius .4, 'sharpness' 15
for s = 1:nscale
wavelength = minWaveLength*mult^(s-1);
fo = 1.0/wavelength; % Centre frequency of filter.
logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2));
logGabor = logGabor.*lp; % Apply low-pass filter
logGabor(1,1) = 0; % Set the value at the 0 frequency point of the
% filter back to zero (undo the radius fudge).
IMF = IM.*logGabor; % Bandpassed image in the frequency domain.
f = real(ifft2(IMF)); % Bandpassed image in spatial domain.
h = ifft2(IMF.*H); % Bandpassed monogenic filtering, real part of h contains
% convolution result with h1, imaginary part
% contains convolution result with h2.
h1 = real(h);
h2 = imag(h);
An = sqrt(f.^2 + h1.^2 + h2.^2); % Amplitude of this scale component.
sumAn = sumAn + An; % Sum of component amplitudes over scale.
sumf = sumf + f;
sumh1 = sumh1 + h1;
sumh2 = sumh2 + h2;
% At the smallest scale estimate noise characteristics from the
% distribution of the filter amplitude responses stored in sumAn.
% tau is the Rayleigh parameter that is used to describe the
% distribution.
if s == 1
if noiseMethod == -1 % Use median to estimate noise statistics
tau = median(sumAn(:))/sqrt(log(4));
elseif noiseMethod == -2 % Use mode to estimate noise statistics
tau = rayleighmode(sumAn(:));
end
maxAn = An;
else
% Record maximum amplitude of components across scales. This is needed
% to determine the frequency spread weighting.
maxAn = max(maxAn,An);
end
end % For each scale
% Form weighting that penalizes frequency distributions that are
% particularly narrow. Calculate fractional 'width' of the frequencies
% present by taking the sum of the filter response amplitudes and dividing
% by the maximum component amplitude at each point on the image. If
% there is only one non-zero component width takes on a value of 0, if
% all components are equal width is 1.
width = (sumAn./(maxAn + epsilon) - 1) / (nscale-1);
% Now calculate the sigmoidal weighting function.
weight = 1.0 ./ (1 + exp( (cutOff - width)*g));
% Automatically determine noise threshold
%
% Assuming the noise is Gaussian the response of the filters to noise will
% form Rayleigh distribution. We use the filter responses at the smallest
% scale as a guide to the underlying noise level because the smallest scale
% filters spend most of their time responding to noise, and only
% occasionally responding to features. Either the median, or the mode, of
% the distribution of filter responses can be used as a robust statistic to
% estimate the distribution mean and standard deviation as these are related
% to the median or mode by fixed constants. The response of the larger
% scale filters to noise can then be estimated from the smallest scale
% filter response according to their relative bandwidths.
%
% This code assumes that the expected reponse to noise on the phase
% congruency calculation is simply the sum of the expected noise responses
% of each of the filters. This is a simplistic overestimate, however these
% two quantities should be related by some constant that will depend on the
% filter bank being used. Appropriate tuning of the parameter 'k' will
% allow you to produce the desired output. (though the value of k seems to
% be not at all critical)
if noiseMethod >= 0 % We are using a fixed noise threshold
T = noiseMethod; % use supplied noiseMethod value as the threshold
else
% Estimate the effect of noise on the sum of the filter responses as
% the sum of estimated individual responses (this is a simplistic
% overestimate). As the estimated noise response at succesive scales
% is scaled inversely proportional to bandwidth we have a simple
% geometric sum.
totalTau = tau * (1 - (1/mult)^nscale)/(1-(1/mult));
% Calculate mean and std dev from tau using fixed relationship
% between these parameters and tau. See
% http://mathworld.wolfram.com/RayleighDistribution.html
EstNoiseEnergyMean = totalTau*sqrt(pi/2); % Expected mean and std
EstNoiseEnergySigma = totalTau*sqrt((4-pi)/2); % values of noise energy
T = EstNoiseEnergyMean + k*EstNoiseEnergySigma; % Noise threshold
end
%------ Final computation of key quantities -------
or = atan(-sumh2./sumh1); % Orientation - this varies +/- pi/2
or(or<0) = or(or<0)+pi; % Add pi to -ve orientation value so that all
% orientation values now range 0 - pi
or = fix(or/pi*180); % Quantize to 0 - 180 degrees (for NONMAXSUP)
ft = atan2(sumf,sqrt(sumh1.^2+sumh2.^2)); % Feature type - a phase angle
% -pi/2 to pi/2.
energy = sqrt(sumf.^2 + sumh1.^2 + sumh2.^2); % Overall energy
% Compute phase congruency. The original measure,
% PC = energy/sumAn
% is proportional to the weighted cos(phasedeviation). This is not very
% localised so this was modified to
% PC = cos(phasedeviation) - |sin(phasedeviation)|
% (Note this was actually calculated via dot and cross products.) This measure
% approximates
% PC = 1 - phasedeviation.
% However, rather than use dot and cross products it is simpler and more
% efficient to simply use acos(energy/sumAn) to obtain the weighted phase
% deviation directly. Note, in the expression below the noise threshold is
% not subtracted from energy immediately as this would interfere with the
% phase deviation computation. Instead it is applied as a weighting as a
% fraction by which energy exceeds the noise threshold. This weighting is
% applied in addition to the weighting for frequency spread. Note also the
% phase deviation gain factor which acts to sharpen up the edge response. A
% value of 1.5 seems to work well. Sensible values are from 1 to about 2.
PC = weight.*max(1 - deviationGain*acos(energy./(sumAn + epsilon)),0) ...
.* max(energy-T,0)./(energy+epsilon);
%------------------------------------------------------------------
% CHECKARGS
%
% Function to process the arguments that have been supplied, assign
% default values as needed and perform basic checks.
function [im, nscale, minWaveLength, mult, sigmaOnf, ...
k, noiseMethod, cutOff, g, deviationGain] = checkargs(arg)
nargs = length(arg);
if nargs < 1
error('No image supplied as an argument');
end
% Set up default values for all arguments and then overwrite them
% with with any new values that may be supplied
im = [];
nscale = 4; % Number of wavelet scales.
minWaveLength = 3; % Wavelength of smallest scale filter.
mult = 2.1; % Scaling factor between successive filters.
sigmaOnf = 0.55; % Ratio of the standard deviation of the
% Gaussian describing the log Gabor filter's
% transfer function in the frequency domain
% to the filter center frequency.
k = 3.0; % No of standard deviations of the noise
% energy beyond the mean at which we set the
% noise threshold point.
noiseMethod = -1; % Use the median response of smallest scale
% filter to estimate noise statistics
cutOff = 0.5;
g = 10;
deviationGain = 1.5;
% Allowed argument reading states
allnumeric = 1; % Numeric argument values in predefined order
keywordvalue = 2; % Arguments in the form of string keyword
% followed by numeric value
readstate = allnumeric; % Start in the allnumeric state
if readstate == allnumeric
for n = 1:nargs
if isa(arg{n},'char')
readstate = keywordvalue;
break;
else
if n == 1, im = arg{n};
elseif n == 2, nscale = arg{n};
elseif n == 3, minWaveLength = arg{n};
elseif n == 4, mult = arg{n};
elseif n == 5, sigmaOnf = arg{n};
elseif n == 6, k = arg{n};
elseif n == 7, cutOff = arg{n};
elseif n == 8, g = arg{n};
elseif n == 9, deviationGain = arg{n};
elseif n == 10, noiseMethod = arg{n};
end
end
end
end
% Code to handle parameter name - value pairs
if readstate == keywordvalue
while n < nargs
if ~isa(arg{n},'char') || ~isa(arg{n+1}, 'double')
error('There should be a parameter name - value pair');
end
if strncmpi(arg{n},'im' ,2), im = arg{n+1};
elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1};
elseif strncmpi(arg{n},'minWaveLength',2), minWaveLength = arg{n+1};
elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1};
elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1};
elseif strncmpi(arg{n},'k' ,1), k = arg{n+1};
elseif strncmpi(arg{n},'cutOff' ,2), cutOff = arg{n+1};
elseif strncmpi(arg{n},'g' ,1), g = arg{n+1};
elseif strncmpi(arg{n},'deviation',3), deviationGain = arg{n+1};
elseif strncmpi(arg{n},'noisemethod',3), noiseMethod = arg{n+1};
else error('Unrecognised parameter name');
end
n = n+2;
if n == nargs
error('Unmatched parameter name - value pair');
end
end
end
if isempty(im)
error('No image argument supplied');
end
if ndims(im) == 3
warning('Colour image supplied: converting image to greyscale...')
im = double(rgb2gray(im));
end
if ~isa(im, 'double')
im = double(im);
end
if nscale < 1
error('nscale must be an integer >= 1');
end
if minWaveLength < 2
error('It makes little sense to have a wavelength < 2');
end
%-------------------------------------------------------------------------
% RAYLEIGHMODE
%
% Computes mode of a vector/matrix of data that is assumed to come from a
% Rayleigh distribution.
%
% Usage: rmode = rayleighmode(data, nbins)
%
% Arguments: data - data assumed to come from a Rayleigh distribution
% nbins - Optional number of bins to use when forming histogram
% of the data to determine the mode.
%
% Mode is computed by forming a histogram of the data over 50 bins and then
% finding the maximum value in the histogram. Mean and standard deviation
% can then be calculated from the mode as they are related by fixed
% constants.
%
% mean = mode * sqrt(pi/2)
% std dev = mode * sqrt((4-pi)/2)
%
% See
% http://mathworld.wolfram.com/RayleighDistribution.html
% http://en.wikipedia.org/wiki/Rayleigh_distribution
%
function rmode = rayleighmode(data, nbins)
if nargin == 1
nbins = 50; % Default number of histogram bins to use
end
mx = max(data(:));
edges = 0:mx/nbins:mx;
n = histc(data(:),edges);
[dum,ind] = max(n); % Find maximum and index of maximum in histogram
rmode = (edges(ind)+edges(ind+1))/2;
|
github
|
jacksky64/imageProcessing-master
|
highpassmonogenic.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/highpassmonogenic.m
| 5,083 |
utf_8
|
5757adc283f2cfd76b0279ac438de2a9
|
% HIGHPASSMONOGENIC Compute phase and amplitude on highpass images via monogenic filters
%
% Usage: [phase, orient, E, f, h1f, h2f] = highpassmonogenic(im, maxwavelength, n)
%
% Arguments: im - Image to be processed.
% maxwavelength - Wavelength(s) in pixels of the cut-in frequency(ies)
% of the Butterworth highpass filter.
% n - The order of the Butterworth filter. This is an
% integer >= 1. The higher the value the sharper
% the cutoff. I generaly do not use a value
% higher than 2 to avoid ringing artifacts
%
% Returns: phase - The local phase. Values are between -pi/2 and pi/2
% orient - The local orientation. Values between -pi and pi.
% Note that where the local phase is close to
% +-pi/2 the orientation will be poorly defined.
% E - Local energy, or amplitude, of the signal.
%
% Note that maxwavelength can be an array in which case the outputs will all
% be cell arrays with an element for each corresponding maxwavelength
% value.
%
% Note also that this code uses the function PERFFT2 rather than FFT2. This
% computes the 'periodic fft'. This comes at the cost of requiring an
% additional fft however the minimisation of boundary effects in the result
% makes it well worth it.
%
% See also: PERFFT2, MONOFILT
% 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.
%
% March 2012
function [phase, orient, E, f, h1f, h2f] = highpassmonogenic(im, maxwavelength, n)
if ndims(im) == 3, im = rgb2gray(im); end
assert(min(maxwavelength) >= 2, 'Minimum wavelength is 2 pixels')
[rows,cols] = size(im);
IM = fft2(double(im));
% IM = perfft2(double(im)); % Periodic fft can be useful but I think we
% may want to add the smooth component of the
% decomposition back in after the
% filtering. Without this one can get edge
% artifcats
% The problem is calculating the periodic fft
% + computing the smooth component in the
% spatial domain involves 3 ffts
% Generate horizontal and vertical frequency grids that vary from -0.5 to
% 0.5. Note there are various calls to clear further below to free up
% memory to allow the processing of very large grids.
[u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ...
([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2)));
u1 = ifftshift(u1); % Quadrant shift to put 0 frequency at the corners
u2 = ifftshift(u2);
radius = sqrt(u1.^2 + u2.^2); % Matrix values contain frequency
% values as a radius from centre
% (but quadrant shifted)
% Get rid of the 0 radius value in the middle (at top left corner after
% fftshifting) so that dividing by the radius, will not cause trouble.
radius(1,1) = 1;
H1 = i*u1./radius; % The two monogenic filters in the frequency domain
H2 = i*u2./radius;
H1(1,1) = 0;
H2(1,1) = 0;
radius(1,1) = 0; % undo fudge
clear('u1', 'u2');
if length(maxwavelength) == 1 % Only one scale requested
% High pass Butterworth filter
H = 1.0 - 1.0 ./ (1.0 + (radius * maxwavelength).^(2*n));
clear('radius');
IM = IM.*H; clear('H');
f = real(ifft2(IM));
h1f = real(ifft2(H1.*IM)); clear('H1');
h2f = real(ifft2(H2.*IM)); clear('H2', 'IM');
phase = atan(f./sqrt(h1f.^2+h2f.^2 + eps));
orient = atan2(h2f, h1f);
E = sqrt(f.^2 + h1f.^2 + h2f.^2);
else % Return output as cell arrays, with elements for each scale requested
for s = 1:length(maxwavelength)
% High pass Butterworth filter
H = 1.0 - 1.0 ./ (1.0 + (radius * maxwavelength(s)).^(2*n));
f{s} = real(ifft2(H.*IM));
h1f{s} = real(ifft2(H.*H1.*IM));
h2f{s} = real(ifft2(H.*H2.*IM));
phase{s} = atan(f{s}./sqrt(h1f{s}.^2+h2f{s}.^2 + eps));
orient{s} = atan2(h2f{s}, h1f{s});
E{s} = sqrt(f{s}.^2 + h1f{s}.^2 + h2f{s}.^2);
end
end
|
github
|
jacksky64/imageProcessing-master
|
step2line.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/step2line.m
| 2,815 |
utf_8
|
3de96275d1352c256efd4160cfc1ec2d
|
% STEP2LINE - Generate test image interpolating a step to a line.
%
% Function to generate a test image where the feature type changes
% from a step edge to a line feature from top to bottom
%
% Usage:
% im = step2line(nscales, ampexponent, sze)
%
% nscales - No of fourier components used to construct the signal
% ampexponent - decay exponent of amplitude with frequency
% a value of -1 will produce amplitude inversely
% proportional to frequency (corresponds to step feature)
% a value of -2 will result in the line feature
% appearing as a triangular waveform.
% sze - Optional size of image, defaults to 256x256
%
% Returns:
% im - Image showing the grating pattern
%
% suggested parameters:
% step2line(100, -1)
%
% Copyright (c) 1997 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.
%
% 1997 Original version
% September 2011 Modified to allow number of cycles to be specified
% January 2013 Fix Octave compatibility. Separate Octave code path no longer needed
function im = step2line(nscales, ampexponent, Npts, nCycles, phaseCycles)
if ~exist('Npts', 'var'), Npts = 256; end
if ~exist('nCycles', 'var'), nCycles = 1.5; end
if ~exist('phaseCycles', 'var'), phaseCycles = 0.5; end
x = [0:(Npts-1)]/(Npts-1)*nCycles*2*pi;
im = zeros(Npts,Npts);
off = 0;
for row = 1:Npts
signal = zeros(1,Npts);
for scale = 1:2:(nscales*2-1)
signal = signal + scale^ampexponent*sin(scale*x + off);
end
im(row,:) = signal;
off = off + phaseCycles*pi/Npts;
end
figure
colormap(gray);
imagesc(im), axis('off') , title('step to line feature interpolation');
range = 3.2;
s = 'Profiles having phase congruency at 0/180, 30/210, 60/240 and 90/270 degrees';
figure
subplot(4,1,1), plot(im(1,:)) , title(s), axis([0,Npts,-range,range]), axis('off');
subplot(4,1,2), plot(im(fix(Npts/3),:)), axis([0,Npts,-range,range]), axis('off');
subplot(4,1,3), plot(im(fix(2*Npts/3),:)), axis([0,Npts,-range,range]), axis('off');
subplot(4,1,4), plot(im(Npts,:)), axis([0,Npts,-range,range]), axis('off');
|
github
|
jacksky64/imageProcessing-master
|
odot.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/odot.m
| 3,720 |
utf_8
|
336255093ed76b067368d764f3d823d5
|
% ODOT - Demonstrates odot and oslash operators on 1D signal
%
% Usage: [smooth, energy] = odot(f, K)
%
% Arguments: f - a 1D signal
% K - optional 'Weiner' type factor to condition the results
% where division by 0 occurs in the 'oslash' operation.
% K defaults to 'eps', If oscillations appear in the
% plots try increasing the value of K
%
% Returns: energy - the Local Energy of the signal.
% smooth - the smooth component of the signal obtained by
% performing the 'oslash' operator between the
% signal and its Local Energy.
% Plots:
% Signal Hilbert Transform of Signal
% Local Energy Hilbert Transform of Energy
% Smooth Component Reconstruction
%
% Smooth = signal 'oslash' energy
% Reconstruction = energy 'odot' smooth
%
% Glitches in the results will be seen at points where the Local Energy
% peaks - these points cause numerical grief. These problems can be
% alleviated by smoothing the signal slightly and/or increasing the
% parameter K.
%
% This code only works for 1D signals - I am not sure how you would
% implement it for 2D images...
% Reference: Robyn Owens. "Feature-Free Images", Pattern Recognition
% Letters. Vol 15. pp 35-44, 1994.
% Copyright (c) 2004 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 2004
function [smooth, energy] = odot(f, K)
if nargin == 1
K = eps;
end
N = length(f);
if rem(N,2) > 0 % odd No of elements - trim the last one off to make the
% number of elements even for simplicity.
N = N - 1;
f = f(1:N);
end
F = fft(f);
F(1) = 0; % Kill DC component
f = real(ifft(F)); % Reconstruct signal minus DC component
% Perform 90 degree phase shift on the signal by multiplying +ve
% frequencies of the fft by i and the -ve frequencies by -i, and then
% inverting.
phaseshift = [ ones(1,N/2)*i ones(1,N/2)*(-i) ];
% Hilbert Transform of signal
h = real(ifft(F.*phaseshift));
energy = sqrt(f.^2 + h.^2); % Energy
% Hilbert Transform of Energy
energyh = real(ifft(fft(energy).*phaseshift));
% smooth = signal 'oslash' energy
divisor = energy.^2 + energyh.^2;
% Where divisor << K, weinercorrector -> 0/K
% Where divisor >> K, weinercorrector -> 1
weinercorrector = divisor.^2 ./ ((divisor.^2)+K);
smooth = (f.*energy + energyh.*h)./divisor .* weinercorrector;
% Hilbert transform of smooth component
smoothh=real(ifft(fft(smooth).*phaseshift));
% Reconstruction = energy odot smooth
recon = (smooth.*energy - smoothh.*energyh);
subplot(3,2,1), plot(f),title('Signal');
subplot(3,2,2), plot(h),title('Hilbert Transform of Signal');
subplot(3,2,3), plot(energy),title('Local Energy');
subplot(3,2,4), plot(energyh),title('Hilbert Transform of Energy');
subplot(3,2,5), plot(smooth),title('Smooth Component');
subplot(3,2,6), plot(recon),title('Reconstruction');
|
github
|
jacksky64/imageProcessing-master
|
dispfeat.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/dispfeat.m
| 6,082 |
utf_8
|
1baad565a14949d330f8fe298e5a0322
|
% DISPFEAT - Displays feature types as detected by PHASECONG.
%
% This function provides a visualisation of the feature types as detected
% by PHASECONG.
%
% Usage: im = dispfeat(ft, edgeim, 'l')
%
% Arguments: ft - An image providing the local weighted mean
% phase angle at every point in the image for the
% orientation having maximum energy. This image can be
% complex valued in which case phase is assumed to be
% the complex angle, or it can be real valued, in which
% case it is assumed to be the phase directly.
% edgeim - A binary edge image (typically obtained via
% non-maxima suppression and thresholding).
% This is used as a `mask' to specify which bits of
% the phase data should be displayed.
% Alternatively you can supply a phase congruency
% image in which case it is used to control the
% saturation of the colour coding
% l - An optional parameter indicating that a line plot
% encoded by line style should also be produced. If
% this is the case then `edgeim' really should be an
% edge image.
%
% Returns: im - An edge image with edges colour coded according to
% feature type.
%
% Two or three plots are generated:
% 1. An edge image with edges colour coded according to feature type.
% 2. A histogram of the frequencies at which the different feature types
% occur.
% 3. Optionally a black/white edge image with edges coded by different line
% styles. Not as pretty as the first plot, but it is something that can
% be put in a paper and reproduced in black and white.
% Copyright (c) 2001-2009 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 2001 Original version
% May 2009 Allowance for phase data 'ft' to be real or complex valued.
function im = dispfeat(ft, edgeim)
% Construct the colour coded image
maxhue = 0.7; % Hues vary from 0 (red) indicating line feature to
% 0.7 (blue) indicating a step feature.
nhues = 50;
if ~isreal(ft) % Phase is encoded as complex values
phaseang = angle(ft);
else
phaseang = ft; % Assume data is phase already
end
% Map -ve phase angles to 0-pi
negphase = phaseang<0;
phaseang = negphase.*(-phaseang) + ~negphase.*phaseang;
% Then map angles > pi/2 to 0-pi/2
x = phaseang>(pi/2);
phaseang = x.*(pi-phaseang) + ~x.*phaseang;
% Now set up a HSV image and convert to RGB
hsvim(:,:,1) = (pi/2-phaseang)/(pi/2)*maxhue;
hsvim(:,:,2) = edgeim; % saturation
hsvim(:,:,3) = 1;
hsvim(1,:,3) = 0;
hsvim(end,:,3) = 0;
hsvim(:,1,3) = 0;
hsvim(:,end,3) = 0;
im = hsv2rgb(hsvim);
% Set up the colour key bar
keybar(:,:,1) = [maxhue:-maxhue/nhues:0]';
keybar(:,:,2) = 1;
keybar(:,:,3) = 1;
keybar = hsv2rgb(keybar);
% Plot the results
figure(1), clf
subplot('position',[.05 .1 .75 .8]), imshow(im)
subplot('position',[.8 .1 .1 .8]), imshow(keybar)
text(3,2,'step feature');
text(3,nhues/2,'step/line');
text(3,nhues,'line feature');
% Construct the histogram of feature types
figure(2),clf
data = phaseang(find(edgeim)); % find phase angles just at edge points
Nbins = 32;
bincentres = [0:pi/2/Nbins:pi/2];
hdata = histc(data(:), bincentres);
bar(bincentres+pi/4/Nbins, hdata) % plot histogram
ymax = max(hdata);
xlabel('phase angle'); ylabel('frequency');
ypos = -.12*ymax;
axis([0 pi/2 0 1.05*ymax])
if nargin == 3
% Construct the feature type image coded using different line styles
% Generate a phase angle image with non-zero values only at edge
% points. An offset of eps is added to differentiate points having 0
% phase from non edge points.
featedge = (phaseang+eps).*double(edgeim);
% Now construct feature images over specified phase ranges
f1 = featedge >= eps & featedge < pi/6;
f2 = featedge >= pi/6 & featedge < pi/3;
f3 = featedge >= pi/3 & featedge <= pi/2;
fprintf('Linking edges for plots...\n');
[f1edgelst dum] = edgelink(f1,2);
[f2edgelst dum] = edgelink(f2,2);
[f3edgelst dum] = edgelink(f3,2);
figno = 3;
figure(figno), clf
% Construct a legend by first drawing some dummy, zero length, lines
% with the appropriate linestyles in the right order
line([0 0],[0 0],'LineStyle','-');
line([0 0],[0 0],'LineStyle','--');
line([0 0],[0 0],'LineStyle',':');
legend('step', 'step/line', 'line',3);
% Now do the real plots
plotedgelist(f1edgelst, figno, '-');
plotedgelist(f2edgelst, figno, '--');
plotedgelist(f3edgelst, figno, ':');
% Draw a border around the whole image
[r c] = size(edgeim);
line([0 c c 0 0],[0 0 r r 0]);
axis([0 c 0 r])
axis equal
axis ij
axis off
end
%------------------------------------------------------------------------
% Internal function to plot an edgelist as generated by edgelink using a
% specified linestyle
function plotedgelist(elist, figno, linestyle)
figure(figno);
for e = 1:length(elist)
line(elist{e}(:,2), elist{e}(:,1), 'LineStyle', linestyle, ...
'LineWidth',1);
end
|
github
|
jacksky64/imageProcessing-master
|
gaborconvolve.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/gaborconvolve.m
| 10,723 |
utf_8
|
e6f93594f5594d23a349d49069729926
|
% GABORCONVOLVE - function for convolving image with log-Gabor filters
%
% Usage: [EO, BP] = gaborconvolve(im, nscale, norient, minWaveLength, mult, ...
% sigmaOnf, dThetaOnSigma, Lnorm, feedback)
%
% Arguments:
% The convolutions are done via the FFT. Many of the parameters relate
% to the specification of the filters in the frequency plane.
%
% Variable Suggested Description
% name value
% ----------------------------------------------------------
% im Image to be convolved.
% nscale = 4; Number of wavelet scales.
% norient = 6; Number of filter orientations.
% minWaveLength = 3; Wavelength of smallest scale filter.
% mult = 1.7; Scaling factor between successive filters.
% sigmaOnf = 0.65; Ratio of the standard deviation of the
% Gaussian describing the log Gabor filter's
% transfer function in the frequency domain
% to the filter center frequency.
% dThetaOnSigma = 1.3; Ratio of angular interval between filter
% orientations and the standard deviation of
% the angular Gaussian function used to
% construct filters in the freq. plane.
% Lnorm 0 Optional integer indicating what norm the
% filters should be normalized to. A value of 1
% will produce filters with the same L1 norm, 2
% will produce filters with matching L2
% norm. the default value of 0 results in no
% normalization (the filters have unit height
% Gaussian transfer functions on a log frequency
% scale)
% feedback 0/1 Optional parameter. If set to 1 a message
% indicating which orientation is being
% processed is printed on the screen.
%
% Returns:
%
% EO - 2D cell array of complex valued convolution results
%
% EO{s,o} = convolution result for scale s and orientation o.
% The real part is the result of convolving with the even
% symmetric filter, the imaginary part is the result from
% convolution with the odd symmetric filter.
%
% Hence:
% abs(EO{s,o}) returns the magnitude of the convolution over the
% image at scale s and orientation o.
% angle(EO{s,o}) returns the phase angles.
%
% BP - Cell array of bandpass images corresponding to each scale s.
%
%
% Notes on filter settings to obtain even coverage of the spectrum energy
% dThetaOnSigma 1.2 - 1.3
% sigmaOnf .90 mult 1.15
% sigmaOnf .85 mult 1.2
% sigmaOnf .75 mult 1.4 (bandwidth ~1 octave)
% sigmaOnf .65 mult 1.7
% sigmaOnf .55 mult 2.2 (bandwidth ~2 octaves)
%
% The determination of mult given sigmaOnf is entirely empirical. What I do is
% plot out the sum of the squared filter amplitudes in the frequency domain and
% see how even the coverage of the spectrum is. If there are concentric 'gaps'
% in the spectrum one needs to reduce mult and/or reduce sigmaOnf (which
% increases filter bandwidth)
%
% If there are 'gaps' radiating outwards then one needs to reduce dthetaOnSigma
% (increasing angular bandwidth of the filters)
%
% For details of log-Gabor filters see:
% D. J. Field, "Relations Between the Statistics of Natural Images and the
% Response Properties of Cortical Cells", Journal of The Optical Society of
% America A, Vol 4, No. 12, December 1987. pp 2379-2394
% Copyright (c) 2001-2010 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.
% May 2001 - Original version
% April 2010 - Reworked to tidy things up. Return of bandpass images added.
% March 2013 - Restored use of dThetaOnSigma to control angular spread of filters.
function [EO, BP] = gaborconvolve(im, nscale, norient, minWaveLength, mult, ...
sigmaOnf, dThetaOnSigma, Lnorm, feedback)
if ndims(im) == 3
warning('Colour image supplied: Converting to greyscale');
im = rgb2gray(im);
end
if ~exist('Lnorm','var'), Lnorm = 0; end
if ~exist('feedback','var'), feedback = 0; end
if ~isa(im,'double'), im = double(im); end
[rows cols] = size(im);
imagefft = fft2(im); % Fourier transform of image
EO = cell(nscale, norient); % Pre-allocate cell array
BP = cell(nscale,1);
% Pre-compute some stuff to speed up filter construction
% 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); % Matrix values contain *normalised* radius from centre.
theta = atan2(y,x); % Matrix values contain polar angle.
radius = ifftshift(radius); % Quadrant shift radius and theta so that filters
theta = ifftshift(theta); % are constructed with 0 frequency at the corners.
radius(1,1) = 1; % Get rid of the 0 radius value at the 0
% frequency point (now at top-left corner)
% so that taking the log of the radius will
% not cause trouble.
sintheta = sin(theta);
costheta = cos(theta);
clear x; clear y; clear theta; % save a little memory
% Filters are constructed in terms of two components.
% 1) The radial component, which controls the frequency band that the filter
% responds to
% 2) The angular component, which controls the orientation that the filter
% responds to.
% The two components are multiplied together to construct the overall filter.
% Construct the radial filter components...
% First construct a low-pass filter that is as large as possible, yet falls
% away to zero at the boundaries. All log Gabor filters are multiplied by
% this to ensure no extra frequencies at the 'corners' of the FFT are
% incorporated. This keeps the overall norm of each filter not too dissimilar.
lp = lowpassfilter([rows,cols],.45,15); % Radius .45, 'sharpness' 15
logGabor = cell(1,nscale);
for s = 1:nscale
wavelength = minWaveLength*mult^(s-1);
fo = 1.0/wavelength; % Centre frequency of filter.
logGabor{s} = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2));
logGabor{s} = logGabor{s}.*lp; % Apply low-pass filter
logGabor{s}(1,1) = 0; % Set the value at the 0
% frequency point of the filter
% back to zero (undo the radius fudge).
% Compute bandpass image for each scale
if Lnorm == 2 % Normalize filters to have same L2 norm
L = sqrt(sum(logGabor{s}(:).^2));
elseif Lnorm == 1 % Normalize to have same L1
L = sum(sum(abs(real(ifft2(logGabor{s})))));
elseif Lnorm == 0 % No normalization
L = 1;
else
error('Lnorm must be 0, 1 or 2');
end
logGabor{s} = logGabor{s}./L;
BP{s} = ifft2(imagefft .* logGabor{s});
end
% The main loop...
for o = 1:norient, % For each orientation.
if feedback
fprintf('Processing orientation %d \r', o);
end
angl = (o-1)*pi/norient; % Calculate filter angle.
wavelength = minWaveLength; % Initialize filter wavelength.
% Pre-compute filter data specific to this orientation
% For each point in the filter matrix calculate the angular distance from the
% specified filter orientation. To overcome the angular wrap-around problem
% sine difference and cosine difference values are first computed and then
% the atan2 function is used to determine angular distance.
ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.
dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.
dtheta = abs(atan2(ds,dc)); % Absolute angular distance.
% Calculate the standard deviation of the angular Gaussian
% function used to construct filters in the freq. plane.
thetaSigma = pi/norient/dThetaOnSigma;
spread = exp((-dtheta.^2) / (2 * thetaSigma^2));
for s = 1:nscale, % For each scale.
filter = logGabor{s} .* spread; % Multiply by the angular spread to get the filter
if Lnorm == 2 % Normalize filters to have the same L2 norm ** why sqrt 2 **????
L = sqrt(sum(real(filter(:)).^2 + imag(filter(:)).^2 ))/sqrt(2);
elseif Lnorm == 1 % Normalize to have same L1
L = sum(sum(abs(real(ifft2(filter)))));
elseif Lnorm == 0 % No normalization
L = 1;
end
filter = filter./L;
% Do the convolution, back transform, and save the result in EO
EO{s,o} = ifft2(imagefft .* filter);
wavelength = wavelength * mult; % Finally calculate Wavelength of next filter
end % ... and process the next scale
end % For each orientation
if feedback, fprintf(' \r'); end
|
github
|
jacksky64/imageProcessing-master
|
monofilt.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/monofilt.m
| 6,435 |
utf_8
|
07ef46eb32d19a4d79e9ec304c6cb2d3
|
% MONOFILT - Apply monogenic filters to an image to obtain 2D analytic signal
%
% Implementation of Felsberg's monogenic filters
%
% Usage: [f, h1f, h2f, A, theta, psi] = ...
% monofilt(im, nscale, minWaveLength, mult, sigmaOnf, orientWrap)
% 3 4 2 0.65 1/0
% Arguments:
% The convolutions are done via the FFT. Many of the parameters relate
% to the specification of the filters in the frequency plane.
%
% Variable Suggested Description
% name value
% ----------------------------------------------------------
% im Image to be convolved.
% nscale = 3; Number of filter scales.
% minWaveLength = 4; Wavelength of smallest scale filter.
% mult = 2; Scaling factor between successive filters.
% sigmaOnf = 0.65; Ratio of the standard deviation of the
% Gaussian describing the log Gabor filter's
% transfer function in the frequency domain
% to the filter center frequency.
% orientWrap 1/0 Optional flag 1/0 to turn on/off
% 'wrapping' of orientation data from a
% range of -pi .. pi to the range 0 .. pi.
% This affects the interpretation of the
% phase angle - see note below. Defaults to 0.
% Returns:
%
% f - cell array of bandpass filter responses with respect to scale.
% h1f - cell array of bandpass h1 filter responses wrt scale.
% h2f - cell array of bandpass h2 filter responses.
% A - cell array of monogenic energy responses.
% theta - cell array of phase orientation responses.
% psi - cell array of phase angle responses.
%
% If orientWrap is 1 (on) theta will be returned in the range 0 .. pi and
% psi (the phase angle) will be returned in the range -pi .. pi. If
% orientWrap is 0 theta will be returned in the range -pi .. pi and psi will
% be returned in the range -pi/2 .. pi/2. Try both options on an image of a
% circle to see what this means!
%
% Experimentation with sigmaOnf can be useful depending on your application.
% I have found values as low as 0.2 (a filter with a *very* large bandwidth)
% to be useful on some occasions.
%
% See also: GABORCONVOLVE
% References:
% Michael Felsberg and Gerald Sommer. "A New Extension of Linear Signal
% Processing for Estimating Local Properties and Detecting Features"
% DAGM Symposium 2000, Kiel
%
% Michael Felsberg and Gerald Sommer. "The Monogenic Signal" IEEE
% Transactions on Signal Processing, 49(12):3136-3144, December 2001
% Copyright (c) 2004-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.
% October 2004 - Original version.
% May 2005 - Orientation wrapping and code cleaned up.
% August 2005 - Phase calculation improved.
function [f, h1f, h2f, A, theta, psi] = ...
monofilt(im, nscale, minWaveLength, mult, sigmaOnf, orientWrap)
if nargin == 5
orientWrap = 0; % Default is no orientation wrapping
end
if nargout > 4
thetaPhase = 1; % Calculate orientation and phase
else
thetaPhase = 0; % Only return filter outputs
end
[rows,cols] = size(im);
IM = fft2(double(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)));
u1 = ifftshift(u1); % Quadrant shift to put 0 frequency at the corners
u2 = ifftshift(u2);
radius = sqrt(u1.^2 + u2.^2); % Matrix values contain frequency
% values as a radius from centre
% (but quadrant shifted)
% Get rid of the 0 radius value in the middle (at top left corner after
% fftshifting) so that taking the log of the radius, or dividing by the
% radius, will not cause trouble.
radius(1,1) = 1;
H1 = i*u1./radius; % The two monogenic filters in the frequency domain
H2 = i*u2./radius;
% The two monogenic filters H1 and H2 are oriented in frequency space
% but are not selective in terms of the magnitudes of the
% frequencies. The code below generates bandpass log-Gabor filters
% which are point-wise multiplied by H1 and H2 to produce different
% bandpass versions of H1 and H2
for s = 1:nscale
wavelength = minWaveLength*mult^(s-1);
fo = 1.0/wavelength; % Centre frequency of filter.
logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2));
logGabor(1,1) = 0; % undo the radius fudge.
% Generate bandpass versions of H1 and H2 at this scale
H1s = H1.*logGabor;
H2s = H2.*logGabor;
% Apply filters to image in the frequency domain and get spatial
% results
f{s} = real(ifft2(IM.*logGabor));
h1f{s} = real(ifft2(IM.*H1s));
h2f{s} = real(ifft2(IM.*H2s));
A{s} = sqrt(f{s}.^2 + h1f{s}.^2 + h2f{s}.^2); % Magnitude of Energy.
% If requested calculate the orientation and phase angles
if thetaPhase
theta{s} = atan2(h2f{s}, h1f{s}); % Orientation.
% Here phase is measured relative to the h1f-h2f plane as an
% 'elevation' angle that ranges over +- pi/2
psi{s} = atan2(f{s}, sqrt(h1f{s}.^2 + h2f{s}.^2));
if orientWrap
% Wrap orientation values back into the range 0-pi
negind = find(theta{s}<0);
theta{s}(negind) = theta{s}(negind) + pi;
% Where orientation values have been wrapped we should
% adjust phase accordingly **check**
psi{s}(negind) = pi-psi{s}(negind);
morethanpi = find(psi{s}>pi);
psi{s}(morethanpi) = psi{s}(morethanpi)-2*pi;
end
end
end
|
github
|
jacksky64/imageProcessing-master
|
ppdrc.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/ppdrc.m
| 6,348 |
utf_8
|
a73a5e99aa7b7db0ace9da43a9a88e26
|
% PPDRC Phase Preserving Dynamic Range Compression
%
% Generates a series of dynamic range compressed images at different scales.
% This function is designed to reveal subtle features within high dynamic range
% images such as aeromagnetic and other potential field grids. Often this kind
% of data is presented using histogram equalisation in conjunction with a
% rainbow colourmap. A problem with histogram equalisation is that the contrast
% amplification of a feature depends on how commonly its data value occurs,
% rather than on the amplitude of the feature itself. In addition, the use of a
% rainbow colourmap can introduce undesirable perceptual distortions.
%
% Phase Preserving Dynamic Range Compression allows subtle features to be
% revealed without these distortions. Perceptually important phase information
% is preserved and the contrast amplification of anomalies in the signal is
% purely a function of their amplitude. It operates as follows: first a highpass
% filter is applied to the data, this controls the desired scale of analysis.
% The 2D analytic signal of the data is then computed to obtain local phase and
% amplitude at each point in the image. The amplitude is attenuated by adding 1
% and then taking its logarithm, the signal is then reconstructed using the
% original phase values.
%
% Usage: dim = ppdrc(im, wavelength, clip, savename, n)
%
% Arguments: im - Image to be processed (can contain NaNs)
% wavelength - Array of wavelengths, in pixels, of the cut-in
% frequencies to be used when forming the highpass
% versions of the image. Try a range of values starting
% with, say, a wavelength corresponding to half the size
% of the image and working down to something like 50
% grid units.
% clip - Percentage of output image histogram to clip. Only a
% very small value should be used, say 0.01 or 0.02, but
% this can be beneficial. Defaults to 0.01%
% savename - (optional) Basename of filname to be used when saving
% the output images. Images are saved as
% 'basename-n.png' where n is the highpass wavelength
% for that image . You will be prompted to select a
% folder to save the images in.
% n - Order of the Butterworth high pass filter. Defaults
% to 2
%
% Returns: dim - Cell array of the dynamic range reduced images. If
% only one wavelength is specified the image is returned
% directly, and not as a one element cell array.
%
% Note when specifying the array 'wavelength' it is suggested that you use
% wavelengths that increase in a geometric series. You can use the function
% GEOSERIES to conveniently do this
%
% Example using GEOSERIES to generate a set of wavelengths that increase
% geometrically in 10 steps from 50 to 800. Output is saved in a series of
% image files called 'result-n.png'
% dim = compressdynamicrange(im, geoseries([50 800], 10), 'result');
%
% View the output images in the form of an Interactive Image using LINIMIX
%
% See also: HIGHPASSMONOGENIC, GEOSERIES, LINIMIX, HISTRUNCATE
%
% Reference:
% Peter Kovesi, "Phase Preserving Tone Mapping of Non-Photographic High Dynamic
% Range Images". Proceedings: Digital Image Computing: Techniques and
% Applications 2012 (DICTA 2012). Available via IEEE Xplore
% 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
% Feb 2014 - Incorporated histogram truncation
function [dim, mask] = ppdrc(im, wavelength, clip, savename, n)
if ~exist('n', 'var') | isempty(n), n = 2; end
if ~exist('clip', 'var') | isempty(clip), clip = 0.01; end
if ~exist('savename', 'var') | isempty(savename), savename = 0; end
nscale = length(wavelength);
% Identify no-data regions in the image (assummed to be marked by NaN
% values). These values are filled by a call to fillnan() when passing image
% to highpassmonogenic. While fillnan() is a very poor 'inpainting' scheme
% it does keep artifacts at the boundaries of no-data regions fairly small.
mask = ~isnan(im);
[ph, ~, E] = highpassmonogenic(fillnan(im), wavelength, n);
% Construct each dynamic range reduced image
if nscale == 1 % Single image: ph and E will not be cell arrays
dim = histtruncate(sin(ph).*log1p(E), clip, clip).*mask;
else % Array of images to be returned.
range = zeros(nscale,1);
for k = 1:nscale
dim{k} = histtruncate(sin(ph{k}).*log1p(E{k}), clip, clip).*mask;
range(k) = max(abs(dim{k}(:)));
end
maxrange = max(range);
% Set the first two pixels of each image to +range and -range so that
% when the sequence of images are displayed together, say using LINIMIX,
% there are no unexpected overall brightness changes
for k = 1:nscale
dim{k}(1) = maxrange;
dim{k}(2) = -maxrange;
end
end
if savename
fprintf('Select a folder to save output images in\n');
dirname = uigetdir([],'Select a folder to save images in');
if ~dirname, return; end % Cancel
if nscale == 1
imwritesc(dim,sprintf('%s/%s-%04d.png', ...
dirname,savename,round(wavelength(1))))
else
for k = 1:nscale
imwritesc(dim{k},sprintf('%s/%s-%04d.png', ...
dirname,savename,round(wavelength(k))))
end
end
end
|
github
|
jacksky64/imageProcessing-master
|
plotgaborfilters.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/plotgaborfilters.m
| 10,822 |
utf_8
|
2734ffd48e7ead17030ee0fd2f31fce7
|
% PLOTGABORFILTERS - Plots log-Gabor filters
%
% The purpose of this code is to see what effect the various parameter
% settings have on the formation of a log-Gabor filter bank.
%
% Usage: [Ffilter, Efilter, Ofilter] = plotgaborfilters(sze, nscale, norient,...
% minWaveLength, mult, sigmaOnf, dThetaOnSigma)
%
% Arguments:
% Many of the parameters relate to the specification of the filters in the frequency plane.
%
% Variable Suggested Description
% name value
% ----------------------------------------------------------
% sze = 200 Size of image grid on which the filters
% are calculated. Note that the actual size
% of the filter is really specified by its
% wavelength.
% nscale = 4; Number of wavelet scales.
% norient = 6; Number of filter orientations.
% minWaveLength = 3; Wavelength of smallest scale filter.
% mult = 1.7; Scaling factor between successive filters.
% sigmaOnf = 0.65; Ratio of the standard deviation of the
% Gaussian describing the log Gabor filter's
% transfer function in the frequency domain
% to the filter center frequency.
% dThetaOnSigma = 1.3; Ratio of angular interval between filter
% orientations and the standard deviation of
% the angular Gaussian function used to
% construct filters in the freq. plane.
%
% Note regarding the specification of norient: In the default case it is assumed
% that the angles of the filters are evenly spaced at intervals of pi/norient
% around the frequency plane. If you want to visualize filters at a specific
% set of orientations that are not necessarily evenly spaced you can set the
% orientations by passing a CELL array of orientations as the argument to
% norient. In this case the value supplied for dThetaOnSigma will be used as
% thetaSigma - the angular standard deviation of the filters. Yes, this is
% an ugly abuse of the argument list, but there it is!
% Example:
% View filters over 3 scales with orientations of -0.3 and +0.3 radians,
% minWaveLength of 6, mult of 2, sigmaOnf of 0.65 and thetaSigma of 0.4
% plotgaborfilters2(200, 3, {-.3 .3}, 6, 2, 0.65, 0.4);
%
% Returns:
% Ffilter - a 2D cell array of filters defined in the frequency domain.
% Efilter - a 2D cell array of even filters defined in the spatial domain.
% Ofilter - a 2D cell array of odd filters defined in the spatial domain.
%
% Ffilter{s,o} = filter for scale s and orientation o.
% The even and odd filters in the spatial domain for scale s,
% orientation o, are obtained using.
%
% Efilter = ifftshift(real(ifft2(fftshift(filter{s,o}))));
% Ofilter = ifftshift(imag(ifft2(fftshift(filter{s,o}))));
%
% Plots:
% Figure 1 - Sum of the filters in the frequency domain
% Figure 2 - Cross sections of Figure 1
% Figures 3 and 4 - Surface and intensity plots of filters in the
% spatial domain at the smallest and largest
% scales respectively.
%
% See also: GABORCONVOLVE, PHASECONG
% Copyright (c) 2001-2008 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.
% May 2001 - Original version.
% February 2005 - Cleaned up.
% August 2005 - Ffilter,Efilter and Ofilter corrected to return with scale
% varying as the first index in the cell arrays.
% July 2008 - Allow specific filter orientations to be specified in
% norient via a cell array.
% March 2013 - Restored use of dThetaOnSigma to control angular spread of filters.
function [Ffilter, Efilter, Ofilter, filtersum] = ...
plotgaborfilters(sze, nscale, norient, minWaveLength, mult, ...
sigmaOnf, dThetaOnSigma)
if ~exist('dThetaOnSigma','var') || isempty(dThetaOnSigma), dThetaOnSigma = 1.3; end
if length(sze) == 1
rows = sze; cols = sze;
else
rows = sze(1); cols = sze(2);
end
if iscell(norient) % Filter orientations and spread have been specified
% explicitly
filterOrient = cell2mat(norient);
thetaSigma = dThetaOnSigma; % Use dThetaOnSigma directly as thetaSigma
norient = length(filterOrient);
else % Usual setup with filters evenly oriented
filterOrient = [0 : pi/norient : pi-pi/norient];
% Calculate the standard deviation of the angular Gaussian function
% used to construct filters in the frequency plane.
thetaSigma = pi/norient/dThetaOnSigma;
end
% Double up all the filter orientations by adding another set offset by
% pi. This allows us to see the overall orientation coverage of the
% filters a bit more easily.
filterOrient = [filterOrient filterOrient+pi];
% Pre-compute some stuff to speed up filter construction
% 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); % Normalised radius (frequency) values 0.0 - 0.5
% Get rid of the 0 radius value in the middle so that taking the log of
% the radius will not cause trouble.
radius(fix(rows/2+1),fix(cols/2+1)) = 1;
theta = atan2(-y,x); % Matrix values contain polar angle.
% (note -ve y is used to give +ve
% anti-clockwise angles)
sintheta = sin(theta);
costheta = cos(theta);
clear x; clear y; clear theta; % save a little memory
% Define a low-pass filter that is as large as possible, yet falls away to zero
% at the boundaries. All log Gabor filters are multiplied by this to ensure
% that filters are as similar as possible across orientations (Eliminate the
% extra frequencies at the 'corners' of the FFT)
lp = fftshift(lowpassfilter([rows,cols],.45,10)); % Radius .4, 'sharpness' 10
% The main loop...
filtersum = zeros(rows,cols);
for o = 1:2*norient, % For each orientation.
angl = filterOrient(o);
wavelength = minWaveLength; % Initialize filter wavelength.
% Compute filter data specific to this orientation
% For each point in the filter matrix calculate the angular distance from the
% specified filter orientation. To overcome the angular wrap-around problem
% sine difference and cosine difference values are first computed and then
% the atan2 function is used to determine angular distance.
ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.
dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.
dtheta = abs(atan2(ds,dc)); % Absolute angular distance.
if ~dThetaOnSigma % If set to 0 use cosine angular weight spread
% function. (I do not think this is a good spread function)
dtheta = min(dtheta*norient/2,pi);
spread = (cos(dtheta)+1)/2;
else % Use a Gaussian angular spread function
spread = exp((-dtheta.^2) / (2 * thetaSigma^2));
end
for s = 1:nscale, % For each scale.
% Construct the filter - first calculate the radial filter component.
fo = 1.0/wavelength; % Centre frequency of filter.
logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2));
logGabor(round(rows/2+1),round(cols/2+1)) = 0; % Set value at center of the filter
% back to zero (undo the radius fudge).
logGabor = logGabor.*lp; % Apply low-pass filter
Ffilter{s,o} = logGabor .* spread; % Multiply by the angular
% spread to get the filter.
filtersum = filtersum + Ffilter{s,o}.^2;
Efilter{s,o} = ifftshift(real(ifft2(fftshift(Ffilter{s,o}))));
Ofilter{s,o} = ifftshift(imag(ifft2(fftshift(Ffilter{s,o}))));
wavelength = wavelength*mult;
end
end
% Plot sum of filters and slices radially and tangentially
figure(1), clf, show(filtersum,1), title('sum of filters');
figure(2), clf
subplot(2,1,1), plot(filtersum(round(rows/2+1),:))
title('radial slice through sum of filters');
ang = [0:pi/32:2*pi];
r = rows/4;
tslice = improfile(filtersum,r*cos(ang)+cols/2,r*sin(ang)+rows/2);
subplot(2,1,2), plot(tslice), axis([0 length(tslice) 0 1.1*max(tslice)]);
title('tangential slice through sum of filters at f = 0.25');
% Plot Even and Odd filters at the largest and smallest scales
h = figure(3); clf
set(h,'name',sprintf('Filters: Wavelenth = %.2f',minWaveLength));
subplot(3,2,1), surfl(Efilter{1,1}), shading interp, colormap(gray),
title('Even Filter');
subplot(3,2,2), surfl(Ofilter{1,1}), shading interp, colormap(gray)
title('Odd Filter');
subplot(3,2,3),imagesc(Efilter{1,1}), axis image, colormap(gray)
subplot(3,2,4),imagesc(Ofilter{1,1}), axis image, colormap(gray)
subplot(3,2,5),imagesc(Ffilter{1,1}), axis image, colormap(gray)
title('Frequency Domain');
h = figure(4); clf
set(h,'name',sprintf('Filters: Wavelenth = %.2f',minWaveLength*mult^(nscale-1)));
subplot(3,2,1), surfl(Efilter{nscale,1}), shading interp, colormap(gray)
title('Even Filter');
subplot(3,2,2), surfl(Ofilter{nscale,1}), shading interp, colormap(gray)
title('Odd Filter');
subplot(3,2,3),imagesc(Efilter{nscale,1}), axis image, colormap(gray)
subplot(3,2,4),imagesc(Ofilter{nscale,1}), axis image, colormap(gray)
subplot(3,2,5),imagesc(Ffilter{nscale,1}), axis image, colormap(gray)
title('Frequency Domain');
|
github
|
jacksky64/imageProcessing-master
|
spatialgabor.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/spatialgabor.m
| 2,644 |
utf_8
|
0d56aa13789e5563961e97238d519790
|
% SPATIALGABOR - applies single oriented gabor filter to an image
%
% Usage:
% [Eim, Oim, Aim] = spatialgabor(im, wavelength, angle, kx, ky, showfilter)
%
% Arguments:
% im - Image to be processed.
% wavelength - Wavelength in pixels of Gabor filter to construct
% angle - Angle of filter in degrees. An angle of 0 gives a
% filter that responds to vertical features.
% kx, ky - Scale factors specifying the filter sigma relative
% to the wavelength of the filter. This is done so
% that the shapes of the filters are invariant to the
% scale. kx controls the sigma in the x direction
% which is along the filter, and hence controls the
% bandwidth of the filter. ky controls the sigma
% across the filter and hence controls the
% orientational selectivity of the filter. A value of
% 0.5 for both kx and ky is a good starting point.
% showfilter - An optional flag 0/1. When set an image of the
% even filter is displayed for inspection.
%
% Returns:
% Eim - Result from filtering with the even (cosine) Gabor filter
% Oim - Result from filtering with the odd (sine) Gabor filter
% Aim - Amplitude image = sqrt(Eim.^2 + Oim.^2)
%
% 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
%
% October 2006
function [Eim, Oim, Aim] = spatialgabor(im, wavelength, angle, kx, ky, showfilter)
if nargin == 5
showfilter = 0;
end
im = double(im);
[rows, cols] = size(im);
newim = zeros(rows,cols);
% Construct even and odd Gabor filters
sigmax = wavelength*kx;
sigmay = wavelength*ky;
sze = round(3*max(sigmax,sigmay));
[x,y] = meshgrid(-sze:sze);
evenFilter = exp(-(x.^2/sigmax^2 + y.^2/sigmay^2)/2)...
.*cos(2*pi*(1/wavelength)*x);
oddFilter = exp(-(x.^2/sigmax^2 + y.^2/sigmay^2)/2)...
.*sin(2*pi*(1/wavelength)*x);
evenFilter = imrotate(evenFilter, angle, 'bilinear');
oddFilter = imrotate(oddFilter, angle, 'bilinear');
% Do the filtering
Eim = filter2(evenFilter,im); % Even filter result
Oim = filter2(oddFilter,im); % Odd filter result
Aim = sqrt(Eim.^2 + Oim.^2); % Amplitude
if showfilter % Display filter for inspection
figure(1), imshow(evenFilter,[]); title('filter');
end
|
github
|
jacksky64/imageProcessing-master
|
phasecong.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/phasecong.m
| 16,644 |
utf_8
|
693c5ec683ef5ce8c816379185261bf7
|
% PHASECONG - Computes phase congruency on an image.
%
% Usage: [pc or ft] = phasecong(im)
%
% This function calculates the PC_2 measure of phase congruency.
% For maximum speed the input image should be square and have a
% size that is a power of 2, but the code will operate on images
% of arbitrary size.
%
%
% Returned values:
% pc - Phase congruency image (values between 0 and 1)
% or - Orientation image. Provides orientation in which
% local energy is a maximum in in degrees (0-180),
% angles positive anti-clockwise.
% ft - A complex valued image giving the weighted mean
% phase angle at every point in the image for the
% orientation having maximum energy. Use the
% function DISPFEAT to display this data.
%
% Parameters:
% im - A greyscale image to be processed.
%
% You can also specify numerous optional parameters. See the code to find
% out what they are. The convolutions are done via the FFT. Many of the
% parameters relate to the specification of the filters in the frequency
% plane. Default values for parameters are set within the file rather than
% being required as arguments because they rarely need to be changed - nor
% are they very critical. However, you may want to experiment with
% specifying/editing the values of `nscales' and `noiseCompFactor'.
%
% Note this phase congruency code is very computationally expensive and uses
% *lots* of memory.
%
%
% Example MATLAB session:
%
% >> im = imread('picci.tif');
% >> image(im); % Display the image
% >> [pc or ft] = phasecong(im);
% >> imagesc(pc), colormap(gray); % Display the phase congruency image
%
%
% To convert the phase congruency image to an edge map (with my usual parameters):
%
% >> nm = nonmaxsup(pc, or, 1.5); % Non-maxima suppression.
% The parameter 1.5 can result in edges more than 1 pixel wide but helps
% in picking up `broad' maxima.
% >> edgim = hysthresh(nm, 0.4, 0.2); % Hysteresis thresholding.
% >> edgeim = bwmorph(edgim,'skel',Inf); % Skeletonize the edgemap to fix
% % the non-maximal suppression.
% >> imagesc(edgeim), colormap(gray);
%
%
% To display the different feature types present in your image use:
%
% >> dispfeat(ft,edgim);
%
% With a small amount of editing the code can be modified to calculate
% a dimensionless measure of local symmetry in the image. The basis
% of this is that one looks for points in the image where the local
% phase is 90 or 270 degrees (the symmetric points in the cycle).
% Editing instructions are within the code.
%
% Notes on filter settings to obtain even coverage of the spectrum
% dthetaOnSigma 1.5
% sigmaOnf .85 mult 1.3
% sigmaOnf .75 mult 1.6 (bandwidth ~1 octave)
% sigmaOnf .65 mult 2.1
% sigmaOnf .55 mult 3 (bandwidth ~2 octaves)
%
% References:
%
% Peter Kovesi, "Image Features From Phase Congruency". Videre: A
% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,
% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html
% Copyright (c) 1996-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.
% Original Version written April 1996
% Noise compensation corrected. August 1998
% Noise compensation corrected. October 1998 - Again!!!
% Modified to operate on non-square images of arbitrary size. September 1999
% Modified to return feature type image. May 2001
function[phaseCongruency,orientation, featType]=phasecong(im, nscale, norient, ...
minWaveLength, mult, ...
sigmaOnf, dThetaOnSigma, ...
k, cutOff)
sze = size(im);
if nargin < 2
nscale = 3; % Number of wavelet scales.
end
if nargin < 3
norient = 6; % Number of filter orientations.
end
if nargin < 4
minWaveLength = 3; % Wavelength of smallest scale filter.
end
if nargin < 5
mult = 2; % Scaling factor between successive filters.
end
if nargin < 6
sigmaOnf = 0.55; % Ratio of the standard deviation of the
% Gaussian describing the log Gabor filter's transfer function
% in the frequency domain to the filter center frequency.
end
if nargin < 7
dThetaOnSigma = 1.7; % Ratio of angular interval between filter orientations
% and the standard deviation of the angular Gaussian
% function used to construct filters in the
% freq. plane.
end
if nargin < 8
k = 3.0; % No of standard deviations of the noise energy beyond the
% mean at which we set the noise threshold point.
% standard deviation to its maximum effect
% on Energy.
end
if nargin < 9
cutOff = 0.4; % The fractional measure of frequency spread
% below which phase congruency values get penalized.
end
g = 10; % Controls the sharpness of the transition in the sigmoid
% function used to weight phase congruency for frequency
% spread.
epsilon = .0001; % Used to prevent division by zero.
thetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the
% angular Gaussian function used to
% construct filters in the freq. plane.
imagefft = fft2(im); % Fourier transform of image
sze = size(imagefft);
rows = sze(1);
cols = sze(2);
zero = zeros(sze);
totalEnergy = zero; % Matrix for accumulating weighted phase
% congruency values (energy).
totalSumAn = zero; % Matrix for accumulating filter response
% amplitude values.
orientation = zero; % Matrix storing orientation with greatest
% energy for each pixel.
estMeanE2n = [];
% Pre-compute some stuff to speed up filter construction
x = ones(rows,1) * (-cols/2 : (cols/2 - 1))/(cols/2);
y = (-rows/2 : (rows/2 - 1))' * ones(1,cols)/(rows/2);
radius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius from centre.
radius(round(rows/2+1),round(cols/2+1)) = 1; % Get rid of the 0 radius value in the middle
% so that taking the log of the radius will
% not cause trouble.
theta = atan2(-y,x); % Matrix values contain polar angle.
% (note -ve y is used to give +ve
% anti-clockwise angles)
sintheta = sin(theta);
costheta = cos(theta);
clear x; clear y; clear theta; % save a little memory
% The main loop...
for o = 1:norient, % For each orientation.
disp(['Processing orientation ' num2str(o)]);
angl = (o-1)*pi/norient; % Calculate filter angle.
wavelength = minWaveLength; % Initialize filter wavelength.
sumE_ThisOrient = zero; % Initialize accumulator matrices.
sumO_ThisOrient = zero;
sumAn_ThisOrient = zero;
Energy_ThisOrient = zero;
EOArray = []; % Array of complex convolution images - one for each scale.
ifftFilterArray = []; % Array of inverse FFTs of filters
% Pre-compute filter data specific to this orientation
% For each point in the filter matrix calculate the angular distance from the
% specified filter orientation. To overcome the angular wrap-around problem
% sine difference and cosine difference values are first computed and then
% the atan2 function is used to determine angular distance.
ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.
dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.
dtheta = abs(atan2(ds,dc)); % Absolute angular distance.
spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the angular filter component.
for s = 1:nscale, % For each scale.
% Construct the filter - first calculate the radial filter component.
fo = 1.0/wavelength; % Centre frequency of filter.
rfo = fo/0.5; % Normalised radius from centre of frequency plane
% corresponding to fo.
logGabor = exp((-(log(radius/rfo)).^2) / (2 * log(sigmaOnf)^2));
logGabor(round(rows/2+1),round(cols/2+1)) = 0; % Set the value at the center of the filter
% back to zero (undo the radius fudge).
filter = logGabor .* spread; % Multiply by the angular spread to get the filter.
filter = fftshift(filter); % Swap quadrants to move zero frequency
% to the corners.
ifftFilt = real(ifft2(filter))*sqrt(rows*cols); % Note rescaling to match power
ifftFilterArray = [ifftFilterArray ifftFilt]; % record ifft2 of filter
% Convolve image with even and odd filters returning the result in EO
EOfft = imagefft .* filter; % Do the convolution.
EO = ifft2(EOfft); % Back transform.
EOArray = [EOArray, EO]; % Record convolution result
An = abs(EO); % Amplitude of even & odd filter response.
sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses.
sumE_ThisOrient = sumE_ThisOrient + real(EO); % Sum of even filter convolution results.
sumO_ThisOrient = sumO_ThisOrient + imag(EO); % Sum of odd filter convolution results.
if s == 1 % Record the maximum An over all scales
maxAn = An;
else
maxAn = max(maxAn, An);
end
if s==1
EM_n = sum(sum(filter.^2)); % Record mean squared filter value at smallest
end % scale. This is used for noise estimation.
wavelength = wavelength * mult; % Finally calculate Wavelength of next filter
end % ... and process the next scale
% Get weighted mean filter response vector, this gives the weighted mean phase angle.
XEnergy = sqrt(sumE_ThisOrient.^2 + sumO_ThisOrient.^2) + epsilon;
MeanE = sumE_ThisOrient ./ XEnergy;
MeanO = sumO_ThisOrient ./ XEnergy;
% Now calculate An(cos(phase_deviation) - | sin(phase_deviation)) | by using
% dot and cross products between the weighted mean filter response vector and
% the individual filter response vectors at each scale. This quantity is
% phase congruency multiplied by An, which we call energy.
for s = 1:nscale,
EO = submat(EOArray,s,cols); % Extract even and odd filter
E = real(EO); O = imag(EO);
Energy_ThisOrient = Energy_ThisOrient ...
+ E.*MeanE + O.*MeanO - abs(E.*MeanO - O.*MeanE);
end
% Note: To calculate the phase symmetry measure replace the for loop above
% with the following loop. (The calculation of MeanE, MeanO, sumE_ThisOrient
% and sumO_ThisOrient can also be omitted). It is suggested that the value
% of nscale is increased (to say, 5 for a 256x256 image) and that cutOff is
% set to 0 to eliminate weighting for frequency spread.
% for s = 1:nscale,
% Energy_ThisOrient = Energy_ThisOrient ...
% + abs(real(submat(EOArray,s,cols))) - abs(imag(submat(EOArray,s,cols)));
% end
% Compensate for noise
% We estimate the noise power from the energy squared response at the smallest scale.
% If the noise is Gaussian the energy squared will have a Chi-squared 2DOF pdf.
% We calculate the median energy squared response as this is a robust statistic.
% From this we estimate the mean.
% The estimate of noise power is obtained by dividing the mean squared energy value
% by the mean squared filter value
medianE2n = median(reshape(abs(submat(EOArray,1,cols)).^2,1,rows*cols));
meanE2n = -medianE2n/log(0.5);
estMeanE2n = [estMeanE2n meanE2n];
noisePower = meanE2n/EM_n; % Estimate of noise power.
% Now estimate the total energy^2 due to noise
% Estimate for sum(An^2) + sum(Ai.*Aj.*(cphi.*cphj + sphi.*sphj))
EstSumAn2 = zero;
for s = 1:nscale
EstSumAn2 = EstSumAn2+submat(ifftFilterArray,s,cols).^2;
end
EstSumAiAj = zero;
for si = 1:(nscale-1)
for sj = (si+1):nscale
EstSumAiAj = EstSumAiAj + submat(ifftFilterArray,si,cols).*submat(ifftFilterArray,sj,cols);
end
end
EstNoiseEnergy2 = 2*noisePower*sum(sum(EstSumAn2)) + 4*noisePower*sum(sum(EstSumAiAj));
tau = sqrt(EstNoiseEnergy2/2); % Rayleigh parameter
EstNoiseEnergy = tau*sqrt(pi/2); % Expected value of noise energy
EstNoiseEnergySigma = sqrt( (2-pi/2)*tau^2 );
T = EstNoiseEnergy + k*EstNoiseEnergySigma; % Noise threshold
% The estimated noise effect calculated above is only valid for the PC_1 measure.
% The PC_2 measure does not lend itself readily to the same analysis. However
% empirically it seems that the noise effect is overestimated roughly by a factor
% of 1.7 for the filter parameters used here.
T = T/1.7; % Empirical rescaling of the estimated noise effect to
% suit the PC_2 phase congruency measure
Energy_ThisOrient = max(Energy_ThisOrient - T, zero); % Apply noise threshold
% Form weighting that penalizes frequency distributions that are particularly
% narrow.
% Calculate fractional 'width' of the frequencies present by taking
% the sum of the filter response amplitudes and dividing by the maximum
% amplitude at each point on the image.
width = sumAn_ThisOrient ./ (maxAn + epsilon) / nscale;
% Now calculate the sigmoidal weighting function for this orientation.
weight = 1.0 ./ (1 + exp( (cutOff - width)*g));
% Apply weighting
Energy_ThisOrient = weight.*Energy_ThisOrient;
% Update accumulator matrix for sumAn and totalEnergy
totalSumAn = totalSumAn + sumAn_ThisOrient;
totalEnergy = totalEnergy + Energy_ThisOrient;
% Update orientation matrix by finding image points where the energy in this
% orientation is greater than in any previous orientation (the change matrix)
% and then replacing these elements in the orientation matrix with the
% current orientation number.
if(o == 1),
maxEnergy = Energy_ThisOrient;
featType = E + i*O;
else
change = Energy_ThisOrient > maxEnergy;
orientation = (o - 1).*change + orientation.*(~change);
featType = (E+i*O).*change + featType.*(~change);
maxEnergy = max(maxEnergy, Energy_ThisOrient);
end
end % For each orientation
disp('Mean Energy squared values recorded with smallest scale filter at each orientation');
disp(estMeanE2n);
% Display results
%imagesc(totalEnergy), axis image, title('total energy');
%disp('Hit any key to continue '); pause
%imagesc(totalSumAn), axis image, title('total sumAn');
%disp('Hit any key to continue '); pause
% Normalize totalEnergy by the totalSumAn to obtain phase congruency
phaseCongruency = totalEnergy ./ (totalSumAn + epsilon);
%imagesc(phaseCongruency), axis image, title('phase congruency');
% Convert orientation matrix values to degrees
orientation = orientation * (180 / norient);
featType = featType*i; % Rotate feature phase angles by 90deg so that 0
% phase corresponds to a step edge (this is a
% fudge I must have something the wrong way
% around somewhere)
%
% SUBMAT
%
% Function to extract the i'th sub-matrix 'cols' wide from a large
% matrix composed of several matricies. The large matrix is used in
% lieu of an array of matricies
function a = submat(big,i,cols)
a = big(:,((i-1)*cols+1):(i*cols));
|
github
|
jacksky64/imageProcessing-master
|
convexplpiccis.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/PhaseCongruency/Docs/convexplpiccis.m
| 2,884 |
utf_8
|
c73812719db08612eddaff3437e2413b
|
% Function to create images for the convolution explanation
function [spread, logGabor, gfilter] = convexplpiccis
rows = 200; cols = 200;
wavelength = 16;
sigmaOnf = 0.65;
angl = 1;
thetaSigma = 0.7;
[x,y] = meshgrid([-cols/2:(cols/2-1)]/cols,...
[-rows/2:(rows/2-1)]/rows);
radius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius
% values ranging from 0 at the centre to
% 0.5 at the boundary.
radius(rows/2+1, cols/2+1) = 1; % Get rid of the 0 radius value in the middle
% so that taking the log of the radius will
% not cause trouble.
fo = 1.0/wavelength; % Centre frequency of filter.
% The following implements the log-gabor transfer function.
logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2));
logGabor(rows/2+1, cols/2+1) = 0; % Set the value at the 0 frequency point
% of the filter back to zero
% (undo the radius fudge).
show(logGabor,1), imwritesc(logGabor, 'loggabor.jpg');
lp = lowpassfilter([rows,cols],.4,10); % Radius .4, 'sharpness' 10
lp = fftshift(lp);
logGabor = logGabor.*lp; % Apply low-pass filter
show(lp,8);
imwritesc(lp, 'lp.jpg');
show(logGabor,2), imwritesc(logGabor, 'loggaborlp.jpg');
theta = atan2(-y,x); % Matrix values contain polar angle.
% (note -ve y is used to give +ve
% anti-clockwise angles)
sintheta = sin(theta);
costheta = cos(theta);
% For each point in the filter matrix calculate the angular distance from the
% specified filter orientation. To overcome the angular wrap-around problem
% sine difference and cosine difference values are first computed and then
% the atan2 function is used to determine angular distance.
ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.
dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.
dtheta = abs(atan2(ds,dc)); % Absolute angular distance.
spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the angular
% filter component.
gfilter = spread.*logGabor;
show(spread,3), imwritesc(spread, 'spread.jpg');
show(gfilter,4), imwritesc(gfilter, 'filter.jpg');
EO = ifft2(fftshift(gfilter));
EO = fftshift(EO);
imwritesc(real(EO),'realEO.jpg');
imwritesc(imag(EO),'imagEO.jpg');
figure(9),surfl(real(EO)); shading interp, colormap(copper)
figure(10),surfl(imag(EO));shading interp, colormap(copper)
|
github
|
jacksky64/imageProcessing-master
|
needleplotgrad.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapelet/needleplotgrad.m
| 758 |
utf_8
|
c0bb3b31a34d8fc8cf86c384b5f2da52
|
% NEEDLEPLOTGRAD - needleplot of 3D surface from gradient data
%
% Usage: needleplotgrad(dzdx, dzdy, len, spacing)
%
% dzdx, dzdy - 2D arrays of gradient with respect to x and y.
% len - length of needle to be plotted.
% spacing - sub-sampling interval to be used in the
% gradient data. (Plotting every point
% is typically not feasible).
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk @ csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% July 2003
function needleplotgrad(dzdx, dzdy, len, spacing)
[slant, tilt] = grad2slanttilt(dzdx, dzdy);
needleplotst(slant, tilt, len, spacing);
|
github
|
jacksky64/imageProcessing-master
|
needleplotst.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapelet/needleplotst.m
| 1,443 |
utf_8
|
86c5bdaa284362a76e6260f265211832
|
% NEEDLEPLOTST - needleplot of 3D surface from slant tilt data
%
% Usage: needleplotst(slant, tilt, len, spacing)
%
% slant, tilt - 2D arrays of slant and tilt values
% len - length of needle to be plotted
% spacing - sub-sampling interval to be used in the
% slant and tilt data. (Plotting every point
% is typically not feasible)
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk @ csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% July 2003
function needleplotst(slant, tilt, len, spacing)
lw = 1; % linewidth
if ~all(size(slant) == size(tilt))
error('slant matrix must have same dimensions as tilt');
end
% Subsample the slant and tilt matrices according to the specified spacing
s_slant = slant(1:spacing:end, 1:spacing:end);
s_tilt = tilt(1:spacing:end, 1:spacing:end);
[s_rows, s_cols] = size(s_slant);
projlen = len*sin(s_slant); % projected length of each needle onto xy plane
dx = projlen.*cos(s_tilt);
dy = projlen.*sin(s_tilt);
clf
for r = 1:s_rows
for c = 1:s_cols
x = (c-1)*spacing+1;
y = (r-1)*spacing+1;
h = plot(x,y,'bo'); hold on
set(h,'MarkerSize',2);
line([x x+dx(r,c)],[y y+dy(r,c)],'color',[0 0 1],'linewidth',lw);
end
end
axis('equal')
hold('off')
|
github
|
jacksky64/imageProcessing-master
|
grad2slanttilt.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapelet/grad2slanttilt.m
| 1,097 |
utf_8
|
051e7b40ca4bf4dbefca92a57a98e63f
|
% GRAD2SLANTTILT - gradient in x y to slant tilt
%
% Function to convert a matrix of surface gradients to
% slant and tilt values.
%
% Usage: [slant, tilt] = grad2slanttilt(dzdx, dzdy)
%
% Copyright (c) 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 2003
function [slant, tilt] = grad2slanttilt(dzdx, dzdy)
if ~all(size(dzdx) == size(dzdy))
error('dzdx must have same dimensions as dzdy');
end
tilt = atan2(-dzdy, -dzdx);
gradmag = sqrt(dzdx.^2 + dzdy.^2)+eps;
slant = atan(gradmag);
|
github
|
jacksky64/imageProcessing-master
|
testp.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapelet/testp.m
| 2,436 |
utf_8
|
9568a363ea5a8f8a4a4d28e4b6bdb4ff
|
% Function to make ramps test surface for shape from shapelet testing
%
% Usage:
% function [z,s,t] = testp(noise)
%
% Arguments:
% noise - An optional parameter specifying the standard
% deviation of Gaussian noise to add to the slant and tilt
% values.
% Returns;
% z - A 2D array of surface height values which can be
% viewed using surf(z)
% s,t - Corresponding arrays of slant and tilt angles in
% radians for each point on the surface.
% Copyright (c) 2003-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.
% July 2003 - Original version
% August 2005 - Changes to accommodate Octave
% September 2008 - Needle plot reinstated for Octave
% January 2013 - Separate code path for Octave no longer needed (random()
% is part of statistics package)
function [z,s,t] = testp(noise)
if nargin == 0
noise = 0;
end
p1 = [zeros(1,15) [0:.2:10] zeros(1,15)];
p2 = zeros(1,length(p1));
n = ceil(length(p1)/2);
p3 = [1:n n:-1:1]/n*6;
p3 = p3(1:length(p1));
z = [ones(15,1)*p2
ones(15,1)*p1
ones(15,1)*p3
ones(15,1)*p2];
figure(1); clf;% surfl(z), shading interp; colormap(copper);
surf(z); % colormap(white);
[dx, dy] = gradient(z);
[s,t] = grad2slanttilt(dx,dy);
[rows,cols] = size(s);
if noise
t = t + random('Normal',0,noise,rows,cols); % add noise to tilt
s = s + random('Normal',0,noise,rows,cols); % ... and slant
% constrain noisy slant values to 0-pi
s = max(s, 0);
s = min(s, pi/2-0.05); % -0.05 to avoid infinite gradient
end
figure(2),needleplotst(s,t,5,2), axis('off')
|
github
|
jacksky64/imageProcessing-master
|
frankotchellappa.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapelet/frankotchellappa.m
| 2,612 |
utf_8
|
56bcc95bb901b40d8eee5f4e8a533b91
|
% FRANKOTCHELLAPPA - Generates integrable surface from gradients
%
% An implementation of Frankot and Chellappa'a algorithm for constructing
% an integrable surface from gradient information.
%
% Usage: z = frankotchellappa(dzdx,dzdy)
%
% Arguments: dzdx, - 2D matrices specifying a grid of gradients of z
% dzdy with respect to x and y.
%
% Returns: z - Inferred surface heights.
% Reference:
%
% Robert T. Frankot and Rama Chellappa
% A Method for Enforcing Integrability in Shape from Shading
% IEEE PAMI Vol 10, No 4 July 1988. pp 439-451
%
% Note this code just implements the surface integration component of the
% paper (Equation 21 in the paper). It does not implement their shape from
% shading algorithm.
% Copyright (c) 2004 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 2004
function z = frankotchellappa(dzdx,dzdy)
if ~all(size(dzdx) == size(dzdy))
error('Gradient matrices must match');
end
[rows,cols] = size(dzdx);
% The following sets up matrices specifying frequencies in the x and y
% directions corresponding to the Fourier transforms of the gradient
% data. They range from -0.5 cycles/pixel to + 0.5 cycles/pixel. The
% fiddly bits in the line below give the appropriate result depending on
% whether there are an even or odd number of rows and columns
[wx, wy] = 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 zero frequency at the appropriate edge
wx = ifftshift(wx); wy = ifftshift(wy);
DZDX = fft2(dzdx); % Fourier transforms of gradients
DZDY = fft2(dzdy);
% Integrate in the frequency domain by phase shifting by pi/2 and
% weighting the Fourier coefficients by their frequencies in x and y and
% then dividing by the squared frequency. eps is added to the
% denominator to avoid division by 0.
Z = (-j*wx.*DZDX -j*wy.*DZDY)./(wx.^2 + wy.^2 + eps); % Equation 21
z = real(ifft2(Z)); % Reconstruction
|
github
|
jacksky64/imageProcessing-master
|
slanttilt2grad.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapelet/slanttilt2grad.m
| 1,090 |
utf_8
|
7fb013bc78a565346b80337d3535d16d
|
% SLANTTILT2GRAD - slant and tilt to gradient in x y
%
% Function to convert a matrix of slant and tilt values to
% surface gradients.
%
% Usage: [dzdx, dzdy] = slanttilt2grad(slant, tilt)
%
% Copyright (c) 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 2003
function [dzdx, dzdy] = slanttilt2grad(slant, tilt)
if ~all(size(slant) == size(tilt))
error('slant matrix must have same dimensions as tilt');
end
gradmag = tan(slant);
dzdx = -gradmag.*cos(tilt);
dzdy = -gradmag.*sin(tilt);
|
github
|
jacksky64/imageProcessing-master
|
shapeletsurf.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Shapelet/shapeletsurf.m
| 9,292 |
utf_8
|
ab9b782a8bb8c8d669105b6ffe6dba0c
|
% SHAPELETSURF - reconstructs surface from surface normals using shapelets
%
% Function reconstructs an estimate of a surface from its surface normals by
% correlating the surface normals with that those of a bank of shapelet
% basis functions. The correlation results are summed to produce the
% reconstruction. The sumation of shapelet basis functions results in an
% implicit integration of the surface while enforcing surface continuity.
%
% Note that the reconstruction is only valid up to a scale factor. However
% the reconstruction process is very robust to noise and to missing data
% values. Reconstructions (up to positive/negative shape ambiguity) are
% possible where there is an ambiguity of pi in tilt values. Low quality
% reconstructions are also possible with just slant, or just tilt data
% alone.
%
%
% Usage:
% recsurf = shapletsurf(slant, tilt, nscales, minradius, mult, opt)
% 6 1 2
% Arguments:
% slant - 2D array of surface slant values across image.
% tilt - 2D array of surface tilt values.
% nscales - number of shapelet scales to use.
% minsigma - sigma of smallest scale Gaussian shapelet.
% mult - scaling factor between successive shapelets.
%
% opt can be the string:
% 'slanttilt' - reconstruct using both slant and tilt (default).
% 'tiltamb' - reconstruct assuming tilt ambiguity of pi.
% 'slant' - reconstruct with slant only.
% 'tilt' - reconstruct with tilt only.
%
% Returns:
% recsurf - reconstructed surface.
%
% Remember when viewing the surface you should use
% >> axis ij
% So that the surface corresponds to the image slant and tilt axes
%
% References:
%
% Peter Kovesi, "Surface Normals to Surfaces via Shapelets"
% Proceedings Australia-Japan Advanced Workshop on Computer Vision
% Adelaide, 9-11 September 2003
%
% Peter Kovesi, "Shapelets Correlated with Surface Normals Produce
% Surfaces". Technical Report 03-003, October 2003.
% http://www.csse.uwa.edu.au/~pk/research/pkpapers/shapelets-03-002.pdf
% Copyright (c) 2003-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.
% July 2003 - Original version.
% September 2003 - Correction to reconstruction with tilt ambiguity.
% October 2003 - Changed to use Gaussian shapelets.
% February 2004 - Convolutions done via fft for speed.
% March 2004 - Padding of slant and tilt data to accommodate large filters.
function recsurf = shapeletsurf(varargin)
[slant, tilt, nscales, minsigma, mult, opt] = checkargs(varargin(:));
if strcmp(opt,'tiltamb') % If we have an ambiguity of pi in the tilt
tilt = tilt*2; % work with doubled angles.
end
[rows,cols] = size(slant);
% Check size of largest filter and, if necessary, pad slant and tilt
% data with zeros so that the largest filter can be accommodated.
% If this is not done wraparound in the convolutions via the FFT produce
% artifacts in the reconstruction.
% Treat max size as +- 3 sigma
maxsize = ceil(6*minsigma*mult^(nscales-1));
paddingapplied = 0;
if rows < maxsize | cols < maxsize % padding needed
paddingapplied = 1;
rowpad = max(0,round(maxsize-rows));
colpad = max(0,round(maxsize-cols));
fprintf('Warning: To accommodate the largest filter size the\n');
fprintf('slant and tilt data is being padded from %dx%d to %dx%d \n', ...
rows,cols, rows+rowpad, cols+colpad);
slant = [slant zeros(rows, colpad)
zeros(rowpad, cols+colpad)];
tilt = [tilt zeros(rows, colpad)
zeros(rowpad, cols+colpad)];
origrows = rows; origcols = cols; % Remember original size.
[rows,cols] = size(slant); % Update current size.
end
% Precompute some values for speed of execution. Note that because we
% generally want to use shapelets at quite large scales relative to the
% size of the image correlations are done in the frequency domain for
% speed. (Note that in the code below the conjugate of the fft is used
% because we want the correlation, not convolution.)
surfgrad = tan(slant); SURFGRAD= fft2(surfgrad);
sintilt = sin(tilt); SINTILT = fft2(sintilt);
costilt = cos(tilt); COSTILT = fft2(costilt);
SURFGRADSINTILT = fft2(surfgrad.*sintilt);
SURFGRADCOSTILT = fft2(surfgrad.*costilt);
for s = 1:nscales
% fprintf('scale %d out of %d\r',s,nscales);
% Use a Gaussian filter shape as the shapelet basis function
% as the phase distortion in the reconstruction should be zero.
f = gaussianf(minsigma*mult^(s-1), rows, cols);
[fdx,fdy] = gradient(f); % filter gradients
[fslant,ftilt] = grad2slanttilt(fdx,fdy); % filter slants and tilts
if strcmp(opt,'tiltamb')
ftilt = ftilt*2;
end
% Now perform the correlations (via the fft) as required depending
% on the options selected.
sinftilt = sin(ftilt);
cosftilt = cos(ftilt);
filtgrad = tan(fslant);
filtgradsintilt = filtgrad.*sinftilt;
filtgradcostilt = filtgrad.*cosftilt;
if strcmp(opt,'slanttilt') % both slant and tilt data available
FILTGRADSINTILT = fft2(filtgrad.*sinftilt);
FILTGRADCOSTILT = fft2(filtgrad.*cosftilt);
fim{s} = real(ifft2(conj(FILTGRADCOSTILT) .* SURFGRADCOSTILT)) + ...
real(ifft2(conj(FILTGRADSINTILT) .* SURFGRADSINTILT));
elseif strcmp(opt,'tiltamb') % assume tilt ambiguity of pi
FILTGRADSINTILT = fft2(filtgrad.*sinftilt);
FILTGRADCOSTILT = fft2(filtgrad.*cosftilt);
FILTGRAD = fft2(filtgrad);
fim{s} = (real(ifft2(conj(FILTGRADCOSTILT) .* SURFGRADCOSTILT)) + ...
real(ifft2(conj(FILTGRADSINTILT) .* SURFGRADSINTILT)) + ...
real(ifft2(conj(FILTGRAD) .* SURFGRAD)))/2;
elseif strcmp(opt,'tilt'); % tilt only reconstruction
SINFTILT = fft2(sinftilt);
COSFTILT = fft2(cosftilt);
fim{s} = real(ifft2(conj(COSFTILT) .* COSTILT)) + ...
real(ifft2(conj(SINFTILT) .* SINTILT));
elseif strcmp(opt,'slant'); % just use slant and ignore tilt
FILTGRAD = fft2(filtgrad);
fim{s} = real(ifft2(conj(FILTGRAD) .* SURFGRAD));
end
end
% fprintf('\n');
% Reconstruct by adding filtered outputs
recsurf = zeros(size(slant));
for s = 1:nscales
recsurf = recsurf + fim{s};
end
if paddingapplied % result is padded - extract the bit we want.
recsurf = recsurf(1:origrows, 1:origcols);
end
%-------------------------------------------------------------------------
% Function to generate a Gaussian filter for use as a shapelet.
% Usage:
% f = gaussian(sigma, rows, cols)
%
% Arguments:
% sigma - standard deviation of Gaussian
% rows, cols - size of filter to create
function f = gaussianf(sigma, rows, cols)
[x,y] = meshgrid( [1:cols]-(fix(cols/2)+1), [1:rows]-(fix(rows/2)+1));
r = sqrt(x.^2 + y.^2);
f = fftshift(exp(-r.^2/(2*sigma^2)));
%--------------------------------------------------------------------------
% Function to check argument values and set defaults
function [slant, tilt, nscales, minradius, mult, opt] = checkargs(arg);
if length(arg)<5
error('too few arguments');
elseif length(arg)>6
error('too many arguments');
end
slant = arg{1};
tilt = arg{2};
nscales = arg{3};
minradius = arg{4};
mult = arg{5};
if length(arg) == 5
opt = 'slanttilt'; % Default is to assume both slant and tilt values
% are valid.
else
opt = arg{6};
end
if ~all(size(slant)==size(tilt))
error('slant and tilt matrices must match');
end
if nscales < 1
error('number of scales must be 1 or greater');
end
if minradius < .1
error('minimum radius of shapelet must be greater than .1');
end
if mult < 1
error('scaling factor between successive filters should be greater than 1');
end
|
github
|
jacksky64/imageProcessing-master
|
ridgefreq.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FingerPrints/ridgefreq.m
| 2,993 |
utf_8
|
06dee0fde68607594d459ca300e6d102
|
% RIDGEFREQ - Calculates a ridge frequency image
%
% Function to estimate the fingerprint ridge frequency across a
% fingerprint image. This is done by considering blocks of the image and
% determining a ridgecount within each block by a call to FREQEST.
%
% Usage:
% [freqim, medianfreq] = ridgefreq(im, mask, orientim, blksze, windsze, ...
% minWaveLength, maxWaveLength)
%
% Arguments:
% im - Image to be processed.
% mask - Mask defining ridge regions (obtained from RIDGESEGMENT)
% orientim - Ridge orientation image (obtained from RIDGORIENT)
% blksze - Size of image block to use (say 32)
% windsze - Window length used to identify peaks. This should be
% an odd integer, say 3 or 5.
% minWaveLength, maxWaveLength - Minimum and maximum ridge
% wavelengths, in pixels, considered acceptable.
%
% Returns:
% freqim - An image the same size as im with values set to
% the estimated ridge spatial frequency within each
% image block. If a ridge frequency cannot be
% found within a block, or cannot be found within the
% limits set by min and max Wavlength freqim is set
% to zeros within that block.
% medianfreq - Median frequency value evaluated over all the
% valid regions of the image.
%
% Suggested parameters for a 500dpi fingerprint image
% [freqim, medianfreq] = ridgefreq(im,orientim, 32, 5, 5, 15);
%
% I seem to find that the median frequency value is more useful as an
% input to RIDGEFILTER than the more detailed freqim. This is possibly
% due to deficiencies in FREQEST.
%
% See also: RIDGEORIENT, FREQEST, RIDGESEGMENT
% Reference:
% Hong, L., Wan, Y., and Jain, A. K. Fingerprint image enhancement:
% Algorithm and performance evaluation. IEEE Transactions on Pattern
% Analysis and Machine Intelligence 20, 8 (1998), 777 789.
% 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
%
% January 2005
function [freq, medianfreq] = ridgefreq(im, mask, orient, blksze, windsze, ...
minWaveLength, maxWaveLength)
[rows, cols] = size(im);
freq = zeros(size(im));
for r = 1:blksze:rows-blksze
for c = 1:blksze:cols-blksze
blkim = im(r:r+blksze-1, c:c+blksze-1);
blkor = orient(r:r+blksze-1, c:c+blksze-1);
freq(r:r+blksze-1,c:c+blksze-1) = ...
freqest(blkim, blkor, windsze, minWaveLength, maxWaveLength);
end
end
% Mask out frequencies calculated for non ridge regions
freq = freq.*mask;
% Find median freqency over all the valid regions of the image.
medianfreq = median(freq(find(freq>0)));
|
github
|
jacksky64/imageProcessing-master
|
freqest.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FingerPrints/freqest.m
| 3,637 |
utf_8
|
a4f96f1105673bbd0d6851306a9712c8
|
% FREQEST - Estimate fingerprint ridge frequency within image block
%
% Function to estimate the fingerprint ridge frequency within a small block
% of a fingerprint image. This function is used by RIDGEFREQ
%
% Usage:
% freqim = freqest(im, orientim, windsze, minWaveLength, maxWaveLength)
%
% Arguments:
% im - Image block to be processed.
% orientim - Ridge orientation image of image block.
% windsze - Window length used to identify peaks. This should be
% an odd integer, say 3 or 5.
% minWaveLength, maxWaveLength - Minimum and maximum ridge
% wavelengths, in pixels, considered acceptable.
%
% Returns:
% freqim - An image block the same size as im with all values
% set to the estimated ridge spatial frequency. If a
% ridge frequency cannot be found, or cannot be found
% within the limits set by min and max Wavlength
% freqim is set to zeros.
%
% Suggested parameters for a 500dpi fingerprint image
% freqim = freqest(im,orientim, 5, 5, 15);
%
% See also: RIDGEFREQ, RIDGEORIENT, RIDGESEGMENT
%
% Note I am not entirely satisfied with the output of this function.
% 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
%
% January 2005
function freqim = freqest(im, orientim, windsze, minWaveLength, maxWaveLength)
debug = 0;
[rows,cols] = size(im);
% Find mean orientation within the block. This is done by averaging the
% sines and cosines of the doubled angles before reconstructing the
% angle again. This avoids wraparound problems at the origin.
orientim = 2*orientim(:);
cosorient = mean(cos(orientim));
sinorient = mean(sin(orientim));
orient = atan2(sinorient,cosorient)/2;
% Rotate the image block so that the ridges are vertical
rotim = imrotate(im,orient/pi*180+90,'nearest', 'crop');
% Now crop the image so that the rotated image does not contain any
% invalid regions. This prevents the projection down the columns
% from being mucked up.
cropsze = fix(rows/sqrt(2)); offset = fix((rows-cropsze)/2);
rotim = rotim(offset:offset+cropsze, offset:offset+cropsze);
% Sum down the columns to get a projection of the grey values down
% the ridges.
proj = sum(rotim);
% Find peaks in projected grey values by performing a greyscale
% dilation and then finding where the dilation equals the original
% values.
dilation = ordfilt2(proj, windsze, ones(1,windsze));
maxpts = (dilation == proj) & (proj > mean(proj));
maxind = find(maxpts);
% Determine the spatial frequency of the ridges by divinding the
% distance between the 1st and last peaks by the (No of peaks-1). If no
% peaks are detected, or the wavelength is outside the allowed bounds,
% the frequency image is set to 0
if length(maxind) < 2
freqim = zeros(size(im));
else
NoOfPeaks = length(maxind);
waveLength = (maxind(end)-maxind(1))/(NoOfPeaks-1);
if waveLength > minWaveLength & waveLength < maxWaveLength
freqim = 1/waveLength * ones(size(im));
else
freqim = zeros(size(im));
end
end
if debug
show(im,1)
show(rotim,2);
figure(3), plot(proj), hold on
meanproj = mean(proj)
if length(maxind) < 2
fprintf('No peaks found\n');
else
plot(maxind,dilation(maxind),'r*'), hold off
waveLength = (maxind(end)-maxind(1))/(NoOfPeaks-1);
end
end
|
github
|
jacksky64/imageProcessing-master
|
ridgefilter.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FingerPrints/ridgefilter.m
| 4,770 |
utf_8
|
a6443447a69fa10919e580f23e30c264
|
% RIDGEFILTER - enhances fingerprint image via oriented filters
%
% Function to enhance fingerprint image via oriented filters
%
% Usage:
% newim = ridgefilter(im, orientim, freqim, kx, ky, showfilter)
%
% Arguments:
% im - Image to be processed.
% orientim - Ridge orientation image, obtained from RIDGEORIENT.
% freqim - Ridge frequency image, obtained from RIDGEFREQ.
% kx, ky - Scale factors specifying the filter sigma relative
% to the wavelength of the filter. This is done so
% that the shapes of the filters are invariant to the
% scale. kx controls the sigma in the x direction
% which is along the filter, and hence controls the
% bandwidth of the filter. ky controls the sigma
% across the filter and hence controls the
% orientational selectivity of the filter. A value of
% 0.5 for both kx and ky is a good starting point.
% showfilter - An optional flag 0/1. When set an image of the
% largest scale filter is displayed for inspection.
%
% Returns:
% newim - The enhanced image
%
% See also: RIDGEORIENT, RIDGEFREQ, RIDGESEGMENT
% Reference:
% Hong, L., Wan, Y., and Jain, A. K. Fingerprint image enhancement:
% Algorithm and performance evaluation. IEEE Transactions on Pattern
% Analysis and Machine Intelligence 20, 8 (1998), 777 789.
% 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
%
% January 2005
function newim = ridgefilter(im, orient, freq, kx, ky, showfilter)
if nargin == 5
showfilter = 0;
end
angleInc = 3; % Fixed angle increment between filter orientations in
% degrees. This should divide evenly into 180
im = double(im);
[rows, cols] = size(im);
newim = zeros(rows,cols);
[validr,validc] = find(freq > 0); % find where there is valid frequency data.
ind = sub2ind([rows,cols], validr, validc);
% Round the array of frequencies to the nearest 0.01 to reduce the
% number of distinct frequencies we have to deal with.
freq(ind) = round(freq(ind)*100)/100;
% Generate an array of the distinct frequencies present in the array
% freq
unfreq = unique(freq(ind));
% Generate a table, given the frequency value multiplied by 100 to obtain
% an integer index, returns the index within the unfreq array that it
% corresponds to
freqindex = ones(100,1);
for k = 1:length(unfreq)
freqindex(round(unfreq(k)*100)) = k;
end
% Generate filters corresponding to these distinct frequencies and
% orientations in 'angleInc' increments.
filter = cell(length(unfreq),180/angleInc);
sze = zeros(length(unfreq),1);
for k = 1:length(unfreq)
sigmax = 1/unfreq(k)*kx;
sigmay = 1/unfreq(k)*ky;
sze(k) = round(3*max(sigmax,sigmay));
[x,y] = meshgrid(-sze(k):sze(k));
reffilter = exp(-(x.^2/sigmax^2 + y.^2/sigmay^2)/2)...
.*cos(2*pi*unfreq(k)*x);
% Generate rotated versions of the filter. Note orientation
% image provides orientation *along* the ridges, hence +90
% degrees, and imrotate requires angles +ve anticlockwise, hence
% the minus sign.
for o = 1:180/angleInc
filter{k,o} = imrotate(reffilter,-(o*angleInc+90),'bilinear','crop');
end
end
if showfilter % Display largest scale filter for inspection
figure(7), imshow(filter{1,end},[]); title('filter');
end
% Find indices of matrix points greater than maxsze from the image
% boundary
maxsze = sze(1);
finalind = find(validr>maxsze & validr<rows-maxsze & ...
validc>maxsze & validc<cols-maxsze);
% Convert orientation matrix values from radians to an index value
% that corresponds to round(degrees/angleInc)
maxorientindex = round(180/angleInc);
orientindex = round(orient/pi*180/angleInc);
i = find(orientindex < 1); orientindex(i) = orientindex(i)+maxorientindex;
i = find(orientindex > maxorientindex);
orientindex(i) = orientindex(i)-maxorientindex;
% Finally do the filtering
for k = 1:length(finalind)
r = validr(finalind(k));
c = validc(finalind(k));
% find filter corresponding to freq(r,c)
filterindex = freqindex(round(freq(r,c)*100));
s = sze(filterindex);
newim(r,c) = sum(sum(im(r-s:r+s, c-s:c+s).*filter{filterindex,orientindex(r,c)}));
end
|
github
|
jacksky64/imageProcessing-master
|
ridgesegment.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FingerPrints/ridgesegment.m
| 2,320 |
utf_8
|
2bb49bf39ab2cc6bdd3a9e158ef0a054
|
% RIDGESEGMENT - Normalises fingerprint image and segments ridge region
%
% Function identifies ridge regions of a fingerprint image and returns a
% mask identifying this region. It also normalises the intesity values of
% the image so that the ridge regions have zero mean, unit standard
% deviation.
%
% This function breaks the image up into blocks of size blksze x blksze and
% evaluates the standard deviation in each region. If the standard
% deviation is above the threshold it is deemed part of the fingerprint.
% Note that the image is normalised to have zero mean, unit standard
% deviation prior to performing this process so that the threshold you
% specify is relative to a unit standard deviation.
%
% Usage: [normim, mask, maskind] = ridgesegment(im, blksze, thresh)
%
% Arguments: im - Fingerprint image to be segmented.
% blksze - Block size over which the the standard
% deviation is determined (try a value of 16).
% thresh - Threshold of standard deviation to decide if a
% block is a ridge region (Try a value 0.1 - 0.2)
%
% Returns: normim - Image where the ridge regions are renormalised to
% have zero mean, unit standard deviation.
% mask - Mask indicating ridge-like regions of the image,
% 0 for non ridge regions, 1 for ridge regions.
% maskind - Vector of indices of locations within the mask.
%
% Suggested values for a 500dpi fingerprint image:
%
% [normim, mask, maskind] = ridgesegment(im, 16, 0.1)
%
% See also: RIDGEORIENT, RIDGEFREQ, RIDGEFILTER
% 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
%
% January 2005
function [normim, mask, maskind] = ridgesegment(im, blksze, thresh)
im = normalise(im,0,1); % normalise to have zero mean, unit std dev
fun = inline('std(x(:))*ones(size(x))');
stddevim = blkproc(im, [blksze blksze], fun);
mask = stddevim > thresh;
maskind = find(mask);
% Renormalise image so that the *ridge regions* have zero mean, unit
% standard deviation.
im = im - mean(im(maskind));
normim = im/std(im(maskind));
|
github
|
jacksky64/imageProcessing-master
|
plotridgeorient.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FingerPrints/plotridgeorient.m
| 1,898 |
utf_8
|
830409dd2081c8e49dec602b704f949d
|
% PLOTRIDGEORIENT - plot of ridge orientation data
%
% Usage: plotridgeorient(orient, spacing, im, figno)
%
% orientim - Ridge orientation image (obtained from RIDGEORIENT)
% spacing - Sub-sampling interval to be used in ploting the
% orientation data the (Plotting every point is
% typically not feasible)
% im - Optional fingerprint image in which to overlay the
% orientation plot.
% figno - Optional figure number for plot
%
% A spacing of about 20 is recommended for a 500dpi fingerprint image
%
% See also: RIDGEORIENT, RIDGEFREQ, FREQEST, RIDGESEGMENT
% 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
%
% January 2005
function plotridgeorient(orient, spacing, im, figno)
if fix(spacing) ~= spacing
error('spacing must be an integer');
end
[rows, cols] = size(orient);
lw = 2; % linewidth
len = 0.8*spacing; % length of orientation lines
% Subsample the orientation data according to the specified spacing
s_orient = orient(spacing:spacing:rows-spacing, ...
spacing:spacing:cols-spacing);
xoff = len/2*cos(s_orient);
yoff = len/2*sin(s_orient);
if nargin >= 3 % Display fingerprint image
if nargin == 4
show(im, figno); hold on
else
show(im); hold on
end
end
% Determine placement of orientation vectors
[x,y] = meshgrid(spacing:spacing:cols-spacing, ...
spacing:spacing:rows-spacing);
x = x-xoff;
y = y-yoff;
% Orientation vectors
u = xoff*2;
v = yoff*2;
quiver(x,y,u,v,0,'.','linewidth',1, 'color','r');
axis equal, axis ij, hold off
|
github
|
jacksky64/imageProcessing-master
|
ridgeorient.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FingerPrints/ridgeorient.m
| 4,785 |
utf_8
|
d0a1e0389d1ba0031b88a48553cbba9f
|
% RIDGEORIENT - Estimates the local orientation of ridges in a fingerprint
%
% Usage: [orientim, reliability, coherence] = ridgeorientation(im, gradientsigma,...
% blocksigma, ...
% orientsmoothsigma)
%
% Arguments: im - A normalised input image.
% gradientsigma - Sigma of the derivative of Gaussian
% used to compute image gradients.
% blocksigma - Sigma of the Gaussian weighting used to
% sum the gradient moments.
% orientsmoothsigma - Sigma of the Gaussian used to smooth
% the final orientation vector field.
% Optional: if ommitted it defaults to 0
%
% Returns: orientim - The orientation image in radians.
% Orientation values are +ve clockwise
% and give the direction *along* the
% ridges.
% reliability - Measure of the reliability of the
% orientation measure. This is a value
% between 0 and 1. I think a value above
% about 0.5 can be considered 'reliable'.
% reliability = 1 - Imin./(Imax+.001);
% coherence - A measure of the degree to which the local
% area is oriented.
% coherence = ((Imax-Imin)./(Imax+Imin)).^2;
%
% With a fingerprint image at a 'standard' resolution of 500dpi suggested
% parameter values might be:
%
% [orientim, reliability] = ridgeorient(im, 1, 3, 3);
%
% See also: RIDGESEGMENT, RIDGEFREQ, RIDGEFILTER
% May 2003 Original version by Raymond Thai,
% January 2005 Reworked by Peter Kovesi
% October 2011 Added coherence computation and orientsmoothsigma made optional
%
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
function [orientim, reliability, coherence] = ...
ridgeorient(im, gradientsigma, blocksigma, orientsmoothsigma)
if ~exist('orientsmoothsigma', 'var'), orientsmoothsigma = 0; end
[rows,cols] = size(im);
% Calculate image gradients.
sze = fix(6*gradientsigma); if ~mod(sze,2); sze = sze+1; end
f = fspecial('gaussian', sze, gradientsigma); % Generate Gaussian filter.
[fx,fy] = gradient(f); % Gradient of Gausian.
Gx = filter2(fx, im); % Gradient of the image in x
Gy = filter2(fy, im); % ... and y
% Estimate the local ridge orientation at each point by finding the
% principal axis of variation in the image gradients.
Gxx = Gx.^2; % Covariance data for the image gradients
Gxy = Gx.*Gy;
Gyy = Gy.^2;
% Now smooth the covariance data to perform a weighted summation of the
% data.
sze = fix(6*blocksigma); if ~mod(sze,2); sze = sze+1; end
f = fspecial('gaussian', sze, blocksigma);
Gxx = filter2(f, Gxx);
Gxy = 2*filter2(f, Gxy);
Gyy = filter2(f, Gyy);
% Analytic solution of principal direction
denom = sqrt(Gxy.^2 + (Gxx - Gyy).^2) + eps;
sin2theta = Gxy./denom; % Sine and cosine of doubled angles
cos2theta = (Gxx-Gyy)./denom;
if orientsmoothsigma
sze = fix(6*orientsmoothsigma); if ~mod(sze,2); sze = sze+1; end
f = fspecial('gaussian', sze, orientsmoothsigma);
cos2theta = filter2(f, cos2theta); % Smoothed sine and cosine of
sin2theta = filter2(f, sin2theta); % doubled angles
end
orientim = pi/2 + atan2(sin2theta,cos2theta)/2;
% Calculate 'reliability' of orientation data. Here we calculate the area
% moment about the orientation axis found (this will be the minimum moment)
% and an axis perpendicular (which will be the maximum moment). The
% reliability measure is given by 1.0-min_moment/max_moment. The reasoning
% being that if the ratio of the minimum to maximum moments is close to one
% we have little orientation information.
Imin = (Gyy+Gxx)/2 - (Gxx-Gyy).*cos2theta/2 - Gxy.*sin2theta/2;
Imax = Gyy+Gxx - Imin;
reliability = 1 - Imin./(Imax+.001);
coherence = ((Imax-Imin)./(Imax+Imin)).^2;
% Finally mask reliability to exclude regions where the denominator
% in the orientation calculation above was small. Here I have set
% the value to 0.001, adjust this if you feel the need
reliability = reliability.*(denom>.001);
|
github
|
jacksky64/imageProcessing-master
|
testfin.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/FingerPrints/Docs/testfin.m
| 1,759 |
utf_8
|
8bd1035571269c92bbeebfee58b37d75
|
% TESTFIN
%
% Function to demonstrate use of fingerprint code
%
% Usage: [newim, binim, mask, reliability] = testfin(im);
%
% Argument: im - Fingerprint image to be enhanced.
%
% Returns: newim - Ridge enhanced image.
% binim - Binary version of enhanced image.
% mask - Ridge-like regions of the image
% reliability - 'Reliability' of orientation data
% 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
%
% January 2005
function [newim, binim, mask, reliability] = testfin(im)
if nargin == 0
im = imread('finger.png');
end
% Identify ridge-like regions and normalise image
blksze = 16; thresh = 0.1;
[normim, mask] = ridgesegment(im, blksze, thresh);
show(normim,1);
% Determine ridge orientations
[orientim, reliability] = ridgeorient(normim, 1, 5, 5);
plotridgeorient(orientim, 20, im, 2)
show(reliability,6)
% Determine ridge frequency values across the image
blksze = 36;
[freq, medfreq] = ridgefreq(normim, mask, orientim, blksze, 5, 5, 15);
show(freq,3)
% Actually I find the median frequency value used across the whole
% fingerprint gives a more satisfactory result...
freq = medfreq.*mask;
% Now apply filters to enhance the ridge pattern
newim = ridgefilter(normim, orientim, freq, 0.5, 0.5, 1);
show(newim,4);
% Binarise, ridge/valley threshold is 0
binim = newim > 0;
show(binim,5);
% Display binary image for where the mask values are one and where
% the orientation reliability is greater than 0.5
show(binim.*mask.*(reliability>0.5), 7)
|
github
|
jacksky64/imageProcessing-master
|
adjcontrast.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/GreyTrans/adjcontrast.m
| 1,772 |
utf_8
|
df466fd21398669febf7971b25906279
|
% ADJCONTRAST - Adjusts image contrast using sigmoid function.
%
% function g = adjcontrast(im, gain, cutoff)
%
% Arguments:
% im - image to be processed.
% gain - controls the actual contrast;
% A value of about 5 is neutral (little change).
% A value of 1 reduces contrast to about 20% of original
% A value of 10 increases contrast about 2.5x.
% a reasonable range of values to experiment with.
% cutoff - represents the (normalised) grey value about which
% contrast is increased or decreased. An initial
% value you might use is 0.5 (the midpoint of the
% greyscale) but different images may require
% different points of the greyscale to be enhanced.
% Copyright (c) 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.
% July 2001
function newim = adjcontrast(im, gain, cutoff)
if isa(im,'uint8');
newim = double(im);
else
newim = im;
end
% rescale range 0-1
newim = newim-min(min(newim));
newim = newim./max(max(newim));
newim = 1./(1 + exp(gain*(cutoff-newim))); % Apply Sigmoid function
|
github
|
jacksky64/imageProcessing-master
|
histtruncate.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/GreyTrans/histtruncate.m
| 4,297 |
utf_8
|
8662c6c4ad1997ffd87d3053e4425473
|
% HISTTRUNCATE - Truncates ends of an image histogram.
%
% Function truncates a specified percentage of the lower and
% upper ends of an image histogram.
%
% This operation allows grey levels to be distributed across
% the primary part of the histogram. This solves the problem
% when one has, say, a few very bright values in the image which
% have the overall effect of darkening the rest of the image after
% rescaling.
%
% Usage:
% [newim, sortv] = histtruncate(im, lHistCut, uHistCut)
% [newim, sortv] = histtruncate(im, lHistCut, uHistCut, sortv)
%
% Arguments:
% im - Image to be processed
% lHistCut - Percentage of the lower end of the histogram
% to saturate.
% uHistCut - Percentage of the upper end of the histogram
% to saturate. If omitted or empty defaults to the value
% for lHistCut.
% sortv - Optional array of sorted image pixel values obtained
% from a previous call to histtruncate. Supplying this
% data speeds the operation of histtruncate when one is
% repeatedly varying lHistCut and uHistCut.
%
% Returns:
% newim - Image with values clipped at the specified histogram
% fraction values. If the input image was colour the
% lightness values are clipped and stretched to the range
% 0-1. If the input image is greyscale no stretching is
% applied. You may want to use NORMAALISE to achieve this
% sortv - Sorted image values for reuse in subsequent calls to
% histruncate.
%
% See also: NORMALISE
% Copyright (c) 2001-2014 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% http://www.cet.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
% February 2012 - Added handling of NaN values in image
% February 2014 - Code cleanup
% September 2014 - Default for uHistCut + cleanup
function [newim, sortv] = histtruncate(im, lHistCut, uHistCut, sortv)
if ~exist('uHistCut', 'var') || isempty(uHistCut), uHistCut = lHistCut; end
if lHistCut < 0 | lHistCut > 100 | uHistCut < 0 | uHistCut > 100
error('Histogram truncation values must be between 0 and 100');
end
if ~exist('sortv', 'var'), sortv = []; end
if ndims(im) == 3 % Assume colour image in RGB
hsv = rgb2hsv(im); % Convert to HSV
% Apply histogram truncation just to intensity component
[hsv(:,:,3), sortv] = Ihisttruncate(hsv(:,:,3), lHistCut, uHistCut, sortv);
% Stretch intensity component to 0-1
hsv(:,:,3) = normalise(hsv(:,:,3));
newim = hsv2rgb(hsv); % Convert back to RGB
else
[newim, sortv] = Ihisttruncate(im, lHistCut, uHistCut, sortv);
end
%-----------------------------------------------------------------------
% Internal function that does the work
%-----------------------------------------------------------------------
function [im, sortv] = Ihisttruncate(im, lHistCut, uHistCut, sortv)
if ndims(im) > 2
error('HISTTRUNCATE only defined for grey value images');
end
% Generate a sorted array of pixel values or use supplied values
if isempty(sortv)
sortv = sort(im(:));
end
% Any NaN values end up at the end of the sorted list. We need to
% eliminate these
sortv = sortv(~isnan(sortv));
N = length(sortv(:));
% Compute indicies corresponding to specified upper and lower fractions
% of the histogram.
lind = floor(1 + N*lHistCut/100);
hind = ceil(N - N*uHistCut/100);
low_in = sortv(lind);
high_in = sortv(hind);
% Adjust image
im(im < low_in) = low_in;
im(im > high_in) = high_in;
% Normalise? normalise with NaNs?
|
github
|
jacksky64/imageProcessing-master
|
adjgamma.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/GreyTrans/adjgamma.m
| 1,278 |
utf_8
|
7923fe5b3ada0cd08b5edf5528839448
|
% ADJGAMMA - Adjusts image gamma.
%
% function g = adjgamma(im, g)
%
% Arguments:
% im - image to be processed.
% g - image gamma value.
% Values in the range 0-1 enhance contrast of bright
% regions, values > 1 enhance contrast in dark
% regions.
% Copyright (c) 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.
% July 2001
function newim = adjgamma(im, g)
if g <= 0
error('Gamma value must be > 0');
end
if isa(im,'uint8');
newim = double(im);
else
newim = im;
end
% rescale range 0-1
newim = newim-min(min(newim));
newim = newim./max(max(newim));
newim = newim.^(1/g); % Apply gamma function
|
github
|
jacksky64/imageProcessing-master
|
histeqfloat.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/GreyTrans/histeqfloat.m
| 2,523 |
utf_8
|
c9d2c9d7f401952ba393c03926112405
|
% HISTEQFLOAT Floating point image histogram equalisation
%
% Histogram equalisation for images containing floating point values. The number
% of distinct values in the output image will be the same as the number of
% distinct values in the input image.
%
% Usage: nim = histeqfloat(im, nbins)
%
% Arguments: im - Image to be equalised.
% nbins - Number of bins to use in forming the histogram. Defaults
% to 256.
%
% Returns: nim - Histogram equalised image.
%
% This function differs from classical histogram equalisation functions in that
% the cumulative histogram of the image grey values is treated as forming a set
% of points on the cumulative distribution function. The key point being that
% it is used as a *function* rather than as a lookup table for mapping input
% grey values to their output values. Under this approach, for images
% containing floating point values, the number of distinct values in the output
% image will be the same as the number of distinct values in the input image.
% This can result in a significant improvement in output compared to HISTEQ
%
% For integer valued images the number of distinct values in the output image
% must be less than, or equal to, the number of distinct values in the input
% image (typically much less than).
%
% See also: HISTEQ
% 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.
% February 2012
function nim = histeqfloat(im, nbins)
if ~exist('nbins', 'var'), nbins = 256; end
im = normalise(im); % Adjust image range 0-1
% Compute histogram bin centres and form histogram
centres = [1/nbins/2 : 1/nbins : 1-1/nbins/2];
n = hist(im(:), centres);
n = cumsum(n/sum(n)); % Cumulative sum of normalised histogram
% Use 1D spline interpolation on the cumulative histogram to map image
% values to their new ones, then reshape the image back to its original
% size.
nim = reshape(interp1(centres, n, im(:), 'spline'), size(im));
|
github
|
jacksky64/imageProcessing-master
|
extractfields.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/GreyTrans/extractfields.m
| 3,195 |
utf_8
|
fc2a0b4ffe621599238d4558ebbab88e
|
% EXTRACTFIELDS - Separates fields from a video frame.
%
% Function to separate fields from a video frame
% and (optionally) interpolate intermediate lines
% for each field.
%
% Usage: [f1, f2] = extractfields(im,interp)
%
% f1 and f2 are the odd and even fields
% im is the frame to be split
% interp is an optional string `interp' indicating
% whether f1 and f2 should be padded out with interpolated
% lines.
% Copyright (c) 2000 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.
% May 2000
% June 2014 Fixed class of returned image for colour images
function [f1, f2] = extractfields(im, interpstring)
if nargin < 2
interpstring = 'nointerp';
end
if (ndims(im)==3), % A colour image - Transform red, green, blue components separately
[f1r, f2r] = extractFieldsI(im(:,:,1), interpstring);
[f1g, f2g] = extractFieldsI(im(:,:,2), interpstring);
[f1b, f2b] = extractFieldsI(im(:,:,3), interpstring);
if strcmp(class(im),'double')
f1 = zeros([size(f1r),3]);
f1(:,:,1) = f1r;
f1(:,:,2) = f1g;
f1(:,:,3) = f1b;
f2 = zeros([size(f2r),3]);
f2(:,:,1) = f2r;
f2(:,:,2) = f2g;
f2(:,:,3) = f2b;
else
% Reform colour image for field 1
f1 = repmat(uint8(0),[size(f1r),3]);
f1(:,:,1) = uint8(round(f1r));
f1(:,:,2) = uint8(round(f1g));
f1(:,:,3) = uint8(round(f1b));
% Reform colour image for field 2
f2 = repmat(uint8(0),[size(f2r),3]);
f2(:,:,1) = uint8(round(f2r));
f2(:,:,2) = uint8(round(f2g));
f2(:,:,3) = uint8(round(f2b));
end
else % Assume grey scale image
[f1, f2] = extractFieldsI(im,interpstring);
end
%--------------------------------------------------------------
function [f1, f2] = extractFieldsI(im, interpstring)
[rows,cols] = size(im);
im = double(im);
if nargin==2
if strcmp(interpstring, 'interp')
interp = 1;
elseif strcmp(interpstring, 'nointerp')
interp = 0;
else
warning(['unknown interpolation option - no interpolation is' ...
' being used']);
interp = 0;
end
else
interp = 0;
end
if mod(rows,2) == 1
rows = rows-1; % This ensures even and odd fields end up with
end % the same No of rows
f1 = im(1:2:rows,:); % odd lines
f2 = im(2:2:rows,:); % even lines
if interp
f1 = interpfields(f1,'odd');
f2 = interpfields(f2,'even');
end
|
github
|
jacksky64/imageProcessing-master
|
interpfields.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/GreyTrans/interpfields.m
| 2,616 |
utf_8
|
995c2497c2bd2f01a7fc72cc0c552c7e
|
% INTERPFIELDS - Interpolates lines on a field extracted from a video frame.
%
% Function to interpolate intermediate lines on odd or even
% fields extracted from a video frame
%
% Usage: intp = interpfields(field, oddeven);
%
%
% Arguments: field - the field to be interpolated
% oddeven - optional flag 1/0 indicating whether the field
% is formed from the odd rows (default is 1)
%
% Returns: interp - an image with extra rows inserted. These rows are
% obtained by averaging the rows above and below.
% A future enhancement might be to use bicubic
% interpolation.
% 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.
% May 2000 - original version
% March 2004 - modified to use bicubic interpolation and to work for
% colour images
% August 2004 - Corrected No of rows to interpolate to avoid NaNs in the result
% August 2005 - Made compatible under Octave
function intp = interpfields(field, oddeven);
v = version; Octave = v(1)<'5'; % Crude Octave test
if nargin==2
if strcmp(oddeven, 'odd')
odd = 1;
else
odd = 0;
end
else % assume odd field
odd = 1;
end
field = double(field);
if ndims(field) == 3
[rows, cols, depth] = size(field);
elseif ndims(field) == 2
[rows, cols] = size(field);
depth = 1;
else
error('can only interpolate greyscale or colour images');
end
intp = zeros(2*rows-1,cols,depth);
[x,y] = meshgrid(1:cols,1:2:2*rows-1); % coords at which data is defined.
[xi,yi] = meshgrid(1:cols,1:2*rows-1); % coords where we want data defined.
for d = 1:depth
if Octave
intp(:,:,d) = interp2(x,y,field(:,:,d),xi,yi,'linear');
else
intp(:,:,d) = interp2(x,y,field(:,:,d),xi,yi,'bicubic');
end
end
if odd % pad an extra row at the bottom
intp = [intp; field(rows,:,:)];
else
intp = [field(1,:,:); intp ]; % pad an extra row at the top
end
|
github
|
jacksky64/imageProcessing-master
|
agc.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/GreyTrans/agc.m
| 3,871 |
utf_8
|
e4153ae09348114147d2cd732b327195
|
% AGC Automatic Gain Control for geophysical images
%
% Usage: agcim = agc(im, sigma, p, r)
%
% Arguments: im - The input image. NaNs in the image are handled
% automatically.
% sigma - The standard deviation of the Gaussian filter used to
% determine local image mean values and to perform the
% summation used to determine the local gain values.
% Sigma is specified in pixels, try experimenting with a
% wide range of values.
% p - The power used to compute the p-norm of the local image
% region. The gain is obtained from the p-norm. If
% unspecified its value defaults to 2 and r defaults to 0.5
% r - Normally r = 1/p (and it defaults to this) but it can
% specified separately to achieve specific results. See
% Rajagopalan's papers.
%
% Returns: agcim - The Automatic Gain Controlled image.
%
% The algorithm is based on Shanti Rajagopalan's papers, referenced below, with
% a couple of differences.
%
% 1) The gain is computed from the difference between the image and its local
% mean. The aim of this is to avoid any local base-level issues and to allow
% the code to be applied to a wide range of image types, not just magnetic
% gradient data. The gain is applied to the difference between the image and
% its local mean to obtain the final AGC image.
%
% 2) The computation of the local mean and the summation operations used to
% compute the local gain is performed using Gaussian smoothing. The aim of this
% is to avoid abrupt changes in gain as the summation window is moved across the
% image. The effective window size is controlled by the value of sigma used to
% specify the Gaussian filter.
%
% References:
% * Shanti Rajagopalan "The use of 'Automatic Gain Control' to Display Vertical
% Magnetic Gradient Data". 5th ASEG Conference 1987. pp 166-169
%
% * Shanti Rajagopalan and Peter Milligan. "Image Enhancement of Aeromagnetic Data
% using Automatic Gain Control". Exploration Geophysics (1995) 25. pp 173-178
% 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.
% April 2012 - Original version
function agcim = agc(im, sigma, p, r)
% Default values for p and r
if ~exist('p', 'var'), p = 2; end
if exist('p','var') & ~exist('r', 'var')
r = 1/p;
elseif ~exist('r', 'var')
r = 0.5;
end
% Make provision for the image containing NaNs
mask = ~isnan(im);
if any(mask)
im = fillnan(im);
end
% Get local mean by smoothing the image with a Gaussian filter
h = fspecial('gaussian', 6*sigma, sigma);
localMean = filter2(h, im);
% Subtract image from local mean, raise to power 'p' then apply Gaussian
% smoothing filter to obtain a local weighted sum. Finally raise the result
% to power 'r' to obtain the 'gain'. Typically p = 2 and r = 0.5 which will
% make gain equal to the local RMS. The abs() function is used to allow
% for arbitrary 'p' and 'r'.
gain = (filter2(h, abs(im-localMean).^p)).^r;
% Apply inverse gain to the difference between the image and the local
% mean to obtain the final AGC image.
agcim = (im-localMean)./(gain + eps) .* mask;
|
github
|
jacksky64/imageProcessing-master
|
normalise.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/GreyTrans/normalise.m
| 2,312 |
utf_8
|
5ea78a2901be537abb01b07cd78b3ddf
|
% NORMALISE - Normalises image values to 0-1, or to desired mean and variance
%
% Usage:
% n = normalise(im)
%
% Offsets and rescales image so that the minimum value is 0
% and the maximum value is 1. Result is returned in n. If the image is
% colour the image is converted to HSV and the value/intensity component
% is normalised to 0-1 before being converted back to RGB.
%
%
% n = normalise(im, reqmean, reqvar)
%
% Arguments: im - A grey-level input image.
% reqmean - The required mean value of the image.
% reqvar - The required variance of the image.
%
% Offsets and rescales image so that it has mean reqmean and variance
% reqvar. Colour images cannot be normalised in this manner.
% Copyright (c) 1996-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.
% January 2005 - modified to allow desired mean and variance
function n = normalise(im, reqmean, reqvar)
if ~(nargin == 1 | nargin == 3)
error('No of arguments must be 1 or 3');
end
if nargin == 1 % Normalise 0 - 1
if ndims(im) == 3 % Assume colour image
hsv = rgb2hsv(im);
v = hsv(:,:,3);
v = v - min(v(:)); % Just normalise value component
v = v/max(v(:));
hsv(:,:,3) = v;
n = hsv2rgb(hsv);
else % Assume greyscale
if ~isa(im,'double'), im = double(im); end
n = im - min(im(:));
n = n/max(n(:));
end
else % Normalise to desired mean and variance
if ndims(im) == 3 % colour image?
error('cannot normalise colour image to desired mean and variance');
end
if ~isa(im,'double'), im = double(im); end
im = im - mean(im(:));
im = im/std(im(:)); % Zero mean, unit std dev
n = reqmean + im*sqrt(reqvar);
end
|
github
|
jacksky64/imageProcessing-master
|
remapim.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/GreyTrans/remapim.m
| 2,589 |
utf_8
|
197534d04489cb4cfd3b0d641d848c0a
|
% REMAPIM - Remaps image intensity values
%
% Usage: newim = remapim(im, x, y, rescale)
% \
% optional
% Arguments
% im - Image to be transformed.
% x,y - Coordinates of spline control points that define the
% mapping function. These coordinates are in the range
% 0-1 and are typically obtained experimentally via the
% function GREYTRANS
% rescale - An optional flag (0 or 1) indicating whether image
% values should be normalised to the range 0-1.
% This is only provided for speed when called
% by GREYTRANS. By default the input image will
% be normalised to the range 0-1.
%
% Image intensity values are remapped to new values via a mapping
% function defined by a series of spline points. The mapping function is
% defined over the range 0-1, accordingly the input image is normalised
% to the range 0-1. The output image will also lie in this range.
% 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.
% April 2002 - original version.
% March 2003 - modified to work with colour images.
function nim = remapim(im, x, y, rescale)
if nargin < 4
rescale = 1;
end
if ndims(im)==3 % Assume we have a colour image
hsv = rgb2hsv(im);
% Apply remapping just to the value component
hsv(:,:,3) = remap(hsv(:,:,3), x, y, rescale);
nim = hsv2rgb(hsv);
else % Assume we have a 2D greyscale image
nim = remap(im, x, y, rescale);
end
% Internal function that does the work
function nim = remap(im, x, y, rescale)
if rescale
im = normalise(im);
end
nim = spline(x,y,im); % Remap image values
% clamp image values within bounds 0 - 1
gt0 = nim > 0;
nim = nim.*gt0; % values < 0 become 0
lt1 = nim < 1;
nim = nim.*lt1 + ~lt1; % values > 1 become 1
|
github
|
jacksky64/imageProcessing-master
|
greytrans.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/GreyTrans/greytrans.m
| 4,462 |
utf_8
|
f2f1254324be1d786b5fee45794f6bca
|
% GREYTRANS - Interactive greyscale manipulation of an image (RGB or greyscale)
%
% Usage: [newim, x, y] = greytrans(im, npts)
%
% Arguments
% im - Image to be transformed
% npts - Optional number of control points of the spline
% defining the mapping function. This defaults to 4 if
% not specified.
%
% Returns:
% newim - The transformed image.
% x,y - Coordinates of spline control points that define the
% mapping function. These coordinates can be passed
% to the function REMAPIM if you want to apply the
% transformation to other images.
%
% Image intensity values are remapped to new values via a mapping
% function defined by a series of spline points. The mapping function is
% defined over the range 0-1, accordingly the input image is normalised
% to the range 0-1. The output image will also lie in this range.
% Colour images are processed by first converting to HSV and then
% remapping the Value component and then reconstructing new RGB values.
% 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.
% April 2002
% March 2003 - modified to work with colour images.
function [nim,x,y] = greytrans(im, npts)
if nargin == 1
npts = 4; % default No of control points
end
if npts < 2
error('Number of control points must be > 2');
end
x = [0:npts-1]/(npts-1); y = x;
h = figure(1); clf
% set(h,'Position',[150 100 800 550]), clf
im = normalise(im); % rescale range 0 - 1
him1 = subplot('Position',[.025 .28 .45 .7]);
him2 = subplot('Position',[.525 .28 .45 .7]);
hcp = subplot('Position',[.35 .03 .25 .25]);
subplot(him1), imshow(im), title('Original Image');
subplot(him2), imshow(im), title('Remapped Image');
subplot(hcp), plotcurve(x,y);
if ndims(im)==3 % Assume we have a colour image
colour = 1;
hsv = rgb2hsv(im);
v = hsv(:,:,3); % Extract the value - this is what we want to
% remap
else
colour = 0;
end
fprintf('Manipulate the mapping curve by clicking with the left mouse button.\n');
fprintf('The closest control point is moved to the digitised location.\n');
fprintf('Click any other button to exit\n');
but = 1;
while but==1
subplot(hcp), [xp yp but] = ginput(1);
if but ~= 1
break;
end
ind = indexOfClosestPt(xp,yp,x,y);
% Make sure control points cannot 'cross' each other and keep
% x-coords of end points at 0 and 1
if ind > 1 & ind < npts
if xp < x(ind-1)
x(ind) = x(ind-1)+0.01;
elseif xp > x(ind+1)
x(ind) = x(ind+1)-0.01;
else
x(ind) = xp;
end
elseif ind == 1
x(ind) = 0;
elseif ind == npts
x(ind) = 1;
end
% Make sure you cannot put control points too high or low...
if yp > 1
yp = 1;
elseif yp < 0
yp = 0;
end
y(ind) = yp;
subplot(hcp), plotcurve(x,y);
if colour
nv = remapim(v, x , y, 0); % Remap value component
hsv(:,:,3) = nv; % Reconstruct colour image
nim = hsv2rgb(hsv);
else
nim = remapim(im, x , y, 0);
end
subplot(him2), imshow(nim), title('Remapped Image');
drawnow
end
%----------------------------------------------------------------
% Function to find control point closest to digitised location
function ind = indexOfClosestPt(xp,yp,x,y)
dist = sqrt( (x-xp).^2 + (y-yp).^2 );
[d,ind] = min(dist);
%----------------------------------------------------------------
% Function to plot mapping curve
function plotcurve(x,y)
xx = [0:.01:1];
yy = spline(x,y,xx);
plot(x, y,'ro');
hold on
plot(xx,yy);
xlabel('input grey value');
ylabel('output grey value');
title('Mapping Function');
axis([0 1 0 1]), axis square
drawnow
hold off
|
github
|
jacksky64/imageProcessing-master
|
ransacfitfundmatrix7.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/ransacfitfundmatrix7.m
| 6,338 |
utf_8
|
e8bb75917201904ec6c3bdd4f36479f1
|
% RANSACFITFUNDMATRIX7 - fits fundamental matrix using RANSAC
%
% Usage: [F, inliers] = ransacfitfundmatrix7(x1, x2, t)
%
% This function requires Andrew Zisserman's 7 point fundamental matrix code.
% See: http://www.robots.ox.ac.uk/~vgg/hzbook/code/
%
% Arguments:
% x1 - 2xN or 3xN set of homogeneous points. If the data is
% 2xN it is assumed the homogeneous scale factor is 1.
% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
% Note that point coordinates are normalised to that their
% mean distance from the origin is sqrt(2). The value of
% t should be set relative to this, say in the range
% 0.001 - 0.01
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% F - The 3x3 fundamental matrix such that x2'Fx1 = 0.
% inliers - An array of indices of the elements of x1, x2 that were
% the inliers for the best model.
%
% See Also: RANSAC, FUNDMATRIX, RANSACFITFUNDMATRIX
% Copyright (c) 2004-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.
% February 2004 Original version
% August 2005 Distance error function changed to match changes in RANSAC
% June 2009 Bug in the wrapper function fixed (thanks to Peter Corke)
function [F, inliers] = ransacfitfundmatrix7(x1, x2, t, feedback)
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
if nargin == 3
feedback = 0;
end
[rows,npts] = size(x1);
if rows~=2 & rows~=3
error('x1 and x2 must have 2 or 3 rows');
end
if rows == 2 % Pad data with homogeneous scale factor of 1
x1 = [x1; ones(1,npts)];
x2 = [x2; ones(1,npts)];
end
% Normalise each set of points so that the origin is at centroid and
% mean distance from origin is sqrt(2). normalise2dpts also ensures the
% scale parameter is 1. Note that 'fundmatrix' will also call
% 'normalise2dpts' but the code in 'ransac' that calls the distance
% function will not - so it is best that we normalise beforehand.
[x1, T1] = normalise2dpts(x1);
[x2, T2] = normalise2dpts(x2);
s = 7; % Number of points needed to fit a fundamental matrix using
% a 7 point solution
fittingfn = @vgg_F_from_7pts_wrapper; % Wrapper for AZ's code
distfn = @funddist;
degenfn = @isdegenerate;
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[F, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t, feedback);
% Now do a final least squares fit on the data points considered to
% be inliers.
F = fundmatrix(x1(:,inliers), x2(:,inliers));
% Denormalise
F = T2'*F*T1;
%--------------------------------------------------------------------------
% Function providing a wrapper for Andrew Zisserman's 7 point fundamental
% matrix code. See: http://www.robots.ox.ac.uk/~vgg/hzbook/code/
% This code takes inputs and returns output according to the requirements of
% RANSAC
function F = vgg_F_from_7pts_wrapper(x)
Fvgg = vgg_F_from_7pts_2img(x(1:3,:), x(4:6,:));
if isempty(Fvgg)
F = [];
return;
end
% Store the (potentially) 3 solutions in a cell array
[rows,cols,Nsolutions] = size(Fvgg);
for n = 1:Nsolutions
F{n} = Fvgg(:,:,n);
end
%--------------------------------------------------------------------------
% Function to evaluate the first order approximation of the geometric error
% (Sampson distance) of the fit of a fundamental matrix with respect to a
% set of matched points as needed by RANSAC. See: Hartley and Zisserman,
% 'Multiple View Geometry in Computer Vision', page 270.
%
% Note that this code allows for F being a cell array of fundamental matrices of
% which we have to pick the best one. (A 7 point solution can return up to 3
% solutions)
function [bestInliers, bestF] = funddist(F, x, t);
x1 = x(1:3,:); % Extract x1 and x2 from x
x2 = x(4:6,:);
if iscell(F) % We have several solutions each of which must be tested
nF = length(F); % Number of solutions to test
bestF = F{1}; % Initial allocation of best solution
ninliers = 0; % Number of inliers
for k = 1:nF
x2tFx1 = zeros(1,length(x1));
for n = 1:length(x1)
x2tFx1(n) = x2(:,n)'*F{k}*x1(:,n);
end
Fx1 = F{k}*x1;
Ftx2 = F{k}'*x2;
% Evaluate distances
d = x2tFx1.^2 ./ ...
(Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);
inliers = find(abs(d) < t); % Indices of inlying points
if length(inliers) > ninliers % Record best solution
ninliers = length(inliers);
bestF = F{k};
bestInliers = inliers;
end
end
else % We just have one solution
x2tFx1 = zeros(1,length(x1));
for n = 1:length(x1)
x2tFx1(n) = x2(:,n)'*F*x1(:,n);
end
Fx1 = F*x1;
Ftx2 = F'*x2;
% Evaluate distances
d = x2tFx1.^2 ./ ...
(Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);
bestInliers = find(abs(d) < t); % Indices of inlying points
bestF = F; % Copy F directly to bestF
end
%----------------------------------------------------------------------
% (Degenerate!) function to determine if a set of matched points will result
% in a degeneracy in the calculation of a fundamental matrix as needed by
% RANSAC. This function assumes this cannot happen...
function r = isdegenerate(x)
r = 0;
|
github
|
jacksky64/imageProcessing-master
|
fitline3d.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/fitline3d.m
| 1,247 |
utf_8
|
1f7cee8975c9f96bfb8aa43046474e5f
|
% FITLINE3D - Fits a line to a set of 3D points
%
% Usage: [L] = fitline3d(XYZ)
%
% Where: XYZ - 3xNpts array of XYZ coordinates
% [x1 x2 x3 ... xN;
% y1 y2 y3 ... yN;
% z1 z2 z3 ... zN]
%
% Returns: L - 3x2 matrix consisting of the two endpoints of the line
% that fits the points. The line is centered about the
% mean of the points, and extends in the directions of the
% principal eigenvectors, with scale determined by the
% eigenvalues.
%
% Author: Felix Duvallet (CMU)
% August 2006
function L = fitline3d(XYZ)
% Since the covariance matrix should be 3x3 (not NxN), need
% to take the transpose of the points.
XYZ = XYZ';
% find mean of the points
mu = mean(XYZ, 1);
% covariance matrix
C = cov(XYZ);
% get the eigenvalues and eigenvectors
[V, D] = eig(C);
% largest eigenvector is in the last column
col = size(V, 2); %get the number of columns
% get the last eigenvector column and the last eigenvalue
eVec = V(:, col);
eVal = D(col, col);
% start point - center about mean and scale eVector by eValue
L(:, 1) = mu' - sqrt(eVal)*eVec;
% end point
L(:, 2) = mu' + sqrt(eVal)*eVec;
|
github
|
jacksky64/imageProcessing-master
|
ransacfitfundmatrix.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/ransacfitfundmatrix.m
| 5,810 |
utf_8
|
26f6632c53896e5e0e2f95b86e26394d
|
% RANSACFITFUNDMATRIX - fits fundamental matrix using RANSAC
%
% Usage: [F, inliers] = ransacfitfundmatrix(x1, x2, t)
%
% Arguments:
% x1 - 2xN or 3xN set of homogeneous points. If the data is
% 2xN it is assumed the homogeneous scale factor is 1.
% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
% Note that point coordinates are normalised to that their
% mean distance from the origin is sqrt(2). The value of
% t should be set relative to this, say in the range
% 0.001 - 0.01
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% F - The 3x3 fundamental matrix such that x2'Fx1 = 0.
% inliers - An array of indices of the elements of x1, x2 that were
% the inliers for the best model.
%
% See Also: RANSAC, FUNDMATRIX
% Copyright (c) 2004-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.
% February 2004 Original version
% August 2005 Distance error function changed to match changes in RANSAC
% February 2016 Catch case when ransac fails so that we skip trying a final
% least squares solution
function [F, inliers] = ransacfitfundmatrix(x1, x2, t, feedback)
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
if nargin == 3
feedback = 0;
end
[rows,npts] = size(x1);
if ~(rows==2 || rows==3)
error('x1 and x2 must have 2 or 3 rows');
end
if rows == 2 % Pad data with homogeneous scale factor of 1
x1 = [x1; ones(1,npts)];
x2 = [x2; ones(1,npts)];
end
% Normalise each set of points so that the origin is at centroid and
% mean distance from origin is sqrt(2). normalise2dpts also ensures the
% scale parameter is 1. Note that 'fundmatrix' will also call
% 'normalise2dpts' but the code in 'ransac' that calls the distance
% function will not - so it is best that we normalise beforehand.
[x1, T1] = normalise2dpts(x1);
[x2, T2] = normalise2dpts(x2);
s = 8; % Number of points needed to fit a fundamental matrix. Note that
% only 7 are needed but the function 'fundmatrix' only
% implements the 8-point solution.
fittingfn = @fundmatrix;
distfn = @funddist;
degenfn = @isdegenerate;
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[F, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t, feedback);
if isempty(F) % ransac failed to find a solution.
return; % Do not attempt to do a final least squares fit
end
% Now do a final least squares fit on the data points considered to
% be inliers.
F = fundmatrix(x1(:,inliers), x2(:,inliers));
% Denormalise
F = T2'*F*T1;
%--------------------------------------------------------------------------
% Function to evaluate the first order approximation of the geometric error
% (Sampson distance) of the fit of a fundamental matrix with respect to a
% set of matched points as needed by RANSAC. See: Hartley and Zisserman,
% 'Multiple View Geometry in Computer Vision', 2nd Ed. page 287.
%
% Note that this code allows for F being a cell array of fundamental matrices of
% which we have to pick the best one. (A 7 point solution can return up to 3
% solutions)
function [bestInliers, bestF] = funddist(F, x, t);
x1 = x(1:3,:); % Extract x1 and x2 from x
x2 = x(4:6,:);
if iscell(F) % We have several solutions each of which must be tested
nF = length(F); % Number of solutions to test
bestF = F{1}; % Initial allocation of best solution
ninliers = 0; % Number of inliers
for k = 1:nF
x2tFx1 = zeros(1,length(x1));
for n = 1:length(x1)
x2tFx1(n) = x2(:,n)'*F{k}*x1(:,n);
end
Fx1 = F{k}*x1;
Ftx2 = F{k}'*x2;
% Evaluate distances
d = x2tFx1.^2 ./ ...
(Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);
inliers = find(abs(d) < t); % Indices of inlying points
if length(inliers) > ninliers % Record best solution
ninliers = length(inliers);
bestF = F{k};
bestInliers = inliers;
end
end
else % We just have one solution
x2tFx1 = zeros(1,length(x1));
for n = 1:length(x1)
x2tFx1(n) = x2(:,n)'*F*x1(:,n);
end
Fx1 = F*x1;
Ftx2 = F'*x2;
% Evaluate distances
d = x2tFx1.^2 ./ ...
(Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);
bestInliers = find(abs(d) < t); % Indices of inlying points
bestF = F; % Copy F directly to bestF
end
%----------------------------------------------------------------------
% (Degenerate!) function to determine if a set of matched points will result
% in a degeneracy in the calculation of a fundamental matrix as needed by
% RANSAC. This function assumes this cannot happen...
function r = isdegenerate(x)
r = 0;
|
github
|
jacksky64/imageProcessing-master
|
ransacfitaffinefund.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/ransacfitaffinefund.m
| 4,443 |
utf_8
|
1f0e4e13663302b2d953db1e18f9ffe2
|
% RANSACFITAFFINEFUND - fits affine fundamental matrix using RANSAC
%
% Usage: [F, inliers] = ransacfitaffinefund(x1, x2, t)
%
% Arguments:
% x1 - 2xN or 3xN set of homogeneous points. If the data is
% 2xN it is assumed the homogeneous scale factor is 1.
% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
% Note that point coordinates are normalised to that their
% mean distance from the origin is sqrt(2). The value of
% t should be set relative to this, say in the range
% 0.001 - 0.01
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% F - The 3x3 fundamental matrix such that x2'Fx1 = 0.
% inliers - An array of indices of the elements of x1, x2 that were
% the inliers for the best model.
%
% See Also: RANSAC, FUNDMATRIX AFFINEFUNDMATRIX
% Copyright (c) 2004-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.
% February 2004 Original version
% August 2005 Distance error function changed to match changes in RANSAC
function [F, inliers] = ransacfitaffinefund(x1, x2, t, feedback)
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
if nargin == 3
feedback = 0;
end
[rows,npts] = size(x1);
if rows~=2 & rows~=3
error('x1 and x2 must have 2 or 3 rows');
end
if rows == 2 % Pad data with homogeneous scale factor of 1
x1 = [x1; ones(1,npts)];
x2 = [x2; ones(1,npts)];
end
% Normalise each set of points so that the origin is at centroid and
% mean distance from origin is sqrt(2). normalise2dpts also ensures the
% scale parameter is 1. Note that 'fundmatrix' will also call
% 'normalise2dpts' but the code in 'ransac' that calls the distance
% function will not - so it is best that we normalise beforehand.
[x1, T1] = normalise2dpts(x1);
[x2, T2] = normalise2dpts(x2);
s = 4; % Number of points needed to fit an affine fundamental matrix.
fittingfn = @affinefundmatrix;
distfn = @funddist;
degenfn = @isdegenerate;
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[F, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t, feedback);
% Now do a final least squares fit on the data points considered to
% be inliers.
F = affinefundmatrix(x1(:,inliers), x2(:,inliers));
% Denormalise
F = T2'*F*T1;
%--------------------------------------------------------------------------
% Function to evaluate the first order approximation of the geometric error
% (Sampson distance) of the fit of a fundamental matrix with respect to a
% set of matched points as needed by RANSAC. See: Hartley and Zisserman,
% 'Multiple View Geometry in Computer Vision', page 270.
function [inliers, F] = funddist(F, x, t);
x1 = x(1:3,:); % Extract x1 and x2 from x
x2 = x(4:6,:);
x2tFx1 = zeros(1,length(x1));
for n = 1:length(x1)
x2tFx1(n) = x2(:,n)'*F*x1(:,n);
end
Fx1 = F*x1;
Ftx2 = F'*x2;
% Evaluate distances
d = x2tFx1.^2 ./ ...
(Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);
inliers = find(abs(d) < t); % Indices of inlying points
%----------------------------------------------------------------------
% (Degenerate!) function to determine if a set of matched points will result
% in a degeneracy in the calculation of a fundamental matrix as needed by
% RANSAC. This function assumes this cannot happen...
function r = isdegenerate(x)
r = 0;
|
github
|
jacksky64/imageProcessing-master
|
fitplane.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/fitplane.m
| 1,694 |
utf_8
|
a058a2453754cff9ea42776f1034436a
|
% FITPLANE - solves coefficients of plane fitted to 3 or more points
%
% Usage: B = fitplane(XYZ)
%
% Where: XYZ - 3xNpts array of xyz coordinates to fit plane to.
% If Npts is greater than 3 a least squares solution
% is generated.
%
% Returns: B - 4x1 array of plane coefficients in the form
% b(1)*X + b(2)*Y +b(3)*Z + b(4) = 0
% The magnitude of B is 1.
%
% See also: RANSACFITPLANE
% Copyright (c) 2003-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.
% June 2003
function B = fitplane(XYZ)
[rows,npts] = size(XYZ);
if rows ~=3
error('data is not 3D');
end
if npts < 3
error('too few points to fit plane');
end
% Set up constraint equations of the form AB = 0,
% where B is a column vector of the plane coefficients
% in the form b(1)*X + b(2)*Y +b(3)*Z + b(4) = 0.
A = [XYZ' ones(npts,1)]; % Build constraint matrix
if npts == 3 % Pad A with zeros
A = [A; zeros(1,4)];
end
[u d v] = svd(A); % Singular value decomposition.
B = v(:,4); % Solution is last column of v.
|
github
|
jacksky64/imageProcessing-master
|
randomsample.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/randomsample.m
| 2,218 |
utf_8
|
d672616e8ac80b56f5cb91ac584537d8
|
% RANDOMSAMPLE - selects n random items from an array
%
% Usage: items = randomsample(a, n)
%
% Arguments: a - Either an array of values from which the items are to
% be selected, or an integer in which case the items
% are values selected from the array [1:a]
% n - The number of items to be selected.
%
%
% This function can be used as a basic replacement for RANDSAMPLE for those
% who do not have the statistics toolbox.
% Also,
% r = randomsample(n,n) will give a random permutation of the integers 1:n
%
% See also: RANSAC
% Strategy is to generate a random integer index into the array and select that
% item from the array. The selected element in the array is then overwritten by
% the last element in the array and the process is then repeated except that
% when we select the next element we generate a random integer index that lies
% in the range 1 to arraylength - 1, and so on. This ensures items are not
% repeated.
% Copyright (c) 2006 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
%
% 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 2006
function item = randomsample(a, n)
npts = length(a);
if npts == 1 % We have a scalar argument for a
npts = a;
a = [1:a]; % Construct an array 1:a
end
if npts < n
error(...
sprintf('Trying to select %d items from a list of length %d',n, npts));
end
item = zeros(1,n);
for i = 1:n
% Generate random value in the appropriate range
r = ceil((npts-i+1).*rand);
item(i) = a(r); % Select the rth element from the list
a(r) = a(end-i+1); % Overwrite selected element
end % ... and repeat
|
github
|
jacksky64/imageProcessing-master
|
iscolinear.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/iscolinear.m
| 2,318 |
utf_8
|
65025b7413f8f6b4cb16dd1689a5900f
|
% ISCOLINEAR - are 3 points colinear
%
% Usage: r = iscolinear(p1, p2, p3, flag)
%
% Arguments:
% p1, p2, p3 - Points in 2D or 3D.
% flag - An optional parameter set to 'h' or 'homog'
% indicating that p1, p2, p3 are homogneeous
% coordinates with arbitrary scale. If this is
% omitted it is assumed that the points are
% inhomogeneous, or that they are homogeneous with
% equal scale.
%
% Returns:
% r = 1 if points are co-linear, 0 otherwise
% Copyright (c) 2004-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.
% February 2004
% January 2005 - modified to allow for homogeneous points of arbitrary
% scale (thanks to Michael Kirchhof)
function r = iscolinear(p1, p2, p3, flag)
if nargin == 3 % Assume inhomogeneous coords
flag = 'inhomog';
end
if ~all(size(p1)==size(p2)) | ~all(size(p1)==size(p3)) | ...
~(length(p1)==2 | length(p1)==3)
error('points must have the same dimension of 2 or 3');
end
% If data is 2D, assume they are 2D inhomogeneous coords. Make them
% homogeneous with scale 1.
if length(p1) == 2
p1(3) = 1; p2(3) = 1; p3(3) = 1;
end
if flag(1) == 'h'
% Apply test that allows for homogeneous coords with arbitrary
% scale. p1 X p2 generates a normal vector to plane defined by
% origin, p1 and p2. If the dot product of this normal with p3
% is zero then p3 also lies in the plane, hence co-linear.
r = abs(dot(cross(p1, p2),p3)) < eps;
else
% Assume inhomogeneous coords, or homogeneous coords with equal
% scale.
r = norm(cross(p2-p1, p3-p1)) < eps;
end
|
github
|
jacksky64/imageProcessing-master
|
ransacfithomography.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/ransacfithomography.m
| 4,920 |
utf_8
|
d479d49f7c8e8689283005bcbe340b61
|
% RANSACFITHOMOGRAPHY - fits 2D homography using RANSAC
%
% Usage: [H, inliers] = ransacfithomography(x1, x2, t)
%
% Arguments:
% x1 - 2xN or 3xN set of homogeneous points. If the data is
% 2xN it is assumed the homogeneous scale factor is 1.
% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
% Note that point coordinates are normalised to that their
% mean distance from the origin is sqrt(2). The value of
% t should be set relative to this, say in the range
% 0.001 - 0.01
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% H - The 3x3 homography such that x2 = H*x1.
% inliers - An array of indices of the elements of x1, x2 that were
% the inliers for the best model.
%
% See Also: ransac, homography2d, homography1d
% Copyright (c) 2004-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.
% February 2004 - original version
% July 2004 - error in denormalising corrected (thanks to Andrew Stein)
% August 2005 - homogdist2d modified to fit new ransac specification.
function [H, inliers] = ransacfithomography(x1, x2, t)
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
[rows,npts] = size(x1);
if rows~=2 & rows~=3
error('x1 and x2 must have 2 or 3 rows');
end
if npts < 4
error('Must have at least 4 points to fit homography');
end
if rows == 2 % Pad data with homogeneous scale factor of 1
x1 = [x1; ones(1,npts)];
x2 = [x2; ones(1,npts)];
end
% Normalise each set of points so that the origin is at centroid and
% mean distance from origin is sqrt(2). normalise2dpts also ensures the
% scale parameter is 1. Note that 'homography2d' will also call
% 'normalise2dpts' but the code in 'ransac' that calls the distance
% function will not - so it is best that we normalise beforehand.
[x1, T1] = normalise2dpts(x1);
[x2, T2] = normalise2dpts(x2);
s = 4; % Minimum No of points needed to fit a homography.
fittingfn = @homography2d;
distfn = @homogdist2d;
degenfn = @isdegenerate;
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[H, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t);
% Now do a final least squares fit on the data points considered to
% be inliers.
H = homography2d(x1(:,inliers), x2(:,inliers));
% Denormalise
H = T2\H*T1;
%----------------------------------------------------------------------
% Function to evaluate the symmetric transfer error of a homography with
% respect to a set of matched points as needed by RANSAC.
function [inliers, H] = homogdist2d(H, x, t);
x1 = x(1:3,:); % Extract x1 and x2 from x
x2 = x(4:6,:);
% Calculate, in both directions, the transfered points
Hx1 = H*x1;
invHx2 = H\x2;
% Normalise so that the homogeneous scale parameter for all coordinates
% is 1.
x1 = hnormalise(x1);
x2 = hnormalise(x2);
Hx1 = hnormalise(Hx1);
invHx2 = hnormalise(invHx2);
d2 = sum((x1-invHx2).^2) + sum((x2-Hx1).^2);
inliers = find(abs(d2) < t);
%----------------------------------------------------------------------
% Function to determine if a set of 4 pairs of matched points give rise
% to a degeneracy in the calculation of a homography as needed by RANSAC.
% This involves testing whether any 3 of the 4 points in each set is
% colinear.
function r = isdegenerate(x)
x1 = x(1:3,:); % Extract x1 and x2 from x
x2 = x(4:6,:);
r = ...
iscolinear(x1(:,1),x1(:,2),x1(:,3)) | ...
iscolinear(x1(:,1),x1(:,2),x1(:,4)) | ...
iscolinear(x1(:,1),x1(:,3),x1(:,4)) | ...
iscolinear(x1(:,2),x1(:,3),x1(:,4)) | ...
iscolinear(x2(:,1),x2(:,2),x2(:,3)) | ...
iscolinear(x2(:,1),x2(:,2),x2(:,4)) | ...
iscolinear(x2(:,1),x2(:,3),x2(:,4)) | ...
iscolinear(x2(:,2),x2(:,3),x2(:,4));
|
github
|
jacksky64/imageProcessing-master
|
ransac.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/ransac.m
| 10,255 |
utf_8
|
c362c71608a367b36e27faf346c8e810
|
% RANSAC - Robustly fits a model to data with the RANSAC algorithm
%
% Usage:
%
% [M, inliers] = ransac(x, fittingfn, distfn, degenfn s, t, feedback, ...
% maxDataTrials, maxTrials)
%
% Arguments:
% x - Data sets to which we are seeking to fit a model M
% It is assumed that x is of size [d x Npts]
% where d is the dimensionality of the data and Npts is
% the number of data points.
%
% fittingfn - Handle to a function that fits a model to s
% data from x. It is assumed that the function is of the
% form:
% M = fittingfn(x)
% Note it is possible that the fitting function can return
% multiple models (for example up to 3 fundamental matrices
% can be fitted to 7 matched points). In this case it is
% assumed that the fitting function returns a cell array of
% models.
% If this function cannot fit a model it should return M as
% an empty matrix.
%
% distfn - Handle to a function that evaluates the
% distances from the model to data x.
% It is assumed that the function is of the form:
% [inliers, M] = distfn(M, x, t)
% This function must evaluate the distances between points
% and the model returning the indices of elements in x that
% are inliers, that is, the points that are within distance
% 't' of the model. Additionally, if M is a cell array of
% possible models 'distfn' will return the model that has the
% most inliers. If there is only one model this function
% must still copy the model to the output. After this call M
% will be a non-cell object representing only one model.
%
% degenfn - Handle to a function that determines whether a
% set of datapoints will produce a degenerate model.
% This is used to discard random samples that do not
% result in useful models.
% It is assumed that degenfn is a boolean function of
% the form:
% r = degenfn(x)
% It may be that you cannot devise a test for degeneracy in
% which case you should write a dummy function that always
% returns a value of 1 (true) and rely on 'fittingfn' to return
% an empty model should the data set be degenerate.
%
% s - The minimum number of samples from x required by
% fittingfn to fit a model.
%
% t - The distance threshold between a data point and the model
% used to decide whether the point is an inlier or not.
%
% feedback - An optional flag 0/1. If set to one the trial count and the
% estimated total number of trials required is printed out at
% each step. Defaults to 0.
%
% maxDataTrials - Maximum number of attempts to select a non-degenerate
% data set. This parameter is optional and defaults to 100.
%
% maxTrials - Maximum number of iterations. This parameter is optional and
% defaults to 1000.
%
% Returns:
% M - The model having the greatest number of inliers.
% inliers - An array of indices of the elements of x that were
% the inliers for the best model.
%
% If no solution could be found M and inliers are both returned as empty
% matrices and a warning reported.
%
% Note that the desired probability of choosing at least one sample free from
% outliers is set at 0.99. You will need to edit the code should you wish to
% change this (it should probably be a parameter)
%
% For an example of the use of this function see RANSACFITHOMOGRAPHY or
% RANSACFITPLANE
% References:
% M.A. Fishler and R.C. Boles. "Random sample concensus: A paradigm
% for model fitting with applications to image analysis and automated
% cartography". Comm. Assoc. Comp, Mach., Vol 24, No 6, pp 381-395, 1981
%
% Richard Hartley and Andrew Zisserman. "Multiple View Geometry in
% Computer Vision". pp 101-113. Cambridge University Press, 2001
% Copyright (c) 2003-2013 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% 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
% February 2004 - Tidied up.
% August 2005 - Specification of distfn changed to allow model fitter to
% return multiple models from which the best must be selected
% Sept 2006 - Random selection of data points changed to ensure duplicate
% points are not selected.
% February 2007 - Jordi Ferrer: Arranged warning printout.
% Allow maximum trials as optional parameters.
% Patch the problem when non-generated data
% set is not given in the first iteration.
% August 2008 - 'feedback' parameter restored to argument list and other
% breaks in code introduced in last update fixed.
% December 2008 - Octave compatibility mods
% June 2009 - Argument 'MaxTrials' corrected to 'maxTrials'!
% January 2013 - Separate code path for Octave no longer needed
function [M, inliers] = ransac(x, fittingfn, distfn, degenfn, s, t, feedback, ...
maxDataTrials, maxTrials)
% Test number of parameters
error ( nargchk ( 6, 9, nargin ) );
if nargin < 9; maxTrials = 1000; end;
if nargin < 8; maxDataTrials = 100; end;
if nargin < 7; feedback = 0; end;
[rows, npts] = size(x);
p = 0.99; % Desired probability of choosing at least one sample
% free from outliers (probably should be a parameter)
bestM = NaN; % Sentinel value allowing detection of solution failure.
trialcount = 0;
bestscore = 0;
N = 1; % Dummy initialisation for number of trials.
while N > trialcount
% Select at random s datapoints to form a trial model, M.
% In selecting these points we have to check that they are not in
% a degenerate configuration.
degenerate = 1;
count = 1;
while degenerate
% Generate s random indicies in the range 1..npts
% (If you do not have the statistics toolbox with randsample(),
% use the function RANDOMSAMPLE from my webpage)
if ~exist('randsample', 'file')
ind = randomsample(npts, s);
else
ind = randsample(npts, s);
end
% Test that these points are not a degenerate configuration.
degenerate = feval(degenfn, x(:,ind));
if ~degenerate
% Fit model to this random selection of data points.
% Note that M may represent a set of models that fit the data in
% this case M will be a cell array of models
M = feval(fittingfn, x(:,ind));
% Depending on your problem it might be that the only way you
% can determine whether a data set is degenerate or not is to
% try to fit a model and see if it succeeds. If it fails we
% reset degenerate to true.
if isempty(M)
degenerate = 1;
end
end
% Safeguard against being stuck in this loop forever
count = count + 1;
if count > maxDataTrials
warning('Unable to select a nondegenerate data set');
break
end
end
% Once we are out here we should have some kind of model...
% Evaluate distances between points and model returning the indices
% of elements in x that are inliers. Additionally, if M is a cell
% array of possible models 'distfn' will return the model that has
% the most inliers. After this call M will be a non-cell object
% representing only one model.
[inliers, M] = feval(distfn, M, x, t);
% Find the number of inliers to this model.
ninliers = length(inliers);
if ninliers > bestscore % Largest set of inliers so far...
bestscore = ninliers; % Record data for this model
bestinliers = inliers;
bestM = M;
% Update estimate of N, the number of trials to ensure we pick,
% with probability p, a data set with no outliers.
fracinliers = ninliers/npts;
pNoOutliers = 1 - fracinliers^s;
pNoOutliers = max(eps, pNoOutliers); % Avoid division by -Inf
pNoOutliers = min(1-eps, pNoOutliers);% Avoid division by 0.
N = log(1-p)/log(pNoOutliers);
end
trialcount = trialcount+1;
if feedback
fprintf('trial %d out of %d \r',trialcount, ceil(N));
end
% Safeguard against being stuck in this loop forever
if trialcount > maxTrials
warning( ...
sprintf('ransac reached the maximum number of %d trials',...
maxTrials));
break
end
end
if feedback, fprintf('\n'); end
if ~isnan(bestM) % We got a solution
M = bestM;
inliers = bestinliers;
else
M = [];
inliers = [];
warning('ransac was unable to find a useful solution');
end
|
github
|
jacksky64/imageProcessing-master
|
fitline.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/fitline.m
| 3,537 |
utf_8
|
4b7acec43fdeacc38c926e7d3e6d8a59
|
% FITLINE - Least squares fit of a line to a set of points
%
% Usage: [C, dist] = fitline(XY)
%
% Where: XY - 2xNpts array of xy coordinates to fit line to data of
% the form
% [x1 x2 x3 ... xN
% y1 y2 y3 ... yN]
%
% XY can also be a 3xNpts array of homogeneous coordinates.
%
% Returns: C - 3x1 array of line coefficients in the form
% c(1)*X + c(2)*Y + c(3) = 0
% dist - Array of distances from the fitted line to the supplied
% data points. Note that dist is only calculated if the
% function is called with two output arguments.
%
% The magnitude of C is scaled so that line equation corresponds to
% sin(theta)*X + (-cos(theta))*Y + rho = 0
% where theta is the angle between the line and the x axis and rho is the
% perpendicular distance from the origin to the line. Rescaling the
% coefficients in this manner allows the perpendicular distance from any
% point (x,y) to the line to be simply calculated as
% r = abs(c(1)*X + c(2)*Y + c(3))
%
%
% If you want to convert this line representation to the classical form
% Y = a*X + b
% use
% a = -c(1)/c(2)
% b = -c(3)/c(2)
%
% Note, however, that this assumes c(2) is not zero
% Copyright (c) 2003-2008 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 2003 - Original version
% September 2004 - Rescaling to allow simple distance calculation.
% November 2008 - Normalising of coordinates added to condition the solution.
function [C, dist] = fitline(XY)
[rows,npts] = size(XY);
if npts < 2
error('Too few points to fit line');
end
if rows ==2 % Add homogeneous scale coordinate of 1
XY = [XY; ones(1,npts)];
end
if npts == 2 % Pad XY with a third column of zeros
XY = [XY zeros(3,1)];
end
% Normalise points so that centroid is at origin and mean distance from
% origin is sqrt(2). This conditions the equations
[XYn, T] = normalise2dpts(XY);
% Set up constraint equations of the form XYn'*C = 0,
% where C is a column vector of the line coefficients
% in the form c(1)*X + c(2)*Y + c(3) = 0.
[u d v] = svd(XYn',0); % Singular value decomposition.
C = v(:,3); % Solution is last column of v.
% Denormalise the solution
C = T'*C;
% Rescale coefficients so that line equation corresponds to
% sin(theta)*X + (-cos(theta))*Y + rho = 0
% so that the perpendicular distance from any point (x,y) to the line
% to be simply calculated as
% r = abs(c(1)*X + c(2)*Y + c(3))
theta = atan2(C(1), -C(2));
% Find the scaling (but avoid dividing by zero)
if abs(sin(theta)) > abs(cos(theta))
k = C(1)/sin(theta);
else
k = -C(2)/cos(theta);
end
C = C/k;
% If requested, calculate the distances from the fitted line to
% the supplied data points
if nargout==2
dist = abs(C(1)*XY(1,:) + C(2)*XY(2,:) + C(3));
end
|
github
|
jacksky64/imageProcessing-master
|
ransacfitline.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/ransacfitline.m
| 4,628 |
utf_8
|
164727c9f870963847fe09846fef96a5
|
% RANSACFITLINE - fits line to 3D array of points using RANSAC
%
% Usage [L, inliers] = ransacfitline(XYZ, t, feedback)
%
% This function uses the RANSAC algorithm to robustly fit a line
% to a set of 3D data points.
%
% Arguments:
% XYZ - 3xNpts array of xyz coordinates to fit line to.
% t - The distance threshold between data point and the line
% used to decide whether a point is an inlier or not.
% feedback - Optional flag 0 or 1 to turn on RANSAC feedback
% information.
%
% Returns:.
% V - Line obtained by a simple fitting on the points that
% are considered inliers. The line goes through the
% calculated mean of the inlier points, and is parallel to
% the principal eigenvector. The line is scaled by the
% square root of the largest eigenvalue.
% This line is a n*2 matrix. The first column is the
% beginning point, the second column is the end point of the
% line.
% L - The two points in the data set that were found to
% define a line having the most number of inliers.
% The two columns of L defining the two points.
% inliers - The indices of the points that were considered
% inliers to the fitted line.
%
% See also: RANSAC, FITPLANE, RANSACFITPLANE
% Copyright (c) 2003-2006 Peter Kovesi and Felix Duvallet (CMU)
% 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.
% Aug 2006 - created ransacfitline from ransacfitplane
% author: Felix Duvallet
function [V, L, inliers] = ransacfitline(XYZ, t, feedback)
if nargin == 2
feedback = 0;
end
[rows, npts] = size(XYZ);
if rows ~=3
error('data is not 3D');
end
if npts < 2
error('too few points to fit line');
end
s = 2; % Minimum No of points needed to fit a line.
fittingfn = @defineline;
distfn = @lineptdist;
degenfn = @isdegenerate;
[L, inliers] = ransac(XYZ, fittingfn, distfn, degenfn, s, t, feedback);
% Find the line going through the mean, parallel to the major
% eigenvector
V = fitline3d(XYZ(:, inliers));
%------------------------------------------------------------------------
% Function to define a line given 2 data points as required by
% RANSAC.
function L = defineline(X);
L = X;
%------------------------------------------------------------------------
% Function to calculate distances between a line and an array of points.
% The line is defined by a 3x2 matrix, L. The two columns of L defining
% two points that are the endpoints of the line.
%
% A line can be defined with two points as:
% lambda*p1 + (1-lambda)*p2
% Then, the distance between the line and another point (p3) is:
% norm( lambda*p1 + (1-lambda)*p2 - p3 )
% where
% (p2-p1).(p2-p3)
% lambda = ---------------
% (p1-p2).(p1-p2)
%
% lambda can be found by taking the derivative of:
% (lambda*p1 + (1-lambda)*p2 - p3)*(lambda*p1 + (1-lambda)*p2 - p3)
% with respect to lambda and setting it equal to zero
function [inliers, L] = lineptdist(L, X, t)
p1 = L(:,1);
p2 = L(:,2);
npts = length(X);
d = zeros(npts, 1);
for i = 1:npts
p3 = X(:,i);
lambda = dot((p2 - p1), (p2-p3)) / dot( (p1-p2), (p1-p2) );
d(i) = norm(lambda*p1 + (1-lambda)*p2 - p3);
end
inliers = find(abs(d) < t);
%------------------------------------------------------------------------
% Function to determine whether a set of 2 points are in a degenerate
% configuration for fitting a line as required by RANSAC.
% In this case two points are degenerate if they are the same point
% or if they are exceedingly close together.
function r = isdegenerate(X)
%find the norm of the difference of the two points
% this will be 0 iff the two points are the same (the norm of their
% difference is zero)
r = norm(X(:,1) - X(:,2)) < eps;
|
github
|
jacksky64/imageProcessing-master
|
ransacfitplane.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/ransacfitplane.m
| 4,394 |
utf_8
|
baa5ff279844792a35a0615536c87855
|
% RANSACFITPLANE - fits plane to 3D array of points using RANSAC
%
% Usage [B, P, inliers] = ransacfitplane(XYZ, t, feedback)
%
% This function uses the RANSAC algorithm to robustly fit a plane
% to a set of 3D data points.
%
% Arguments:
% XYZ - 3xNpts array of xyz coordinates to fit plane to.
% t - The distance threshold between data point and the plane
% used to decide whether a point is an inlier or not.
% feedback - Optional flag 0 or 1 to turn on RANSAC feedback
% information.
%
% Returns:
% B - 4x1 array of plane coefficients in the form
% b(1)*X + b(2)*Y +b(3)*Z + b(4) = 0
% The magnitude of B is 1.
% This plane is obtained by a least squares fit to all the
% points that were considered to be inliers, hence this
% plane will be slightly different to that defined by P below.
% P - The three points in the data set that were found to
% define a plane having the most number of inliers.
% The three columns of P defining the three points.
% inliers - The indices of the points that were considered
% inliers to the fitted plane.
%
% See also: RANSAC, FITPLANE
% Copyright (c) 2003-2008 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 2003 - Original version.
% Feb 2004 - Modified to use separate ransac function
% Aug 2005 - planeptdist modified to fit new ransac specification
% Dec 2008 - Much faster distance calculation in planeptdist (thanks to
% Alastair Harrison)
function [B, P, inliers] = ransacfitplane(XYZ, t, feedback)
if nargin == 2
feedback = 0;
end
[rows, npts] = size(XYZ);
if rows ~=3
error('data is not 3D');
end
if npts < 3
error('too few points to fit plane');
end
s = 3; % Minimum No of points needed to fit a plane.
fittingfn = @defineplane;
distfn = @planeptdist;
degenfn = @isdegenerate;
[P, inliers] = ransac(XYZ, fittingfn, distfn, degenfn, s, t, feedback);
% Perform least squares fit to the inlying points
B = fitplane(XYZ(:,inliers));
%------------------------------------------------------------------------
% Function to define a plane given 3 data points as required by
% RANSAC. In our case we use the 3 points directly to define the plane.
function P = defineplane(X);
P = X;
%------------------------------------------------------------------------
% Function to calculate distances between a plane and a an array of points.
% The plane is defined by a 3x3 matrix, P. The three columns of P defining
% three points that are within the plane.
function [inliers, P] = planeptdist(P, X, t)
n = cross(P(:,2)-P(:,1), P(:,3)-P(:,1)); % Plane normal.
n = n/norm(n); % Make it a unit vector.
npts = length(X);
d = zeros(npts,1); % d will be an array of distance values.
% The following loop builds up the dot product between a vector from P(:,1)
% to every X(:,i) with the unit plane normal. This will be the
% perpendicular distance from the plane for each point
for i=1:3
d = d + (X(i,:)'-P(i,1))*n(i);
end
inliers = find(abs(d) < t);
%------------------------------------------------------------------------
% Function to determine whether a set of 3 points are in a degenerate
% configuration for fitting a plane as required by RANSAC. In this case
% they are degenerate if they are colinear.
function r = isdegenerate(X)
% The three columns of X are the coords of the 3 points.
r = iscolinear(X(:,1),X(:,2),X(:,3));
|
github
|
jacksky64/imageProcessing-master
|
testfund.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/example/testfund.m
| 4,834 |
utf_8
|
0a1cac5c368987d90056180271adbfb5
|
% Demonstration of feature matching via simple correlation, and then using
% RANSAC to estimate the fundamental matrix and at the same time identify
% (mostly) inlying matches
%
% Usage: testfund - Demonstrates fundamental matrix calculation
% on two default images.
% testfund(im1,im2) - Computes fundamental matrix on two supplied
% images.
%
% Edit code as necessary to tweak parameters
% Copyright (c) 2004-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.
% February 2004
% August 2005 Octave compatibility
% July 2013 Adust threshold to suit use of Farid and Simoncelli's
% derivative filters now used in harris.m
% June 2016 Changed to suit new calling method for harris.m
function testfund(im1,im2)
if nargin == 0
im1 = imread('im02.jpg');
im2 = imread('im03.jpg');
end
v = version; Octave=v(1)<'5'; % Crude Octave test
nonmaxrad = 3; % Non-maximal suppression radius
dmax = 50; % Maximum search distance for matching
w = 11; % Window size for correlation matching
% Find 100 strongest Harris corners in image1 and image2
[cim1, r1, c1] = harris(im1, 1, 0.04, 'N', 100, 'radius', nonmaxrad);
show(im1,1), hold on, plot(c1,r1,'r+');
[cim2, r2, c2] = harris(im2, 1, 0.04, 'N', 100, 'radius', nonmaxrad);
show(im2,2), hold on, plot(c2,r2,'r+');
drawnow
correlation = 1; % Change this between 1 or 0 to switch between the two
% matching functions below
if correlation % Use normalised correlation matching
[m1,m2] = matchbycorrelation(im1, [r1';c1'], im2, [r2';c2'], w, dmax);
else % Use monogenic phase matching
nscale = 1;
minWaveLength = 10;
mult = 4;
sigmaOnf = .2;
[m1,m2] = matchbymonogenicphase(im1, [r1';c1'], im2, [r2';c2'], w, dmax,...
nscale, minWaveLength, mult, sigmaOnf);
end
% Display putative matches
show(im1,3), set(3,'name','Putative matches')
if Octave, figure(1); title('Putative matches'), axis('equal'), end
for n = 1:length(m1);
line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)])
end
% Assemble homogeneous feature coordinates for fitting of the
% fundamental matrix, note that [x,y] corresponds to [col, row]
x1 = [m1(2,:); m1(1,:); ones(1,length(m1))];
x2 = [m2(2,:); m2(1,:); ones(1,length(m1))];
t = .002; % Distance threshold for deciding outliers
% Change the commenting on the lines below to switch between the use
% of 7 or 8 point fundamental matrix solutions, or affine fundamental
% matrix solution.
% [F, inliers] = ransacfitfundmatrix7(x1, x2, t, 1);
[F, inliers] = ransacfitfundmatrix(x1, x2, t, 1);
% [F, inliers] = ransacfitaffinefund(x1, x2, t, 1);
fprintf('Number of inliers was %d (%d%%) \n', ...
length(inliers),round(100*length(inliers)/length(m1)))
fprintf('Number of putative matches was %d \n', length(m1))
% Display both images overlayed with inlying matched feature points
if Octave
figure(4); title('Inlying matches'), axis('equal'),
else
show(im1,4), set(4,'name','Inlying matches'), hold on
end
plot(m1(2,inliers),m1(1,inliers),'r+');
plot(m2(2,inliers),m2(1,inliers),'g+');
for n = inliers
line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)],'color',[0 0 1])
end
if Octave, return, end
response = input('Step through each epipolar line [y/n]?\n','s');
if response == 'n'
return
end
% Step through each matched pair of points and display the
% corresponding epipolar lines on the two images.
l2 = F*x1; % Epipolar lines in image2
l1 = F'*x2; % Epipolar lines in image1
% Solve for epipoles
[U,D,V] = svd(F);
e1 = hnormalise(V(:,3));
e2 = hnormalise(U(:,3));
for n = inliers
figure(1), clf, imshow(im1), hold on, plot(x1(1,n),x1(2,n),'r+');
hline(l1(:,n)); plot(e1(1), e1(2), 'g*');
figure(2), clf, imshow(im2), hold on, plot(x2(1,n),x2(2,n),'r+');
hline(l2(:,n)); plot(e2(1), e2(2), 'g*');
fprintf('hit any key to see next point\r'); pause
end
fprintf(' \n');
|
github
|
jacksky64/imageProcessing-master
|
testfitline.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/example/testfitline.m
| 3,953 |
utf_8
|
f97a656b9a7452fe4bce589b0ea934c4
|
% TESTFITLINE - demonstrates RANSAC line fitting
%
% Usage: testfitline(outliers, sigma, t, feedback)
%
% Arguments:
% outliers - Fraction specifying how many points are to be
% outliers.
% sigma - Standard deviation of inlying points from the
% true line.
% t - Distance threshold to be used by the RANSAC
% algorithm for deciding whether a point is an
% inlier.
% feedback - Optional flag 0 or 1 to turn on RANSAC feedback
% information.
%
% Try using: testfitline(0.3, 0.05, 0.05)
%
% See also: RANSACFITPLANE, FITPLANE
% Copyright (c) 2003-2006 Peter Kovesi and Felix Duvallet (CMU)
% 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.
% August 2006 testfitline created from testfitplane
% author: Felix Duvallet
function testfitline(outliers, sigma, t, feedback)
close all;
if nargin == 3
feedback = 0;
end
% Hard wire some constants - vary these as you wish
npts = 100; % Number of 3D data points
% Define a line:
% Y = m*X
% Z = n*X + Y + b
% This definition needs fixing, but it works for now
m = 6;
n = -3;
b = -4;
outsigma = 30*sigma; % outlying points have a distribution that is
% 30 times as spread as the inlying points
vpts = round((1-outliers)*npts); % No of valid points
opts = npts - vpts; % No of outlying points
% Generate npts points in the line
X = rand(1,npts);
Y = m*X;
Z = n*X + Y + b;
Z = zeros(size(Y));
XYZ = [X
Y
Z];
% Add uniform noise of +/-sigma
XYZ = XYZ + (2*rand(size(XYZ))-1)*sigma;
% Generate opts random outliers
n = length(XYZ);
ind = randperm(n); % get a random set of point indices
ind = ind(1:opts); % ... of length opts
% Add uniform noise of outsigma to the points chosen to be outliers.
XYZ(:,ind) = XYZ(:,ind) + sign(rand(3,opts)-.5).*(rand(3,opts)+1)*outsigma;
% Perform RANSAC fitting of the line
[V, P, inliers] = ransacfitline(XYZ, t, feedback);
if(feedback)
disp(['Number of Inliers: ' num2str(length(inliers)) ]);
end
% We want to plot the inlier points blue, with the outlier points in
% red. In order to do that, we must find the outliers.
% Use setxor on all the points, and the inliers to find outliers
% (plotting all the points in red and then plotting over them in blue
% does not work well)
oulier_points = setxor(transpose(XYZ), transpose(XYZ(:, inliers)), 'rows');
oulier_points = oulier_points';
% Display the cloud of outlier points
figure(1); clf
hold on;
plot3(oulier_points(1,:),oulier_points(2,:),oulier_points(3,:), 'r*');
% Plot the inliers as blue points
plot3(XYZ(1,inliers), XYZ(2, inliers), XYZ(3, inliers), 'b*');
% Display the line formed by the 2 points that gave the
% line of maximum consensus as a green line
line(P(1,:), P(2,:), P(3,:), 'Color', 'green', 'LineWidth', 4);
%Display the line formed by the covariance fitting in magenta
line(V(1,:), V(2, :), V(3,:), 'Color', 'magenta', 'LineWidth', 5);
box('on'), grid('on'), rotate3d('on')
|
github
|
jacksky64/imageProcessing-master
|
testhomog.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/example/testhomog.m
| 2,978 |
utf_8
|
8c24c0c26133700b6ca737053fc660e7
|
% Demonstration of feature matching via simple correlation, and then using
% RANSAC to estimate the homography between two images and at the same time
% identify (mostly) inlying matches
%
% Usage: testhomog - Demonstrates homography calculation on two
% default images
% testhomog(im1,im2) - Computes homography on two supplied images
%
% Edit code as necessary to tweak parameters
% Copyright (c) 2004-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.
% February 2004
% August 2005 Octave compatibility
function testhomog(im1,im2)
if nargin == 0
im1 = imread('boats.tif');
im2 = imread('boatsrot.tif');
end
close all
v = version; Octave=v(1)<'5'; % Crude Octave test
thresh = 500; % Harris corner threshold
nonmaxrad = 3; % Non-maximal suppression radius
dmax = 50;
w = 11; % Window size for correlation matching
% Find Harris corners in image1 and image2
[cim1, r1, c1] = harris(im1, 1, thresh, 3);
show(im1,1), hold on, plot(c1,r1,'r+');
[cim2, r2, c2] = harris(im2, 1, thresh, 3);
show(im2,2), hold on, plot(c2,r2,'r+');
drawnow
[m1,m2] = matchbycorrelation(im1, [r1';c1'], im2, [r2';c2'], w, dmax);
% Display putative matches
show(im1,3), set(3,'name','Putative matches'),
if Octave, figure(1); title('Putative matches'), axis('equal'), end
for n = 1:length(m1);
line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)])
end
% Assemble homogeneous feature coordinates for fitting of the
% homography, note that [x,y] corresponds to [col, row]
x1 = [m1(2,:); m1(1,:); ones(1,length(m1))];
x2 = [m2(2,:); m2(1,:); ones(1,length(m1))];
t = .001; % Distance threshold for deciding outliers
[H, inliers] = ransacfithomography(x1, x2, t);
fprintf('Number of inliers was %d (%d%%) \n', ...
length(inliers),round(100*length(inliers)/length(m1)))
fprintf('Number of putative matches was %d \n', length(m1))
% Display both images overlayed with inlying matched feature points
if Octave
figure(4); title('Inlying matches'), axis('equal'),
else
show(im1,4), set(4,'name','Inlying matches'), hold on
end
plot(m1(2,inliers),m1(1,inliers),'r+');
plot(m2(2,inliers),m2(1,inliers),'g+');
for n = inliers
line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)],'color',[0 0 1])
end
|
github
|
jacksky64/imageProcessing-master
|
testfundOctave.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/example/testfundOctave.m
| 2,769 |
utf_8
|
44430d35fa0a1d0a29001b5d76e0f81a
|
% Demonstration of feature matching via simple correlation, and then using
% RANSAC to estimate the fundamental matrix and at the same time identify
% (mostly) inlying matches
% 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
%
% February 2004
% August 2005 Octave version
function testfundOctave
close all
thresh = 500; % Harris corner threshold
nonmaxrad = 3; % Non-maximal suppression radius
dmax = 50;
w = 11; % Window size for correlation matching
im1 = imread('im02.jpg');
im2 = imread('im03.jpg');
% Find Harris corners in image1 and image2
[cim1, r1, c1] = harris(im1, 1, thresh, 3);
% show(im1,1), hold on, plot(c1,r1,'r+');
[cim2, r2, c2] = harris(im2, 1, thresh, 3);
% show(im2,2), hold on, plot(c2,r2,'r+');
drawnow
[m1,m2] = matchbycorrelation(im1, [r1';c1'], im2, [r2';c2'], w, dmax);
% Display putative matches
% show(im1,3), set(3,'name','Putative matches'), hold on
for n = 1:length(m1);
line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)])
end
% Assemble homogeneous feature coordinates for fitting of the
% fundamental matrix, note that [x,y] corresponds to [col, row]
x1 = [m1(2,:); m1(1,:); ones(1,length(m1))];
x2 = [m2(2,:); m2(1,:); ones(1,length(m1))];
t = .001; % Distance threshold for deciding outliers
[F, inliers] = ransacfitfundmatrix(x1, x2, t);
fprintf('Number of inliers was %d (%d%%) \n', ...
length(inliers),round(100*length(inliers)/length(m1)))
fprintf('Number of putative matches was %d \n', length(m1))
% Display both images overlayed with inlying matched feature points
% show(double(im1)+double(im2),4), set(4,'name','Inlying matches'), hold on
plot(m1(2,inliers),m1(1,inliers),'r+');
plot(m2(2,inliers),m2(1,inliers),'g+');
for n = inliers
line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)],'color',[0 0 1])
end
% Step through each matched pair of points and display the
% corresponding epipolar lines on the two images.
l2 = F*x1; % Epipolar lines in image2
l1 = F'*x2; % Epipolar lines in image1
% Solve for epipoles
[U,D,V] = svd(F,0);
e1 = hnormalise(V(:,3));
e2 = hnormalise(U(:,3));
return
for n = inliers
figure(1), clf, imshow(im1), hold on, plot(x1(1,n),x1(2,n),'r+');
hline(l1(:,n)); plot(e1(1), e1(2), 'g*');
figure(2), clf, imshow(im2), hold on, plot(x2(1,n),x2(2,n),'r+');
hline(l2(:,n)); plot(e2(1), e2(2), 'g*');
fprintf('hit any key to see next point\r'); pause
end
fprintf(' \n');
|
github
|
jacksky64/imageProcessing-master
|
testfitplane.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/example/testfitplane.m
| 3,474 |
utf_8
|
8e3a7a2e2bd65da6d3a122e6e903d3f8
|
% TESTFITPLANE - demonstrates RANSAC plane fitting
%
% Usage: testfitplane(outliers, sigma, t, feedback)
%
% Arguments:
% outliers - Fraction specifying how many points are to be
% outliers.
% sigma - Standard deviation of inlying points from the
% true plane.
% t - Distance threshold to be used by the RANSAC
% algorithm for deciding whether a point is an
% inlier.
% feedback - Optional flag 0 or 1 to turn on RANSAC feedback
% information.
%
% Try using: testfitplane(0.3, 0.05, 0.05)
%
% See also: RANSACFITPLANE, FITPLANE
% Copyright (c) 2003-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.
% June 2003
function testfitplane(outliers, sigma, t, feedback)
if nargin == 3
feedback = 0;
end
% Hard wire some constants - vary these as you wish
npts = 100; % Number of 3D data points
% Define a plane ax + by + cz + d = 0
a = 10; b = -3; c = 5; d = 1;
B = [a b c d]';
B = B/norm(B);
outsigma = 30*sigma; % outlying points have a distribution that is
% 30 times as spread as the inlying points
vpts = round((1-outliers)*npts); % No of valid points
opts = npts - vpts; % No of outlying points
% Generate npts points in the plane
X = rand(1,npts);
Y = rand(1,npts);
Z = (-a*X -b*Y -d)/c;
XYZ = [X
Y
Z];
% Add uniform noise of +/-sigma
XYZ = XYZ + (2*rand(size(XYZ))-1)*sigma;
% Generate opts random outliers
n = length(XYZ);
ind = randperm(n); % get a random set of point indices
ind = ind(1:opts); % ... of length opts
% Add uniform noise of outsigma to the points chosen to be outliers.
% XYZ(:,ind) = XYZ(:,ind) + (2*rand(3,opts)-1)*outsigma;
XYZ(:,ind) = XYZ(:,ind) + sign(rand(3,opts)-.5).*(rand(3,opts)+1)*outsigma;
% Display the cloud of points
figure(1), clf, plot3(XYZ(1,:),XYZ(2,:),XYZ(3,:), 'r*');
% Perform RANSAC fitting of the plane
[Bfitted, P, inliers] = ransacfitplane(XYZ, t, feedback);
fprintf('Original plane coefficients: ');
fprintf('%8.3f ',B);
fprintf('\nFitted plane coefficients: ');
fprintf('%8.3f ',Bfitted);
fprintf('\n');
% Display the triangular patch formed by the 3 points that gave the
% plane of maximum consensus
patch(P(1,:), P(2,:), P(3,:), 'g')
box('on'), grid('on'), rotate3d('on')
fprintf('\nRotate image so that planar patch is seen edge on\n');
fprintf('If the fit has been successful the inlying points should\n');
fprintf('form a line\n\n');
|
github
|
jacksky64/imageProcessing-master
|
testvgghomog.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Robust/example/testvgghomog.m
| 2,985 |
utf_8
|
fb71f9f4828200b6a682941b00c1b3a6
|
% Demonstration of feature matching via simple correlation, and then using
% RANSAC to estimate the homography between two images and at the same time
% identify (mostly) inlying matches
%
% Usage: testhomog - Demonstrates homography calculation on two
% default images
% testhomog(im1,im2) - Computes homography on two supplied images
%
% Edit code as necessary to tweak parameters
% Copyright (c) 2004-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.
% February 2004
% August 2005 Octave compatibility
function testvgghomog(im1,im2)
if nargin == 0
im1 = imread('boats.tif');
im2 = imread('boatsrot.tif');
end
close all
v = version; Octave=v(1)<'5'; % Crude Octave test
thresh = 500; % Harris corner threshold
nonmaxrad = 3; % Non-maximal suppression radius
dmax = 50;
w = 11; % Window size for correlation matching
% Find Harris corners in image1 and image2
[cim1, r1, c1] = harris(im1, 1, thresh, 3);
show(im1,1), hold on, plot(c1,r1,'r+');
[cim2, r2, c2] = harris(im2, 1, thresh, 3);
show(im2,2), hold on, plot(c2,r2,'r+');
drawnow
[m1,m2] = matchbycorrelation(im1, [r1';c1'], im2, [r2';c2'], w, dmax);
% Display putative matches
show(im1,3), set(3,'name','Putative matches'),
if Octave, figure(1); title('Putative matches'), axis('equal'), end
for n = 1:length(m1);
line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)])
end
% Assemble homogeneous feature coordinates for fitting of the
% homography, note that [x,y] corresponds to [col, row]
x1 = [m1(2,:); m1(1,:); ones(1,length(m1))];
x2 = [m2(2,:); m2(1,:); ones(1,length(m1))];
t = .001; % Distance threshold for deciding outliers
[H, inliers] = ransacfithomography_vgg(x1, x2, t);
fprintf('Number of inliers was %d (%d%%) \n', ...
length(inliers),round(100*length(inliers)/length(m1)))
fprintf('Number of putative matches was %d \n', length(m1))
% Display both images overlayed with inlying matched feature points
if Octave
figure(4); title('Inlying matches'), axis('equal'),
else
show(im1,4), set(4,'name','Inlying matches'), hold on
end
plot(m1(2,inliers),m1(1,inliers),'r+');
plot(m2(2,inliers),m2(1,inliers),'g+');
for n = inliers
line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)],'color',[0 0 1])
end
|
github
|
jacksky64/imageProcessing-master
|
map2lutfile.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/map2lutfile.m
| 754 |
utf_8
|
2300f6e519f599653ffb3bf7f3286eeb
|
% MAP2LUTFILE Writes a colourmap to a .lut file for use with ImageJ
%
% Usage: map2lutfile(map, fname)
%
% The format of a lookup table for ImageJ is 256 bytes of red values, followed
% by 256 green values and finally 256 blue values. A total of 768 bytes.
%
% PK June 2014
function map2lutfile(map, fname)
[N, chan] = size(map);
if N ~= 256 | chan ~= 3
error('Colourmap must be 256x3');
end
% Ensure file has a .lut ending
if ~strendswith(fname, '.lut')
fname = [fname '.lut'];
end
% Convert map to integers 0-255 and form into a single vector of
% sequential RGB values
map = round(map(:)*255);
fid = fopen(fname, 'w');
fwrite(fid, map, 'uint8');
fclose(fid);
|
github
|
jacksky64/imageProcessing-master
|
labmaplib.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/labmaplib.m
| 57,246 |
utf_8
|
dcd370a01f0282850d06f15390cb801c
|
% LABMAPLIB Library of colour maps designed in CIELAB or RGB space
%
% Usage: 1: [map, name, desc] = labmaplib(I, param_name, value ...)
% 2: labmaplib
% 3: labmaplib(str)
%
% Arguments for Usage 1:
%
% I - An integer specifying the index of the colour map to be
% generated or a string specifying a colour map name to search
% for. Type labmaplib with no arguments to get a full list of
% possible colour maps and their corresponding numbers.
%
% Possible param_name - value options:
%
% 'chromaK' - The scaling to apply to the chroma values of the colour map,
% 0 - 1. The default is 1 giving a fully saturated colour map
% as designed. However, depending on your application you may
% want a colour map with reduced chroma/saturation values.
% You can use values greater than 1 however gamut clipping is
% likely to occur giving rise to artifacts in the colour map.
% 'N' - Number of values in the colour map. Defaults to 256.
% 'shift' - Fraction of the colour map length N that the colour map is
% to be cyclically rotated, may be negative. (Should only be
% applied to cyclic colour maps!). Defaults to 0.
% 'reverse' - If set to 1 reverses the colour map. Defaults to 0.
% 'diagnostics' - If set to 1 displays various diagnostic plots. Note the
% diagnostic plots will be for the map _before_ any cyclic
% shifting or reversing is applied. Defaults to 0.
%
% The parameter name strings can be abbreviated to their first letter.
%
% Returns:
% map - Nx3 rgb colour map
% name - A string giving a nominal name for the colour map
% desc - A string giving a brief description of the colour map
%
% Colour Map naming convention:
%
% linear_kryw_5-100_c67_n256
% / / | \ \
% Colour Map attribute(s) / | \ Number of colour map entries
% / | \
% String indicating nominal | Mean chroma of colour map
% hue sequence. |
% Range of lightness values
%
% In addition, the name of the colour map may have cyclic shift information
% appended to it, it may also have a flag indicating it is reversed.
%
% cyclic_wrwbw_90-40_c42_n256_s25_r
% / \
% / Indicates that the map is reversed.
% /
% Percentage of colour map length
% that the map has been rotated by.
%
% * Attributes may be: linear, diverging, cyclic, rainbow, or isoluminant. A
% colour map may have more than one attribute. For example, diverging-linear or
% cyclic-isoluminant.
%
% * Lightness values can range from 0 to 100. For linear colour maps the two
% lightness values indicate the first and last lightness values in the
% map. For diverging colour maps the second value indicates the lightness value
% of the centre point of the colour map (unless it is a diverging-linear
% colour map). For cyclic and rainbow colour maps the two values indicate the
% minimum and maximum lightness values. Isoluminant colour maps have only
% one lightness value.
%
% * The string of characters indicating the nominal hue sequence uses the following code
% r - red g - green b - blue
% c - cyan m - magenta y - yellow
% o - orange v - violet
% k - black w - white j - grey
%
% ('j' rhymes with grey). Thus a 'heat' style colour map would be indicated by
% the string 'kryw'. If the colour map is predominantly one colour then the
% full name of that colour may be used. Note these codes are mainly used to
% indicate the hues of the colour map independent of the lightness/darkness and
% saturation of the colours.
%
% * Mean chroma/saturation is an indication of vividness of the colour map. A
% value of 0 corresponds to a greyscale. A value of 50 or more will indicate a
% vivid colour map.
%
%
% Usage 2 and 3: labmaplib(str)
%
% Given the large number of colour maps that this function can create this usage
% option provides some help by listing the numbers of all the colour maps with
% names containing the string 'str'. Typically this is used to search for
% colour maps having a specified attribute: 'linear', 'diverging', 'rainbow',
% 'cyclic', or 'isoluminant' etc. If 'str' is omitted all colour maps are
% listed.
%
% >> labmaplib % lists all colour maps
% >> labmaplib('diverging') % lists all diverging colour maps
%
% Note the listing of colour maps can be a bit slow because each colour map has to
% be created in order to determine its full name.
%
% See also: EQUALISECOLOURMAP, VIEWLABSPACE, SINERAMP, CIRCLESINERAMP, COLOURMAPPATH
% Adding your own colour maps is straightforward.
%
% 1) Colour maps are almost invariably defined via a spline path through CIELAB
% colourspace. Use VIEWLABSPACE to work out the positions of the spline
% control points in CIELAB space to achieve the colour map path you desire.
% These are stored in an array 'colpts' with columns corresponding to L a
% and b. If desired the path can be specified in terms of RGB space by
% setting 'colourspace' to 'RGB'. See the ternary colour maps as an example.
%
% 2) Set 'splineorder' to 2 for a linear spline segments. Use 3 for a quadratic
% b-spline.
%
% 3) If the colour map path has lightness gradient reversals set 'sigma' to a
% value of around 5 to 7 to smooth the gradient reversal.
%
% 4) If the colour map is of very low lightness contrast, or isoluminant, set
% the lightness, a and b colour difference weight vector W to [1 1 1].
% See EQUALISECOLOURMAP for more details
%
% 5) Set the attribute and hue sequence strings ('attributeStr' and 'hueStr')
% appropriately so that a colour map name can be generated. Note that if you
% are constructing a cyclic colour map it is important that 'attributeStr'
% contains the word 'cyclic'. This ensures that a periodic b-spline is used
% and also ensures that smoothing is applied in a cyclic manner. Setting the
% description string is optional.
%
% 6) Run LABMAPLIB specifying the number of your new colour map with the
% diagnostics flag set to one. Various plots are generated allowing you to
% check the perceptual uniformity, colour map path, and any gamut clipping of
% your colour map.
% Copyright (c) 2013-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.
% December 2013 Original version
% March 2014 Various enhancements
% August 2014 Catalogue listing
% September 2014 Provision for specifying paths in RGB, cyclic shifting and
% reversing
function [map, name, desc] = labmaplib(varargin)
[I, N, chromaK, shift, reverse, diagnostics] = parseinputs(varargin{:});
% Check if the user wants to list a catalogue of colour maps
if ischar(I)
catalogue(I);
return
end
% Default parameters for colour map construction.
% Individual colour map specifications may override some of these.
colourspace = 'LAB'; % Control points specified in CIELAB space
sigma = 0; % Default smoothing for colour map lightness equalisation.
splineorder = 3; % Default order of b-spline colour map curve.
formula = 'CIE76'; % Default colour difference formula.
W = [1 0 0]; % Colour difference weighting for Lightness,
% chroma and hue (default is to only use Lightness)
desc = '';
name = '';
attributeStr = '';
hueStr = '';
switch I
%% 1-19 series: Linear scales going from low to high
case 1 % Grey 0 - 100
desc = 'Grey scale';
attributeStr = 'linear';
hueStr = 'grey';
colpts = [ 0 0 0
100 0 0];
splineorder = 2;
case 2 % Grey 10 - 95
desc = ['Grey scale with slightly reduced contrast to '...
'avoid display saturation problems'];
attributeStr = 'linear';
hueStr = 'grey';
colpts = [10 0 0
95 0 0];
splineorder = 2;
case 3
desc = 'Black-Red-Yellow-White heat colour map';
attributeStr = 'linear';
hueStr = 'kryw';
colpts = [5 0 0
15 37 21
25 49 37
35 60 50
45 72 60
55 80 70
65 56 73
75 31 78
85 9 84
100 0 0 ];
case 4
desc = 'Black-Red-Yellow heat colour map';
attributeStr = 'linear';
hueStr = 'kry';
colpts = [5 0 0
15 37 21
25 49 37
35 60 50
45 72 60
55 80 70
65 56 73
75 31 78
85 9 84
98 -16 93];
case 5
desc = 'Colour Map along the green edge of CIELAB space';
attributeStr = 'linear';
hueStr = 'green';
colpts = [ 5 -9 5
15 -23 20
25 -31 31
35 -39 39
45 -47 47
55 -55 55
65 -63 63
75 -71 71
85 -79 79
95 -38 90];
case 6
desc = 'Blue shades running vertically up the blue edge of CIELAB space';
attributeStr = 'linear';
hueStr = 'blue';
colpts = [ 5 30 -52
15 49 -80
25 64 -105
35 52 -103
45 26 -87
55 6 -72
65 -12 -56
75 -29 -40
85 -44 -24
95 -31 -9];
case 7
desc = 'Blue-Pink-Light Pink colour map';
attributeStr = 'linear';
hueStr = 'bmw';
colpts = [ 5 30 -52
15 49 -80
25 64 -105
35 73 -105
45 81 -88
55 90 -71
65 85 -55
75 58 -38
85 34 -23
95 10 -7];
case 10
desc = 'Blue-Magenta-Orange-Yellow highly saturated colour map';
attributeStr = 'linear';
hueStr = 'bmy';
colpts = [10 polar2ab( 78,-60)
20 polar2ab(100,-60)
30 polar2ab( 78,-40)
40 polar2ab( 74,-20)
50 polar2ab( 80, 0)
60 polar2ab( 80, 20)
70 polar2ab( 72, 50)
80 polar2ab( 84, 77)
95 polar2ab( 90, 95)];
case 11
desc = 'Blue-Green-Yellow colour map';
attributeStr = 'linear';
hueStr = 'bgy';
colpts = [10 polar2ab( 78,-60)
20 polar2ab(100,-60)
30 polar2ab( 80,-70)
40 polar2ab( 40,-100)
50 polar2ab( 37, 180)
60 polar2ab( 80, 135)
70 polar2ab( 93, 135)
80 polar2ab( 105, 135) % green
95 polar2ab( 90, 95)]; % yellow
case 12
desc = 'Blue-Magenta-Green-Yellow highly saturated colour map';
attributeStr = 'linear';
hueStr = 'bmgy';
colpts = [10 polar2ab( 78,-60)
20 polar2ab(100,-60)
30 polar2ab( 78,-40)
40 polar2ab( 74,-20)
50 polar2ab( 80, 0)
60 polar2ab( 95, 45)
70 polar2ab( 70, 110)
80 polar2ab( 105, 135)
95 polar2ab( 90, 95)];
case 13
desc = 'Dark Red-Brown-Green-Yellow colour map';
attributeStr = 'linear';
hueStr = 'rgy';
colpts = [10 polar2ab( 35, 24)
20 polar2ab( 50, 35)
30 polar2ab( 49, 55)
40 polar2ab( 50, 75)
50 polar2ab( 55, 95)
60 polar2ab( 67, 115)
70 polar2ab( 75, 115)
80 polar2ab( 80, 100)
95 polar2ab( 90, 95)];
case 14
desc = ['Attempt at a ''geographical'' colour map. '...
'Best used with relief shading'];
attributeStr = 'linear';
hueStr = 'gow';
colpts = [60 polar2ab(20, 180) % pale blue green
65 polar2ab(30, 135)
70 polar2ab(35, 75)
75 polar2ab(45, 85)
80 polar2ab(22, 90)
85 0 0 ];
case 15 % Adaptation of 14. Lighter and slightly more saturated. I
% think this is better
desc = ['Attempt at a ''geographical'' colour map. '...
'Best used with relief shading'];
attributeStr = 'linear';
hueStr = 'gow';
colpts = [65 polar2ab(50, 135) % pale blue green
75 polar2ab(45, 75)
80 polar2ab(45, 85)
85 polar2ab(22, 90)
90 0 0 ];
case 16
desc = 'Attempt at a ''water depth'' colour map';
attributeStr = 'linear';
hueStr = 'blue';
colpts = [95 0 0
80 polar2ab(20, -95)
70 polar2ab(25, -95)
60 polar2ab(25, -95)
50 polar2ab(35, -95)];
% The following three colour maps are for ternary images, eg Landsat images
% and radiometric images. These colours form the nominal red, green and
% blue 'basis colours' that are used to form the composite image. They are
% designed so that they, and their secondary colours, have nearly the same
% lightness levels and comparable chroma. This provides consistent feature
% salience no matter what channel-colour assignment is made. The
% colour maps are specified as straight lines in RGB space. For their
% derivation see
% http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary
case 17
desc = 'red colour map for ternary images';
attributeStr = 'linear';
hueStr = 'ternary-red';
colourspace = 'RGB';
colpts = [0.00 0.00 0.00
0.90 0.17 0.00];
splineorder = 2;
case 18
desc = 'green colour map for ternary images';
attributeStr = 'linear';
hueStr = 'ternary-green';
colourspace = 'RGB';
colpts = [0.00 0.00 0.00
0.00 0.50 0.00];
splineorder = 2;
case 19
desc = 'blue colour map for ternary images';
attributeStr = 'linear';
hueStr = 'ternary-blue';
colourspace = 'RGB';
colpts = [0.00 0.00 0.00
0.10 0.33 1.00];
splineorder = 2;
%% 20 Series: Diverging colour maps
% Note that on these colour maps we do not go to full white but use a
% lightness value of 95. This helps avoid saturation problems on monitors.
% A lightness smoothing sigma of 7 is used to avoid generating a false
% feature at the white point in the middle. Note however, this does create
% a small perceptual contrast blind spot at the middle.
case 20
desc = 'Diverging blue-white-red colour map';
attributeStr = 'diverging';
hueStr = 'bwr';
colpts = [40 polar2ab(83,-64)
95 0 0
40 polar2ab(83, 39)];
sigma = 7;
splineorder = 2;
case 21
desc = 'Diverging green-white-violet colour map';
attributeStr = 'diverging';
hueStr = 'gwv';
colpts = [55 -50 55
95 0 0
55 60 -55];
sigma = 7;
splineorder = 2;
case 22
desc = 'Diverging green-white-red colour map';
attributeStr = 'diverging';
hueStr = 'gwr';
colpts = [55 -50 55
95 0 0
55 63 39];
sigma = 7;
splineorder = 2;
case 23
desc = 'Diverging orange/brown to crimson/purple';
attributeStr = 'diverging';
hueStr ='owm';
colpts = [45 polar2ab(63, 61)
95 0 0
45 polar2ab(63, -15)];
sigma = 7;
splineorder = 2;
case 24
desc = 'Diverging blue - black - red colour map';
attributeStr = 'diverging';
hueStr = 'bkr';
colpts = [55 polar2ab(70, -85)
10 0 0
55 polar2ab(70, 35)];
sigma = 7;
splineorder = 2;
case 25
desc = 'Diverging green - black - red colour map';
attributeStr = 'diverging';
hueStr = 'gkr';
colpts = [60 polar2ab(80, 134)
10 0 0
60 polar2ab(80, 40)];
sigma = 7;
splineorder = 2;
case 26
desc = 'Diverging blue - black - yellow colour map';
attributeStr = 'diverging';
hueStr = 'bky';
colpts = [60 polar2ab(60, -95)
10 0 0
60 polar2ab(60, 85)];
sigma = 7;
splineorder = 2;
case 27
desc = 'Diverging green - black - magenta colour map';
attributeStr = 'diverging';
hueStr = 'gkm';
colpts = [60 polar2ab(80, 134)
10 0 0
60 polar2ab(80, -37)];
sigma = 7;
splineorder = 2;
case 28 % Constant lightness diverging map for when you want to use
% relief shading ? Perhaps lighten the grey so it is not quite
% isoluminant ?
desc = 'Diverging isoluminat lightblue - lightgrey - orange colour map';
attributeStr = 'diverging-isoluminant';
hueStr = 'cjo';
colpts = [70 polar2ab(50, -115)
70 0 0
70 polar2ab(50, 45)];
sigma = 7;
splineorder = 2;
W = [1 1 1];
case 29 % Constant lightness diverging map for when you want to use
% relief shading ? Perhaps lighten the grey so it is not quite
% isoluminant ?
desc = 'Diverging isoluminat lightblue - lightgrey - pink colour map';
attributeStr = 'diverging-isoluminant';
hueStr = 'cjm';
colpts = [75 polar2ab(48, -127)
75 0 0
75 polar2ab(48, -30)];
sigma = 7;
splineorder = 2;
W = [1 1 1];
% 30 Series: Cyclic colour maps
case 31 % Cyclic isoluminant path around perimeter of 60 slice Looks
% reasonable, may want a bit of cyclic shifting, but looks good.
% It really hurts to look at a sinewave with this map!
attributeStr = 'cyclic-isoluminant';
hueStr = 'grmbg';
colpts = [60 -55 60
60 0 60
60 60 65
60 70 0
60 95 -60
60 40 -60
60 5 -60
60 -40 0
60 -55 60];
W = [1 1 1];
case 32 % Cyclic non-isoluminant path between 45 and 55 lightness
% Interesting but not as successful as No 31
% Problem in the blue section
attributeStr = 'cyclic';
hueStr = 'bormb';
colpts = [55 -55 -55
55 15 60
55 80 70
50 80 -5
45 80 -90
45 55 -90
45 25 -90
50 -25 -25
55 -55 -55];
W = [1 1 1];
case 33 % Attempt at an isoluminant green-magenta cyclic map
% Perhaps apply a circshift of -25, or + 35 to it
% It really hurts to look at a sinewave with this map!
attributeStr = 'cyclic-isoluminant';
hueStr = 'mvgom';
colpts = [65 70 -15
65 85 -55
65 40 -55
65 -55 25
65 -60 60
65 -20 65
65 70 -15];
W = [1 1 1];
case 34 % Circle at 55
attributeStr = 'cyclic-isoluminant';
hueStr = 'mgbm';
colpts = [55 polar2ab(36,0)
55 polar2ab(36,60)
55 polar2ab(36,120)
55 polar2ab(36,180)
55 polar2ab(36,240)
55 polar2ab(36,300)
55 polar2ab(36,360)];
W = [1 1 1];
case 35 % Circle at 67 - sort of ok but a bit flouro
attributeStr = 'cyclic-isoluminant';
hueStr = 'mgbm';
rad = 42;
ang = 124;
colpts = [67 polar2ab(rad, ang-90)
67 polar2ab(rad, ang)
67 polar2ab(rad, ang+90)
67 polar2ab(rad, ang+180)
67 polar2ab(rad, ang-90)];
W = [1 1 1];
case 36 % Same as 35 with shift for cycle of length pi
attributeStr = 'cyclic-isoluminant_s';
hueStr = 'mgbm';
rad = 42;
ang = 124;
colpts = [67 polar2ab(rad, ang-90)
67 polar2ab(rad, ang)
67 polar2ab(rad, ang+90)
67 polar2ab(rad, ang+180)
67 polar2ab(rad, ang-90)];
W = [1 1 1];
shift = N/4;
case 37 % Distorted larger circle at 55 but with reduced radius across
% the cyan section of the circle to fit within the gamut.
% Quite a good compromise.
attributeStr = 'cyclic-isoluminant';
hueStr = 'mogbm';
colpts = [55 polar2ab(60,0)
55 polar2ab(60,60)
55 polar2ab(60,120)
55 polar2ab(60,145)
55 polar2ab(37,180)
55 polar2ab(35,240)
55 polar2ab(50,270)
55 polar2ab(60,300)
55 polar2ab(60,360)];
W = [1 1 1];
case 39 % Constant lightness 'v' path to test importance of having a smooth
% path in hue. Slight 'feature' at the green corner (Seems more
% important on poor monitors) but is a good example of the
% relative unimportance of hue slope continuity
attributeStr = 'isoluminant-example';
hueStr = 'vgr';
colpts = [50 80 -75
50 -50 50
50 80 65];
splineorder = 2; % linear path
W = [0 0 0];
%% 40 Series: Rainbow style colour maps
case 41 % Reasonable rainbow colour map after it has been fixed by
% equalisecolour map with a smoothing sigma value of about 7.
desc = ['The least worst rainbow colour map I can devise. Note there are' ...
' small perceptual blind spots at yellow and red'];
attributeStr = 'rainbow';
hueStr = 'bgyrm';
colpts = [35 60 -100
45 -15 -30
60 -55 60
85 0 80
55 70 65
75 55 -35];
sigma = 7;
splineorder = 2; % linear path
case 42 % A sort of rainbow map. Deliberately illustrates issues in the
% design of these maps. The direction/lightness discontinuities in
% LAB space at green, yellow and red produce features in the
% colour map. It is also interesting in that it shows the
% importance of constant change in L. The slope is low from blue
% to green relative green to yellow. This is noticeable when the
% sineramp test image is viewed with this colour map
attributeStr = 'rainbow';
hueStr = 'bgyrm';
colpts = [45 30 -80
55 -30 -10
60 -55 60
85 0 80
55 70 65
60 80 -55];
splineorder = 2; % linear path
W = [0 0 0];
case 43 % Constant lightness of 50 version of the colour map above.
attributeStr = 'isoluminant';
hueStr = 'bgrm';
colpts = [50 30 -80
50 -30 -10
50 -55 60
50 0 80
50 70 65
50 80 -55];
splineorder = 2; % linear path
W = [1 1 1];
case 44 % Similar to 41 but with the colour map finishing at red rather
% than continuing onto pink.
desc = ['Reasonable rainbow colour map from blue to red. Note there is' ...
' a small perceptual blind spot at yellow'];
attributeStr = 'rainbow';
hueStr = 'bgyr';
colpts = [35 60 -100
45 -15 -30
60 -55 60
85 0 80
55 75 70];
sigma = 5;
splineorder = 2; % linear path
%% Miscellaneous
case 50 % Line from max blue saturation to max green saturation
attributeStr = 'linear';
hueStr = 'bg';
colpts = [30 polar2ab(135, -59)
90 polar2ab(112, 135)];
splineorder = 2; % linear path
case 51 % Line from max red saturation to max green saturation
attributeStr = 'linear';
hueStr = 'rog';
colpts = [50 polar2ab(100, 40)
90 polar2ab(112, 135)];
splineorder = 2; % linear path
case 52 % Line from max blue saturation to max red saturation
desc = 'Line from max blue saturation to max red saturation';
attributeStr = 'linear';
hueStr = 'bmr';
colpts = [20 polar2ab(110, -59)
60 polar2ab(100, 46)];
splineorder = 2; % linear path
case 53 % Line from black- max blue saturation to max green saturation
% - white
attributeStr = 'linear';
hueStr = 'bgw';
colpts = [5 0 0
30 polar2ab(100, -59)
40 polar2ab(115, -59)
80 polar2ab(112, 135)
90 polar2ab(100, 135)
95 0 0];
case 54
desc = 'Isoluminant arc blue-magenta-yellow at lightness = 65';
attributeStr = 'isoluminant';
hueStr = 'cmo';
colpts = [65 -13 -55
65 48 -54
65 67 -7
65 61 40
65 22 68];
W = [1 1 1];
case 55
desc = 'Low contrast arc blue-magenta-yellow ';
attributeStr = 'linear';
hueStr = 'bmo';
colpts = [50 polar2ab(80, -80)
55 polar2ab(90, -50)
60 polar2ab(82, -10)
65 polar2ab(80, 51)
75 polar2ab(77, 83)];
W = [1 1 1];
case 56
desc = 'Isoluminant green to orange at lightness 75';
attributeStr = 'isoluminant';
hueStr = 'go';
colpts = [75 polar2ab(53, 135)
75 polar2ab(53, 80)];
W = [1 1 1];
splineorder = 2;
case 57 % Grey 10 - 90
desc = ['Grey scale with slightly reduced contrast to '...
'avoid display saturation problems'];
attributeStr = 'linear';
hueStr = 'grey';
colpts = [10 0 0
90 0 0];
splineorder = 2;
case 58
desc = ['Diverging blue - red colour map. No smoothing to illustrate' ...
' feature problem'];
attributeStr = 'diverging-nosmoothing';
hueStr = 'bwr';
colpts = [40 31 -80
95 0 0
40 65 56];
sigma = 0;
splineorder = 2;
case 59
desc = ['Isoluminant blue to green to orange at lightness 70. '...
'Poor on its own but works well with relief shading'];
attributeStr = 'isoluminant';
hueStr = 'cgo';
colpts = [70 polar2ab(40, -115)
70 polar2ab(50, 160)
70 polar2ab(50, 90)
70 polar2ab(50, 45)];
W = [1 1 1];
case 60
desc = ['Diverging blue - red colour map. Large degree of smoothing for' ...
' poster'];
attributeStr = 'diverging-oversmoothed';
hueStr = 'bwr';
colpts = [40 31 -80
95 0 0
40 65 56];
sigma = 12;
splineorder = 2;
case 61
desc = 'Non-Isoluminant version of No 62, lightness 25 to 75.';
attributeStr = 'linear';
hueStr = 'bm';
colpts = [25 polar2ab(40, -125)
42 polar2ab(40, -80)
59 polar2ab(40, -40)
75 polar2ab(50, 0)];
case 62
desc = ['Isoluminant version of No 61, lightness 70. '...
'Poor on its own but works well with relief shading'];
attributeStr = 'isoluminant';
hueStr = 'cm';
colpts = [70 polar2ab(40, -125)
70 polar2ab(40, -80)
70 polar2ab(40, -40)
70 polar2ab(50, 0)];
W = [1 1 1];
case 63
desc = 'Non-Isoluminant version of No 62, lightness 35 to 75.';
attributeStr = 'linear';
hueStr = 'bm';
colpts = [35 polar2ab(40, -125)
48 polar2ab(40, -80)
62 polar2ab(40, -40)
75 polar2ab(50, 0)];
case 64 % Adaptation of 59 shifted to 80 from 70
desc = ['Isoluminant blue to green to orange at lightness 80. '...
'Poor on its own but works well with relief shading'];
attributeStr = 'isoluminant';
hueStr = 'cgo';
colpts = [80 polar2ab(40, -115)
80 polar2ab(50, 160)
80 polar2ab(50, 90)
80 polar2ab(50, 45)];
W = [1 1 1];
%% More cyclic attempts
case 70 % 29-9-2014 Everything one tries converges to a similar solution!
% How do you get 4 perceptually equivalent land mark colours from
% a tristimulaus system?!
% Hit the corners of the gamut red - green - blue/cyan - blue with
% small tweeks to keep linear path within the gamut. However,
% keep the control points symmetric in terms of lightness and only
% weight for lightness when equalising. This achieves symmetry of
% the colour arrangement despite the non symmetric path because
% the control points are symmetric in terms of lightness.
% BUT the trouble is we 'see' only three colours! The colourmap
% looks green for top half, blue for bottom left and red for
% bottom right. Interesting example
attributeStr = 'cyclic';
hueStr = 'rgcbr';
colpts = [55 75 65
80 -80 76
55 19 -71
30 65 -95
55 80 67];
W = [1 0 0];
sigma = 3;
splineorder = 2;
case 71 % Attempt at cyclic map based on No 41 a rainbow map
% Looks really nice!!
% Problem is that key colours are not spaced as well as one
% would like.
attributeStr = 'cyclic';
hueStr = 'bgyrmb';
colpts = [35 60 -100
45 -15 -30
60 -55 60
85 0 80
55 70 65
75 55 -35
35 60 -100];
sigma = 5;
splineorder = 2; % linear path
case 72 % Variation of 78. Perceptually this is good. Excellent balance
% of colours in the quadrants but the colour mix is not to my
% taste. Don't like the green. The reg-green transition clashes
attributeStr = 'cyclic';
hueStr = 'bgrmb';
blu = [35 70 -100];
colpts = [blu
70 -70 64
35 65 50
70 75 -46
blu ];
sigma = 7;
splineorder = 2; % linear path
case 73 % 2nd Attempt to modify 71 so that key colours are placed at
% quadrants. Competing with 74 but I think this is a bit
% better but 74 has better symmetry
attributeStr = 'cyclic';
hueStr = 'bgyrm';
colpts = [35 60 -100
45 -15 -30
80 0 80
53 70 65
80 47 -31
35 60 -100];
sigma = 7;
splineorder = 2; % linear path
case 74 % 3rd Attempt to modify 71 so that key colours are placed at
% quadrants. Competing with 73. Has better symmetry
attributeStr = 'cyclic';
hueStr = 'byrmb';
colpts = [40 70 -95
60 -25 -20
80 0 80
40 70 -95
80 47 -31
60 80 -65
40 70 -95];
sigma = 7;
splineorder = 2; % linear path
case 75 % Like 70 but use yellow instead of green - Nicer to look at
attributeStr = 'cyclic';
hueStr = 'rycbr';
colpts = [55 75 65
90 -10 85
55 19 -71
20 50 -77
55 80 67];
W = [1 0 0];
sigma = 3;
splineorder = 2;
case 76 % Try a variation based on 78 with green instead of magenta. OK
% but I dislike the colour mix
attributeStr = 'cyclic';
hueStr = 'byrmb';
blu = [35 70 -100];
colpts = [blu
85 -85 81
35 60 48
% 35 -40 40
85 3 87
blu ];
sigma = 7;
splineorder = 2; % linear path
case 476 % okish
attributeStr = 'cyclic';
hueStr = 'byrmb';
blu = [35 70 -100];
colpts = [blu
85 -40 -25
35 -40 40
85 10 87
60 35 -60
blu ];
sigma = 7;
splineorder = 2; % linear path
case 479 % Try same as 477 but with yellow/orange instead of green and
% cyan instead of magenta. Nup!
attributeStr = 'cyclic';
hueStr = 'byrmb';
blu = [35 70 -100];
colpts = [blu
70 37 77
35 65 50
70 -12 -50
blu ];
sigma = 7;
splineorder = 2; % linear path
case 77 % OK
attributeStr = 'cyclic';
hueStr = 'mygbm';
ang = 112;
colpts = [70 polar2ab(46, ang-90)
90 polar2ab(82, ang)
70 polar2ab(46, ang+90)
50 polar2ab(82, ang+180)
70 polar2ab(46, ang-90)];
W = [1 1 1];
case 78 % Development of 74 to improve placement of key colours.
% Control points are placed so that lightness steps up and
% down are equalised. Additional intermediate points are
% placed to try to even up the 'spread' of the key colours.
% I think this is my best zigzag style cyclic map - Good!
attributeStr = 'cyclic';
hueStr = 'mrybm';
mag = [75 60 -40];
yel = [75 0 77];
blu = [35 70 -100];
red = [35 60 48];
colpts = [mag
55 70 0
red
55 35 62
yel
50 -20 -30
blu
55 45 -67
mag];
sigma = 7;
splineorder = 2; % linear path
case 79 % We start at dark pink with 0 phase 90 (the peak corresponds to
% the brightest point in the colour map at yellow, then down to
% green/blue at 180, blue at 270 (darkest point) then back up to
% dark pink.
attributeStr = 'cyclic';
hueStr = 'mybm';
colpts = [67.5 42.5 15
95 -30 85
67.5 -42.5 -15
40 30 -85
67.5 42.5 15];
W = [1 1 1];
sigma = 9;
case 80 % Try to push 79 a bit further. Greater range of lightness
% values and slightly more saturated colours. Seems to work
% however I do not find the colour sequence that
% attractive. This is a constraint of the gamut.
attributeStr = 'cyclic';
hueStr = 'mybm';
ang = 124;
colpts = [60 polar2ab(40, ang-90)
100 polar2ab(98, ang)
60 polar2ab(40, ang+90)
20 polar2ab(98, ang+180)
60 polar2ab(40, ang-90)];
W = [1 1 1];
sigma = 7;
case 82
desc = 'Cyclic: greyscale'; % Works well
attributeStr = 'cyclic';
hueStr = 'grey';
colpts = [50 0 0
85 0 0
15 0 0
50 0 0];
sigma = 7;
splineorder = 2;
case 84 % red-white-blue-black-red allows quadrants to be identified
desc = 'Cyclic: red - white - blue - black - red';
attributeStr = 'cyclic';
hueStr = 'rwbkr';
colpts = [50 polar2ab(85, 39)
85 0 0
50 polar2ab(85, -70)
15 0 0
50 polar2ab(85, 39)];
sigma = 7;
splineorder = 2;
case 85 % A big diamond across the gamut. Really good!
% Incorporates two extra conrol points around blue to extend the
% width of that segment slightly.
attributeStr = 'cyclic';
hueStr = 'mygbm';
colpts = [62.5 83 -54
80 20 25
95 -20 90
62.5 -65 62
42 10 -50
30 75 -103
48 70 -80
62.5 83 -54];
sigma = 7;
splineorder = 2;
case 87 % works fine but I think I would rather use 88 below instead
desc = 'Cyclic: grey-yellow-grey-blue';
attributeStr = 'cyclic';
hueStr = 'jyjbj';
colpts = [60 0 0
90 -10 90
60 0 0
30 79 -108
60 0 0];
sigma = 7;
splineorder = 2;
case 88 % % white-red-white-blue-white Works nicely
desc = 'Cyclic: white - red - white - blue';
attributeStr = 'cyclic';
hueStr = 'wrwbw';
colpts = [90 0 0
40 65 56
90 0 0
40 31 -80
90 0 0];
sigma = 7;
splineorder = 2;
%-------------------------------------------
case 101
desc = ['Two linear segments with different slope to illustrate importance' ...
' of lightness gradient. Equalised lightness.'];
attributeStr = 'linear-lightnessnormalised';
hueStr = 'by';
colpts = [40 polar2ab(60, -75)
72 0 0
80 polar2ab(70, 105)];
splineorder = 2;
case 102
desc = ['Two linear segments with different slope to illustrate importance' ...
' of lightness gradient. Equalised CIE76'];
attributeStr = 'linear-CIE76normalised';
hueStr = 'by';
colpts = [40 polar2ab(60, -75)
72 0 0
80 polar2ab(70, 105)];
W = [1 1 1];
splineorder = 2;
case 103 % Constant lightness 'v' path to test unimportance of having a smooth
% path in hue. Slight 'feature' at the red corner (Seems more
% important on poor monitors)
attributeStr = 'isoluminant-HueSlopeDiscontinuity';
hueStr = 'brg';
colpts = [50 17 -78
50 77 57
50 -48 50];
splineorder = 2; % linear path
W = [1 1 1];
case 104 % Linear diverging blue - grey - orange. This works but the
% blue and orange are not nice to look at
attributeStr = 'diverging-linear';
hueStr = 'bjo';
colpts = [30 polar2ab(90, -60)
47.5 0 0
65 polar2ab(90,55)];
splineorder = 2;
case 105 % Linear diverging blue - grey - yellow. Works well
attributeStr = 'diverging-linear';
hueStr = 'bjy';
colpts = [30 polar2ab(89, -59)
60 0 0
90 polar2ab(89,96)];
splineorder = 2;
case 106 % Linear diverging blue - grey - green
attributeStr = 'diverging-linear';
hueStr = 'bjg';
colpts = [20 polar2ab(110, -58)
55 0 0
90 polar2ab(110,135)];
splineorder = 2;
case 107 % Linear diverging blue - grey - red
attributeStr = 'diverging-linear';
hueStr = 'bjr';
colpts = [30 polar2ab(105, -60)
42.5 0 0
55 polar2ab(105,40)];
splineorder = 2;
case 108 % Linear diverging blue - grey - magenta
attributeStr = 'diverging-linear';
hueStr = 'bjm';
colpts = [30 polar2ab(105, -60)
45 0 0
60 polar2ab(105,-32)];
splineorder = 2;
case 109 % low contrast diverging map for when you want to use
% relief shading Adapted from 29. Works well
desc = 'Diverging lowcontrast cyan - white - magenta colour map';
attributeStr = 'diverging';
hueStr = 'cwm';
colpts = [80 polar2ab(44, -135)
100 0 0
80 polar2ab(44, -30)];
sigma = 0; % Try zero smoothing- not needed for low contrast
splineorder = 2;
W = [1 1 1];
case 110 % low contrast diverging map for when you want to use
% relief shading. Try green-white-yellow becuase you have have
% much more strongly saturated colours. Works well but colours
% are a bit unusual. Unsure which should be +ve or -ve
desc = 'Diverging lowcontrast green - white - yellow colour map';
attributeStr = 'diverging';
hueStr = 'gwy';
colpts = [80 polar2ab(83, 135)
95 0 0
80 polar2ab(83, 80)];
sigma = 0;
splineorder = 2;
W = [1 1 1];
case 111 % Slightly increased contrast version of 109 works well with
% relief shading.
attributeStr = 'diverging';
hueStr = 'bwr';
colpts = [60 polar2ab(60, -85)
95 0 0
60 polar2ab(60, 40)];
sigma = 0;
splineorder = 2;
W = [1 1 1];
case 112 % low contrast linear diverging attempt
% magenta grey yellow. OK but colour interpretation not so
% intuitive
attributeStr = 'diverging';
hueStr = 'mjy';
colpts = [70 polar2ab(87, -32)
82.5 0 0
95 polar2ab(87, 100)];
sigma = 0;
splineorder = 2;
W = [1 1 1];
case 113 % Lightened version of 20 for relief shading - Good.
desc = 'Diverging blue - red colour map';
attributeStr = 'diverging';
hueStr = 'bwr';
colpts = [55 polar2ab(73,-74)
98 0 0
55 polar2ab(73, 39)];
sigma = 3; % Less smoothing needed for low contrast
splineorder = 2;
%% Special colour maps designed to illustrate various design principles.
% A set of isoluminant colour maps only varying in saturation to test
% the importance of saturation (not much) Colour Maps are linear with
% a reversal to test importance of continuity.
% uses de2000 with no smoothing
case 200 % Isoluminant 50 only varying in saturation
attributeStr = 'isoluminant';
hueStr = 'r';
colpts = [50 0 0
50 77 64
50 0 0];
splineorder = 2;
W = [1 1 1];
case 201 % Isoluminant 50 only varying in saturation
attributeStr = 'isoluminant';
hueStr = 'b';
colpts = [50 0 0
50 0 -56
50 0 0];
splineorder = 2;
W = [1 1 1];
case 202 % Isoluminant 90 only varying in saturation
attributeStr = 'isoluminant';
hueStr = 'isoluminant_90_g';
colpts = [90 0 0
90 -76 80
90 0 0];
splineorder = 2;
W = [1 1 1];
case 203 % Isoluminant 55 only varying in saturation. CIEDE76
attributeStr= 'isoluminant-CIE76';
hueStr = 'jr';
colpts = [55 0 0
55 80 67];
splineorder = 2;
W = [1 1 1];
formula = 'CIE76';
case 204 % Same as 203 but using CIEDE2000
attributeStr= 'isoluminant-CIEDE2000';
hueStr = 'jr';
colpts = [55 0 0
55 80 67];
splineorder = 2;
W = [1 1 1];
formula = 'CIEDE2000';
case 205 % Grey 0 - 100. Same as No 1 but with CIEDE2000
desc = 'Grey scale';
attributeStr= 'linear-CIEDE2000';
hueStr = 'grey';
colpts = [ 0 0 0
100 0 0];
splineorder = 2;
formula = 'CIEDE2000';
case 206 % Isoluminant 30 only varying in saturation
attributeStr= 'isoluminant';
hueStr = 'b';
colpts = [30 0 0
30 77 -106];
splineorder = 2;
W = [1 1 1];
case 210 % Blue to yellow section of rainbow map 41 for illustrating
% colour ordering issues
attributeStr= 'rainbow-section1';
hueStr = 'bgy';
colpts = [35 60 -100
45 -15 -30
60 -55 60
85 0 80];
splineorder = 2; % linear path
case 211 % Red to yellow section of rainbow map 41 for illustrating
% colour ordering issues
attributeStr= 'rainbow-section2';
hueStr = 'ry';
colpts = [55 70 65
85 0 80];
splineorder = 2; % linear path
case 212 % Red to pink section of rainbow map 41 for illustrating
% colour ordering issues
attributeStr= 'rainbow-section3';
hueStr = 'rm';
colpts = [55 70 65
75 55 -35];
splineorder = 2; % linear path
%% Another attempt at getting a better set of ternary colour maps. Try
% slightly unequal lightness values
case 217
desc = '5-55 lightness red colour map for radiometric data';
attributeStr = 'linear';
hueStr = 'ternary-red';
ang = 36; % 37
colpts = [5 0 0
30 polar2ab(38,ang) % 40
55 polar2ab(94, ang)]; % 100 39
splineorder = 2;
case 218
desc = '5-55 lightness green colour map for radiometric data';
attributeStr = 'linear';
hueStr = 'ternary-green';
colpts = [5 0 0
65 polar2ab(88, 137)]; % 90 136
splineorder = 2;
case 219
desc = '5-55 lightness blue colour map for radiometric data';
attributeStr = 'linear';
hueStr = 'ternary-blue';
colpts = [5 0 0
43 polar2ab(87, -65)]; % 93 54
splineorder = 2;
%% ------ Rejects / Maps that need more work -------------
% These are not listed in a catalogue search
case 336 % Circle at 75 - is too bright ? might be ok with relief
% shading if that makes any sense with cyclic data
attributeStr = 'cyclic-isoluminant';
hueStr = 'mgbm';
colpts = [75 polar2ab(43,0)
75 polar2ab(43,60)
75 polar2ab(43,120)
75 polar2ab(43,180)
75 polar2ab(43,240)
75 polar2ab(43,300)
75 polar2ab(43,360)];
W = [1 1 1];
case 374 % More circular less lightness contrast. Dk Green violet red,
% orange greem cycle. Not centred on grey. Might be ok with
% some work. Want some compromise between equalisation on 1
% or 2.
attributeStr = 'cyclic';
hueStr = 'gmog';
colpts = [50 polar2ab(50, 90)
40 polar2ab(40, -235)
50 polar2ab(50, -25)
60 polar2ab(90, 45)
50 polar2ab(50, 90)];
W = [1 1 1];
sigma = 9;
case 378 % Similar philosophy to 77 but hue shift
% pink yellow/green blue purple pink - also looks good but a
% bit more lairy than 77
attributeStr = 'cyclic';
hueStr = 'mgbvm';
colpts = [70 30 32
90 -75 80
70 -30 -32
50 80 -75
70 30 32];
W = [1 1 1];
sigma = 9;
case 381 % green cyan pink/red green - A bit dark and needs some
% equalisation work
attributeStr = 'cyclic';
hueStr = 'gcmg';
colpts = [50 -40 25
70 -25 -40
50 40 -25
30 25 40
50 -40 25];
W = [1 1 1];
sigma = 9;
case 384 % Nuh
desc = 'Cyclic: red - white - green - black - red';
attributeStr = 'cyclic';
hueStr = 'rwgkr';
colpts = [50 polar2ab(40, 30)
85 0 0
50 polar2ab(40, 140)
15 0 0
50 polar2ab(40, 30)];
sigma = 7;
splineorder = 2;
case 385 % Cyclic: red - green. Problem is that red is perceived as
% +ve but is a darker colour than green giving confilicting
% perceptual cues
desc = 'Cyclic: red - green';
attributeStr = 'cyclic';
hueStr = 'gr';
colpts = [65 0 60
45 70 50
85 -70 70
65 0 60];
sigma = 7;
splineorder = 2;
case 386
desc = 'Cyclic: red - blue'; % A bit harsh on the eye but the colour
% and lighness cues are in sync
attributeStr = 'cyclic';
hueStr = 'vrvbv';
colpts = [45 60 -17.5
55 70 65
35 50 -100
45 60 -17.5];
sigma = 7;
splineorder = 2;
%%-------------------------------------------------------------
otherwise
warning('Sorry, no colour map option with that number');
map = [];
return
end
% Adjust chroma/saturation but only if colourspace is LAB
if strcmpi(colourspace, 'LAB')
colpts(:,2:3) = chromaK * colpts(:,2:3);
end
% Colour map path is formed via a b-spline in the specified colour space
Npts = size(colpts,1);
if Npts < 2
error('Number of input points must be 2 or more')
elseif Npts < splineorder
splineorder = Npts;
fprintf('Warning: Spline order is greater than number of data points\n')
fprintf('Reducing order of spline to %d\n', Npts)
end
% Rely on the attribute string to identify if colour map is cyclic. We may
% want to construct a colour map that has identical endpoints but do not
% necessarily want continuity in the slope of the colour map path.
if strfind(attributeStr, 'cyclic')
cyclic = 1;
labspline = pbspline(colpts', splineorder, N);
else
cyclic = 0;
labspline = bbspline(colpts', splineorder, N);
end
% Apply contrast equalisation with required parameters. Note that sigma is
% normalised with respect to a colour map of length 256 so that if a short
% colour map is specified the smoothing that is applied is adjusted to suit.
sigma = sigma*N/256;
map = equalisecolourmap(colourspace, labspline', formula,...
W, sigma, cyclic, diagnostics);
% If specified apply a cyclic shift to the colour map
if shift
if isempty(strfind(attributeStr, 'cyclic'))
fprintf('Warning: Colour map shifting being applied to a non-cyclic map\n');
end
map = circshift(map, round(N*shift));
end
if reverse
map = flipud(map);
end
% Compute mean chroma of colour map
lab = rgb2lab(map);
meanchroma = sum(sqrt(sum(lab(:,2:3).^2, 2)))/N;
% Construct lightness range description
if strcmpi(colourspace, 'LAB') % Use the control points
L = colpts(:,1);
else % For RGB use the converted CIELAB values
L = round(lab(:,1));
end
minL = min(L);
maxL = max(L);
if minL == maxL % Isoluminant
LStr = sprintf('%d', minL);
elseif L(1) == maxL && ...
(~isempty(strfind(attributeStr, 'diverging')) ||...
~isempty(strfind(attributeStr, 'linear')))
LStr = sprintf('%d-%d', maxL, minL);
else
LStr = sprintf('%d-%d', minL, maxL);
end
% Build overall colour map name
name = sprintf('%s_%s_%s_c%d_n%d',...
attributeStr, hueStr, LStr, round(meanchroma), N);
if shift
name = sprintf('%s_s%d', name, round(shift*100));
end
if reverse
name = sprintf('%s_r', name);
end
if diagnostics % Print description and plot path in colourspace
fprintf('%s\n',desc);
colourmappath(map, 6, 'lab', 10)
end
%------------------------------------------------------------------
function ab = polar2ab(radius, angle_degrees)
theta = angle_degrees/180*pi;
ab = radius*[cos(theta) sin(theta)];
%------------------------------------------------------------------
%
% Function to list colour maps with names containing a specific string.
% Typically this is used to search for colour maps having a specified attribute:
% 'linear', 'diverging', 'rainbow', 'cyclic', 'isoluminant' or 'all'.
function catalogue(str)
if ~exist('str', 'var')
str = 'all';
end
fprintf('\n No Colour Map name\n')
fprintf('---------------------------------\n')
warning('off');
for n = 1:300
[m, name] = labmaplib(n);
if ~isempty(m)
if any(strfind(name, str)) || strcmpi(str, 'all')
fprintf('%4d %s\n', n, name);
end
end
end
warning('on');
%-----------------------------------------------------------------------
% Function to parse the input arguments and set defaults
function [I, N, chromaK, shift, reverse, diagnostics] = parseinputs(varargin)
p = inputParser;
numericORchar = @(x) isnumeric(x) || ischar(x);
numericORlogical = @(x) isnumeric(x) || islogical(x);
% The first argument is either a colour map number or a string to search for
% in a colourmap name. If no argument is supplied it is assumed the user
% wants to list all possible colourmaps.
addOptional(p, 'I', 'all', numericORchar);
% Optional parameter-value pairs and their defaults
addParameter(p, 'N', 256, @isnumeric);
addParameter(p, 'shift', 0, @isnumeric);
addParameter(p, 'chromaK', 1, @isnumeric);
addParameter(p, 'reverse', 0, numericORlogical);
addParameter(p, 'diagnostics', 0, numericORlogical);
parse(p, varargin{:});
I = p.Results.I;
N = p.Results.N;
chromaK = p.Results.chromaK;
shift = p.Results.shift;
reverse = p.Results.reverse;
diagnostics = p.Results.diagnostics;
if abs(shift) > 1
error('Cyclic shift fraction magnitude cannot be larger than 1');
end
if chromaK < 0
error('chromaK must be greater than 0')
end
if chromaK > 1
fprintf('Warning: chromaK is greater than 1. Gamut clipping may occur')
end
|
github
|
jacksky64/imageProcessing-master
|
map2ermapperlutfile.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/map2ermapperlutfile.m
| 1,797 |
utf_8
|
aace8b9f7a1a077cdab2c5bc541bea51
|
% MAP2ERMAPPERLUTFILE Writes ER Mapper LUT colour map file
%
% Usage: map2ermapperlutfile(map, filename, name, description)
%
% Arguments: map - N x 3 rgb colour map of values 0-1.
% filename - Filename of LUT file to create. A .lut ending is added
% if the filename has no suffix.
% name - Optional string to name the colour map. This is used
% by ER Mapper to construct the lookup table menu list.
% description - Optional string to describe the colour map.
%
% The ER Mapper LUT file format is also used ny MapInfo
%
% See also: READERMAPPERLUTFILE, READIMAGEJLUTFILE
% 2014 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
% PK September 2014
function map2ermapperlutfile(map, filename, name, description)
if ~exist('name','var'), name = basename(namenpath(filename)); end
if ~exist('description','var'), description = ''; end
[N, chan] = size(map);
if chan ~= 3
error('Colourmap must be Nx3');
end
% Ensure file has a .lut ending
if ~strendswith(filename, '.lut')
filename = [filename '.lut'];
end
[fid, msg] = fopen(filename, 'wt');
error(msg);
% Scale colour map values to 16 bit ints
map = round(map*(2^16 - 1));
fprintf(fid, 'LookUpTable Begin\n');
fprintf(fid, ' Name = "%s"\n', name);
fprintf(fid, ' Description = "%s"\n', description);
fprintf(fid, ' NrEntries = %d\n', N);
fprintf(fid, ' LUT = {\n', N);
for n = 1:N
fprintf(fid, '%8d %8d %8d %8d\n',n-1, map(n,1), map(n,2), map(n,3));
end
fprintf(fid, ' }\n');
fprintf(fid, 'LookUpTable End\n');
fclose(fid);
|
github
|
jacksky64/imageProcessing-master
|
equalisecolourmap.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/equalisecolourmap.m
| 17,904 |
utf_8
|
fb400048f547aa42b98ce524346562d4
|
% EQUALISECOLOURMAP - Equalise colour contrast over a colourmap
%
% Usage: newrgbmap = equalisecolourmap(rgblab, map, formula, W, sigma, diagnostics)
%
% Arguments: rgblab - String 'RGB' or 'LAB' indicating the type of data
% in map.
% map - A Nx3 RGB or CIELAB colour map
% formula - String 'CIE76' or 'CIEDE2000'
% W - A 3-vector of weights to be applied to the
% lightness, chroma and hue components of the
% difference equation. Use [1 0 0] to only take into
% account lightness, [1 1 1] for the full formula.
% See note below.
% sigma - Optional Gaussian smoothing parameter, see
% explanation below.
% cyclic - Flag 1/0 indicating whether the colour map is
% cyclic. This affects how smoothing is applied at
% the end points.
% diagnostics - Optional flag 0/1 indicating whether diagnostic
% plots should be displayed. Defaults to 0.
%
% Returns: newrgbmap - RGB colour map adjusted so that the perceptual
% contrast of colours along the colour map is constant.
%
% Suggested parameters:
%
% The CIE76 and CIEDE2000 colour difference formulas were developed for much
% lower spatial frequencies than we are typically interested in. Neither is
% ideal for our application. While the CIEDE2000 lightness correction is
% probably useful the difference is barely noticeable. The CIEDE2000 chroma
% correction is definitely *not* suitable for our needs.
%
% For colour maps with a significant range of lightness use:
% formula = 'CIE76' or 'CIEDE2000'
% W = [1 0 0] (Only correct for lightness)
% sigma = 5 - 7
%
% For isoluminant or low lightness gradient colour maps use:
% formula = 'CIE76'
% W = [1 1 1] (Correct for colour and lightness)
% sigma = 5 - 7
%
% Ideally, for a colour map to be effective the perceptual contrast along the
% colour map should be constant. Many colour maps are very poor in this regard.
% Try testing your favourite colour map on the SINERAMP test image. The
% perceptual contrast is very much dominated by the contrast in colour lightness
% values along the map. This function attempts to equalise the chosen
% perceptual contrast measure along a colour map by stretching and/or
% compressing sections of the colour map.
%
% This function's primary use is for the correction of colour maps generated by
% CMAP however it can be applied to any colour map. There are limitations to
% what this function can correct. When applied to some of MATLAB's colour maps
% such as 'jet', 'hsv' and 'cool' you get colour discontinuity artifacts because
% these colour maps have segments that are nearly constant in lightness.
% However, it does a nice job of fixing up MATLAB's 'hot', 'winter', 'spring'
% and 'autumn' colour maps. If you do see colour discontinuities in the
% resulting colour map try changing W from [1 0 0] to [1 1 1], or some
% intermediate weighting of [1 0.5 0.5], say.
%
% Difference formula: Neither CIE76 or CIEDE2000 difference measures are ideal
% for the high spatial frequencies that we are interested in. Empirically I
% find that CIEDE2000 seems to give slightly better results on colour maps where
% there is a significant lightness gradient (this applies to most colour maps).
% In this case you would be using a weighting vector W = [1 0 0]. For
% isoluminant, or low lightness gradient colour maps where one is using a
% weighting vector W = [1 1 1] CIE76 should be used as the CIEDE2000 chroma
% correction is inapropriate for the spatial frequencies we are interested in.
%
% Weighting vetor W: The CIEDE2000 colour difference formula incorporates the
% scaling parameters kL, kC, kH in the demonimator of the lightness, chroma, and
% hue difference components respectively. The 3 components of W correspond to
% the reciprocal of these 3 parameters. (I do not know why they chose to put
% kL, kC, kH in the denominator. If you wanted to ignore, say, the chroma
% component you would have to set kC to Inf, rather than setting W(2) to 0 which
% seems more sensible to me). If you are using CIE76 then W(2) amd W(3) are
% applied to the differences in a and b. In this case you should ensure W(2) =
% W(3). In general, for the spatial frequencies of interest to us, lightness
% differences are overwhelmingly more important than chroma or hue and W shoud
% be set to [1 0 0]
%
% Smoothing parameter sigma:
% The output colour map will have lightness values of constant slope magnitude.
% However, it is possible that the sign of the slope may change, for example at
% the mid point of a bilateral colour map. This slope discontinuity of lightness
% can induce a false apparent feature in the colour map. A smaller effect is
% also occurs for slope discontinuities in a and b. For such colour maps it can
% be useful to introduce a small amount of smoothing of the Lab values to soften
% the transition of sign in the slope to remove this apparent feature. However
% in doing this one creates a small region of suppressed luminance contrast in
% the colour map which induces a 'blind spot' that compromises the visibility of
% features should they fall in that data range. Accordingly the smoothing
% should be kept to a minimum. A value of sigma in the range 5 to 7 in a 256
% element colour map seems about right. As a guideline sigma should not be more
% than about 1/25 of the number of entries in the colour map, preferably less.
%
% If you use the CIEDE2000 formula option this function requires Gaurav Sharma's
% MATLAB implementation of the CIEDE2000 color difference formula deltaE2000.m
% available at: http://www.ece.rochester.edu/~gsharma/ciede2000/
%
% See also: CMAP, SINERAMP, COLOURMAPPATH, ISOCOLOURMAPPATH
% Copyright (C) 2013-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.
%
% December 2013 - Original version
% June 2014 - Generalised and cleaned up
function newrgbmap = equalisecolourmap(rgblab, map, formula, W, sigma, cyclic, diagnostics)
if ~exist('formula', 'var'), formula = 'CIE76'; end
if ~exist('W', 'var'), W = [1 0 0]; end
if ~exist('sigma', 'var'), sigma = 0; end
if ~exist('cyclic', 'var'), cyclic = 0; end
if ~exist('diagnostics', 'var'), diagnostics = 0; end
N = size(map,1); % No of colour map entries
if N/sigma < 25
warning(['It is not recommended that sigma be larger than 1/25 of' ...
' colour map length'])
end
if strcmpi(rgblab, 'RGB') && (max(map(:)) > 1.01 || min(map(:) < -0.01))
error('If map is RGB values should be in the range 0-1')
elseif strcmpi(rgblab, 'LAB') && max(abs(map(:))) < 10
error('If map is LAB magnitude of values are expected to be > 10')
end
% Use D65 whitepoint to match typical monitors.
wp = whitepoint('D65');
% If input is RGB convert colour map to Lab.
if strcmpi(rgblab, 'RGB')
rgbmap = map;
labmap = applycform(map, makecform('srgb2lab', 'AdaptedWhitePoint', wp));
L = labmap(:,1);
a = labmap(:,2);
b = labmap(:,3);
elseif strcmpi(rgblab, 'LAB')
labmap = map;
rgbmap = applycform(map, makecform('lab2srgb', 'AdaptedWhitePoint', wp));
L = map(:,1);
a = map(:,2);
b = map(:,3);
else
error('Input must be RGB or LAB')
end
% The following section of code computes the locations to interpolate into
% the colour map in order to achieve equal steps of perceptual contrast.
% The process is repeated recursively on its own output. This helps overcome
% the approximations induced by using linear interpolation to estimate the
% locations of equal perceptual contrast. This is mainly an issue for
% colour maps with only a few entries.
for iter = 1:3
% Compute perceptual colour difference values along the colour map using
% the chosen formula and weighting vector.
if strcmpi(formula, 'CIE76')
deltaE = cie76(L, a, b, W);
elseif strcmpi(formula, 'CIEDE2000')
if ~exist('deltaE2000','file')
fprintf('You need Gaurav Sharma''s function deltaE2000.m\n');
fprintf('available at:\n');
fprintf('http://www.ece.rochester.edu/~gsharma/ciede2000/\n');
newrgbmap = [];
return
end
deltaE = ciede2000(L, a, b, W);
else
error('Unknown colour difference formula')
end
% Form cumulative sum of of delta E values. However, first ensure all
% values are larger than 0.001 to ensure the cumulative sum always
% increases.
deltaE(deltaE < 0.001) = 0.001;
cumdE = cumsum(deltaE);
% Form an array of equal steps in cumulative contrast change.
equicumdE = (0:(N-1))'/(N-1) * (cumdE(end)-cumdE(1)) + cumdE(1);
% Solve for the locations that would give equal Delta E values.
method = 'linear';
newN = interp1(cumdE, (1:N)', equicumdE, method, 'extrap');
% newN now represents the locations where we want to interpolate into the
% colour map to obtain constant perceptual contrast
L = interp1((1:N)', L, newN, method, 'extrap');
a = interp1((1:N)', a, newN, method, 'extrap');
b = interp1((1:N)', b, newN, method, 'extrap');
% Record initial colour differences for evaluation at the end
if iter == 1
initialdeltaE = deltaE;
initialcumdE = cumdE;
initialequicumdE = equicumdE;
initialnewN = newN;
end
end
% Apply smoothing of the path in CIELAB space if requested. The aim is to
% smooth out sharp lightness/colour changes that might induce the perception
% of false features. In doing this there will be some cost to the
% perceptual contrast at these points.
if sigma
L = smooth(L, sigma, cyclic);
a = smooth(a, sigma, cyclic);
b = smooth(b, sigma, cyclic);
end
% Convert map back to RGB
newlabmap = [L a b];
newrgbmap = applycform(newlabmap, makecform('lab2srgb', 'AdaptedWhitePoint', wp));
if diagnostics
% Compute actual perceptual contrast values achieved
if strcmpi(formula, 'CIE76')
newdeltaE = cie76(L, a, b, W);
elseif strcmpi(formula, 'CIEDE2000')
newdeltaE = ciede2000(L, a, b, W);
else
error('Unknown colour difference formula')
end
show(sineramp,1,'Unequalised input colour map'), colormap(rgbmap);
show(sineramp,2,'Equalised colour map'), colormap(newrgbmap);
figure(3), clf
subplot(2,1,1)
plot(initialcumdE)
title(sprintf('Cumulative change in %s of input colour map', formula));
axis([1 N 0 1.05*max(cumdE(:))]);
xlabel('Colour map index');
subplot(2,1,2)
plot(1:N, initialdeltaE, 1:N, newdeltaE)
axis([1 N 0 1.05*max(initialdeltaE(:))]);
legend('Original colour map', ...
'Adjusted colour map', 'location', 'NorthWest');
title(sprintf('Magnitude of %s differences along colour map', formula));
xlabel('Colour map index');
ylabel('dE')
% Convert newmap back to Lab to check for gamut clipping
labmap = applycform(newrgbmap,...
makecform('srgb2lab', 'AdaptedWhitePoint', wp));
figure(4), clf
subplot(3,1,3)
plot(1:N, L-labmap(:,1),...
1:N, a-labmap(:,2),...
1:N, b-labmap(:,3))
legend('Lightness', 'a', 'b', 'Location', 'NorthWest')
maxe = max(abs([L-labmap(:,1); a-labmap(:,2); b-labmap(:,3)]));
axis([1 N -maxe maxe]);
title('Difference between desired and achieved L a b values (gamut clipping)')
% Plot RGB values
subplot(3,1,1)
plot(1:N, newrgbmap(:,1),'r-',...
1:N, newrgbmap(:,2),'g-',...
1:N, newrgbmap(:,3),'b-')
legend('Red', 'Green', 'Blue', 'Location', 'NorthWest')
axis([1 N 0 1.1]);
title('RGB values along colour map')
% Plot Lab values
subplot(3,1,2)
plot(1:N, L, 1:N, a, 1:N, b)
legend('Lightness', 'a', 'b', 'Location', 'NorthWest')
axis([1 N -100 100]);
title('L a b values along colour map')
%% Extra plots to generate figures.
% The following plots were developed for illustrating the
% equalization of MATLAB's hot(64) colour map. Run using:
% >> hoteq = equalisecolourmap('RGB', hot, 'CIE76', [1 0 0], 0, 0, 1);
fs = 12; % fontsize
% Colour difference values
figure(10), clf
plot(1:N, initialdeltaE, 'linewidth', 2);
axis([1 N 0 1.05*max(initialdeltaE(:))]);
title(sprintf('Magnitude of %s lightness differences along colour map', ...
formula), 'fontweight', 'bold', 'fontsize', fs);
xlabel('Colour map index', 'fontweight', 'bold', 'fontsize', fs);
ylabel('dE', 'fontweight', 'bold', 'fontsize', fs);
% Cumulative difference plot showing mapping of equicontrast colours
figure(11), clf
plot(initialcumdE, 'linewidth', 2), hold on
s = 7;
s = 10;
for n = s:s:N
line([0 initialnewN(n) initialnewN(n)],...
[initialequicumdE(n) initialequicumdE(n) 0], ...
'linestyle', '--', 'color', [0 0 0], 'linewidth', 1.5)
ah = s/2; % Arrow height and width
aw = ah/5;
plot([initialnewN(n)-aw initialnewN(n) initialnewN(n)+aw],...
[ah 0 ah],'k-', 'linewidth', 1.5)
end
title(sprintf('Cumulative change in %s lightness of colour map', formula), ...
'fontweight', 'bold', 'fontsize', fs);
axis([1 N+6 0 1.05*max(cumdE(:))]);
xlabel('Colour map index', 'fontweight', 'bold', 'fontsize', fs);
ylabel('Equispaced cumulative contrast', 'fontweight', 'bold', 'fontsize', fs);
hold off
end
%----------------------------------------------------------------------------
%
% Function to smooth an array of values but also ensure end values are not
% altered or, if the map is cyclic, ensures smoothing is applied across the end
% points in a cyclic manner. Assumed that the input data is a column vector
function Ls = smooth(L, sigma, cyclic)
sze = ceil(6*sigma); if ~mod(sze,2), sze = sze+1; end
G = fspecial('gaussian', [sze 1], sigma);
if cyclic
Le = [L(:); L(:); L(:)]; % Form a concatenation of 3 repetitions of the array.
Ls = filter2(G, Le); % Apply smoothing filter
% and then return the center section
Ls = Ls(length(L)+1: length(L)+length(L));
else % Non-cyclic colour map: Pad out input array L at both ends by 3*sigma
% with additional values at the same slope. The aim is to eliminate
% edge effects in the filtering
extension = (1:ceil(3*sigma))';
dL1 = L(2)-L(1);
dL2 = L(end)-L(end-1);
Le = [-flipud(dL1*extension)+L(1); L; dL2*extension+L(end)];
Ls = filter2(G, Le); % Apply smoothing filter
% Trim off extensions
Ls = Ls(length(extension)+1 : length(extension)+length(L));
end
%----------------------------------------------------------------------------
% Delta E using the CIE76 formula + weighting
function deltaE = cie76(L, a, b, W)
N = length(L);
% Compute central differences
dL = zeros(size(L));
da = zeros(size(a));
db = zeros(size(b));
dL(2:end-1) = (L(3:end) - L(1:end-2))/2;
da(2:end-1) = (a(3:end) - a(1:end-2))/2;
db(2:end-1) = (b(3:end) - b(1:end-2))/2;
% Differences at end points
dL(1) = L(2) - L(1); dL(end) = L(end) - L(end-1);
da(1) = a(2) - a(1); da(end) = a(end) - a(end-1);
db(1) = b(2) - b(1); db(end) = b(end) - b(end-1);
deltaE = sqrt(W(1)*dL.^2 + W(2)*da.^2 + W(3)*db.^2);
%----------------------------------------------------------------------------
% Delta E using the CIEDE2000 formula + weighting
%
% This function requires Gaurav Sharma's MATLAB implementation of the CIEDE2000
% color difference formula deltaE2000.m available at:
% http://www.ece.rochester.edu/~gsharma/ciede2000/
function deltaE = ciede2000(L, a, b, W)
N = length(L);
Lab = [L(:) a(:) b(:)];
KLCH = 1./W;
% Compute deltaE using central differences
deltaE = zeros(N, 1);
deltaE(2:end-1) = deltaE2000(Lab(1:end-2,:), Lab(3:end,:), KLCH)/2;
% Differences at end points
deltaE(1) = deltaE2000(Lab(1,:), Lab(2,:), KLCH);
deltaE(end) = deltaE2000(Lab(end-1,:), Lab(end,:), KLCH);
|
github
|
jacksky64/imageProcessing-master
|
cmap.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/cmap.m
| 45,076 |
utf_8
|
f2b84fc935b1cb87ca94d191893eefde
|
% CMAP Library of perceptually uniform colour maps
%
% Usage: 1: [map, name, desc] = cmap(I, param_name, value ...)
% 2: cmap
% 3: cmap(str)
%
% Arguments for Usage 1:
%
% I - A string label indicating the colour map to be generated or a
% string specifying a colour map name or attribute to search
% for. Type 'cmap' with no arguments to get a full list of
% possible colour maps and their corresponding labels.
%
% labels: 'L1' - 'L15' for linear maps
% 'D1' - 'D12' for diverging maps
% 'C1' - 'C9' for cyclic maps
% 'R1' - 'R2' for rainbow maps
% 'I1' - 'I3' for isoluminant maps
%
% Some colour maps have alternate labels for convenience and readability.
% >> map = cmap('L1') or map = cmap('grey') will produce a linear grey map.
% >> cmap % With no arguments lists all colour maps and labels.
%
% Possible param_name - value options:
%
% 'chromaK' - The scaling to apply to the chroma values of the colour map,
% 0 - 1. The default is 1 giving a fully saturated colour map
% as designed. However, depending on your application you may
% want a colour map with reduced chroma/saturation values.
% You can use values greater than 1 however gamut clipping is
% likely to occur giving rise to artifacts in the colour map.
% 'N' - Number of values in the colour map. Defaults to 256.
% 'shift' - Fraction of the colour map length N that the colour map is
% to be cyclically rotated, may be negative. (Should only be
% applied to cyclic colour maps!). Defaults to 0.
% 'reverse' - If set to 1 reverses the colour map. Defaults to 0.
% 'diagnostics' - If set to 1 displays various diagnostic plots. Note the
% diagnostic plots will be for the map _before_ any cyclic
% shifting or reversing is applied. Defaults to 0.
%
% The parameter name strings can be abbreviated to their first letter.
%
% Returns:
% map - Nx3 rgb colour map
% name - A string giving a nominal name for the colour map
% desc - A string giving a brief description of the colour map
%
%
% Usage 2 and 3: cmap(str)
%
% Given the large number of colour maps that this function can create this usage
% option provides some help by listing the numbers of all the colour maps with
% names containing the string 'str'. Typically this is used to search for
% colour maps having a specified attribute: 'linear', 'diverging', 'rainbow',
% 'cyclic', or 'isoluminant' etc. If 'str' is omitted all colour maps are
% listed.
%
% >> cmap % lists all colour maps
% >> cmap('diverging') % lists all diverging colour maps
%
% Note the listing of colour maps can be a bit slow because each colour map has to
% be created in order to determine its full name.
%
%
% Colour Map naming convention:
%
% linear_kryw_5-100_c67_n256
% / / | \ \
% Colour Map attribute(s) / | \ Number of colour map entries
% / | \
% String indicating nominal | Mean chroma of colour map
% hue sequence. |
% Range of lightness values
%
% In addition, the name of the colour map may have cyclic shift information
% appended to it, it may also have a flag indicating it is reversed.
%
% cyclic_wrwbw_90-40_c42_n256_s25_r
% / \
% / Indicates that the map is reversed.
% /
% Percentage of colour map length
% that the map has been rotated by.
%
% * Attributes may be: linear, diverging, cyclic, rainbow, or isoluminant. A
% colour map may have more than one attribute. For example, diverging-linear or
% cyclic-isoluminant.
%
% * Lightness values can range from 0 to 100. For linear colour maps the two
% lightness values indicate the first and last lightness values in the
% map. For diverging colour maps the second value indicates the lightness value
% of the centre point of the colour map (unless it is a diverging-linear
% colour map). For cyclic and rainbow colour maps the two values indicate the
% minimum and maximum lightness values. Isoluminant colour maps have only
% one lightness value.
%
% * The string of characters indicating the nominal hue sequence uses the following code
% r - red g - green b - blue
% c - cyan m - magenta y - yellow
% o - orange v - violet
% k - black w - white j - grey
%
% ('j' rhymes with grey). Thus a 'heat' style colour map would be indicated by
% the string 'kryw'. If the colour map is predominantly one colour then the
% full name of that colour may be used. Note these codes are mainly used to
% indicate the hues of the colour map independent of the lightness/darkness and
% saturation of the colours.
%
% * Mean chroma/saturation is an indication of vividness of the colour map. A
% value of 0 corresponds to a greyscale. A value of 50 or more will indicate a
% vivid colour map.
%
%
% See also: EQUALISECOLOURMAP, VIEWLABSPACE, SINERAMP, CIRCLESINERAMP, COLOURMAPPATH
% Adding your own colour maps is straightforward.
%
% 1) Colour maps are almost invariably defined via a spline path through CIELAB
% colourspace. Use VIEWLABSPACE to work out the positions of the spline
% control points in CIELAB space to achieve the colour map path you desire.
% These are stored in an array 'colpts' with columns corresponding to L a and
% b. If desired the path can be specified in terms of RGB space by setting
% 'colourspace' to 'RGB'. See the ternary colour maps as an example. Note
% the case expression for the colour map label must be upper case.
%
% 2) Set 'splineorder' to 2 for a linear spline segments. Use 3 for a quadratic
% b-spline.
%
% 3) If the colour map path has lightness gradient reversals set 'sigma' to a
% value of around 5 to 7 to smooth the gradient reversal.
%
% 4) If the colour map is of very low lightness contrast, or isoluminant, set
% the lightness, a and b colour difference weight vector W to [1 1 1].
% See EQUALISECOLOURMAP for more details
%
% 5) Set the attribute and hue sequence strings ('attributeStr' and 'hueStr')
% appropriately so that a colour map name can be generated. Note that if you
% are constructing a cyclic colour map it is important that 'attributeStr'
% contains the word 'cyclic'. This ensures that a periodic b-spline is used
% and also ensures that smoothing is applied in a cyclic manner. Setting the
% description string is optional.
%
% 6) Run CMAP specifying the number of your new colour map with the diagnostics
% flag set to one. Various plots are generated allowing you to check the
% perceptual uniformity, colour map path, and any gamut clipping of your
% colour map.
% Copyright (c) 2013-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.
% December 2013 Original version
% March 2014 Various enhancements
% August 2014 Catalogue listing
% September 2014 Provision for specifying paths in RGB, cyclic shifting and
% reversing
% October 2014 Renamed to CMAP (from LABMAPLIB) and all the failed
% experimental maps cleaned out and retained maps renumbered
% in a more coherent way
function [map, name, desc] = cmap(varargin)
[I, N, chromaK, shift, reverse, diagnostics] = parseinputs(varargin{:});
% Default parameters for colour map construction.
% Individual colour map specifications may override some of these.
colourspace = 'LAB'; % Control points specified in CIELAB space
sigma = 0; % Default smoothing for colour map lightness equalisation.
splineorder = 3; % Default order of b-spline colour map curve.
formula = 'CIE76'; % Default colour difference formula.
W = [1 0 0]; % Colour difference weighting for Lightness,
% chroma and hue (default is to only use Lightness)
desc = '';
name = '';
attributeStr = '';
hueStr = '';
switch I % Note all case expressions must be upper case.
%-----------------------------------------------------------------------------
%% Linear series
case {'L1', 'GREY'} % Grey 0 - 100
desc = 'Grey scale';
attributeStr = 'linear';
hueStr = 'grey';
colpts = [ 0 0 0
100 0 0];
splineorder = 2;
case {'L2', 'REDUCEDGREY'} % Grey 10 - 95
desc = ['Grey scale with slightly reduced contrast to '...
'avoid display saturation problems'];
attributeStr = 'linear';
hueStr = 'grey';
colpts = [10 0 0
95 0 0];
splineorder = 2;
case {'L3', 'HEAT', 'HEATWHITE'}
desc = 'Black-Red-Yellow-White heat colour map';
attributeStr = 'linear';
hueStr = 'kryw';
colpts = [5 0 0
15 35 21
25 47 37
35 58 48
45 69 58
55 74 66
65 48 70
75 21 75
85 -10 75
100 0 0 ];
case {'L4', 'HEATYELLOW'}
desc = 'Black-Red-Yellow heat colour map';
attributeStr = 'linear';
hueStr = 'kry';
colpts = [5 0 0
15 35 21
25 47 37
35 58 48
45 69 58
55 74 66
65 48 70
75 21 75
85 -10 75
95 -22 92];
case 'L5'
desc = 'Colour Map along the green edge of CIELAB space';
attributeStr = 'linear';
hueStr = 'green';
colpts = [ 5 -9 5
15 -23 20
25 -31 31
35 -39 39
45 -47 47
55 -55 55
65 -63 63
75 -71 71
85 -79 79
95 -38 90];
case 'L6'
desc = 'Blue shades running vertically up the blue edge of CIELAB space';
attributeStr = 'linear';
hueStr = 'blue';
colpts = [ 5 31 -45
15 50 -66
25 65 -90
35 70 -100
45 45 -85
55 20 -70
65 0 -53
75 -22 -37
85 -38 -20
95 -25 -3];
case 'L7'
desc = 'Blue-Pink-Light Pink colour map';
attributeStr = 'linear';
hueStr = 'bmw';
colpts = [ 5 30 -52
15 49 -80
25 64 -105
35 73 -105
45 81 -88
55 90 -71
65 85 -55
75 58 -38
85 34 -23
95 10 -7];
case 'L8'
desc = 'Blue-Magenta-Orange-Yellow highly saturated colour map';
attributeStr = 'linear';
hueStr = 'bmy';
colpts = [10 ch2ab( 78,-60)
20 ch2ab(100,-60)
30 ch2ab( 78,-40)
40 ch2ab( 74,-20)
50 ch2ab( 80, 0)
60 ch2ab( 80, 20)
70 ch2ab( 72, 50)
80 ch2ab( 84, 77)
95 ch2ab( 90, 95)];
case 'L9' % Blue to yellow section of R1 with short extensions at
% each end
attributeStr = 'linear';
hueStr = 'bgyw';
colpts = [15 50 -65
35 67 -100
45 -14 -30
60 -55 60
85 -10 80
95 -17 50
100 0 0];
case {'L10', 'GEOGRAPHIC1'}
desc = ['A ''geographical'' colour map. '...
'Best used with relief shading'];
attributeStr = 'linear';
hueStr = 'gow';
colpts = [60 ch2ab(20, 180) % pale blue green
65 ch2ab(30, 135)
70 ch2ab(35, 75)
75 ch2ab(45, 85)
80 ch2ab(22, 90)
85 0 0 ];
case {'L11', 'GEOGRAPHIC2'} % Lighter version of L10 with a bit more chroma
desc = ['A ''geographical'' colour map. '...
'Best used with relief shading'];
attributeStr = 'linear';
hueStr = 'gow';
colpts = [65 ch2ab(50, 135) % pale blue green
75 ch2ab(45, 75)
80 ch2ab(45, 85)
85 ch2ab(22, 90)
90 0 0 ];
case {'L12', 'DEPTH'}
desc = 'A ''water depth'' colour map';
attributeStr = 'linear';
hueStr = 'blue';
colpts = [95 0 0
80 ch2ab(20, -95)
70 ch2ab(25, -95)
60 ch2ab(25, -95)
50 ch2ab(35, -95)];
% The following three colour maps are for ternary images, eg Landsat images
% and radiometric images. These colours form the nominal red, green and
% blue 'basis colours' that are used to form the composite image. They are
% designed so that they, and their secondary colours, have nearly the same
% lightness levels and comparable chroma. This provides consistent feature
% salience no matter what channel-colour assignment is made. The colour
% maps are specified as straight lines in RGB space. For their derivation
% see
% http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary
case {'L13', 'REDTERNARY'}
desc = 'red colour map for ternary images';
attributeStr = 'linear';
hueStr = 'ternary-red';
colourspace = 'RGB';
colpts = [0.00 0.00 0.00
0.90 0.17 0.00];
splineorder = 2;
case {'L14', 'GREENTERNARY'}
desc = 'green colour map for ternary images';
attributeStr = 'linear';
hueStr = 'ternary-green';
colourspace = 'RGB';
colpts = [0.00 0.00 0.00
0.00 0.50 0.00];
splineorder = 2;
case {'L15', 'BLUETERNARY'}
desc = 'blue colour map for ternary images';
attributeStr = 'linear';
hueStr = 'ternary-blue';
colourspace = 'RGB';
colpts = [0.00 0.00 0.00
0.10 0.33 1.00];
splineorder = 2;
%--------------------------------------------------------------------------------
%% Diverging colour maps
% Note that on these colour maps often we do not go to full white but use a
% lightness value of 95. This helps avoid saturation problems on monitors.
% A lightness smoothing sigma of 5 to 7 is used to avoid generating a false
% feature at the white point in the middle. Note however, this does create
% a small perceptual contrast blind spot at the middle.
case 'D1'
desc = 'Diverging blue-white-red colour map';
attributeStr = 'diverging';
hueStr = 'bwr';
colpts = [40 ch2ab(83,-64)
95 0 0
40 ch2ab(83, 39)];
sigma = 7;
splineorder = 2;
case 'D1A' % Attempt to imrove metric property of D1
desc = 'Diverging blue-white-red colour map';
attributeStr = 'diverging';
hueStr = 'bwr';
colpts = [40 ch2ab(83,-64)
65 ch2ab(70, -28)
95 0 0
95 0 0
% 65 ch2ab(60, 13)
65 ch2ab(70, 75)
40 ch2ab(83, 39)];
sigma = 7;
splineorder = 3;
case 'D2'
desc = 'Diverging green-white-violet colour map';
attributeStr = 'diverging';
hueStr = 'gwv';
colpts = [55 -50 55
95 0 0
55 60 -55];
sigma = 7;
splineorder = 2;
case 'D3'
desc = 'Diverging green-white-red colour map';
attributeStr = 'diverging';
hueStr = 'gwr';
colpts = [55 -50 55
95 0 0
55 63 39];
sigma = 7;
splineorder = 2;
case 'D4'
desc = 'Diverging blue - black - red colour map';
attributeStr = 'diverging';
hueStr = 'bkr';
colpts = [55 ch2ab(70, -85)
10 0 0
55 ch2ab(70, 35)];
sigma = 7;
splineorder = 2;
case 'D5'
desc = 'Diverging green - black - red colour map';
attributeStr = 'diverging';
hueStr = 'gkr';
colpts = [60 ch2ab(80, 134)
10 0 0
60 ch2ab(80, 40)];
sigma = 7;
splineorder = 2;
case 'D6'
desc = 'Diverging blue - black - yellow colour map';
attributeStr = 'diverging';
hueStr = 'bky';
colpts = [60 ch2ab(60, -95)
10 0 0
60 ch2ab(60, 85)];
sigma = 7;
splineorder = 2;
case 'D7' % Linear diverging blue - grey - yellow. Works well
attributeStr = 'diverging-linear';
hueStr = 'bjy';
colpts = [30 ch2ab(89, -59)
60 0 0
90 ch2ab(89,96)];
splineorder = 2;
case 'D7B' % Linear diverging blue - grey - yellow.
% Similar to 'D7' but with slight curves in the path to
% slightly increase the chroma at the 1/4 and 3/4 locations
% in the map.
attributeStr = 'diverging-linear';
hueStr = 'bjy';
h1 = -59; h2 = 95;
mh = (h1+h2)/2;
dh = 10;
colpts = [30 ch2ab(88, h1)
48 ch2ab(40, h1+dh)
60 0 0
60 0 0
72 ch2ab(40, h2-dh)
90 ch2ab(88, h2)];
splineorder = 3;
case 'D8' % Linear diverging blue - grey - red
attributeStr = 'diverging-linear';
hueStr = 'bjr';
colpts = [30 ch2ab(105, -60)
42.5 0 0
55 ch2ab(105,40)];
splineorder = 2;
case 'D9' % Lightened version of D1 for relief shading - Good.
desc = 'Diverging low contrast blue - red colour map';
attributeStr = 'diverging';
hueStr = 'bwr';
colpts = [55 ch2ab(73,-74)
98 0 0
55 ch2ab(73, 39)];
sigma = 2; % Less smoothing needed for low contrast
splineorder = 2;
case 'D10' % low contrast diverging map for when you want to use
% relief shading
desc = 'Diverging low contrast cyan - white - magenta colour map';
attributeStr = 'diverging';
hueStr = 'cwm';
colpts = [80 ch2ab(44, -135)
100 0 0
80 ch2ab(44, -30)];
sigma = 0; % No smoothing needed for lightness range of 20
splineorder = 2;
W = [1 1 1];
case 'D11' % Constant lightness diverging map for when you want to use
% relief shading ? Perhaps lighten the grey so it is not quite
% isoluminant ?
desc = 'Diverging isoluminat lightblue - lightgrey - orange colour map';
attributeStr = 'diverging-isoluminant';
hueStr = 'cjo';
colpts = [70 ch2ab(50, -115)
70 0 0
70 ch2ab(50, 45)];
sigma = 7;
splineorder = 2;
W = [1 1 1];
case 'D12' % Constant lightness diverging map for when you want to use
% relief shading ? Perhaps lighten the grey so it is not quite
% isoluminant ?
desc = 'Diverging isoluminat lightblue - lightgrey - pink colour map';
attributeStr = 'diverging-isoluminant';
hueStr = 'cjm';
colpts = [75 ch2ab(48, -127)
75 0 0
75 ch2ab(48, -30)];
sigma = 7;
splineorder = 2;
W = [1 1 1];
%-------------------------------------------------------------------------
%% Cyclic colour maps
case 'C1' % I think this is my best zigzag style cyclic map - Good!
% Control points are placed so that lightness steps up and
% down are equalised. Additional intermediate points are
% placed to try to even up the 'spread' of the key colours.
attributeStr = 'cyclic';
hueStr = 'mrybm';
mag = [75 60 -40];
yel = [75 0 77];
blu = [35 70 -100];
red = [35 60 48];
colpts = [mag
55 70 0
red
55 35 62
yel
50 -20 -30
blu
55 45 -67
mag];
sigma = 7;
splineorder = 2; % linear path
case 'C2' % A big diamond across the gamut. Really good! Incorporates two
% extra cotnrol points around blue to extend the width of that
% segment slightly.
attributeStr = 'cyclic';
hueStr = 'mygbm';
colpts = [62.5 83 -54
80 20 25
95 -20 90
62.5 -65 62
42 10 -50
30 75 -103
48 70 -80
62.5 83 -54];
sigma = 7;
splineorder = 2;
case 'C3' % red-white-blue-black-red allows quadrants to be identified
desc = 'Cyclic: red - white - blue - black - red';
attributeStr = 'cyclic';
hueStr = 'rwbkr';
colpts = [50 ch2ab(85, 39)
85 0 0
50 ch2ab(85, -70)
15 0 0
50 ch2ab(85, 39)];
sigma = 7;
splineorder = 2;
case 'C4' % white-red-white-blue-white Works nicely
desc = 'Cyclic: white - red - white - blue';
attributeStr = 'cyclic';
hueStr = 'wrwbw';
colpts = [90 0 0
40 65 56
90 0 0
40 31 -80
90 0 0];
sigma = 7;
splineorder = 2;
case {'C5', 'CYCLICGREY'} % Cyclic greyscale Works well
desc = 'Cyclic: greyscale';
attributeStr = 'cyclic';
hueStr = 'grey';
colpts = [50 0 0
85 0 0
15 0 0
50 0 0];
sigma = 7;
splineorder = 2;
case 'C6' % Circle at 67 - sort of ok but a bit flouro
attributeStr = 'cyclic-isoluminant';
hueStr = 'mgbm';
chr = 42;
ang = 124;
colpts = [67 ch2ab(chr, ang-90)
67 ch2ab(chr, ang)
67 ch2ab(chr, ang+90)
67 ch2ab(chr, ang+180)
67 ch2ab(chr, ang-90)];
W = [1 1 1];
case 'C7' % Elliptical path - ok
attributeStr = 'cyclic';
hueStr = 'mygbm';
ang = 112;
colpts = [70 ch2ab(46, ang-90)
90 ch2ab(82, ang)
70 ch2ab(46, ang+90)
50 ch2ab(82, ang+180)
70 ch2ab(46, ang-90)];
W = [1 1 1];
case 'C8' % Elliptical path. Greater range of lightness values and
% slightly more saturated colours. Seems to work however I do
% not find the colour sequence that attractive. This is a
% constraint of the gamut.
attributeStr = 'cyclic';
hueStr = 'mybm';
ang = 124;
colpts = [60 ch2ab(40, ang-90)
100 ch2ab(98, ang)
60 ch2ab(40, ang+90)
20 ch2ab(98, ang+180)
60 ch2ab(40, ang-90)];
W = [1 1 1];
sigma = 7;
case 'C9' % Variation of C1. Perceptually this is good. Excellent balance
% of colours in the quadrants but the colour mix is not to my
% taste. Don't like the green. The red-green transition clashes
attributeStr = 'cyclic';
hueStr = 'bgrmb';
blu = [35 70 -100];
colpts = [blu
70 -70 64
35 65 50
70 75 -46
blu ];
sigma = 7;
splineorder = 2; % linear path
%-----------------------------------------------------------------------------
%% Rainbow style colour maps
case {'R1', 'RAINBOW'} % Reasonable rainbow colour map after it has been
% fixed by equalisecolourmap.
desc = ['The least worst rainbow colour map I can devise. Note there are' ...
' small perceptual blind spots at yellow and red'];
attributeStr = 'rainbow';
hueStr = 'bgyrm';
colpts = [35 60 -100
45 -15 -30
60 -55 60
85 0 80
55 70 65
75 55 -35];
sigma = 7;
splineorder = 2; % linear path
case {'R2', 'RAINBOW2'} % Similar to R1 but with the colour map finishing
% at red rather than continuing onto pink.
desc = ['Reasonable rainbow colour map from blue to red. Note there is' ...
' a small perceptual blind spot at yellow'];
attributeStr = 'rainbow';
hueStr = 'bgyr';
colpts = [35 60 -100
45 -15 -30
60 -55 60
85 0 80
55 75 70];
sigma = 5;
splineorder = 2; % linear path
case 'R3' % Diverging rainbow. The blue and red points are matched in
% lightness and chroma as are the green and magenta points
attributeStr = 'diverging-rainbow';
hueStr = 'bgymr';
colpts = [45 39 -83
52 -23 -23
60 -55 55
85 -2 85
60 74 -17
45 70 59];
sigma = 5;
splineorder = 2; % linear path
%-----------------------------------------------------------------------------
%% Isoluminant colour maps
case 'I1'
desc = ['Isoluminant blue to green to orange at lightness 70. '...
'Poor on its own but works well with relief shading'];
attributeStr = 'isoluminant';
hueStr = 'cgo';
colpts = [70 ch2ab(40, -115)
70 ch2ab(50, 160)
70 ch2ab(50, 90)
70 ch2ab(50, 45)];
W = [1 1 1];
case 'I2' % Adaptation of I1 shifted to 80 from 70
desc = ['Isoluminant blue to green to orange at lightness 80. '...
'Poor on its own but works well with relief shading'];
attributeStr = 'isoluminant';
hueStr = 'cgo';
colpts = [80 ch2ab(40, -115)
80 ch2ab(50, 160)
80 ch2ab(50, 90)
80 ch2ab(50, 45)];
W = [1 1 1];
case 'I3'
attributeStr = 'isoluminant';
hueStr = 'cm';
colpts = [70 ch2ab(40, -125)
70 ch2ab(40, -80)
70 ch2ab(40, -40)
70 ch2ab(50, 0)];
W = [1 1 1];
%-----------------------------------------------------------------------------
%% Experimental colour maps and colour maps that illustrate some design principles
case 'X1'
desc = ['Two linear segments with different slope to illustrate importance' ...
' of lightness gradient.'];
attributeStr = 'linear-lightnessnormalised';
hueStr = 'by';
colpts = [30 ch2ab(102, -54)
40 0 0
90 ch2ab(90, 95)];
W = [1 0 0];
splineorder = 2;
case 'X2'
desc = ['Two linear segments with different slope to illustrate importance' ...
' of lightness gradient.'];
attributeStr = 'linear-CIE76normalised';
hueStr = 'by';
colpts = [30 ch2ab(102, -54)
40 0 0
90 ch2ab(90, 95)];
W = [1 1 1];
splineorder = 2;
case 'X3' % Constant lightness 'v' path to test unimportance of having a smooth
% path in hue/chroma. Slight 'feature' at the red corner (Seems more
% important on poor monitors)
attributeStr = 'isoluminant-HueChromaSlopeDiscontinuity';
hueStr = 'brg';
colpts = [50 17 -78
50 77 57
50 -48 50];
splineorder = 2; % linear path
W = [1 1 1];
% A set of isoluminant colour maps only varying in saturation to test
% the importance of saturation (not much) Colour Maps are linear with
% a reversal to test importance of continuity.
case 'X10' % Isoluminant 50 only varying in saturation
attributeStr = 'isoluminant';
hueStr = 'r';
colpts = [50 0 0
50 77 64
50 0 0];
splineorder = 2;
sigma = 0;
W = [1 1 1];
case 'X11' % Isoluminant 50 only varying in saturation
attributeStr = 'isoluminant';
hueStr = 'b';
colpts = [50 0 0
50 0 -56
50 0 0];
splineorder = 2;
sigma = 0;
W = [1 1 1];
case 'X12' % Isoluminant 90 only varying in saturation
attributeStr = 'isoluminant';
hueStr = 'isoluminant_90_g';
colpts = [90 0 0
90 -76 80
90 0 0];
splineorder = 2;
sigma = 0;
W = [1 1 1];
% Difference in CIE76 and CIEDE2000 in chroma
case 'X13' % Isoluminant 55 only varying in chroma. CIEDE76
attributeStr= 'isoluminant-CIE76';
hueStr = 'jr';
colpts = [55 0 0
55 80 67];
splineorder = 2;
W = [1 1 1];
formula = 'CIE76';
case 'X14' % Same as X13 but using CIEDE2000
attributeStr= 'isoluminant-CIEDE2000';
hueStr = 'jr';
colpts = [55 0 0
55 80 67];
splineorder = 2;
W = [1 1 1];
formula = 'CIEDE2000';
case 'X15' % Grey 0 - 100. Same as No 1 but with CIEDE2000
desc = 'Grey scale';
attributeStr= 'linear-CIEDE2000';
hueStr = 'grey';
colpts = [ 0 0 0
100 0 0];
splineorder = 2;
formula = 'CIEDE2000';
case 'X16' % Isoluminant 30 only varying in chroma
attributeStr= 'isoluminant';
hueStr = 'b';
colpts = [30 0 0
30 77 -106];
splineorder = 2;
W = [1 1 1];
case 'X21' % Blue to yellow section of rainbow map R1 for illustrating
% colour ordering issues
attributeStr= 'rainbow-section1';
hueStr = 'bgy';
colpts = [35 60 -100
45 -15 -30
60 -55 60
85 0 80];
splineorder = 2; % linear path
case 'X22' % Red to yellow section of rainbow map R1 for illustrating
% colour ordering issues
attributeStr= 'rainbow-section2';
hueStr = 'ry';
colpts = [55 70 65
85 0 80];
splineorder = 2; % linear path
case 'X23' % Red to pink section of rainbow map R1 for illustrating
% colour ordering issues
attributeStr= 'rainbow-section3';
hueStr = 'rm';
colpts = [55 70 65
75 55 -35];
splineorder = 2; % linear path
case 'XD1' % Same as D1 but with no smoothing
desc = 'Diverging blue-white-red colour map';
attributeStr = 'diverging';
hueStr = 'bwr';
colpts = [40 ch2ab(83,-64)
95 0 0
40 ch2ab(83, 39)];
sigma = 0;
splineorder = 2;
case 'X30'
desc = 'red - green - blue interpolated in rgb';
attributeStr = 'linear';
hueStr = 'rgb';
colourspace = 'RGB';
colpts = [1.00 0.00 0.00
0.00 1.00 0.00
0.00 0.00 1.00];
sigma = 0;
W = [0 0 0];
splineorder = 2;
case 'X31'
desc = 'red - green - blue interpolated in CIELAB';
attributeStr = 'linear';
hueStr = 'rgb';
colourspace = 'LAB';
colpts = [53 80 67
88 -86 83
32 79 -108];
sigma = 0;
W = [0 0 0];
splineorder = 2;
case 'XD7A' % Linear diverging blue - magenta- grey - orange - yellow.
% Modified from 'D7' to have a double arch shaped path in an attempt
% to improve its Metric properties. Also starts at lightness
% of 40 rather than 30. The centre grey region is a bit too
% prominant and overall the map is perhaps a bit too 'bright'
attributeStr = 'diverging-linear';
hueStr = 'bmjoy';
colpts = [40 ch2ab(88, -64)
55 ch2ab(70, -30)
64 ch2ab(2.5, -72.5)
65 0 0
66 ch2ab(2.5, 107.5)
75 ch2ab(70, 70)
90 ch2ab(88,100)];
splineorder = 3;
case 'XC15B' % Francesca Samsel's beautiful c15b blue-white-green
% diverging map. Map is reproduced in its original form
% with no equalisation of lightness gradient. (It is
% close to being equal as originally designed.)
desc = 'Francesca Samsel''s c15b blue-white-green diverging map';
attributeStr = 'diverging';
hueStr = 'bwg';
colourspace = 'RGB';
colpts = [0.231373 0.247059 0.329412
0.266667 0.305882 0.411765
0.286275 0.368627 0.478431
0.301961 0.439216 0.549020
0.309804 0.521569 0.619608
0.380392 0.631373 0.690196
0.454902 0.745098 0.760784
0.541176 0.831373 0.803922
0.631373 0.901961 0.843137
0.768627 0.960784 0.894118
0.901961 1.000000 0.949020
0.768627 0.960784 0.835294
0.635294 0.909804 0.698039
0.552941 0.850980 0.576471
0.490196 0.780392 0.466667
0.447059 0.701961 0.384314
0.407843 0.611765 0.305882
0.360784 0.509804 0.231373
0.305882 0.400000 0.160784
0.231373 0.278431 0.098039
0.141176 0.149020 0.043137];
sigma = 0;
W = [0 0 0]; % Set to zero to reproduce original map exactly
splineorder = 2;
case 'XC15BM' % Francesca's map modified slightly with additional
% starting control point to create symmetric lightness
% profile. Alternatively, remove the near black colour at
% the end. Map is equalised for lightness gradient. A
% really nice map!
desc = 'Francesca Samsel''s c15b blue-white-green diverging map';
attributeStr = 'diverging';
hueStr = 'bwg';
colourspace = 'RGB';
colpts = [%0.120752 0.138784 0.214192 % additional point to match lightness at end
0.231373 0.247059 0.329412
0.266667 0.305882 0.411765
0.286275 0.368627 0.478431
0.301961 0.439216 0.549020
0.309804 0.521569 0.619608
0.380392 0.631373 0.690196
0.454902 0.745098 0.760784
0.541176 0.831373 0.803922
0.631373 0.901961 0.843137
0.768627 0.960784 0.894118
0.901961 1.000000 0.949020
0.768627 0.960784 0.835294
0.635294 0.909804 0.698039
0.552941 0.850980 0.576471
0.490196 0.780392 0.466667
0.447059 0.701961 0.384314
0.407843 0.611765 0.305882
0.360784 0.509804 0.231373
0.305882 0.400000 0.160784
% 0.231373 0.278431 0.098039
0.2218 0.2690 0.0890 % tweeked to match start lightness
% 0.141176 0.149020 0.043137
];
sigma = 7;
W = [1 0 0];
splineorder = 2;
case 'XD7C' % Linear diverging green - grey - yellow
% Reasonable, perhaps easier on the eye than D7
attributeStr = 'diverging-linear';
hueStr = 'gjy';
rad = 65;
colpts = [40 ch2ab(rad, 136)
65 0 0
90 ch2ab(rad, 95)];
splineorder = 2;
%%-------------------------------------------------------------
otherwise
% Invoke the catalogue search to help the user
catalogue(I);
clear map;
clear name;
clear desc;
return
end
% Adjust chroma/saturation but only if colourspace is LAB
if strcmpi(colourspace, 'LAB')
colpts(:,2:3) = chromaK * colpts(:,2:3);
end
% Colour map path is formed via a b-spline in the specified colour space
Npts = size(colpts,1);
if Npts < 2
error('Number of input points must be 2 or more')
elseif Npts < splineorder
splineorder = Npts;
fprintf('Warning: Spline order is greater than number of data points\n')
fprintf('Reducing order of spline to %d\n', Npts)
end
% Rely on the attribute string to identify if colour map is cyclic. We may
% want to construct a colour map that has identical endpoints but do not
% necessarily want continuity in the slope of the colour map path.
if strfind(attributeStr, 'cyclic')
cyclic = 1;
labspline = pbspline(colpts', splineorder, N);
else
cyclic = 0;
labspline = bbspline(colpts', splineorder, N);
end
% Apply contrast equalisation with required parameters. Note that sigma is
% normalised with respect to a colour map of length 256 so that if a short
% colour map is specified the smoothing that is applied is adjusted to suit.
sigma = sigma*N/256;
map = equalisecolourmap(colourspace, labspline', formula,...
W, sigma, cyclic, diagnostics);
% If specified apply a cyclic shift to the colour map
if shift
if isempty(strfind(attributeStr, 'cyclic'))
fprintf('Warning: Colour map shifting being applied to a non-cyclic map\n');
end
map = circshift(map, round(N*shift));
end
if reverse
map = flipud(map);
end
% Compute mean chroma of colour map
lab = rgb2lab(map);
meanchroma = sum(sqrt(sum(lab(:,2:3).^2, 2)))/N;
% Construct lightness range description
if strcmpi(colourspace, 'LAB') % Use the control points
L = colpts(:,1);
else % For RGB use the converted CIELAB values
L = round(lab(:,1));
end
minL = min(L);
maxL = max(L);
if minL == maxL % Isoluminant
LStr = sprintf('%d', minL);
elseif L(1) == maxL && ...
(~isempty(strfind(attributeStr, 'diverging')) ||...
~isempty(strfind(attributeStr, 'linear')))
LStr = sprintf('%d-%d', maxL, minL);
else
LStr = sprintf('%d-%d', minL, maxL);
end
% Build overall colour map name
name = sprintf('%s_%s_%s_c%d_n%d',...
attributeStr, hueStr, LStr, round(meanchroma), N);
if shift
name = sprintf('%s_s%d', name, round(shift*100));
end
if reverse
name = sprintf('%s_r', name);
end
if diagnostics % Print description and plot path in colourspace
fprintf('%s\n',desc);
colourmappath(map, 'fig', 10)
end
%------------------------------------------------------------------
% Conversion from (chroma, hue angle) description to (a*, b*) coords
function ab = ch2ab(chroma, angle_degrees)
theta = angle_degrees/180*pi;
ab = chroma*[cos(theta) sin(theta)];
%------------------------------------------------------------------
%
% Function to list colour maps with names containing a specific string.
% Typically this is used to search for colour maps having a specified attribute:
% 'linear', 'diverging', 'rainbow', 'cyclic', 'isoluminant' or 'all'.
% This code is awful!
function catalogue(str)
if ~exist('str', 'var')
str = 'all';
end
% Get all case expressions in this function
caseexpr = findcaseexpr;
% Construct all colour map names
for n = 1:length(caseexpr)
% Get 1st comma separated element in caseexpr
label = strtok(caseexpr{n},',');
[~, name{n}] = cmap(label);
end
% Check each colour name for the specified search string. Exclude the
% experimental maps with label starting with X.
fprintf('\n CMAP label(s) Colour Map name\n')
fprintf('------------------------------------------------\n')
found = 0;
for n = 1:length(caseexpr)
if caseexpr{n}(1) ~= 'X'
if any(strfind(upper(name{n}), str)) || strcmpi(str, 'all')
fprintf('%-20s %s\n', caseexpr{n}, name{n});
found = 1;
end
end
end
if ~found
fprintf('Sorry, no colour map with label or attribute %s found\n', str);
end
%-----------------------------------------------------------------------
% Function to find all the case expressions in this function. Yuk there must
% be a better way! Assumes the case statement do not span more than one line
function caseexpr = findcaseexpr
[fid, msg] = fopen([mfilename('fullpath') '.m'], 'r');
error(msg);
caseexpr = {};
n = 0;
line = fgetl(fid);
while ischar(line)
[tok, remain] = strtok(line);
if strcmpi(tok, 'case')
% If we are here remain should be the case expression.
% Remove any trailing comment from case expression
[tok, remain] = strtok(remain,'%');
% Remove any curly brackets from the case expression
tok(tok=='{') = [];
tok(tok=='}') = [];
tok(tok=='''') = [];
n = n+1;
caseexpr{n} = tok;
end
line = fgetl(fid);
end
caseexpr = strtrim(caseexpr);
fclose(fid);
%-----------------------------------------------------------------------
% Function to parse the input arguments and set defaults
function [I, N, chromaK, shift, reverse, diagnostics] = parseinputs(varargin)
p = inputParser;
numericORchar = @(x) isnumeric(x) || ischar(x);
numericORlogical = @(x) isnumeric(x) || islogical(x);
% The first argument is either a colour map label string or a string to
% search for in a colourmap name. If no argument is supplied it is assumed
% the user wants to list all possible colourmaps.
addOptional(p, 'I', 'all', @ischar);
% Optional parameter-value pairs and their defaults
% ** Note if you are using R2012 or earlier you should change the calls to
% 'addParameter' below to 'addParamValue' and hopefully the code will work
% for you.
addParameter(p, 'N', 256, @isnumeric);
addParameter(p, 'shift', 0, @isnumeric);
addParameter(p, 'chromaK', 1, @isnumeric);
addParameter(p, 'reverse', 0, numericORlogical);
addParameter(p, 'diagnostics', 0, numericORlogical);
parse(p, varargin{:});
I = strtrim(upper(p.Results.I));
N = p.Results.N;
chromaK = p.Results.chromaK;
shift = p.Results.shift;
reverse = p.Results.reverse;
diagnostics = p.Results.diagnostics;
if abs(shift) > 1
error('Cyclic shift fraction magnitude cannot be larger than 1');
end
if chromaK < 0
error('chromaK must be greater than 0')
end
if chromaK > 1
fprintf('Warning: chromaK is greater than 1. Gamut clipping may occur')
end
|
github
|
jacksky64/imageProcessing-master
|
ternarycolours.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/ternarycolours.m
| 4,004 |
utf_8
|
ea4668fc20c8bc3e6e26893981927aab
|
% TERNARYCOLOURS Determine 3 basis colours for a ternary image
%
% This function determines 3 basis colours for constructing ternary/radiometric
% images. Ideally these are isoluminant and have the same chroma. While this
% function does not achieve this perfectly the three colours it generates are
% fairly good.
%
% Usage: [C1, C2, C3, rgb1, rgb2, rgb3] = ternarycolours
%
% Returns: C1 C2 C3 - Basis colours defined in CIELAB space
% rgb1-3 - Basis colours in RGB space.
%
% The strategy is to first define 2 colours in CIELAB, a nominal 'red' and
% 'green'. From this we compute third colour, 'blue' so that the 3 colours when
% summed in RGB space produce a neutral grey.
%
% After some experimentation the two colours in CIELAB that I defined were
% C1 = [53 80 67]; % Red (as in RGB red)
% C2 = [52 -57 55]; % Green having maximum chroma at a lightness of 52
%
% This results in the third colour being
% C3 = [50 30 -78];
%
% These are not quite isoluminant but seems to be a good compromise. Choosing a
% green with a lightness of 52 results in a 'blue' with a lightness of about
% 50. While this is slightly darker than the other colours it allows the blue to
% have a larger chroma/saturation than what would be otherwise possible at a
% lightness of 53. The three colours have chroma of 104, 79 and 86
% respectively. While these are not equal they are comparable. Visually the
% result appears to be a reasonable compromise.
%
% The RGB values that these three colours correspond to are:
% rgb1 = [1.00 0.00 0.00]
% rgb2 = [0.00 0.57 0.00]
% rgb3 = [0.00 0.43 1.00]
%
% Inspecting these values we can see that by using a reduced green (RGB green
% has a lightness of about 88) some of this 'greenness' is transferred to the
% 'blue' basis colour increasing its lightness and making it more of a cyan
% colour.
%
% See also: VIEWLABSPACE, LINEARRGBMAP, LABMAPLIB
% Copyright (c) 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 2014
function [C1, C2, C3, rgb1, rgb2, rgb3] = ternarycolours
% Define the two initial basis colours. These are what I came up with by
% experimentation, edit as you wish...
C1 = [53 80 67]; % Red (as in RGB red)
C2 = [52 -57 55]; % Green having maximum chroma at a lightness of 52
% Convert to rgb and subtract from [1 1 1] to solve for the rgb values of
% the 3rd basis colour.
rgb1 = lab2rgb(C1);
rgb2 = lab2rgb(C2);
rgb3 = [1 1 1] - rgb1 - rgb2;
% Convert back to CIELAB space to check for any gamut clipping etc
C1 = rgb2lab(rgb1);
C2 = rgb2lab(rgb2);
C3 = rgb2lab(rgb3);
% Reconstruct rgb3 to check for gamut clipping
rgb3 = lab2rgb(C3);
% Construct linear rgb colourmaps to these 3 colours so that we can
% inspect what we have created.
map1 = linearrgbmap(rgb1);
map2 = linearrgbmap(rgb2);
map3 = linearrgbmap(rgb3);
show(sineramp, 11), colormap(map1);
show(sineramp, 12), colormap(map2);
show(sineramp, 13), colormap(map3);
% Form the sum of the colourmaps so that we can check there is no colour
% cast in the sum of the maps.
summaps = map1+map2+map3;
max(summaps(:));
summaps = summaps/max(summaps(:));
show(sineramp, 14), colormap(summaps);
figure(15)
plot(0:255,summaps(:,1), 'r-', ...
0:255,summaps(:,2), 'g-', ...
0:255,summaps(:,3), 'b-')
title('R G B values of summed colourmaps')
|
github
|
jacksky64/imageProcessing-master
|
map2qgisstyle.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/map2qgisstyle.m
| 3,266 |
utf_8
|
e8e5248686bb0f8761231f97fcc521db
|
% MAP2QGISSTYLE Writes colour maps to QGIS style file
%
% Usage: map2qgisstyle(map, mapname, filename)
%
% Arguments: map - N x 3 colour map, or a cell array of N x 3 colour maps
% mapname - String giving the colour map name, or a cell array of
% strings
% filename - File name to write QGIS xml style file to.
%
% See also: WRITEQGISMAPS
% Copyright (c) 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.
% October 2014
function map2qgisstyle(map, mapname, filename)
% Ideally I should construct a DOMnode object and write that out using xmlwrite
% but I do not know enough about the QGIS spec. Hence this hand rolled file.
% If a single colourmap has been supplied rather than a cell array
% convert it and its mapname to a single element cell arrays
if ~iscell(map)
tmp1 = map; delete map;
tmp2 = mapname; delete mapname;
map{1} = tmp1;
mapname{1} = tmp2;
end
nmaps = length(map);
% Ensure file has a .xml ending
if ~strendswith(filename, '.xml')
filename = [filename '.xml'];
end
[fid, msg] = fopen(filename, 'wt');
error(msg);
fprintf(fid,'<!DOCTYPE qgis_style>\n');
fprintf(fid,'<qgis_style version="1">\n');
fprintf(fid,'<!-- \n');
fprintf(fid,'CET Perceptually Uniform Colour Maps\n');
fprintf(fid,'Peter Kovesi\n');
fprintf(fid,'Center for Exploration Targeting\n');
fprintf(fid,'The University of Western Australia\n');
fprintf(fid,'www.cet.edu.au\n');
fprintf(fid,'-->\n');
fprintf(fid,'<colorramps>\n');
for m = 1:nmaps
% Convert colour map values from doubles in range 0-1 to ints ranging
% from 0-255
map{m} = round(map{m}*255);
[mapelements,~] = size(map{m});
fprintf(fid,'<colorramp type="gradient" name="%s">\n', mapname{m});
fprintf(fid,'<prop k="color1" v="%d,%d,%d,255"/>\n', ...
map{m}(1,1), map{m}(1,2), map{m}(1,3));
fprintf(fid,'<prop k="color2" v="%d,%d,%d,255"/>\n', ...
map{m}(end,1), map{m}(end,2), map{m}(end,3));
fprintf(fid,'<prop k="discrete" v="0"/>\n');
fprintf(fid,'<prop k="stops" v="');
for n = 2:mapelements-1
fprintf(fid,'%.3f;%d,%d,%d,255',(n-1)/(mapelements-1), ...
map{m}(n,1), map{m}(n,2), map{m}(n,3));
if n < (mapelements-1)
fprintf(fid,':');
end
end
fprintf(fid,'"/>\n');
fprintf(fid,'</colorramp>\n');
end % for each map
fprintf(fid,'</colorramps>\n');
fprintf(fid,'</qgis_style>\n');
fclose(fid);
|
github
|
jacksky64/imageProcessing-master
|
ternaryimage.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/ternaryimage.m
| 3,966 |
utf_8
|
34a7ce4ff9d4772808994acf7a46b194
|
% TERNARYIMAGE Perceptualy uniform ternary image from 3 bands of data
%
% Usage: rgbim = ternaryimage(im, bands, histcut, Rmap, Gmap, Bmap)
%
% Arguments
% im - Multiband image with at least 3 bands, or a cell array of
% at least 3 images.
% bands - Array of 3 values indicating the bands, to be assigned to
% the red, green and blue basis colour maps. If omitted, or
% empty, bands defaults to [1 2 3].
% histcut - Percentage of image band histograms to clip. It can be
% useful to clip 1-2%. If you see lots of white in your
% ternary image you have clipped too much. Defaults to 0.
% R/G/Bmap - Three basis colourmaps to be applied to the specified
% bands of the input image which are then summed to form
% the ternary image. If omitted the colour maps default to
% those generated by TERNARYMAPS.
% If Rmap is the string 'RGB' then the RGB primaries are
% used. This creates a 'classical' ternary image. (Though not
% very efficiently).
%
% Returns:
% rgbim - RGB ternary image
%
% The default colour maps obtained from TERNARYMAPS result in colours that are
% not as vivid as the RGB primaries but they produce perceptually uniform
% ternary images with consistent feature salience no matter what permutation of
% channel-colour assignement is used.
%
% For the derivation of the three primary colours used by TERNARYMAPS see:
% http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary
%
% See also: TERNARYMAPS, APPLYCOLOURMAP, LINEARRGBMAP
% Copyright (c) 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.
function rgbim = ternaryimage(im, bands, histcut, Rmap, Gmap, Bmap)
if ~exist('bands', 'var') || isempty(bands), bands = [1 2 3]; end
if ~exist('histcut', 'var'), histcut = 0; end
if ~exist('Rmap', 'var'), [Rmap, Gmap, Bmap] = ternarymaps; end
if strcmpi(Rmap, 'RGB')
Rmap = linearrgbmap([1 0 0]);
Gmap = linearrgbmap([0 1 0]);
Bmap = linearrgbmap([0 0 1]);
end
if iscell(im)
if max(bands) > length(im)
error('Band specification outside image range');
end
if histcut
rgbim = applycolourmap(histtruncate(im{bands(1)}, histcut), Rmap) + ...
applycolourmap(histtruncate(im{bands(2)}, histcut), Gmap) + ...
applycolourmap(histtruncate(im{bands(3)}, histcut), Bmap);
else
rgbim = applycolourmap(im{bands(1)}, Rmap) + ...
applycolourmap(im{bands(2)}, Gmap) + ...
applycolourmap(im{bands(3)}, Bmap);
end
else
if max(bands) > size(im,3)
error('Band specification outside image range');
end
if histcut
rgbim = applycolourmap(histtruncate(im(:,:,bands(1)), histcut), Rmap) + ...
applycolourmap(histtruncate(im(:,:,bands(2)), histcut), Gmap) + ...
applycolourmap(histtruncate(im(:,:,bands(3)), histcut), Bmap);
else
rgbim = applycolourmap(im(:,:,bands(1)), Rmap) + ...
applycolourmap(im(:,:,bands(2)), Gmap) + ...
applycolourmap(im(:,:,bands(3)), Bmap);
end
end
|
github
|
jacksky64/imageProcessing-master
|
linearrgbmap.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/linearrgbmap.m
| 882 |
utf_8
|
ffe885dc19eb15928ea8117e1902d32e
|
% LINEARRGBMAP Linear rgb colourmap from black to a specified colour
%
% Usage: map = linearrgbmap(C, N)
%
% Arguments: C - 3-vector specifying RGB colour
% N - Number of colourmap elements, defaults to 256
%
% Returns: map - Nx3 RGB colourmap ranging from [0 0 0] to colour C
%
% It is suggested that you pass the resulting colour map to EQUALISECOLOURMAP
% to obtain a map with uniform steps in perceptual lightness
% >> map = equalisecolourmap('rgb', linearrgbmap(C, N));
%
% See also: EQUALISECOLOURMAP, TERNARYMAPS, COLOURMAPPATH
% Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
% PK August 2014
function map = linearrgbmap(C, N)
if ~exist('N', 'var'), N = 256; end
map = zeros(N,3);
ramp = (0:(N-1))'/(N-1);
for n = 1:3
map(:,n) = C(n) * ramp;
end
|
github
|
jacksky64/imageProcessing-master
|
readermapperlutfile.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/readermapperlutfile.m
| 3,143 |
utf_8
|
137e2c6fab526b434b8ab24d23106693
|
% READERMAPPERLUTFILE Read ER Mapper LUT colour map file
%
% Usage: [map, name, description] = readermapperlutfile(filename)
%
% Argument: filename - Filename to read
%
% Returns:
% map - N x 3 rgb colour map of values 0-1.
% name - Name of colour map (if specified in file).
% description - Description of colour map (if specified in file).
%
% The ER Mapper LUT file format is also used by MapInfo
%
% This function has minimal error checking and assumes the file is reasonably
% 'well formed'.
%
% See also: MAP2ERMAPPERLUTFILE, MAP2IMAGEJLUTFILE
% 2014 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
% PK Sept 2014
function [map, name, description] = readermapperlutfile(filename)
map = []; name = ''; description = '';
if ~exist('filename', 'var')
[filename, pathname] = uigetfile('*.lut');
if ~filename
return;
end
filename = [pathname filename];
end
[fid,msg] = fopen(filename, 'r');
if fid == -1
error(sprintf('Unable to open %s', filename));
end
% Read each line, discard empty lines and look for keywords
line = fgetl(fid);
[tok, remain] = strtok(line);
while ~strcmpi(tok, 'LUT')
if strcmpi(tok, 'Name')
name = processline(remain);
elseif strcmpi(tok, 'Description')
description = processline(remain);
elseif strcmpi(tok, 'NrEntries')
NrEntries = eval(processline(remain));
end
line = fgetl(fid);
if line == -1
error('Unexpected end of file encountered');
end
[tok, remain] = strtok(line);
end
if ~exist('NrEntries', 'var')
error('Unable to determine number of colour map entries')
end
% If we get to here we expect to have NrEntries lines of the form
% EntryNo R G B
% There may also be a comment at the end of each line so we have to read
% them one by one.
% Note that we read the data from the file in row order but MATLAB stores
% it in column order hence the [4 NrEntries] dimensioning and the
% subsequent transpose
map = zeros(4, NrEntries);
for n = 1:NrEntries
line = fgetl(fid);
if line == -1
error('Unexpected end of file encountered');
end
% Read 4 ints from each line and ignore anything beyond
[map(:,n), count] = sscanf(line, '%d %d %d %d');
if count ~= 4
error('Incorrect number of entries in colour map');
end
end
map = map';
% Read the final } and LookUpTable End ?
fclose(fid);
% Remove the first column of map and rescale values 0-1
map = double(map(:,2:4))/(2^16-1);
%---------------------------------------------------------
% Grab the remaining token in a line ignoring white space, tabs, '=' and '"'
function tok = processline(line)
[tok,remain] = strtok(line, [' = "' char(9)]);
|
github
|
jacksky64/imageProcessing-master
|
writecolourmapfn.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/writecolourmapfn.m
| 1,354 |
utf_8
|
2b064a86456dae2b3ea2634a7edad8c0
|
% WRITECOLOURMAPFN Creates a MATLAB function file from a Nx3 colourmap
%
% Usage: writecolourmapfn(map, fname)
%
% PK June 2014
function writecolourmapfn(map, fname)
[N, chan] = size(map);
if chan ~= 3
error('Colourmap must be Nx3');
end
if strendswith(fname, '.m') % If fname has been given a .m ending
fname = strtok(fname, '.'); % remove it (but we will restore it later)
end
% Convert any '-' characters in the name to '_' as '-' is an operator and
% cannot be used in a function name
fname(fname=='-') = '_';
fid = fopen([fname '.m'], 'wt');
% Strip off any directory path from the filename
str = strsplit(fname, '/');
fname = str{end};
fprintf(fid, '%% Uniform Perceptual Contrast Colourmap\n');
fprintf(fid, '%% \n');
fprintf(fid, '%% Usage: map = %s\n', fname);
fprintf(fid, '%% \n');
fprintf(fid, '%% \n');
fprintf(fid, '%% Centre for Exploration Targeting\n');
fprintf(fid, '%% The University of Western Australia\n');
fprintf(fid, '%% %s \n', date);
fprintf(fid, '%% \n');
fprintf(fid, 'function map = %s\n', fname);
fprintf(fid, 'map = [ ...\n');
for n = 1:N
fprintf(fid, '%f %f %f\n', map(n,1), map(n,2), map(n,3));
end
fprintf(fid, '];\n');
fclose(fid);
|
github
|
jacksky64/imageProcessing-master
|
map2geosofttbl.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/map2geosofttbl.m
| 1,634 |
utf_8
|
f354e08adec5586e24061af7e42c98de
|
% MAP2GEOSOFTTBL Converts MATLAB colourmap to Geosoft .tbl file
%
% Usage: map2geosofttbl(map, filename, cmyk)
%
% Arguments: map - N x 3 rgb colourmap
% filename - Output filename
% cmyk - Optional flag 0/1 indicating whether CMYK values should
% be written. Defaults to 0 whereby RGB values are
% written
%
% This function writes a RGB colourmap out to a .tbl file that can be loaded
% into Geosoft Oasis Montaj
%
% See also: RGB2CMYK
% Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
% PK October 2012
% June 2014 - RGB or CMYK option
function map2geosofttbl(map, filename, cmyk)
if ~exist('cmyk', 'var'), cmyk = 0; end
[N, cols] = size(map);
if cols ~= 3
error('Colourmap must be N x 3 in size')
end
% Ensure filename ends with .tbl
if ~strendswith(filename, '.tbl')
filename = [filename '.tbl'];
end
fid = fopen(filename, 'wt');
if cmyk % Convert RGB values in map to CMYK and scale 0 - 255
cmyk = round(rgb2cmyk(map)*255);
kcmy = circshift(cmyk, [0 1]); % Shift K to 1st column
fprintf(fid, '{ blk cyn mag yel }\n');
for n = 1:N
fprintf(fid, ' %03d %03d %03d %03d \n', kcmy(n,:));
end
else % Write RGB values
map = round(map*255);
fprintf(fid, '{ red grn blu }\n');
for n = 1:N
fprintf(fid, ' %3d %3d %3d\n', map(n,:));
end
end
fclose(fid);
|
github
|
jacksky64/imageProcessing-master
|
readimagejlutfile.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/readimagejlutfile.m
| 1,122 |
utf_8
|
f1de0f94122413d9e59d237a6b0c2674
|
% READIMAGEJLUTFILE Reads lut colourmap file as used by ImageJ
%
% Usage: map = readimagejlutfile(fname)
%
% Argument: fname - Filename of a .lut file
% Returns: map - 256 x 3 colourmap table
%
% The format of a lookup table for ImageJ is 256 bytes of red values, followed
% by 256 green values and finally 256 blue values. A total of 768 bytes.
%
% See also: MAP2IMAGEJLUTFILE, MAP2ERMAPPERLUTFILE
% 2014 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
% PK June 2014
function map = readimagejlutfile(fname)
map = [];
if ~exist('filename', 'var')
[filename, pathname] = uigetfile('*.lut');
if ~filename
return;
end
filename = [pathname filename];
end
[fid, msg] = fopen(fname, 'r');
if fid == -1
error(sprintf('Unable to open %s', fname));
end
map = fread(fid, inf, 'uint8');
if length(map) ~= 768
error('LUT file does not have 768 entries');
end
map = reshape(map, 256, 3);
map = double(map)/255;
fclose(fid);
|
github
|
jacksky64/imageProcessing-master
|
map2actfile.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/map2actfile.m
| 741 |
utf_8
|
4c119e2da488dd0845d360b13ebc6d46
|
% MAP2ACTFILE Writes colourmap to .act file Adobe Colourmap Table
%
% Usage: map2actfile(map, fname)
%
% An Adobe Colourmap Table is a file of 256 sets of R G and B values written as
% bytes, a total of 768 bytes.
%
% PK June 2014
function map2actfile(map, fname)
[N, chan] = size(map);
if N ~= 256 | chan ~= 3
error('Colourmap must be 256x3');
end
% Ensure file has a .act ending
if ~strendswith(fname, '.act')
fname = [fname '.act'];
end
% Convert map to integers 0-255 and form into a single vector of
% sequential RGB values
map = round(map*255);
map = map';
map = map(:);
fid = fopen(fname, 'w');
fwrite(fid, map, 'uint8');
fclose(fid);
|
github
|
jacksky64/imageProcessing-master
|
ternarymaps.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/ternarymaps.m
| 1,992 |
utf_8
|
f1edae4213fc031028b69d29f72addcc
|
% TERNARYMAPS Returns three basis colour maps for generating ternary images
%
% Usage: [Rmap, Gmap, Bmap] = ternarymaps(N);
%
% Argument: N - Number of elements within the colour maps. This is optional
% and defaults to 256
% Returns:
% Rmap, Gmap, Bmap - Three colour maps that are nominally red, green
% and blue but the colours have been chosen so that
% they, and their secondary colours, are closely matched
% in lightness.
%
% The colours are not as vivid as the RGB primaries but they produce ternary
% images with consistent feature salience no matter what permutation of
% channel-colour assignement is used.
%
% For the derivation of the three primary colours see:
% http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary
%
% See also: TERNARYIMAGE, EQUALISECOLOURMAP, LINEARRGBMAP, APPLYCOLOURMAP
% Copyright (c) 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.
function [Rmap, Gmap, Bmap] = ternarymaps(N)
if ~exist('N', 'var'), N = 256; end
% The three primary colours. For their derivation see:
% http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary
R = [0.90 0.17 0.00];
G = [0.00 0.50 0.00];
B = [0.10 0.33 1.00];
Rmap = equalisecolourmap('rgb', linearrgbmap(R, N));
Gmap = equalisecolourmap('rgb', linearrgbmap(G, N));
Bmap = equalisecolourmap('rgb', linearrgbmap(B, N));
|
github
|
jacksky64/imageProcessing-master
|
geosofttbl2map.m
|
.m
|
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/geosofttbl2map.m
| 1,313 |
utf_8
|
97f965db62a9a1ea1d2d5bccb32bd608
|
% GEOSOFTTBL2MAP Converts Geosoft .tbl file to MATLAB colourmap
%
% Usage: geosofttbl2map(filename, map)
%
% Arguments: filename - Input filename of tbl file
% map - N x 3 rgb colourmap
%
%
% This function reads a Geosoft .tbl file and converts the KCMY values to a RGB
% colourmap.
%
% See also: MAP2GEOSOFTTBL, RGB2CMYK
% Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
% PK July 2013
function map = geosofttbl2map(filename)
% Read the file
[fid, msg] = fopen(filename, 'rt');
error(msg);
% Read, test and then discard first line
txt = strtrim(fgetl(fid));
% Very basic file check. Test that it starts with '{'
if txt(1) ~= '{'
error('This may not be a Geosoft tbl file')
end
% Read remaining lines containing the colour table
[data, count] = fscanf(fid, '%d');
if mod(count,4) % We expect 4 columns of data
error('Number of values read not a multiple of 4');
end
% Reshape data so that columns form kcmy tuples
kcmy = reshape(data, 4, count/4);
% Transpose so that the rows form kcmy tuples and normalise 0-1
kcmy = kcmy'/255;
cmyk = [kcmy(:,2:4) kcmy(:,1)];
map = cmyk2rgb(cmyk);
fclose(fid);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.