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
colourmappath.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/colourmappath.m
11,106
utf_8
657a67e384f4f2074c75cffc36b9c945
% COLOURMAPPATH Plots the path of a colour map through colour space % % Usage: colourmappath(map, param_name, value, ....) % % Required argument: % map - The colourmap to be plotted % % Optional parameter-value pairs, default values in brackets: % 'N' - The nmber of slices through the colourspace to plot (6). % 'colspace' - String 'rgb' or 'lab' indicating the colourspace to plot % ('lab'). % 'fig' - Optional figure number to use (new figure created). % 'linewidth' - Width of map path line (2.5). % 'dotspace' - Spacing between colour map entries where dots are plotted % along the path (5). % 'dotsize' - (15). Use 0 if you want no dots plotted. % 'dotcolour' - ([0.8 0.8 0.8]) % 'fontsize' - (14). % 'fontweight' - ('bold'). % % The colour space is represented as a series of semi-transparent 2D slices % which hopefully lets you visualise the colour space and the colour map path % simultaneously. % % Note that for some reason repeated calls of this function to render a colour % map path in RGB space seem to ultimately cause MATLAB to crash (under MATLAB % 2013b on OSX). Rendering paths in CIELAB space cause no problem. % % See also: CMAP, EQUALISECOLOURMAP, VIEWLABSPACE, SINERAMP, CIRCSINERAMP % 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. % October 2013 - Original version % October 2014 - Parameter options added %function colourmappath(map, N, colspace, fig) % Original argument list function colourmappath(varargin) [map, N, colspace, fig, linewidth, ds, dotcolour, dotsize, fontsize, fontweight] ... = parseinputs(varargin{:}); mapref = map; %% RGB plot --------------------------------------------------------- if strcmpi(colspace, 'rgb') R = 255; delta = 2; % Downsampling factor for red and green [x,y] = meshgrid(0:delta:R, 0:delta:R); [sze, ~] = size(x); im = zeros(sze, sze, 3, 'uint8'); figure(fig), clf, axis([-1 sze+1 -1 sze+1 -1 sze+1]) % Draw N red-green planes of increasing blue value through RGB space for b = 0:R/(N-1):R for r = 0:delta:R for g = 0:delta:R im(g/delta+1, r/delta+1, :) = [r; g; round(b)]; end end h = warp(b*ones(sze,sze), im); hold on set(h, 'FaceAlpha', 0.9); end % Plot the colour map path through the RGB colour space. Rescale map % to account for scaling to 255 and for downsampling (yuk) map(:,1:2) = map(:,1:2)*255/delta; map(:,3) = map(:,3)*255; line(map(:,1), map(:,2), map(:,3), 'linewidth', linewidth, 'color', [0 0 0]); hold on % Plot a dot for every 'dotspace' point along the colour map to indicate the % spacing of colours in the colour map if dotsize plot3(map(1:ds:end,1), map(1:ds:end,2), map(1:ds:end,3), '.', ... 'Color', dotcolour, 'MarkerSize', dotsize); end hold off % Generate axis tick values tickcoords = [0:50:250]/delta; ticklabels = {'0'; '50'; '100'; '150'; '200'; '250'}; set(gca, 'xtick', tickcoords); set(gca, 'ytick', tickcoords); set(gca, 'xticklabel', ticklabels); set(gca, 'yticklabel', ticklabels); xlabel('Red'); ylabel('Green'); zlabel('Blue'); set(gca,'Fontsize', fontsize); set(gca,'Fontweight', fontweight); axis vis3d %% CIELAB plot ---------------------------------------------------- elseif strcmpi(colspace, 'lab') if iscell(mapref) % We have a cell array of colour maps figure(fig), clf, axis([-110 110 -110 110 0 100]) for n = 1:length(mapref) lab = rgb2lab(mapref{n}); line(lab(:,2), lab(:,3), lab(:,1), 'linewidth', linewidth, 'color', [0 0 0]) hold on if dotsize plot3(lab(1:ds:end,2), lab(1:ds:end,3), lab(1:ds:end,1), '.', ... 'Color', dotcolour, 'MarkerSize', dotsize); end end elseif ~isempty(map) % Single colour map supplied lab = rgb2lab(mapref); figure(fig), clf, axis([-110 110 -110 110 0 100]) line(lab(:,2), lab(:,3), lab(:,1), 'linewidth', linewidth, 'color', [0 0 0]) hold on if dotsize plot3(lab(1:ds:end,2), lab(1:ds:end,3), lab(1:ds:end,1), '.', ... 'Color', dotcolour, 'MarkerSize', dotsize); end % line([0 0], [0 0], [0 100]) % Line up a = 0, b = 0 axis end %% Generate Lab image slices % Define a*b* grid for image scale = 1; [a, b] = meshgrid([-127:1/scale:127]); [rows,cols] = size(a); % Generate N equi-spaced lightness levels between 5 and 95. for L = 5:90/(N-1):95 % For each lightness level... % Build image in lab space lab = zeros(rows,cols,3); lab(:,:,1) = L; lab(:,:,2) = a; lab(:,:,3) = b; % Generate rgb values from lab rgb = applycform(lab, makecform('lab2srgb')); % Invert to reconstruct the lab values lab2 = applycform(rgb, makecform('srgb2lab')); % 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 2 end [x,y,z,cdata] = labsurface(lab, rgb, L, 100); h = surface(x,y,z,cdata); shading interp; hold on set(h, 'FaceAlpha', 0.9); end % for each lightness level % Generate axis tick values tickval = [-100 -50 0 50 100]; tickcoords = tickval; %scale*tickval + cols/2; ticklabels = {'-100'; '-50'; '0'; '50'; '100'}; set(gca, 'xtick', tickcoords); set(gca, 'ytick', tickcoords); set(gca, 'xticklabel', ticklabels); set(gca, 'yticklabel', ticklabels); ztickval = [0 20 40 60 80 100]; zticklabels = {'0' '20' ' 40' '60' '80' '100'}; set(gca, 'ztick', ztickval); set(gca, 'zticklabel', zticklabels); set(gca,'Fontsize', fontsize); set(gca,'Fontweight', fontweight); % Label axes. Note option for manual placement for a and b manual = 0; if ~manual xlabel('a', 'Fontsize', fontsize, 'FontWeight', fontweight); ylabel('b', 'Fontsize', fontsize, 'FontWeight', fontweight); else text(0, -170, 0, 'a', 'Fontsize', fontsize, 'FontWeight', ... fontweight); text(155, 0, 0, 'b', 'Fontsize', fontsize, 'FontWeight', ... fontweight); end zlabel('L', 'Fontsize', fontsize, 'FontWeight', fontweight); axis vis3d grid on, box on view(64, 28) hold off else error('colspace must be rgb or lab') end %------------------------------------------------------------------- % LABSURFACE % % Idea to generate lab surfaces. Generate lab surface image, Sample a % parametric grid of x, y, z and colour values. Texturemap the colour values % onto the surface. % % Find first and last rows of image containing valid values. Interpolate y % over this range. For each value of y find first and last valid x values. % Interpolate x over this range sampling colour values as one goes. function [x, y, z, cdata] = labsurface(lab, rgb, zval, N) x = zeros(N,N); y = zeros(N,N); z = zeros(N,N); cdata = zeros(N,N,3); % Determine top and bottom edges of non-zero section of image gim = sum(rgb, 3); % Sum over all colour channels rowsum = sum(gim, 2); % Sum over rows ind = find(rowsum); top = ind(1); bottom = ind(end); rowvals = round(top + (0:N-1)/(N-1)*(bottom-top)); rowind = 1; for row = rowvals % Find first and last non-zero elements in this row ind = find(gim(row,:)); left = ind(1); right = ind(end); colvals = round(left + (0:N-1)/(N-1)*(right-left)); % Fill matrices colind = 1; for col = colvals x(rowind,colind) = lab(row,col,2); y(rowind,colind) = lab(row,col,3); z(rowind,colind) = zval; cdata(rowind, colind, :) = rgb(row, col, :); colind = colind+1; end rowind = rowind+1; end %----------------------------------------------------------------------- % Function to parse the input arguments and set defaults function [map, N, colspace, fig, linewidth, dotspace, dotcolour, dotsize, ... fontsize, fontweight] = parseinputs(varargin) p = inputParser; % numericorcell = @(x) isnumeric(x) || iscell(x); % addRequired(p, 'map', @numericorcell); addRequired(p, 'map'); % Optional parameter-value pairs and their defaults addParameter(p, 'N', 6, @isnumeric); addParameter(p, 'colspace', 'LAB', @ischar); addParameter(p, 'fig', -1, @isnumeric); addParameter(p, 'linewidth', 2.5, @isnumeric); addParameter(p, 'dotspace', 5, @isnumeric); addParameter(p, 'dotsize', 15, @isnumeric); addParameter(p, 'dotcolour', [0.8 0.8 0.8], @isnumeric); addParameter(p, 'fontsize', 14, @isnumeric); addParameter(p, 'fontweight', 'bold', @ischar); parse(p, varargin{:}); map = p.Results.map; N = p.Results.N; colspace = p.Results.colspace; dotspace = p.Results.dotspace; dotcolour = p.Results.dotcolour; dotsize = p.Results.dotsize; linewidth = p.Results.linewidth; fontsize = p.Results.fontsize; fontweight = p.Results.fontweight; fig = p.Results.fig; if fig < 0, fig = figure; end
github
jacksky64/imageProcessing-master
map2imagejlutfile.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/map2imagejlutfile.m
946
utf_8
20cb86304c4f39be3822f85d6648f55f
% MAP2IMAGEJLUTFILE Writes a colourmap to a .lut file for use with ImageJ % % Usage: map2imagejlutfile(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. % % See also: READIMAGEJLUTFILE, READERMAPPERLUTFILE % 2014 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % PK June 2014 function map2imagejlutfile(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
generatelabslice.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Colourmaps/generatelabslice.m
2,213
utf_8
99f7d5a31fd659193715f4e2451be585
% GENERATELABSLICE Generates RGB image of slice through CIELAB space % % Usage: rgbim = generatelabslice(L, flip); % % Arguments: L - Desired lightness level of slice through CIELAB space % flip - If set to 1 the image is fliped up-down. Default is 0 % Returns: rgbim - RGB image of slice % % The size of the returned image is 255 x 255. % The achromatic point being at (128, 128) % To convert from image (row, col) values to CIELAB (a, b) use: % The a coordinate corresponds to (col - 128) % If flip == 0 b = (row - 128) % else b = -(row - 128) % % See also: VIEWLABSPACE % 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. % PK September 2014 function rgb = generatelabslice(L, flip) if ~exist('flip', 'var'), flip = 0; end % Define a*b* grid for image [a, b] = meshgrid([-127:127]); if flip a = flipud(a); % Flip to make image display match convention b = flipud(b); % of LAB space display end [rows,cols] = size(a); % Build image in lab space labim = zeros(rows,cols,3); labim(:,:,1) = L; labim(:,:,2) = a; labim(:,:,3) = b; % Generate rgb values from lab rgb = applycform(labim, makecform('lab2srgb')); % Invert to reconstruct the lab values labim2 = applycform(rgb, makecform('srgb2lab')); % 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(labim-labim2),[],3); for n = 1:3 rgb(:,:,n) = rgb(:,:,n).*(mask<1); % tolerance of 1 end
github
jacksky64/imageProcessing-master
imagept2plane.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/imagept2plane.m
4,695
utf_8
aa2e6cfa89e81e68b3652ab0b7ea3e52
% IMAGEPT2PLANE - Project image points to a plane and return their 3D locations % % Usage: pt = imagept2plane(C, xy, planeP, planeN) % % Arguments: % C - Camera structure, see CAMSTRUCT for definition. Alternatively % C can be a 3x4 camera projection matrix. % xy - Image points specified as 2 x N array (x,y) / (col,row) % planeP - Some point on the plane. % planeN - Plane normal vector. % % Returns: % pt - 3xN array of 3D points on the plane that the image points % correspond to. % % Note that the plane is specified in terms of the world frame by defining a % 3D point on the plane, planeP, and a surface normal, planeN. % % Lens distortion is handled by using the standard lens distortion parameters, % assuming locally that the distortion is constant, computing the forward % distortion and then subtracting the distortion. % % See also CAMSTRUCT, CAMERAPROJECT % Copyright (c) 2015-2016 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 2015 - Original version % Jan 2016 - Removed use of inverse lens distortion parameters and instead % use the standard lens distortion parameters, assuming locally % that the distortion is constant, and subtracting the distortion. function pt = imagept2plane(C, xy, planeP, planeN) [dim,N] = size(xy); if dim ~= 2 error('Image xy data must be a 2 x N array'); end if ~isstruct(C) && all(size(C) == [3,4]) % We have a projection matrix C = projmatrix2camstruct(C); % Convert to camera structure end planeP = planeP(:); % Ensure column vectors planeN = planeN(:); % Reverse the projection process as used by CAMERAPROJECT % If only one focal length specified in structure use it for both fx and fy if isfield(C, 'f') fx = C.f; fy = C.f; elseif isfield(C, 'fx') && isfield(C, 'fy') fx = C.fx; fy = C.fy; else error('Invalid focal length specification in camera structure'); end if isfield(C, 'skew') % Handle optional skew specfication skew = C.skew; else skew = 0; end % Subtract principal point and divide by focal length to get normalised, % distorted image coordinates. Note skew represents the 2D shearing % coefficient times fx y_d = (xy(2,:) - C.ppy)/fy; x_d = (xy(1,:) - C.ppx - y_d*skew)/fx; % Radial distortion factor. Here the squared radius is computed from the % already distorted coordinates. The approximation we are making here is to % assume that the distortion is locally constant. rsqrd = x_d.^2 + y_d.^2; r_d = 1 + C.k1*rsqrd + C.k2*rsqrd.^2 + C.k3*rsqrd.^3; % Tangential distortion component, again computed from the already distorted % coords. dtx = 2*C.p1*x_d.*y_d + C.p2*(rsqrd + 2*x_d.^2); dty = C.p1*(rsqrd + 2*y_d.^2) + 2*C.p2*x_d.*y_d; % Subtract the tangential distortion components and divide by the radial % distortion factor to get an approximation of the undistorted normalised % image coordinates (with no skew) x_n = (x_d - dtx)./r_d; y_n = (y_d - dty)./r_d; % Define a set of points at the normalised distance of z = 1 from the % principal point, these define the viewing rays in terms of the camera % frame. ray = [x_n; y_n; ones(1,N)]; % Rotate to get the viewing rays in the world frame ray = C.Rc_w'*ray; % The point of intersection of each ray with the plane will be % pt = C.P + k*ray where k is to be determined % % Noting that the vector planeP -> pt will be perpendicular to planeN. % Hence the dot product between these two vectors will be 0. % dot((( C.P + k*ray ) - planeP) , planeN) = 0 % Rearranging this equation allows k to be solved pt = zeros(3,N); for n = 1:N % k = (dot(planeP, planeN) - dot(C.P, planeN)) / dot(ray(:,n), planeN); k = (planeP'*planeN - C.P'*planeN) / (ray(:,n)'*planeN); % Much faster! pt(:,n) = C.P + k*ray(:,n); end
github
jacksky64/imageProcessing-master
skew.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/skew.m
527
utf_8
68057bbcf6dc0afb3b008a6351532a72
% SKEW - Constructs 3x3 skew-symmetric matrix from 3-vector % % Usage: s = skew(v) % % Argument: v - 3-vector % Returns: s - 3x3 skew-symmetric matrix % % The cross product between two vectors, a x b can be implemented as a matrix % product skew(a)*b % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % October 2013 function s = skew(v) assert(numel(v) == 3); s = [ 0 -v(3) v(2) v(3) 0 -v(1) -v(2) v(1) 0 ];
github
jacksky64/imageProcessing-master
makehomogeneous.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/makehomogeneous.m
649
utf_8
19d1cac5b6483d4dd545ef8b6bca5dcb
% MAKEHOMOGENEOUS - Appends a scale of 1 to array inhomogeneous coordinates % % Usage: hx = makehomogeneous(x) % % Argument: % x - an N x npts array of inhomogeneous coordinates. % % Returns: % hx - an (N+1) x npts array of homogeneous coordinates with the % homogeneous scale set to 1 % % See also: MAKEINHOMOGENEOUS % 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 % % April 2010 function hx = makehomogeneous(x) [rows, npts] = size(x); hx = ones(rows+1, npts); hx(1:rows,:) = x;
github
jacksky64/imageProcessing-master
plotPoint.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/plotPoint.m
1,068
utf_8
d515fe2aec3bd3915d334310b903a4ba
% PLOTPOINT - Plots point with specified mark and optional text label. % % Function to plot 2D points with an optionally specified % marker and optional text label. % % Usage: % plotPoint(p) where p is a 2D point % plotPoint(p, 'mark') where mark is say 'r+' or 'g*' etc % plotPoint(p, 'mark', 'text') % % 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 % % April 2000 % November 2006 Typo in setting 'mk' fixed, text offset relative to point improved. function plotPoint(p, mark, txt) hold on mk = 'r+'; % Default mark is a red + if nargin >= 2 mk = mark; end plot(p(1), p(2), mk); if nargin == 3 % Print text next to point - calculate an appropriate amount to offset % the text from the point. xlim = get(gca,'Xlim'); ylim = get(gca,'Ylim'); offset = min((xlim(2)-xlim(1)),(ylim(2)-ylim(1)))/50; text(p(1)+offset,p(2)-offset,txt,'Color',mk(1)); end
github
jacksky64/imageProcessing-master
lengthRatioConstraint.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/lengthRatioConstraint.m
1,137
utf_8
587f4507cf32933e2f0468f438c17505
% lengthRatioConstraint - Affine transform constraints given a length ratio. % % Function calculates centre and radius of the constraint % circle in alpha-beta space generated by having a known % lenth ratio between two non-parallel line segemnts in % an affine image % % Usage: [c, r] = lengthRatioConstraint(p11, p12, p21, p22, s) % % Where: p11, p12 and p21, p22 are four points defining two line % segments having a known length ratio. % s is the known length ratio % c is the 2D coordinate of the centre of the constraint circle. % r is the radius of the centre of the constraint circle. % 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 % % April 2000 % % Equations from Liebowitz and Zisserman function [c, r] = lengthRatioConstraint(p11, p12, p21, p22, s) dp1 = p12-p11; dx1 = dp1(1); dy1 = dp1(2); dp2 = p22-p21; dx2 = dp2(1); dy2 = dp2(2); c = [(dx1*dy1 - s^2*dx2*dy2)/(dy1^2 - s^2*dy2^2), 0]; r = abs( s*(dx2*dy1 - dx1*dy2)/(dy1^2 - s^2*dy2^2) );
github
jacksky64/imageProcessing-master
fundfromcameras.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/fundfromcameras.m
1,308
utf_8
89d7618588ec84ececead8d97ea76b3e
% FUNDFROMCAMERAS - Fundamental matrix from camera matrices % % Usage: F = fundfromcameras(P1, P2) % % Arguments: P1, P2 - Two 3x4 camera matrices % Returns: F - Fundamental matrix relating the two camera views % % See also: FUNDMATRIX, AFFINEFUNDMATRIX % Reference: Hartley and Zisserman p244 % Copyright (c) 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 F = fundfromcameras(P1, P2) if ~all(size(P1) == [3 4]) | ~all(size(P2) == [3 4]) error('Camera matrices must be 3x4'); end C1 = null(P1); % Camera centre 1 is the null space of P1 e2 = P2*C1; % epipole in camera 2 e2x = [ 0 -e2(3) e2(2) % Skew symmetric matrix from e2 e2(3) 0 -e2(1) -e2(2) e2(1) 0 ]; F = e2x*P2*pinv(P1);
github
jacksky64/imageProcessing-master
circleintersect.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/circleintersect.m
2,710
utf_8
489ffc783300c34976f2c82fbed8c020
% CIRCLEINTERSECT - Finds intersection of two circles. % % Function to return the intersection points between two circles % given their centres and radi. % % Usage: [i1, i2] = circleintersect(c1, r1, c2, r2, lr) % % Where: % c1 and c2 are 2-vectors specifying the centres of the two circles. % r1 and r2 are the radii of the two circles. % i1 and i2 are the two 2D intersection points (if they exist) % lr is an optional string specifying what solution is wanted: % 'l' for the solution to the left of the line from c1 to c2 % 'r' for the solution to the right of the line from c1 to c2 % 'lr' if both solutions are wanted (default). % Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % Peter Kovesi % pk @ csse uwa edu au % http://www.csse.uwa.edu.au/~pk % % April 2000 - original version % October 2003 - mods to allow selection of left/right solutions % and catching of degenerate triangles function [i1, i2] = circleintersect(c1, r1, c2, r2, lr) if nargin == 4 lr = 'lr'; end maxmag = max([max(r1, r2), max(c1), max(c2)]); % maximum value in data input tol = 100*(maxmag+1)*eps; % Tolerance used for deciding whether values are equal % scaling by 100 is a bit arbitrary... bv = (c2-c1); % Baseline vector from c1 to c2 b = norm(bv); % The distance between the centres % Trap case of baseline of zero length. If r1 == r2 % we have a valid geometric situation, but there are an infinite number of % solutions. Here we simply choose to add r1 in the x direction to c1. if b < eps & abs(r1-r2) < tol i1 = c1 + [r1 0]; i2 = i1; return end bv = bv/b; % Normalise baseline vector. bvp = [-bv(2) bv(1)]; % Vector perpendicular to baseline % Trap the degenerate cases where one of the radii are zero, or nearly zero if r1 < tol & abs(b-r2) < tol i1 = c1; i2 = c1; return; elseif r2 < tol & abs(b-r1) < tol i1 = c2; i2 = c2; return; end % Check triangle inequality if b > (r1+r2) | r1 > (b+r2) | r2 > (b+r1) c1, c2, r1, r2, b error('No solution to circle intersection'); end % Normal solution cosR2 = (b^2 + r1^2 - r2^2)/(2*b*r1); sinR2 = sqrt(1-cosR2^2); if strcmpi(lr,'lr') i1 = c1 + r1*cosR2*bv + r1*sinR2*bvp; % 'left' solution i2 = c1 + r1*cosR2*bv - r1*sinR2*bvp; % and 'right solution elseif strcmpi(lr,'l') i1 = c1 + r1*cosR2*bv + r1*sinR2*bvp; % 'left' solution i2 = []; elseif strcmpi(lr,'r') i1 = c1 + r1*cosR2*bv - r1*sinR2*bvp; % 'right solution i2 = []; else error('illegal left/right solution request'); end
github
jacksky64/imageProcessing-master
undistortimage.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/undistortimage.m
3,670
utf_8
96664f80594b9f7b22b3372441e5f591
% UNDISTORTIMAGE - Removes lens distortion from an image % % Usage: nim = undistortimage(im, f, ppx, ppy, k1, k2, k3, p1, p2) % % Arguments: % im - Image to be corrected. % f - Focal length in terms of pixel units % (focal_length_mm/pixel_size_mm) % ppx, ppy - Principal point location in pixels. % k1, k2, k3 - Radial lens distortion parameters. % p1, p2 - Tangential lens distortion parameters. % % Returns: % nim - Corrected image. % % It is assumed that radial and tangential distortion parameters are % computed/defined with respect to normalised image coordinates corresponding % to an image plane 1 unit from the projection centre. This is why the % focal length is required. % Copyright (c) 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. % October 2010 Original version % November 2010 Bilinear interpolation + corrections % April 2015 Cleaned up and speeded up via use of interp2 % September 2015 Incorporated k3 + tangential distortion parameters function nim = undistortimage(im, f, ppx, ppy, k1, k2, k3, p1, p2) % Strategy: Generate a grid of coordinate values corresponding to an ideal % undistorted image. We then apply the imaging process to these % coordinates, including lens distortion, to obtain the actual distorted % image locations. In this process these distorted image coordinates end up % being stored in a matrix that is indexed via the original ideal, % undistorted coords. Thus for every undistorted pixel location we can % determine the location in the distorted image that we should map the grey % value from. % Start off generating a grid of ideal values in the undistorted image. [rows,cols,chan] = size(im); [xu,yu] = meshgrid(1:cols, 1:rows); % Convert grid values to normalised values with the origin at the principal % point. Dividing pixel coordinates by the focal length (defined in pixels) % gives us normalised coords corresponding to z = 1 x = (xu-ppx)/f; y = (yu-ppy)/f; % Radial lens distortion component r2 = x.^2+y.^2; % Squared normalized radius. dr = k1*r2 + k2*r2.^2 + k3*r2.^3; % Distortion scaling factor. % Tangential distortion component (Beware of different p1,p2 % orderings used in the literature) dtx = 2*p1*x.*y + p2*(r2 + 2*x.^2); dty = p1*(r2 + 2*y.^2) + 2*p2*x.*y; % Apply the radial and tangential distortion components to x and y x = x + dr.*x + dtx; y = y + dr.*y + dty; % Now rescale by f and add the principal point back to get distorted x % and y coordinates xd = x*f + ppx; yd = y*f + ppy; % Interpolate values from distorted image to their ideal locations if ndims(im) == 2 % Greyscale nim = interp2(xu,yu,double(im),xd,yd); else % Colour nim = zeros(size(im)); for n = 1:chan nim(:,:,n) = interp2(xu,yu,double(im(:,:,n)),xd,yd); end end if isa(im, 'uint8') % Cast back to uint8 if needed nim = uint8(nim); end
github
jacksky64/imageProcessing-master
homoTrans.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/homoTrans.m
879
utf_8
bde17d25ed5c319d12d7c6c52fa76ac9
% HOMOTRANS - homogeneous transformation of points % % Function to perform a transformation on homogeneous points/lines % The resulting points are normalised to have a homogeneous scale of 1 % % Usage: % t = homoTrans(P,v); % % Arguments: % P - 3 x 3 or 4 x 4 transformation matrix % v - 3 x n or 4 x n matrix of points/lines % 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 % % April 2000 % September 2007 function t = homotrans(P,v); [dim,npts] = size(v); if ~all(size(P)==dim) error('Transformation matrix and point dimensions do not match'); end t = P*v; % Transform for r = 1:dim-1 % Now normalise t(r,:) = t(r,:)./t(end,:); end t(end,:) = ones(1,npts);
github
jacksky64/imageProcessing-master
imTrans.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/imTrans.m
6,266
utf_8
efdc293e9b12ecbd2485a2d4a360f8f8
% IMTRANS - Homogeneous transformation of an image. % % Applies a geometric transform to an image % % [newim, newT] = imTrans(im, T, region, sze); % % Arguments: % im - The image to be transformed. % T - The 3x3 homogeneous transformation matrix. % region - An optional 4 element vector specifying % [minrow maxrow mincol maxcol] to transform. % This defaults to the whole image if you omit it % or specify it as an empty array []. % sze - An optional desired size of the transformed image % (this is the maximum No of rows or columns). % This defaults to the maximum of the rows and columns % of the original image. % % Returns: % newim - The transformed image. % newT - The transformation matrix that relates transformed image % coordinates to the reference coordinates for use in a % function such as DIGIPLANE. % % The region argument is used when one is inverting a perspective % transformation of a plane and the vanishing line of the plane lies within % the image. Attempts to transform any part of the vanishing line will % position you at infinity. Accordingly one should specify a region that % excludes any part of the vanishing line. % % The sze parameter is optionally used to control the size of the % output image. When inverting a perpective or affine transformation % the scale parameter is unknown/arbitrary, and without specifying % it explicitly the transformed image can end up being very small % or very large. % % Problems: If your transformed image ends up as being two small bits of % image separated by a large black area then the chances are that you have % included the vanishing line of the plane within the specified region to % transform. If your image degenerates to a very thin triangular shape % part of your region is probably very close to the vanishing line of the % plane. % 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. % April 2000 - original version. % July 2001 - transformation of region boundaries corrected. % May 2016 - Minor tidying function [newim, newT] = imTrans(im, T, region, sze); if isa(im,'uint8') im = double(im); % Make sure image is double end % Set up default region and transformed image size values [rows, cols, chan] = size(im); if ~exist('region', 'var') || isempty(region) region = [1 rows 1 cols]; end if ~exist('sze', 'var') || isempty(sze) sze = max([rows, cols]); end if chan == 3 % Transform red, green, blue components separately im = im/255; [r, newT] = transformImage(im(:,:,1), T, region, sze); [g, newT] = transformImage(im(:,:,2), T, region, sze); [b, newT] = transformImage(im(:,:,3), T, region, sze); newim = repmat(uint8(0),[size(r),3]); newim(:,:,1) = uint8(round(r*255)); newim(:,:,2) = uint8(round(g*255)); newim(:,:,3) = uint8(round(b*255)); else % Assume the image is greyscale [newim, newT] = transformImage(im, T, region, sze); end %------------------------------------------------------------ % The internal function that does all the work function [newim, newT] = transformImage(im, T, region, sze); [rows, cols] = size(im); % Cut the image down to the specified region im = im(region(1):region(2), region(3):region(4)); [rows, cols] = size(im); % Find where corners go - this sets the bounds on the final image B = bounds(T,region); nrows = B(2) - B(1); ncols = B(4) - B(3); % Determine any rescaling needed s = sze/max(nrows,ncols); S = [s 0 0 % Scaling matrix 0 s 0 0 0 1]; T = S*T; Tinv = inv(T); % Recalculate the bounds of the new (scaled) image to be generated B = bounds(T,region); nrows = B(2) - B(1); ncols = B(4) - B(3); % Construct a transformation matrix that relates transformed image % coordinates to the reference coordinates for use in a function such as % DIGIPLANE. This transformation is just an inverse of a scaling and % origin shift. newT=inv(S - [0 0 B(3); 0 0 B(1); 0 0 0]); % Set things up for the image transformation. newim = zeros(nrows,ncols); [xi,yi] = meshgrid(1:ncols,1:nrows); % All possible xy coords in the image. % Transform these xy coords to determine where to interpolate values % from. Note we have to work relative to x=B(3) and y=B(1). sxy = homoTrans(Tinv, [xi(:)'+B(3) ; yi(:)'+B(1) ; ones(1,ncols*nrows)]); xi = reshape(sxy(1,:),nrows,ncols); yi = reshape(sxy(2,:),nrows,ncols); [x,y] = meshgrid(1:cols,1:rows); x = x+region(3)-1; % Offset x and y relative to region origin. y = y+region(1)-1; newim = interp2(x,y,double(im),xi,yi); % Interpolate values from source image. %% Plot bounding region %P = [region(3) region(4) region(4) region(3) % region(1) region(1) region(2) region(2) % 1 1 1 1 ]; %B = round(homoTrans(T,P)); %Bx = B(1,:); %By = B(2,:); %Bx = Bx-min(Bx); Bx(5)=Bx(1); %By = By-min(By); By(5)=By(1); %show(newim,2), axis xy %line(Bx,By,'Color',[1 0 0],'LineWidth',2); %% end plot bounding region %--------------------------------------------------------------------- % % Internal function to find where the corners of a region, R % defined by [minrow maxrow mincol maxcol] are transformed to % by transform T and returns the bounds, B in the form % [minrow maxrow mincol maxcol] function B = bounds(T, R) P = [R(3) R(4) R(4) R(3) % homogeneous coords of region corners R(1) R(1) R(2) R(2) 1 1 1 1 ]; PT = round(homoTrans(T,P)); B = [min(PT(2,:)) max(PT(2,:)) min(PT(1,:)) max(PT(1,:))]; % minrow maxrow mincol maxcol
github
jacksky64/imageProcessing-master
affinefundmatrix.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/affinefundmatrix.m
3,219
utf_8
7cbd1c7c427cf3466f0df1c9c57cd131
% AFFINEFUNDMATRIX - computes affine fundamental matrix from 4 or more points % % Function computes the affine fundamental matrix from 4 or more matching % points in a stereo pair of images. The Gold Standard algorithm given % by Hartley and Zisserman p351 (2nd Ed.) is used. % % Usage: [F, e1, e2] = affinefundmatrix(x1, x2) % [F, e1, e2] = affinefundmatrix(x) % % Arguments: % x1, x2 - Two sets of corresponding point. If each set is 3xN % it is assumed that they are homogeneous coordinates. % If they are 2xN it is assumed they are inhomogeneous. % % x - If a single argument is supplied it is assumed that it % is in the form x = [x1; x2] % Returns: % F - The 3x3 fundamental matrix such that x2'*F*x1 = 0. % e1 - The epipole in image 1 such that F*e1 = 0 % e2 - The epipole in image 2 such that F'*e2 = 0 % % 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 % % Feb 2005 function [F,e1,e2] = affinefundmatrix(varargin) [x1, x2, npts] = checkargs(varargin(:)); X = [x2; x1]; % Form vectors of correspondences Xmean = mean(X,2); % Mean deltaX = zeros(size(X)); for k = 1:4 deltaX(k,:) = X(k,:) - Xmean(k); end [U,D,V] = svd(deltaX',0); % Form fundamental matrix from the column of V corresponding to % smallest singular value. v = V(:,4); F = [ 0 0 v(1) 0 0 v(2) v(3) v(4) -v'*Xmean]; % Solve for epipoles [U,D,V] = svd(F,0); e1 = V(:,3); e2 = U(:,3); %-------------------------------------------------------------------------- % Function to check argument values and set defaults function [x1, x2, npts] = checkargs(arg); if length(arg) == 2 x1 = arg{1}; x2 = arg{2}; if ~all(size(x1)==size(x2)) error('x1 and x2 must have the same size'); elseif size(x1,1) == 3 % Convert to inhomogeneous coords x1(1,:) = x1(1,:)./x1(3,:); x1(2,:) = x1(2,:)./x1(3,:); x2(1,:) = x2(1,:)./x2(3,:); x2(2,:) = x2(2,:)./x2(3,:); x1 = x1(1:2,:); x2 = x2(1:2,:); elseif size(x1,1) ~= 2 error('x1 and x2 must be 2xN or 3xN arrays'); end elseif length(arg) == 1 if size(arg{1},1) == 6 x1 = arg{1}(1:3,:); x2 = arg{1}(4:6,:); % Convert to inhomogeneous coords x1(1,:) = x1(1,:)./x1(3,:); x1(2,:) = x1(2,:)./x1(3,:); x2(1,:) = x2(1,:)./x2(3,:); x2(2,:) = x2(2,:)./x2(3,:); x1 = x1(1:2,:); x2 = x2(1:2,:); elseif size(arg{1},1) == 4 x1 = arg{1}(1:2,:); x2 = arg{1}(3:4,:); else error('Single argument x must be 6xN'); end else error('Wrong number of arguments supplied'); end npts = size(x1,2); if npts < 4 error('At least 4 points are needed to compute the affine fundamental matrix'); end
github
jacksky64/imageProcessing-master
ray2raydist.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/ray2raydist.m
1,643
utf_8
eeaa7c5e8fa86f575414560d70b2d3ae
% RAY2RAYDIST Minimum distance between two 3D rays % % Usage: d = ray2raydist(p1, v1, p2, v2) % % Arguments: % p1, p2 - 3D points that lie on rays 1 and 2. % v1, v2 - 3D vectors defining the direction of each ray. % % Returns: % d - The minimum distance between the rays. % % Each ray is defined by a point on the ray and a vector giving the direction % of the ray. Thus a point on ray 1 will be given by p1 + alpha*v1 where % alpha is some scalar. % Peter Kovesi % peterkovesi.com % June 2016 function d = ray2raydist(p1, v1, p2, v2) % Get vector perpendicular to both rays n = cross(v1, v2); n = n(:); nnorm = sqrt(n'*n); % Check if lines are parallel. If so, form a vector perpendicular to v1 % that is within the plane formed by the parallel rays. if nnorm < eps; n = cross(v1, p1-p2); % Vector perpendicular to plane formed by pair % of rays. n = cross(v1, n); % Vector perpendicular to v1 within the plane n = n(:); % formed by the 2 rays. nnorm = sqrt(n'*n); if nnorm < eps d = 0; return end end n = n/nnorm; % Unit vector % The vector joining the two closest points on the rays is: % d*n = p2 + beta*v2 - (p1 + alpha*v1) % for some unknown values of alpha and beta. % % Take dot product of n on both sides % d*n.n = p2.n + beta*v2.n - p1.n - alpha*v1.n % % as n is prependicular to v1 and v2 this reduces to % d = (p2 - p1).n d = abs((p2(:)' - p1(:)')*n);
github
jacksky64/imageProcessing-master
idealimagepts.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/idealimagepts.m
2,834
utf_8
b6897b349d37dd57db0f46ad95c3ade7
% IDEALIMAGEPTS - Ideal image points with no distortion. % % Usage: xyideal = idealimagepts(C, xy) % % Arguments: % C - Camera structure, see CAMSTRUCT for definition. % xy - Image points specified as 2 x N array (x,y) / (col,row) % % Returns: % xyideal - Ideal image points. These points correspond to the image % locations that would be obtained if the camera had no lens % distortion. That is, if they had been projected using an ideal % projection matrix computed from fx, fy, ppx, ppy, skew. % % See also CAMSTRUCT, CAMERAPROJECT, SOLVESTEREOPT % Copyright (c) 2015 Peter Kovesi % pk at peterkovesi com % % 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 2015 Adapted from imagept2plane % February 2016 Refined inversion of distortion process slightly function xyideal = idealimagepts(C, xy) [dim,N] = size(xy); if dim ~= 2 error('Image xy data must be a 2 x N array'); end % Reverse the projection process as used by CAMERAPROJECT % Subtract principal point and divide by focal length to get normalised, % distorted image coordinates. Note skew represents the 2D shearing % coefficient times fx y_d = (xy(2,:) - C.ppy)/C.fy; x_d = (xy(1,:) - C.ppx - y_d*C.skew)/C.fx; % Compute the inverse of the lens distortion effect by computing the % 'forward' direction lens distortion at this point and then subtracting % this from the current point. % Radial distortion factor. Here the squared radius is computed from the % already distorted coordinates. The approximation we are making here is to % assume that the distortion is locally constant. rsqrd = x_d.^2 + y_d.^2; r_d = 1 + C.k1*rsqrd + C.k2*rsqrd.^2 + C.k3*rsqrd^3; % Tangential distortion component, again computed from the already distorted % coords. dtx = 2*C.p1*x_d.*y_d + C.p2*(rsqrd + 2*x_d.^2); dty = C.p1*(rsqrd + 2*y_d.^2) + 2*C.p2*x_d.*y_d; % Subtract the tangential distortion components and divide by the radial % distortion factor to get an approximation of the undistorted normalised % image coordinates (with no skew) x_n = (x_d - dtx)./r_d; y_n = (y_d - dty)./r_d; % Finally project back to pixel coordinates. x_p = C.ppx + x_n*C.fx + y_n*C.skew; y_p = C.ppy + y_n*C.fy; xyideal = [x_p y_p];
github
jacksky64/imageProcessing-master
imTransD.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/imTransD.m
3,965
utf_8
253939b60899cb7418ae8eebee0f8b87
% IMTRANSD - Homogeneous transformation of an image. % % This is a stripped down version of imTrans which does not apply any origin % shifting to the transformed image % % Applies a geometric transform to an image % % newim = imTransD(im, T, sze, lhrh); % % Arguments: % im - The image to be transformed. % T - The 3x3 homogeneous transformation matrix. % sze - 2 element vector specifying the size of the image that the % transformed image is placed into. If you are not sure % where your image is going to 'go' make sze large! (though % this does not help you if the image is placed at a negative % location) % lhrh - String 'lh' or 'rh' indicating whether the transform was % computed assuming columns represent x and rows represent y % (a left handed coordinate system) or if it was computed % using rows as x and columns as y (a right handed system, % albeit rotated 90 degrees). The default is assumed 'lh' % though 'rh' is probably more sensible. % % % Returns: % newim - The transformed image. % % See also: IMTRANS % % 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. % April 2000 - Original version. % April 2010 - Allowance for left hand and right hand coordinate systems. % Offset of 1 pixel that was (incorrectly) applied in % transformImage removed. function newim = imTransD(im, T, sze, lhrh); if ~exist('lhrh','var'), lhrh = 'l'; end if isa(im,'uint8') im = double(im); % Make sure image is double end if lhrh(1) == 'r' % Transpose the image allowing for colour images im = permute(im,[2 1 3]); end threeD = (ndims(im)==3); % A colour image if threeD % Transform red, green, blue components separately im = im/255; r = transformImage(im(:,:,1), T, sze); g = transformImage(im(:,:,2), T, sze); b = transformImage(im(:,:,3), T, sze); newim = repmat(uint8(0),[size(r),3]); newim(:,:,1) = uint8(round(r*255)); newim(:,:,2) = uint8(round(g*255)); newim(:,:,3) = uint8(round(b*255)); else % Assume the image is greyscale newim = transformImage(im, T, sze); end if lhrh(1) == 'r' % Transpose back again newim = permute(newim,[2 1 3]); end %------------------------------------------------------------ % The internal function that does all the work function newim = transformImage(im, T, sze); [rows, cols] = size(im); % Set things up for the image transformation. newim = zeros(rows,cols); [xi,yi] = meshgrid(1:cols,1:rows); % All possible xy coords in the image. % Transform these xy coords to determine where to interpolate values % from. Tinv = inv(T); sxy = homoTrans(Tinv, [xi(:)' ; yi(:)' ; ones(1,cols*rows)]); xi = reshape(sxy(1,:),rows,cols); yi = reshape(sxy(2,:),rows,cols); [x,y] = meshgrid(1:cols,1:rows); % x = x-1; % Offset x and y relative to region origin. % y = y-1; newim = interp2(x,y,im,xi,yi); % Interpolate values from source image. % Place new image into an image of the desired size newim = implace(zeros(sze),newim,0,0);
github
jacksky64/imageProcessing-master
camstruct2projmatrix.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/camstruct2projmatrix.m
1,238
utf_8
59571df196f3b1f2119baf291817faa7
% CAMSTRUCT2PROJMATRIX % % Usage: P = camstruct2projmatrix(C) % % Argument: C - Camera structure. % Returns: P - 3x4 camera projection matrix that maps homogeneous 3D world % coordinates to homogeneous image coordinates. % % Function takes a camera structure and returns its equivalent projection matrix % ignoring lens distortion parameters etc % % See also: CAMSTRUCT, PROJMATRIX2CAMSTRUCT, CAMERAPROJECT % Copyright (c) Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % PK April 2015 function P = camstruct2projmatrix(C) K = [C.fx C.skew C.ppx 0 0 C.fy C.ppy 0 0 0 1 0]; T = [ C.Rc_w -C.Rc_w*C.P 0 0 0 1 ]; P = K*T;
github
jacksky64/imageProcessing-master
hnormalise.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/hnormalise.m
1,010
utf_8
40eeebb3462ab60fb05b133bf0055baf
% HNORMALISE - Normalises array of homogeneous coordinates to a scale of 1 % % Usage: nx = hnormalise(x) % % Argument: % x - an Nxnpts array of homogeneous coordinates. % % Returns: % nx - an Nxnpts array of homogeneous coordinates rescaled so % that the scale values nx(N,:) are all 1. % % Note that any homogeneous coordinates at infinity (having a scale value of % 0) are left unchanged. % Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/~pk % % February 2004 function nx = hnormalise(x) [rows,npts] = size(x); nx = x; % Find the indices of the points that are not at infinity finiteind = find(abs(x(rows,:)) > eps); % if length(finiteind) ~= npts % warning('Some points are at infinity'); % end % Normalise points not at infinity for r = 1:rows-1 nx(r,finiteind) = x(r,finiteind)./x(rows,finiteind); end nx(rows,finiteind) = 1;
github
jacksky64/imageProcessing-master
homography2d.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/homography2d.m
2,963
utf_8
f321f03ac1a2722e93c1c15cf2ec62f2
% HOMOGRAPHY2D - computes 2D homography % % Usage: H = homography2d(x1, x2) % H = homography2d(x) % % Arguments: % x1 - 3xN set of homogeneous points % x2 - 3xN set of homogeneous points such that x1<->x2 % % x - If a single argument is supplied it is assumed that it % is in the form x = [x1; x2] % Returns: % H - the 3x3 homography such that x2 = H*x1 % % This code follows the normalised direct linear transformation % algorithm given by Hartley and Zisserman "Multiple View Geometry in % Computer Vision" p92. % Copyright (c) 2003-2005 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. % May 2003 - Original version. % Feb 2004 - Single argument allowed for to enable use with RANSAC. % Feb 2005 - SVD changed to 'Economy' decomposition (thanks to Paul O'Leary) function H = homography2d(varargin) [x1, x2] = checkargs(varargin(:)); % Attempt to normalise each set of points so that the origin % is at centroid and mean distance from origin is sqrt(2). [x1, T1] = normalise2dpts(x1); [x2, T2] = normalise2dpts(x2); % Note that it may have not been possible to normalise % the points if one was at infinity so the following does not % assume that scale parameter w = 1. Npts = length(x1); A = zeros(3*Npts,9); O = [0 0 0]; for n = 1:Npts X = x1(:,n)'; x = x2(1,n); y = x2(2,n); w = x2(3,n); A(3*n-2,:) = [ O -w*X y*X]; A(3*n-1,:) = [ w*X O -x*X]; A(3*n ,:) = [-y*X x*X O ]; end [U,D,V] = svd(A,0); % 'Economy' decomposition for speed % Extract homography H = reshape(V(:,9),3,3)'; % Denormalise H = T2\H*T1; %-------------------------------------------------------------------------- % Function to check argument values and set defaults function [x1, x2] = checkargs(arg); if length(arg) == 2 x1 = arg{1}; x2 = arg{2}; if ~all(size(x1)==size(x2)) error('x1 and x2 must have the same size'); elseif size(x1,1) ~= 3 error('x1 and x2 must be 3xN'); end elseif length(arg) == 1 if size(arg{1},1) ~= 6 error('Single argument x must be 6xN'); else x1 = arg{1}(1:3,:); x2 = arg{1}(4:6,:); end else error('Wrong number of arguments supplied'); end
github
jacksky64/imageProcessing-master
digiplane.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/digiplane.m
2,368
utf_8
9634b931390f4536b8d7280b8745f6a1
% DIGIPLANE - Digitise and transform points within a planar region in an image. % % This function allows you to digitise points within a planar region of an % image for which an inverse perspective transformation has been previously % determined using, say, INVPERSP. The digitised points are then % transformed into coordinates defined in terms of the reference frame. % % Usage: pts = digiplane(im, T, xyij) % % Arguments: im - Image. % T - Inverse perspective transform. % xyij - An optional string 'xy' or 'ij' indicating what % coordinate system should be used when displaying % the image. % xy - cartesian system with origin at bottom-left. % ij - 'matrix' system with origin at top-left. % An image which has been rectified, say using % imTrans, may want 'xy' set. % % Returns: pts - Nx2 array of transformed (x,y) coordinates. % % See also: invpersp, imTrans % % % Examples of use: % Assuming you have an image `im' for which you have a set of image % points 'impts' and a corresponding set of reference points 'refpts'. % % T = invpersp(refpts, impts); % Compute perspective transformation. % p = digiplane(im,T); % Digitise points in original image. % % ... or work with the rectified image % [newim, newT] = imTrans(im,T); % Rectify image using T from above % p = digiplane(newim,newT); % Digitise points in rectified image. % 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 % % August 2001 function pts = digiplane(im, T, xyij) if nargin < 3 xyij = 'ij'; end pts = []; figure(1), clf, imshow(im), axis(xyij), hold on fprintf('Digitise points in the image with the left mouse button\n'); fprintf('Click any other button to exit\n'); [x,y,but] = ginput(1); while but == 1 p = T*[x;y;1]; % Transform point. xp = p(1)/p(3); yp = p(2)/p(3); pts = [pts; xp yp]; plot(x,y,'r+'); % Mark coordinates on image. text(x+3,y-3,sprintf('[%.1f, %.1f]',xp,yp),'Color',[0 0 1], ... 'FontSize',6); [x,y,but] = ginput(1); % Get next point. end
github
jacksky64/imageProcessing-master
circle.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/circle.m
1,226
utf_8
3ce939f9b481cd974576f40a598a69b6
% CIRCLE - Draws a circle. % % Usage: circle(c, r, n, col) % % Arguments: c - A 2-vector [x y] specifying the centre. % r - The radius. % n - Optional number of sides in the polygonal approximation. % (defualt is 16 sides) % col - optional colour, defaults to blue. % 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. function h = circle(c, r, nsides, col) if nargin == 2 nsides = 16; end if nargin < 4 col = [0 0 1]; end nsides = max(round(nsides),3); % Make sure it is an integer >= 3 a = [0:2*pi/nsides:2*pi]; h = line(r*cos(a)+c(1), r*sin(a)+c(2), 'color', col);
github
jacksky64/imageProcessing-master
makeinhomogeneous.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/makeinhomogeneous.m
791
utf_8
ce76d362845ed0c7eef257d1d0406795
% MAKEINHOMOGENEOUS - Converts homogeneous coords to inhomogeneous coordinates % % Usage: x = makehomogeneous(hx) % % Argument: % hx - an N x npts array of homogeneous coordinates. % % Returns: % x - an (N-1) x npts array of inhomogeneous coordinates % % Warning: If there are any points at infinity (scale = 0) the coordinates % of these points are simply returned minus their scale coordinate. % % See also: MAKEHOMOGENEOUS, HNORMALISE % 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 % % April 2010 function x = makeinhomogeneous(hx) hx = hnormalise(hx); % Normalise to scale of one x = hx(1:end-1,:); % Extract all but the last row
github
jacksky64/imageProcessing-master
equalAngleConstraint.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/equalAngleConstraint.m
1,377
utf_8
ad2156349de0fe1efde5bee65bc38203
% equalAngleConstraint - Affine transform constraints given two equal angles. % % Function calculates centre and radius of the constraint % circle in alpha-beta space generated by having two equal % (but unknown) angles between two pairs of lines in % an affine image % % Usage: [c, r] = equalAngleConstraint(la1, lb1, la2, lb2) % % Where: la1 and lb1 are two lines defined using homogeneous coords that % are separated by an angle that is known to % be the same as the angle between % la2 and lb2 - the other two lines. % c is the 2D coordinate of the centre of the constraint circle. % r is the radius of the centre of the constraint circle. % 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 % % April 2000 % % Equations from Liebowitz and Zisserman function [c, r] = equalAngleConstraint(la1, lb1, la2, lb2) a1 = -1a1(2)/la1(1); % direction of line la1 b1 = -1b1(2)/lb1(1); % direction of line lb1 a2 = -1a2(2)/la2(1); % direction of line la2 b2 = -1b2(2)/lb2(1); % direction of line lb2 c = [(a1*b2 - b1*a2)/(a1 - b1 - a2 + b2), 0]; r = ((a1*b2 - b1*a2)/(a1 - b1 - a2 + b2))^2 ... + ((a1 - b1)*(a1*b1 - a2*b2))/(a1 - b1 - a2 + b2) ... - a1*b1;
github
jacksky64/imageProcessing-master
homogreprojerr.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/homogreprojerr.m
1,423
utf_8
15a06a2d240a29dd5d8a3a1e64268057
% HOMOGREPROJERR % % Computes the symmetric reprojection error for points related by a % homography. % % Usage: % d2 = homogreprojerr(H, x1, x2) % % Arguments: % H - The homography. % x1, x2 - [ndim x npts] arrays of corresponding homogeneous % data points. % % Returns: % d2 - 1 x npts vector of squared reprojection distances for % each corresponding pair of points. % 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. % May 2003 % November 2005 - bug fix (thanks to Scott Blunsden) function d2 = homogreprojerr(H, x1, x2) x2t = H*x1; % Calculate projections of points x1t = H\x2; x1 = hnormalise(x1); % Ensure scale is 1 x2 = hnormalise(x2); x1t = hnormalise(x1t); x2t = hnormalise(x2t); d2 = sum( (x1-x1t).^2 + (x2-x2t).^2) );
github
jacksky64/imageProcessing-master
solvestereopt.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/solvestereopt.m
2,796
utf_8
ab30e670d732d1cd166a798c6abcb100
% SOLVESTEREOPT - Homogeneous linear solution of a stereo point % % Usage: [pt, xy_reproj] = solvestereopt(xy, P) % % Multiview stereo: Solves 3D location of a point given image coordinates of % that point in two, or more, images. % % Arguments: xy - 2xN matrix of x, y image coordinates, one column for % each camera. % C - N element cell array of corresponding image projection % matrices. Or an N element cell array of camera structures % % Returns: pt - 3D location in space returned in normalised % homogeneous coordinates (a 4-vector with last element = 1) % xy_reproj - 2xN matrix of reprojected image coordinates. % % % See also: CORRECTIMAGEPTS, CAMSTRUCT2PROJMATRIX % Copyright (c) 2011-2016 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 2011 % February 2016 Provision for either camera projection matrices or camera % structs function [pt, xy_reproj] = solvestereopt(xy, C) [dim,N] = size(xy); assert(N == length(C)); assert(dim == 2); assert(N >= 2); % Determine if C is a cell array of projection matrices or camera % structures if isstruct(C{1}) % Assume camera structure % Correct image points from each camera so that they correspond to image % points from an ideal camera with no lens distortion. Also generate the % corresponding ideal projection matrices for each camera struct for n = 1:N xy(:,n) = idealimagepts(C{n}, xy(:,n)); P{n} = camstruct2projmatrix(C{n}); end elseif isnumeric(C{1}) % Assume projection matrix P = C; else error('Camera argument must be a camera structure or projection matrix'); end % Build eqn of the form A*pt = 0 A = zeros(2*N, 4); for n = 1:N A(2*n-1,:) = xy(1,n)*P{n}(3,:) - P{n}(1,:); A(2*n ,:) = xy(2,n)*P{n}(3,:) - P{n}(2,:); end [~,~,v] = svd(A); pt = hnormalise(v(:,4)); if nargout == 2 % Project the point back into the source images to determine the residual % error xy_reproj = zeros(size(xy)); for n = 1:N xy_reproj(:,n) = cameraproject(P{n}, pt(1:3)); end end
github
jacksky64/imageProcessing-master
plotcamera.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/plotcamera.m
4,710
utf_8
d5ab74b232b4b16fae65c1dd4a7be3fe
% PLOTCAMERA - Plots graphical representation of camera(s) showing pose % % Usage plotcamera(C, l, col, plotCamPath, fig) % % Arguments: % C - Camera structure (or structure array). % l - The length of the sides of the rectangular cone indicating % the camera's field of view. % col - Optional three element vector specifying the RGB colour to % use. If omitted or empty defaults to blue. % plotCamPath - Optional flag 0/1 to plot line joining camera centre % positions. If omitted or empty defaults to 0. % fig - Optional figure number to be used. % % The function plots into the current figure a graphical representation of one % or more cameras showing their pose. This consists of a rectangular cone, % with its vertex at the camera centre, indicating the camera's field of view. % The camera's coordinate axes are also plotted at the camera centre. % % See also: CAMERASTRUCT % Copyright (c) Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % September 2009 % September 2011 Fixed long standing bug in plotting camera frame. % Allowance for cameras being a structure array. % June 2015 Changes to make compatible with new version of % CAMERASTRUCT. function plotcamera(C, l, col, plotCamPath, fig) if ~exist('col', 'var') || isempty(col) col = [0 0 1]; end if ~exist('plotCamPath', 'var') || isempty(plotCamPath) plotCamPath = 0; end if exist('fig', 'var') figure(fig) end for i = 1:length(C) if C(i).rows == 0 || C(i).cols == 0 warning('Camera rows and cols not specified'); continue end % If only one focal length specified in structure use it for both fx and fy if isfield(C, 'f') f = C.f; elseif isfield(C, 'fx') && isfield(C, 'fy') f = C.fx; % Use fx as the focal length else error('Invalid focal length specification in camera structure'); end if i > 1 & plotCamPath line([C(i-1).P(1) C(i).P(1)],... [C(i-1).P(2) C(i).P(2)],... [C(i-1).P(3) C(i).P(3)]) end % Construct transform from camera coordinates to world coords Tw_c = [C(i).Rc_w' C(i).P 0 0 0 1 ]; % Generate the 4 viewing rays that emanate from the principal point and % pass through the corners of the image. corner{1} = [-C(i).cols/2; -C(i).rows/2; f]; corner{2} = [ C(i).cols/2; -C(i).rows/2; f]; corner{3} = [ C(i).cols/2; C(i).rows/2; f]; corner{4} = [-C(i).cols/2; C(i).rows/2; f]; for n = 1:4 % Scale rays to length l and make homogeneous ray{n} = [corner{n}*l/f; 1]; % Transform to world coords ray{n} = Tw_c*ray{n}; % Draw the ray line([C(i).P(1), ray{n}(1)],... [C(i).P(2), ray{n}(2)],... [C(i).P(3), ray{n}(3)], ... 'color', col); end % Draw rectangle joining ends of rays line([ray{1}(1) ray{2}(1) ray{3}(1) ray{4}(1) ray{1}(1)],... [ray{1}(2) ray{2}(2) ray{3}(2) ray{4}(2) ray{1}(2)],... [ray{1}(3) ray{2}(3) ray{3}(3) ray{4}(3) ray{1}(3)],... 'color', col); % Draw and label axes X = Tw_c(1:3,1)*l + C(i).P; Y = Tw_c(1:3,2)*l + C(i).P; Z = Tw_c(1:3,3)*l + C(i).P; line([C(i).P(1), X(1,1)], [C(i).P(2), X(2,1)], [C(i).P(3), X(3,1)],... 'color', col); line([C(i).P(1), Y(1,1)], [C(i).P(2), Y(2,1)], [C(i).P(3), Y(3,1)],... 'color', col); % line([C(i).P(1), Z(1,1)], [C(i).P(2), Z(2,1)], [C(i).P(3), Z(3,1)],... % 'color', col); text(X(1), X(2), X(3), 'X', 'color', col); text(Y(1), Y(2), Y(3), 'Y', 'color', col); end
github
jacksky64/imageProcessing-master
rq3.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/rq3.m
2,075
utf_8
e3b4214d505526702abed6b2183c76ea
% RQ3 RQ decomposition of 3x3 matrix % % Usage: [R,Q] = rq3(A) % % Argument: A - 3 x 3 matrix % Returns: R - Upper triangular 3 x 3 matrix % Q - 3 x 3 orthonormal rotation matrix % Such that R*Q = A % % The signs of the rows and columns of R and Q are chosen so that the diagonal % elements of R are +ve. % % See also: DECOMPOSECAMERA % Follows algorithm given by Hartley and Zisserman 2nd Ed. A4.1 p 579 % Copyright (c) 2010 Peter Kovesi % Centre for Exploration Targeting % School of Earth and Environment % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % October 2010 % February 2014 Incorporated modifications suggested by Mathias Rothermel to % avoid potential division by zero problems function [R,Q] = rq3(A) if ~all(size(A)==[3 3]) error('A must be 3x3'); end eps = 1e-10; % Find rotation Qx to set A(3,2) to 0 A(3,3) = A(3,3) + eps; c = -A(3,3)/sqrt(A(3,3)^2+A(3,2)^2); s = A(3,2)/sqrt(A(3,3)^2+A(3,2)^2); Qx = [1 0 0; 0 c -s; 0 s c]; R = A*Qx; % Find rotation Qy to set A(3,1) to 0 R(3,3) = R(3,3) + eps; c = R(3,3)/sqrt(R(3,3)^2+R(3,1)^2); s = R(3,1)/sqrt(R(3,3)^2+R(3,1)^2); Qy = [c 0 s; 0 1 0;-s 0 c]; R = R*Qy; % Find rotation Qz to set A(2,1) to 0 R(2,2) = R(2,2) + eps; c = -R(2,2)/sqrt(R(2,2)^2+R(2,1)^2); s = R(2,1)/sqrt(R(2,2)^2+R(2,1)^2); Qz = [c -s 0; s c 0; 0 0 1]; R = R*Qz; Q = Qz'*Qy'*Qx'; % Adjust R and Q so that the diagonal elements of R are +ve for n = 1:3 if R(n,n) < 0 R(:,n) = -R(:,n); Q(n,:) = -Q(n,:); end end
github
jacksky64/imageProcessing-master
cameraproject.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/cameraproject.m
4,913
utf_8
f9fc42724dcaf1f7daedf1d2a3dc0eb1
% CAMERAPROJECT - Projects 3D points into camera image % % Usage: [xy, visible] = cameraproject(C, pt) % % Arguments: % C - Camera structure, see CAMSTRUCT for definition. % Alternatively C can be a 3x4 camera projection matrix. % pt - 3xN matrix of 3D points to project into the image. % % Returns: % xy - 2xN matrix of projected image positions % visible - Array of values 1/0 indicating whether the point is % within the field of view. This is only evaluated if % the camera structure has non zero values for its % 'rows' and 'cols' fields. Otherwise an empty matrix % is returned, an empty matrix is also returned if C % is a 3x4 projection matrix. % % Note the ordering of the tangential distortion parameters p1 and p2 is not % always consistent in the literature. Here they are used in the following % order. % dx = 2*p1*x*y + p2*(r^2 + 2*x^2) % dy = p1*(r^2 + 2*y^2) + 2*p2*x*y % % See also: CAMSTRUCT, CAMSTRUCT2PROJMATRIX, IMAGEPT2PLANE % Copyright (c) 2008-2015 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % PK September 2008 % April 2015 - Refactored from CAMERAPROJECTV for camera structure % which now includes fx, fy. % May 2015 - Simplified by removing R and rotscale and, Tc_w reduced % to a rotation matrix Rc_w, Allow for C to be a % projection matrix as well. % August 2015 - Changes to accommodate k1,k2,k3 radial parameter % and p1,p2 tangential parameter renaming. % December 2015 - Bug fix for k3 when pt represents multiple points. function [xy, visible] = cameraproject(C, pt) [rows, npts] = size(pt); if rows ~= 3 error('Points must be in a 3xN array'); end if ~isstruct(C) && all(size(C) == [3,4]) % C is a projection matrix xy = C*makehomogeneous(pt); xy = makeinhomogeneous(xy); visible = []; return; end % If we get here C is a camera structure and we follow the classical % projection process. % If only one focal length specified in structure use it for both fx and fy if isfield(C, 'f') fx = C.f; fy = C.f; elseif isfield(C, 'fx') && isfield(C, 'fy') fx = C.fx; fy = C.fy; else error('Invalid focal length specification in camera structure'); end if isfield(C, 'skew') % Handle optional skew specfication skew = C.skew; else skew = 0; end % Transformation of a ground point from world coordinates to camera coords % can be thought of as a translation, then rotation as follows % % Gc = Tc_p * Tp_w * Gw % % | . . . | | 1 -x | |Gx| % | Rc_w | | 1 -y | |Gy| % | . . . | | 1 -z | |Gz| % | 1 | | 1 | | 1| % % Subscripts: % w - world frame % p - world frame translated to camera origin % c - camera frame % First translate world frame origin to match camera origin. This is % the Tp_w bit. for n = 1:3 pt(n,:) = pt(n,:) - C.P(n); end % Then rotate to camera frame using Rc_w pt = C.Rc_w*pt; % Follow Bouget's projection process % Generate normalized coords x_n = pt(1,:)./pt(3,:); y_n = pt(2,:)./pt(3,:); rsqrd = x_n.^2 + y_n.^2; % radius squared from centre % Radial distortion factor r_d = 1 + C.k1*rsqrd + C.k2*rsqrd.^2 + C.k3*rsqrd.^3; % Tangential distortion component dtx = 2*C.p1*x_n.*y_n + C.p2*(rsqrd + 2*x_n.^2); dty = C.p1*(rsqrd + 2*y_n.^2) + 2*C.p2*x_n.*y_n; % Obtain lens distorted coordinates x_d = r_d.*x_n + dtx; y_d = r_d.*y_n + dty; % Finally project to pixel coordinates % Note skew represents the 2D shearing coefficient times fx x_p = C.ppx + x_d*fx + y_d*skew; y_p = C.ppy + y_d*fy; xy = [x_p y_p]; % If C.rows and C.cols ~= 0 determine points that are within image bounds if C.rows && C.cols visible = x_p >= 1 & x_p <= C.cols & y_p >= 1 & y_p <= C.rows; else visible = []; end
github
jacksky64/imageProcessing-master
projmatrix2camstruct.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/projmatrix2camstruct.m
1,873
utf_8
81a5a584da00209fcf97254abc68630d
% PROJMATRIX2CAMSTRUCT - Projection matrix to camera structure % % Function takes a projection matrix and returns its equivalent camera % structure. % % Usage: C = projmatrix2camstruct(P, rows, cols) % % Argument: P - 3x4 camera projection matrix that maps homogeneous 3D world % coordinates to homogeneous image coordinates. % rows,cols - Optional specification of number of rows and columns in the % camera image. This can get used later in functions such as % CAMERAPROJECT to determine if projected points are within % image bounds. % % Returns: C - Camera structure. % % See also: CAMSTRUCT2PROJMATRIX, CAMSTRUCT, CAMERAPROJECT % Copyright (c) Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % PK April 2015 % August 2015 Renaming of radial and tangential distortion parameters function C = projmatrix2camstruct(P, rows, cols) if ~exist('rows', 'var') || ~exist('cols', 'var') rows = 0; cols = 0; end [K, Rc_w, Pc, pp, pv] = decomposecamera(P); C = struct('fx', K(1,1), 'fy', K(2,2), ... 'skew', K(1,2), ... 'ppx', pp(1), 'ppy', pp(2), ... 'k1', 0, 'k2', 0, 'k3', 0, 'p1', 0, 'p2', 0, ... 'rows', rows, 'cols', cols, ... 'P', Pc(:), 'Rc_w', Rc_w);
github
jacksky64/imageProcessing-master
camstruct.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/camstruct.m
6,365
utf_8
dcc71aa566e144d95085ce040c320786
% CAMSTRUCT - Construct a camera structure % % Usage: C = camstruct(param_name, value, ... % % Where the parameter names can be as follows with defaults in brackets % % fx - X focal length in pixel units. ([]) % fy - Y focal length in pixel units. ([]) % or f - Focal length in pixel units, the same value is copied to % both fx and fy. ([]) % ppx, ppy - Principal point. (0,0) % k1, k2, k3 - Radial lens distortion parameters. (0,0,0) % p1, p2 - Tangential lens distortion parameters. (0,0) % skew - Camera skew. (0) % rows, cols - Image size. (0,0) % P - 3D location of camera in world coordinates. ([0;0;0]) % Rc_w - 3x3 rotation matrix describing the world relative to the % camera frame. (eye(3)) % % Alternatively P and Rc_w can be replaced with: % Tw_c - 4x4 homogeneous transformation matrix describing camera % position and orientation with respect to world % coordinates. ([]) % % Example: % >> C = camstruct('f', 2000, 'k1', 1.5, 'P', [0;0;2000], 'Rc_w', rotx(pi)); % % Alternatively you can construct a camera structure from a projection % matrix using the parameter name 'PM' % % >> C = camstruct('PM', proj_matrix); % % Returns: C - Camera structure with fields: % fx, fy, ppx, ppy, k1, k2, k3, k4, skew, rows, cols, P, Rc_w % % Note rows and cols, if supplied, are only used to determine if projected % points fall within the image bounds by CAMERAPROJECT. % % Note the ordering of the tangential distortion parameters p1 and p2 is not % always consistent in the literature. Within CAMERAPROJECT they are used in % the following order. % dx = 2*p1*x*y + p2*(r^2 + 2*x^2) % dy = p1*(r^2 + 2*y^2) + 2*p2*x*y % % See also: CAMERAPROJECT, CAMSTRUCT2PROJMATRIX, IMAGEPT2PLANE % Copyright (c) Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % April 2015 % August 2015 Change to 3 radial distortion parameters k1, k2, k3 and two % tangential parameters p1, p2 % January 2016 Allow for Rc_w to be supplied as a 4x4 homogeneous matrix function C = camstruct(varargin) % !! This code is awful, I wish MATLAB was a proper language which allowed you % to specify optional argument values in the function definition and also had % proper constructors for structures/objects, and had multiple dispatch !! % I am moving all my code over to Julia... % Parse the input arguments and set defaults p = inputParser; p.CaseSensitive = false; % Define optional parameter-value pairs and their defaults addParameter(p, 'PM', [], @isnumeric); addParameter(p, 'f', [], @isnumeric); addParameter(p, 'fx', [], @isnumeric); addParameter(p, 'fy', [], @isnumeric); addParameter(p, 'ppx', 0, @isnumeric); addParameter(p, 'ppy', 0, @isnumeric); addParameter(p, 'k1', 0, @isnumeric); addParameter(p, 'k2', 0, @isnumeric); addParameter(p, 'k3', 0, @isnumeric); addParameter(p, 'p1', 0, @isnumeric); addParameter(p, 'p2', 0, @isnumeric); addParameter(p, 'skew', 0, @isnumeric); addParameter(p, 'rows', 0, @isnumeric); addParameter(p, 'cols', 0, @isnumeric); addParameter(p, 'P', [0;0;0], @isnumeric); addParameter(p, 'Rc_w', eye(3), @isnumeric); addParameter(p, 'Tw_c', [], @isnumeric); parse(p, varargin{:}); PM = p.Results.PM; f = p.Results.f; fx = p.Results.fx; fy = p.Results.fy; ppx = p.Results.ppx; ppy = p.Results.ppy; k1 = p.Results.k1; k2 = p.Results.k2; k3 = p.Results.k3; p1 = p.Results.p1; p2 = p.Results.p2; skew = p.Results.skew; rows = p.Results.rows; cols = p.Results.cols; P = p.Results.P(:); Rc_w = p.Results.Rc_w; Tw_c = p.Results.Tw_c; % Handle case when projection matrix is supplied if ~isempty(PM) if ~all(size(PM) == [3,4]) error('Projection matrix must be 3x4'); end C = projmatrix2camstruct(PM); % It is possible, though unlikely, the user wanted to specify some lens % distortion parameters in addition to the projection matrix. C.k1 = k1; C.k2 = k2; C.k3 = k3; C.p1 = p1; C.p2 = p2; return end % Handle case where f is supplied, copy it to fx, fy if ~isempty(f) && isempty(fx) && isempty(fy) fx = f; fy = f; elseif ~isempty(f) && (~isempty(fx) || ~isempty(fy)) error('Cannot specify f and fx or fy'); elseif isempty(fx) || isempty(fy) error('Focal length not defined'); end % Handle case when Tw_c is supplied if ~isempty(Tw_c) P = Tw_c(1:3,4); Rc_w = Tw_c(1:3,1:3)'; elseif ~isempty(Tw_c) && (~isempty(P) || ~isempty(Rc_w)) error('Cannot specify Tw_c and P or Rc_w'); else % Rc_w has been supplied. If it has been supplied as a 4x4 % homogeneous transform just extract the 3x3 rotation component if all(size(Rc_w) == [4,4]) Rc_w = Rc_w(1:3,1:3) end end if ~all(size(P) == [3,1]) error('Camera position must be 3x1 vector'); end if ~all(size(Rc_w) == [3,3]) error('Camera pose must be specified via a 3x3 rotation matrix or 4x4 homogeneous matrix'); end C = struct('fx', fx, 'fy', fy, ... 'ppx', ppx, 'ppy', ppy, ... 'k1', k1, 'k2', k2, 'k3', k3, ... 'p1', p1, 'p2', p2, ... 'skew', skew, ... 'rows', rows, 'cols', cols, ... 'P', P(:), 'Rc_w', Rc_w);
github
jacksky64/imageProcessing-master
knownAngleConstraint.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/knownAngleConstraint.m
929
utf_8
b51714229fca51b80fc72c837575dd25
% knownAngleConstraint - Affine transform constraints given a known angle. % % Function calculates centre and radius of the constraint % circle in alpha-beta space generated by having a known % angle between two lines in an affine image % % Usage: [c, r] = knownAngleConstraint(la, lb, theta) % % Where: la and lb are the two lines defined using homogeneous coords. % theta is the known angle between the lines. % c is the 2D coordinate of the centre of the constraint circle. % r is the radius of the centre of the constraint circle. % Peter Kovesi April 2000 % Department of Computer Science % The University of Western Australia % Equations from Liebowitz and Zisserman function [c, r] = knownAngleConstraint(la, lb, theta) a = -la(2)/la(1); % direction of line la b = -lb(2)/lb(1); % direction of line lb c = [(a+b)/2, (a-b)/2*cot(theta)]; r = abs( (a-b)/(2*sin(theta)) );
github
jacksky64/imageProcessing-master
fundmatrix.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/fundmatrix.m
4,069
utf_8
632e6f9e26790316764a91117aa2adb9
% FUNDMATRIX - computes fundamental matrix from 8 or more points % % Function computes the fundamental matrix from 8 or more matching points in % a stereo pair of images. The normalised 8 point algorithm given by % Hartley and Zisserman p265 is used. To achieve accurate results it is % recommended that 12 or more points are used % % Usage: [F, e1, e2] = fundmatrix(x1, x2) % [F, e1, e2] = fundmatrix(x) % % Arguments: % x1, x2 - Two sets of corresponding 3xN set of homogeneous % points. % % x - If a single argument is supplied it is assumed that it % is in the form x = [x1; x2] % Returns: % F - The 3x3 fundamental matrix such that x2'*F*x1 = 0. % e1 - The epipole in image 1 such that F*e1 = 0 % e2 - The epipole in image 2 such that F'*e2 = 0 % % Copyright (c) 2002-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. % Feb 2002 - Original version. % May 2003 - Tidied up and numerically improved. % Feb 2004 - Single argument allowed to enable use with RANSAC. % Mar 2005 - Epipole calculation added, 'economy' SVD used. % Aug 2005 - Octave compatibility function [F,e1,e2] = fundmatrix(varargin) [x1, x2, npts] = checkargs(varargin(:)); Octave = exist('OCTAVE_VERSION', 'builtin') == 5; % Are we running under Octave % 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. [x1, T1] = normalise2dpts(x1); [x2, T2] = normalise2dpts(x2); % Build the constraint matrix. Note that the line continuations are % required so that we build a matrix with 9 columns (not 3) A = [x2(1,:)'.*x1(1,:)' x2(1,:)'.*x1(2,:)' x2(1,:)' ... x2(2,:)'.*x1(1,:)' x2(2,:)'.*x1(2,:)' x2(2,:)' ... x1(1,:)' x1(2,:)' ones(npts,1) ]; if Octave [U,D,V] = svd(A); % Don't seem to be able to use the economy % decomposition under Octave here else [U,D,V] = svd(A,0); % Under MATLAB use the economy decomposition end % Extract fundamental matrix from the column of V corresponding to % smallest singular value. F = reshape(V(:,9),3,3)'; % Enforce constraint that fundamental matrix has rank 2 by performing % a svd and then reconstructing with the two largest singular values. [U,D,V] = svd(F,0); F = U*diag([D(1,1) D(2,2) 0])*V'; % Denormalise F = T2'*F*T1; if nargout == 3 % Solve for epipoles [U,D,V] = svd(F,0); e1 = hnormalise(V(:,3)); e2 = hnormalise(U(:,3)); end %-------------------------------------------------------------------------- % Function to check argument values and set defaults function [x1, x2, npts] = checkargs(arg); if length(arg) == 2 x1 = arg{1}; x2 = arg{2}; if ~all(size(x1)==size(x2)) error('x1 and x2 must have the same size'); elseif size(x1,1) ~= 3 error('x1 and x2 must be 3xN'); end elseif length(arg) == 1 if size(arg{1},1) ~= 6 error('Single argument x must be 6xN'); else x1 = arg{1}(1:3,:); x2 = arg{1}(4:6,:); end else error('Wrong number of arguments supplied'); end npts = size(x1,2); if npts < 8 error('At least 8 points are needed to compute the fundamental matrix'); end
github
jacksky64/imageProcessing-master
hline.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/hline.m
1,836
utf_8
6b627df996e670c2c7287683e1851639
% HLINE - Plot 2D lines defined in homogeneous coordinates. % % Function for ploting 2D homogeneous lines defined by 2 points % or a line defined by a single homogeneous vector % % Usage: hline(p1,p2) where p1 and p2 are 2D homogeneous points. % hline(p1,p2,'colour_name') 'black' 'red' 'white' etc % hline(l) where l is a line in homogeneous coordinates % hline(l,'colour_name') % % Note that in the case where a homogeneous line is supplied as the argument % the extent of the line drawn depends on the current axis limits. This will % require you to set the desired limits with a call to AXIS prior to calling % this function. % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % April 2000 % October 2013 Corrections to computation of line limits function hline(a, b, c) col = 'blue'; % default colour if nargin >= 2 & isa(a,'double') & isa(b,'double') % Two points specified p1 = a./a(3); % make sure homogeneous points lie in z=1 plane p2 = b./b(3); if nargin == 3 & isa(c,'char') % 2 points and a colour specified col = c; end elseif nargin >= 1 & isa(a,'double') % A single line specified a = a./a(3); % ensure line in z = 1 plane (not needed??) if abs(a(1)) > abs(a(2)) % line is more vertical ylim = get(gca,'Ylim'); p1 = hcross(a, [0 -1 ylim(1)]'); p2 = hcross(a, [0 -1 ylim(2)]'); else % line more horizontal xlim = get(gca,'Xlim'); p1 = hcross(a, [-1 0 xlim(1)]'); p2 = hcross(a, [-1 0 xlim(2)]'); end if nargin == 2 & isa(b,'char') % 1 line vector and a colour specified col = b; end else error('Bad arguments passed to hline'); end line([p1(1) p2(1)], [p1(2) p2(2)], 'color', col);
github
jacksky64/imageProcessing-master
findinverselensdist.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/findinverselensdist.m
3,831
utf_8
043036f753c8840f6f801b5111b368b7
% FINDINVERSELENSDIST - Find inverse radial lens distortion parameters % % Usage: [ik1, ik2, maxerr] = findinverselensdist(k1, k2, rmax, fig) % % Arguments: k1, k2 - Radial lens distortion coeffecients. % rmax - Maximum normalised radius to consider in fitting the % inverse lens distortion function. If omitted this % parameter defaults to 0.43 which roughly corresponds % to the normalized distance to the corner of a 35mm % sensor with a 50mm lens. Use smaller values for % longer lenses as this will improve accuracy. % 50mm lens -> rmax ~0.43 % 100mm lens -> rmax ~0.22 % 200mm lens -> rmax ~0.11 % fig - Optional figure number to plot fitted result to. % % Returns: ik1, ik2 - Radial lens distortion coefficients that attempt to % invert the distortion. % maxerr - Maximum error between corrected radius and ideal % radius reprted in normalised radius units. % % Given the distortion model as a function of radius from the principal point % % rd = r*(1 + k1*r^2 + k2*r^4) % % where r is the undistorted normalised radius and rd is the distorted radius. % Rather than try to solve for the inverse of this 5th order polynomial this % function numerically fits a function of the same form, but with new % coefficients for k1 and k2, that attempts to recover r from the distorted % values in rd. % % r = rd*(1 + ik1*rd^2 + ik2*rd^4) % % Thus r will not be exact, however the approximation is typically very good. % The maximum error is reported back as maxerr. The ratio of maxerr to rmax % is probably what you should be concerned with. % % Note the normalised image radius corresponds to the radius on an image plane % with a focal length of 1. % % See also: CAMERAPROJECT, IMAGEPT2PLANE % Copyright (c) 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. % October 2010 function [ik1, ik2, maxerr] = findinverselensdist(k1, k2, rmax, fig) % Set up the range of radius values to fit the inverse function to. if ~exist('rmax', 'var'), rmax = 0.43; end r = [0:rmax/100:rmax]'; d = 1.0 + k1*r.^2 + k2*r.^4; % Distortion factor rd = r.*d; % Distorted radius % Least squares solution to the inverse transform ik = [rd.^3 rd.^5]\(r-rd); ik1 = ik(1); ik2 = ik(2); % Check results. Correct the distorted radius values and see how close % the corrected values are to the ideal ones rc = rd.*(1.0 + ik1*rd.^2 + ik2*rd.^4); % Corrected radius values maxerr = max(abs(r-rc)); if exist('fig', 'var') % Produce diagnostic plots figure(fig), clf subplot(2,1,1) plot(r, r, r, rc, r, rd) title('Distorted vs corrected radius') xlabel('Normalised radius'); legend('Ideal radius', 'Corrected radius', 'Distorted radius', ... 'Location', 'NorthWest' ) subplot(2,1,2) plot(r,(r-rc)) title('Error between corrected radius and ideal radius') xlabel('Normalised radius'); end
github
jacksky64/imageProcessing-master
homography1d.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/homography1d.m
2,662
utf_8
bf1d84269964988e4400e66cabf14617
% HOMOGRAPHY1D - computes 1D homography % % Usage: H = homography1d(x1, x2) % % Arguments: % x1 - 2xN set of homogeneous points % x2 - 2xN set of homogeneous points such that x1<->x2 % Returns: % H - the 2x2 homography such that x2 = H*x1 % % This code is modelled after the normalised direct linear transformation % algorithm for the 2D homography given by Hartley and Zisserman p92. % % 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 % % May 2003 function H = homography1d(x1, x2) % check matrix sizes if ~all(size(x1) == size(x2)) error('x1 and x2 must have same dimensions'); end % Attempt to normalise each set of points so that the origin % is at centroid and mean distance from origin is 1. [x1, T1] = normalise1dpts(x1); [x2, T2] = normalise1dpts(x2); % Note that it may have not been possible to normalise % the points if one was at infinity so the following does not % assume that scale parameter w = 1. Npts = length(x1); A = zeros(2*Npts,4); for n = 1:Npts X = x1(:,n)'; x = x2(1,n); w = x2(2,n); A(n,:) = [-w*X x*X]; end [U,D,V] = svd(A); % Extract homography H = reshape(V(:,4),2,2)'; % Denormalise H = T2\H*T1; % Report error in fitting homography... % NORMALISE1DPTS - normalises 1D homogeneous points % % Function translates and normalises a set of 1D homogeneous points % so that their centroid is at the origin and their mean distance from % the origin is 1. % % Usage: [newpts, T] = normalise1dpts(pts) % % Argument: % pts - 2xN array of 2D homogeneous coordinates % % Returns: % newpts - 2xN array of transformed 1D homogeneous coordinates % T - The 2x2 transformation matrix, newpts = T*pts % % Note that if one of the points is at infinity no normalisation % is possible. In this case a warning is printed and pts is % returned as newpts and T is the identity matrix. function [newpts, T] = normalise1dpts(pts) if ~all(pts(2,:)) warning('Attempt to normalise a point at infinity') newpts = pts; T = eye(2); return; end % Ensure homogeneous coords have scale of 1 pts(1,:) = pts(1,:)./pts(2,:); c = mean(pts(1,:)')'; % Centroid. newp = pts(1,:)-c; % Shift origin to centroid. meandist = mean(abs(newp)); scale = 1/meandist; T = [scale -scale*c 0 1 ]; newpts = T*pts;
github
jacksky64/imageProcessing-master
decomposecamera.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/decomposecamera.m
3,310
utf_8
bd4b36c6cb0956aae39430857afe8750
% DECOMPOSECAMERA Decomposition of a camera projection matrix % % Usage: [K, Rc_w, Pc, pp, pv] = decomposecamera(P); % % P is decomposed into the form P = K*[R -R*Pc] % % Argument: P - 3 x 4 camera projection matrix % Returns: % K - Calibration matrix of the form % | ax s ppx | % | 0 ay ppy | % | 0 0 1 | % % Where: % ax = f/pixel_width and ay = f/pixel_height, % ppx and ppy define the principal point in pixels, % s is the camera skew. % Rc_w - 3 x 3 rotation matrix defining the world coordinate frame % in terms of the camera frame. Columns of R transposed define % the directions of the camera X, Y and Z axes in world % coordinates. % Pc - Camera centre position in world coordinates. % pp - Image principal point. % pv - Principal vector from the camera centre C through pp % pointing out from the camera. This may not be the same as % R'(:,3) if the principal point is not at the centre of the % image, but it should be similar. % % See also: RQ3 % Reference: Hartley and Zisserman 2nd Ed. pp 155-164 % Copyright (c) 2010 Peter Kovesi % Centre for Exploration Targeting % School of Earth and Environment % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % October 2010 Original version % November 2013 Description of rotation matrix R corrected (transposed) function [K, Rc_w, Pc, pp, pv] = decomposecamera(P) % Projection matrix from Hartley and Zisserman p 163 used for testing if ~exist('P','var') P = [ 3.53553e+2 3.39645e+2 2.77744e+2 -1.44946e+6 -1.03528e+2 2.33212e+1 4.59607e+2 -6.32525e+5 7.07107e-1 -3.53553e-1 6.12372e-1 -9.18559e+2]; end % Convenience variables for the columns of P p1 = P(:,1); p2 = P(:,2); p3 = P(:,3); p4 = P(:,4); M = [p1 p2 p3]; m3 = M(3,:)'; % Camera centre, analytic solution X = det([p2 p3 p4]); Y = -det([p1 p3 p4]); Z = det([p1 p2 p4]); T = -det([p1 p2 p3]); Pc = [X;Y;Z;T]; Pc = Pc/Pc(4); Pc = Pc(1:3); % Make inhomogeneous % Pc = null(P,'r'); % numerical way of computing C % Principal point pp = M*m3; pp = pp/pp(3); pp = pp(1:2); % Make inhomogeneous % Principal ray pointing out of camera pv = det(M)*m3; pv = pv/norm(pv); % Perform RQ decomposition of M matrix. Note that rq3 returns K with +ve % diagonal elements, as required for the calibration matrix. [K Rc_w] = rq3(M); % Check that R is right handed, if not give warning if dot(cross(Rc_w(:,1), Rc_w(:,2)), Rc_w(:,3)) < 0 warning('Note that rotation matrix is left handed'); end
github
jacksky64/imageProcessing-master
normalise2dpts.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/normalise2dpts.m
2,361
utf_8
2b9d94a3681186006a3fd47a45faf939
% NORMALISE2DPTS - normalises 2D homogeneous points % % Function translates and normalises a set of 2D homogeneous points % so that their centroid is at the origin and their mean distance from % the origin is sqrt(2). This process typically improves the % conditioning of any equations used to solve homographies, fundamental % matrices etc. % % Usage: [newpts, T] = normalise2dpts(pts) % % Argument: % pts - 3xN array of 2D homogeneous coordinates % % Returns: % newpts - 3xN array of transformed 2D homogeneous coordinates. The % scaling parameter is normalised to 1 unless the point is at % infinity. % T - The 3x3 transformation matrix, newpts = T*pts % % If there are some points at infinity the normalisation transform % is calculated using just the finite points. Being a scaling and % translating transform this will not affect the points at infinity. % 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 % % May 2003 - Original version % February 2004 - Modified to deal with points at infinity. % December 2008 - meandist calculation modified to work with Octave 3.0.1 % (thanks to Ron Parr) function [newpts, T] = normalise2dpts(pts) if size(pts,1) ~= 3 error('pts must be 3xN'); end % Find the indices of the points that are not at infinity finiteind = find(abs(pts(3,:)) > eps); if length(finiteind) ~= size(pts,2) warning('Some points are at infinity'); end % For the finite points ensure homogeneous coords have scale of 1 pts(1,finiteind) = pts(1,finiteind)./pts(3,finiteind); pts(2,finiteind) = pts(2,finiteind)./pts(3,finiteind); pts(3,finiteind) = 1; c = mean(pts(1:2,finiteind)')'; % Centroid of finite points newp(1,finiteind) = pts(1,finiteind)-c(1); % Shift origin to centroid. newp(2,finiteind) = pts(2,finiteind)-c(2); dist = sqrt(newp(1,finiteind).^2 + newp(2,finiteind).^2); meandist = mean(dist(:)); % Ensure dist is a column vector for Octave 3.0.1 scale = sqrt(2)/meandist; T = [scale 0 -scale*c(1) 0 scale -scale*c(2) 0 0 1 ]; newpts = T*pts;
github
jacksky64/imageProcessing-master
hcross.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Projective/hcross.m
919
utf_8
dbb3f3d4ef79e25ca3000ea976409e0c
% HCROSS - Homogeneous cross product, result normalised to s = 1. % % Function to form cross product between two points, or lines, % in homogeneous coodinates. The result is normalised to lie % in the scale = 1 plane. % % Usage: c = hcross(a,b) % % 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. % April 2000 function c = hcross(a,b) c = cross(a,b); c = c/c(3);
github
jacksky64/imageProcessing-master
upwardcontinue.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Geosci/upwardcontinue.m
3,839
utf_8
a7a1d8416166d9c658b7a7d4bac8770b
% UPWARDCONTINUE Upward continuation for magnetic or gravity potential field data % % Usage: [up, psf] = upwardcontinue(im, h, dx, dy) % % Arguments: im - Input potential field image % h - Height to upward continue to (+ve) % dx, dy - Grid spacing in x and y. The upward continuation height % is computed relative to the grid spacing. If omitted dx = % dy = 1, that is, the value of h is in grid spacing units. % If dy is omitted it is assumed dy = dx. % % Returns: up - The upward continued field image % psf - The point spread function corresponding to the upward % continuation height. % % Upward continuation filtering is done in the frequency domain whereby the % Fourier transform of the upward continued image F(Up) is obtained from the % Fourier transform of the input image F(U) using % F(Up) = e^(-2*pi*h * sqrt(u^2 + v^2)) * F(U) % where u and v are the spatial frequencies over the input grid. % % To minimise edge effect problems Moisan's Periodic FFT is used. This avoids % the need for data tapering. % % References: % Richard Blakely, "Potential Theory in Gravity and Magnetic Applications" % Cambridge University Press, 1996, pp 315-319 % % L. Moisan, "Periodic plus Smooth Image Decomposition", Journal of % Mathematical Imaging and Vision, vol 39:2, pp. 161-179, 2011. % % See also: PERFFT2 % Copyright (c) Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % % June 2012 - Original version. % June 2014 - Tidied up and documented. % August 2014 - Smooth, non periodic component of orginal image added back to % filtered result so that calculation of residual against the % original image is facilitated. function [up, psf] = upwardcontinue(im, h, dx, dy) if ~exist('dx', 'var'), dx = 1; end if ~exist('dy', 'var'), dy = dx; end [rows,cols,chan] = size(im); assert(chan == 1, 'Image must be single channel'); mask = ~isnan(im); % Use Periodic FFT rather than data tapering to minimise edge effects. % Save the smooth, non periodic component of the image to add back into % the final filtered result. [IM, ~, ~, sm] = perfft2(fillnan(im)); % Generate horizontal and vertical frequency grids that vary from % -0.5 to 0.5 [u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ... ([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2))); % Quadrant shift to put 0 frequency at the corners. Also, divide by grid % size to get correct spatial frequencies u1 = ifftshift(u1)/dx; u2 = ifftshift(u2)/dy; freq = sqrt(u1.^2 + u2.^2); % Matrix values contain spatial frequency % values as a radius from centre (but % quadrant shifted) % Continuation filter in the frequency domain W = exp(-2*pi*h*freq); % Apply filter to obtain upward continuation, add smooth component of % image back in and apply mask to remove NaN values up = (real(ifft2(IM.*W)) + sm) .* double(mask); % Reconstruct the spatial representation of the point spread function % corresponding to the upward continuation height psf = real(fftshift(ifft2(W)));
github
jacksky64/imageProcessing-master
tiltderiv.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Geosci/tiltderiv.m
1,298
utf_8
ef5a552157a3f7a9282a06162331419d
% TILTDERIV Tilt derivative of potential field data % % Usage: td = tiltderiv(im) % % Arguments: im - Input potential field image. % % Returns: td - The tilt derivative. % % % Reference: % Hugh G. Miller and Vijay Singh. Potential field tilt - a new concept for % location of potential field sources. Applied Geophysics (32) 1994. pp % 213-217. % % See also: VERTDERIV % Copyright (c) Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % % March 2015 function td = tiltderiv(im) [rows,cols,chan] = size(im); assert(chan == 1, 'Image must be single channel'); % Use Farid and Simoncelli's 5-tap derivative filters to get the horizontal % gradient [gx, gy] = derivative5(im, 'x', 'y'); gz = vertderiv(im, 1); td = atan(gz./sqrt(gx.^2 + gy.^2));
github
jacksky64/imageProcessing-master
orientationfilter.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Geosci/orientationfilter.m
6,042
utf_8
9e5fa0a05cdc4d0f3b48c2710e4e91f4
% ORIENTATIONFILTER Generate orientation selective filterings of an image % % Usage: oim = orientationfilter(im, norient, angoverlap, boost, cutoff, histcut) % % Arguments: im - Image to be filtered. % norient - Number of orientations, try 8. % angoverlap - Angular bandwidth overlap factor. A value of 1 gives a % minimum overlap between adjacent filter orientations % while still providing full coverage of the spectrum. % However, it is often useful to provide greater overlap % between adjacent filter orientations, especially if the % output is to be viewed using the CYCLEMIX image % blender. This gives smoother transitions between % images. Try values 1.5 to 2.0 % boost - The ratio that high frequency values are boosted % (or supressed) relative to the low frequency values. % Try values in the range 2 - 4 to start with. Use a % value of 1 for no boost. % cutoff - Cutoff frequency of the highboost filter 0 - 0.5, try 0.2 % histcut - Percentage of the histogram extremes to truncate. This % is useful in preventing outlying values in the data % from dominating in the image rescaling for display. Try % a small amount, say, 0.01% % % Returns: oim - Cell array of length 'norient' containing the % orientation filtered images. % % % This function is designed to help identify oriented structures within an image % by applying orientation selective filters. If one is looking for lineaments % it is typically useful to boost the high frequency components in the image as % well, hence the combination of the two filters % % Example: Generate 8 orientation filterings of an image with an angular % bandwidth overlap factor of 1.5 and amplifying spatial frequencies greater % than 0.1 (wavelenths < 10 pixels) by a factor of 2. Also truncate the image % histograms so that 0.01% of image pixels are saturated. This helps ensure % that outlying data values do not dominate when the image is scaled for % display. % % >> oim = orienationfilter(im, 8, 1.5, 2, 0.1, 0.01); % % An effective way to view all the output images is to use the cyclic image % blending tool CYCLEMIX.m % % >> cyclemix(oim); % % Note that the cyclemix control wheel varies from 0 - 2pi and these angles are % mapped to the orientation filtered images which vary from 0 - pi in angle. % This makes the interface a bit counterintuitive to use. To get around this % one can replicate the the cell array of orientation filtered images giving an % array that corresponds to the angles 0 - pi, 0 - pi. When this is passed to % cyclemix you get a much more intuitive interface % % >> cyclemix({oim{:} oim{:}}) % % See also: CYCLEMIX, HIGHBOOSTFILTER, HISTTRUNCATE % 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. % August 2012 Original version % July 2014 Revised to incorporate highboost filtering and histogram truncation function oim = orientationfilter(im, norient, angoverlap, boost, cutoff, histcut) IM = fft2(im); [rows,cols] = size(im); if ~exist('angoverlap','var') angScale = norient/2; else angScale = norient/2 / angoverlap; end % If a highboost filter has been specified apply it to the fourier % transform of the image. if exist('cutoff', 'var') IM = IM .* highboostfilter([rows,cols], cutoff, 1, boost); end if ~exist('histcut','var'), histcut = 0; end % Construct frequency domain filter matrices [ ~ , u1, u2] = filtergrid(rows,cols); theta = atan2(-u2,u1); % Matrix values contain polar angle. % (note -ve y is used to give +ve % anti-clockwise angles) sintheta = sin(theta); costheta = cos(theta); for o = 1:norient % For each orientation... 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*angScale,pi); % The orientation filter haa a cosine cross section in the frequency domain % 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; spread = spread + fliplr(flipud(spread)); % show(fftshift(spread),o); % Apply orientation filter oim{o} = real(ifft2(IM.*spread)); % Truncate extremes of image histogram if histcut oim{o} = histtruncate(oim{o}, histcut, histcut); end end
github
jacksky64/imageProcessing-master
relief.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Geosci/relief.m
5,218
utf_8
8f99e38c832592297aa91384d12779a2
% RELIEF Generates relief shaded image % % Usage: shadeim = relief(im, azimuth, elevation, dx, rgbim) % % Arguments: im - Image/heightmap to be relief shaded. % azimuth - Of light direction in degrees. Zero azimuth points % upwards and increases clockwise. Defaults to 45. % elevation - Of light direction in degrees. Defaults to 45. % gradscale - Scaling to apply to the surface gradients. If the shading % is excessive decrease the scaling. Try successive doubling % or halving to find a good value. % rgbim - Optional RGB image to which the shading pattern derived % from 'im' is applied. Alternatively, rgbim can be a Nx3 % RGB colourmap which is applied to the input % image/heightmap in order to obtain a RGB image to which % the shading pattern is applied. % % This function generates a relief shaded image. For interactive relief % shading use IRELIEF. IRELIEF reports the azimuth, elevation and gradient % scaling values that can then be reused on this function. % % Lambertian shading is used to form the relief image. This obtained from the % cosine of the angle between the surface normal and light direction. Note that % shadows are ignored. Thus a small feature that might otherwise be in the % shadow of a nearby large structure is rendered as if the large feature was not % there. % % See also: IRELIEF, 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. % April 2014 function shadeim = relief(im, az, el, gradscale, rgbim) [rows, cols, chan] = size(im); assert(chan==1) if ~exist('az', 'var'), az = 45; end if ~exist('el', 'var'), el = 45; end if ~exist('gradscale', 'var'), gradscale = 1; end if exist('rgbim', 'var') [rr, cc, ch] = size(rgbim); if cc == 3 && ch == 1 % Assume this is a colourmap that is to be % applied to the image/heightmap rgbim = applycolourmap(im, rgbim); elseif ~isempty(rgbim) % Check its size if rows ~= rr || cols ~= cc || ch ~= 3 error('Sizes of im and rgbim are not compatible'); end end else % No image supplied rgbim = []; end % Obtain surface normals of im loggrad = 'lin'; [n1, n2, n3] = surfacenormals(im, gradscale, loggrad); % Convert azimuth and elevation to a lighting direction vector. Note that % the vector is constructed so that an azimuth of 0 points upwards and % increases clockwise. az = az/180*pi; el = el/180*pi; I = [cos(el)*sin(az), cos(el)*cos(az), sin(el)]; I = I./norm(I); % Ensure I is a unit vector % Generate Lambertian shading via the dot product between surface normals % and the light direction. Note that the product with n2 is negated to % account for the image +ve y increasing downwards. shading = I(1)*n1 - I(2)*n2 + I(3)*n3; % Remove -ve shading values which are generated by surface normals pointing % away from the light source. shading(shading < 0) = 0; % If no RGB image has been supplied just return the raw shading image if isempty(rgbim) shadeim = shading; else % Apply shading to the RGB image supplied shadeim = zeros(size(rgbim)); for n = 1:3 shadeim(:,:,n) = rgbim(:,:,n).*shading; end end % ** Resolve issue with RGB image being double or uint8 %--------------------------------------------------------------------------- % Compute image/heightmap surface normals function [n1, n2, n3] = surfacenormals(im, gradscale, loggrad) % Compute partial derivatives of z. % p = dz/dx, q = dz/dy [p,q] = gradient(im); p = p*gradscale; q = q*gradscale; % If specified take logs of gradient. % Note that taking the log of the surface gradients will produce a surface % that is not integrable (probably only of theoretical interest) if strcmpi(loggrad, 'log') p = sign(p).*log1p(abs(p)); q = sign(q).*log1p(abs(q)); elseif strcmpi(loggrad, 'loglog') p = sign(p).*log1p(log1p(abs(p))); q = sign(q).*log1p(log1p(abs(q))); elseif strcmpi(loggrad, 'logloglog') p = sign(p).*log1p(log1p(log1p(abs(p)))); q = sign(q).*log1p(log1p(log1p(abs(q)))); end % Generate surface unit normal vectors. Components stored in n1, n2 % and n3 mag = sqrt(1 + p.^2 + q.^2); n1 = -p./mag; n2 = -q./mag; n3 = 1./mag;
github
jacksky64/imageProcessing-master
irelief.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Geosci/irelief.m
13,089
utf_8
64ddae94f44fb4a9df10a6065b3753fe
% IRELIEF Interactive Relief Shading % % Usage: irelief(im, rgbim, figNo) % % Arguments: im - Image/heightmap to be relief shaded % rgbim - Optional RGB image to which the shading pattern derived % from 'im' is applied. Alternatively, rgbim can be a Nx3 % RGB colourmap which is applied to the input % image/heightmap in order to obtain a RGB image to which % the shading pattern is applied. % figNo - Optional figure window number to use. % % This function provides an interactive relief shading image % % Click in the image to toggle in/out of interactive relief shading mode. The % location of the click defines a reference point which is indicated by a % surrounding circle. Positioning the cursor at the centre of the circle % corresponds to the sun being placed directly overhead. Moving it radially % outwards reduces the sun's elevation and moving it around the circle % corresponds to changing the sun's azimuth. The intended use is that you would % click on a feature of interest within an image and then move the sun around % with respect to that feature to illuminate it from various directions. % % Lambertian shading is used to form the relief image. This is the cosine of % the angle between the surface normal and light direction. Note that shadows % are ignored. Thus a small feature that might otherwise be in the shadow of a % nearby large structure is rendered as if the large feature was not there. % % Note that the scale of the surface gradient of the input image is arbitrary, % indeed it is likely to be of mixed units. However, the gradient scale has a % big effect on the resulting image display. Initially the gradient is scaled % to achieve a median value of 0.25. Using the up and down arrow keys the % user can successively double or halve the gradient values to obtain a % pleasing result. % % A note on colourmaps: It is strongly suggested that you use a constant % lightness colourmap, or low contrast colourmap, to construct the image to % which the shading is applied. The reason for this is that the perception of % features within the data is provided by the relief shading. If the colourmap % itself has a wide range of lightness values within its colours then these will % induce an independent shading pattern that will interfere with the relief % shading. Thus, the use of a map having colours of uniform lightness ensures % that they do not interfere with the perception of features induced by the % relief shading. % % See also: RELIEF, 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. % April 2014 function irelief(im, rgbim, figNo) [rows, cols, chan] = size(im); assert(chan==1) im = double(im); % Ensure double if exist('rgbim', 'var') [rr, cc, ch] = size(rgbim); if cc == 3 && ch == 1 % Assume this is a colourmap that is to be % applied to the image/heightmap rgbim = applycolourmap(im, rgbim); elseif ~isempty(rgbim) % Check its size if rows ~= rr || cols ~= cc || ch ~= 3 error('Sizes of im and rgbim are not compatible'); end end shrgbim = zeros(rows,cols,3); % Allocate space for shaded image else % No image supplied rgbim = []; end % Compute a gradient scaling to give initial median gradient of 0.25 gradscale = initialgradscale; loggrad = 'linear'; % Max radius value for normalising radius values when determining % elevation and azimuth maxRadius = min(rows/6,cols/6); fprintf('\nClick in the image to toggle in/out of relief rendering mode. \n\n'); fprintf(['The clicked location is the reference point for specifying the' ... ' sun direction. \n']); fprintf('Move the cursor with respect to this point to change the illumination.\n\n'); fprintf('Use up and down arrow keys to increase/decrease surface gradients.\n\n'); if exist('figNo','var') fig = figure(figNo); clf else fig = figure; end % precompute surface normals [n1, n2, n3] = surfacenormals(im, gradscale, loggrad); % Generate an initial dummy image to display and obtain its handle S = warning('off'); imHandle = imshow(ones(rows,cols), 'border', 'tight'); ah = get(fig,'CurrentAxes'); if isempty(rgbim) % Use a slightly reduced contrast grey colourmap colormap(gray(256)); % colormap(cmap('REDUCEDGREY')); end % Set initial reference point to the centre of the image and draw a % circle around this point. xo = cols/2; yo = rows/2; [xd, yd] = circlexy([xo, yo], maxRadius); ho = line(xd, yd, 'Color', [.8 .8 .8]); set(ho,'Visible', 'off'); % Set up button down callback and window title set(fig, 'WindowButtonDownFcn', @wbdcb); set(fig, 'KeyReleaseFcn', @keyreleasecb); set(fig, 'NumberTitle', 'off') set(fig, 'name', 'CET Interactive Relief Shading Tool') set(fig, 'Menubar','none'); % Text area to display current azimuth, elevation, gradscale values texth = text(50, 50,'', 'color', [1 1 1], 'FontSize', 20); % Generate initial image display. relief(xo+maxRadius, yo-maxRadius); drawnow warning(S) blending = 0; % Set up custom pointer myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)]; myPointer(~myPointer) = NaN; hold on %----------------------------------------------------------------------- % Window button down callback function wbdcb(src,evnt) if strcmp(get(src,'SelectionType'),'normal') if ~blending % Turn blending on blending = 1; set(ho,'Visible', 'on'); set(src,'Pointer','custom', 'PointerShapeCData', myPointer,... 'PointerShapeHotSpot',[9 9]) set(src,'WindowButtonMotionFcn',@wbmcb) % Reset reference point to the click location cp = get(ah,'CurrentPoint'); xo = cp(1,1); yo = cp(1,2); [xd, yd] = circlexy([xo, yo], maxRadius); set(ho,'XData', xd); set(ho,'YData', yd); else % Turn blending off blending = 0; set(ho,'Visible', 'off'); set(src,'Pointer','arrow') set(src,'WindowButtonMotionFcn','') % For paper illustration (need marker size of 95 if using export_fig) cp = get(ah,'CurrentPoint'); x = cp(1,1); y = cp(1,2); end % Right-clicks while blending also reset the origin for determining elevation and azimuth elseif blending && strcmp(get(src,'SelectionType'),'alt') cp = get(ah,'CurrentPoint'); xo = cp(1,1); yo = cp(1,2); [xd, yd] = circlexy([xo, yo], maxRadius); set(ho,'XData', xd); set(ho,'YData', yd); wbmcb(src,evnt); % update the display end end %----------------------------------------------------------------------- % Window button move call back function wbmcb(src,evnt) cp = get(ah,'CurrentPoint'); x = cp(1,1); y = cp(1,2); relief(x, y); end %----------------------------------------------------------------------- % Key Release callback % If '+' or up is pressed the gradients in the image are doubled % '-' or down halves the gradients function keyreleasecb(src,evnt) if evnt.Character == '+' | evnt.Character == 30 gradscale = gradscale*2; [n1, n2, n3] = surfacenormals(im, gradscale, loggrad); elseif evnt.Character == '-' | evnt.Character == 31 gradscale = gradscale/2; [n1, n2, n3] = surfacenormals(im, gradscale, loggrad); elseif evnt.Character == 'l' if strcmp(loggrad, 'linear') loggrad = 'log'; fprintf('Using log of gradients\n'); elseif strcmp(loggrad, 'log') loggrad = 'loglog'; fprintf('Using log of log of gradients\n'); elseif strcmp(loggrad, 'loglog') loggrad = 'logloglog'; fprintf('Using log log log gradients\n'); elseif strcmp(loggrad, 'logloglog') loggrad = 'linear'; fprintf('Using raw data gradients\n'); end [n1, n2, n3] = surfacenormals(im, gradscale, loggrad); end wbmcb(src,evnt); % update the display end %----------------------------------------------------------------------- function relief(x, y) % Clamp x and y to image limits x = max(0,x); x = min(cols,x); y = max(0,y); y = min(rows,y); % Convert to polar coordinates with respect to reference point xp = x - xo; yp = y - yo; radius = sqrt(xp.^2 + yp.^2); % Compute azimuth. We want 0 azimuth pointing up increasing % clockwise. Hence yp must be negaated becasuse +ve y points down in the % image, pi/2 must be subtracted to shift 0 from east to north, and the % overall result must be negated to make angles +ve clockwise (yuk). azimuth = -(atan2(-yp, xp) - pi/2); % Convert radius to normalised coords with respect to image size a radius = radius/maxRadius; radius = min(radius,1); % Convert azimuth and elevation to a light direction. Note that % the vector is constructed so that an azimuth of 0 points upwards and % increases clockwise. elevation = pi/2 - radius*2*pi/8; I = [cos(elevation)*sin(azimuth), cos(elevation)*cos(azimuth), sin(elevation)]; I = I./norm(I); % Ensure I is a unit vector % Display light direction and current gradscale value set(texth, 'String', sprintf('Az: %d El: %d Gs: %.2f', ... round(azimuth/pi*180), round(elevation/pi*180), gradscale)); % Generate Lambertian shading - dot product between surface normal and light % direction. Note that the product with n2 is negated to account for the % image +ve y increasing downwards. shading = I(1)*n1 - I(2)*n2 + I(3)*n3; % Remove -ve shading values (surfaces pointing away from light source) shading(shading < 0) = 0; % If an image has been supplied apply shading to it if ~isempty(rgbim) for n = 1:3 shrgbim(:,:,n) = rgbim(:,:,n).*shading; end set(imHandle,'CData', shrgbim); else % Just display shading image set(imHandle,'CData', shading); end end %--------------------------------------------------------------------------- % Compute image/heightmap surface normals function [n1, n2, n3] = surfacenormals(im, gradscale, loggrad) % Compute partial derivatives of z. % p = dz/dx, q = dz/dy [p,q] = gradient(im); p = p*gradscale; q = q*gradscale; % If specified take logs of gradient if strcmpi(loggrad, 'log') p = sign(p).*log1p(abs(p)); q = sign(q).*log1p(abs(q)); elseif strcmpi(loggrad, 'loglog') p = sign(p).*log1p(log1p(abs(p))); q = sign(q).*log1p(log1p(abs(q))); elseif strcmpi(loggrad, 'logloglog') p = sign(p).*log1p(log1p(log1p(abs(p)))); q = sign(q).*log1p(log1p(log1p(abs(q)))); end % Generate surface unit normal vectors. Components stored in n1, n2 % and n3 mag = sqrt(1 + p.^2 + q.^2); n1 = -p./mag; n2 = -q./mag; n3 = 1./mag; end %--------------------------------------------------------------------------- % Generate coordinates of points around a circle with centre c, radius r function [xd, yd] = circlexy(c, r) nsides = 32; a = [0:2*pi/nsides:2*pi]; xd = r*cos(a) + c(1); yd = r*sin(a) + c(2); end %--------------------------------------------------------------------------- % Estimate initial gradient scale for a reasonable initial shading result % Aim for a median gradient of around 0.25 function gradscale = initialgradscale mediantarget = 0.25; [p,q] = gradient(im); pt = abs([p(:); q(:)]); pt(isnan(pt) | pt <eps) = []; gradscale = mediantarget/median(pt); end %--------------------------------------------------------------------------- end % of dynamicrelief
github
jacksky64/imageProcessing-master
agc.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Geosci/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
vertderiv.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Geosci/vertderiv.m
2,723
utf_8
f77ed0c735d85a28547dfac1878a70a7
% VERTDERIV Vertical derivative of potential field data % % Usage: vd = vertderiv(im, order) % % Arguments: im - Input potential field image. % order - Order of derivative 1st 2nd etc. Defaults to 1. % The order can be fractional if you wish, say, 1.5 % % Returns: vd - The vertical derivative. % % Vertical derivative filtering is done in the frequency domain whereby the % Fourier transform of the filtered image F(VD) is obtained from the % Fourier transform of the input image F(U) using % F(VD) = F(U) * (sqrt(u^2 + v^2))^order % where u and v are the spatial frequencies in x and y over the input grid. % % To minimise edge effect problems Moisan's Periodic FFT is used. This avoids % the need for data tapering. % % References: % Richard Blakely, "Potential Theory in Gravity and Magnetic Applications" % Cambridge University Press, 1996. pp 324-326. % % L. Moisan, "Periodic plus Smooth Image Decomposition", Journal of % Mathematical Imaging and Vision, vol 39:2, pp. 161-179, 2011. % % See also: TILTDERIV, PERFFT2 % Copyright (c) Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % % March 2015 function vd = vertderiv(im, order) if ~exist('order', 'var'), order = 1; end [rows,cols,chan] = size(im); assert(chan == 1, 'Image must be single channel'); assert(order >= 0, 'Derivative order must be >= 0'); mask = ~isnan(im); % Use Periodic FFT rather than data tapering to minimise edge effects. IM = perfft2(fillnan(im)); % Generate horizontal and vertical frequency grids that vary from -0.5 to % 0.5. This represents spatial frequency in grid units. [u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ... ([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2))); % Quadrant shift to put 0 frequency at the corners. u1 = ifftshift(u1); u2 = ifftshift(u2); % Form the filter by raising the frequency magnitude to the desired power, % then multiply by the Fourier transform of the image, invert the Fourier % transform, and finally mask out any NaN regions from the input image. vd = real(ifft2(IM .* (sqrt(u1.^2 + u2.^2)).^order)) .* double(mask);
github
jacksky64/imageProcessing-master
smoothorient.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/smoothorient.m
1,577
utf_8
792640aa0e4acc0b3bf99d63587a382f
% SMOOTHORIENT - applies smoothing to orientation field % % Usage: smorient = smoothorient(orient, sigma) % % Input: % orient - Image containing feature normal orientation angles in degrees. % sigma - Standard deviation of Gaussian to use (try 1) % % Returns: % smorient - Smoothed orientation image. % % It seems to be useful to smooth the orientation field returned by phasecong2 % before applying nonmaximal suppression. % % See Also: NONMAXSUP, PHASECONG2 % Copyright (c) 2007 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. function smor = smoothorient(or, sigma) or = or/180*pi; % Convert orientations to radians % Smoothing is applied separately to the sine and cosine of the angles to % avoid wraparound problems. cosor = cos(or); sinor = sin(or); f = fspecial('gaussian', max(1,fix(6*sigma)), sigma); cosor = filter2(f,cosor); sinor = filter2(f,sinor); % Reconstitute angles and convert back to degrees smor = atan2(sinor, cosor)/pi*180;
github
jacksky64/imageProcessing-master
imtrim.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/imtrim.m
767
utf_8
3198c92eac92c39200792c9dc1e94f9d
% IMTRIM - removes a boundary of an image % % Usage: trimmedim = imtrim(im, b) % % Arguments: im - Image to be trimmed (greyscale or colour) % b - Width of boundary to be removed % % Returns: trimmedim - Trimmed image of size rows-2*b x cols-2*b % % See also: IMPAD, IMSETBORDER % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % June 2010 function tim = imtrim(im, b) assert(b >= 1, 'Padding size must be > 1') b = round(b); % ensure integer [rows, cols, channels] = size(im); if rows <= 2*b || cols <= 2*b error('Amount to be trimmed is greater than image size'); end tim = im(1+b:end-b, 1+b:end-b, 1:channels);
github
jacksky64/imageProcessing-master
hessianfeatures.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/hessianfeatures.m
2,917
utf_8
9e1d6647b257b73405b63ecc1dfc3924
% HESSIANFEATURES - Computes determiant of hessian features in an image. % % Usage: hdet = hessianfeatures(im, sigma) % % Arguments: % im - Greyscale image to be processed. % sigma - Defines smoothing scale. % % Returns: hdet - Matrix of determinants of Hessian % % The local maxima of hdet tend to mark the centres of dark or light blobs. % However, the point that gets localised can be dependent on scale. If the % blobs you wish to detect are large you will need to use a value of sigma that % is comparable in magnitude. % % The local minima of hdet is useful for marking the intersection points of a % camera calibration checkerbaord pattern. These saddle features seem to be % more stable under scale variations. % % For example to get the 100 strongest saddle features in image 'im' use: % >> hdet = hessianfeatures(im, 1); % sigma = 1 % >> [r, c] = nonmaxsuppts(-hdet, 'N', 100); % % See also: HARRIS, NOBLE, SHI_TOMASI, DERIVATIVE5, NONMAXSUPPTS % Copyright (c) 2007-2016 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % PK Oct 2007 - Original version % Sept 2015 - Cleanup, scaled Harris removed. % Sept 2015 - Removed calculation of trace/LoG to reduce memory use % Jan 2016 - Made single scale. See HESSAINFEATUREMULTISCALE instead % Derivative calulation change to use DERIVATIVE5 function hdet = hessianfeatures(im, sigma) if ndims(im) == 3 warning('Input image is colour, converting to greyscale') im = rgb2gray(im); end if ~isa(im,'double') im = double(im); end if sigma > 0 % Convolve with Gaussian at desired sigma sze = ceil(7*sigma); if ~mod(sze,2) % ensure size is odd sze = sze+1; end G = fspecial('gaussian', sze, sigma); Gim = filter2(G, im); else % No smoothing Gim = im; sigma = 1; % Needed for normalisation later end % Take 1st and 2nd derivatives in x and y [Lx, Ly, Lxx, Lxy, Lyy] = derivative5(Gim, 'x', 'y', 'xx', 'xy', 'yy'); % Apply normalizing scaling factor of sigma to 1st derivatives and % sigma^2 to 2nd derivatives Lx = Lx*sigma; Ly = Ly*sigma; Lxx = Lxx*sigma^2; Lyy = Lyy*sigma^2; Lxy = Lxy*sigma^2; % Determinant hdet = Lxx.*Lyy - Lxy.^2;
github
jacksky64/imageProcessing-master
regionadjacency.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/regionadjacency.m
4,510
utf_8
c2fb48dec79835eac0afc0d068601942
% REGIONADJACENCY Computes adjacency matrix for image of labeled segmented regions % % Usage: [Am, Al] = regionadjacency(L, connectivity) % % Arguments: L - A region segmented image, such as might be produced by a % graph cut or superpixel algorithm. All pixels in each % region are labeled by an integer. % connectivity - 8 or 4. If not specified connectivity defaults to 8. % % Returns: Am - An adjacency matrix indicating which labeled regions are % adjacent to each other, that is, they share boundaries. Am % is sparse to save memory. % Al - A cell array representing the adjacency list corresponding % to Am. Al{n} is an array of the region indices adjacent to % region n. % % Regions with a label of 0 are not processed. They are considered to be % 'background regions' that are not to be considered. If you want to include % these regions you should assign a new positive label to these areas using, say % >> L(L==0) = max(L(:)) + 1; % % See also: CLEANUPREGIONS, RENUMBERREGIONS, SLIC % Copyright (c) 2013 Peter Kovesi % Centre for Exploration Targeting % School of Earth and Environment % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % February 2013 Original version % July 2013 Speed improvement in sparse matrix formation (4x) function [Am, varargout] = regionadjacency(L, connectivity) if ~exist('connectivity', 'var'), connectivity = 8; end [rows,cols] = size(L); % Identify the unique labels in the image, excluding 0 as a label. labels = setdiff(unique(L(:))',0); if isempty(labels) warning('There are no objects in the image') Am = []; Al = {}; return end N = max(labels); % Required size of adjacency matrix % Strategy: Step through the labeled image. For 8-connectedness inspect % pixels as follows and set the appropriate entries in the adjacency % matrix. % x - o % / | \ % o o o % % For 4-connectedness we only inspect the following pixels % x - o % | % o % % Becuase the adjacency search looks 'forwards' a final OR operation is % performed on the adjacency matrix and its transpose to ensure % connectivity both ways. % Allocate vectors for forming row, col, value triplets used to construct % sparse matrix. Forming these vectors first is faster than filling % entries directly into the sparse matrix i = zeros(rows*cols,1); % row value j = zeros(rows*cols,1); % col value s = zeros(rows*cols,1); % value if connectivity == 8 n = 1; for r = 1:rows-1 % Handle pixels in 1st column i(n) = L(r,1); j(n) = L(r ,2); s(n) = 1; n=n+1; i(n) = L(r,1); j(n) = L(r+1,1); s(n) = 1; n=n+1; i(n) = L(r,1); j(n) = L(r+1,2); s(n) = 1; n=n+1; % ... now the rest of the column for c = 2:cols-1 i(n) = L(r,c); j(n) = L(r ,c+1); s(n) = 1; n=n+1; i(n) = L(r,c); j(n) = L(r+1,c-1); s(n) = 1; n=n+1; i(n) = L(r,c); j(n) = L(r+1,c ); s(n) = 1; n=n+1; i(n) = L(r,c); j(n) = L(r+1,c+1); s(n) = 1; n=n+1; end end elseif connectivity == 4 n = 1; for r = 1:rows-1 for c = 1:cols-1 i(n) = L(r,c); j(n) = L(r ,c+1); s(n) = 1; n=n+1; i(n) = L(r,c); j(n) = L(r+1,c ); s(n) = 1; n=n+1; end end else error('Connectivity must be 4 or 8'); end % Form the logical sparse adjacency matrix Am = logical(sparse(i, j, s, N, N)); % Zero out the diagonal for r = 1:N Am(r,r) = 0; end % Ensure connectivity both ways for all regions. Am = Am | Am'; % If an adjacency list is requested... if nargout == 2 Al = cell(N,1); for r = 1:N Al{r} = find(Am(r,:)); end varargout{1} = Al; end
github
jacksky64/imageProcessing-master
integgausfilt.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/integgausfilt.m
2,500
utf_8
a2a14a4604cd4a021514fffb77dd587e
% INTEGGAUSFILT - Approximate Gaussian filtering using integral filters % % This function approximates Gaussian filtering by repeatedly applying % averaging filters. The averaging is performed via integral images which % results in a fixed and very low computational cost that is independent of % the Gaussian size. % % Usage: fim = integgausfilt(im, sigma, nFilt) % % Arguments: % im - Image to be Gaussian smoothed % sigma - Desired standard deviation of Gaussian filter % nFilt - The number of average filterings to be used to % approximate the Gaussian. This should be a minimum of % 3, using 4 is better. If the smoothed image is to be % differentiated an additional averaging should be applied % for each derivative. Eg if a second derivative is to be % taken at least 5 averagings should be applied. If omitted % this parameter defaults to 5. % % Note that the desired standard deviation will not be achieved exactly. A % combination of different sized averaging filters are applied to approximate it % as closely as possible. If nFilt is 5 the deviation from the desired standard % deviation will be at most about 0.15 pixels % % See also: INTEGAVERAGE, SOLVEINTEG, INTEGRALIMAGE % Copyright (c) 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. % September 2009 function im = integgausfilt(im, sigma, nFilt) if ~exist('nFilt', 'var') nFilt = 5; end % Solve for the combination of averaging filter sizes that will result in % the closest approximation of sigma given nFilt. [wl, wu, m] = solveinteg(sigma, nFilt); radl = (wl-1)/2; radu = (wu-1)/2; % Apply the averaging filters via integral images. for i = 1:m im = integaverage(im,radl); end for n = 1:(nFilt-m) im = integaverage(im,radu); end
github
jacksky64/imageProcessing-master
anisodiff.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/anisodiff.m
2,600
utf_8
3d6827b7cb6831ab151cc363a892fd5a
% ANISODIFF - Anisotropic diffusion. % % Usage: % diff = anisodiff(im, niter, kappa, lambda, option) % % Arguments: % im - input image % niter - number of iterations. % kappa - conduction coefficient 20-100 ? % lambda - max value of .25 for stability % option - 1 Perona Malik diffusion equation No 1 % 2 Perona Malik diffusion equation No 2 % % Returns: % diff - diffused image. % % kappa controls conduction as a function of gradient. If kappa is low % small intensity gradients are able to block conduction and hence diffusion % across step edges. A large value reduces the influence of intensity % gradients on conduction. % % lambda controls speed of diffusion (you usually want it at a maximum of % 0.25) % % Diffusion equation 1 favours high contrast edges over low contrast ones. % Diffusion equation 2 favours wide regions over smaller ones. % Reference: % P. Perona and J. Malik. % Scale-space and edge detection using ansotropic diffusion. % IEEE Transactions on Pattern Analysis and Machine Intelligence, % 12(7):629-639, July 1990. % % Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk @ csse uwa edu au % http://www.csse.uwa.edu.au % % June 2000 original version. % March 2002 corrected diffusion eqn No 2. function diff = anisodiff(im, niter, kappa, lambda, option) if ndims(im)==3 error('Anisodiff only operates on 2D grey-scale images'); end im = double(im); [rows,cols] = size(im); diff = im; for i = 1:niter % fprintf('\rIteration %d',i); % Construct diffl which is the same as diff but % has an extra padding of zeros around it. diffl = zeros(rows+2, cols+2); diffl(2:rows+1, 2:cols+1) = diff; % North, South, East and West differences deltaN = diffl(1:rows,2:cols+1) - diff; deltaS = diffl(3:rows+2,2:cols+1) - diff; deltaE = diffl(2:rows+1,3:cols+2) - diff; deltaW = diffl(2:rows+1,1:cols) - diff; % Conduction if option == 1 cN = exp(-(deltaN/kappa).^2); cS = exp(-(deltaS/kappa).^2); cE = exp(-(deltaE/kappa).^2); cW = exp(-(deltaW/kappa).^2); elseif option == 2 cN = 1./(1 + (deltaN/kappa).^2); cS = 1./(1 + (deltaS/kappa).^2); cE = 1./(1 + (deltaE/kappa).^2); cW = 1./(1 + (deltaW/kappa).^2); end diff = diff + lambda*(cN.*deltaN + cS.*deltaS + cE.*deltaE + cW.*deltaW); % Uncomment the following to see a progression of images % subplot(ceil(sqrt(niter)),ceil(sqrt(niter)), i) % imagesc(diff), colormap(gray), axis image end %fprintf('\n');
github
jacksky64/imageProcessing-master
drawregionboundaries.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/drawregionboundaries.m
2,312
utf_8
52e55969a30f9db62b4847f5a14997d4
% DRAWREGIONBOUNDARIES Draw boundaries of labeled regions in an image % % Usage: maskim = drawregionboundaries(l, im, col) % % Arguments: % l - Labeled image of regions. % im - Optional image to overlay the region boundaries on. % col - Optional colour specification. Defaults to black. Note that % the colour components are specified as values 0-255. % For example red is [255 0 0] and white is [255 255 255]. % % Returns: % maskim - If no image has been supplied maskim is a binary mask % image indicating where the region boundaries are. % If an image has been supplied maskim is the image with the % region boundaries overlaid % % See also: MASKIMAGE % Copyright (c) 2013 Peter Kovesi % Centre for Exploration Targeting % School of Earth and Environment % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % Feb 2013 function maskim = drawregionboundaries(l, im, col) % Form the mask by applying a sobel edge detector to the labeled image, % thresholding and then thinning the result. % h = [1 0 -1 % 2 0 -2 % 1 0 -1]; h = [-1 1]; % A simple small filter is better in this application. % Small regions 1 pixel wide get missed using a Sobel % operator gx = filter2(h ,l); gy = filter2(h',l); maskim = (gx.^2 + gy.^2) > 0; maskim = bwmorph(maskim, 'thin', Inf); % Zero out any mask values that may have been set around the edge of the % image. maskim(1,:) = 0; maskim(end,:) = 0; maskim(:,1) = 0; maskim(:,end) = 0; % If an image has been supplied apply the mask to the image and return it if exist('im', 'var') if ~exist('col', 'var'), col = 0; end maskim = maskimage(im, maskim, col); end
github
jacksky64/imageProcessing-master
canny.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/canny.m
2,293
utf_8
6bdaaea9bcfecd3c0443e573bdac5381
% CANNY - Canny edge detection % % Function to perform Canny edge detection. % % Usage: [gradient or] = canny(im, sigma) % % Arguments: im - image to be procesed % sigma - standard deviation of Gaussian smoothing filter. % Optional, defaults to 1. % % Returns: gradient - edge strength image (gradient amplitude) % or - orientation image (in degrees 0-180, positive % anti-clockwise) % % % To obtain a binary edge image one would typically do the following % >> [gr or] = canny(im, sigma); % Choose sigma to taste % >> nm = nonmaxsup(gr, or, rad); % I use a rad value ~ 1.2 to 1.5 % >> bw = hysthresh(nm, T1, T2); % Choose T1 and T2 until the result looks ok % % See also: NONMAXSUP, HYSTHRESH, DERIVATIVE5 % Copyright (c) 1999-2010 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in all % copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % April 1999 Original version % January 2003 Error in calculation of d2 corrected % August 2010 Changed to use derivatives computed using Farid and % Simoncelli's filters. Cleaned up % May 2013 Sigma optional with default of 1 function [gradient, or] = canny(im, sigma) assert(ndims(im) == 2, 'Image must be greyscale'); if ~exist('sigma', 'var'), sigma = 1; end % If needed convert im to double if ~strcmp(class(im),'double') im = double(im); end im = gaussfilt(im, sigma); % Smooth the image. [Ix, Iy] = derivative5(im,'x','y'); % Get derivatives. gradient = sqrt(Ix.*Ix + Iy.*Iy); % Gradient magnitude. or = atan2(-Iy, Ix); % Angles -pi to + pi. or(or<0) = or(or<0)+pi; % Map angles to 0-pi. or = or*180/pi; % Convert to degrees.
github
jacksky64/imageProcessing-master
integralimage.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/integralimage.m
1,583
utf_8
625ff486923979d644b6b48a01c2af43
% INTEGRALIMAGE - computes integral image of an image % % Usage: intim = integralimage(im) % % This function computes an integral image such that the value of intim(r,c) % equals sum(sum(im(1:r, 1:c)) % % An integral image can be used with the function INTEGRALFILTER to perform % filtering operations (using rectangular filters) on an image in time that % only depends on the image size, irrespective of the filter size. % % See also: INTEGRALFILTER, INTEGAVERAGE, INTFILTTRANSPOSE % Reference: Crow, Franklin (1984). "Summed-area tables for texture % mapping". SIGGRAPH '84. pp. 207-212. % Paul Viola and Michael Jones, "Robust Real-Time Face Detection", % IJCV 57(2). pp 137-154. 2004. % 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/ % % 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 2006 function intim = integralimage(im) if ndims(im) == 3 error('Image must be greyscale'); end if strcmp(class(im),'uint8') % A cast to double is needed im = double(im); end intim = cumsum(cumsum(im,1),2);
github
jacksky64/imageProcessing-master
slic.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/slic.m
14,966
utf_8
8fa6f6e0639ea7e9ed8c1e3b8dd480fd
% SLIC Simple Linear Iterative Clustering SuperPixels % % Implementation of Achanta, Shaji, Smith, Lucchi, Fua and Susstrunk's % SLIC Superpixels % % Usage: [l, Am, Sp, d] = slic(im, k, m, seRadius, colopt, mw) % % Arguments: im - Image to be segmented. % k - Number of desired superpixels. Note that this is nominal % the actual number of superpixels generated will generally % be a bit larger, espiecially if parameter m is small. % m - Weighting factor between colour and spatial % differences. Values from about 5 to 40 are useful. Use a % large value to enforce superpixels with more regular and % smoother shapes. Try a value of 10 to start with. % seRadius - Regions morphologically smaller than this are merged with % adjacent regions. Try a value of 1 or 1.5. Use 0 to % disable. % colopt - String 'mean' or 'median' indicating how the cluster % colour centre should be computed. Defaults to 'mean' % mw - Optional median filtering window size. Image compression % can result in noticeable artifacts in the a*b* components % of the image. Median filtering can reduce this. mw can be % a single value in which case the same median filtering is % applied to each L* a* and b* components. Alternatively it % can be a 2-vector where mw(1) specifies the median % filtering window to be applied to L* and mw(2) is the % median filtering window to be applied to a* and b*. % % Returns: l - Labeled image of superpixels. Labels range from 1 to k. % Am - Adjacency matrix of segments. Am(i, j) indicates whether % segments labeled i and j are connected/adjacent % Sp - Superpixel attribute structure array with fields: % L - Mean L* value % a - Mean a* value % b - Mean b* value % r - Mean row value % c - Mean column value % stdL - Standard deviation of L* % stda - Standard deviation of a* % stdb - Standard deviation of b* % N - Number of pixels % edges - List of edge numbers that bound each % superpixel. This field is allocated, but not set, % by SLIC. Use SPEDGES for this. % d - Distance image giving the distance each pixel is from its % associated superpixel centre. % % It is suggested that use of this function is followed by SPDBSCAN to perform a % DBSCAN clustering of superpixels. This results in a simple and fast % segmentation of an image. % % Minor variations from the original algorithm as defined in Achanta et al's % paper: % % - SuperPixel centres are initialised on a hexagonal grid rather than a square % one. This results in a segmentation that will be nominally 6-connected % which hopefully facilitates any subsequent post-processing that seeks to % merge superpixels. % - Initial cluster positions are not shifted to point of lowest gradient % within a 3x3 neighbourhood because this will be rendered irrelevant the % first time cluster centres are updated. % % Reference: R. Achanta, A. Shaji, K. Smith, A. Lucchi, P. Fua and % S. Susstrunk. "SLIC Superpixels Compared to State-of-the-Art Superpixel % Methods" PAMI. Vol 34 No 11. November 2012. pp 2274-2281. % % See also: SPDBSCAN, MCLEANUPREGIONS, REGIONADJACENCY, DRAWREGIONBOUNDARIES, RGB2LAB % Copyright (c) 2013 Peter Kovesi % Centre for Exploration Targeting % School of Earth and Environment % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % Feb 2013 % July 2013 Super pixel attributes returned as a structure array % Note that most of the computation time is not in the clustering, but rather % in the region cleanup process. function [l, Am, Sp, d] = slic(im, k, m, seRadius, colopt, mw, nItr, eim, We) if ~exist('colopt','var') || isempty(colopt), colopt = 'mean'; end if ~exist('mw','var') || isempty(mw), mw = 0; end if ~exist('nItr','var') || isempty(nItr), nItr = 10; end if exist('eim', 'var'), USEDIST = 0; else, USEDIST = 1; end MEANCENTRE = 1; MEDIANCENTRE = 2; if strcmp(colopt, 'mean') centre = MEANCENTRE; elseif strcmp(colopt, 'median') centre = MEDIANCENTRE; else error('Invalid colour centre computation option'); end [rows, cols, chan] = size(im); if chan ~= 3 error('Image must be colour'); end % Convert image to L*a*b* colourspace. This gives us a colourspace that is % nominally perceptually uniform. This allows us to use the euclidean % distance between colour coordinates to measure differences between % colours. Note the image becomes double after conversion. We may want to % go to signed shorts to save memory. im = rgb2lab(im); % Apply median filtering to colour components if mw has been supplied % and/or non-zero if mw if length(mw) == 1 mw(2) = mw(1); % Use same filtering for L and chrominance end for n = 1:3 im(:,:,n) = medfilt2(im(:,:,n), [mw(1) mw(1)]); end end % Nominal spacing between grid elements assuming hexagonal grid S = sqrt(rows*cols / (k * sqrt(3)/2)); % Get nodes per row allowing a half column margin at one end that alternates % from row to row nodeCols = round(cols/S - 0.5); % Given an integer number of nodes per row recompute S S = cols/(nodeCols + 0.5); % Get number of rows of nodes allowing 0.5 row margin top and bottom nodeRows = round(rows/(sqrt(3)/2*S)); vSpacing = rows/nodeRows; % Recompute k k = nodeRows * nodeCols; % Allocate memory and initialise clusters, labels and distances. C = zeros(6,k); % Cluster centre data 1:3 is mean Lab value, % 4:5 is row, col of centre, 6 is No of pixels l = -ones(rows, cols); % Pixel labels. d = inf(rows, cols); % Pixel distances from cluster centres. % Initialise clusters on a hexagonal grid kk = 1; r = vSpacing/2; for ri = 1:nodeRows % Following code alternates the starting column for each row of grid % points to obtain a hexagonal pattern. Note S and vSpacing are kept % as doubles to prevent errors accumulating across the grid. if mod(ri,2), c = S/2; else, c = S; end for ci = 1:nodeCols cc = round(c); rr = round(r); C(1:5, kk) = [squeeze(im(rr,cc,:)); cc; rr]; c = c+S; kk = kk+1; end r = r+vSpacing; end % Now perform the clustering. 10 iterations is suggested but I suspect n % could be as small as 2 or even 1 S = round(S); % We need S to be an integer from now on for n = 1:nItr for kk = 1:k % for each cluster % Get subimage around cluster rmin = max(C(5,kk)-S, 1); rmax = min(C(5,kk)+S, rows); cmin = max(C(4,kk)-S, 1); cmax = min(C(4,kk)+S, cols); subim = im(rmin:rmax, cmin:cmax, :); assert(numel(subim) > 0) % Compute distances D between C(:,kk) and subimage if USEDIST D = dist(C(:, kk), subim, rmin, cmin, S, m); else D = dist2(C(:, kk), subim, rmin, cmin, S, m, eim, We); end % If any pixel distance from the cluster centre is less than its % previous value update its distance and label subd = d(rmin:rmax, cmin:cmax); subl = l(rmin:rmax, cmin:cmax); updateMask = D < subd; subd(updateMask) = D(updateMask); subl(updateMask) = kk; d(rmin:rmax, cmin:cmax) = subd; l(rmin:rmax, cmin:cmax) = subl; end % Update cluster centres with mean values C(:) = 0; for r = 1:rows for c = 1:cols tmp = [im(r,c,1); im(r,c,2); im(r,c,3); c; r; 1]; C(:, l(r,c)) = C(:, l(r,c)) + tmp; end end % Divide by number of pixels in each superpixel to get mean values for kk = 1:k C(1:5,kk) = round(C(1:5,kk)/C(6,kk)); end % Note the residual error, E, is not calculated because we are using a % fixed number of iterations end % Cleanup small orphaned regions and 'spurs' on each region using % morphological opening on each labeled region. The cleaned up regions are % assigned to the nearest cluster. The regions are renumbered and the % adjacency matrix regenerated. This is needed because the cleanup is % likely to change the number of labeled regions. if seRadius [l, Am] = mcleanupregions(l, seRadius); else l = makeregionsdistinct(l); [l, minLabel, maxLabel] = renumberregions(l); Am = regionadjacency(l); end % Recompute the final superpixel attributes and write information into % the Sp struct array. N = length(Am); Sp = struct('L', cell(1,N), 'a', cell(1,N), 'b', cell(1,N), ... 'stdL', cell(1,N), 'stda', cell(1,N), 'stdb', cell(1,N), ... 'r', cell(1,N), 'c', cell(1,N), 'N', cell(1,N)); [X,Y] = meshgrid(1:cols, 1:rows); L = im(:,:,1); A = im(:,:,2); B = im(:,:,3); for n = 1:N mask = l==n; nm = sum(mask(:)); if centre == MEANCENTRE Sp(n).L = sum(L(mask))/nm; Sp(n).a = sum(A(mask))/nm; Sp(n).b = sum(B(mask))/nm; elseif centre == MEDIANCENTRE Sp(n).L = median(L(mask)); Sp(n).a = median(A(mask)); Sp(n).b = median(B(mask)); end Sp(n).r = sum(Y(mask))/nm; Sp(n).c = sum(X(mask))/nm; % Compute standard deviations of the colour components of each super % pixel. This can be used by code seeking to merge superpixels into % image segments. Note these are calculated relative to the mean colour % component irrespective of the centre being calculated from the mean or % median colour component values. Sp(n).stdL = std(L(mask)); Sp(n).stda = std(A(mask)); Sp(n).stdb = std(B(mask)); Sp(n).N = nm; % Record number of pixels in superpixel too. end %-- dist ------------------------------------------- % % Usage: D = dist(C, im, r1, c1, S, m) % % Arguments: C - Cluster being considered % im - sub-image surrounding cluster centre % r1, c1 - row and column of top left corner of sub image within the % overall image. % S - grid spacing % m - weighting factor between colour and spatial differences. % % Returns: D - Distance image giving distance of every pixel in the % subimage from the cluster centre % % Distance = sqrt( dc^2 + (ds/S)^2*m^2 ) % where: % dc = sqrt(dl^2 + da^2 + db^2) % Colour distance % ds = sqrt(dx^2 + dy^2) % Spatial distance % % m is a weighting factor representing the nominal maximum colour distance % expected so that one can rank colour similarity relative to distance % similarity. try m in the range [1-40] for L*a*b* space % % ?? Might be worth trying the Geometric Mean instead ?? % Distance = sqrt(dc * ds) % but having a factor 'm' to play with is probably handy % This code could be more efficient function D = dist(C, im, r1, c1, S, m) % Squared spatial distance % ds is a fixed 'image' we should be able to exploit this % and use a fixed meshgrid for much of the time somehow... [rows, cols, chan] = size(im); [x,y] = meshgrid(c1:(c1+cols-1), r1:(r1+rows-1)); x = x-C(4); % x and y dist from cluster centre y = y-C(5); ds2 = x.^2 + y.^2; % Squared colour difference for n = 1:3 im(:,:,n) = (im(:,:,n)-C(n)).^2; end dc2 = sum(im,3); D = sqrt(dc2 + ds2/S^2*m^2); %--- dist2 ------------------------------------------ % % Usage: D = dist2(C, im, r1, c1, S, m, eim) % % Arguments: C - Cluster being considered % im - sub-image surrounding cluster centre % r1, c1 - row and column of top left corner of sub image within the % overall image. % S - grid spacing % m - weighting factor between colour and spatial differences. % eim - Edge strength sub-image corresponding to im % % Returns: D - Distance image giving distance of every pixel in the % subimage from the cluster centre % % Distance = sqrt( dc^2 + (ds/S)^2*m^2 ) % where: % dc = sqrt(dl^2 + da^2 + db^2) % Colour distance % ds = sqrt(dx^2 + dy^2) % Spatial distance % % m is a weighting factor representing the nominal maximum colour distance % expected so that one can rank colour similarity relative to distance % similarity. try m in the range [1-40] for L*a*b* space % function D = dist2(C, im, r1, c1, S, m, eim, We) % Squared spatial distance % ds is a fixed 'image' we should be able to exploit this % and use a fixed meshgrid for much of the time somehow... [rows, cols, chan] = size(im); [x,y] = meshgrid(c1:(c1+cols-1), r1:(r1+rows-1)); x = x-C(4); y = y-C(5); ds2 = x.^2 + y.^2; % Squared colour difference for n = 1:3 im(:,:,n) = (im(:,:,n)-C(n)).^2; end dc2 = sum(im,3); % Combine colour and spatial distance measure D = sqrt(dc2 + ds2/S^2*m^2); % for every pixel in the subimage call improfile to the cluster centre % and use the largest value as the 'edge distance' rCentre = C(5)-r1; % Cluster centre coords relative to this sub-image cCentre = C(4)-c1; de = zeros(rows,cols); for r = 1:rows for c = 1:cols v = improfile(eim,[c cCentre], [r rCentre]); de(r,c) = max(v); end end % Combine edge distance with weight, We with total Distance. D = D + We * de;
github
jacksky64/imageProcessing-master
nonmaxsuppts.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/nonmaxsuppts.m
6,729
utf_8
eb23198eb43f6202473f2bc1364435e0
% NONMAXSUPPTS - Non-maximal suppression for features/corners % % Non maxima suppression and thresholding for points generated by a feature % or corner detector. % % Usage: [r,c] = nonmaxsuppts(cim, Keyword-Value options...) % % Required argument: % cim - Corner strength image. % % Optional arguments specified as keyword - value pairs: % 'radius' - Radius of region considered in non-maximal % suppression. Typical values to use might % be 1-3 pixels. Default is 1. % 'thresh' - Threshold, only features with value greater than % threshold are returned. Default is 0. % 'N' - Maximum number of features to return. In this case the % N strongest features with value above 'thresh' are % returned. Default is Inf. % 'subpixel' - If set to true features are localised to subpixel % precision. Default is false. % 'im' - Optional image data. If an image is supplied the % detected corners are overlayed on this image. This can % be useful for parameter tuning. Default is []. % Returns: % r - Row coordinates of corner points. % c - Column coordinates of corner points. % % Example of use: % >> hes = hessianfeatures(im, 1); % Compute Hessian feature image in image im % % Find the 1000 strongest features to subpixel precision using a non-maximal % suppression radius of 2 and overlay the detected corners on the origin image. % >> [r,c]= nonmaxsuppts(abs(hes), 'radius', 2, 'N', 1000, 'im', im, 'subpixel', true); % % Note: An issue with integer valued images is that if there are multiple pixels % all with the same value within distance 2*radius of each other then they will % all be marked as local maxima. % % See also: HARRIS, NOBLE, SHI_TOMASI, HESSIANFEATURES % Copyright (c) 2003-2016 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. % September 2003 Original version % August 2005 Subpixel localization and Octave compatibility % January 2010 Fix for completely horizontal and vertical lines (by Thomas Stehle, % RWTH Aachen University) % January 2011 Warning given if no maxima found % January 2016 Reworked to allow the N strongest features to be returned. % Arguments changed to be specified as keyword - value % pairs. (no doubt this breaks some code, sorry) function [r,c] = nonmaxsuppts(cim, varargin) [thresh, radius, N, subpixel, im] = checkargs(varargin); [rows,cols] = size(cim); % Extract local maxima by performing a grey scale morphological % dilation and then finding points in the corner strength image that % match the dilated image and are also greater than the threshold. sze = 2*radius+1; % Size of dilation mask. mx = imdilate(cim, strel('disk',radius)); % mx = ordfilt2(cim, sze^2,ones(sze)); % Grey-scale dilate. % Make mask to exclude points within radius of the image boundary. bordermask = zeros(size(cim)); bordermask(radius+1:end-radius, radius+1:end-radius) = 1; % Find maxima, threshold, and apply bordermask cimmx = (cim==mx) & (cim>thresh) & bordermask; [r,c] = find(cimmx); % Find row,col coords. % Check if we want to limit the number of maxima if isfinite(N) mxval = cim(cimmx); % Get values of maxima and sort them. [mxval,ind] = sort(mxval,1,'descend'); r = r(ind); % Reorder r and c arrays c = c(ind); % to match. if length(r) > N % Grab the N strongest features. r = r(1:N); c = c(1:N); end end if isempty(r) warning('No maxima above threshold found'); return end if subpixel % Compute local maxima to sub pixel accuracy ind = sub2ind(size(cim),r,c); % 1D indices of feature points w = 1; % Width that we look out on each side of the feature % point to fit a local parabola % Indices of points above, below, left and right of feature point indrminus1 = max(ind-w,1); indrplus1 = min(ind+w,rows*cols); indcminus1 = max(ind-w*rows,1); indcplus1 = min(ind+w*rows,rows*cols); % Solve for quadratic down rows rowshift = zeros(size(ind)); cy = cim(ind); ay = (cim(indrminus1) + cim(indrplus1))/2 - cy; by = ay + cy - cim(indrminus1); rowshift(ay ~= 0) = -w*by(ay ~= 0)./(2*ay(ay ~= 0)); % Maxima of quadradic rowshift(ay == 0) = 0; % Solve for quadratic across columns colshift = zeros(size(ind)); cx = cim(ind); ax = (cim(indcminus1) + cim(indcplus1))/2 - cx; bx = ax + cx - cim(indcminus1); colshift(ax ~= 0) = -w*bx(ax ~= 0)./(2*ax(ax ~= 0)); % Maxima of quadradic colshift(ax == 0) = 0; r = r+rowshift; % Add subpixel corrections to original row c = c+colshift; % and column coords. end if ~isempty(im) % Overlay corners on supplied image. figure, imshow(im,[]), hold on plot(c,r,'r+'), title('corners detected'); hold off end end %--------------------------------------------------------------- function [thresh, radius, N, subpixel, im] = checkargs(v) p = inputParser; p.CaseSensitive = false; % Define optional parameter-value pairs and their defaults addParameter(p, 'thresh', 0, @isnumeric); addParameter(p, 'radius', 1, @isnumeric); addParameter(p, 'N', Inf, @isnumeric); addParameter(p, 'subpixel', false, @islogical); addParameter(p, 'im', [], @isnumeric); parse(p, v{:}); thresh = p.Results.thresh; radius = p.Results.radius; N = p.Results.N; subpixel = p.Results.subpixel; im = p.Results.im; end
github
jacksky64/imageProcessing-master
hysthresh.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/hysthresh.m
2,218
utf_8
1083374237be0a6bad69e6afd431e1c0
% HYSTHRESH - Hysteresis thresholding % % Usage: bw = hysthresh(im, T1, T2) % % Arguments: % im - image to be thresholded (assumed to be non-negative) % T1 - upper threshold value % T2 - lower threshold value % (T1 and T2 can be entered in any order, the larger of the % two values is used as the upper threshold) % Returns: % bw - the thresholded image (containing values 0 or 1) % % Function performs hysteresis thresholding of an image. % All pixels with values above threshold T1 are marked as edges % All pixels that are connected to points that have been marked as edges % and with values above threshold T2 are also marked as edges. Eight % connectivity is used. % 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. % December 1996 - Original version % March 2001 - Speed improvements made (~4x) % April 2005 - Modified to cope with MATLAB 7's uint8 behaviour % July 2005 - Enormous simplification and great speedup by realizing % that you can use bwselect to do all the work function bw = hysthresh(im, T1, T2) if T1 < T2 % T1 and T2 reversed - swap values tmp = T1; T1 = T2; T2 = tmp; end aboveT2 = im > T2; % Edge points above lower % threshold. [aboveT1r, aboveT1c] = find(im > T1); % Row and colum coords of points % above upper threshold. % Obtain all connected regions in aboveT2 that include a point that has a % value above T1 bw = bwselect(aboveT2, aboveT1c, aboveT1r, 8);
github
jacksky64/imageProcessing-master
renumberregions.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/renumberregions.m
2,350
utf_8
0bf07a365af7d4978066949f3e98d8a5
% RENUMBERREGIONS % % Usage: [nL, minLabel, maxLabel] = renumberregions(L) % % Argument: L - A labeled image segmenting an image into regions, such as % might be produced by a graph cut or superpixel algorithm. % All pixels in each region are labeled by an integer. % % Returns: nL - A relabeled version of L so that label numbers form a % sequence 1:maxRegions or 0:maxRegions-1 depending on % whether L has a region labeled with 0s or not. % minLabel - Minimum label in the renumbered image. This will be 0 or 1. % maxLabel - Maximum label in the renumbered image. % % Application: Segmentation algorithms can produce a labeled image with a non % contiguous numbering of regions 1 4 6 etc. This function renumbers them into a % contiguous sequence. If the input image has a region labeled with 0s this % region is treated as a privileged 'background region' and retains its 0 % labeling. The resulting image will have labels ranging over 0:maxRegions-1. % Otherwise the image will be relabeled over the sequence 1:maxRegions % % See also: CLEANUPREGIONS, REGIONADJACENCY % Copyright (c) 2010 Peter Kovesi % Centre for Exploration Targeting % School of Earth and Environment % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % October 2010 % February 2013 Return label numbering range function [nL, minLabel, maxLabel] = renumberregions(L) nL = L; labels = unique(L(:))'; % Sorted list of unique labels N = length(labels); % If there is a label of 0 we ensure that we do not renumber that region % by removing it from the list of labels to be renumbered. if labels(1) == 0 labels = labels(2:end); minLabel = 0; maxLabel = N-1; else minLabel = 1; maxLabel = N; end % Now do the relabelling count = 1; for n = labels nL(L==n) = count; count = count+1; end
github
jacksky64/imageProcessing-master
harris.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/harris.m
5,655
utf_8
e82f23a9bcba7fbf7a20e48f24f766f1
% Harris - Harris corner detector % % Usage: cim = harris(im, sigma, k) % [cim, r, c] = harris(im, sigma, k, keyword-value options...) % % Required arguments: % im - Image to be processed. % sigma - Standard deviation of smoothing Gaussian used to sum % the derivatives when forming the structure tensor. Typical % values to use might be 1-3. % k - Parameter relating the trace to the determinant of the % structure tensor in the Harris measure. % cim = det(M) - k trace^2(M). % Traditionally k = 0.04 % % Optional keyword - value arguments for performing non-maxima suppression: % % 'radius' - Radius of region considered in non-maximal % suppression. Typical values to use might % be 1-3 pixels. Default is 1. % 'thresh' - Threshold, only features with value greater than % threshold are returned. Default is 1. % 'N' - Maximum number of features to return. In this case the % N strongest features with value above 'thresh' are % returned. Default is Inf. % 'subpixel' - If set to true features are localised to subpixel % precision. Default is false. % 'display' - Optional flag true/false. If true the detected corners % are overlayed on the input image. This can be useful % for parameter tuning. Default is false. % % Returns: % cim - Corner strength image. % r - Row coordinates of corner points. % c - Column coordinates of corner points. % % With only 'im' 'sigma' and 'k' supplied as arguments only 'cim' is returned % as a raw corner strength image. You may then want to look at the values % within 'cim' to determine the appropriate threshold value to use. Note that % the Harris corner strength varies with the intensity gradient raised to the % 4th power. Small changes in input image contrast result in huge changes in % the appropriate threshold. % % If any of the optional keyword - value arguments for performing non-maxima % suppression are specified then the feature coordinate locations are also % returned. % % Example: To get the 100 strongest features and display the detected points % on the input image use: % >> [cim, r, c] = harris(im, 1, .04, 'N', 100, 'display', true); % % The Harris measure is det(M) - k trace^2(M), where k is a parameter you have % to set (traditionally k = 0.04) and M is the structure tensor. Use Noble's % measure if you wish to avoid the need to set a parameter k. However the % Shi-Tomasi measure is probably what you really want. % % See also: NOBLE, SHI_TOMASI, HESSIANFEATURES, NONMAXSUPPTS, DERIVATIVE5 % References: % C.G. Harris and M.J. Stephens. "A combined corner and edge detector", % Proceedings Fourth Alvey Vision Conference, Manchester. % pp 147-151, 1988. % Copyright (c) 2002-2016 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % March 2002 - Original version % December 2002 - Updated comments % August 2005 - Changed so that code calls nonmaxsuppts % August 2010 - Changed to use Farid and Simoncelli's derivative filters % January 2016 - Noble made distinct from the Harris function and argument % handling changed (this will break some code, sorry) function [cim, r, c] = harris(im, sigma, k, varargin) if ~isa(im,'double') im = double(im); end % Compute derivatives and the elements of the structure tensor. [Ix, Iy] = derivative5(im, 'x', 'y'); Ix2 = gaussfilt(Ix.^2, sigma); Iy2 = gaussfilt(Iy.^2, sigma); Ixy = gaussfilt(Ix.*Iy, sigma); % Compute Harris corner measure. cim = (Ix2.*Iy2 - Ixy.^2) - k*(Ix2 + Iy2).^2; if length(varargin) > 0 [thresh, radius, N, subpixel, disp] = checkargs(varargin); if disp [r,c] = nonmaxsuppts(cim, 'thresh', thresh, 'radius', radius, 'N', N, ... 'subpixel', subpixel, 'im', im); else [r,c] = nonmaxsuppts(cim, 'thresh', thresh, 'radius', radius, 'N', N, ... 'subpixel', subpixel, 'im', []); end else r = []; c = []; end %--------------------------------------------------------------- function [thresh, radius, N, subpixel, disp] = checkargs(v) p = inputParser; p.CaseSensitive = false; % Define optional parameter-value pairs and their defaults addParameter(p, 'thresh', 0, @isnumeric); addParameter(p, 'radius', 1, @isnumeric); addParameter(p, 'N', Inf, @isnumeric); addParameter(p, 'subpixel', false, @islogical); addParameter(p, 'display', false, @islogical); parse(p, v{:}); thresh = p.Results.thresh; radius = p.Results.radius; N = p.Results.N; subpixel = p.Results.subpixel; disp = p.Results.display;
github
jacksky64/imageProcessing-master
imsetborder.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/imsetborder.m
807
utf_8
8dd6e75f6b5240fffbdb56e60521ef9b
% IMSETBORDER - sets pixels on image border to a value % % Usage: im = imsetborder(im, b, v) % % Arguments: % im - image % b - border size % v - value to set image borders to (defaults to 0) % % See also: IMPAD, IMTRIM % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % June 2010 function im = imsetborder(im, b, v) if ~exist('v','var'), v = 0; end assert(b >= 1, 'Padding size must be >= 1') b = round(b); % ensure integer [rows,cols,channels] = size(im); for chan = 1:channels im(1:b,:,chan) = v; im(end-b+1:end,:,chan) = v; im(:,1:b,chan) = v; im(:,end-b+1:end,chan) = v; end
github
jacksky64/imageProcessing-master
shi_tomasi.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/shi_tomasi.m
5,131
utf_8
af81f94ffce582e9531f9618ded6de3f
% SHI_TOMASI - Shi - Tomasi corner detector % % Usage: cim = shi_tomasi(im, sigma) % [cim, r, c] = shi_tomasi(im, sigma, keyword-value options...) % % Required arguments: % im - Image to be processed. % sigma - Standard deviation of smoothing Gaussian used to sum % the derivatives when forming the structure tensor. Typical % values to use might be 1-3. % % Optional keyword - value arguments for performing non-maxima suppression: % % 'radius' - Radius of region considered in non-maximal % suppression. Typical values to use might % be 1-3 pixels. Default is 1. % 'thresh' - Threshold, only features with value greater than % threshold are returned. Default is 1. % 'N' - Maximum number of features to return. In this case the % N strongest features with value above 'thresh' are % returned. Default is Inf. % 'subpixel' - If set to true features are localised to subpixel % precision. Default is false. % 'display' - Optional flag true/false. If true the detected corners % are overlayed on the input image. This can be useful % for parameter tuning. Default is false. % % Returns: % cim - Corner strength image. % r - Row coordinates of corner points. % c - Column coordinates of corner points. % % With only 'im' and 'sigma' supplied as arguments only 'cim' is returned % as a raw corner strength image. You may then want to look at the values % within 'cim' to determine the appropriate threshold value to use. % % If any of the optional keyword - value arguments for performing non-maxima % suppression are specified then the feature coordinate locations are also % returned. % % Example: To get the 100 strongest features and display the detected points % on the input image use: % >> [cim, r, c] = shi_tomasi(im, 1, 'N', 100, 'display', true); % % The Shi - Tomasi measure returns the minimum eigenvalue of the structure % tensor. This represents the ideal that the Harris and Noble detectors attempt % to approximate. Back in 1988 Harris wanted to avoid the computational cost of % taking a square root when computing features. This is no longer relevant % today! % % See also: HARRIS, NOBLE, HESSIANFEATURES, NONMAXSUPPTS, DERIVATIVE5 % Reference: % J. Shi and C. Tomasi. "Good Features to Track,". 9th IEEE Conference on % Computer Vision and Pattern Recognition. 1994. % Copyright (c) 2016 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % January 2016 - Original version function [cim, r, c] = shi_tomasi(im, sigma, varargin) if ~isa(im,'double') im = double(im); end % Compute derivatives and the elements of the structure tensor. [Ix, Iy] = derivative5(im, 'x', 'y'); Ix2 = gaussfilt(Ix.^2, sigma); Iy2 = gaussfilt(Iy.^2, sigma); Ixy = gaussfilt(Ix.*Iy, sigma); T = Ix2 + Iy2; % trace D = Ix2.*Iy2 - Ixy.^2; % determinant % The two eigenvalues of the 2x2 structure tensor are: % L1 = T/2 + sqrt(T.^2/4 - D) % L2 = T/2 - sqrt(T.^2/4 - D) % We just want the minimum eigenvalue cim = T/2 - sqrt(T.^2/4 - D); if ~isempty(varargin) [thresh, radius, N, subpixel, disp] = checkargs(varargin); if disp [r,c] = nonmaxsuppts(cim, 'thresh', thresh, 'radius', radius, 'N', N, ... 'subpixel', subpixel, 'im', im); else [r,c] = nonmaxsuppts(cim, 'thresh', thresh, 'radius', radius, 'N', N, ... 'subpixel', subpixel, 'im', []); end else r = []; c = []; end %--------------------------------------------------------------- function [thresh, radius, N, subpixel, display] = checkargs(v) p = inputParser; p.CaseSensitive = false; % Define optional parameter-value pairs and their defaults addParameter(p, 'thresh', 0, @isnumeric); addParameter(p, 'radius', 1, @isnumeric); addParameter(p, 'N', Inf, @isnumeric); addParameter(p, 'subpixel', false, @islogical); addParameter(p, 'display', false, @islogical); parse(p, v{:}); thresh = p.Results.thresh; radius = p.Results.radius; N = p.Results.N; subpixel = p.Results.subpixel; display = p.Results.display;
github
jacksky64/imageProcessing-master
integralfilter.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/integralfilter.m
3,939
utf_8
ec95f49a7ef5558aefe8fd9a4309c358
% INTEGRALFILTER - performs filtering using an integral image % % This function exploits an integral image to perform filtering operations % (using rectangular filters) on an image in time that only depends on the % image size irrespective of the filter size. % % Usage: fim = integralfilter(intim, f) % % Arguments: intim - An integral image computed using INTEGRALIMAGE. % f - An n x 5 array defining the filter (see below). % % Returns: fim - The filtered image. % % % Defining Filters: f is a n x 5 array in the following form % [ r1 c1 r2 c2 v % r1 c1 r2 c2 v % r1 c1 r2 c2 v % ....... ] % % Where (r1 c1) and (r2 c2) are the row and column coordinates defining the % top-left and bottom-right corners of a rectangular region of the filter % (inclusive) and v is the value to be associated with that region of the % filter. The row and column coordinates of the rectangular region are defined % with respect to the reference point of the filter, typically its centre. % % Examples: % f = [-3 -3 3 3 1/49] % Defines a 7x7 averaging filter % % f = [-3 -3 3 -1 -1 % -3 1 3 3 1]; % Defines a differnce of boxes filter over a 7x7 % region where the left 7x3 region has a value % of -1, the right 7x3 region has a value of +1, % and the vertical line of pixels through the % centre have a (default) value of 0. % % If you want to check your filter design simply apply it to the integral image % of an image that is zero everywhere except for one pixel with a value of 1. % This will give you the impulse response/point spread function of your filter. % % Note under MATLAB the execution speed of this filtering code may not be any % faster than using imfilter (sadly). So in some sense this code is a bit % academic. However it is interesting that this interpreted code can perform % filtering at a speed that is comparable to the native code that is exectuted % via imfilter. Under Octave there may be useful speed gains. % % See also: INTEGRALIMAGE, INTEGAVERAGE, INTFILTTRANSPOSE % Reference: Paul Viola and Michael Jones, "Robust Real-Time Face Detection", % IJCV 57(2). pp 137-154. 2004. % Copyright (c) 2007 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % October 2007 function fim = integralfilter(intim, f) [rows, cols] = size(intim); fim = zeros(rows, cols); [nfilters, fcols] = size(f); if fcols ~= 5 error('Filters must be specified via an nx5 matrix'); end f(:,1:2) = f(:,1:2)-1; % Adjust the values of r1 and c1 to save addition % operations inside the loops below rmin = 1-min(f(:,1)); % Set loop bounds so that we do not try to rmax = rows - max(f(:,3)); % access values outside the image. cmin = 1-min(f(:,2)); cmax = cols - max(f(:,4)); for r = rmin:rmax for c = cmin:cmax for n = 1:nfilters fim(r,c) = fim(r,c) + f(n,5)*... (intim(r+f(n,3),c+f(n,4)) - intim(r+f(n,1),c+f(n,4)) ... - intim(r+f(n,3),c+f(n,2)) + intim(r+f(n,1),c+f(n,2))); end end end
github
jacksky64/imageProcessing-master
adaptivethresh.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/adaptivethresh.m
5,822
utf_8
bc7dac46afe55c2c4fb9c0add2d40792
% ADAPTIVETHRESH - Wellner's adaptive thresholding % % Thresholds an image using a threshold that is varied across the image relative % to the local mean, or median, at that point in the image. Works quite well on % text with shadows % % Usage: bw = adaptivethresh(im, fsize, t, filterType, thresholdMode) % % bw = adaptivethresh(im) (uses default parameter values) % % Arguments: im - Image to be thresholded. % % fsize - Filter size used to determine the local weighted mean % or local median. % - If the filterType is 'gaussian' fsize specifies the % standard deviation of Gaussian smoothing to be % applied. % - If the filterType is 'median' fsize specifies the % size of the window over which the local median is % calculated. % % The value for fsize should be large, around one tenth to % one twentieth of the image size. It defaults to one % twentieth of the maximum image dimension. % % t - Depending on the value of 'mode' this is the value % expressed as a percentage or fixed amount, relative to % the local average, or median grey value, below which % the local threshold is set. % Try values in the range -20 to +20. % Use +ve values to threshold dark objects against a % white background. Use -ve values if you are % thresholding white objects on a predominatly % dark background so that the local threshold is set % above the local mean/median. This parameter defaults to 15. % % filterType - Optional string specifying smoothing to be used % - 'gaussian' use Gaussian smoothing to obtain local % weighted mean as the local reference value for setting % the local threshold. This is the default % - 'median' use median filtering to obtain local reference % value for setting the local threshold % % thresholdMode - Optional string specifying the way the threshold is % defined. % - 'relative' the value of t represents the percentage, % relative to the local average grey value, below which % the local threshold is set. This is the default. % - 'fixed' the value of t represents the fixed grey level % relative to the local average grey value, below which % the local threshold is set. % % Note that in the 'relative' threshold mode the amount the % threshold differs from the local mean/median will vary in % proportion with the local mean/median. A small difference % from the local mean in the dark regions of the image will % be more significant than the same difference in a bright % portion of the image. This will match with human % perception. However this does mean that the results will % depend on the grey value origin and whether the image % is,say, negated. % % The implementation differs from Pierre Wellner's original adaptive % thresholding algorithm in that he calculated the local weighted mean just % along the row, or pairs of rows, in the image using a recursive filter. Here % we use symmetrical 2D Gaussian smoothing to calculate the local mean. This is % slower but more general. This code also offers the option of using median % filtering as a robust alternative to the mean (outliers will not influence the % result) and offers the option of using a fixed threshold relative to the % mean/median. Despite the potential advantage of median filtering being % more robust I find the output from using Gaussian filtering more pleasing. % % Reference: Pierre Wellner, "Adaptive Thresholding for the DigitalDesk" Rank % Xerox Technical Report EPC-1993-110 1993 % 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. % % August 2008 function bw = adaptivethresh(im, fsize, t, filterType, thresholdMode) % Set up default parameter values as needed if nargin < 2 fsize = fix(length(im)/20); end if nargin < 3 t = 15; end if nargin < 4 filterType = 'gaussian'; end if nargin < 5 thresholdMode = 'relative'; end % Apply Gaussian or median smoothing if strncmpi(filterType, 'gaussian', 3) g = fspecial('gaussian', 6*fsize, fsize); fim = filter2(g, im); elseif strncmpi(filterType, 'median', 3) fim = medfilt2(im, [fsize fsize], 'symmetric'); else error('Filtertype must be ''gaussian'' or ''median'' '); end % Finally apply the threshold if strncmpi(thresholdMode,'relative',3) bw = im > fim*(1-t/100); elseif strncmpi(thresholdMode,'fixed',3) bw = im > fim-t; else error('mode must be ''relative'' or ''fixed'' '); end
github
jacksky64/imageProcessing-master
featureorient.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/featureorient.m
4,226
utf_8
a6493ad9d0ee982914e92bc8b1e31ce3
% FEATUREORIENT - Estimates the local orientation of features in an edgeimage % % Usage: orientim = featureorient(im, gradientsigma,... % blocksigma, ... % orientsmoothsigma, ... % radians) % % Arguments: im - A normalised input image. % gradientsigma - Sigma of the derivative of Gaussian % used to compute image gradients. This can % be 0 as the derivatives are calculaed with % a 5-tap filter. % blocksigma - Sigma of the Gaussian weighting used to % form the local weighted sum of gradient % covariance data. A small value around 1, % or even less, is usually fine on most % feature images. % orientsmoothsigma - Sigma of the Gaussian used to smooth % the final orientation vector field. % Optional: if ommitted it defaults to 0 % radians - Optional flag 0/1 indicating whether the % output should be given in radians. Defaults % to 0 (degrees) % % Returns: orientim - The orientation image in degrees/radians % range is (0 - 180) or (0 - pi). % Orientation values are +ve anti-clockwise % and give the orientation across the feature % ridges % % The intended application of this function is to compute orientations on a % feature image prior to nonmaximal suppression in the case where no orientation % information is available from the feature detection process. Accordingly % the default output is in degrees to suit NONMAXSUP. % % See also: NONMAXSUP, RIDGEORIENT % Copyright (c) 1996-2013 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % May 2013 Adapted from RIDGEORIENT function or = featureorient(im, gradientsigma, blocksigma, orientsmoothsigma, ... radians) if ~exist('orientsmoothsigma', 'var'), orientsmoothsigma = 0; end if ~exist('radians', 'var'), radians = 0; end [rows,cols] = size(im); im = gaussfilt(im, gradientsigma); % Smooth the image. [Gx, Gy] = derivative5(im,'x','y'); % Get derivatives. Gy = -Gy; % Negate Gy to give +ve anticlockwise angles. % 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. Gxx = gaussfilt(Gxx, blocksigma); Gxy = 2*gaussfilt(Gxy, blocksigma); Gyy = gaussfilt(Gyy, blocksigma); % 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 cos2theta = gaussfilt(cos2theta, orientsmoothsigma); % Smoothed sine and cosine of sin2theta = gaussfilt(sin2theta, orientsmoothsigma); % doubled angles end or = atan2(sin2theta,cos2theta)/2; or(or<0) = or(or<0)+pi; % Map angles to 0-pi. if ~radians % Convert to degrees. or = or*180/pi; end
github
jacksky64/imageProcessing-master
cleanupregions.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/cleanupregions.m
5,516
utf_8
c5b7d4595fd7df10edbce6cbb7cc912e
% CLEANUPREGIONS Cleans up small segments in an image of segmented regions % % Usage: [seg, Am] = cleanupregions(seg, areaThresh, connectivity) % % Arguments: seg - A region segmented image, such as might be produced by a % graph cut algorithm. All pixels in each region are labeled % by an integer. % areaThresh - Regions below this area in pixels will be merged with an % adjacent segment. I find a value of about 1/20th of the % expected mean segment area, or 1/1000th of the image area % usually looks 'about right'. % connectivity - Specify 8 or 4 connectivity. If not specified 8 % connectivity is assumed. % % Note that regions with a label of 0 are ignored. These are treated as % privileged 'background regions' and are untouched. If you want these % regions to be considered you should assign a new positive label to these % areas using, say % >> L(L==0) = max(L(:)) + 1; % % Returns: seg - The updated segment image. % Am - Adjacency matrix of segments. Am(i, j) indicates whether % segments labeled i and j are connected/adjacent % % Typical application: % If a graph cut or superpixel algorithm fails to converge stray segments % can be left in the result. This function tries to clean things up by: % 1) Checking there is only one region for each segment label. If there is more % than one region they are given unique labels. % 2) Eliminating regions below a specified size and assigning them a label of an % adjacent region. % % See also: MCLEANUPREGIONS, REGIONADJACENCY, RENUMBERREGIONS % Copyright (c) 2010 Peter Kovesi % Centre for Exploration Targeting % School of Earth and Environment % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % % October 2010 - Original version % February 2013 - Connectivity choice, function returns adjacency matrix. function [seg, Am] = cleanupregions(seg, areaThresh, connectivity, prioritySeg) if ~exist('connectivity','var'), connectivity = 8; end if ~exist('prioritySeg','var'), prioritySeg = -1; end % 1) Ensure every segment is distinct but do not touch segments with a % label of 0 labels = unique(seg(:))'; maxlabel = max(labels); labels = setdiff(labels,0); % Remove 0 from the label list for l = labels [bl,num] = bwlabel(seg==l, connectivity); if num > 1 % We have more than one region with the same label for n = 2:num maxlabel = maxlabel+1; % Generate a new label seg(bl==n) = maxlabel; % and assign to this segment end end end if areaThresh % 2) Merge segments with small areas stat = regionprops(seg,'area'); % Get segment areas area = cat(1, stat.Area); Am = regionadjacency(seg); % Get adjacency matrix labels = unique(seg(:))'; labels = setdiff(labels,0); % Remove 0 from the label list for n = labels if ~isnan(area(n)) && area(n) < areaThresh % Find regions adjacent to n and keep merging with the first element % in the adjacency list until we obtain an area >= areaThresh, % or we run out of regions to merge. ind = find(Am(n,:)); while ~isempty(ind) && area(n) < areaThresh if ismember(prioritySeg, ind) [seg, Am, area] = mergeregions(n, prioritySeg, seg, Am, area); prioritySeg = n; else [seg, Am, area] = mergeregions(n, ind(1), seg, Am, area); end ind = find(Am(n,:)); % (The adjacency matrix will have changed) end end end end % 3) As some regions will have been absorbed into others and no longer exist % we now renumber the regions so that they sequentially increase from 1. % We also need to reconstruct the adjacency matrix to reflect the reduced % number of regions and their relabeling [seg, minLabel, maxLabel] = renumberregions(seg); Am = regionadjacency(seg); %------------------------------------------------------------------- % Function to merge segment s2 into s1 % The segment image, Adjacency matrix and area arrays are updated. % We could make this a nested function for efficiency but then it would not % run under Octave. function [seg, Am, area] = mergeregions(s1, s2, seg, Am, area) if s1==s2 fprintf('s1 == s2!\n') return end % The area of s1 is now that of s1 and s2 area(s1) = area(s1)+area(s2); area(s2) = NaN; % s1 inherits the adjacancy matrix entries of s2 Am(s1,:) = Am(s1,:) | Am(s2,:); Am(:,s1) = Am(:,s1) | Am(:,s2); Am(s1,s1) = 0; % Ensure s1 is not connected to itself % Disconnect s2 from the adjacency matrix Am(s2,:) = 0; Am(:,s2) = 0; % Relabel s2 with s1 in the segment image seg(seg==s2) = s1;
github
jacksky64/imageProcessing-master
subpix2d.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/subpix2d.m
4,179
utf_8
9130e8af913300cae8a4eec009fb10af
% SUBPIX2D Sub-pixel locations in 2D image % % Usage: [rs, cs] = subpix2d(r, c, L); % % Arguments: % r, c - row, col vectors of extrema to pixel precision. % L - 2D corner image % % Returns: % rs, cs - row, col vectors of valid extrema to sub-pixel % precision. % % Note that the number of sub-pixel extrema returned can be less than the number % of integer precision extrema supplied. Any computed sub-pixel location that % is more than 0.5 pixels from the initial integer location is rejected. The % reasoning is that this implies that the extrema should be centred on a % neighbouring pixel, but this is inconsistent with the assumption that the % input data represents extrema locations to pixel precision. % % The sub-pixel locations are solved by forming a Taylor series representation % of the corner image values in the vicinity of each integer location extrema % % L(x) = L + dL/dx' x + 1/2 x' d2L/dx2 x % % x represents a position relative to the integer location of the extrema. This % gives us a quadratic and we solve for the location where the gradient is zero % - these are the extrema locations to sub-pixel precision % % Reference: Brown and Lowe "Invariant Features from Interest Point Groups" % BMVC 2002 pp 253-262 % % See also: SUBPIX3D % ** I am not entirely satisfied with the output of this function. Perhaps using % finite differences for derivative calculation is a problem, try using Farid % and Simoncelli's approach? ** % Copyright (c) 2010 Peter Kovesi % Centre for Exploration Targeting % School of Earth and Environment % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % July 2010 function [rs, cs] = subpix2d(R, C, L) if ndims(L) == 3 error('Corner image must be grey scale'); end [rows, cols] = size(L); x = zeros(2, length(R)); % Buffer for storing sub-pixel locations m = 0; % Counter for valid extrema for n = 1:length(R) r = R(n); % Convenience variables c = C(n); % If coords are too close to boundary skip if r < 2 || c < 2 || ... r > rows-1 || c > cols-1 continue end % Compute partial derivatives via finite differences % 1st derivatives dLdr = (L(r+1,c) - L(r-1,c))/2; dLdc = (L(r,c+1) - L(r,c-1))/2; D = [dLdr; dLdc]; % Column vector of derivatives % 2nd Derivatives d2Ldr2 = L(r+1,c) - 2*L(r,c) + L(r-1,c); d2Ldc2 = L(r,c+1) - 2*L(r,c) + L(r,c-1); d2Ldrdc = (L(r+1,c+1) - L(r+1,c-1) - L(r-1,c+1) + L(r-1,c-1))/4; % Form Hessian from 2nd derivatives H = [d2Ldr2 d2Ldrdc d2Ldrdc d2Ldc2 ]; % Solve for location where gradients are zero - these are the extrema % locations to sub-pixel precision if rcond(H) < eps continue; % Skip to next point % warning('Hessian is singular'); else dx = -H\D; % dx is location relative to centre pixel % Check solution is within 0.5 pixels of centre. A solution % outside of this implies that the extrema should be centred on a % neighbouring pixel, but this is inconsistent with the % assumption that the input data represents extrema locations to % pixel precision. Hence these points are rejected % if all(abs(dx) <= 0.5) m = m + 1; x(:,m) = [r;c] + dx; % end end end % Extract the subpixel row and column values from x noting we just % have m valid extrema. rs = x(1, 1:m); cs = x(2, 1:m);
github
jacksky64/imageProcessing-master
filterregionproperties.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/filterregionproperties.m
3,359
utf_8
269f01ad39e5f78d6ef590d56473ad58
% FILTERREGIONPROPERTIES Filters regions on their property values % % Usage: bw = filterregionproperties(bw, {property, fn, value}, { ... } ) % % Arguments: % bw - Binary image % {property, fn, value} - 3-element cell array consisting of: % property - String matching one of the properties % computed by REGIONPROPS. % fn - Handle to a function that will compare % the region property to a % value. Typically @lt or @gt. % value - The value that the region property is % compared against % % You can specify multiple {property, fn, value} cell arrays in the argument % list. Blobs/regions in the binary image that satisfy all the specified % constaints are retained in the image. % % Examples: % % Retain blobs that have an area greater than 50 pixels % >> bw = filterregionproperties(bw, {'Area', @gt, 50}); % % Retain blobs with an area less than 20 and having a major axis orientation % that is greater than 0 % >> bw = filterregionproperties(bw, {'Area', @lt, 20}, {'Orientation', @gt, 0}); % % See also: REGIONPROPS % Copyright (c) 2013 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % PK May 2013 function bw = filterregionproperties(bw, varargin) varargin = varargin(:); % Form separate cell arrays of the properties, functions and values, % and perform basic check of datatypes nOps = length(varargin); property = cell(nOps,1); fn = cell(nOps,1); value = cell(nOps,1); for m = 1:nOps if length(varargin{m}) ~= 3 error('Property, function and value must be a 3 element cell array'); end property{m} = varargin{m}{1}; fn{m} = varargin{m}{2}; value{m} = varargin{m}{3}; if ~ischar(property{m}) error('Property must be a string'); end if ~strcmp(class(fn{m}), 'function_handle') error('Invalid function handle'); end end [L, N] = bwlabel(bw); % Label image s = regionprops(L, property); % Get region properties % Form a table indicating which labeled region should be zeroed out on % the basis that its properties do not satisfy the % property-function-value requirements table = ones(N,1); for n = 1:N for m = 1:nOps if ~feval(fn{m}, s(n).(property{m}), value{m}); table(n) = 0; end end end % Step through the binary image applying the table to zero out the % appropriate blobs for n = 1:numel(bw) if bw(n) bw(n) = table(L(n)); end end
github
jacksky64/imageProcessing-master
intfilttranspose.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/intfilttranspose.m
1,102
utf_8
0007e26379314049c0716d1ff851e36c
% INTFILTTRANSPOSE - transposes an integral filter % % Usage: ft = intfilttranspose(f) % % Argument: f - an integral image filter as described in the function INTEGRALFILTER % % Returns: ft - a transposed version of the filter % % See also: INTEGRALFILTER, INTEGRALIMAGE, INTEGAVERAGE % Copyright (c) 2007 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % October 2007 function ft = intfilttranspose(f) [nfilt, dum] = size(f); ft = f; for n = 1:nfilt ft(n,1:4) = [f(n,2) -f(n,3) f(n,4) -f(n,1)]; end
github
jacksky64/imageProcessing-master
makeregionsdistinct.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/makeregionsdistinct.m
2,142
utf_8
87ec3511235a3eefd60cffbc8135de46
% MAKEREGIONSDISTINCT Ensures labeled segments are distinct % % Usage: [seg, maxlabel] = makeregionsdistinct(seg, connectivity) % % Arguments: seg - A region segmented image, such as might be produced by a % superpixel or graph cut algorithm. All pixels in each % region are labeled by an integer. % connectivity - Optional parameter indicating whether 4 or 8 connectedness % should be used. Defaults to 4. % % Returns: seg - A labeled image where all segments are distinct. % maxlabel - Maximum segment label number. % % Typical application: A graphcut or superpixel algorithm may terminate in a few % cases with multiple regions that have the same label. This function % identifies these regions and assigns a unique label to them. % % See also: SLIC, CLEANUPREGIONS, RENUMBERREGIONS % Copyright (c) 2013 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % June 2013 function [seg, maxlabel] = makeregionsdistinct(seg, connectivity) if ~exist('connectivity', 'var'), connectivity = 4; end % Ensure every segment is distinct but do not touch segments % with a label of 0 labels = unique(seg(:))'; maxlabel = max(labels); labels = setdiff(labels,0); % Remove 0 from the label list for l = labels [bl,num] = bwlabel(seg==l, connectivity); if num > 1 % We have more than one region with the same label for n = 2:num maxlabel = maxlabel+1; % Generate a new label seg(bl==n) = maxlabel; % and assign to this segment end end end
github
jacksky64/imageProcessing-master
mcleanupregions.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/mcleanupregions.m
4,352
utf_8
956767ca7a2a6d8f168c2b2ab86d64f9
% MCLEANUPREGIONS Morphological clean up of small segments in an image of segmented regions % % Usage: [seg, Am] = mcleanupregions(seg, seRadius) % % Arguments: seg - A region segmented image, such as might be produced by a % graph cut algorithm. All pixels in each region are labeled % by an integer. % seRadius - Structuring element radius. This can be set to 0 in which % case the function will simply ensure all labeled regions % are distinct and relabel them if necessary. % % Returns: seg - The updated segment image. % Am - Adjacency matrix of segments. Am(i, j) indicates whether % segments labeled i and j are connected/adjacent % % Typical application: % If a graph cut or superpixel algorithm fails to converge stray segments % can be left in the result. This function tries to clean things up by: % 1) Checking there is only one region for each segment label. If there is % more than one region they are given unique labels. % 2) Eliminating regions below the structuring element size % % Note that regions labeled 0 are treated as a 'privileged' background region % and is not processed/affected by the function. % % See also: REGIONADJACENCY, RENUMBERREGIONS, CLEANUPREGIONS, MAKEREGIONSDISTINCT % Copyright (c) 2013 Peter Kovesi % Centre for Exploration Targeting % School of Earth and Environment % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % % March 2013 % June 2013 Improved morphological cleanup process using distance map function [seg, Am, mask] = mcleanupregions(seg, seRadius) option = 2; % 1) Ensure every segment is distinct [seg, maxlabel] = makeregionsdistinct(seg); % 2) Perform a morphological opening on each segment, subtract the opening % from the orignal segment to obtain regions to be reassigned to % neighbouring segments. if seRadius se = circularstruct(seRadius); % Accurate and not noticeably slower % if radius is small % se = strel('disk', seRadius, 4); % Use approximated disk for speed mask = zeros(size(seg)); if option == 1 for l = 1:maxlabel b = seg == l; mask = mask | (b - imopen(b,se)); end else % Rather than perform a morphological opening on every % individual region in sequence the following finds separate % lists of unconnected regions and performs openings on these. % Typically an image can be covered with only 5 or 6 lists of % unconnected regions. Seems to be about 2X speed of option % 1. (I was hoping for more...) list = finddisconnected(seg); for n = 1:length(list) b = zeros(size(seg)); for m = 1:length(list{n}) b = b | seg == list{n}(m); end mask = mask | (b - imopen(b,se)); end end % Compute distance map on inverse of mask [~, idx] = bwdist(~mask); % Assign a label to every pixel in the masked area using the label of % the closest pixel not in the mask as computed by bwdist seg(mask) = seg(idx(mask)); end % 3) As some regions will have been relabled, possibly broken into several % parts, or absorbed into others and no longer exist we ensure all regions % are distinct again, and renumber the regions so that they sequentially % increase from 1. We also need to reconstruct the adjacency matrix to % reflect the changed number of regions and their relabeling. seg = makeregionsdistinct(seg); [seg, minLabel, maxLabel] = renumberregions(seg); Am = regionadjacency(seg);
github
jacksky64/imageProcessing-master
integaverage.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/integaverage.m
2,088
utf_8
6ff6d948c4e18c25ee2d9269d186448c
% INTEGAVERAGE - performs averaging filtering using an integral image % % Usage: avim = integaverage(im,rad) % % Arguments: im - Image to be filtered % rad - 'Radius' of square region over which averaging is % performed (rad = 1 implies a 3x3 average) % Returns: avim - Averaged image % % See also: INTEGRALIMAGE, INTEGRALFILTER, INTFILTTRANSPOSE % Reference: Paul Viola and Michael Jones, "Robust Real-Time Face Detection", % IJCV 57(2). pp 137-154. 2004. % Copyright (c) 2007 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % October 2007 - Original version % September 2009 - Changed so that input is the image rather than its % integral image function avim = integaverage(im, rad) if rad == 0 % Trap case where averaging filter is 1x1 hence radius = 0 avim = im; return; end [rows, cols] = size(im); intim = integralimage(im); avim = zeros(rows, cols); % Fiddle with indices to ensure we calculate the average over a square % region that has an odd No of pixels on each side (ie has a centre pixel % located over each pixel of interest) down = rad; % offset to 'lower' indices up = down+1; % offset to 'upper' indices for r = 1+up:rows-down for c = 1+up:cols-down avim(r,c) = intim(r+down,c+down) - intim(r-up,c+down) ... - intim(r+down,c-up) + intim(r-up,c-up); end end avim = avim/(down+up)^2;
github
jacksky64/imageProcessing-master
subpix3d.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/subpix3d.m
4,434
utf_8
22fda4d036d1bac30b6b36da20187f7a
% SUBPIX3D Sub-pixel locations in 3D volume % % Usage: [rs, cs, ss] = subpix3d(r, c, s, L); % % Arguments: % r, c, s - row, col and scale vectors of extrema to pixel precision. % L - 3D volumetric corner data, or 2D + scale space data. % % Returns: % rs, cs, ss - row, col and scale vectors of valid extrema to sub-pixel % precision. % % Note that the number of sub-pixel extrema returned can be less than the number % of integer precision extrema supplied. Any computed sub-pixel location that % is more than 0.5 pixels from the initial integer location is rejected. The % reasoning is that this implies that the extrema should be centred on a % neighbouring pixel, but this is inconsistent with the assumption that the % input data represents extrema locations to pixel precision. % % The sub-pixel locations are solved by forming a Taylor series representation % of the scale-space values in the vicinity of each integer location extrema % % L(x) = L + dL/dx' x + 1/2 x' d2L/dx2 x % % x represents a position relative to the integer location of the extrema. This % gives us a quadratic and we solve for the location where the gradient is zero % - these are the extrema locations to sub-pixel precision % % Reference: Brown and Lowe "Invariant Features from Interest Point Groups" % BMVC 2002 pp 253-262 % % See also: SUBPIX2D % Copyright (c) 2010 Peter Kovesi % Centre for Exploration Targeting % School of Earth and Environment % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % July 2010 function [rs, cs, ss] = subpix3d(R, C, S, L) [rows, cols, scales] = size(L); x = zeros(3, length(R)); % Buffer for storing sub-pixel locations m = 0; % Counter for valid extrema for n = 1:length(R) r = R(n); % Convenience variables c = C(n); s = S(n); % If coords are too close to boundary skip if r < 2 || c < 2 || s < 2 || ... r > rows-1 || c > cols-1 || s > scales-1 continue end % Compute partial derivatives via finite differences % 1st derivatives dLdr = (L(r+1,c,s) - L(r-1,c,s))/2; dLdc = (L(r,c+1,s) - L(r,c-1,s))/2; dLds = (L(r,c,s+1) - L(r,c,s-1))/2; D = [dLdr; dLdc; dLds]; % Column vector of derivatives % 2nd Derivatives d2Ldr2 = L(r+1,c,s) - 2*L(r,c,s) + L(r-1,c,s); d2Ldc2 = L(r,c+1,s) - 2*L(r,c,s) + L(r,c-1,s); d2Lds2 = L(r,c,s+1) - 2*L(r,c,s) + L(r,c,s-1); d2Ldrdc = (L(r+1,c+1,s) - L(r+1,c-1,s) - L(r-1,c+1,s) + L(r-1,c-1,s))/4; d2Ldrds = (L(r+1,c,s+1) - L(r+1,c,s-1) - L(r-1,c,s+1) + L(r-1,c,s-1))/4; d2Ldcds = (L(r,c+1,s+1) - L(r,c+1,s-1) - L(r,c-1,s+1) + L(r,c-1,s-1))/4; % Form Hessian from 2nd derivatives H = [d2Ldr2 d2Ldrdc d2Ldrds d2Ldrdc d2Ldc2 d2Ldcds d2Ldrds d2Ldcds d2Lds2 ]; % Solve for location where gradients are zero - these are the extrema % locations to sub-pixel precision if rcond(H) < eps continue; % Skip to next point % warning('Hessian is singular'); else dx = -H\D; % dx is location relative to centre pixel % Check solution is within 0.5 pixels of centre. A solution % outside of this implies that the extrema should be centred on a % neighbouring pixel, but this is inconsistent with the % assumption that the input data represents extrema locations to % pixel precision. Hence these points are rejected if all(abs(dx) <= 0.5) m = m + 1; x(:,m) = [r;c;s] + dx; end end end % Extract the subpixel row, column and scale values from x noting we just % have m valid extrema. rs = x(1, 1:m); cs = x(2, 1:m); ss = x(3, 1:m);
github
jacksky64/imageProcessing-master
fastradial.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/fastradial.m
5,399
utf_8
b540902aad74684be591d3126ad87319
% FASTRADIAL - Loy and Zelinski's fast radial feature detector % % An implementation of Loy and Zelinski's fast radial feature detector % % Usage: S = fastradial(im, radii, alpha, beta) % % Arguments: % im - Image to be analysed % radii - Array of integer radius values to be processed % suggested radii might be [1 3 5] % alpha - Radial strictness parameter. % 1 - slack, accepts features with bilateral symmetry. % 2 - a reasonable compromise. % 3 - strict, only accepts radial symmetry. % ... and you can go higher % beta - Gradient threshold. Gradients below this threshold do % not contribute to symmetry measure, defaults to 0. % % Returns S - Symmetry map. Bright points with high symmetry are % marked with large positive values. Dark points of % high symmetry marked with large -ve values. % % To localize points use NONMAXSUPPTS on S, -S or abs(S) depending on % what you are seeking to find. % Reference: % Loy, G. Zelinsky, A. Fast radial symmetry for detecting points of % interest. IEEE PAMI, Vol. 25, No. 8, August 2003. pp 959-973. % Copyright (c) 2004-2010 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % November 2004 - original version % July 2005 - Bug corrected: magitude and orientation matrices were % not zeroed for each radius value used (Thanks to Ben % Jackson) % December 2009 - Gradient threshold added + minor code cleanup % July 2010 - Gradients computed via Farid and Simoncelli's 5 tap % derivative filters function [S, So] = fastradial(im, radii, alpha, beta, feedback) if ~exist('beta','var'), beta = 0; end if ~exist('feedback','var'), feedback = 0; end if any(radii ~= round(radii)) || any(radii < 1) error('radii must be integers and > 1') end [rows,cols]=size(im); % Compute derivatives in x and y via Farid and Simoncelli's 5 tap % derivative filters [imgx, imgy] = derivative5(im, 'x', 'y'); mag = sqrt(imgx.^2 + imgy.^2)+eps; % (+eps to avoid division by 0) % Normalise gradient values so that [imgx imgy] form unit % direction vectors. imgx = imgx./mag; imgy = imgy./mag; S = zeros(rows,cols); % Symmetry matrix So = zeros(rows,cols); % Orientation only symmetry matrix [x,y] = meshgrid(1:cols, 1:rows); for n = radii M = zeros(rows,cols); % Magnitude projection image O = zeros(rows,cols); % Orientation projection image % Coordinates of 'positively' and 'negatively' affected pixels posx = x + round(n*imgx); posy = y + round(n*imgy); negx = x - round(n*imgx); negy = y - round(n*imgy); % Clamp coordinate values to range [1 rows 1 cols] posx( posx<1 ) = 1; posx( posx>cols ) = cols; posy( posy<1 ) = 1; posy( posy>rows ) = rows; negx( negx<1 ) = 1; negx( negx>cols ) = cols; negy( negy<1 ) = 1; negy( negy>rows ) = rows; % Form the orientation and magnitude projection matrices for r = 1:rows for c = 1:cols if mag(r,c) > beta O(posy(r,c),posx(r,c)) = O(posy(r,c),posx(r,c)) + 1; O(negy(r,c),negx(r,c)) = O(negy(r,c),negx(r,c)) - 1; M(posy(r,c),posx(r,c)) = M(posy(r,c),posx(r,c)) + mag(r,c); M(negy(r,c),negx(r,c)) = M(negy(r,c),negx(r,c)) - mag(r,c); end end end % Clamp Orientation projection matrix values to a maximum of % +/-kappa, but first set the normalization parameter kappa to the % values suggested by Loy and Zelinski if n == 1, kappa = 8; else kappa = 9.9; end O(O > kappa) = kappa; O(O < -kappa) = -kappa; % Unsmoothed symmetry measure at this radius value F = M./kappa .* (abs(O)/kappa).^alpha; Fo = sign(O) .* (abs(O)/kappa).^alpha; % Orientation only based measure % Smooth and spread the symmetry measure with a Gaussian proportional to % n. Also scale the smoothed result by n so that large scales do not % lose their relative weighting. S = S + gaussfilt(F, 0.25*n) * n; So = So + gaussfilt(Fo, 0.25*n) * n; end % for each radius S = S /length(radii); % Average So = So/length(radii);
github
jacksky64/imageProcessing-master
maskimage.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/maskimage.m
1,122
utf_8
189c1feb312b970fdf4e22824ef53747
% MASKIMAGE Apply mask to image % % Usage: maskedim = maskimage(im, mask, col) % % Arguments: im - Image to be masked % mask - Binary masking image % col - Value/colour to be applied to regions where mask == 1 % If im is a colour image col can be a 3-vector % specifying the colour values to be applied. % % Returns: maskedim - The masked image % % See also; DRAWREGIONBOUNDARIES % Peter Kovesi % Centre for Exploration Targeting % School of Earth and Environment % The University of Western Australia % peter.kovesi at uwa edu au % % Feb 2013 function maskedim = maskimage(im, mask, col) [rows,cols, chan] = size(im); % Set default colour to 0 (black) if ~exist('col', 'var'), col = 0; end % Ensure col has same length as image depth. if length(col) == 1 col = repmat(col, [chan 1]); else assert(length(col) == chan); end % Perform masking maskedim = im; for n = 1:chan tmp = maskedim(:,:,n); tmp(mask) = col(n); maskedim(:,:,n) = tmp; end
github
jacksky64/imageProcessing-master
impad.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/impad.m
1,134
utf_8
5b51ac5f58f9a48d78c3468799786d4c
% IMPAD - adds zeros to the boundary of an image % % Usage: paddedim = impad(im, b, v) % % Arguments: im - Image to be padded (greyscale or colour) % b - Width of padding boundary to be added % v - Optional padding value if you do not want it to be 0. % % Returns: paddedim - Padded image of size rows+2*b x cols+2*b % % See also: IMTRIM, IMSETBORDER % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % June 2010 % January 2011 Added optional padding value function pim = impad(im, b, v) assert(b >= 1, 'Padding size must be >= 1') if ~exist('v', 'var'), v = 0; end b = round(b); % Ensure integer [rows, cols, channels] = size(im); if nargin == 3 pim = v*ones(rows+2*b, cols+2*b, channels, class(im)); else if islogical(im) pim = logical(zeros(rows+2*b, cols+2*b, channels, 'uint8')); else pim = zeros(rows+2*b, cols+2*b, channels, class(im)); end end pim(1+b:rows+b, 1+b:cols+b, 1:channels) = im;
github
jacksky64/imageProcessing-master
finddisconnected.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/finddisconnected.m
2,563
utf_8
3e7d83e1dd00f59f9bd54fe42b93428b
% FINDDISCONNECTED find groupings of disconnected labeled regions % % Usage: list = finddisconnected(l) % % Argument: l - A labeled image segmenting an image into regions, such as % might be produced by a graph cut or superpixel algorithm. % All pixels in each region are labeled by an integer. % % Returns: list - A cell array of lists of regions that are not % connected. Typically there are 5 to 6 lists. % % Used by MCLEANUPREGIONS to reduce the number of morphological closing % operations % % See also: MCLEANUPREGIONS, REGIONADJACENCY % Copyright (c) 2013 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % PK July 2013 function list = finddisconnected(l) debug = 0; [Am, Al] = regionadjacency(l); N = max(l(:)); % number of labels % Array for keeping track of visited labels visited = zeros(N,1); list = {}; listNo = 0; for n = 1:N if ~visited(n) listNo = listNo + 1; list{listNo} = n; visited(n) = 1; % Find all regions not directly connected to n and not visited notConnected = setdiff(find(~Am(n,:)), find(visited)); % For each unconnected region check that it is not already % connected to a region in the list. If not, add to list for m = notConnected if isempty(intersect(Al{m}, list{listNo})) list{listNo} = [list{listNo} m]; visited(m) = 1; end end end % if not visited(n) end % Display each list of unconncted regions as an image if debug for n = 1:length(list) mask = zeros(size(l)); for m = 1:length(list{n}) mask = mask | l == list{n}(m); end fprintf('list %d of %d length %d \n', n, length(list), length(list{n})) show(mask); keypause end end
github
jacksky64/imageProcessing-master
gaussfilt.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/gaussfilt.m
1,114
utf_8
4e021d34f436d86073a1a4fcb135b2b7
% GAUSSFILT - Small wrapper function for convenient Gaussian filtering % % Usage: smim = gaussfilt(im, sigma) % % Arguments: im - Image to be smoothed. % sigma - Standard deviation of Gaussian filter. % % Returns: smim - Smoothed image. % % If called with sigma = 0 the function immediately returns with im assigned % to smim % % See also: INTEGGAUSSFILT % Peter Kovesi % Centre for Explortion Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % March 2010 % June 2013 - Provision for multi-channel images function smim = gaussfilt(im, sigma) if sigma < eps smim = im; return; end % If needed convert im to double if ~strcmp(class(im),'double') im = double(im); end sze = max(ceil(6*sigma), 1); if ~mod(sze,2) % Ensure filter size is odd sze = sze+1; end h = fspecial('gaussian', [sze sze], sigma); % Apply filter to all image channels smim = zeros(size(im)); for n = 1:size(im,3) smim(:,:,n) = filter2(h, im(:,:,n)); end
github
jacksky64/imageProcessing-master
noble.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/noble.m
5,562
utf_8
5edfd0d0dceb4dad2a92712a2be8f5f6
% NOBLE - Noble's corner detector % % Usage: cim = noble(im, sigma) % [cim, r, c] = noble(im, sigma, keyword-value options...) % % Required arguments: % im - Image to be processed. % sigma - Standard deviation of smoothing Gaussian used to sum % the derivatives when forming the structure tensor. Typical % values to use might be 1-3. % % Optional keyword - value arguments for performing non-maxima suppression: % % 'radius' - Radius of region considered in non-maximal % suppression. Typical values to use might % be 1-3 pixels. Default is 1. % 'thresh' - Threshold, only features with value greater than % threshold are returned. Default is 1. % 'N' - Maximum number of features to return. In this case the % N strongest features with value above 'thresh' are % returned. Default is Inf. % 'subpixel' - If set to true features are localised to subpixel % precision. Default is false. % 'display' - Optional flag true/false. If true the detected corners % are overlayed on the input image. This can be useful % for parameter tuning. Default is false. % % Returns: % cim - Corner strength image. % r - Row coordinates of corner points. % c - Column coordinates of corner points. % % With only 'im' and 'sigma' supplied as arguments only 'cim' is returned as a % raw corner strength image. You may then want to look at the values within % 'cim' to determine the appropriate threshold value to use. Note that the Noble % and Harris corner strength varies with the intensity gradient raised to the % 4th power. Small changes in input image contrast result in huge changes in % the appropriate threshold. % % If any of the optional keyword - value arguments for performing non-maxima % suppression are specified then the feature coordinate locations are also % returned. % % Example: To get the 100 strongest features and display the detected points % on the input image use: % >> [cim, r, c] = noble(im, 1, 'N', 100, 'display', true); % % Note that Noble's corner measure is det(M)/trace(M) where M is the stucture % tensor. In comparision, the Harris measure is det(M) - k trace^2(M), where k % is a parameter you have to set (traditionally k = 0.04). Noble's measure % avoids the need to set a parameter k and to my mind is much more satisfactory. % However the Shi-Tomasi measure is probably what one really wants. % % See also: HARRIS, SHI_TOMASI, HESSIANFEATURES, NONMAXSUPPTS, DERIVATIVE5 % References: % C.G. Harris and M.J. Stephens. "A combined corner and edge detector", % Proceedings Fourth Alvey Vision Conference, Manchester. % pp 147-151, 1988. % % Alison Noble, "Descriptions of Image Surfaces", PhD thesis, Department % of Engineering Science, Oxford University 1989, p45. % Copyright (c) 2002-2016 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % March 2002 - Original version % December 2002 - Updated comments % August 2005 - Changed so that code calls nonmaxsuppts % August 2010 - Changed to use Farid and Simoncelli's derivative filters % January 2016 - Noble made distinct from the Harris function function [cim, r, c] = noble(im, sigma, varargin) if ~isa(im,'double') im = double(im); end % Compute derivatives and the elements of the structure tensor. [Ix, Iy] = derivative5(im, 'x', 'y'); Ix2 = gaussfilt(Ix.^2, sigma); Iy2 = gaussfilt(Iy.^2, sigma); Ixy = gaussfilt(Ix.*Iy, sigma); % Compute Noble's corner measure. cim = (Ix2.*Iy2 - Ixy.^2)./(Ix2 + Iy2 + eps); if length(varargin) > 0 [thresh, radius, N, subpixel, disp] = checkargs(varargin); if disp [r,c] = nonmaxsuppts(cim, 'thresh', thresh, 'radius', radius, 'N', N, ... 'subpixel', subpixel, 'im', im); else [r,c] = nonmaxsuppts(cim, 'thresh', thresh, 'radius', radius, 'N', N, ... 'subpixel', subpixel, 'im', []); end else r = []; c = []; end %--------------------------------------------------------------- function [thresh, radius, N, subpixel, disp] = checkargs(v) p = inputParser; p.CaseSensitive = false; % Define optional parameter-value pairs and their defaults addParameter(p, 'thresh', 0, @isnumeric); addParameter(p, 'radius', 1, @isnumeric); addParameter(p, 'N', Inf, @isnumeric); addParameter(p, 'subpixel', false, @islogical); addParameter(p, 'display', false, @islogical); parse(p, v{:}); thresh = p.Results.thresh; radius = p.Results.radius; N = p.Results.N; subpixel = p.Results.subpixel; disp = p.Results.display;
github
jacksky64/imageProcessing-master
derivative5.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/derivative5.m
4,808
utf_8
989b39a3f681a8cad7375573fa1a7a0f
% DERIVATIVE5 - 5-Tap 1st and 2nd discrete derivatives % % This function computes 1st and 2nd derivatives of an image using the 5-tap % coefficients given by Farid and Simoncelli. The results are significantly % more accurate than MATLAB's GRADIENT function on edges that are at angles % other than vertical or horizontal. This in turn improves gradient orientation % estimation enormously. If you are after extreme accuracy try using DERIVATIVE7. % % Usage: [gx, gy, gxx, gyy, gxy] = derivative5(im, derivative specifiers) % % Arguments: % im - Image to compute derivatives from. % derivative specifiers - A comma separated list of character strings % that can be any of 'x', 'y', 'xx', 'yy' or 'xy' % These can be in any order, the order of the % computed output arguments will match the order % of the derivative specifier strings. % Returns: % Function returns requested derivatives which can be: % gx, gy - 1st derivative in x and y % gxx, gyy - 2nd derivative in x and y % gxy - 1st derivative in y of 1st derivative in x % % Examples: % Just compute 1st derivatives in x and y % [gx, gy] = derivative5(im, 'x', 'y'); % % Compute 2nd derivative in x, 1st derivative in y and 2nd derivative in y % [gxx, gy, gyy] = derivative5(im, 'xx', 'y', 'yy') % % See also: DERIVATIVE7 % Reference: Hany Farid and Eero Simoncelli "Differentiation of Discrete % Multi-Dimensional Signals" IEEE Trans. Image Processing. 13(4): 496-508 (2004) % Copyright (c) 2010 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % % April 2010 function varargout = derivative5(im, varargin) varargin = varargin(:); varargout = cell(size(varargin)); % Check if we are just computing 1st derivatives. If so use the % interpolant and derivative filters optimized for 1st derivatives, else % use 2nd derivative filters and interpolant coefficients. % Detection is done by seeing if any of the derivative specifier % arguments is longer than 1 char, this implies 2nd derivative needed. secondDeriv = false; for n = 1:length(varargin) if length(varargin{n}) > 1 secondDeriv = true; break end end if ~secondDeriv % 5 tap 1st derivative cofficients. These are optimal if you are just % seeking the 1st deriavtives p = [0.037659 0.249153 0.426375 0.249153 0.037659]; d1 =[0.109604 0.276691 0.000000 -0.276691 -0.109604]; else % 5-tap 2nd derivative coefficients. The associated 1st derivative % coefficients are not quite as optimal as the ones above but are % consistent with the 2nd derivative interpolator p and thus are % appropriate to use if you are after both 1st and 2nd derivatives. p = [0.030320 0.249724 0.439911 0.249724 0.030320]; d1 = [0.104550 0.292315 0.000000 -0.292315 -0.104550]; d2 = [0.232905 0.002668 -0.471147 0.002668 0.232905]; end % Compute derivatives. Note that in the 1st call below MATLAB's conv2 % function performs a 1D convolution down the columns using p then a 1D % convolution along the rows using d1. etc etc. gx = false; for n = 1:length(varargin) if strcmpi('x', varargin{n}) varargout{n} = conv2(p, d1, im, 'same'); gx = true; % Record that gx is available for gxy if needed gxn = n; elseif strcmpi('y', varargin{n}) varargout{n} = conv2(d1, p, im, 'same'); elseif strcmpi('xx', varargin{n}) varargout{n} = conv2(p, d2, im, 'same'); elseif strcmpi('yy', varargin{n}) varargout{n} = conv2(d2, p, im, 'same'); elseif strcmpi('xy', varargin{n}) | strcmpi('yx', varargin{n}) if gx varargout{n} = conv2(d1, p, varargout{gxn}, 'same'); else gx = conv2(p, d1, im, 'same'); varargout{n} = conv2(d1, p, gx, 'same'); end else error(sprintf('''%s'' is an unrecognized derivative option',varargin{n})); end end
github
jacksky64/imageProcessing-master
solveinteg.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/solveinteg.m
3,146
utf_8
0b0df74b4066fbe41ed1f8a44f09200f
% SOLVEINTEG % % This function is used by INTEGGAUSFILT to solve for the multiple averaging % filter widths needed to approximate a Gaussian of desired standard deviation. % % Usage: [wl, wu, m, sigmaActual] = solveinteg(sigma, n) % % Arguments: sigma - Desired standard deviation of Gaussian. This should not % be less than one. % n - Number of averaging passes that will be used. I % suggest using a value that is at least 4, use at least % 5, perhaps 6 if you will be taking derivatives. % % Returns: wl - Width of smaller averaging filter to use % wu - Width of larger averaging filter to use % (Note wu = wl + 2 and wl is always odd) % m - The number of filterings to be done with the smaller % averaging filter. The number of filterings to be done % with the larger filter is n-m % sigmaActual - The actual standard deviation of the approximated % Gaussian that is achieved. % % Note that the desired standard deviation will not be achieved exactly. A % combination of different sized averaging filters are applied to approximate it % as closely as possible. If n is 5 the deviation from the desired standard % deviation will be at most about 0.15 pixels % % To acheive a filtering that approximates a Gaussian with the desired % standard deviation perform: % m filterings with an averaging filter of width wl, followed by % n-m filterings with an averaging filter of width wu % % See also: INTEGGAUSSFILT, INTEGAVERAGE, INTEGRALIMAGE % Copyright (c) 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. % September 2009 function [wl, wu, m, sigmaActual] = solveinteg(sigma, n) if sigma < 0.8 warning('Sigma values below about 0.8 cannot be represented'); end wIdeal = sqrt(12*sigma^2/n + 1); % Ideal averaging filter width % wl is first odd valued integer less than wIdeal wl = floor(wIdeal); if ~mod(wl,2) wl = wl-1; end % wu is the next odd value > wl wu = wl+2; % Compute m. Refer to the tech note for derivation of this formula mIdeal = (12*sigma^2 - n*wl^2 - 4*n*wl - 3*n)/(-4*wl - 4); m = round(mIdeal); if m > n || m < 0 error('calculation of m has failed'); end % Compute actual sigma that will be achieved sigmaActual = sqrt((m*wl^2 + (n-m)*wu^2 - n)/12); % fprintf('wl %d wu %d m %d actual sigma %.3f\n', wl, wu, m, sigmaActual);
github
jacksky64/imageProcessing-master
derivative7.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/derivative7.m
3,752
utf_8
358273e985c8915dbe914b5368390cdc
% DERIVATIVE7 - 7-Tap 1st and 2nd discrete derivatives % % This function computes 1st and 2nd derivatives of an image using the 7-tap % coefficients given by Farid and Simoncelli. The results are significantly % more accurate than MATLAB's GRADIENT function on edges that are at angles % other than vertical or horizontal. This in turn improves gradient orientation % estimation enormously. % % Usage: [gx, gy, gxx, gyy, gxy] = derivative7(im, derivative specifiers) % % Arguments: % im - Image to compute derivatives from. % derivative specifiers - A comma separated list of character strings % that can be any of 'x', 'y', 'xx', 'yy' or 'xy' % These can be in any order, the order of the % computed output arguments will match the order % of the derivative specifier strings. % Returns: % Function returns requested derivatives which can be: % gx, gy - 1st derivative in x and y % gxx, gyy - 2nd derivative in x and y % gxy - 1st derivative in y of 1st derivative in x % % Examples: % Just compute 1st derivatives in x and y % [gx, gy] = derivative7(im, 'x', 'y'); % % Compute 2nd derivative in x, 1st derivative in y and 2nd derivative in y % [gxx, gy, gyy] = derivative7(im, 'xx', 'y', 'yy') % % See also: DERIVATIVE5 % Reference: Hany Farid and Eero Simoncelli "Differentiation of Discrete % Multi-Dimensional Signals" IEEE Trans. Image Processing. 13(4): 496-508 (2004) % Copyright (c) 2010 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % % April 2010 function varargout = derivative7(im, varargin) varargin = varargin(:); varargout = cell(size(varargin)); % 7-tap interpolant and 1st and 2nd derivative coefficients p = [ 0.004711 0.069321 0.245410 0.361117 0.245410 0.069321 0.004711]; d1 = [ 0.018708 0.125376 0.193091 0.000000 -0.193091 -0.125376 -0.018708]; d2 = [ 0.055336 0.137778 -0.056554 -0.273118 -0.056554 0.137778 0.055336]; % Compute derivatives. Note that in the 1st call below MATLAB's conv2 % function performs a 1D convolution down the columns using p then a 1D % convolution along the rows using d1. etc etc. gx = false; for n = 1:length(varargin) if strcmpi('x', varargin{n}) varargout{n} = conv2(p, d1, im, 'same'); gx = true; % Record that gx is available for gxy if needed gxn = n; elseif strcmpi('y', varargin{n}) varargout{n} = conv2(d1, p, im, 'same'); elseif strcmpi('xx', varargin{n}) varargout{n} = conv2(p, d2, im, 'same'); elseif strcmpi('yy', varargin{n}) varargout{n} = conv2(d2, p, im, 'same'); elseif strcmpi('xy', varargin{n}) | strcmpi('yx', varargin{n}) if gx varargout{n} = conv2(d1, p, varargout{gxn}, 'same'); else gx = conv2(p, d1, im, 'same'); varargout{n} = conv2(d1, p, gx, 'same'); end else error(sprintf('''%s'' is an unrecognized derivative option',varargin{n})); end end
github
jacksky64/imageProcessing-master
nonmaxsup.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/nonmaxsup.m
6,606
utf_8
175ee530f04d95568bfbdb8b17524c7f
% NONMAXSUP - Non-maxima suppression % % Usage: % [im,location] = nonmaxsup(inimage, orient, radius); % % Function for performing non-maxima suppression on an image using an % orientation image. It is assumed that the orientation image gives % feature normal orientation angles in degrees (0-180). % % Input: % inimage - Image to be non-maxima suppressed. % % orient - Image containing feature normal orientation angles in degrees % (0-180), angles positive anti-clockwise. % % radius - Distance in pixel units to be looked at on each side of each % pixel when determining whether it is a local maxima or not. % This value cannot be less than 1. % (Suggested value about 1.2 - 1.5) % % Returns: % im - Non maximally suppressed image. % location - Complex valued image holding subpixel locations of edge % points. For any pixel the real part holds the subpixel row % coordinate of that edge point and the imaginary part holds % the column coordinate. (If a pixel value is 0+0i then it % is not an edgepoint.) % (Note that if this function is called without 'location' % being specified as an output argument is not computed) % % Notes: % % The suggested radius value is 1.2 - 1.5 for the following reason. If the % radius parameter is set to 1 there is a chance that a maxima will not be % identified on a broad peak where adjacent pixels have the same value. To % overcome this one typically uses a radius value of 1.2 to 1.5. However % under these conditions there will be cases where two adjacent pixels will % both be marked as maxima. Accordingly there is a final morphological % thinning step to correct this. % % This function is slow. It uses bilinear interpolation to estimate % intensity values at ideal, real-valued pixel locations on each side of % pixels to determine if they are local maxima. % Copyright (c) 1996-2013 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % % 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 1996 - Original version % September 2004 - Subpixel localization added % August 2005 - Made Octave compatible % October 2013 - Final thinning applied to binary image for Octave % compatbility (Thanks to Chris Pudney) function [im, location] = nonmaxsup(inimage, orient, radius) if any(size(inimage) ~= size(orient)) error('image and orientation image are of different sizes'); end if radius < 1 error('radius must be >= 1'); end Octave = exist('OCTAVE_VERSION', 'builtin') == 5; % Are we running under Octave [rows,cols] = size(inimage); im = zeros(rows,cols); % Preallocate memory for output image if nargout == 2 location = zeros(rows,cols); end iradius = ceil(radius); % Precalculate x and y offsets relative to centre pixel for each orientation angle angle = [0:180].*pi/180; % Array of angles in 1 degree increments (but in radians). xoff = radius*cos(angle); % x and y offset of points at specified radius and angle yoff = radius*sin(angle); % from each reference position. hfrac = xoff - floor(xoff); % Fractional offset of xoff relative to integer location vfrac = yoff - floor(yoff); % Fractional offset of yoff relative to integer location orient = fix(orient)+1; % Orientations start at 0 degrees but arrays start % with index 1. % Now run through the image interpolating grey values on each side % of the centre pixel to be used for the non-maximal suppression. for row = (iradius+1):(rows - iradius) for col = (iradius+1):(cols - iradius) or = orient(row,col); % Index into precomputed arrays x = col + xoff(or); % x, y location on one side of the point in question y = row - yoff(or); fx = floor(x); % Get integer pixel locations that surround location x,y cx = ceil(x); fy = floor(y); cy = ceil(y); tl = inimage(fy,fx); % Value at top left integer pixel location. tr = inimage(fy,cx); % top right bl = inimage(cy,fx); % bottom left br = inimage(cy,cx); % bottom right upperavg = tl + hfrac(or) * (tr - tl); % Now use bilinear interpolation to loweravg = bl + hfrac(or) * (br - bl); % estimate value at x,y v1 = upperavg + vfrac(or) * (loweravg - upperavg); if inimage(row, col) > v1 % We need to check the value on the other side... x = col - xoff(or); % x, y location on the `other side' of the point in question y = row + yoff(or); fx = floor(x); cx = ceil(x); fy = floor(y); cy = ceil(y); tl = inimage(fy,fx); % Value at top left integer pixel location. tr = inimage(fy,cx); % top right bl = inimage(cy,fx); % bottom left br = inimage(cy,cx); % bottom right upperavg = tl + hfrac(or) * (tr - tl); loweravg = bl + hfrac(or) * (br - bl); v2 = upperavg + vfrac(or) * (loweravg - upperavg); if inimage(row,col) > v2 % This is a local maximum. im(row, col) = inimage(row, col); % Record value in the output % image. % Code for sub-pixel localization if it was requested if nargout == 2 % Solve for coefficients of parabola that passes through % [-1, v1] [0, inimage] and [1, v2]. % v = a*r^2 + b*r + c c = inimage(row,col); a = (v1 + v2)/2 - c; b = a + c - v1; % location where maxima of fitted parabola occurs r = -b/(2*a); location(row,col) = complex(row + r*yoff(or), col - r*xoff(or)); end end end end end % Finally thin the 'nonmaximally suppressed' image by pointwise % multiplying itself with a morphological skeletonization of itself. % % I know it is oxymoronic to thin a nonmaximally supressed image but % fixes the multiple adjacent peaks that can arise from using a radius % value > 1. if Octave skel = bwmorph(im>0,'thin',Inf); % Octave's 'thin' seems to produce better results. else skel = bwmorph(im>0,'skel',Inf); end im = im.*skel; if nargout == 2 location = location.*skel; end
github
jacksky64/imageProcessing-master
integgaussfilt.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Spatial/integgaussfilt.m
4,116
utf_8
957cc904a9b7d1545d8c3094dfc9e044
% INTEGGAUSSFILT - Approximate Gaussian filtering using integral filters % % This function approximates Gaussian filtering by repeatedly applying % averaging filters. The averaging is performed via integral images which % results in a fixed and very low computational cost that is independent of % the Gaussian size. % % Usage: [fim, sigmaActual] = integgaussfilt(im, sigma, nFilt) % % Arguments: % im - Image to be Gaussian smoothed % sigma - Desired standard deviation of Gaussian filter % nFilt - The number of average filterings to be used to % approximate the Gaussian. This should be a minimum of % 3, using 4 is better. If the smoothed image is to be % differentiated an additional averaging should be applied % for each derivative. Eg if a second derivative is to be % taken at least 5 averagings should be applied. If omitted % this parameter defaults to 5. % % Returns: % fim - Smoothed image % sigmaActual - Actual standard deviation of approximate Gaussian filter % that was used % % Notes: % 1. The desired standard deviation will not be achieved exactly. A combination % of different sized averaging filters are applied to approximate it as closely % as possible. If nFilt is 5 the deviation from the desired standard deviation % will be at most about 0.15 pixels. % % 2. Values of sigma less than about 1.8 cannot be well approximated by % repeated averagings. For sigma < 1.8 the smoothing is performed using % conventional Gaussian convolution. % % See also: INTEGAVERAGE, SOLVEINTEG, INTEGRALIMAGE, GAUSSFILT % Copyright (c) 2009-2010 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % September 2009 - Original version % April 2010 - Added return of actual standard deviation of effective % filter used. Use standard convolution for small sigma function [im, sigmaActual] = integgaussfilt(im, sigma, nFilt) if ~exist('nFilt', 'var') nFilt = 5; end % First check if sigma is too small to be well represented by repeated % averagings. 5 averagings with a width 3 filter produces an equivalent % sigma of ~1.8 This represents the minimum threshold. For sigma less % than this we use conventional convolution if sigma < 1.8 im = gaussfilt(im, sigma); sigmaActual = sigma; else % Use repeated averagings via integral images % Solve for the combination of averaging filter sizes that will result % in the closest approximation of sigma given nFilt. [wl, wu, m, sigmaActual] = solveinteg(sigma, nFilt); radl = (wl-1)/2; radu = (wu-1)/2; % Apply the averaging filters via integral images. for i = 1:m im = integaverage(im,radl); % im = runningaverage(im,radl); end for n = 1:(nFilt-m) im = integaverage(im,radu); % im = runningaverage(im,radu); end end %------------------------------------------------------------------- % GAUSSFILT - Small wrapper function for convenient Gaussian filtering % % Usage: smim = gaussfilt(im, sigma) % function smim = gaussfilt(im, sigma) sze = ceil(6*sigma); if ~mod(sze,2) % Ensure filter size is odd sze = sze+1; end sze = max(sze,1); % and make sure it is at least 1 h = fspecial('gaussian', [sze sze], sigma); smim = filter2(h, im);
github
jacksky64/imageProcessing-master
rotx.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/rotx.m
589
utf_8
bc55598911b9d73eb90ab44cab59a9db
% ROTX - Homogeneous transformation for a rotation about the x axis % % Usage: T = rotx(theta) % % Argument: theta - rotation about x axis % Returns: T - 4x4 homogeneous transformation matrix % % See also: TRANS, ROTY, ROTZ, INVHT % Copyright (c) 2001 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ function T = rotx(theta) T = [ 1 0 0 0 0 cos(theta) -sin(theta) 0 0 sin(theta) cos(theta) 0 0 0 0 1];
github
jacksky64/imageProcessing-master
angleaxisrotate.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/angleaxisrotate.m
1,352
utf_8
aa84e472c4234c58e628b30ac255b800
% ANGLEAXISROTATE - uses angle axis descriptor to rotate vectors % % Usage: v2 = angleaxisrotate(t, v) % % Arguments: t - 3-vector giving rotation axis with magnitude equal to the % rotation angle in radians. % v - 4xn matrix of homogeneous 4-vectors to be rotated or % 3xn matrix of inhomogeneous 3-vectors to be rotated % Returns: v2 - The rotated vectors. % % See also: MATRIX2ANGLEAXIS, NEWANGLEAXIS, ANGLEAXIS2MATRIX, NORMALISEANGLEAXIS % Copyright (c) 2008 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. function v2 = angleaxisrotate(t, v) [ndim,npts] = size(v); T = angleaxis2matrix(t); if ndim == 3 v2 = T(1:3,1:3)*v; elseif ndim == 4 v2 = T*v; else error('v must be 4xN or 3xN'); end
github
jacksky64/imageProcessing-master
homotrans.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/homotrans.m
1,371
utf_8
8fc0c2c8b73dcccc47ba10e8a451beee
% HOMOTRANS - Homogeneous transformation of points/lines % % Function to perform a transformation on 2D or 3D homogeneous coordinates % The resulting coordinates are normalised to have a homogeneous scale of 1 % % Usage: % t = homotrans(P, v); % % Arguments: % P - 3 x 3 or 4 x 4 homogeneous transformation matrix % v - 3 x n or 4 x n matrix of homogeneous coordinates % Copyright (c) 2000-2007 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. function t = homotrans(P, v); [dim,npts] = size(v); if ~all(size(P)==dim) error('Transformation matrix and point dimensions do not match'); end t = P*v; % Transform for r = 1:dim-1 % Now normalise t(r,:) = t(r,:)./t(end,:); end t(end,:) = ones(1,npts);
github
jacksky64/imageProcessing-master
trans.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/trans.m
708
utf_8
c2bc04ae87a1f56d814ee75d140cea19
% TRANS - Homogeneous transformation for a translation by x, y, z % % Usage: T = trans(x, y, z) % T = trans(v) % % Arguments: x,y,z - translations in x,y and z, or alternatively % v - 3-vector defining x, y and z. % Returns: T - 4x4 homogeneous transformation matrix % % See also: ROTX, ROTY, ROTZ, INVHT % Copyright (c) 2001 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ function T = trans(x, y, z) if nargin == 1 % x is a 3-vector y = x(2); z = x(3); x = x(1); end T = [ 1 0 0 x 0 1 0 y 0 0 1 z 0 0 0 1];
github
jacksky64/imageProcessing-master
plotframe.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/plotframe.m
1,964
utf_8
0f41b60ca2191bba7912190141e9250b
% PLOTFRAME - plots a coordinate frame specified by a homogeneous transform % % Usage: function plotframe(T, len, label, colr) % % Arguments: % T - 4x4 homogeneous transform or 3x3 rotation matrix % len - length of axis arms to plot (defaults to 1) % label - text string to append to x,y,z labels on axes % colr - Three element array spcifying colour to plot axes. % % len, label and colr are optional and default to 1 and '' and [0 0 1] % respectively. % % See also: ROTX, ROTY, ROTZ, TRANS, INVHT % Peter Kovesi % www.peterkovesi.com % 2001 - Original version % April 2016 - Allowance for 3x3 rotation matrices as as well as 4x4 homogeneous % transforms function plotframe(T, len, label, colr) if all(size(T) == [3,3]) % we have a rotation matrix T = [ T [0;0;0] 0 0 0 1 ]; end if ~all(size(T) == [4,4]) error('plotframe: matrix is not 4x4') end if ~exist('len','var') || isempty(len) len = 1; end if ~exist('label','var') || isempty(label) label = ''; end if ~exist('colr','var') || isempty(colr) colr = [0 0 1]; end % Assume scale specified by T(4,4) == 1 origin = T(1:3, 4); % 1st three elements of 4th column X = origin + len*T(1:3, 1); % point 'len' units out along x axis Y = origin + len*T(1:3, 2); % point 'len' units out along y axis Z = origin + len*T(1:3, 3); % point 'len' units out along z axis line([origin(1),X(1)], [origin(2), X(2)], [origin(3), X(3)], 'color', colr); line([origin(1),Y(1)], [origin(2), Y(2)], [origin(3), Y(3)], 'color', colr); line([origin(1),Z(1)], [origin(2), Z(2)], [origin(3), Z(3)], 'color', colr); text(X(1), X(2), X(3), ['x' label], 'color', colr); text(Y(1), Y(2), Y(3), ['y' label], 'color', colr); text(Z(1), Z(2), Z(3), ['z' label], 'color', colr);
github
jacksky64/imageProcessing-master
newangleaxis.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/newangleaxis.m
1,120
utf_8
99157ce84285ee91eeb2c84cecccfd22
% NEWANGLEAXIS - Constructs angle-axis descriptor % % Usage: t = newangleaxis(theta, axis) % % Arguments: theta - angle of rotation % axis - 3-vector defining axis of rotation % Returns: t - 3-vector giving rotation axis with magnitude equal to the % rotation angle in radians. % % See also: MATRIX2ANGLEAXIS, ANGLEAXISROTATE, ANGLEAXIS2MATRIX % NORMALISEANGLEAXIS % Copyright (c) 2008 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ function t = newangleaxis(theta, axis) if length(axis) ~= 3 error('axis must be a 3 vector'); end axis = axis(:)/norm(axis(:)); % Ensure unit magnitude % Normalise theta to lie in the range -pi to pi to ensure one-to-one mapping % between angle-axis descriptor and resulting rotation. theta = rem(theta, 2*pi); % Remove multiples of 2pi if theta > pi theta = theta - 2*pi; elseif theta < -pi theta = theta + 2*pi; end t = theta*axis;
github
jacksky64/imageProcessing-master
rotz.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/rotz.m
593
utf_8
485891081a31d4907a07ce934642fea2
% ROTZ - Homogeneous transformation for a rotation about the z axis % % Usage: T = rotz(theta) % % Argument: theta - rotation about z axis % Returns: T - 4x4 homogeneous transformation matrix % % See also: TRANS, ROTX, ROTY, INVHT % Copyright (c) 2001 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ function T = rotz(theta) T = [ cos(theta) -sin(theta) 0 0 sin(theta) cos(theta) 0 0 0 0 1 0 0 0 0 1];
github
jacksky64/imageProcessing-master
angleaxis2matrix.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/angleaxis2matrix.m
1,793
utf_8
965230307dd2fd317515c242f796a791
% ANGLEAXIS2MATRIX - converts angle-axis descriptor to 4x4 homogeneous % transformation matrix % % Usage: T = angleaxis2matrix(t) % % Argument: t - 3-vector giving rotation axis with magnitude equal to the % rotation angle in radians. % Returns: T - 4x4 Homogeneous transformation matrix % % See also: MATRIX2ANGLEAXIS, ANGLEAXISROTATE, NEWANGLEAXIS, NORMALISEANGLEAXIS % Copyright (c) 2008 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. function T = angleaxis2matrix(t) theta = sqrt(t(:)'*t(:)); % = norm(t), but faster if theta < eps % If the rotation is very small... T = [ 1 -t(3) t(2) 0 t(3) 1 -t(1) 0 -t(2) t(1) 1 0 0 0 0 1]; return end % Otherwise set up standard matrix, first setting up some convenience % variables t = t/theta; x = t(1); y = t(2); z = t(3); c = cos(theta); s = sin(theta); C = 1-c; xs = x*s; ys = y*s; zs = z*s; xC = x*C; yC = y*C; zC = z*C; xyC = x*yC; yzC = y*zC; zxC = z*xC; T = [ x*xC+c xyC-zs zxC+ys 0 xyC+zs y*yC+c yzC-xs 0 zxC-ys yzC+xs z*zC+c 0 0 0 0 1];
github
jacksky64/imageProcessing-master
matrix2quaternion.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/matrix2quaternion.m
2,010
utf_8
ad7a1983aceaa9953be167eddabb22ae
% MATRIX2QUATERNION - Homogeneous matrix to quaternion % % Converts 4x4 homogeneous rotation matrix to quaternion % % Usage: Q = matrix2quaternion(T) % % Argument: T - 4x4 Homogeneous transformation matrix % Returns: Q - a quaternion in the form [w, xi, yj, zk] % % See Also QUATERNION2MATRIX % Copyright (c) 2008 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. function Q = matrix2quaternion(T) % This code follows the implementation suggested by Hartley and Zisserman R = T(1:3, 1:3); % Extract rotation part of T % Find rotation axis as the eigenvector having unit eigenvalue % Solve (R-I)v = 0; [v,d] = eig(R-eye(3)); % The following code assumes the eigenvalues returned are not necessarily % sorted by size. This may be overcautious on my part. d = diag(abs(d)); % Extract eigenvalues [s, ind] = sort(d); % Find index of smallest one if d(ind(1)) > 0.001 % Hopefully it is close to 0 warning('Rotation matrix is dubious'); end axis = v(:,ind(1)); % Extract appropriate eigenvector if abs(norm(axis) - 1) > .0001 % Debug warning('non unit rotation axis'); end % Now determine the rotation angle twocostheta = trace(R)-1; twosinthetav = [R(3,2)-R(2,3), R(1,3)-R(3,1), R(2,1)-R(1,2)]'; twosintheta = axis'*twosinthetav; theta = atan2(twosintheta, twocostheta); Q = [cos(theta/2); axis*sin(theta/2)];
github
jacksky64/imageProcessing-master
vector2quaternion.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/vector2quaternion.m
563
utf_8
a87aa8408a94f8010721a2ea603c64f9
% VECTOR2QUATERNION - embeds 3-vector in a quaternion representation % % Usage: Q = vector2quaternion(v) % % Argument: v - 3-vector % Returns: Q - Quaternion given by [0; v(:)] % % See also: NEWQUATERNION, QUATERNIONROTATE, QUATERNIONPRODUCT, QUATERNIONCONJUGATE % Copyright (c) 2008 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ function Q = vector2quaternion(v) if length(v) ~= 3 error('v must be a 3-vector'); end Q = [0; v(:)];
github
jacksky64/imageProcessing-master
invht.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/invht.m
505
utf_8
62f8fca3096c7b08ba22952fef7e6416
% INVHT - inverse of a homogeneous transformation matrix % % Usage: Tinv = invht(T) % % Argument: T - 4x4 homogeneous transformation matrix % Returns: Tinv - inverse % % See also: TRANS, ROTX, ROTY, ROTZ % Copyright (c) 2001 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ function Tinv = invht(T) A = T(1:3,1:3); Tinv = [ A' -A'*T(1:3,4) 0 0 0 1 ];
github
jacksky64/imageProcessing-master
roty.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/roty.m
589
utf_8
1523f4098a8a375de8eed1c69ae75c92
% ROTY - Homogeneous transformation for a rotation about the y axis % % Usage: T = roty(theta) % % Argument: theta - rotation about y axis % Returns: T - 4x4 homogeneous transformation matrix % % See also: TRANS, ROTX, ROTZ, INVHT % Copyright (c) 2001 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ function T = roty(theta) T = [ cos(theta) 0 sin(theta) 0 0 1 0 0 -sin(theta) 0 cos(theta) 0 0 0 0 1];
github
jacksky64/imageProcessing-master
invrpy.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/invrpy.m
1,416
utf_8
564006f3b82a8b1d500b2ec21afc1f92
% INVRPY - inverse of Roll Pitch Yaw transform % % Usage: [rpy1, rpy2] = invrpy(RPY) % % Argument: RPY - 4x4 Homogeneous transformation matrix or 3x3 rotation matrix % Returns: rpy1 = [phi1, theta1, psi1] - the 1st solution and % rpy2 = [phi2, theta2, psi2] - the 2nd solution % % rotz(phi1) * roty(theta1) * rotx(psi1) = RPY % rotz(rpy1(1)) * roty(rpy1(2)) * rotx(rpy1(3)) = RPY % % % See also: INVEULER, INVHT, ROTX, ROTY, ROTZ % Reference: Richard P. Paul Robot Manipulators: Mathematics, Programming and Control. % MIT Press 1981. Page 70 % % Copyright (c) 2001 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % May 2015 Help documentation corrected! function [rpy1, rpy2] = invrpy(RPY) % Z rotation phi1 = atan2(RPY(2,1), RPY(1,1)); phi2 = phi1 + pi; % Y rotation theta1 = atan2(-RPY(3,1), cos(phi1)*RPY(1,1) + sin(phi1)*RPY(2,1)); theta2 = atan2(-RPY(3,1), cos(phi2)*RPY(1,1) + sin(phi2)*RPY(2,1)); % X rotation psi1 = atan2(sin(phi1)*RPY(1,3) - cos(phi1)*RPY(2,3), ... -sin(phi1)*RPY(1,2) + cos(phi1)*RPY(2,2)); psi2 = atan2(sin(phi2)*RPY(1,3) - cos(phi2)*RPY(2,3), ... -sin(phi2)*RPY(1,2) + cos(phi2)*RPY(2,2)); rpy1 = [phi1, theta1, psi1]; rpy2 = [phi2, theta2, psi2];
github
jacksky64/imageProcessing-master
normaliseangleaxis.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/normaliseangleaxis.m
1,163
utf_8
b382ff3c5687a58b63642451c0e3153b
% NORMALISEANGLEAXIS - normalises angle-axis descriptor % % Function normalises theta so that it lies in the range -pi to pi to ensure % one-to-one mapping between angle-axis descriptor and resulting rotation % % Usage: t2 = normaliseangleaxis(t) % % Argument: t - 3-vector giving rotation axis with magnitude equal to the % rotation angle in radians. % Returns: t2 - Normalised angle-axis descriptor % % See also: MATRIX2ANGLEAXIS, NEWANGLEAXIS, ANGLEAXIS2MATRIX, ANGLEAXIS2MATRIX2, % ANGLEAXISROTATE % Copyright (c) 2008 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ function t2 = normaliseangleaxis(t) if length(t) ~= 3 error('axis must be a 3 vector'); end theta = norm(t); axis = t/theta; theta = rem(theta, 2*pi); % Remove multiples of 2pi if theta > pi % Note theta cannot be -ve theta = theta - 2*pi; end t = theta*axis; if norm(t) > pi t2 = t*(1 - (2*pi)/norm(t)); else t2 = t; end
github
jacksky64/imageProcessing-master
quaternionconjugate.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/quaternionconjugate.m
525
utf_8
d7df86d9770e7881f0cda73f664a8be5
% QUATERNIONCONJUGATE - Conjugate of a quaternion % % Usage: Qconj = quaternionconjugate(Q) % % Argument: Q - Quaternions in the form Q = [Qw Qi Qj Qk] % Returns: Qconj - Conjugate % % See also: NEWQUATERNION, QUATERNIONROTATE, QUATERNIONPRODUCT % Copyright (c) 2008 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ function Qconj = quaternionconjugate(Q) Qconj = Q(:); Qconj(2:4) = -Qconj(2:4);
github
jacksky64/imageProcessing-master
dhtrans.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Rotations/dhtrans.m
1,161
utf_8
817bf7d3f603627a2da4773fefc67097
% DHTRANS - computes Denavit Hartenberg matrix % % This function calculates the 4x4 homogeneous transformation matrix, representing % the Denavit Hartenberg matrix, given link parameters of joint angle, length, joint % offset and twist. % % Usage: T = DHtrans(theta, offset, length, twist) % % Arguments: theta - joint angle (rotation about local z) % offset - offset (translation along z) % length - translation along link x axis % twist - rotation about link x axis % % Returns: T - 4x4 Homogeneous transformation matrix % % See also: TRANS, ROTX, ROTY, ROTZ, INVHT % Copyright (c) 2001 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ function T = dhtrans(theta, offset, length, twist) T = [ cos(theta) -sin(theta)*cos(twist) sin(theta)*sin(twist) length*cos(theta) sin(theta) cos(theta)*cos(twist) -cos(theta)*sin(twist) length*sin(theta) 0 sin(twist) cos(twist) offset 0 0 0 1 ];