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 | zongwave/IPASS-master | show_bayer_raw.m | .m | IPASS-master/ReadImage/show_bayer_raw.m | 2,940 | utf_8 | 07fb3de8e9e892fb345d92b33e13b085 | % show_bayer_raw.m - convert bayer image to RGB
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function show_bayer_raw(width, heigh, bit_depth, bayer_pattern)
clear;
clc;
close all;
[filename, pathname] = uigetfile( ...
{ '*.raw','RAW files (*.raw)'; ...
'*.bmp','Bitmap files (*.bmp)'; ...
'*.tif','TIF files (*.tif)'; ...
'*.jpg','JPEG files (*.jpg)'; ...
'*.*', 'All Files (*.*)'}, ...
'Pick a file');
if (nargin < 3)
% width = 2048;
% heigh = 1092;
width = 1920;
heigh = 1080;
bit_depth = 10;
bayer_pattern = 'rggb';
end
fullfilename = fullfile(pathname, filename);
fip_raw = fopen(fullfilename,'rb');
[RAW, num] = fread(fip_raw, inf, 'uint16');
pixel_count = width * heigh;
frame_count = num / pixel_count;
fclose(fip_raw);
bayer_vid_name = [fullfilename '_bayer'];
vidObj = VideoWriter([bayer_vid_name '.mp4'], 'MPEG-4');
open(vidObj);
for frame_idx=1: frame_count
frame_idx
for pix_idx=1 : pixel_count
temp(pix_idx) = RAW(pix_idx + (frame_idx-1) * pixel_count);
bayer(pix_idx) = double(temp(pix_idx) / (bitshift(1, bit_depth) - 1));
end
bayer = reshape(bayer, width, heigh);
bayer = bayer';
RGB = demosaic(uint8(255 * bayer), bayer_pattern);
writeVideo(vidObj, RGB)
end
close(vidObj);
bayer_filename = [fullfilename '_frame.raw'];
fip_bayer = fopen(bayer_filename,'w');
fwrite(fip_bayer, temp, 'uint16');
fclose(fip_bayer);
imwrite(RGB, [fullfilename '.bmp']);
figure();
imshow(RGB);
% for i=1 : 2: (pixel_count - width - 1)
% tempR = RAW(i);
% tempGr = RAW(i + 1);
% tempGb = RAW(i + width);
% tempB = RAW(i + width + 1);
%
% R(i) = double(tempR / (bitshift(1, bit_depth) - 1));
% R(i+1) = R(i);
% R(i + width) = R(i);
% R(i + width + 1) = R(i);
%
% G(i) = double((tempGr + tempGb) / (2 * (bitshift(1, bit_depth) - 1)));
% G(i + 1) = G(i);
% G(i + width) = G(i);
% G(i + width + 1) = G(i);
%
% B(i) = double(tempB / (bitshift(1, bit_depth) - 1));
% B(i + 1) = B(i);
% B(i + width) = B(i);
% B(i + width + 1) = B(i);
% end
%
% R = reshape(R, width, heigh);
% G = reshape(G, width, heigh);
% B = reshape(B, width, heigh);
%
% R = R';
% G = G';
% B = B';
%
% RGB = cat(3, R, G, B);
|
github | zongwave/IPASS-master | sfb3D.m | .m | IPASS-master/Wavelet/biShrink/sfb3D.m | 1,567 | utf_8 | c7ef9448ec966a9f630ab9be5d316f28 | function y = sfb3D(lo, hi, sf1, sf2, sf3)
% 3D Synthesis Filter Bank
%
% USAGE:
% y = sfb3D(lo, hi, sf1, sf2, sf3);
% INPUT:
% lo, hi - lowpass subbands
% sfi - synthesis filters for dimension i
% OUPUT:
% y - output array
% See afb3D
%
% WAVELET SOFTWARE AT POLYTECHNIC UNIVERSITY, BROOKLYN, NY
% http://taco.poly.edu/WaveletSoftware/
if nargin < 4
sf2 = sf1;
sf3 = sf1;
end
LLL = lo;
LLH = hi{1};
LHL = hi{2};
LHH = hi{3};
HLL = hi{4};
HLH = hi{5};
HHL = hi{6};
HHH = hi{7};
% filter along dimension 3
LL = sfb3D_A(LLL, LLH, sf3, 3);
LH = sfb3D_A(LHL, LHH, sf3, 3);
HL = sfb3D_A(HLL, HLH, sf3, 3);
HH = sfb3D_A(HHL, HHH, sf3, 3);
% filter along dimension 3
L = sfb3D_A(LL, LH, sf2, 2);
H = sfb3D_A(HL, HH, sf2, 2);
% filter along dimension 1
y = sfb3D_A(L, H, sf1, 1);
% LOCAL FUNCTION
function y = sfb3D_A(lo, hi, sf, d)
% 3D Synthesis Filter Bank
% (along single dimension only)
%
% y = sfb3D_A(lo, hi, sf, d);
% sf - synthesis filters
% d - dimension of filtering
% see afb2D_A
lpf = sf(:, 1); % lowpass filter
hpf = sf(:, 2); % highpass filter
% permute dimensions of lo and hi so that dimension d is first.
p = mod(d-1+[0:2], 3) + 1;
lo = permute(lo, p);
hi = permute(hi, p);
[N1, N2, N3] = size(lo);
N = 2*N1;
L = length(sf);
y = zeros(N+L-2, N2, N3);
for k = 1:N3
y(:, :, k) = upfirdn(lo(:, :, k), lpf, 2, 1) + upfirdn(hi(:, :, k), hpf, 2, 1);
end
y(1:L-2, :, :) = y(1:L-2, :, :) + y(N+[1:L-2], :, :);
y = y(1:N, :, :);
y = cshift3D(y, 1-L/2, 1);
% permute dimensions of y (inverse permutation)
y = ipermute(y, p);
|
github | zongwave/IPASS-master | afb3D.m | .m | IPASS-master/Wavelet/biShrink/afb3D.m | 2,569 | utf_8 | d60f781f473b436449d0a260f6a420c2 | function [lo, hi] = afb3D(x, af1, af2, af3)
% 3D Analysis Filter Bank
%
% USAGE:
% [lo, hi] = afb3D(x, af1, af2, af3);
% INPUT:
% x - N1 by N2 by N3 array matrix, where
% 1) N1, N2, N3 all even
% 2) N1 >= 2*length(af1)
% 3) N2 >= 2*length(af2)
% 4) N3 >= 2*length(af3)
% afi - analysis filters for dimension i
% afi(:, 1) - lowpass filter
% afi(:, 2) - highpass filter
% OUTPUT:
% lo - lowpass subband
% hi{d}, d = 1..7 - highpass subbands
% EXAMPLE:
% x = rand(32,64,16);
% [af, sf] = farras;
% [lo, hi] = afb3D(x, af, af, af);
% y = sfb3D(lo, hi, sf, sf, sf);
% err = x - y;
% max(max(max(abs(err))))
%
% WAVELET SOFTWARE AT POLYTECHNIC UNIVERSITY, BROOKLYN, NY
% http://taco.poly.edu/WaveletSoftware/
if nargin < 3
af2 = af1;
af3 = af1;
end
% filter along dimension 1
[L, H] = afb3D_A(x, af1, 1);
% filter along dimension 2
[LL LH] = afb3D_A(L, af2, 2);
[HL HH] = afb3D_A(H, af2, 2);
% filter along dimension 3
[LLL LLH] = afb3D_A(LL, af3, 3);
[LHL LHH] = afb3D_A(LH, af3, 3);
[HLL HLH] = afb3D_A(HL, af3, 3);
[HHL HHH] = afb3D_A(HH, af3, 3);
lo = LLL;
hi{1} = LLH;
hi{2} = LHL;
hi{3} = LHH;
hi{4} = HLL;
hi{5} = HLH;
hi{6} = HHL;
hi{7} = HHH;
% LOCAL FUNCTION
function [lo, hi] = afb3D_A(x, af, d)
% 3D Analysis Filter Bank
% (along one dimension only)
%
% [lo, hi] = afb3D_A(x, af, d);
% INPUT:
% x - N1xN2xN2 matrix, where min(N1,N2,N3) > 2*length(filter)
% (Ni are even)
% af - analysis filter for the columns
% af(:, 1) - lowpass filter
% af(:, 2) - highpass filter
% d - dimension of filtering (d = 1, 2 or 3)
% OUTPUT:
% lo, hi - lowpass, highpass subbands
%
% % Example
% x = rand(32,64,16);
% [af, sf] = farras;
% d = 2;
% [lo, hi] = afb3D_A(x, af, d);
% y = sfb3D_A(lo, hi, sf, d);
% err = x - y;
% max(max(max(abs(err))))
lpf = af(:, 1); % lowpass filter
hpf = af(:, 2); % highpass filter
% permute dimensions of x so that dimension d is first.
p = mod(d-1+[0:2], 3) + 1;
x = permute(x, p);
% filter along dimension 1
[N1, N2, N3] = size(x);
L = size(af, 1)/2;
x = cshift3D(x, -L, 1);
lo = zeros(L+N1/2, N2, N3);
hi = zeros(L+N1/2, N2, N3);
for k = 1:N3
lo(:, :, k) = upfirdn(x(:, :, k), lpf, 1, 2);
end
lo(1:L, :, :) = lo(1:L, :, :) + lo([1:L]+N1/2, :, :);
lo = lo(1:N1/2, :, :);
for k = 1:N3
hi(:, :, k) = upfirdn(x(:, :, k), hpf, 1, 2);
end
hi(1:L, :, :) = hi(1:L, :, :) + hi([1:L]+N1/2, :, :);
hi = hi(1:N1/2, :, :);
% permute dimensions of x (inverse permutation)
lo = ipermute(lo, p);
hi = ipermute(hi, p);
|
github | zongwave/IPASS-master | import_video.m | .m | IPASS-master/Wavelet/denoise/import_video.m | 1,567 | utf_8 | 901835343dbf77f79712538cb65eba81 | % import_video.m - import original video
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function [fullname, vid_frame, frame_count, frame_rate, duration, vid_width, vid_height] = import_video(file)
clc;
clear;
if (nargin < 1)
[filename, pathname] = uigetfile( ...
{'*.mp4','MP4 files (*.mp4)'; ...
'*.mpg','MPEG files (*.mpg)'; ...
'*.mov','MOV files (*.mov)'; ...
'*.*', 'All Files (*.*)'}, ...
'Pick original noisy video file');
fullname = fullfile(pathname, filename);
vidObj = VideoReader(fullname);
frame_count = 0;
frame_rate = vidObj.FrameRate;
vid_height = vidObj.Height;
vid_width = vidObj.Width;
duration = vidObj.Duration;
figure();
title('Original Video');
currAxes = axes;
while hasFrame(vidObj)
vidFrame = readFrame(vidObj);
frame_count = frame_count + 1
vid_frame(frame_count).cdata = vidFrame;
image(vid_frame(frame_count).cdata, 'Parent', currAxes);
currAxes.Visible = 'off';
pause(0.001/vidObj.FrameRate);
end
end
|
github | zongwave/IPASS-master | denoising_dwt.m | .m | IPASS-master/Wavelet/denoise/denoising_dwt.m | 4,332 | utf_8 | 22df1599fbd981002d1cf611d21aa922 | % denoising_dwt.m - image denoise using wavelet
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function y = denoising_dwt(x, wname, tname, tuning)
% Local Adaptive Image Denoising Algorithm
% Usage :
% y = denoising_dwt(x)
% INPUT :
% x - a noisy image
% OUTPUT :
% y - the corresponding denoised image
if nargin < 2
wname = 'haar';
tname = 'penalhi';
tuning = 1;
end
glb = 0;
alpha = 1;
level = 5;
% wavedec2 is a two-dimensional wavelet analysis function.
% Vector C is organized as a vector with A(N), H(N), V(N), D(N), H(N-1), V(N-1), D(N-1), ..., H(1), V(1), D(1), where A, H, V, and D are each a row vector. Each vector is the vector column-wise storage of a matrix.
%
% A contains the approximation coefficients
% H contains the horizontal detail coefficients
% V contains the vertical detail coefficients
% D contains the diagonal detail coefficients
% Matrix S is such that
%
% S(1,:) = size of approximation coefficients(N).
% S(i,:) = size of detail coefficients(N-i+2) for i = 2, ...N+1 and S(N+2,:) = size(X).
%
[C, S] = wavedec2(x, level, wname);
sorh = 's';
if glb == 1
% Estimate the noise standard deviation from the
% detail coefficients at level 1.
det1 = detcoef2('compact', C, S, 1);
sigma = median(abs(det1))/0.6745;
keepapp = 1;
% Use wbmpen for selecting global threshold
% for image de-noising.
glb_thr = wbmpen(C, S, sigma, alpha)
XDEN = wdencmp('gbl', C, S, wname, level, glb_thr, sorh, keepapp);
else
% Obtain denoising (wavelet shrinkage) thresholds. Use the Birge-Massart strategy with a tuning parameter of 3.
% De-noising using level dependent thresholds.
% [C,S] is the wavelet decomposition structure of the image to be de-noised,
% SCAL defines the multiplicative threshold rescaling (see wden for more information) and
% ALFA is a sparsity parameter (see wbmpen for more information).
%
% THR = wthrmngr('dw2ddenoLVL','penalhi',C,S,ALFA)
% ALFA must be such that 2.5 < ALFA < 10
% THR = wthrmngr('dw2ddenoLVL','penalme',C,S,ALFA)
% ALFA must be such that 1.5 < ALFA < 2.5
% THR = wthrmngr('dw2ddenoLVL','penallo',C,S,ALFA)
% ALFA must be such that 1 < ALFA < 2
% THR = wthrmngr('dw2ddenoLVL','sqtwolog',C,S,SCAL)
% THR = wthrmngr('dw2ddenoLVL','sqrtbal_sn',C,S)
%
if strcmp(tname, 'penalhi')
alpha = 5;
elseif strcmp(tname, 'penalme')
alpha = 2;
elseif strcmp(tname, 'penallo')
alpha = 1.5;
elseif strcmp(tname, 'sqtwolog')
alpha = 1;
end
alpha = alpha * tuning;
if strcmp(tname, 'sqrtbal_sn')
lvd_thr = wthrmngr('dw2ddenoLVL', tname, C, S)
else
lvd_thr = wthrmngr('dw2ddenoLVL', tname, C, S, alpha)
end
% wdencmp is a one- or two-dimensional de-noising and compression-oriented function.
% wdencmp performs a de-noising or compression process of a signal or an image, using wavelets.
%
% [XC,CXC,LXC,PERF0,PERFL2] = wdencmp('gbl',X,'wname',N,THR,SORH,KEEPAPP) returns a de-noised or compressed version XC of input signal X (one- or two-dimensional) obtained by wavelet coefficients thresholding using global positive threshold THR.
%
% Additional output arguments [CXC,LXC] are the wavelet decomposition structure of XC (see wavedec or wavedec2 for more information). PERF0 and PERFL2 are L2 -norm recovery and compression score in percentage.
%
% PERFL2 = 100 * (vector-norm of CXC / vector-norm of C)2 if [C,L] denotes the wavelet decomposition structure of X.
%
[XDEN, cfsDEN, dimCFS] = wdencmp('lvd', C, S, wname, level, lvd_thr, sorh);
end
% figure;
% subplot(1,2,1);
% imagesc(x); colormap gray; axis off;
% title('Noisy Image');
% subplot(1,2,2);
% imagesc(XDEN); colormap gray; axis off;
% title('Denoised Image');
y = XDEN;
end
|
github | zongwave/IPASS-master | image_denoise.m | .m | IPASS-master/Wavelet/denoise/image_denoise.m | 8,940 | utf_8 | 2dc2762bb65c1d5cf7df5c9c2323027a | % image_denoise.m - image denoise using wavelet
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function varargout = image_denoise(varargin)
% IMAGE_DENOISE MATLAB code for image_denoise.fig
% IMAGE_DENOISE, by itself, creates a new IMAGE_DENOISE or raises the existing
% singleton*.
%
% H = IMAGE_DENOISE returns the handle to a new IMAGE_DENOISE or the handle to
% the existing singleton*.
%
% IMAGE_DENOISE('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in IMAGE_DENOISE.M with the given input arguments.
%
% IMAGE_DENOISE('Property','Value',...) creates a new IMAGE_DENOISE or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before image_denoise_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to image_denoise_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help image_denoise
% Last Modified by GUIDE v2.5 19-Jul-2017 11:27:11
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @image_denoise_OpeningFcn, ...
'gui_OutputFcn', @image_denoise_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before image_denoise is made visible.
function image_denoise_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to image_denoise (see VARARGIN)
% Choose default command line output for image_denoise
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes image_denoise wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = image_denoise_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on slider movement.
function set_param_Callback(hObject, eventdata, handles)
% hObject handle to set_param (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
thresh = get( handles.set_param, 'value');
if rem(thresh, 1) ~= 0
thresh = round(thresh);
set(hObject,'Value', thresh)
end
set(handles.params,'string', thresh);
% --- Executes during object creation, after setting all properties.
function set_param_CreateFcn(hObject, eventdata, handles)
% hObject handle to set_param (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
set(hObject,'Value', 1);
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
function params_Callback(hObject, eventdata, handles)
% hObject handle to params (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of params as text
% str2double(get(hObject,'String')) returns contents of params as a double
% --- Executes during object creation, after setting all properties.
function params_CreateFcn(hObject, eventdata, handles)
% hObject handle to params (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
set(hObject,'Value', 1);
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in wavelet_basis.
function wavelet_basis_Callback(hObject, eventdata, handles)
% hObject handle to wavelet_basis (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns wavelet_basis contents as cell array
% contents{get(hObject,'Value')} returns selected item from wavelet_basis
% --- Executes during object creation, after setting all properties.
function wavelet_basis_CreateFcn(hObject, eventdata, handles)
% hObject handle to wavelet_basis (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in thresh_setting.
function thresh_setting_Callback(hObject, eventdata, handles)
% hObject handle to thresh_setting (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns thresh_setting contents as cell array
% contents{get(hObject,'Value')} returns selected item from thresh_setting
% --- Executes during object creation, after setting all properties.
function thresh_setting_CreateFcn(hObject, eventdata, handles)
% hObject handle to thresh_setting (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in denoise.
function denoise_Callback(hObject, eventdata, handles)
% hObject handle to denoise (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
basis_index = get(handles.wavelet_basis,'value');
switch basis_index
case 1
wname = 'haar';
case 2
wname = 'db2';
case 3
wname = 'db4';
case 4
wname = 'db8';
case 5
wname = 'coif1';
case 6
wname = 'coif2';
case 7
wname = 'coif4';
case 8
wname = 'sym2';
case 9
wname = 'sym4';
case 10
wname = 'sym8';
case 11
wname = 'bior1.1';
case 12
wname = 'bior3.5';
otherwise
wname = 'haar';
end
thresh_index = get(handles.thresh_setting,'value');
switch thresh_index
case 1
tname = 'penalhi';
case 2
tname = 'penalme';
case 3
tname = 'penallo';
case 4
tname = 'sqtwolog';
case 5
tname = 'sqrtbal_sn';
otherwise
tname = 'penalhi';
end
tuning = get( handles.set_param, 'value');
wavelet_denoise(wname, tname, tuning);
|
github | zongwave/IPASS-master | wavelet_denoise.m | .m | IPASS-master/Wavelet/denoise/wavelet_denoise.m | 2,731 | utf_8 | 33462ea2d55ccace62dd3cbbf4a3410f | % wavelet_denoise.m - image denoise using wavelet
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function wavelet_denoise(wname, tname, tuning)
[vid_name, vid_frame, frame_count, frame_rate, duration, vid_width, vid_height] = import_video();
% THR = wthrmngr('dw2ddenoLVL','penalhi',C,S,ALFA)
% ALFA must be such that 2.5 < ALFA < 10
% THR = wthrmngr('dw2ddenoLVL','penalme',C,S,ALFA)
% ALFA must be such that 1.5 < ALFA < 2.5
% THR = wthrmngr('dw2ddenoLVL','penallo',C,S,ALFA)
% ALFA must be such that 1 < ALFA < 2
% THR = wthrmngr('dw2ddenoLVL','sqtwolog',C,S,SCAL)
% THR = wthrmngr('dw2ddenoLVL','sqrtbal_sn',C,S)
alpha = tuning;
glb = 0;
vidObj = VideoWriter([vid_name '_wavelet_denoise_' wname '_tuning_' tname '_' mat2str(tuning) '_global_thresh_' mat2str(glb) '.mp4'], 'MPEG-4');
open(vidObj);
figure();
title([wname ' Wavelet denoised Video ' tname ' tuning ' mat2str(tuning)]);
currAxes = axes;
test_frame_count = 20;
for iFrame=1: frame_count
input = vid_frame(iFrame).cdata;
in_name = [vid_name '_' mat2str(iFrame) '.bmp'];
if iFrame == 1
imwrite(input, in_name);
end
[row, col, channel] = size(input);
if channel == 3
input_yuv = rgb2yuv(input(:, :, 1), input(:, :, 2), input(:, :, 3));
else
input_yuv = rgb2yuv(input(:, :, 1), input(:, :, 1), input(:, :, 1));
end
input_yuv = im2double(input_yuv);
% Run local adaptive image denoising algorithm
for iChannel = 1: channel
output_yuv(:, :, iChannel) = 255 * denoising_dwt(input_yuv(:, :, iChannel), wname, tname, tuning);
end
if channel == 3
output = yuv2rgb(output_yuv(:, :, 1), output_yuv(:, :, 2), output_yuv(:, :, 3), 'YUV444_8');
else
output = output_yuv(:, :, 1);
end
output = im2double(output);
out_name = [vid_name '_' mat2str(iFrame) '_wavelet_denoise_' wname '_threh_' tname '_' mat2str(tuning) '.bmp'];
if iFrame == 1
imwrite(output, out_name);
end
image(output, 'Parent', currAxes);
currAxes.Visible = 'off';
pause(1/frame_rate);
writeVideo(vidObj, output)
iFrame
end
close(vidObj);
end |
github | gaoyuantim/LHS-Maximin-master | LHS_multi.m | .m | LHS-Maximin-master/LHS_SUM/LHS_multi.m | 2,284 | utf_8 | 858bdceba6500914048d76fb477d5a8d | % Input : n = number of points
% k = number of dimension
% sum = a group of square distance we are insterested in
%
% Output : A table if there is a conbinaison satisfying the command;
% "FALSE" if the result doesn't exist
%
% SYNTAX : Table = LHS_multi ( n , k , sum)
%
% Exemple : Table = LHS_multi(5, 8, [40]);
%
% Result :
%
% Table =
%
% 0 1 2 3 4
% 0 1 2 4 3
% 0 3 4 1 2
% 1 2 4 3 0
% 1 4 0 2 3
% 1 4 2 0 3
% 1 4 2 3 0
% 2 1 4 0 3
% Copyright Notice
%
% Copyright (C) 2016 Yuan Gao <[email protected]>
%
% Author: Yuan Gao <[email protected]>
%
% Copying Permission Statement
%
% This program is free software; you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as published
% by the Free Software Foundation; either version 2.1 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTA-
% BILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
% Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License along with this program; if not, see
% <http://www.gnu.org/licenses/>.
function [ table_Fix ] = LHS_Bound_multi( n , k , addition )
num_Addition = length(addition);
Table = [];
if num_Addition > 0
for i = 1:num_Addition
Table_Plus = sos_decompose( addition(i) , k , n - 1);
while Table_Plus(1,1) >= n * n
Table_Plus(1,:) = [];
end
Table = [ Table ; Table_Plus];
end
[Height, Length] = size(Table);
num_Result = zeros(1,(Height + 1)*(n - 1));
for i = 1:Height
for j = 1:Length
num = sqrt(Table(i,j));
num_Result(1,(i * (n - 1) + num)) = num_Result(1 , (i * (n - 1) + num)) + 1;
end
end
table_Fix = LHS_Bound_Sum(n, k, Height, num_Result)';
end
end
|
github | gaoyuantim/LHS-Maximin-master | sos_decompose.m | .m | LHS-Maximin-master/LHS_SUM/sos_decompose.m | 1,980 | utf_8 | bddfc9e37b618824e38d88e896a3f5f9 | % sos_decompose computes decompositions into sum of squares
%
% SYNTAX: sos = sos_decompose (S, k, n - 1)
%
% computes all possible decompositions of integer S into a sum of k squares
%
% EXAMPLE: S = 56, k = 6
%
% >> sos = sos_decompose (56, 6, 6)
%
% sos =
%
% 36 16 1 1 1 1
% 36 4 4 4 4 4
% 25 16 9 4 1 1
% 16 9 9 9 9 4
% Copyright Notice
%
% Copyright (C) 2016 CentraleSupelec
%
% Author: Julien Bect <[email protected]>
%
% Copying Permission Statement
%
% This program is free software; you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as published
% by the Free Software Foundation; either version 2.1 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTA-
% BILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
% Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License along with this program; if not, see
% <http://www.gnu.org/licenses/>.
function [sos, sos_all] = sos_decompose (S, k, dmax)
if k == 1
sos = cell (S, 1);
dmax = min (dmax, floor (sqrt (S)));
for t = 1:dmax
sos{t^2, 1} = t^2;
end
else
[~, sos] = sos_decompose (S, k - 1, dmax);
sos = [sos cell(S, 1)];
for SS = k:S,
dmax0 = min (dmax, floor (sqrt (SS - (k - 1))));
for t = dmax0:-1:1
B = sos{SS - t^2, k - 1};
if ~ isempty (B)
A = t^2 * (ones (size (B, 1), 1));
sos{SS, k} = [sos{SS, k}; [A B]];
end
end
sos{SS, k} = unique (sort (sos{SS, k}, 2, 'descend'), 'rows');
end
end % if
sos_all = sos;
sos = sos_all{end, end};
end
|
github | gaoyuantim/LHS-Maximin-master | LHS_D2.m | .m | LHS-Maximin-master/LHS_D2TEST/LHS_D2.m | 1,865 | utf_8 | cfb9abb99c5e99461417b1a9aaed6660 | % Input: n = number of points
% m = number of dimension
% D2 = the square distance tested
%
% Output: A table of points constructed by the maximin D2 if D2is suitable;
% "D2 too big" when D2 is too big
% "Dimension is to big" if m is bigger than 3
%
% SYNTAX: table = LHS_D2(n , m , D2)
%
% Exemple: table = LHS(15, 2, 17)
%
% table =
% 0 0
% 1 4
% 2 8
% 3 12
% 4 1
% 5 5
% 6 9
% 7 13
% 8 2
% 9 6
% 10 10
% 11 14
% 12 3
% 13 7
% 14 11
% Copyright Notice
%
% Copyright (C) 2016 Yuan Gao <[email protected]>
%
% Author: Yuan Gao <[email protected]>
%
% Copying Permission Statement
%
% This program is free software; you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as published
% by the Free Software Foundation; either version 2.1 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTA-
% BILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
% Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License along with this program; if not, see
% <http://www.gnu.org/licenses/>.
function [ table ] = LHS_D2( n , m , D2 )
if m == 2
table = LHS_D2_2( n , D2 );
else
if m == 3
table = LHS_D2_3( n , D2 );
else
disp('Dimension is to big');
end
end |
github | ojwoodford/ojwul-master | expm_srt_3d_sym.m | .m | ojwul-master/symbolic/expm_srt_3d_sym.m | 1,705 | utf_8 | d73555feef49a0dfba8a2780aed71738 | %EXPM_SRT_3D Compute a transformation matrix, given the Lie algebra vector
%
% M = expm_srt_3d_sym(r, [t, [s]])
%
% Computes the symbolic transformation matrix defined by a Lie vector
% consisting of a rotation, translation and uniform scaling.
%
% This function applies the formula given in the paper:
% "Distances and Means of Direct Similarities"
% M-T Pham et al.
%
%IN:
% r - 3x1 rotation parameter vector
% t - 3x1 translation parameter vector. Default: [].
% s - scalar uniform scaling parameter. Default: 0.
%
%OUT:
% M - 3x3 (if t == []) or 4x4 transformation matrix.
function M = expm_srt_3d_sym(r, t, s)
% Default values
if nargin < 3
s = sym(0);
if nargin < 2
t = [];
end
end
% Angles
theta2 = r(:)' * r(:);
theta = sqrt(theta2);
% Skew matrix
W = skew(r);
W2 = W * W;
% Rotation matrix via Rodrigues formula
M = W * sinc(theta) + W2 * cosf(theta) + eye(3);
% Apply scale
M = M * exp(s);
if isempty(t)
return;
end
% Translation multipler
if nargin < 3
eta_r = sym(1) - sinc(theta);
eta_i = cosf(theta);
else
x = cos(theta) * exp(s) - 1;
y = sin(theta) * exp(s);
eta_r = expf(s) - (s * x + theta * y) / (s * s);
eta_i = (s * y - theta * x) / (theta * (s * s + theta2));
end
eta_r = at0is1(theta2, @(theta2) eta_r / theta2);
A = W * eta_i + W2 * eta_r + (eye(3) * expf(s));
% Compute the translation part
M(1:3,4) = simplify(A * t(:));
end
function x = sinc(x)
x = at0is1(x, @(x) sin(x) / x);
end
function x = cosf(x)
x = at0is1(x, @(x) (1 - cos(x)) / (x * x));
end
function x = expf(x)
x = at0is1(x, @(x) (exp(x) - 1) / x);
end
function x = at0is1(x, fun)
if isequal(x, sym(0))
x = sym(1);
else
x = fun(x);
end
end
|
github | ojwoodford/ojwul-master | line2line_symeq.m | .m | ojwul-master/symbolic/line2line_symeq.m | 1,057 | utf_8 | 0dbe06c4fc41a0ef82989a6c30386fb3 | %LINE2LINE_SYMEQ Compute the shortest vector between two lines
%
% y = line2line_symeq(x1, d1, x2, d2)
%
% Symbolically computes the shortest vector between two lines.
%
%IN:
% x1 - Nx1 point on line 1.
% d1 - Nx1 direction vector of line 1.
% x2 - Nx1 point on line 2.
% d2 - Nx1 direction vector of line 2.
%
%OUT:
% y - Nx1 shortest vector.
function y = line2line_symeq(x1, d1, x2, d2)
persistent eq tv
N = numel(x1);
if numel(eq) ~= N
% Compute the line to line shortest vector once
% Initialize symbolic variables
x1_ = sym(sym('x1%d', [N 1]), 'real');
d1_ = sym(sym('d1%d', [N 1]), 'real');
x2_ = sym(sym('x2%d', [N 1]), 'real');
d2_ = sym(sym('d2%d', [N 1]), 'real');
syms l1 l2 real
eq = x1_ + d1_ * l1 - x2_ - d2_ * l2;
l = solve(jacobian(eq' * eq, [l1 l2]) == [0 0], l1, l2); % Simultaneous equations
eq = simplify(subs(eq, [l1; l2], [l.l1; l.l2]));
tv = [x1_; d1_; x2_; d2_];
end
if nargin < 4
y = eq;
else
y = subs(eq, tv, [x1; d1; x2; d2]);
end |
github | ojwoodford/ojwul-master | point2line_symeq.m | .m | ojwul-master/symbolic/point2line_symeq.m | 861 | utf_8 | 69a05298ede557a9ee8ad43f6ed3c8fe | %POINT2LINE_SYMEQ Compute the shortest vector between a point and a line
%
% V = point2line_symeq(X, Y, D)
%
% Symbolically computes the shortest vector between a point and a line in
% N-D.
%
%IN:
% X - Nx1 point.
% Y - Nx1 point on the line.
% D - Nx1 line direction.
%
%OUT:
% V - Nx1 output vector.
function v = point2line_symeq(X, Y, D)
persistent eq tv
N = numel(X);
if numel(tv) ~= N * 3
% Initialize symbolic variables
tv = sym(sym('tv%d', [N*3 1]), 'real');
X_ = tv(1:N);
Y_ = tv(N+1:2*N);
D_ = tv(2*N+1:3*N);
% Compute the point to line vector equation once
syms l real
eq = X_ - Y_ - D_ * l;
l_sol = solve(diff(sum(eq .^ 2), l) == sym(0), l); % Minimize error
eq = simplify(subs(eq, l, l_sol));
end
if nargin < 3
v = eq;
else
v = subs(eq, tv, [X; Y; D]);
end |
github | ojwoodford/ojwul-master | auto_jacobian.m | .m | ojwul-master/symbolic/auto_jacobian.m | 4,521 | utf_8 | 59d589cacf7beca35565336113c19730 | %AUTO_JACOBIAN Write and compile a mex file to compute Jacobian of residuals
%
% auto_jacobian(residuals, params, fname, var_fixed, var_sum)
%
% This function differentiates a symbolic set of resdiuals with respect to
% some parameters, creates a mex file which can compute the residuals and
% the derivatives, and finally compiles the mex file.
%
%IN:
% residuals - Mx1 set of symbolic equations for some residuals.
% params - Nx1 set of symbolic variables to differentiate the residuals
% with respect to.
% fname - String containing the file name (or full path) of the mex file
% to be written, including the extension.
% var_fixed - Px1 set of symbolic variables which are the same for every
% column of var_sum variables.
% var_sum - Qx1 set of symbolic variables, of which many sets can be
% passed to the mex file (see below).
%
% The resulting mex function operates in the form:
% [res, J] = fname(var_fixed, var_sum)
%
%IN:
% var_fixed - Px1 vector of fixed variables.
% var_sum - QxR array of R vectors of variables which are looped over.
%
%OUT:
% res - MxR array of residuals
% J - (M*N)xR array of Jacobians
function auto_jacobian(residuals, params, fname, var_fixed, var_sum)
fprintf('AUTO JACOBIAN: %s\n', fname)
% Residuals with zero inputs
fprintf('Residuals at zero...'); drawnow;
tic
res = subs(residuals, params, zeros(size(params)));
fprintf(' %gs.\n', toc);
% Compute the Jacobian of the residuals
fprintf('Compute Jacobian...'); drawnow;
tic
J = jacobian(residuals, params);
fprintf(' %gs.\n', toc);
% Linearize the Jacobian w.r.t. the parameters
fprintf('Taylor expansion...'); drawnow;
tic
J = subs(J, params, zeros(size(params)));
fprintf(' %gs.\n', toc);
% Turn into some C code
fprintf('Generating C code...'); drawnow;
tic
res = res(:)';
J = J(:)';
res_ = write_C_fragment(res);
J_ = write_C_fragment(J);
% % Generate the other lines of the C file
lines = { ...
'#include "mex.h"', ...
'#include <math.h>', ...
'void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {', ...
'if (nrhs != 2 || nlhs < 1 || nlhs > 2) { mexErrMsgTxt("Unexpected number of arguments."); }', ...
['if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || mxGetNumberOfElements(prhs[0]) != ' num2str(numel(var_fixed)) ')'], ...
'{ mexErrMsgTxt("First input of unexpected size or type"); }', ...
['if (!mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || mxGetM(prhs[1]) != ' num2str(numel(var_sum)) ')'], ...
'{ mexErrMsgTxt("Second input of unexpected size or type"); }', ...
'const double *var_fixed = (const double *)mxGetData(prhs[0]);', ...
'const double *var_sum = (const double *)mxGetData(prhs[1]);', ...
'int N = mxGetN(prhs[1]);', ...
['plhs[0] = mxCreateNumericMatrix(' num2str(numel(res)) ', N, mxDOUBLE_CLASS, mxREAL);'], ...
'double *res = (double *)mxGetData(plhs[0]);', ...
'double *J = NULL;', ...
['if (nlhs > 1) { plhs[1] = mxCreateNumericMatrix(' num2str(numel(J)) ', N, mxDOUBLE_CLASS, mxREAL); J = (double *)mxGetData(plhs[1]); }'], ...
['for (int a = 0; a < N; ++a, var_sum += ' num2str(numel(var_sum)) ', res += ' num2str(numel(res)) ') {'], ...
res_, ...
'if (J) { ', ...
J_, ...
['J += ' num2str(numel(J)) ';'], ...
'}}}', ...
};
% Write out to a file
fid = fopen(fname, 'wt');
for l = lines
fprintf(fid, [l{1} '\n']);
end
fclose(fid);
fprintf(' %gs.\n', toc);
% Mex the function
fprintf('Compiling...'); drawnow;
tic
try
mex(fname, '-O');
catch me
% The file might be in use - just report the error
fprintf('%s\n', getReport(me, 'basic'));
end
fprintf(' %gs.\n', toc);
end
function str = write_C_fragment(symFunc)
% Save the C code to file
fname = [tempname '.cpp'];
ccode(symFunc, 'file', fname);
% Read in the code fragment
fid = fopen(fname, 'rt');
str = textscan(fid, '%s', 'delimiter', '\n');
fclose(fid);
% Delete the file
delete(fname);
% Deal with single value cases
str = str{1};
if numel(symFunc) == 1
str{end} = regexprep(str{end}, '\S+ = ', 'A0[0][0] = ');
end
% Remove the extra dimension from the output, and change the variable name
str = strrep(sprintf(' %s\n', str{:}), 'A0[0][', [inputname(1) '[']);
% Add double to the start of temporary variables
str = regexprep(str, ' t(\d*) = ', ' double t${$1} = ');
% Put in the brackets
sub1 = @(n) num2str(str2double(n) - 1);
str = regexprep(str, '_l_(\d*)_r_', '[${sub1($1)}]');
end |
github | ojwoodford/ojwul-master | line_plane_intersect_symeq.m | .m | ojwul-master/symbolic/line_plane_intersect_symeq.m | 976 | utf_8 | 0d0bfa0e138deee193332d77058887cf | %LINE_PLANE_INTERSECT_SYMEQ Compute the intersection point of a line and a plane
%
% y = line_plane_intersect_symeq(n, d, x, l)
%
% Symbolically computes the point of intersection of a line and a plane in
% N dimensions.
%
%IN:
% n - Nx1 plane normal.
% d - scalar plane offset from origin.
% x - Nx1 point on line.
% l - Nx1 line direction.
%
%OUT:
% y - Nx1 output point.
function y = line_plane_intersect_symeq(n, d, x, l)
persistent eq tv
N = numel(n);
if numel(tv) ~= N * 3 + 1
% Compute the line-plane intersection equation once
% Initialize symbolic variables
n_ = sym(sym('n%d', [N 1]), 'real');
x_ = sym(sym('x%d', [N 1]), 'real');
l_ = sym(sym('l%d', [N 1]), 'real');
syms d_ y_ real
y_ = solve(n_' * (x_ + l_ * y_) + d_ == 0, y_); % Simultaneous equations
eq = simplify(x_ + l_ * y_);
tv = [n_; d_; x_; l_];
end
if nargin < 4
y = eq;
else
y = subs(eq, tv, [n; d; x; l]);
end |
github | ojwoodford/ojwul-master | rodrigues_sym.m | .m | ojwul-master/symbolic/rodrigues_sym.m | 391 | utf_8 | d5e8d50b3c288fa16f358e632a712665 | %RODRIGUES_SYM Transform angle-axis to rotation matrix via Rodrigues' formula
%
% R = rodrigues_sym(axis, angle)
%
%IN:
% axis - 3x1 normalized rotation axis vector.
% angle - rotation angle in radians.
%
%OUT:
% R - 3x3 rotation matrix
function R = rodrigues_sym(axis, angle)
R = sin(angle) * skew(axis) + (1 - cos(angle)) * (axis * axis') + cos(angle) * eye(3);
end
|
github | ojwoodford/ojwul-master | line_intersect_symeq.m | .m | ojwul-master/symbolic/line_intersect_symeq.m | 999 | utf_8 | bddacbc394544901eb2327cc6b5a0837 | %LINE_INTERSECT_SYMEQ Compute the intersection point of two lines
%
% y = line_intersect_symeq(x1, n1, x2, n2)
%
% Symbolically computes the point of intersection of two lines in 2D.
%
%IN:
% x1 - 2x1 point on line 1.
% n1 - 2x1 direction of line 1.
% x2 - 2x1 point on line 2.
% n2 - 2x1 direction of line 2.
%
%OUT:
% v - 2x1 output point.
function y = line_intersect_symeq(x1, n1, x2, n2)
persistent eq tv
if isempty(eq)
% Compute the line intersection equation once
syms l1 l2 x1_1 x1_2 n1_1 n1_2 x2_1 x2_2 n2_1 n2_2 real
tv = [x1_1 x1_2 n1_1 n1_2 x2_1 x2_2 n2_1 n2_2]';
eq = tv(1:2) + tv(3:4) * l1;
l1_sol = getfield(solve(eq == tv(5:6) + tv(7:8) * l2, l1, l2), 'l1'); % Simultaneous equations
%l1_sol = getfield(solve(diff(sum((tv(5:6) + tv(7:8) * l2 - eq) .^ 2), l1) == 0, l1, l2), 'l1'); % Minimize error
eq = simplify(subs(eq, l1, l1_sol));
end
if nargin < 4
y = eq;
else
y = subs(eq, tv, [x1; n1; x2; n2]);
end |
github | ojwoodford/ojwul-master | epipolar_disparity_symeq.m | .m | ojwul-master/symbolic/epipolar_disparity_symeq.m | 1,450 | utf_8 | f1f4bffbbd83488796b8172d19b7edd4 | %EPIPOLAR_DISPARITY_SYMEQ Compute the disparity of a point on/near an
% epipolar line
%
% d = epipolar_disparity_symeq(RX, T, x)
%
% Symbolically computes the disparity of a point on an epipolar line that
% is closest to a point in an image.
%
%IN:
% RX - 3x1 world point multiplied by rotation part of projection matrix
% P(:,1:3).
% T - 3x1 translation part of project matrix P(:,4).
% x - 2x1 corresponding point in the image.
%
%OUT:
% d - output disparity.
function [d, d_] = epipolar_disparity_symeq(RX, T, x, cov)
persistent eq tv
proj = @(X) X(1:2) / X(3);
if isempty(eq)
% Compute the point to line distance equation once
tv = [sym('RX%d', [3 1]); sym('T%d', [3 1]); sym('x%d', [2 1]); col(sym('cov%d', [2 2]))];
assume(tv, 'real');
syms d_ real
eq = (proj(tv(1:3) + tv(4:6) * d_) - tv(7:8));
eq = simplify(solve(diff(eq' * eq, d_) == sym(0), d_), 'Steps', 10); % Minimize error
end
if nargin < 4
d = eq;
if nargout > 1 || nargout == 0
% Output the point to line residual error
d_ = simplify((proj(tv(1:3) + tv(4:6) * eq) - tv(7:8)), 'Steps', 10);
d_ = simplify(sqrt(d_' * d_));
if nargout == 0
% Write a MATLAB function to compute the error
matlabFunction(d_, 'File', 'epipolar_error_symeq');
end
end
else
d = subs(eq, tv, [RX; T; x; col(cov)]);
end
|
github | ojwoodford/ojwul-master | expm_sym.m | .m | ojwul-master/symbolic/expm_sym.m | 575 | utf_8 | 489d9f3dac40fbc2056f001932f0e1d2 | %EXPM_SYM Symbolic matrix exponential, up to a certain order
%
% B = expm_sym(A, order)
%
% Given a symbolic (or numeric) matrix, this function computes an
% approximation of the matrix exponential up to a certain order.
%
%IN:
% A - MxM input matrix.
% order - scalar indicating the order up to which the matrix exponential
% is to be computed.
%
%OUT:
% B - MxM output matrix.
function B = expm_sym(A, order)
B = eye(size(A));
if isa(A, 'sym')
B = sym(B);
end
A_ = B;
for a = 1:order
A_ = A_ * (A / a);
B = B + A_;
end |
github | ojwoodford/ojwul-master | auto_diff.m | .m | ojwul-master/symbolic/auto_diff.m | 1,967 | utf_8 | 8bfe59eb60832fd92cb22fd26784cca2 | %AUTO_DIFF Output C code to compute function values and their Jacobian
%
% C = auto_diff(funcs, vars, curr_val)
%
% This function differentiates a symbolic set of resdiuals with respect to
% some parameters.
%
%IN:
% funcs - Mx1 vector of functional expressions.
% vars - Nx1 vector of variables to differentiate over.
% curr_val - Nx1 vector of current values for each variable.
%
%OUT:
% C - text array of C code to compute M function outputs and MxN Jacobian
% coefficients.
function C = auto_diff(funcs, vars, curr_val)
% Compute the function values
F = subs(funcs, vars, curr_val);
% Compute the Jacobian of the functions
J = jacobian(funcs, vars);
% Linearize the Jacobian w.r.t. the variables
J = subs(J, vars, curr_val);
% Turn into some C code
C = write_C_fragment([F(:)' J(:)']);
end
function str = write_C_fragment(symFunc)
% Save the C code to file
fname = [tempname '.cpp'];
ccode(symFunc, 'file', fname);
% Read in the code fragment
fid = fopen(fname, 'rt');
str = textscan(fid, '%s', 'delimiter', '\n');
fclose(fid);
% Delete the file
delete(fname);
% Deal with single value cases
str = str{1};
if numel(symFunc) == 1
str{end} = regexprep(str{end}, '\S+ = ', 'A0[0][0] = ');
end
% Remove the extra dimension from the output, and change the variable name
str = strrep(sprintf(' %s\n', str{:}), 'A0[0][', 'out[');
% Add float to the start of temporary variables
str = regexprep(str, ' t(\d*) = ', ' float t${$1} = ');
% Replace special strings
% Replace brackets
sub1 = @(n) num2str(str2double(n) - 1);
str = regexprep(str, '_l_(\d+)_r_', '[${sub1($1)}]');
% Put in dots
str = regexprep(str, '_d_', '.');
% Find those outputs which haven't been set
I = regexp(str, 'out\[(\d+)\] = ', 'tokens');
I = find(~ismember((0:numel(symFunc)-1)', str2double([I{:}])'));
% Set the zero outputs
if ~isempty(I)
str = [str sprintf(' out[%d] = 0;\n', I - 1)];
end
end |
github | ojwoodford/ojwul-master | skew.m | .m | ojwul-master/geometry/skew.m | 510 | utf_8 | 8d41bfbc4fce7e037e11d9dc8a290ec6 | %SKEW Generate 3x3 skew matrices from 3-vectors
%
% B = skew(A)
%
% Convert one or more 3-vectors to 3x3 skew matrices.
%
%IN:
% A - 3xM matrix of 3-vectors
%
%OUT:
% B - 3x3xM array of skew matrices
function B = skew(A)
sz = size(A);
assert(sz(1) == 3);
sz = [3 3 sz(2:end)];
if isa(A, 'sym')
B = sym(zeros(sz));
else
B = zeros(sz, class(A));
end
B(2,1,:) = A(3,:);
B(3,1,:) = -A(2,:);
B(1,2,:) = -A(3,:);
B(3,2,:) = A(1,:);
B(1,3,:) = A(2,:);
B(2,3,:) = -A(1,:);
end |
github | ojwoodford/ojwul-master | dpsimplify.m | .m | ojwul-master/geometry/dpsimplify.m | 7,986 | utf_8 | 3ef3a9b3638b7390a28425512f9f262e | function [ps,ix] = dpsimplify(p,tol)
% Recursive Douglas-Peucker Polyline Simplification, Simplify
%
% [ps,ix] = dpsimplify(p,tol)
%
% dpsimplify uses the recursive Douglas-Peucker line simplification
% algorithm to reduce the number of vertices in a piecewise linear curve
% according to a specified tolerance. The algorithm is also know as
% Iterative Endpoint Fit. It works also for polylines and polygons
% in higher dimensions.
%
% In case of nans (missing vertex coordinates) dpsimplify assumes that
% nans separate polylines. As such, dpsimplify treats each line
% separately.
%
% For additional information on the algorithm follow this link
% http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
%
% Input arguments
%
% p polyline n*d matrix with n vertices in d
% dimensions.
% tol tolerance (maximal euclidean distance allowed
% between the new line and a vertex)
%
% Output arguments
%
% ps simplified line
% ix linear index of the vertices retained in p (ps = p(ix))
%
% Examples
%
% 1. Simplify line
%
% tol = 1;
% x = 1:0.1:8*pi;
% y = sin(x) + randn(size(x))*0.1;
% p = [x' y'];
% ps = dpsimplify(p,tol);
%
% plot(p(:,1),p(:,2),'k')
% hold on
% plot(ps(:,1),ps(:,2),'r','LineWidth',2);
% legend('original polyline','simplified')
%
% 2. Reduce polyline so that only knickpoints remain by
% choosing a very low tolerance
%
% p = [(1:10)' [1 2 3 2 4 6 7 8 5 2]'];
% p2 = dpsimplify(p,eps);
% plot(p(:,1),p(:,2),'k+--')
% hold on
% plot(p2(:,1),p2(:,2),'ro','MarkerSize',10);
% legend('original line','knickpoints')
%
% 3. Simplify a 3d-curve
%
% x = sin(1:0.01:20)';
% y = cos(1:0.01:20)';
% z = x.*y.*(1:0.01:20)';
% ps = dpsimplify([x y z],0.1);
% plot3(x,y,z);
% hold on
% plot3(ps(:,1),ps(:,2),ps(:,3),'k*-');
% Author: Wolfgang Schwanghart, 13. July, 2010.
% w.schwanghart[at]unibas.ch
%
% Copyright (c) 2009, Wolfgang Schwanghart
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
if nargin == 0
help dpsimplify
return
end
error(nargchk(2, 2, nargin))
% error checking
if ~isscalar(tol) || tol<0;
error('tol must be a positive scalar')
end
% nr of dimensions
nrvertices = size(p,1);
dims = size(p,2);
% anonymous function for starting point and end point comparision
% using a relative tolerance test
compare = @(a,b) abs(a-b)/max(abs(a),abs(b)) <= eps;
% what happens, when there are NaNs?
% NaNs divide polylines.
Inan = any(isnan(p),2);
% any NaN at all?
Inanp = any(Inan);
% if there is only one vertex
if nrvertices == 1 || isempty(p);
ps = p;
ix = 1;
% if there are two
elseif nrvertices == 2 && ~Inanp;
% when the line has no vertices (except end and start point of the
% line) check if the distance between both is less than the tolerance.
% If so, return the center.
if dims == 2;
d = hypot(p(1,1)-p(2,1),p(1,2)-p(2,2));
else
d = sqrt(sum((p(1,:)-p(2,:)).^2));
end
if d <= tol;
ps = sum(p,1)/2;
ix = 1;
else
ps = p;
ix = [1;2];
end
elseif Inanp;
% case: there are nans in the p array
% --> find start and end indices of contiguous non-nan data
Inan = ~Inan;
sIX = strfind(Inan',[0 1])' + 1;
eIX = strfind(Inan',[1 0])';
if Inan(end)==true;
eIX = [eIX;nrvertices];
end
if Inan(1);
sIX = [1;sIX];
end
% calculate length of non-nan components
lIX = eIX-sIX+1;
% put each component into a single cell
c = mat2cell(p(Inan,:),lIX,dims);
% now call dpsimplify again inside cellfun.
if nargout == 2;
[ps,ix] = cellfun(@(x) dpsimplify(x,tol),c,'uniformoutput',false);
ix = cellfun(@(x,six) x+six-1,ix,num2cell(sIX),'uniformoutput',false);
else
ps = cellfun(@(x) dpsimplify(x,tol),c,'uniformoutput',false);
end
% write the data from a cell array back to a matrix
ps = cellfun(@(x) [x;nan(1,dims)],ps,'uniformoutput',false);
ps = cell2mat(ps);
ps(end,:) = [];
% ix wanted? write ix to a matrix, too.
if nargout == 2;
ix = cell2mat(ix);
end
else
% if there are no nans than start the recursive algorithm
ixe = size(p,1);
ixs = 1;
% logical vector for the vertices to be retained
I = true(ixe,1);
% call recursive function
p = simplifyrec(p,tol,ixs,ixe);
ps = p(I,:);
% if desired return the index of retained vertices
if nargout == 2;
ix = find(I);
end
end
% _________________________________________________________
function p = simplifyrec(p,tol,ixs,ixe)
% check if startpoint and endpoint are the same
% better comparison needed which included a tolerance eps
c1 = num2cell(p(ixs,:));
c2 = num2cell(p(ixe,:));
% same start and endpoint with tolerance
sameSE = all(cell2mat(cellfun(compare,c1(:),c2(:),'UniformOutput',false)));
if sameSE;
% calculate the shortest distance of all vertices between ixs and
% ixe to ixs only
if dims == 2;
d = hypot(p(ixs,1)-p(ixs+1:ixe-1,1),p(ixs,2)-p(ixs+1:ixe-1,2));
else
d = sqrt(sum(bsxfun(@minus,p(ixs,:),p(ixs+1:ixe-1,:)).^2,2));
end
else
% calculate shortest distance of all points to the line from ixs to ixe
% subtract starting point from other locations
pt = bsxfun(@minus,p(ixs+1:ixe,:),p(ixs,:));
% end point
a = pt(end,:)';
beta = (a' * pt')./(a'*a);
b = pt-bsxfun(@times,beta,a)';
if dims == 2;
% if line in 2D use the numerical more robust hypot function
d = hypot(b(:,1),b(:,2));
else
d = sqrt(sum(b.^2,2));
end
end
% identify maximum distance and get the linear index of its location
[dmax,ixc] = max(d);
ixc = ixs + ixc;
% if the maximum distance is smaller than the tolerance remove vertices
% between ixs and ixe
if dmax <= tol;
if ixs ~= ixe-1;
I(ixs+1:ixe-1) = false;
end
% if not, call simplifyrec for the segments between ixs and ixc (ixc
% and ixe)
else
p = simplifyrec(p,tol,ixs,ixc);
p = simplifyrec(p,tol,ixc,ixe);
end
end
end
|
github | ojwoodford/ojwul-master | icp_sim.m | .m | ojwul-master/geometry/icp_sim.m | 2,615 | utf_8 | e6c911fa5628d4af5a576be7042fc42f | %ICP_SIM Compute the similarity transform that best aligns two point sets
%
% T = icp_sim(X, Y, [initialize])
%
% Given two sets of points, X and Y, this function iteratively solves the
% optimization problem:
%
% T = argmin_T sum_i min_j || T * homg(X(:,i)) - Y(:,j) || ^ 2
%
% subject to T being a similarity transform.
%
%IN:
% X - DxM set of D-dimensional points to transform
% Y - DxN set of D-dimensional points to align to (which should be well
% distributed)
% initialize - Scalar, 0 (no initialization), 1 (try 4 starting
% positions), 2 (optimize 4 starting positions for 4
% iterations each).
%
%OUT:
% T - Dx(D+1) similarity transform matrix.
function T = icp_sim(X, Y, initialize, debug_vis)
% Initialize the search function
Xt = X';
Yt = Y';
tri = delaunayn(Yt);
find_closest = @(X) dsearchn(Yt, tri, X);
% Initialize the output
if nargin > 2 && initialize
% Prealign using principle components
[~, T] = whiten_srt(X);
[~, T_] = whiten_srt(Y);
% Try 4 possible axis flips
R = cat(3, diag([1 1 1 1]), diag([1 -1 -1 1]), diag([-1 1 -1 1]), diag([-1 -1 1 1]));
for a = 4:-1:1
d = T_ \ (R(:,:,a) * T);
T__{a} = d(1:end-1,:) / d(end,end);
if initialize == 1
[~, d] = find_closest(Xt * T__{a}(:,1:end-1)' + T__{a}(:,end)');
scores(a) = sum(d);
else
[T__{a}, scores(a)] = run_iters(Xt, Yt, T__{a}, find_closest, [], 4);
end
end
% Pick the best
[~, a] = min(scores);
T = T__{a};
else
% Start from the input
T = eye(size(X, 1), size(X, 1)+1);
end
% Debug rendering
handle = [];
if nargin > 3 && debug_vis
figure();
plot3(Yt(:,1), Yt(:,2), Yt(:,3), 'b.');
hold on
handle = plot3(Xt(:,1), Xt(:,2), Xt(:,3), 'r.');
end
% Iterate until convergence
T = run_iters(Xt, Yt, T, find_closest, handle, 100);
end
function [T, best_score] = run_iters(Xt, Yt, T, find_closest, handle, iters)
R = T(:,1:end-1)';
t = T(:,end);
best_score = Inf;
while iters > 0
iters = iters - 1;
% Compute the closest points from X to Y
X_ = Xt * R + t';
closest = find_closest(X_);
% Debug rendering
if ~isempty(handle)
set(handle, 'XData', X_(:,1), 'YData', X_(:,2), 'ZData', X_(:,3));
drawnow();
end
% Solve the procrustes problem
[R, s, t, ~, score] = procrustes(Xt, Yt(closest,:));
% Check the score decreased
if score >= best_score
break;
end
best_score = score;
% Compute the transform
R = s * R;
T = [R', t];
end
end
|
github | ojwoodford/ojwul-master | expm_srt_3d.m | .m | ojwul-master/geometry/expm_srt_3d.m | 964 | utf_8 | 57095643f98d6b694e028be1a0770c4e | %EXPM_SRT_3D Compute a transformation matrix, given the Lie algebra vector
%
% M = expm_srt_3d(X)
%
% Computes the transformation matrix defined by a Lie vector consisting of
% a rotation, translation and uniform scaling.
%
% The computation is done in closed form, using the formulae given in the
% paper:
% "Distances and Means of Direct Similarities"
% M-T Pham et al.
%
%IN:
% X - DxN array, where each column specifies a different
% transformation. X(1:3,:) are the rotation components, X(4:6,:) are
% the translation components and X(7,:) are the scale components. D
% can be 3 (rotation only), 6 (rotation and translation), or 7
% (rotation, translation and scale).
%
%OUT:
% M - 3x(3+D~=3)xN array of transformation matrices.
function varargout = expm_srt_3d(varargin)
sourceList = {'expm_srt_3d.cpp', '-Xopenmp'}; % Cell array of source files
[varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here
return
|
github | ojwoodford/ojwul-master | msac_essenmatrix.m | .m | ojwul-master/geometry/msac_essenmatrix.m | 3,819 | utf_8 | 0690ca4344b59de9c1327c1934dbc232 | % MSAC_ESSENMATRIX - fits essential matrix using RANSAC
%
% Usage: [F, inliers] = msac_essenmatrix(x1, x2, K, t)
%
% Arguments:
% x1 - 2xN or 3xN set of homogeneous image points. If the data is
% 2xN it is assumed the homogeneous scale factor is 1.
% x2 - 2xN or 3xN set of homogeneous image points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
% Note that point coordinates are normalised to that their
% mean distance from the origin is sqrt(2). The value of
% t should be set relative to this, say in the range
% 0.001 - 0.01
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% E - The 3x3 essential matrix such that x2'Fx1 = 0.
% inliers - An array of indices of the elements of x1, x2 that were
% the inliers for the best model.
function [E, D, stats] = msac_essenmatrix(x1, x2, K, t)
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
[rows,npts] = size(x1);
if rows~=2 && rows~=3
error('x1 and x2 must have 2 or 3 rows');
end
if rows == 2 % Pad data with homogeneous scale factor of 1
x1 = [x1; ones(1,npts)];
x2 = [x2; ones(1,npts)];
end
% Convert from image to calibrated coordinates
x1n = K \ x1;
x2n = K \ x2;
t = t / prod(K([1 5]));
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[E, inliers, stats] = msac([x1n; x2n], @(x) calibrated_fivepoint(x(1:3,:), x(4:6,:)), @(E, x) funddist(E, x(1:3,:), x(4:6,:)), 5, t);
inliers = inliers < t;
if sum(inliers) > 7
% Now do a final least squares fit on the data points considered to
% be inliers, using the normalized 8-point algorithm
[T, T] = normalise2dpts([x1 x2]);
x1n = T * x1;
x2n = T * x2;
E = fundmatrix(x1n(:,inliers), x2n(:,inliers));
E = T' * E * T;
E = E / E(3,3);
E = K' * E * K;
end
if nargout < 2
return;
end
% Compute the distances
D = funddist(K' \ E / K, x1, x2);
end
%--------------------------------------------------------------------------
% 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
function F = fundmatrix(x1, x2)
% Build the constraint matrix
F = [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(size(x1, 2),1) ];
[U, D, F] = svd(F,0); % Under MATLAB use the economy decomposition
% Extract fundamental matrix from the column of V corresponding to
% smallest singular value.
F = reshape(F(:,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, F] = svd(F,0);
F = U * diag([D(1,1) D(2,2) 0]) * F';
end
%--------------------------------------------------------------------------
% Function to evaluate the first order approximation of the geometric error
% (Sampson distance) of the fit of a fundamental matrix with respect to a
% set of matched points as needed by RANSAC. See: Hartley and Zisserman,
% 'Multiple View Geometry in Computer Vision', page 270.
function D = funddist(F, x1, x2)
Fx = F * x1;
x2tFx1 = sum(x2 .* Fx, 1);
Fx = [Fx; F' * x2];
% Evaluate distances
D = (x2tFx1 .* x2tFx1) ./ sum(Fx .* Fx, 1);
end
|
github | ojwoodford/ojwul-master | P_from_E.m | .m | ojwul-master/geometry/P_from_E.m | 449 | utf_8 | f98fa8604cb24d9a9117de47abe6ed3c | %P_FROM_E Compute potential motion hypotheses from an essential matrix
%
% P = P_from_E(E)
%
%IN:
% E - 3x3 essential matrix.
%
%OUT:
% P - 3x4x4 array of 4 potential extrinsic matrices [R, t] (up to scale).
function P = P_from_E(P)
[U, W, V] = svd(P, 0);
W = [0 -1 0; 1 0 0; 0 0 1];
R = U * W * V';
if det(R) < 0
U = -U;
R = -R;
end
U3 = U(:,3);
P = U * W' * V';
P = cat(3, [R U3], [R -U3], [P U3], [P -U3]);
end |
github | ojwoodford/ojwul-master | msac_homography.m | .m | ojwul-master/geometry/msac_homography.m | 3,945 | utf_8 | 02cbf66faa2fb293c01d4c9dc6f816ff | % msac_homography - fits fundamental matrix using RANSAC
%
% Usage: [H, inliers] = msac_homography(x1, x2, t)
%
% Arguments:
% x1 - 2xN set of points.
% x2 - 2xN set of homogeneous points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
% Note that point coordinates are normalised to that their
% mean distance from the origin is sqrt(2). The value of
% t should be set relative to this, say in the range
% 0.001 - 0.01
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% H - The 3x3 homography such that x2 = proj(H*homg(x1)).
% D - 1xN array of squared errors.
%
function [H, D, stats] = msac_homography(x1, x2, t)
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
% Normalize each set of points so that the origin is at centroid and
% mean distance from origin is sqrt(2). normalize2dpts also ensures the
% scale parameter is 1.
[x1n, T1] = whiten(x1);
x1n = homg(x1n);
[x2n, T2] = whiten(x2);
x2n = homg(x2n);
t = t * T2(1) * T2(5);
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[H, D, stats] = msac([x1n; x2n], @(x) homography2d(x(1:3,:), x(4:6,:)), @(H, x) homogdist2d(H, x(1:3,:), x(4:6,:)), 4, t);
D = D < t;
% Iterate the least squares fit on the data points considered to
% be inliers
for a = 1:5
D_ = D;
H_ = homography2d(x1n(:,D), x2n(:,D));
if isempty(H_)
break;
end
D = homogdist2d(H_, x1n, x2n) < t;
if isequal(D_, D)
break;
end
if sum(D_) > sum(D)
break;
end
H = H_;
end
% Denormalize
H = T2 \ H * T1;
if nargout < 2
return;
end
% Compute the distances
D = homogdist2d(H, homg(x1), homg(x2));
end
%----------------------------------------------------------------------
% HOMOGRAPHY2D - computes 2D homography
%
% Usage: H = homography2d(x1, x2)
%
% 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.
function H = homography2d(x1, x2)
H = [];
if iscolinear(x1) || iscolinear(x2)
return;
end
% 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 = size(x1, 2);
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(1,n,:) = [ O -w*X y*X];
A(2,n,:) = [ w*X O -x*X];
A(3,n,:) = [-y*X x*X O ];
end
A = reshape(A, 3*Npts, 9);
[U, D, V] = svd(A, 0); % 'Economy' decomposition for speed
% Extract homography
H = reshape(V(:,9), 3, 3)';
end
%----------------------------------------------------------------------
% Function to evaluate the symmetric transfer error of a homography with
% respect to a set of matched points as needed by RANSAC.
function D = homogdist2d(H, x1, x2)
% Calculate, in both directions, the distances
D = [x1 - hnormalise(H \ x2); x2 - hnormalise(H * x1)];
D = 0.5 * sum(D .* D, 1);
end
%----------------------------------------------------------------------
% Test whether any 3 of the 4 points in each set is colinear.
function tf = iscolinear(x)
try
tf = any(normd(cross(x(:,[1 1 1 2]) - x(:,[2 2 3 3]), x(:,[1 1 1 2]) - x(:,[3 4 4 4])), 1) < eps);
catch
tf = false;
end
end
function x = hnormalise(x)
x = x ./ x(end,:);
end
|
github | ojwoodford/ojwul-master | P0To1.m | .m | ojwul-master/geometry/P0To1.m | 193 | utf_8 | 4077eb08e6c6ab002a509f85957f07ee | %P0TO1 Convert projection matrices' principal points from 0 to 1 based
%
% P = P0To1(P)
function P = P0To1(P)
for a = 1:size(P, 3)
P(:,:,a) = [1 0 1; 0 1 1; 0 0 1] * P(:,:,a);
end |
github | ojwoodford/ojwul-master | PcTo1.m | .m | ojwul-master/geometry/PcTo1.m | 296 | utf_8 | 55e365afd092726522dabdacf5b9e609 | %PCTO1 Convert projection matrices' principal points from centre to 1 based
%
% P = PcTo1(P, im)
function P = PcTo1(P, im)
if numel(im) == 2 || numel(im) == 3
h = im(1);
w = im(2);
else
[h, w, c] = size(im);
end
K = [1 0 (w+1)/2; 0 1 (h+1)/2; 0 0 1];
P = tmult(K, P);
|
github | ojwoodford/ojwul-master | lie.m | .m | ojwul-master/geometry/lie.m | 6,684 | utf_8 | f192cb6d610ea2c5d6cbf5e5fea8dd56 | classdef lie
properties (Hidden = true, SetAccess = protected)
G; % Generators for computing tangent
Gv; % Generators for computing matrix
sz;
end
methods
function this = lie(generators_)
if ischar(generators_)
generators_ = generators(generators_);
end
this.sz = [size(generators_, 1) size(generators_, 2)];
this.G = reshape(generators_, [], size(generators_, 3));
this.Gv = pinv(this.G);
end
% NDIMS - Return the dimensionality of the space
function n = ndims(this)
n = size(this.G, 2);
end
% SIZE - Return the size of the warp
function sz = size(this)
sz = this.sz;
end
% VEE - Convert from Lie matrix to Lie tangent space
function tangent = vee(this, matrix)
tangent = this.Gv * reshape(matrix, size(this.Gv, 2), []);
end
% LOG - Convert from transform to Lie matrix to Lie tangent space
function tangent = log(this, transform)
[~, ~, N] = size(transform);
tangent = this.vee(logm(transform(:,:,1))); % Hack for non-numeric types, e.g. autodiff
for a = N:-1:2
tangent(:,a) = this.vee(logm(transform(:,:,a)));
end
end
% HAT - Convert from Lie tangent space to Lie matrix
function matrix = hat(this, tangent)
matrix = reshape(this.G * tangent, this.sz(1), this.sz(2), []);
end
% EXP - Convert from Lie tangent space to transform
function transform = exp(this, tangent)
[~, N] = size(tangent);
if N == 1
transform = expm(this.hat(tangent));
return;
end
transform = expm(this.hat(tangent(:,1))); % Hack for non-numeric types, e.g. autodiff
for a = N:-1:2
transform(:,:,a) = expm(this.hat(tangent(:,a)));
end
end
% ADJOINT - Compute the adjoint matrix of a Lie tangent vector
function adj = adjoint(this, tangent)
end
function tangent = Adjoint_times(this, transform, tangent)
tangent = tmult(transform, this.hat(tangent));
for a = 1:size(transform, 3)
transform(:,:,a) = inv(transform(:,:,a));
end
tangent = this.vee(tmult(tangent, transform));
end
% LIEBRACKET - Apply the Lie bracket to two Lie tangent vectors
function tangent = liebracket(this, tangentA, tangentB)
%tangent = this.adjoint(tangentA) * tangentB;
A = this.hat(tangentA);
B = this.hat(tangentB);
tangent = this.vee(tmult(A, B) - tmult(B, A));
end
% INTERP1 - Linear interpolation between transforms
function Vq = interp1(this, X, V, Xq)
for a = numel(X)-1:-1:1
tangents(:,a) = this.log(V(:,:,a+1) / V(:,:,a));
end
[~, ind] = histc(Xq, [X(:); Inf]);
ind = min(max(ind, 1), numel(X)-1);
for a = numel(Xq):-1:1
Vq(:,:,a) = this.exp(tangents(:,ind(a)) * ((Xq(a) - X(ind(a))) / (X(ind(a)+1) - X(ind(a))))) * V(:,:,ind(a));
end
end
end
methods (Static)
function check_orthogonal(groups)
if nargin < 1
groups = {'so2', 'se2', 'sim2', 'aff2', 'so3', 'rxso3', 'uv3', 'rxuv3', 'se3', 'sim3', 'sl3'};
elseif ~iscell(groups)
groups = {groups};
end
for group = groups
% Chech the generators are orthogonal
G = generators(group{1});
G = reshape(G, [], size(G, 3));
dot_prod = tril(squeeze(sum(bsxfun(@times, G, permute(G, [1 3 2])), 1)), -1);
[y, x] = find(abs(dot_prod) > 1e-14);
if ~isempty(y)
y = [y(:)'; x(:)'];
warning('The following pairs of %s group generators are not orthogonal:\n%s', group{1}, sprintf(' %d,%d\n', y));
end
end
end
end
end
function G = generators(group)
switch group
case 'shift2'
% Generators for 2D translations
G = zeros(3, 3, 2);
G(1,3,1) = 1; % X translation
G(2,3,2) = 1; % Y translation
case 'so2'
% Generators for so2
G = [0 -1; 1 0];
case 'se2'
% Generators for se2
G = generators('shift2');
G(1:2,1:2,3) = generators('so2'); % Rotation
case 'sim2'
% Generators for sim2
G = cat(3, generators('se2'), diag([0.5 0.5 -1])); % Uniform scale
case 'rs2'
G = generators('sim2');
G = G(:,:,3:4);
case 'aff2'
% Generators for aff2 (2D affine transformation)
G = zeros(3, 3, 6);
G(:,:,1:4) = generators('sim2');
G(1,1,5) = 1; % Aspect ratio
G(2,2,5) = -1;
G(1,2,6) = 1; % Shear
G(2,1,6) = 1;
case 'so3'
% Generators for so3
G = zeros(3, 3, 3);
G(3,2,1) = 1;
G(2,3,1) = -1;
G(1,3,2) = 1;
G(3,1,2) = -1;
G(1,2,3) = -1;
G(2,1,3) = 1;
case 'rxso3'
% Generators for rxso3
G = generators('so3');
G(1,1,4) = 1;
G(2,2,4) = 1;
G(3,3,4) = 1;
case 'uv3' % 3D unit vector
G = generators('so3');
G = G(:,:,2:3);
case 'rxuv3' % 3D vector parameterized by rotation and scale
G = generators('rxso3');
G = G(:,:,2:4);
case 'se3'
% Generators for se3
G = zeros(4, 4, 6);
G(1,4,1) = 1;
G(2,4,2) = 1;
G(3,4,3) = 1;
G(1:3,1:3,4:6) = generators('so3');
case 'sim3'
% Generators for sim3
G = zeros(4, 4, 7);
G(1,4,1) = 1;
G(2,4,2) = 1;
G(3,4,3) = 1;
G(1:3,1:3,4:7) = generators('rxso3');
case 'sl3'
% Generators for sl3
G = zeros(3, 3, 8);
G_ = generators('so3');
G(:,:,1:3) = G_;
G_ = abs(G_);
G(:,:,4) = 0.5 * G_(:,:,3) - G_(:,:,1) - G_(:,:,2);
G(:,:,5) = G_(:,:,2) + G_(:,:,3) - 0.5 * G_(:,:,1);
G(:,:,6) = G_(:,:,3) + G_(:,:,1) - 0.5 * G_(:,:,2);
G(1,1,7) = -1;
G(3,3,7) = 1;
G(1,1,8) = 0.5;
G(3,3,8) = 0.5;
G(2,2,8) = -1;
otherwise
error('Lie group %s not recognized', group);
end
% Normalize the generators
G = bsxfun(@times, G, 1 ./ sqrt(sum(sum(G .* G, 1), 2)));
end
|
github | ojwoodford/ojwul-master | procrustes.m | .m | ojwul-master/geometry/procrustes.m | 965 | utf_8 | 477416028b7bcef304121f739d72aa54 | % [R,s,t,Y1,p] = procrustes(X,Y) Procrustes alignment
%
% Finds the best similarity transformation Y = s.X.R + ones(N,1).t' (in the
% least squares sense).
%
% References:
% - Borg & Groenen: "Modern Multidimensional Scaling: Theory and Application",
% Springer, 2005 (chapter 20).
% - Cox & Cox: "Multidimensional Scaling", 2nd ed. Chapman & Hall, 2000
% (chapter 5).
%
% In:
% X,Y: NxD data sets of row vectors.
% Out:
% R: DxD orthogonal matrix.
% s: scale.
% t: Dx1 translation vector.
% Y1: NxD matrix, transformed X.
% p: Procrustes statistic (normalised error |Y-Y1|?/tr(Y.Y')).
% Copyright (c) 2009 by Miguel A. Carreira-Perpinan
function [R,s,t,Y1,p] = procrustes(X,Y)
[N, D] = size(Y);
sY = sum(Y,1); sX = sum(X,1); C = Y'*X - sY'*(sX/N); [U,S,V] = svd(C);
R = V*U';
s = sum(sum(C.*R')) / (sum(sum(X.^2))-(sX*sX')/N);
t = (sY - s*sX*R)'/N;
if nargout > 3
Y1 = bsxfun(@plus,s*X*R,t');
p = sum(sum((Y1-Y).^2))/sum(sum(Y.^2));
end
end |
github | ojwoodford/ojwul-master | proj2orthonormal.m | .m | ojwul-master/geometry/proj2orthonormal.m | 294 | utf_8 | d84258c1578512ceadd4d88a9a6d2b20 | %PROJ2ORTHONORMAL Project a matrix onto an orthonormal basis
%
% B = proj2orthonormal(A)
%
%IN:
% A - MxN matrix
% B - Closest MxN matrix to A, where the rows are unit length and
% orthogonal.
function A = proj2orthonormal(A)
[U, ~, V] = svd(A, 'econ');
A = U * V';
end |
github | ojwoodford/ojwul-master | calibrated_fivepoint.m | .m | ojwul-master/geometry/calibrated_fivepoint.m | 4,166 | utf_8 | 435ccefe3eb92b250019ff7e2679f5d5 | %CALIBRATED_FIVEPOINT Stewenius & Engel's implementation of Nister's 5
%point algorithm
%
% [SOLS,EE] = fivePoint(Q1,Q2)
%
%
% Copyright Chris Engels 2004
%
% The algorithm follows
%@Article{ nister-itpam-04,
% author = {Nist\'er, D.},
% journal = pami,
% month = {June},
% number = {6},
% title = {Problem},
% pages = {756-770},
% volume = {26},
% year = {2004}
%}
%
% This implemenation was written for the paper
%
% ARTICLE{stewenius-engels-nister-isprsj-2006,
% AUTHOR = {H. Stew\'enius and C. Engels and D. Nist\'er},
% TITLE = {Recent Developments on Direct Relative Orientation},
% JOURNAL = {ISPRS Journal of Photogrammetry and Remote Sensing},
% URL = {http://dx.doi.org/10.1016/j.isprsjprs.2006.03.005},
% VOLUME = {60},
% ISSUE = {4},
% PAGES = {284--294},
% MONTH = JUN,
% CODE = {http://vis.uky.edu/~stewe/FIVEPOINT},
% PDF = {http://www.vis.uky.edu/~stewe/publications/stewenius_engels_nister_5pt_isprs.pdf},
% YEAR = 2006
%}
%
%
% Please refer to this paper if you use this code.
function Evec = calibrated_fivepoint(Q1,Q2)
Q1 = Q1';
Q2 = Q2';
Q = [Q1(:,1).*Q2(:,1) , ...
Q1(:,2).*Q2(:,1) , ...
Q1(:,3).*Q2(:,1) , ...
Q1(:,1).*Q2(:,2) , ...
Q1(:,2).*Q2(:,2) , ...
Q1(:,3).*Q2(:,2) , ...
Q1(:,1).*Q2(:,3) , ...
Q1(:,2).*Q2(:,3) , ...
Q1(:,3).*Q2(:,3) ] ;
% EE = null(Q);
[U,S,V]=svd(Q, 0);
EE = V(:,6:9);
A = calibrated_fivepoint_helper( EE ) ;
if 1
p=[1 4 2 3 5 11 7 13 6 12 8 14 17 9 15 18 10 16 19 20] ;%rearrange the columns of A
A=A(:,p);
A=rref(A) ;
B(1,1) =-A(6,11);
B(1,2) = A(5,11)-A(6,12);
B(1,3) = A(5,12)-A(6,13);
B(1,4) = A(5,13);
B(1,5) =-A(6,14);
B(1,6) = A(5,14)-A(6,15);
B(1,7) = A(5,15)-A(6,16);
B(1,8) = A(5,16);
B(1,9) =-A(6,17);
B(1,10)= A(5,17)-A(6,18);
B(1,11)= A(5,18)-A(6,19);
B(1,12)= A(5,19)-A(6,20);
B(1,13)= A(5,20);
B(2,1) =-A(8,11);
B(2,2) = A(7,11)-A(8,12);
B(2,3) = A(7,12)-A(8,13);
B(2,4) = A(7,13);
B(2,5) =-A(8,14);
B(2,6) = A(7,14)-A(8,15);
B(2,7) = A(7,15)-A(8,16);
B(2,8) = A(7,16);
B(2,9) =-A(8,17);
B(2,10)= A(7,17)-A(8,18);
B(2,11)= A(7,18)-A(8,19);
B(2,12)= A(7,19)-A(8,20);
B(2,13)= A(7,20);
B(3,1) =-A(10,11);
B(3,2) = A(9,11)-A(10,12);
B(3,3) = A(9,12)-A(10,13);
B(3,4) = A(9,13);
B(3,5) =-A(10,14);
B(3,6) = A(9,14)-A(10,15);
B(3,7) = A(9,15)-A(10,16);
B(3,8) = A(9,16);
B(3,9) =-A(10,17);
B(3,10)= A(9,17)-A(10,18);
B(3,11)= A(9,18)-A(10,19);
B(3,12)= A(9,19)-A(10,20);
B(3,13)= A(9,20);
b11=B(1,1:4) ;
b12=B(1,5:8) ;
b13=B(1,9:13) ;
b21=B(2,1:4) ;
b22=B(2,5:8) ;
b23=B(2,9:13) ;
b31=B(3,1:4) ;
b32=B(3,5:8) ;
b33=B(3,9:13);
n=(conv(conv(b11,b22),b33) - conv(conv(b11,b23),b32)) +...
(conv(conv(b12,b23),b31) - conv(conv(b12,b21),b33)) +...
(conv(conv(b13,b21),b32) - conv(conv(b13,b22),b31));
SOLS(:,3)=roots(n);
r=SOLS(:,3);
for i=1:length(r)
if isreal(r(i))
bt(1,1)=b11(1)*r(i)^3 + b11(2)*r(i)^2 + b11(3)*r(i)^1 + b11(4);
bt(1,2)=b12(1)*r(i)^3 + b12(2)*r(i)^2 + b12(3)*r(i)^1 + b12(4) ;
bt(1,3)=b13(1)*r(i)^4 + b13(2)*r(i)^3 + b13(3)*r(i)^2 + b13(4)*r(i)^1 + b13(5);
bt(2,1)=b21(1)*r(i)^3 + b21(2)*r(i)^2 + b21(3)*r(i)^1 + b21(4) ;
bt(2,2)=b22(1)*r(i)^3 + b22(2)*r(i)^2 + b22(3)*r(i)^1 + b22(4) ;
bt(2,3)=b23(1)*r(i)^4 + b23(2)*r(i)^3 + b23(3)*r(i)^2 + b23(4)*r(i)^1 + b23(5);
bt(3,1)=b31(1)*r(i)^3 + b31(2)*r(i)^2 + b31(3)*r(i)^1 + b31(4) ;
bt(3,2)=b32(1)*r(i)^3 + b32(2)*r(i)^2 + b32(3)*r(i)^1 + b32(4) ;
bt(3,3)=b33(1)*r(i)^4 + b33(2)*r(i)^3 + b33(3)*r(i)^2 + b33(4)*r(i)^1 + b33(5);
[U,S,V] = svd( bt);
xy1 = V(:,end);
if( xy1(3) ~= 0)
SOLS(i,1)=xy1(1)./xy1(3);
SOLS(i,2)=xy1(2)./xy1(3);
end
end
end
SOLS = SOLS';
else
A = A(:,1:10)\A(:,11:20);
M = -A([1 2 3 5 6 8], :);
M(7,1) = 1;
M(8,2) = 1;
M(9,4) = 1;
M(10,7) = 1;
[V,D] = eig(M );
SOLS = V(7:9,:)./(ones(3,1)*V(10,:));
end
Evec = EE*homg(SOLS);
Evec = Evec./ ( ones(9,1)*sqrt(sum( Evec.^2)));
Evec = permute(reshape(Evec(:,~imag(Evec(1,:))), 3, 3, []), [2 1 3]);
Evec = mat2cell(Evec, 3, 3, ones(size(Evec, 3), 1));
end
|
github | ojwoodford/ojwul-master | msac_aff2.m | .m | ojwul-master/geometry/msac_aff2.m | 1,187 | utf_8 | 65741399892feffa4ab7b8577b762a62 | % MSAC_AFF2 Fit an affine matrix using RANSAC
%
% Usage: [A, D] = msac_aff2(x1, x2, t)
%
% Arguments:
% x1 - 2xN set of homogeneous image points.
% x2 - 2xN set of image points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% A - The 3x2 matrix such that A * homg(x1) - x2 is small.
% D - 1xN array of squared errors.
function [A, D] = msac_aff2(x1, x2, t)
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
[rows, npts] = size(x1);
if rows ~= 2
error('x1 and x2 must have 2 rows');
end
% x1 and x2 are 'stacked' to create a 6xN array for ransac
A = msac([x1; x2], @(x) x(3:4,:) / homg(x(1:2,:)), @(A, x) dist(A, x(1:2,:), x(3:4,:)), 3, t);
D = [];
if nargout < 2 || isempty(A)
return;
end
% Compute the distances
D = dist(A, x1, x2);
end
function D = dist(A, x1, x2)
D = A(:,1:2) * x1 - x2 + A(:,3);
D = sum(D .* D, 1);
end
|
github | ojwoodford/ojwul-master | P_align.m | .m | ojwul-master/geometry/P_align.m | 990 | utf_8 | d4e627a28c53154425297cf742ecb33b | %P_ALIGN Align one scene to another
%
% [Ptgt, Xtgt] = P_align(Pref, Ptgt, Xtgt, [indices])
%
%IN:
% Pref - 3x4xN camera poses of reference trajectory.
% Ptgt - 3x4xN camera poses of trajectory to transform.
% Xtgt - 3xM array of world coordinates to transform.
% indices - 2x1 indices of camera frames to use for the alignment.
% Default: [1 2].
%
%OUT:
% Ptgt - 3x4xN transformed target trajectory
% Xtgt - 3xM tranformed world coordinates
function [Ptgt, Xtgt] = P_align(Pref, Ptgt, Xtgt, indices)
if nargin < 4
indices = [1 2];
end
a = indices(1);
b = indices(2);
N = size(Ptgt, 3);
% Adjust the scale
s = norm(cc(Pref(:,:,a)) - cc(Pref(:,:,b))) / norm(cc(Ptgt(:,:,a)) - cc(Ptgt(:,:,b)));
Ptgt(:,4,:) = Ptgt(:,4,:) * s;
Xtgt = Xtgt * s;
% Align the origin
T = [Ptgt(:,:,a); 0 0 0 1] \ [Pref(:,:,a); 0 0 0 1];
for i = 1:N
Ptgt(:,:,i) = Ptgt(:,:,i) * T;
end
Xtgt = T(1:3,1:3)' * Xtgt + cc(T);
end
function C = cc(P)
C = P(1:3,1:3)' * -P(1:3,4);
end
|
github | ojwoodford/ojwul-master | P_from_H.m | .m | ojwul-master/geometry/P_from_H.m | 1,772 | utf_8 | 6449c71bf2d483d6f2dc9df73615be4c | %P_FROM_H Compute motion hypotheses from a homography
%
% P = P_from_H(H)
%
%IN:
% H - 3x3 homography on calibrated image coordinates, i.e.
% K^-1 * X2 = H * K^-1 * X1
%
%OUT:
% P - 3x4xM array of M potential extrinsic matrices [R, t] (up to scale).
% N - 3xM array of corresponding plane normals
function [P, N, H] = P_from_H(H)
% Use the method of Faugeras to compute the rotations
% Do the SVD of H
if det(H) < 0
H = -H;
end
[U, S, V] = svd(H);
% Normalize the homography
S = diag(S);
H = H / S(2);
% Check for no motion case
if S(1) - S(3) < S(2) * 1e-10
N = [0; 0; 1];
P = [H zeros(3, 1)];
return;
end
V = V';
S2 = S .* S;
% Compute first set
ctheta = 1 ./ (S(2) * (S(1) + S(3)));
stheta = sqrt((S2(1) - S2(2)) * (S2(2) - S2(3))) * ctheta;
ctheta = ctheta * (S2(2) + S(1) * S(3));
R1 = U * [ctheta 0 -stheta; 0 1 0; stheta 0 ctheta] * V;
R2 = U * [ctheta 0 stheta; 0 1 0; -stheta 0 ctheta] * V;
P = cat(3, R1, R2);
% Compute second set
ctheta = 1 ./ (S(2) * (S(1) - S(3)));
stheta = sqrt((S2(1) - S2(2)) * (S2(2) - S2(3))) * ctheta;
ctheta = ctheta * (S(1) * S(3) - S2(2));
R1 = U * [ctheta 0 stheta; 0 -1 0; stheta 0 -ctheta] * V;
R2 = U * [ctheta 0 -stheta; 0 -1 0; -stheta 0 -ctheta] * V;
P2 = cat(3, R1, R2);
% Compute the normals and translations
rank1 = cat(3, H - P, -H - P2);
N = sum(rank1, 1);
n = 1 ./ normd(N, 2);
N = N .* n;
T = sum(rank1 .* N, 2);
N = squeeze(N);
% Ensure the first camera is looking at the plane
P = cat(3, P, P2);
M = N(3,:) > 0;
N(:,M) = -N(:,M);
T(:,:,M) = -T(:,:,M);
% Ensure the second camera is in front of the plane
M = dot(reshape(tmult(P, -T, [1 0]), 3, []), N) < 1;
P(:,4,:) = cat(3, T);
P = P(:,:,M);
N = N(:,M);
end
|
github | ojwoodford/ojwul-master | perspectiveIPPE.m | .m | ojwul-master/geometry/perspectiveIPPE.m | 13,730 | utf_8 | 9eb53fe152d9e4d6869a892a99234d7b | function [IPPEPoses,refinedPoses] = perspectiveIPPE(U,Q,hEstMethod,opts)
%perspectiveIPPE: The solution to Perspective IPPE with point correspondences computed
%between points in world coordinates on the plane z=0, and normalised points in the
%camera's image.
%
%Inputs:
%
%U: 2xN or 3xN matrix holding the model points in world coordinates. If U
%is 2xN then the points are defined in world coordinates on the plane z=0
%
%Q: 2xN matrix holding the points in the image. These are in normalised
%pixel coordinates. That is, the effects of the camera's intrinsic matrix
%and lens distortion are corrected, so that the Q projects with a perfect
%pinhole model.
%
%hEstMethod: the homography estimation method, either 'Harker' (default) or 'DLT'. If
%'Harker' then the method of Harker and O'Leary is used, from the paper
%"Computation of Homographies" in the 2005 British Computer Vision
%Conference. Otherwise the Direct Linear Transform is used, from Peter Kovesi's implementation at http://www.csse.uwa.edu.au/~pk.
%If hEstMethod=[] then the default is used.
%
%opts is an optional datastructure holding the fields:
%setup IPPE options:
%opts.withPoseRefinement = true; %If this is set, we also refine the camera pose from IPPE by gradient-based optimisation (Levenberg–Marquardt). This is designed to give the statistically optimal pose assuming zero mean I.I.D nose for the feature's 2D positions, but requires initialisation (from IPPE). Note that it about two orders of magnitude slower than IPPE.
%opts.displayTiming = true; %set this to true if you want to see how long IPPE takes in Matlab.
%
%Outputs:
%IPPEPoses: structure containing the two pose solutions from IPPE.
% IPPEPoses.R1 is the first pose's rotation
% IPPEPoses.t1 is the first pose's translation
% IPPEPoses.R2 is the second pose's rotation
% IPPEPoses.t2 is the second pose's translation
% IPPEPoses.reprojError1 is the first pose's reprojection error
% IPPEPoses.reprojError2 is the second pose's reprojection error
%
%refinedPoses: structure containing the two refined pose solutions using
%Levenberg–Marquardt (same format as IPPEPoses). This is only outputted if opts.withPoseRefinement = true
%
%Note that the poses are transforms from world
%coordinates to camera coordinates. If you
%want to get the camera's pose in world coordinates you would get it with
%M1 = inv([[R1,t1];[0,0,0,1]]) and M2 = inv([[R2,t2];[0,0,0,1]])
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This file is part of the IPPE package for very fast plane-based pose
% estimation from a single perspective image, from the paper "Infinitesimal Plane-based Pose Estimation"
% by Toby Collins and Adrien Bartoli, published in the International Journal of Computer Vision, September 2014.
% A copy of the author's pre-print version can be found here: http://isit.u-clermont1.fr/~ab/Publications/Collins_Bartoli_IJCV14.pdf
%
% Feel free to contact Toby ([email protected]) if you have any
% questions about the paper and IPPE.
%
% This package is free and covered by the BSD licence without any warranty. We hope you find this code useful and please cite our paper in your work:
% (c) Toby Collins 2015
%
%@article{
%year={2014},
%issn={0920-5691},
%journal={International Journal of Computer Vision},
%volume={109},
%number={3},
%doi={10.1007/s11263-014-0725-5},
%title={Infinitesimal Plane-Based Pose Estimation},
%url={http://dx.doi.org/10.1007/s11263-014-0725-5},
%publisher={Springer US},
%keywords={Plane; Pose; SfM; PnP; Homography},
%author={Collins, Toby and Bartoli, Adrien},
%pages={252-286},
%language={English}
%}
opts = parseOpts(opts);
measureTiming = opts.measureTiming;
refineSolutions = opts.withPoseRefinement;
U = double(U);
Q = double(Q);
%set defaults for hEstMethod:
if isempty(hEstMethod)
hEstMethod = 'Harker';
else
if ~(strcmp(hEstMethod,'Harker')||strcmp(hEstMethod,'DLT'))
error('You must specify a valid homography estimation method in perspectiveIPPE. The options are Harker or DLT');
end
end
%argument sanity check:
assert(size(U,1)==2|size(U,1)==3);
assert(size(U,2)==size(Q,2));
assert(size(Q,1) == 2);
%n is the number of points:
n = size(U,2);
modelDims = size(U,1);
Uuncentred = U;
if modelDims==2
%we zero-center the model points:
Pbar = [mean(U,2);0];
U(1,:) = U(1,:)-Pbar(1);
U(2,:) = U(2,:)-Pbar(2);
else
%we rotate the model points onto the plane z=0 and zero center them:
Pbar = mean(U,2);
MCenter = eye(4);
MCenter(1:3,end) = -Pbar;
U_ = MCenter(1:3,:)*[U;ones(1,size(U,2))];
[modelRotation,sigs,~] = svd(U_*U_'); modelRotation=modelRotation';
if (sigs(3,3)/sigs(2,2)>1e-5)
error('IPPE requires the model points to be planar!');
end
modelRotation(4,4) = 1;
Mcorrective = modelRotation*MCenter;
U = Mcorrective(1:2,:)*[U;ones(1,size(U,2))];
end
if measureTiming
tic;
end
%compute the model-to-image homography:
switch hEstMethod
case 'DLT'
H = homography2d([U;ones(1,n)],[Q;ones(1,n)]);
case 'Harker'
H = homographyHarker([U;ones(1,n)],[Q;ones(1,n)]);
end
%[ px, py, 1, 0, 0, 0, -px*qx, -py*qx]h = qx
%[ 0, 0, 0, px, py, 1, -px*qy, -py*qy]h = qy
%Compute the Jacobian J of the homography at (0,0):
H = H./H(3,3);
J(1,1) = H(1,1)-H(3,1)*H(1,3);
J(1,2) = H(1,2)-H(3,2)*H(1,3);
J(2,1) = H(2,1)-H(3,1)*H(2,3);
J(2,2) = H(2,2)-H(3,2)*H(2,3);
%Compute the two rotation solutions:
v = [H(1,3);H(2,3)];
[R1,R2] = IPPE_dec(v,J);
%Compute the two translation solutions:
t1_ = estT(R1,U,Q);
t2_ = estT(R2,U,Q);
if modelDims==2
t1 = [R1,t1_]*[-Pbar;1];
t2 = [R2,t2_]*[-Pbar;1];
else
M1 = [R1,t1_];
M1(4,4) = 1;
M2 = [R2,t2_];
M2(4,4) = 1;
M1 = M1*Mcorrective;
M2 = M2*Mcorrective;
R1 = M1(1:3,1:3);
R2 = M2(1:3,1:3);
t1 = M1(1:3,end);
t2 = M2(1:3,end);
end
[reprojErr1,reprojErr2] = computeReprojErrs(R1,R2,t1,t2,Uuncentred,Q);
%sort solutions:
if reprojErr1>reprojErr2
[R1,R2,t1,t2,reprojErr1,reprojErr2] = swapSolutions(R1,R2,t1,t2,reprojErr1,reprojErr2);
end
IPPEPoses.R1 = R1;
IPPEPoses.t1 = t1;
IPPEPoses.R2 = R2;
IPPEPoses.t2 = t2;
IPPEPoses.reprojError1 = reprojErr1;
IPPEPoses.reprojError2 = reprojErr2;
%%with timing?
if measureTiming
disp('Computing time to estimate homography for IPPE. Warning this slows things down, so turn it off when you are not benchmarking!');
tic;
%average timing over 100 runs:
for i=1:100
switch hEstMethod
case 'DLT'
H = homography2d([U;ones(1,n)],[Q;ones(1,n)]);
case 'Harker'
H = homographyHarker([U;ones(1,n)],[Q;ones(1,n)]);
end
end
tm = toc;
disp(['Time to estimate homography: ' num2str(1000*tm/100) 'ms']);
disp('Computing time to solve IPPE given homography...');
tic;
%average timing over 100 runs:
for i=1:100
%Compute the Jacobian J of the homography at (0,0):
H = H./H(3,3);
J(1,1) = H(1,1)-H(3,1)*H(1,3);
J(1,2) = H(1,2)-H(3,2)*H(1,3);
J(2,1) = H(2,1)-H(3,1)*H(2,3);
J(2,2) = H(2,2)-H(3,2)*H(2,3);
%Compute the two rotation solutions:
v = [H(1,3);H(2,3)];
[R1,R2] = IPPE_dec(v,J);
%Compute the two translation solutions:
t1_ = estT(R1,U,Q);
t2_ = estT(R2,U,Q);
t1 = [R1,t1_]*[-Pbar;1];
t2 = [R2,t2_]*[-Pbar;1];
end
tm = toc;
disp(['Time to solve IPPE given homography: ' num2str(1000*tm/100) 'ms']);
end
if modelDims==2
Uuncentred(3,:) = 0;
end
if refineSolutions
poseEst= pnpLMRefinement(Uuncentred,Q,R1,t1,'MLE');
R1 = poseEst.R;
t1 = poseEst.t;
poseEst= pnpLMRefinement(Uuncentred,Q,R2,t2,'MLE');
R2 = poseEst.R;
t2 = poseEst.t;
[reprojErr1,reprojErr2] = computeReprojErrs(R1,R2,t1,t2,Uuncentred,Q);
%Sort the solutions:
if reprojErr1>reprojErr2
[R1,R2,t1,t2,reprojErr1,reprojErr2] = swapSolutions(R1,R2,t1,t2,reprojErr1,reprojErr2);
end
refinedPoses.R1 = R1;
refinedPoses.t1 = t1;
refinedPoses.R2 = R2;
refinedPoses.t2 = t2;
refinedPoses.reprojError1 = reprojErr1;
refinedPoses.reprojError2 = reprojErr2;
%%with timing?
if measureTiming
disp('Computing time to refine IPPE solutions with Levenberg Marquardt...');
tic;
%average timing over 100 runs:
for i=1:100
pnpLMRefinement(Uuncentred,Q,IPPEPoses.R1,IPPEPoses.t1,'MLE');
pnpLMRefinement(Uuncentred,Q,IPPEPoses.R2,IPPEPoses.t2,'MLE');
end
tm = toc;
disp(['Time to refine IPPE solutions with Levenberg Marquardt: ' num2str(1000*tm/100) 'ms']);
end
end
function [reprojErr1,reprojErr2] = computeReprojErrs(R1,R2,t1,t2,U,Q)
%computeReprojErrs: Computes the reprojection errors for the two solutions
%generated by IPPE.
%transform model points to camera coordinates and project them onto the
%image:
if size(U,1)==2
PCam1 = R1(:,1:2)*U;
PCam2 = R2(:,1:2)*U(1:2,:);
else
PCam1 = R1*U;
PCam2 = R2*U;
end
PCam1(1,:) = PCam1(1,:) + t1(1);
PCam1(2,:) = PCam1(2,:) + t1(2);
PCam1(3,:) = PCam1(3,:) + t1(3);
PCam2(1,:) = PCam2(1,:) + t2(1);
PCam2(2,:) = PCam2(2,:) + t2(2);
PCam2(3,:) = PCam2(3,:) + t2(3);
Qest_1 = PCam1./[PCam1(3,:);PCam1(3,:);PCam1(3,:)];
Qest_2 = PCam2./[PCam2(3,:);PCam2(3,:);PCam2(3,:)];
%compute reprojection errors:
reprojErr1 = norm(Qest_1(1:2,:)-Q);
reprojErr2 = norm(Qest_2(1:2,:)-Q);
function t = estT(R,psPlane,Q)
%Computes the least squares estimate of translation given the rotation solution.
if size(psPlane,1)==2
psPlane(3,:) =0;
end
%qq = homoMult(Kinv,pp')';
Ps = R*psPlane;
numPts = size(psPlane,2);
Ax = zeros(numPts,3);
bx = zeros(numPts,1);
Ay = zeros(numPts,3);
by = zeros(numPts,1);
Ax(:,1) = 1;
Ax(:,3) = -Q(1,:);
bx(:) = Q(1,:).*Ps(3,:) - Ps(1,:);
Ay(:,2) = 1;
Ay(:,3) = -Q(2,:);
by(:) = Q(2,:).*Ps(3,:) - Ps(2,:);
A = [Ax;Ay];
b = [bx;by];
AtA = A'*A;
Atb = A'*b;
Ainv = IPPE_inv33(AtA);
t = Ainv*Atb;
function [R1,R2,t1,t2,reprojErr1,reprojErr2] = swapSolutions(R1_,R2_,t1_,t2_,reprojErr1_,reprojErr2_)
%swaps the solutions:
R1 = R2_;
t1 = t2_;
reprojErr1 = reprojErr2_;
R2 = R1_;
t2 = t1_;
reprojErr2 = reprojErr1_;
function Ainv = IPPE_inv33(A)
%computes the inverse of a 3x3 matrix, assuming it is full-rank.
a11 = A(1,1);
a12 = A(1,2);
a13 = A(1,3);
a21 = A(2,1);
a22 = A(2,2);
a23 = A(2,3);
a31 = A(3,1);
a32 = A(3,2);
a33 = A(3,3);
Ainv = [[ a22*a33 - a23*a32, a13*a32 - a12*a33, a12*a23 - a13*a22];
[ a23*a31 - a21*a33, a11*a33 - a13*a31, a13*a21 - a11*a23];
[ a21*a32 - a22*a31, a12*a31 - a11*a32, a11*a22 - a12*a21]];
Ainv = Ainv./(a11*a22*a33 - a11*a23*a32 - a12*a21*a33 + a12*a23*a31 + a13*a21*a32 - a13*a22*a31);
function opts = parseOpts(opts)
if ~isfield(opts,'measureTiming')
opts.measureTiming = false;
end
if ~isfield(opts,'withPoseRefinement')
opts.withPoseRefinement = true;
end
function [R1,R2,gamma] = IPPE_dec(v,J)
%IPPE_dec: Computes the two solutions to rotation from the J Jacobian of the
%model-to-plane homography H (IPPE Algorithm 1).
%
%
%Inputs v: 2x1 vector holding the point in normalised pixel coordinates
%which maps by H^-1 to the point (0,0,0) in world coordinates.
%
%J: 2x2 Jacobian matrix of H at (0,0).
%
%Outputs:
%R1: 3x3 Rotation matrix (first solution)
%R2: 3x3 Rotation matrix (second solution)
%gamma: The positive real-valued inverse-scale factor.
%
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This file is part of the IPPE package for very fast plane-based pose
% estimation from a single perspective image, from the paper "Infinitesimal Plane-based Pose Estimation"
% by Toby Collins and Adrien Bartoli, published in the International Journal of Computer Vision, September 2014.
% A copy of the author's pre-print version can be found here: http://isit.u-clermont1.fr/~ab/Publications/Collins_Bartoli_IJCV14.pdf
%
% Feel free to contact Toby ([email protected]) if you have any
% questions about the paper and IPPE.
%
% This package is free and covered by the BSD licence without any warranty. We hope you find this code useful and please cite our paper in your work:
% (c) Toby Collins 2015
%
%@article{
%year={2014},
%issn={0920-5691},
%journal={International Journal of Computer Vision},
%volume={109},
%number={3},
%doi={10.1007/s11263-014-0725-5},
%title={Infinitesimal Plane-Based Pose Estimation},
%url={http://dx.doi.org/10.1007/s11263-014-0725-5},
%publisher={Springer US},
%keywords={Plane; Pose; SfM; PnP; Homography},
%author={Collins, Toby and Bartoli, Adrien},
%pages={252-286},
%language={English}
%}
%compute the correction rotation Rv:
t = norm(v);
s = norm([v;1]);
costh = 1/s;
sinth = sqrt(1-1/(s^2));
Kcrs = 1/t*[zeros(2,2),v;-v',0];
Rv = eye(3) + sinth*Kcrs + (1-costh)*Kcrs^2;
%setup the 2x2 SVD decomposition:
B = [eye(2),-v]*Rv(:,1:2);
dt = (B(1,1)*B(2,2) - B(1,2)*B(2,1));
Binv = [B(2,2)/dt, -B(1,2)/dt;-B(2,1)/dt, B(1,1)/dt];
A = Binv*J;
%compute the largest singular value of A:
AAT = A*transpose(A);
gamma = sqrt(1/2*(AAT(1,1) + AAT(2,2) + sqrt((AAT(1,1)-AAT(2,2))^2 + 4*AAT(1,2)^2)));
%reconstruct the full rotation matrices:
R22_tild = A/gamma;
h = eye(2)-R22_tild'*R22_tild;
b = [sqrt(h(1,1));sqrt(h(2,2))];
if h(1,2)<0
b(2) = -b(2);
end
d = IPPE_crs([R22_tild(:,1);b(1)],[R22_tild(:,2);b(2)]);
c = d(1:2);
a = d(3);
R1 = Rv*[R22_tild,c;b',a];
R2 = Rv*[R22_tild,-c;-b',a];
function v3 = IPPE_crs(v1,v2)
%3D cross product between vectors v1 and v2
v3 = zeros(3,1);
v3(1) = v1(2)*v2(3)-v1(3)*v2(2);
v3(2) = v1(3)*v2(1)-v1(1)*v2(3);
v3(3) = v1(1)*v2(2)-v1(2)*v2(1); |
github | ojwoodford/ojwul-master | euler2rot.m | .m | ojwul-master/geometry/euler2rot.m | 2,142 | utf_8 | 9cff5f197c14a730dd7a9d673a384582 | %EULER2ROT Computes a rotation matrix from a set of Euler angles.
%
% R = euler2rot(X)
% R = euler2rot(X, type)
%
% The Euler representation is a set of 3 angles (in radians), which are
% applied about the three intrinsic axes of the frame specified.
%
%IN:
% X - 3xM matrix of Euler angle vectors.
% type - 1x3 character string representing the intrinsic axes the angles
% are applied to. Default: 'xyz'.
%
%OUT:
% R - 3x3xM rotation matrix.
function R = euler2rot(X, type)
if nargin < 2
type = 'xyz';
end
if size(X, 1) == 1
X = shiftdim(X, 1);
end
sz = size(X);
% Compute trig functions
c = cos(X);
s = sin(X);
% Compute matrix
switch type
case 'zxz'
R = [c(1,:) .* c(3,:) - c(2,:) .* s(1,:) .* s(3,:); ...
c(3,:) .* s(1,:) + c(1,:) .* c(2,:) .* s(3,:); ...
s(2,:) .* s(3,:); ...
-c(1,:) .* s(3,:) - c(2,:) .* c(3,:) .* s(1,:); ...
c(1,:) .* c(2,:) .* c(3,:) - s(1,:) .* s(3,:); ...
c(3,:) .* s(2,:); ...
s(1,:) .* s(2,:); ...
-c(1,:) .* s(2,:); ...
c(2,:)];
case 'xyz'
R = [c(2,:) .* c(3,:); ...
c(1,:) .* s(3,:) + c(3,:) .* s(1,:) .* s(2,:); ...
s(1,:) .* s(3,:) - c(1,:) .* c(3,:) .* s(2,:); ...
-c(2,:) .* s(3,:); ...
c(1,:) .* c(3,:) - s(1,:) .* s(2,:) .* s(3,:); ...
c(3,:) .* s(1,:) + c(1,:) .* s(2,:) .* s(3,:); ...
s(2,:); ...
-c(2,:) .* s(1,:); ...
c(1,:) .* c(2,:)];
case 'zyx'
R = [c(1,:) .* c(2,:); ...
c(2,:) .* s(1,:); ...
-s(2,:); ...
c(1,:) .* s(2,:) .* s(3,:) - c(3,:) .* s(1,:); ...
c(1,:) .* c(3,:) + s(1,:) .* s(2,:) .* s(3,:); ...
c(2,:) .* s(3,:); ...
s(1,:) .* s(3,:) + c(1,:) .* c(3,:) .* s(2,:); ...
c(3,:) .* s(1,:) .* s(2,:) - c(1,:) .* s(3,:); ...
c(2,:) .* c(3,:)];
otherwise
error('type not recognised');
end
% Reshape
R = reshape(R, [3 3 sz(2:end)]);
|
github | ojwoodford/ojwul-master | quat_norm.m | .m | ojwul-master/geometry/quat_norm.m | 221 | utf_8 | 7e72a921038a91e18db404c07385d718 | %QUAT_NORM Normalize quaternions
function Q = quat_norm(Q)
Q = reshape(Q, 4, []);
N = sum(Q .* Q);
M = N == 0;
Q(1,M) = 1;
M = ~M & N ~= 1;
if any(M)
Q(:,M) = bsxfun(@times, Q(:,M), 1./sqrt(N(M)));
end
end |
github | ojwoodford/ojwul-master | P1To0.m | .m | ojwul-master/geometry/P1To0.m | 195 | utf_8 | 2b1dec97e51706a081c886259a724c35 | %P1TO0 Convert projection matrices' principal points from 1 to 0 based
%
% P = P1To0(P)
function P = P1To0(P)
for a = 1:size(P, 3)
P(:,:,a) = [1 0 -1; 0 1 -1; 0 0 1] * P(:,:,a);
end |
github | ojwoodford/ojwul-master | PcTo0.m | .m | ojwul-master/geometry/PcTo0.m | 296 | utf_8 | 07536b43cd308df4bab548824fbba6b6 | %PCTO0 Convert projection matrices' principal points from centre to 0 based
%
% P = PcTo0(P, im)
function P = PcTo0(P, im)
if numel(im) == 2 || numel(im) == 3
h = im(1);
w = im(2);
else
[h, w, c] = size(im);
end
K = [1 0 (w-1)/2; 0 1 (h-1)/2; 0 0 1];
P = tmult(K, P);
|
github | ojwoodford/ojwul-master | expmap2rot.m | .m | ojwul-master/geometry/expmap2rot.m | 1,044 | utf_8 | a35272599335ed029c983ac4d61aba74 | %EXPMAP2ROT Computes a rotation matrix from exponential map angle.
%
% R = expmap2rot(X)
function R = expmap2rot(X)
% Compute the angle
sz = size(X);
X = reshape(X, 3, []);
angle = sqrt(sum(X .* X, 1));
% Initialize output
R = repmat([1 0 0 0 1 0 0 0 1]', 1, numel(angle));
% Only update rotations with non-zero angles
M = angle ~= 0;
angle = angle(M);
if ~isempty(angle)
% Compute the axes, sin and cos
axis = bsxfun(@times, X(:,M), 1./angle);
% Compute the skew matrix
cpm = zeros(9, numel(angle));
cpm([2 6 7],:) = axis([3 1 2],:);
cpm([3 4 8],:) = -axis([2 3 1],:);
% Compute the squared skew matrix
cpm2 = reshape(bsxfun(@times, reshape(axis, 3, 1, []), reshape(axis, 1, 3, [])), 9, []);
cpm2([1 5 9],:) = bsxfun(@minus, cpm2([1 5 9],:), sum(cpm2([1 5 9],:)));
% Apply Rodrigues' formula
R(:,M) = R(:,M) + bsxfun(@times, cpm, sin(angle)) + bsxfun(@times, cpm2, 1 - cos(angle));
end
% Reshape for output
R = reshape(R, [3 3 sz(2:end)]);
|
github | ojwoodford/ojwul-master | gridfit.m | .m | ojwul-master/geometry/gridfit.m | 36,357 | utf_8 | 71d40f001761b87b8a56c3b57b6bf849 | function [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes,varargin)
% gridfit: estimates a surface on a 2d grid, based on scattered data
% Replicates are allowed. All methods extrapolate to the grid
% boundaries. Gridfit uses a modified ridge estimator to
% generate the surface, where the bias is toward smoothness.
%
% Gridfit is not an interpolant. Its goal is a smooth surface
% that approximates your data, but allows you to control the
% amount of smoothing.
%
% usage #1: zgrid = gridfit(x,y,z,xnodes,ynodes);
% usage #2: [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes);
% usage #3: zgrid = gridfit(x,y,z,xnodes,ynodes,prop,val,prop,val,...);
%
% Arguments: (input)
% x,y,z - vectors of equal lengths, containing arbitrary scattered data
% The only constraint on x and y is they cannot ALL fall on a
% single line in the x-y plane. Replicate points will be treated
% in a least squares sense.
%
% ANY points containing a NaN are ignored in the estimation
%
% xnodes - vector defining the nodes in the grid in the independent
% variable (x). xnodes need not be equally spaced. xnodes
% must completely span the data. If they do not, then the
% 'extend' property is applied, adjusting the first and last
% nodes to be extended as necessary. See below for a complete
% description of the 'extend' property.
%
% If xnodes is a scalar integer, then it specifies the number
% of equally spaced nodes between the min and max of the data.
%
% ynodes - vector defining the nodes in the grid in the independent
% variable (y). ynodes need not be equally spaced.
%
% If ynodes is a scalar integer, then it specifies the number
% of equally spaced nodes between the min and max of the data.
%
% Also see the extend property.
%
% Additional arguments follow in the form of property/value pairs.
% Valid properties are:
% 'smoothness', 'interp', 'regularizer', 'solver', 'maxiter'
% 'extend', 'tilesize', 'overlap'
%
% Any UNAMBIGUOUS shortening (even down to a single letter) is
% valid for property names. All properties have default values,
% chosen (I hope) to give a reasonable result out of the box.
%
% 'smoothness' - scalar or vector of length 2 - determines the
% eventual smoothness of the estimated surface. A larger
% value here means the surface will be smoother. Smoothness
% must be a non-negative real number.
%
% If this parameter is a vector of length 2, then it defines
% the relative smoothing to be associated with the x and y
% variables. This allows the user to apply a different amount
% of smoothing in the x dimension compared to the y dimension.
%
% Note: the problem is normalized in advance so that a
% smoothness of 1 MAY generate reasonable results. If you
% find the result is too smooth, then use a smaller value
% for this parameter. Likewise, bumpy surfaces suggest use
% of a larger value. (Sometimes, use of an iterative solver
% with too small a limit on the maximum number of iterations
% will result in non-convergence.)
%
% DEFAULT: 1
%
%
% 'interp' - character, denotes the interpolation scheme used
% to interpolate the data.
%
% DEFAULT: 'triangle'
%
% 'bilinear' - use bilinear interpolation within the grid
% (also known as tensor product linear interpolation)
%
% 'triangle' - split each cell in the grid into a triangle,
% then linear interpolation inside each triangle
%
% 'nearest' - nearest neighbor interpolation. This will
% rarely be a good choice, but I included it
% as an option for completeness.
%
%
% 'regularizer' - character flag, denotes the regularization
% paradignm to be used. There are currently three options.
%
% DEFAULT: 'gradient'
%
% 'diffusion' or 'laplacian' - uses a finite difference
% approximation to the Laplacian operator (i.e, del^2).
%
% We can think of the surface as a plate, wherein the
% bending rigidity of the plate is specified by the user
% as a number relative to the importance of fidelity to
% the data. A stiffer plate will result in a smoother
% surface overall, but fit the data less well. I've
% modeled a simple plate using the Laplacian, del^2. (A
% projected enhancement is to do a better job with the
% plate equations.)
%
% We can also view the regularizer as a diffusion problem,
% where the relative thermal conductivity is supplied.
% Here interpolation is seen as a problem of finding the
% steady temperature profile in an object, given a set of
% points held at a fixed temperature. Extrapolation will
% be linear. Both paradigms are appropriate for a Laplacian
% regularizer.
%
% 'gradient' - attempts to ensure the gradient is as smooth
% as possible everywhere. Its subtly different from the
% 'diffusion' option, in that here the directional
% derivatives are biased to be smooth across cell
% boundaries in the grid.
%
% The gradient option uncouples the terms in the Laplacian.
% Think of it as two coupled PDEs instead of one PDE. Why
% are they different at all? The terms in the Laplacian
% can balance each other.
%
% 'springs' - uses a spring model connecting nodes to each
% other, as well as connecting data points to the nodes
% in the grid. This choice will cause any extrapolation
% to be as constant as possible.
%
% Here the smoothing parameter is the relative stiffness
% of the springs connecting the nodes to each other compared
% to the stiffness of a spting connecting the lattice to
% each data point. Since all springs have a rest length
% (length at which the spring has zero potential energy)
% of zero, any extrapolation will be minimized.
%
% Note: The 'springs' regularizer tends to drag the surface
% towards the mean of all the data, so too large a smoothing
% parameter may be a problem.
%
%
% 'solver' - character flag - denotes the solver used for the
% resulting linear system. Different solvers will have
% different solution times depending upon the specific
% problem to be solved. Up to a certain size grid, the
% direct \ solver will often be speedy, until memory
% swaps causes problems.
%
% What solver should you use? Problems with a significant
% amount of extrapolation should avoid lsqr. \ may be
% best numerically for small smoothnesss parameters and
% high extents of extrapolation.
%
% Large numbers of points will slow down the direct
% \, but when applied to the normal equations, \ can be
% quite fast. Since the equations generated by these
% methods will tend to be well conditioned, the normal
% equations are not a bad choice of method to use. Beware
% when a small smoothing parameter is used, since this will
% make the equations less well conditioned.
%
% DEFAULT: 'normal'
%
% '\' - uses matlab's backslash operator to solve the sparse
% system. 'backslash' is an alternate name.
%
% 'symmlq' - uses matlab's iterative symmlq solver
%
% 'lsqr' - uses matlab's iterative lsqr solver
%
% 'normal' - uses \ to solve the normal equations.
%
%
% 'maxiter' - only applies to iterative solvers - defines the
% maximum number of iterations for an iterative solver
%
% DEFAULT: min(10000,length(xnodes)*length(ynodes))
%
%
% 'extend' - character flag - controls whether the first and last
% nodes in each dimension are allowed to be adjusted to
% bound the data, and whether the user will be warned if
% this was deemed necessary to happen.
%
% DEFAULT: 'warning'
%
% 'warning' - Adjust the first and/or last node in
% x or y if the nodes do not FULLY contain
% the data. Issue a warning message to this
% effect, telling the amount of adjustment
% applied.
%
% 'never' - Issue an error message when the nodes do
% not absolutely contain the data.
%
% 'always' - automatically adjust the first and last
% nodes in each dimension if necessary.
% No warning is given when this option is set.
%
%
% 'tilesize' - grids which are simply too large to solve for
% in one single estimation step can be built as a set
% of tiles. For example, a 1000x1000 grid will require
% the estimation of 1e6 unknowns. This is likely to
% require more memory (and time) than you have available.
% But if your data is dense enough, then you can model
% it locally using smaller tiles of the grid.
%
% My recommendation for a reasonable tilesize is
% roughly 100 to 200. Tiles of this size take only
% a few seconds to solve normally, so the entire grid
% can be modeled in a finite amount of time. The minimum
% tilesize can never be less than 3, although even this
% size tile is so small as to be ridiculous.
%
% If your data is so sparse than some tiles contain
% insufficient data to model, then those tiles will
% be left as NaNs.
%
% DEFAULT: inf
%
%
% 'overlap' - Tiles in a grid have some overlap, so they
% can minimize any problems along the edge of a tile.
% In this overlapped region, the grid is built using a
% bi-linear combination of the overlapping tiles.
%
% The overlap is specified as a fraction of the tile
% size, so an overlap of 0.20 means there will be a 20%
% overlap of successive tiles. I do allow a zero overlap,
% but it must be no more than 1/2.
%
% 0 <= overlap <= 0.5
%
% Overlap is ignored if the tilesize is greater than the
% number of nodes in both directions.
%
% DEFAULT: 0.20
%
%
% 'autoscale' - Some data may have widely different scales on
% the respective x and y axes. If this happens, then
% the regularization may experience difficulties.
%
% autoscale = 'on' will cause gridfit to scale the x
% and y node intervals to a unit length. This should
% improve the regularization procedure. The scaling is
% purely internal.
%
% autoscale = 'off' will disable automatic scaling
%
% DEFAULT: 'on'
%
%
% Arguments: (output)
% zgrid - (nx,ny) array containing the fitted surface
%
% xgrid, ygrid - as returned by meshgrid(xnodes,ynodes)
%
%
% Speed considerations:
% Remember that gridfit must solve a LARGE system of linear
% equations. There will be as many unknowns as the total
% number of nodes in the final lattice. While these equations
% may be sparse, solving a system of 10000 equations may take
% a second or so. Very large problems may benefit from the
% iterative solvers or from tiling.
%
%
% Example usage:
%
% x = rand(100,1);
% y = rand(100,1);
% z = exp(x+2*y);
% xnodes = 0:.1:1;
% ynodes = 0:.1:1;
%
% g = gridfit(x,y,z,xnodes,ynodes);
%
% Note: this is equivalent to the following call:
%
% g = gridfit(x,y,z,xnodes,ynodes, ...
% 'smooth',1, ...
% 'interp','triangle', ...
% 'solver','normal', ...
% 'regularizer','gradient', ...
% 'extend','warning', ...
% 'tilesize',inf);
%
%
% Author: John D'Errico
% e-mail address: [email protected]
% Release: 2.0
% Release date: 5/23/06
% Copyright (c) 2016, John D'Errico
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
% set defaults
params.smoothness = 1;
params.interp = 'triangle';
params.regularizer = 'gradient';
params.solver = 'backslash';
params.maxiter = [];
params.extend = 'warning';
params.tilesize = inf;
params.overlap = 0.20;
params.mask = [];
params.autoscale = 'on';
params.xscale = 1;
params.yscale = 1;
% was the params struct supplied?
if ~isempty(varargin)
if isstruct(varargin{1})
% params is only supplied if its a call from tiled_gridfit
params = varargin{1};
if length(varargin)>1
% check for any overrides
params = parse_pv_pairs(params,varargin{2:end});
end
else
% check for any overrides of the defaults
params = parse_pv_pairs(params,varargin);
end
end
% check the parameters for acceptability
params = check_params(params);
% ensure all of x,y,z,xnodes,ynodes are column vectors,
% also drop any NaN data
x=x(:);
y=y(:);
z=z(:);
k = isnan(x) | isnan(y) | isnan(z);
if any(k)
x(k)=[];
y(k)=[];
z(k)=[];
end
xmin = min(x);
xmax = max(x);
ymin = min(y);
ymax = max(y);
% did they supply a scalar for the nodes?
if length(xnodes)==1
xnodes = linspace(xmin,xmax,xnodes)';
xnodes(end) = xmax; % make sure it hits the max
end
if length(ynodes)==1
ynodes = linspace(ymin,ymax,ynodes)';
ynodes(end) = ymax; % make sure it hits the max
end
xnodes=xnodes(:);
ynodes=ynodes(:);
dx = diff(xnodes);
dy = diff(ynodes);
nx = length(xnodes);
ny = length(ynodes);
ngrid = nx*ny;
% set the scaling if autoscale was on
if strcmpi(params.autoscale,'on')
params.xscale = mean(dx);
params.yscale = mean(dy);
params.autoscale = 'off';
end
% check to see if any tiling is necessary
if (params.tilesize < max(nx,ny))
% split it into smaller tiles. compute zgrid and ygrid
% at the very end if requested
zgrid = tiled_gridfit(x,y,z,xnodes,ynodes,params);
else
% its a single tile.
% mask must be either an empty array, or a boolean
% aray of the same size as the final grid.
nmask = size(params.mask);
if ~isempty(params.mask) && ((nmask(2)~=nx) || (nmask(1)~=ny))
if ((nmask(2)==ny) || (nmask(1)==nx))
error 'Mask array is probably transposed from proper orientation.'
else
error 'Mask array must be the same size as the final grid.'
end
end
if ~isempty(params.mask)
params.maskflag = 1;
else
params.maskflag = 0;
end
% default for maxiter?
if isempty(params.maxiter)
params.maxiter = min(10000,nx*ny);
end
% check lengths of the data
n = length(x);
if (length(y)~=n) || (length(z)~=n)
error 'Data vectors are incompatible in size.'
end
if n<3
error 'Insufficient data for surface estimation.'
end
% verify the nodes are distinct
if any(diff(xnodes)<=0) || any(diff(ynodes)<=0)
error 'xnodes and ynodes must be monotone increasing'
end
% do we need to tweak the first or last node in x or y?
if xmin<xnodes(1)
switch params.extend
case 'always'
xnodes(1) = xmin;
case 'warning'
warning('GRIDFIT:extend',['xnodes(1) was decreased by: ',num2str(xnodes(1)-xmin),', new node = ',num2str(xmin)])
xnodes(1) = xmin;
case 'never'
error(['Some x (',num2str(xmin),') falls below xnodes(1) by: ',num2str(xnodes(1)-xmin)])
end
end
if xmax>xnodes(end)
switch params.extend
case 'always'
xnodes(end) = xmax;
case 'warning'
warning('GRIDFIT:extend',['xnodes(end) was increased by: ',num2str(xmax-xnodes(end)),', new node = ',num2str(xmax)])
xnodes(end) = xmax;
case 'never'
error(['Some x (',num2str(xmax),') falls above xnodes(end) by: ',num2str(xmax-xnodes(end))])
end
end
if ymin<ynodes(1)
switch params.extend
case 'always'
ynodes(1) = ymin;
case 'warning'
warning('GRIDFIT:extend',['ynodes(1) was decreased by: ',num2str(ynodes(1)-ymin),', new node = ',num2str(ymin)])
ynodes(1) = ymin;
case 'never'
error(['Some y (',num2str(ymin),') falls below ynodes(1) by: ',num2str(ynodes(1)-ymin)])
end
end
if ymax>ynodes(end)
switch params.extend
case 'always'
ynodes(end) = ymax;
case 'warning'
warning('GRIDFIT:extend',['ynodes(end) was increased by: ',num2str(ymax-ynodes(end)),', new node = ',num2str(ymax)])
ynodes(end) = ymax;
case 'never'
error(['Some y (',num2str(ymax),') falls above ynodes(end) by: ',num2str(ymax-ynodes(end))])
end
end
% determine which cell in the array each point lies in
[junk,indx] = histc(x,xnodes); %#ok
[junk,indy] = histc(y,ynodes); %#ok
% any point falling at the last node is taken to be
% inside the last cell in x or y.
k=(indx==nx);
indx(k)=indx(k)-1;
k=(indy==ny);
indy(k)=indy(k)-1;
ind = indy + ny*(indx-1);
% Do we have a mask to apply?
if params.maskflag
% if we do, then we need to ensure that every
% cell with at least one data point also has at
% least all of its corners unmasked.
params.mask(ind) = 1;
params.mask(ind+1) = 1;
params.mask(ind+ny) = 1;
params.mask(ind+ny+1) = 1;
end
% interpolation equations for each point
tx = min(1,max(0,(x - xnodes(indx))./dx(indx)));
ty = min(1,max(0,(y - ynodes(indy))./dy(indy)));
% Future enhancement: add cubic interpolant
switch params.interp
case 'triangle'
% linear interpolation inside each triangle
k = (tx > ty);
L = ones(n,1);
L(k) = ny;
t1 = min(tx,ty);
t2 = max(tx,ty);
A = sparse(repmat((1:n)',1,3),[ind,ind+ny+1,ind+L], ...
[1-t2,t1,t2-t1],n,ngrid);
case 'nearest'
% nearest neighbor interpolation in a cell
k = round(1-ty) + round(1-tx)*ny;
A = sparse((1:n)',ind+k,ones(n,1),n,ngrid);
case 'bilinear'
% bilinear interpolation in a cell
A = sparse(repmat((1:n)',1,4),[ind,ind+1,ind+ny,ind+ny+1], ...
[(1-tx).*(1-ty), (1-tx).*ty, tx.*(1-ty), tx.*ty], ...
n,ngrid);
end
rhs = z;
% do we have relative smoothing parameters?
if numel(params.smoothness) == 1
% it was scalar, so treat both dimensions equally
smoothparam = params.smoothness;
xyRelativeStiffness = [1;1];
else
% It was a vector, so anisotropy reigns.
% I've already checked that the vector was of length 2
smoothparam = sqrt(prod(params.smoothness));
xyRelativeStiffness = params.smoothness(:)./smoothparam;
end
% Build regularizer. Add del^4 regularizer one day.
switch params.regularizer
case 'springs'
% zero "rest length" springs
[i,j] = meshgrid(1:nx,1:(ny-1));
ind = j(:) + ny*(i(:)-1);
m = nx*(ny-1);
stiffness = 1./(dy/params.yscale);
Areg = sparse(repmat((1:m)',1,2),[ind,ind+1], ...
xyRelativeStiffness(2)*stiffness(j(:))*[-1 1], ...
m,ngrid);
[i,j] = meshgrid(1:(nx-1),1:ny);
ind = j(:) + ny*(i(:)-1);
m = (nx-1)*ny;
stiffness = 1./(dx/params.xscale);
Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny], ...
xyRelativeStiffness(1)*stiffness(i(:))*[-1 1],m,ngrid)];
[i,j] = meshgrid(1:(nx-1),1:(ny-1));
ind = j(:) + ny*(i(:)-1);
m = (nx-1)*(ny-1);
stiffness = 1./sqrt((dx(i(:))/params.xscale/xyRelativeStiffness(1)).^2 + ...
(dy(j(:))/params.yscale/xyRelativeStiffness(2)).^2);
Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny+1], ...
stiffness*[-1 1],m,ngrid)];
Areg = [Areg;sparse(repmat((1:m)',1,2),[ind+1,ind+ny], ...
stiffness*[-1 1],m,ngrid)];
case {'diffusion' 'laplacian'}
% thermal diffusion using Laplacian (del^2)
[i,j] = meshgrid(1:nx,2:(ny-1));
ind = j(:) + ny*(i(:)-1);
dy1 = dy(j(:)-1)/params.yscale;
dy2 = dy(j(:))/params.yscale;
Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...
xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ...
2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid);
[i,j] = meshgrid(2:(nx-1),1:ny);
ind = j(:) + ny*(i(:)-1);
dx1 = dx(i(:)-1)/params.xscale;
dx2 = dx(i(:))/params.xscale;
Areg = Areg + sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ...
xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ...
2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid);
case 'gradient'
% Subtly different from the Laplacian. A point for future
% enhancement is to do it better for the triangle interpolation
% case.
[i,j] = meshgrid(1:nx,2:(ny-1));
ind = j(:) + ny*(i(:)-1);
dy1 = dy(j(:)-1)/params.yscale;
dy2 = dy(j(:))/params.yscale;
Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...
xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ...
2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid);
[i,j] = meshgrid(2:(nx-1),1:ny);
ind = j(:) + ny*(i(:)-1);
dx1 = dx(i(:)-1)/params.xscale;
dx2 = dx(i(:))/params.xscale;
Areg = [Areg;sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ...
xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ...
2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid)];
end
nreg = size(Areg,1);
% Append the regularizer to the interpolation equations,
% scaling the problem first. Use the 1-norm for speed.
NA = norm(A,1);
NR = norm(Areg,1);
A = [A;Areg*(smoothparam*NA/NR)];
rhs = [rhs;zeros(nreg,1)];
% do we have a mask to apply?
if params.maskflag
unmasked = find(params.mask);
end
% solve the full system, with regularizer attached
switch params.solver
case {'\' 'backslash'}
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
zgrid(unmasked) = A(:,unmasked)\rhs;
else
% no mask
zgrid = reshape(A\rhs,ny,nx);
end
case 'normal'
% The normal equations, solved with \. Can be faster
% for huge numbers of data points, but reasonably
% sized grids. The regularizer makes A well conditioned
% so the normal equations are not a terribly bad thing
% here.
if params.maskflag
% there is a mask to use
Aunmasked = A(:,unmasked);
zgrid=nan(ny,nx);
zgrid(unmasked) = (Aunmasked'*Aunmasked)\(Aunmasked'*rhs);
else
zgrid = reshape((A'*A)\(A'*rhs),ny,nx);
end
case 'symmlq'
% iterative solver - symmlq - requires a symmetric matrix,
% so use it to solve the normal equations. No preconditioner.
tol = abs(max(z)-min(z))*1.e-13;
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
[zgrid(unmasked),flag] = symmlq(A(:,unmasked)'*A(:,unmasked), ...
A(:,unmasked)'*rhs,tol,params.maxiter);
else
[zgrid,flag] = symmlq(A'*A,A'*rhs,tol,params.maxiter);
zgrid = reshape(zgrid,ny,nx);
end
% display a warning if convergence problems
switch flag
case 0
% no problems with convergence
case 1
% SYMMLQ iterated MAXIT times but did not converge.
warning('GRIDFIT:solver',['Symmlq performed ',num2str(params.maxiter), ...
' iterations but did not converge.'])
case 3
% SYMMLQ stagnated, successive iterates were the same
warning('GRIDFIT:solver','Symmlq stagnated without apparent convergence.')
otherwise
warning('GRIDFIT:solver',['One of the scalar quantities calculated in',...
' symmlq was too small or too large to continue computing.'])
end
case 'lsqr'
% iterative solver - lsqr. No preconditioner here.
tol = abs(max(z)-min(z))*1.e-13;
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
[zgrid(unmasked),flag] = lsqr(A(:,unmasked),rhs,tol,params.maxiter);
else
[zgrid,flag] = lsqr(A,rhs,tol,params.maxiter);
zgrid = reshape(zgrid,ny,nx);
end
% display a warning if convergence problems
switch flag
case 0
% no problems with convergence
case 1
% lsqr iterated MAXIT times but did not converge.
warning('GRIDFIT:solver',['Lsqr performed ', ...
num2str(params.maxiter),' iterations but did not converge.'])
case 3
% lsqr stagnated, successive iterates were the same
warning('GRIDFIT:solver','Lsqr stagnated without apparent convergence.')
case 4
warning('GRIDFIT:solver',['One of the scalar quantities calculated in',...
' LSQR was too small or too large to continue computing.'])
end
end % switch params.solver
end % if params.tilesize...
% only generate xgrid and ygrid if requested.
if nargout>1
[xgrid,ygrid]=meshgrid(xnodes,ynodes);
end
% ============================================
% End of main function - gridfit
% ============================================
% ============================================
% subfunction - parse_pv_pairs
% ============================================
function params=parse_pv_pairs(params,pv_pairs)
% parse_pv_pairs: parses sets of property value pairs, allows defaults
% usage: params=parse_pv_pairs(default_params,pv_pairs)
%
% arguments: (input)
% default_params - structure, with one field for every potential
% property/value pair. Each field will contain the default
% value for that property. If no default is supplied for a
% given property, then that field must be empty.
%
% pv_array - cell array of property/value pairs.
% Case is ignored when comparing properties to the list
% of field names. Also, any unambiguous shortening of a
% field/property name is allowed.
%
% arguments: (output)
% params - parameter struct that reflects any updated property/value
% pairs in the pv_array.
%
% Example usage:
% First, set default values for the parameters. Assume we
% have four parameters that we wish to use optionally in
% the function examplefun.
%
% - 'viscosity', which will have a default value of 1
% - 'volume', which will default to 1
% - 'pie' - which will have default value 3.141592653589793
% - 'description' - a text field, left empty by default
%
% The first argument to examplefun is one which will always be
% supplied.
%
% function examplefun(dummyarg1,varargin)
% params.Viscosity = 1;
% params.Volume = 1;
% params.Pie = 3.141592653589793
%
% params.Description = '';
% params=parse_pv_pairs(params,varargin);
% params
%
% Use examplefun, overriding the defaults for 'pie', 'viscosity'
% and 'description'. The 'volume' parameter is left at its default.
%
% examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world')
%
% params =
% Viscosity: 10
% Volume: 1
% Pie: 3
% Description: 'Hello world'
%
% Note that capitalization was ignored, and the property 'viscosity'
% was truncated as supplied. Also note that the order the pairs were
% supplied was arbitrary.
npv = length(pv_pairs);
n = npv/2;
if n~=floor(n)
error 'Property/value pairs must come in PAIRS.'
end
if n<=0
% just return the defaults
return
end
if ~isstruct(params)
error 'No structure for defaults was supplied'
end
% there was at least one pv pair. process any supplied
propnames = fieldnames(params);
lpropnames = lower(propnames);
for i=1:n
p_i = lower(pv_pairs{2*i-1});
v_i = pv_pairs{2*i};
ind = strmatch(p_i,lpropnames,'exact');
if isempty(ind)
ind = find(strncmp(p_i,lpropnames,length(p_i)));
if isempty(ind)
error(['No matching property found for: ',pv_pairs{2*i-1}])
elseif length(ind)>1
error(['Ambiguous property name: ',pv_pairs{2*i-1}])
end
end
p_i = propnames{ind};
% override the corresponding default in params
params = setfield(params,p_i,v_i); %#ok
end
% ============================================
% subfunction - check_params
% ============================================
function params = check_params(params)
% check the parameters for acceptability
% smoothness == 1 by default
if isempty(params.smoothness)
params.smoothness = 1;
else
if (numel(params.smoothness)>2) || any(params.smoothness<=0)
error 'Smoothness must be scalar (or length 2 vector), real, finite, and positive.'
end
end
% regularizer - must be one of 4 options - the second and
% third are actually synonyms.
valid = {'springs', 'diffusion', 'laplacian', 'gradient'};
if isempty(params.regularizer)
params.regularizer = 'diffusion';
end
ind = find(strncmpi(params.regularizer,valid,length(params.regularizer)));
if (length(ind)==1)
params.regularizer = valid{ind};
else
error(['Invalid regularization method: ',params.regularizer])
end
% interp must be one of:
% 'bilinear', 'nearest', or 'triangle'
% but accept any shortening thereof.
valid = {'bilinear', 'nearest', 'triangle'};
if isempty(params.interp)
params.interp = 'triangle';
end
ind = find(strncmpi(params.interp,valid,length(params.interp)));
if (length(ind)==1)
params.interp = valid{ind};
else
error(['Invalid interpolation method: ',params.interp])
end
% solver must be one of:
% 'backslash', '\', 'symmlq', 'lsqr', or 'normal'
% but accept any shortening thereof.
valid = {'backslash', '\', 'symmlq', 'lsqr', 'normal'};
if isempty(params.solver)
params.solver = '\';
end
ind = find(strncmpi(params.solver,valid,length(params.solver)));
if (length(ind)==1)
params.solver = valid{ind};
else
error(['Invalid solver option: ',params.solver])
end
% extend must be one of:
% 'never', 'warning', 'always'
% but accept any shortening thereof.
valid = {'never', 'warning', 'always'};
if isempty(params.extend)
params.extend = 'warning';
end
ind = find(strncmpi(params.extend,valid,length(params.extend)));
if (length(ind)==1)
params.extend = valid{ind};
else
error(['Invalid extend option: ',params.extend])
end
% tilesize == inf by default
if isempty(params.tilesize)
params.tilesize = inf;
elseif (length(params.tilesize)>1) || (params.tilesize<3)
error 'Tilesize must be scalar and > 0.'
end
% overlap == 0.20 by default
if isempty(params.overlap)
params.overlap = 0.20;
elseif (length(params.overlap)>1) || (params.overlap<0) || (params.overlap>0.5)
error 'Overlap must be scalar and 0 < overlap < 1.'
end
% ============================================
% subfunction - tiled_gridfit
% ============================================
function zgrid=tiled_gridfit(x,y,z,xnodes,ynodes,params)
% tiled_gridfit: a tiled version of gridfit, continuous across tile boundaries
% usage: [zgrid,xgrid,ygrid]=tiled_gridfit(x,y,z,xnodes,ynodes,params)
%
% Tiled_gridfit is used when the total grid is far too large
% to model using a single call to gridfit. While gridfit may take
% only a second or so to build a 100x100 grid, a 2000x2000 grid
% will probably not run at all due to memory problems.
%
% Tiles in the grid with insufficient data (<4 points) will be
% filled with NaNs. Avoid use of too small tiles, especially
% if your data has holes in it that may encompass an entire tile.
%
% A mask may also be applied, in which case tiled_gridfit will
% subdivide the mask into tiles. Note that any boolean mask
% provided is assumed to be the size of the complete grid.
%
% Tiled_gridfit may not be fast on huge grids, but it should run
% as long as you use a reasonable tilesize. 8-)
% Note that we have already verified all parameters in check_params
% Matrix elements in a square tile
tilesize = params.tilesize;
% Size of overlap in terms of matrix elements. Overlaps
% of purely zero cause problems, so force at least two
% elements to overlap.
overlap = max(2,floor(tilesize*params.overlap));
% reset the tilesize for each particular tile to be inf, so
% we will never see a recursive call to tiled_gridfit
Tparams = params;
Tparams.tilesize = inf;
nx = length(xnodes);
ny = length(ynodes);
zgrid = zeros(ny,nx);
% linear ramp for the bilinear interpolation
rampfun = inline('(t-t(1))/(t(end)-t(1))','t');
% loop over each tile in the grid
h = waitbar(0,'Relax and have a cup of JAVA. Its my treat.');
warncount = 0;
xtind = 1:min(nx,tilesize);
while ~isempty(xtind) && (xtind(1)<=nx)
xinterp = ones(1,length(xtind));
if (xtind(1) ~= 1)
xinterp(1:overlap) = rampfun(xnodes(xtind(1:overlap)));
end
if (xtind(end) ~= nx)
xinterp((end-overlap+1):end) = 1-rampfun(xnodes(xtind((end-overlap+1):end)));
end
ytind = 1:min(ny,tilesize);
while ~isempty(ytind) && (ytind(1)<=ny)
% update the waitbar
waitbar((xtind(end)-tilesize)/nx + tilesize*ytind(end)/ny/nx)
yinterp = ones(length(ytind),1);
if (ytind(1) ~= 1)
yinterp(1:overlap) = rampfun(ynodes(ytind(1:overlap)));
end
if (ytind(end) ~= ny)
yinterp((end-overlap+1):end) = 1-rampfun(ynodes(ytind((end-overlap+1):end)));
end
% was a mask supplied?
if ~isempty(params.mask)
submask = params.mask(ytind,xtind);
Tparams.mask = submask;
end
% extract data that lies in this grid tile
k = (x>=xnodes(xtind(1))) & (x<=xnodes(xtind(end))) & ...
(y>=ynodes(ytind(1))) & (y<=ynodes(ytind(end)));
k = find(k);
if length(k)<4
if warncount == 0
warning('GRIDFIT:tiling','A tile was too underpopulated to model. Filled with NaNs.')
end
warncount = warncount + 1;
% fill this part of the grid with NaNs
zgrid(ytind,xtind) = NaN;
else
% build this tile
zgtile = gridfit(x(k),y(k),z(k),xnodes(xtind),ynodes(ytind),Tparams);
% bilinear interpolation (using an outer product)
interp_coef = yinterp*xinterp;
% accumulate the tile into the complete grid
zgrid(ytind,xtind) = zgrid(ytind,xtind) + zgtile.*interp_coef;
end
% step to the next tile in y
if ytind(end)<ny
ytind = ytind + tilesize - overlap;
% are we within overlap elements of the edge of the grid?
if (ytind(end)+max(3,overlap))>=ny
% extend this tile to the edge
ytind = ytind(1):ny;
end
else
ytind = ny+1;
end
end % while loop over y
% step to the next tile in x
if xtind(end)<nx
xtind = xtind + tilesize - overlap;
% are we within overlap elements of the edge of the grid?
if (xtind(end)+max(3,overlap))>=nx
% extend this tile to the edge
xtind = xtind(1):nx;
end
else
xtind = nx+1;
end
end % while loop over x
% close down the waitbar
close(h)
if warncount>0
warning('GRIDFIT:tiling',[num2str(warncount),' tiles were underpopulated & filled with NaNs'])
end
|
github | ojwoodford/ojwul-master | line_plane_intersect.m | .m | ojwul-master/geometry/line_plane_intersect.m | 540 | utf_8 | 9b909d96cedd515c326d8d31911ae40b | %LINE_PLANE_INTERSECT Compute the intersection point of a line and a plane
%
% Z = line_plane_intersect(N, X, Y, D)
%
% Computes the point of intersection of a line and a plane in M dimensions.
%
%IN:
% N - MxN plane normals.
% X - MxN points on plane.
% Y - MxN points on line.
% D - MxN line directions.
%
%OUT:
% Z - MxN output points.
function Y = line_plane_intersect(N, X, Y, D)
Y = bsxfun(@plus, Y, bsxfun(@times, D, sum(bsxfun(@times, bsxfun(@minus, X, Y), N), 1) ./ sum(bsxfun(@times, D, N), 1)));
end |
github | ojwoodford/ojwul-master | clip_line2rect.m | .m | ojwul-master/geometry/clip_line2rect.m | 1,709 | utf_8 | 13042b68e1492681d1292f72d51b403a | %CLIP_LINE2RECT Clips a line segment to within a rectangle
%
% X = clip_line2rect(X, rect)
%
% Clip a line to a rectangle using the Cohen-Sutherland algorithm,
% described here: https://en.wikipedia.org/wiki/Cohen-Sutherland_algorithm
%
%IN:
% X - 2x2 matrix of [x1 x2; y1 y2] start and end points.
% rect - 2x2 matrix of [left right; top bottom] rectangle boundaries.
%
%OUT:
% X - 2x2 matrix of [x1 x1; y1 y2] clipped start and end points.
function X = clip_line2rect(X, rect)
c(1) = area_code(X(:,1), rect);
c(2) = area_code(X(:,2), rect);
while true
if bitand(c(1), c(2))
% Segment is out of the rectangle
X(:) = NaN;
return;
end
[c_, ind] = max(c);
if c_ == 0
% Segment is inside the rectangle
return;
end
% Clip to one of the crossing axes
if c_ >= 8
X(1,ind) = X(1,ind) + (X(1,3-ind) - X(1,ind)) * (rect(2,2) - X(2,ind)) / (X(2,3-ind) - X(2,ind));
X(2,ind) = rect(2,2);
elseif c_ >= 4
X(1,ind) = X(1,ind) + (X(1,3-ind) - X(1,ind)) * (rect(2,1) - X(2,ind)) / (X(2,3-ind) - X(2,ind));
X(2,ind) = rect(2,1);
elseif c_ >= 2
X(2,ind) = X(2,ind) + (X(2,3-ind) - X(2,ind)) * (rect(1,2) - X(1,ind)) / (X(1,3-ind) - X(1,ind));
X(1,ind) = rect(1,2);
else
X(2,ind) = X(2,ind) + (X(2,3-ind) - X(2,ind)) * (rect(1,1) - X(1,ind)) / (X(1,3-ind) - X(1,ind));
X(1,ind) = rect(1,1);
end
c(ind) = area_code(X(:,ind), rect);
end
end
function c = area_code(X, rect)
c = uint8(0);
if X(1) < rect(1,1)
c = uint8(1);
elseif X(1) > rect(1,2)
c = uint8(2);
end
if X(2) < rect(2,1)
c = uint8(c) + 4;
elseif X(2) > rect(2,2)
c = uint8(c) + 8;
end
end
|
github | ojwoodford/ojwul-master | epipolar_error.m | .m | ojwul-master/geometry/epipolar_error.m | 795 | utf_8 | f1847d888974856b6633fb045ba76e01 | %EPIPOLAR_ERROR Compute the perpendicular error of points to epipolar lines
%
% d = epipolar_error(RX, T, x, [c])
%
% Computes the point to line error (i.e. signed distance) of points in an
% image to the corresponding epipolar lines.
%
%IN:
% RX - 3xN world points multiplied by rotation part of projection matrix
% P(:,1:3).
% T - 3x1 or 3xN translation part of projection matrix P(:,4).
% x - 2xN corresponding points in the image(s).
% c - 2x2xN conditioning matrix to weight the error.
%
%OUT:
% d - 1xN output error.
function d = epipolar_error(RX, T, x, cov)
T = proj(T);
x = x - T;
RX = proj(RX) - T;
RX = [RX(2,:); -RX(1,:)];
if nargin > 3
RX = tmult(inv22n(cov), RX, [1 0]);
x = tmult(cov, x);
end
d = dot(x, normalize(RX));
end
|
github | ojwoodford/ojwul-master | msac.m | .m | ojwul-master/geometry/msac.m | 3,015 | utf_8 | 76e32992cb6fdf8c15aa1ebe9b9a3696 | %MSAC Robustly fit a model to data with the MSAC algorithm
%
% [model, sqDists] = msac(X, fittingFunc, distFunc, minSamples, distThresh, maxTrials)
%
%IN:
% X - MxN data matrix, with each column being one datum, to which we are
% seeking to fit a model.
% fittingFunc - Handle to a function that fits a model to minSamples data
% from X. It is assumed that the function is of the form:
% model = fittingFunc(X);
% The fitting function can return multiple models in a cell
% array. If this function cannot fit a model, it should an
% empty matrix.
% distFunc - Handle to a function that computes the squared distances
% for each datum in X, given a model. It is assumed that the
% function is of the form:
% sqDist = distFunc(model, X);
% minSamples - The minimum number of samples from X required by
% fittingFunc to fit a model.
% distThresh - The squared distance threshold used to decide whether the
% point is an inlier or not.
% maxTrials - Maximum number of iterations. Default: 200.
%
%OUT:
% model - The best scoring model found.
% sqDists - 1xN vector of squared distances for the best model found.
function [bestM, bestD, stats] = msac(X, fittingFunc, distFunc, minSamples, distThresh, maxTrials)
confidence = 0.99999; % Desired probability of choosing at least one sample free from outliers
confidence = log1p(-confidence);
if nargin < 6
% Assume 30% inliers
maxTrials = confidence / (log1p(-(0.3 ^ minSamples)) + 1e-300);
end
bestM = [];
bestD = [];
[~, nPoints] = size(X);
if nPoints < minSamples
stats = zeros(1, 3);
return;
end
numTrials = 0;
numFailures = 0;
bestScore = Inf;
N = maxTrials;
while numTrials < N
% Select a set of points to try
ind = randperm(nPoints, minSamples);
% Fit model(s) to this random selection of data points
M = fittingFunc(X(:,ind));
if isempty(M)
numFailures = numFailures + 1;
if (numTrials + numFailures) >= maxTrials
break;
end
continue;
end
if ~iscell(M)
M = {M};
end
for a = 1:numel(M)
% Compute the distances for each datum
D = distFunc(M{a}, X);
% Compute a score
score = sum(min(D, distThresh));
% Compare the model to the current best
if score < bestScore
% Compute a new number of trials
pNoOutliers = sum(D < distThresh);
if pNoOutliers == 0
continue;
end
pNoOutliers = (pNoOutliers / nPoints) ^ minSamples;
N = min(maxTrials, confidence / (log1p(-pNoOutliers) + 1e-300));
% Store the new best model
bestScore = score;
bestD = D;
bestM = M{a};
end
end
numTrials = numTrials + numel(M);
end
if nargout > 2
stats = [numTrials numFailures maxTrials];
end
end
|
github | ojwoodford/ojwul-master | proj2so3.m | .m | ojwul-master/geometry/proj2so3.m | 280 | utf_8 | 042f2fb40c7c28f8459adae89d5c9510 | %PROJ2SO3 Project a 3x3 matrix onto the SO(3) manifold
%
% B = proj2so3(A)
%
% Projects a 3x3 matrix onto SO(3) (the space of rotation matrices) in a
% least squares way, s.t. B = argmin_{B in SO(3)} || B - A ||_F.
function R = proj2so3(R)
R = proj2orthonormal(R);
end |
github | ojwoodford/ojwul-master | rot2angle.m | .m | ojwul-master/geometry/rot2angle.m | 383 | utf_8 | 991bf0d787b4959bbd21201f88f7ebc2 | %ROT2ANGLE Given rotation matrices, compute their angle of rotation (in degrees)
%
% angle = rot2angle(R)
%
%IN:
% R - 3x{3,4}xN array of rotation or SO(3) matrices.
%
%OUT:
% angle - 1xN vector of angles, in degrees.
function R = rot2angle(R)
R = reshape(R, 3*size(R, 2), []);
R = sum(R([1 5 9],:), 1);
R = (180 / pi) * acos(max(min(0.5 * (R - 1), 1), -1));
end |
github | ojwoodford/ojwul-master | rot2euler.m | .m | ojwul-master/geometry/rot2euler.m | 496 | utf_8 | f762bbc225e86939d19abc9c6814951f | %ROT2EULER Converts 3x3xN rotation matrices to 3xN Euler angle representation
%
% X = rot2euler(R)
%
% The Euler representation is a [roll; pitch; yaw] set of angles (in
% radians), which are applied about the X, Y and Z axes of the frame
% respectively, and in that order.
function X = rot2euler(R)
X = shiftdim(max(min([R(3,3,:) R(3,1,:) R(1,1,:)], 1), -1), 1);
X(2,:) = -asin(X(2,:));
cospitch = cos(X(2,:));
X(1,:) = acos(X(1,:) ./ cospitch);
X(3,:) = acos(X(3,:) ./ cospitch); |
github | ojwoodford/ojwul-master | map_points.m | .m | ojwul-master/geometry/map_points.m | 3,939 | utf_8 | 5dee42a5ca70e7692415a6b2b7b8f0bc | %MAP POINTS Maps 3D points onto a series of input images
%
% map_points([options])
%
% Plots the feature points obtained from a Structure from Motion algorithm
% onto the input images in the sequence.
%
% IN:
% options - Pairs of arguments, the first being the option name and the
% second being the value. See the m file for details of the
% options available.
function map_points(varargin)
state.points = 'y.'; % Format string to use when plotting points.
state.tracks = 'c-'; % Format string to use when plotting tracks.
state.depth_thresh = 1e300; % Furthest depth to plot
state.stream_name = 'input.000.png'; % Name of the first frame in the sequence
state.Pi = []; % Camera projection matrices
state.X = []; % 3d scene points
state = vgg_argparse(state, varargin);
% Initialize variables
state.stream = imstream(state.stream_name, 100);
if isempty(state.Pi) || isempty(state.X)
path = fileparts(state.stream_name);
if ~isempty(path)
s = load([path '/data.mat']);
else
s = load('data.mat');
end
if isempty(state.Pi)
Pi = PcTo1(s.Pi, state.stream(1)); % Convert P matrices to MATLAB indexing conventions.
else
Pi = state.Pi;
end
if isempty(state.X)
points = s.points;
else
points = state.X;
end
else
Pi = state.Pi;
points = state.X;
end
state = rmfield(state, {'Pi', 'X'});
if size(points, 1) ~= 3
points = points';
end
points(4,:) = 1;
state.num_in = size(Pi, 3);
state.ind = 0;
state.projected_points = zeros(state.num_in, size(points, 2), 3);
for n = 1:state.num_in
% Project the 3-D points
A = Pi(:,:,n) * points;
state.projected_points(n,:,3) = A(3,:);
A(3,:) = 1 ./ A(3,:);
state.projected_points(n,:,1) = A(1,:) .* A(3,:);
state.projected_points(n,:,2) = A(2,:) .* A(3,:);
end
if sum(sum(state.projected_points(:,:,3)<0)) > (numel(state.projected_points) / 6)
state.projected_points(:,:,3) = -state.projected_points(:,:,3);
end
clear A
% Render the figure layout
fig = gcf();
figure(fig); clf('reset');
state.hIm = imdisp(state.stream(1));
hold on
if ~isempty(state.tracks)
state.hTracks = plot(zeros(100, 1), zeros(100, 1), state.tracks);
end
state.hPoints = plot(zeros(100, 1), zeros(100, 1), state.points);
hold off
% Set the callbacks
set(fig, 'KeyPressFcn', @keypress_callback, 'UserData', state, 'Interruptible', 'off', 'BusyAction', 'cancel');
% Update the figure
event_data.Character = 29;
keypress_callback(fig, event_data);
end
function keypress_callback(fig, event_data)
% Check what key was pressed and update the image index as necessary
switch event_data.Character
case 28 % Left
off = -2;
case 29 % Right
off = 0;
case 30 % Up
off = 9;
case 31 % Down
off = -11;
otherwise
return
end
state = get(fig, 'UserData');
state.ind = mod(state.ind + off, state.num_in) + 1;
% Select points in front of the camera and within a certain range
A = state.stream(state.ind);
M = state.projected_points(state.ind,:,3) > 0 & state.projected_points(state.ind,:,3) < state.depth_thresh;
M = M & state.projected_points(state.ind,:,1) > 1 & state.projected_points(state.ind,:,1) < size(A, 2);
M = M & state.projected_points(state.ind,:,2) > 1 & state.projected_points(state.ind,:,2) < size(A, 1);
% Update the image and points
set(state.hIm, 'CData', A);
if ~isempty(state.tracks) && state.ind > 1
X = state.projected_points(max(state.ind-4,1):state.ind,M,1); X(end+1,:) = NaN;
Y = state.projected_points(max(state.ind-4,1):state.ind,M,2); Y(end+1,:) = NaN;
set(state.hTracks, 'XData', X(:), 'YData', Y(:));
end
set(state.hPoints, 'XData', state.projected_points(state.ind,M,1), 'YData', state.projected_points(state.ind,M,2));
drawnow;
set(fig, 'UserData', state);
end
|
github | ojwoodford/ojwul-master | camera_extrinsics.m | .m | ojwul-master/geometry/camera_extrinsics.m | 764 | utf_8 | f97f7abb368f88889cdd2cf50d85e7ec | %CAMERA_EXTRINSICS Compute camera extrinsics from projection matrices
%
% [Pe, K] = camera_extrinsics(P)
%
% Given an array of 3x4 camera projection matrices, this function computes
% their extrinsics (matrices in SE3), and (optionally) their intrinsics
% (upper triangular 3x3 matrices).
%
% The output is such that P(:,:,i) = K(:,:,i) * Pe(:,:,i), for all i.
%
%IN:
% P - 3x4xM array of camera projection matrices.
%
%OUT:
% Pe - 3x4xM array of SE3 camera extrinsics matrices.
% K - 3x3xM array of upper triangular camera intrinsics matrices.
function [P, K] = camera_extrinsics(P)
sz = [size(P) 1];
K = zeros([3, 3, sz(3:end)]);
for a = 1:prod(sz(3:end))
[K(:,:,a), R, t] = KR_from_P(P(:,:,a));
P(:,:,a) = [R R*-t];
end
|
github | ojwoodford/ojwul-master | iou.m | .m | ojwul-master/geometry/iou.m | 780 | utf_8 | ed9a0b83ae67aa80477559307018ae6f | %IOU Compute the intersection over union of two shapes
%
% score = iou(A, B)
%
% Compute the intersection over union of two shapes, represented either by
% logical images, or by polygons.
%
%IN:
% A - 2xM polygon coordinates, or HxW logical matrix.
% B - 2xN polygon coordinates, or HxW logical matrix.
%
%OUT:
% score - scalar intersection over union score, in the range [0, 1].
function score = iou(A, B)
if isnumeric(A) && size(A, 1) == 2 && isnumeric(B) && size(B, 1) == 2
% Polygons
A = polyshape(A');
B = polyshape(B');
score = area(intersect(A, B)) / area(union(A, B));
elseif islogical(A) && islogical(B) && isequal(size(A), size(B))
% Bitmaps
score = sum(A(:) & B(:)) / sum(A(:) | B(:));
else
error('Inputs not recognized');
end
end
|
github | ojwoodford/ojwul-master | rot2quat.m | .m | ojwul-master/geometry/rot2quat.m | 1,201 | utf_8 | dc07a0572e836f2439454e0544aaecf9 | %ROT2QUAT Convert an array of 3x3 rotation matrices into quaternions
%
% Q = rot2quat(R, [w_last])
%
% This function generates quaternions of the form [w x y z]', such that R =
% eye(3) corresponds to Q = [1 0 0 0]'. If w_last is true, quaternions are
% of the form [x y z w].
%
%IN:
% R - 3x3xN array of rotation matrices.
% w_last - boolean indicating whether quaternions should be of the form
% [x y z w]'. Default: false.
%
%OUT:
% Q - 4xN array of corresponding quaternions.
function Q = rot2quat(R, w_last)
M = cat(3, [1 0 0 0 0 0 0; 0 0 0 0 1 0 -1; 0 0 -1 0 0 1 0; 0 1 0 -1 0 0 0], ...
[0 0 0 0 1 0 -1; 1 0 0 0 0 0 0; 0 1 0 1 0 0 0; 0 0 1 0 0 1 0], ...
[0 0 -1 0 0 1 0; 0 1 0 1 0 0 0; 1 0 0 0 0 0 0; 0 0 0 0 1 0 1], ...
[0 1 0 -1 0 0 0; 0 0 1 0 0 1 0; 0 0 0 0 1 0 1; 1 0 0 0 0 0 0]);
sz = size(R);
R = reshape(R, 9, []);
[m, n] = max([1, 1, 1; 1, -1, -1; -1, 1, -1; -1, -1, 1] * R([1 5 9],:));
m = sqrt(1 + m) / 2;
Q = sum(bsxfun(@times, M(:,:,n), shiftdim([m; bsxfun(@times, R([2 3 4 6 7 8],:), 1 ./ (4 * m))], -1)), 2);
Q = reshape(Q, [4 sz(3:end) 1]);
if nargin > 1 && w_last
Q = Q([2:4 1],:);
end
end
|
github | ojwoodford/ojwul-master | icp.m | .m | ojwul-master/geometry/icp.m | 19,735 | utf_8 | 9bd93b4bacde8a9293369d5fb1d1af8a | function [TR, TT, ER, t] = icp(q,p,varargin)
% Perform the Iterative Closest Point algorithm on three dimensional point
% clouds.
%
% [TR, TT] = icp(q,p) returns the rotation matrix TR and translation
% vector TT that minimizes the distances from (TR * p + TT) to q.
% p is a 3xm matrix and q is a 3xn matrix.
%
% [TR, TT] = icp(q,p,k) forces the algorithm to make k iterations
% exactly. The default is 10 iterations.
%
% [TR, TT, ER] = icp(q,p,k) also returns the RMS of errors for k
% iterations in a (k+1)x1 vector. ER(0) is the initial error.
%
% [TR, TT, ER, t] = icp(q,p,k) also returns the calculation times per
% iteration in a (k+1)x1 vector. t(0) is the time consumed for preprocessing.
%
% Additional settings may be provided in a parameter list:
%
% Boundary
% {[]} | 1x? vector
% If EdgeRejection is set, a vector can be provided that indexes into
% q and specifies which points of q are on the boundary.
%
% EdgeRejection
% {false} | true
% If EdgeRejection is true, point matches to edge vertices of q are
% ignored. Requires that boundary points of q are specified using
% Boundary or that a triangulation matrix for q is provided.
%
% Extrapolation
% {false} | true
% If Extrapolation is true, the iteration direction will be evaluated
% and extrapolated if possible using the method outlined by
% Besl and McKay 1992.
%
% Matching
% {bruteForce} | Delaunay | kDtree
% Specifies how point matching should be done.
% bruteForce is usually the slowest and kDtree is the fastest.
% Note that the kDtree option is depends on the Statistics Toolbox
% v. 7.3 or higher.
%
% Minimize
% {point} | plane | lmaPoint
% Defines whether point to point or point to plane minimization
% should be performed. point is based on the SVD approach and is
% usually the fastest. plane will often yield higher accuracy. It
% uses linearized angles and requires surface normals for all points
% in q. Calculation of surface normals requires substantial pre
% proccessing.
% The option lmaPoint does point to point minimization using the non
% linear least squares Levenberg Marquardt algorithm. Results are
% generally the same as in points, but computation time may differ.
%
% Normals
% {[]} | n x 3 matrix
% A matrix of normals for the n points in q might be provided.
% Normals of q are used for point to plane minimization.
% Else normals will be found through a PCA of the 4 nearest
% neighbors.
%
% ReturnAll
% {false} | true
% Determines whether R and T should be returned for all iterations
% or only for the last one. If this option is set to true, R will be
% a 3x3x(k+1) matrix and T will be a 3x1x(k+1) matrix.
%
% Triangulation
% {[]} | ? x 3 matrix
% A triangulation matrix for the points in q can be provided,
% enabling EdgeRejection. The elements should index into q, defining
% point triples that act together as triangles.
%
% Verbose
% {false} | true
% Enables extrapolation output in the Command Window.
%
% Weight
% {@(match)ones(1,m)} | Function handle
% For point or plane minimization, a function handle to a weighting
% function can be provided. The weighting function will be called
% with one argument, a 1xm vector that specifies point pairs by
% indexing into q. The weighting function should return a 1xm vector
% of weights for every point pair.
%
% WorstRejection
% {0} | scalar in ]0; 1[
% Reject a given percentage of the worst point pairs, based on their
% Euclidean distance.
%
% Martin Kjer and Jakob Wilm, Technical University of Denmark, 2012
% Copyright (c) 2012, Jakob Wilm & Hans Martin Kjer
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
% Use the inputParser class to validate input arguments.
inp = inputParser;
inp.addRequired('q', @(x)isreal(x) && size(x,1) == 3);
inp.addRequired('p', @(x)isreal(x) && size(x,1) == 3);
inp.addOptional('iter', 10, @(x)x > 0 && x < 10^5);
inp.addParamValue('Boundary', [], @(x)size(x,1) == 1);
inp.addParamValue('EdgeRejection', false, @(x)islogical(x));
inp.addParamValue('Extrapolation', false, @(x)islogical(x));
validMatching = {'bruteForce','Delaunay','kDtree'};
inp.addParamValue('Matching', 'bruteForce', @(x)any(strcmpi(x,validMatching)));
validMinimize = {'point','plane','lmapoint'};
inp.addParamValue('Minimize', 'point', @(x)any(strcmpi(x,validMinimize)));
inp.addParamValue('Normals', [], @(x)isreal(x) && size(x,1) == 3);
inp.addParamValue('NormalsData', [], @(x)isreal(x) && size(x,1) == 3);
inp.addParamValue('ReturnAll', false, @(x)islogical(x));
inp.addParamValue('Triangulation', [], @(x)isreal(x) && size(x,2) == 3);
inp.addParamValue('Verbose', false, @(x)islogical(x));
inp.addParamValue('Weight', @(x)ones(1,length(x)), @(x)isa(x,'function_handle'));
inp.addParamValue('WorstRejection', 0, @(x)isscalar(x) && x > 0 && x < 1);
inp.parse(q,p,varargin{:});
arg = inp.Results;
clear('inp');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Actual implementation
% Allocate vector for RMS of errors in every iteration.
t = zeros(arg.iter+1,1);
% Start timer
tic;
Np = size(p,2);
% Transformed data point cloud
pt = p;
% Allocate vector for RMS of errors in every iteration.
ER = zeros(arg.iter+1,1);
% Initialize temporary transform vector and matrix.
T = zeros(3,1);
R = eye(3,3);
% Initialize total transform vector(s) and rotation matric(es).
TT = zeros(3,1, arg.iter+1);
TR = repmat(eye(3,3), [1,1, arg.iter+1]);
% If Minimize == 'plane', normals are needed
if (strcmp(arg.Minimize, 'plane') && isempty(arg.Normals))
arg.Normals = lsqnormest(q,4);
end
% If Matching == 'Delaunay', a triangulation is needed
if strcmp(arg.Matching, 'Delaunay')
DT = DelaunayTri(transpose(q));
end
% If Matching == 'kDtree', a kD tree should be built (req. Stat. TB >= 7.3)
if strcmp(arg.Matching, 'kDtree')
kdOBJ = KDTreeSearcher(transpose(q));
end
% If edge vertices should be rejected, find edge vertices
if arg.EdgeRejection
if isempty(arg.Boundary)
bdr = find_bound(q, arg.Triangulation);
else
bdr = arg.Boundary;
end
end
if arg.Extrapolation
% Initialize total transform vector (quaternion ; translation vec.)
qq = [ones(1,arg.iter+1);zeros(6,arg.iter+1)];
% Allocate vector for direction change and change angle.
dq = zeros(7,arg.iter+1);
theta = zeros(1,arg.iter+1);
end
t(1) = toc;
% Go into main iteration loop
for k=1:arg.iter
% Do matching
switch arg.Matching
case 'bruteForce'
[match mindist] = match_bruteForce(q,pt);
case 'Delaunay'
[match mindist] = match_Delaunay(q,pt,DT);
case 'kDtree'
[match mindist] = match_kDtree(q,pt,kdOBJ);
end
% If matches to edge vertices should be rejected
if arg.EdgeRejection
p_idx = not(ismember(match, bdr));
q_idx = match(p_idx);
mindist = mindist(p_idx);
else
p_idx = true(1, Np);
q_idx = match;
end
% If worst matches should be rejected
if arg.WorstRejection
edge = round((1-arg.WorstRejection)*sum(p_idx));
pairs = find(p_idx);
[~, idx] = sort(mindist);
p_idx(pairs(idx(edge:end))) = false;
q_idx = match(p_idx);
mindist = mindist(p_idx);
end
if k == 1
ER(k) = sqrt(sum(mindist.^2)/length(mindist));
end
switch arg.Minimize
case 'point'
% Determine weight vector
weights = arg.Weight(match);
[R,T] = eq_point(q(:,q_idx),pt(:,p_idx), weights(p_idx));
case 'plane'
weights = arg.Weight(match);
[R,T] = eq_plane(q(:,q_idx),pt(:,p_idx),arg.Normals(:,q_idx),weights(p_idx));
case 'lmaPoint'
[R,T] = eq_lmaPoint(q(:,q_idx),pt(:,p_idx));
end
% Add to the total transformation
TR(:,:,k+1) = R*TR(:,:,k);
TT(:,:,k+1) = R*TT(:,:,k)+T;
% Apply last transformation
pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np);
% Root mean of objective function
ER(k+1) = rms_error(q(:,q_idx), pt(:,p_idx));
% If Extrapolation, we might be able to move quicker
if arg.Extrapolation
qq(:,k+1) = [rmat2quat(TR(:,:,k+1));TT(:,:,k+1)];
dq(:,k+1) = qq(:,k+1) - qq(:,k);
theta(k+1) = (180/pi)*acos(dot(dq(:,k),dq(:,k+1))/(norm(dq(:,k))*norm(dq(:,k+1))));
if arg.Verbose
disp(['Direction change ' num2str(theta(k+1)) ' degree in iteration ' num2str(k)]);
end
if k>2 && theta(k+1) < 10 && theta(k) < 10
d = [ER(k+1), ER(k), ER(k-1)];
v = [0, -norm(dq(:,k+1)), -norm(dq(:,k))-norm(dq(:,k+1))];
vmax = 25 * norm(dq(:,k+1));
dv = extrapolate(v,d,vmax);
if dv ~= 0
q_mark = qq(:,k+1) + dv * dq(:,k+1)/norm(dq(:,k+1));
q_mark(1:4) = q_mark(1:4)/norm(q_mark(1:4));
qq(:,k+1) = q_mark;
TR(:,:,k+1) = quat2rmat(qq(1:4,k+1));
TT(:,:,k+1) = qq(5:7,k+1);
% Reapply total transformation
pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np);
% Recalculate root mean of objective function
% Note this is costly and only for fun!
switch arg.Matching
case 'bruteForce'
[~, mindist] = match_bruteForce(q,pt);
case 'Delaunay'
[~, mindist] = match_Delaunay(q,pt,DT);
case 'kDtree'
[~, mindist] = match_kDtree(q,pt,kdOBJ);
end
ER(k+1) = sqrt(sum(mindist.^2)/length(mindist));
end
end
end
t(k+1) = toc;
end
if not(arg.ReturnAll)
TR = TR(:,:,end);
TT = TT(:,:,end);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [match mindist] = match_bruteForce(q, p)
m = size(p,2);
n = size(q,2);
match = zeros(1,m);
mindist = zeros(1,m);
for ki=1:m
d=zeros(1,n);
for ti=1:3
d=d+(q(ti,:)-p(ti,ki)).^2;
end
[mindist(ki),match(ki)]=min(d);
end
mindist = sqrt(mindist);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [match mindist] = match_Delaunay(q, p, DT)
match = transpose(nearestNeighbor(DT, transpose(p)));
mindist = sqrt(sum((p-q(:,match)).^2,1));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [match mindist] = match_kDtree(~, p, kdOBJ)
[match mindist] = knnsearch(kdOBJ,transpose(p));
match = transpose(match);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [R,T] = eq_point(q,p,weights)
m = size(p,2);
n = size(q,2);
% normalize weights
weights = weights ./ sum(weights);
% find data centroid and deviations from centroid
q_bar = q * transpose(weights);
q_mark = q - repmat(q_bar, 1, n);
% Apply weights
q_mark = q_mark .* repmat(weights, 3, 1);
% find data centroid and deviations from centroid
p_bar = p * transpose(weights);
p_mark = p - repmat(p_bar, 1, m);
% Apply weights
%p_mark = p_mark .* repmat(weights, 3, 1);
N = p_mark*transpose(q_mark); % taking points of q in matched order
[U,~,V] = svd(N); % singular value decomposition
R = V*diag([1 1 det(U*V')])*transpose(U);
T = q_bar - R*p_bar;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [R,T] = eq_plane(q,p,n,weights)
n = n .* repmat(weights,3,1);
c = cross(p,n);
cn = vertcat(c,n);
C = cn*transpose(cn);
b = - [sum(sum((p-q).*repmat(cn(1,:),3,1).*n));
sum(sum((p-q).*repmat(cn(2,:),3,1).*n));
sum(sum((p-q).*repmat(cn(3,:),3,1).*n));
sum(sum((p-q).*repmat(cn(4,:),3,1).*n));
sum(sum((p-q).*repmat(cn(5,:),3,1).*n));
sum(sum((p-q).*repmat(cn(6,:),3,1).*n))];
X = C\b;
cx = cos(X(1)); cy = cos(X(2)); cz = cos(X(3));
sx = sin(X(1)); sy = sin(X(2)); sz = sin(X(3));
R = [cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz;
cy*sz cx*cz+sx*sy*sz cx*sy*sz-cz*sx;
-sy cy*sx cx*cy];
T = X(4:6);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [R,T] = eq_lmaPoint(q,p)
Rx = @(a)[1 0 0;
0 cos(a) -sin(a);
0 sin(a) cos(a)];
Ry = @(b)[cos(b) 0 sin(b);
0 1 0;
-sin(b) 0 cos(b)];
Rz = @(g)[cos(g) -sin(g) 0;
sin(g) cos(g) 0;
0 0 1];
Rot = @(x)Rx(x(1))*Ry(x(2))*Rz(x(3));
myfun = @(x,xdata)Rot(x(1:3))*xdata+repmat(x(4:6),1,length(xdata));
options = optimset('Algorithm', 'levenberg-marquardt');
x = lsqcurvefit(myfun, zeros(6,1), p, q, [], [], options);
R = Rot(x(1:3));
T = x(4:6);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Extrapolation in quaternion space. Details are found in:
%
% Besl, P., & McKay, N. (1992). A method for registration of 3-D shapes.
% IEEE Transactions on pattern analysis and machine intelligence, 239?256.
function [dv] = extrapolate(v,d,vmax)
p1 = polyfit(v,d,1); % linear fit
p2 = polyfit(v,d,2); % parabolic fit
v1 = -p1(2)/p1(1); % linear zero crossing
v2 = -p2(2)/(2*p2(1)); % polynomial top point
if issorted([0 v2 v1 vmax]) || issorted([0 v2 vmax v1])
disp('Parabolic update!');
dv = v2;
elseif issorted([0 v1 v2 vmax]) || issorted([0 v1 vmax v2])...
|| (v2 < 0 && issorted([0 v1 vmax]))
disp('Line based update!');
dv = v1;
elseif v1 > vmax && v2 > vmax
disp('Maximum update!');
dv = vmax;
else
disp('No extrapolation!');
dv = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Determine the RMS error between two point equally sized point clouds with
% point correspondance.
% ER = rms_error(p1,p2) where p1 and p2 are 3xn matrices.
function ER = rms_error(p1,p2)
dsq = sum(power(p1 - p2, 2),1);
ER = sqrt(mean(dsq));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Converts (orthogonal) rotation matrices R to (unit) quaternion
% representations
%
% Input: A 3x3xn matrix of rotation matrices
% Output: A 4xn matrix of n corresponding quaternions
%
% http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion
function quaternion = rmat2quat(R)
Qxx = R(1,1,:);
Qxy = R(1,2,:);
Qxz = R(1,3,:);
Qyx = R(2,1,:);
Qyy = R(2,2,:);
Qyz = R(2,3,:);
Qzx = R(3,1,:);
Qzy = R(3,2,:);
Qzz = R(3,3,:);
w = 0.5 * sqrt(1+Qxx+Qyy+Qzz);
x = 0.5 * sign(Qzy-Qyz) .* sqrt(1+Qxx-Qyy-Qzz);
y = 0.5 * sign(Qxz-Qzx) .* sqrt(1-Qxx+Qyy-Qzz);
z = 0.5 * sign(Qyx-Qxy) .* sqrt(1-Qxx-Qyy+Qzz);
quaternion = reshape([w;x;y;z],4,[]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Converts (unit) quaternion representations to (orthogonal) rotation matrices R
%
% Input: A 4xn matrix of n quaternions
% Output: A 3x3xn matrix of corresponding rotation matrices
%
% http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#From_a_quaternion_to_an_orthogonal_matrix
function R = quat2rmat(quaternion)
q0(1,1,:) = quaternion(1,:);
qx(1,1,:) = quaternion(2,:);
qy(1,1,:) = quaternion(3,:);
qz(1,1,:) = quaternion(4,:);
R = [q0.^2+qx.^2-qy.^2-qz.^2 2*qx.*qy-2*q0.*qz 2*qx.*qz+2*q0.*qy;
2*qx.*qy+2*q0.*qz q0.^2-qx.^2+qy.^2-qz.^2 2*qy.*qz-2*q0.*qx;
2*qx.*qz-2*q0.*qy 2*qy.*qz+2*q0.*qx q0.^2-qx.^2-qy.^2+qz.^2];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Least squares normal estimation from point clouds using PCA
%
% H. Hoppe, T. DeRose, T. Duchamp, J. McDonald, and W. Stuetzle.
% Surface reconstruction from unorganized points.
% In Proceedings of ACM Siggraph, pages 71:78, 1992.
%
% p should be a matrix containing the horizontally concatenated column
% vectors with points. k is a scalar indicating how many neighbors the
% normal estimation is based upon.
%
% Note that for large point sets, the function performs significantly
% faster if Statistics Toolbox >= v. 7.3 is installed.
%
% Jakob Wilm 2010
function n = lsqnormest(p, k)
m = size(p,2);
n = zeros(3,m);
v = ver('stats');
if ~isempty(v) && str2double(v.Version) >= 7.5
neighbors = transpose(knnsearch(transpose(p), transpose(p), 'k', k+1));
else
neighbors = k_nearest_neighbors(p, p, k+1);
end
for i = 1:m
x = p(:,neighbors(2:end, i));
p_bar = 1/k * sum(x,2);
P = (x - repmat(p_bar,1,k)) * transpose(x - repmat(p_bar,1,k)); %spd matrix P
%P = 2*cov(x);
[V,D] = eig(P);
[~, idx] = min(diag(D)); % choses the smallest eigenvalue
n(:,i) = V(:,idx); % returns the corresponding eigenvector
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Program to find the k - nearest neighbors (kNN) within a set of points.
% Distance metric used: Euclidean distance
%
% Note that this function makes repetitive use of min(), which seems to be
% more efficient than sort() for k < 30.
function [neighborIds neighborDistances] = k_nearest_neighbors(dataMatrix, queryMatrix, k)
numDataPoints = size(dataMatrix,2);
numQueryPoints = size(queryMatrix,2);
neighborIds = zeros(k,numQueryPoints);
neighborDistances = zeros(k,numQueryPoints);
D = size(dataMatrix, 1); %dimensionality of points
for i=1:numQueryPoints
d=zeros(1,numDataPoints);
for t=1:D % this is to avoid slow repmat()
d=d+(dataMatrix(t,:)-queryMatrix(t,i)).^2;
end
for j=1:k
[s,t] = min(d);
neighborIds(j,i)=t;
neighborDistances(j,i)=sqrt(s);
d(t) = NaN; % remove found number from d
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Boundary point determination. Given a set of 3D points and a
% corresponding triangle representation, returns those point indices that
% define the border/edge of the surface.
function bound = find_bound(pts, poly)
%Correcting polygon indices and converting datatype
poly = double(poly);
pts = double(pts);
%Calculating freeboundary points:
TR = TriRep(poly, pts(1,:)', pts(2,:)', pts(3,:)');
FF = freeBoundary(TR);
%Output
bound = FF(:,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github | ojwoodford/ojwul-master | KR_from_P.m | .m | ojwul-master/geometry/KR_from_P.m | 424 | utf_8 | 02dc227cf003aa17ea2fff578a4d449e | %KR_from_P Generate K, R and t matrices from a 3x4 projection matrix
%
% [K, R, t] = KR_from_P(P)
%
% P = scalar * K * R * [eye(3) -t]
function [K, R, t] = KR_from_P(P)
st = @(M) M(end:-1:1,end:-1:1)';
[R, K] = qr(st(P(:,1:3)));
K = st(K);
I = diag(K) < 0;
K(:,I) = -K(:,I);
if nargout > 1
R = st(R);
R(I,:) = -R(I,:);
if nargout > 2
t = (K * R) \ -P(:,4);
end
end
K = K / K(3,3); |
github | ojwoodford/ojwul-master | epipolar_disparity.m | .m | ojwul-master/geometry/epipolar_disparity.m | 1,249 | utf_8 | 9f4bd1fc9640f3290556b864f06f64e5 | %EPIPOLAR_DISPARITY Compute the disparity of points on/near epipolar lines
%
% d = epipolar_disparity(RX, T, x)
%
% Computes the disparity of points on epipolar lines that are closest to
% points in an image.
%
%IN:
% RX - 3xN world points multiplied by rotation part of projection matrix
% P(:,1:3).
% T - 3x1 or 3xN translation part of projection matrix P(:,4).
% x - 2xN corresponding points in the image(s).
%
%OUT:
% d - 1xN output disparity.
% dx - 2xN derivative of d w.r.t. x
function [d, dx] = epipolar_disparity(RX, T, x)
sum2 = @(X) [X(1,:)+X(2,:); X(3,:)];
RXT = sum2(bsxfun(@times, RX, T));
RX2 = sum2(RX .* RX);
T2 = sum2(T .* T);
Tx = sum(bsxfun(@times, T(1:2,:), x), 1);
RXx = sum(RX(1:2,:) .* x, 1);
n = T(3,:) .* RX2(1,:) - RXT(1,:) .* RX(3,:) + Tx .* RX2(2,:) - RXT(2,:) .* RXx;
d = T2(1,:) .* RX(3,:) - RXT(1,:) .* T(3,:) + RXx .* T2(2,:) - RXT(2,:) .* Tx;
if nargout > 1
% Compute the derivative
dx = bsxfun(@times, bsxfun(@times, T(1:2,:), RX2(2,:)) - bsxfun(@times, RX(1:2,:), RXT(2,:)), d) + ...
bsxfun(@times, bsxfun(@times, T(1:2,:), RXT(2,:)) - bsxfun(@times, RX(1:2,:), T2(2,:)), n);
dx = bsxfun(@times, dx, 1 ./ (d .* d));
end
d = n ./ d;
end
|
github | ojwoodford/ojwul-master | msac_fundmatrix.m | .m | ojwul-master/geometry/msac_fundmatrix.m | 3,810 | utf_8 | e5fd0ac329c9365e4e0dc7ace1eec21b | % MSAC_FUNDMATRIX - fits fundamental matrix using RANSAC
%
% Usage: [F, inliers] = msac_fundmatrix(x1, x2, t)
%
% Arguments:
% x1 - 2xN or 3xN set of homogeneous points. If the data is
% 2xN it is assumed the homogeneous scale factor is 1.
% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
% Note that point coordinates are normalised to that their
% mean distance from the origin is sqrt(2). The value of
% t should be set relative to this, say in the range
% 0.001 - 0.01
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% F - The 3x3 fundamental matrix such that x2'Fx1 = 0.
% inliers - An array of indices of the elements of x1, x2 that were
% the inliers for the best model.
% Copyright (c) 2004-2005 Peter Kovesi
function [F, D, stats] = msac_fundmatrix(x1, x2, t)
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
[rows,npts] = size(x1);
if rows~=2 && rows~=3
error('x1 and x2 must have 2 or 3 rows');
end
if rows == 2 % Pad data with homogeneous scale factor of 1
x1 = [x1; ones(1,npts)];
x2 = [x2; ones(1,npts)];
end
% Normalize each set of points so that the origin is at centroid and
% mean distance from origin is sqrt(2). normalize2dpts also ensures the
% scale parameter is 1.
[T, T] = normalise2dpts([x1 x2]);
x1n = T * x1;
x2n = T * x2;
t = t * T(1) * T(5);
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[F, inliers, stats] = msac([x1n; x2n], @(x) fundmatrix(x(1:3,:), x(4:6,:)), @(F, x) funddist(F, x(1:3,:), x(4:6,:)), 8, t);
inliers = inliers < t;
% Now do a final least squares fit on the data points considered to
% be inliers.
F = fundmatrix(x1n(:,inliers), x2n(:,inliers));
% Denormalize
F = T' * F * T;
F = F / F(3,3);
if nargout < 2
return;
end
% Compute the distances
D = funddist(F, x1, x2);
end
%--------------------------------------------------------------------------
% 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
function F = fundmatrix(x1, x2)
% Build the constraint matrix
F = [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(size(x1, 2),1) ];
[U, D, F] = svd(F,0); % Under MATLAB use the economy decomposition
% Extract fundamental matrix from the column of V corresponding to
% smallest singular value.
F = reshape(F(:,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, F] = svd(F,0);
F = U * diag([D(1,1) D(2,2) 0]) * F';
end
%--------------------------------------------------------------------------
% Function to evaluate the first order approximation of the geometric error
% (Sampson distance) of the fit of a fundamental matrix with respect to a
% set of matched points as needed by RANSAC. See: Hartley and Zisserman,
% 'Multiple View Geometry in Computer Vision', page 270.
function D = funddist(F, x1, x2)
Fx = F * x1;
x2tFx1 = sum(x2 .* Fx, 1);
Fx = [Fx; F' * x2];
% Evaluate distances
D = (x2tFx1 .* x2tFx1) ./ sum(Fx .* Fx, 1);
end
|
github | ojwoodford/ojwul-master | plane_fit.m | .m | ojwul-master/geometry/plane_fit.m | 512 | utf_8 | 0c9c37021ab1e4eaf2e1eb03c2d2cf9a | %PLANE_FIT Weighted least squares plane fit to 3D points
%
% N = plane_fit(X, [W])
%
% Finds the (weighted) least squares fit of a plane to 3D points, such that
% N' * homg(X) = 0.
%
%IN:
% X - 3xM matrix of 3D points.
% W - 1xM vector of weights per point. Default: ones(1, M).
%
%OUT:
% N - 1x4 plane equation vector.
function N = plane_fit(X, W)
m = mean(X, 2);
X = bsxfun(@minus, X, m);
if nargin > 1
X = bsxfun(@times, X, sqrt(W(:)'));
end
[N, ~] = svd(X, 0);
N = N(:,3)';
N(4) = -(N * m);
end
|
github | ojwoodford/ojwul-master | epipolar_demo.m | .m | ojwul-master/geometry/epipolar_demo.m | 2,902 | utf_8 | 33517fb629c7e7fa6883f3ee908344db | %EPIPOLAR_DEMO Interactively show epipolar geometry between two images
%
% epipolar_demo(ims, F)
%
% Given a pair of images and their fundamental matrix, or two projection
% matrices from world to image coordinates, this function renders the
% epipolar geometry of a given pixel from one image in the second image.
% Lines can be stored by clicking on pixels.
%
% IN:
% ims - 2x1 cell array of input images
% F - 3x3 fundamental matrix or 3x4x2 set of projection matrices.
function epipolar_demo(ims, F)
% Convert projection matrices to a fundamental matrx
if isequal(size(F), [3 4 2])
F = F_from_P(F);
end
state.F = {F, F'};
% Initialize the plot
clf;
nn = [NaN; NaN];
for a = 2:-1:1
% Render the image
state.im(a).hAx = axes('Position', [0.01+(a-1)*0.495 0.01 0.485 0.98]);
state.im(a).sz = size(ims{a});
image(ims{a});
colormap(gray(256));
axis equal off
xlim([0.5 state.im(a).sz(2)+0.5]);
ylim([0.5 state.im(a).sz(1)+0.5]);
% Render the line
hold on
state.im(a).hL = plot(nn, nn, 'r-');
hold off
end
set(gcf(), 'Interruptible', 'off', 'BusyAction', 'cancel', 'WindowButtonUpFcn', @mouseup_callback, 'WindowButtonMotionFcn', @mouse_callback, 'UserData', state);
end
function mouse_callback(fig, evnt)
state = get(fig, 'UserData');
nn = [NaN; NaN];
for a = 1:2
% Get the mouse location
y = get(state.im(a).hAx, 'CurrentPoint');
x = round(y(1,1));
y = round(y(1,2));
% Check if it is over the image
if x < 1 || x > state.im(a).sz(2) || y < 1 || y > state.im(a).sz(1)
% Clear the line in the other image
X = nn;
Y = nn;
else
% Plot the epipolar line in the other image
[X, Y] = compute_line(state, a, x, y);
end
set(state.im(3-a).hL, 'XData', X, 'YData', Y);
end
drawnow();
end
function mouseup_callback(fig, evnt)
state = get(fig, 'UserData');
% Render the point and line in a random colour
col = rand(1, 3);
for a = 1:2
% Get the mouse location
y = get(state.im(a).hAx, 'CurrentPoint');
x = round(y(1,1));
y = round(y(1,2));
% Check if it is over the image
if x < 1 || x > state.im(a).sz(2) || y < 1 || y > state.im(a).sz(1)
continue;
end
% Plot the epipolar line in the other image
[X, Y] = compute_line(state, a, x, y);
set(fig, 'CurrentAxes', state.im(a).hAx);
hold on
plot(x, y, 'r+', 'Color', col);
hold off
set(fig, 'CurrentAxes', state.im(3-a).hAx);
hold on
plot(X, Y, 'r-', 'Color', col);
hold off
end
drawnow;
end
function [X, Y] = compute_line(state, a, x, y)
L = state.F{a} * [x; y; 1];
if L(1) > L(2)
X = [0.5; state.im(3-a).sz(2)+0.5];
Y = (-L(3) - L(1) * X) / L(2);
else
Y = [0.5; state.im(3-a).sz(1)+0.5];
X = (-L(3) - L(2) * Y) / L(1);
end
end
|
github | ojwoodford/ojwul-master | line_intersect.m | .m | ojwul-master/geometry/line_intersect.m | 594 | utf_8 | 5e41795b812d28bb6ac63664a7340d16 | %LINE_INTERSECT Compute the intersection point of two lines
%
% [y, l] = line_intersect(x1, n1, x2, n2)
%
% Computes the point of intersection of two lines in 2D.
%
%IN:
% x1 - 2xN points on line 1.
% n1 - 2xN directions of line 1.
% x2 - 2xN points on line 2.
% n2 - 2xN directions of line 2.
%
%OUT:
% v - 2xN output point.
% l - 1xN distance of intersection from x1 in units of norm(n1).
function [y, l] = line_intersect(x1, n1, x2, n2)
n2 = [n2(2,:); -n2(1,:)];
l = (sum(n2 .* x2, 1) - sum(n2 .* x1, 1)) ./ sum(n1 .* n2, 1);
y = x1 + bsxfun(@times, n1, l); |
github | ojwoodford/ojwul-master | rot2expmap.m | .m | ojwul-master/geometry/rot2expmap.m | 410 | utf_8 | d484cd1eda51e7558ba93cc2bccd196b | %ROT2EXPMAP Converts 3x3xN rotation matrices to 3xN exponential mappings
%
% X = rot2expmap(R)
function X = rot2expmap(R)
sz = [size(R) 1];
th = reshape(acos(1 - mod((0.5 * (1 - min(R(1,1,:) + R(2,2,:) + R(3,3,:), 3)) - 1), 2)), [1 sz(3:end)]);
X = reshape([R(3,2,:)-R(2,3,:); R(1,3,:)-R(3,1,:); R(2,1,:)-R(1,2,:)], [3 sz(3:end)]);
X = bsxfun(@times, X, th ./ (sqrt(sum(X .* X, 1)) + 1e-300));
end
|
github | ojwoodford/ojwul-master | homg.m | .m | ojwul-master/geometry/homg.m | 257 | utf_8 | db8f103523c3288323bcb424c53c36e5 | %HOMG Homogenize vectors
%
% Y = homg(X)
%
% Homogenize an array of vectors along the first dimension, by
% concatenating a 1.
%
%IN:
% X - MxN input array.
%
%OUT:
% Y - (M+1)xN output array.
function X = homg(X)
X(end+1,:) = 1;
end
|
github | ojwoodford/ojwul-master | proj.m | .m | ojwul-master/geometry/proj.m | 484 | utf_8 | eff570a09cdbf49c19e36e5d6c7ad40c | %PROJ Project points onto the image plane
%
% [Y, z] = proj(X)
%
% Project points into a lower dimension by dividing thorugh by the last
% dimension, e.g. pinhole camera projection.
%
%IN:
% X - MxN input array.
%
%OUT:
% Y - (M-1)xN output array.
% z - 1xN array of normalizing values, z = 1./X(end,:).
function [X, z] = proj(X)
sz = size(X);
sz(1) = sz(1) - 1;
z = 1 ./ X(end,:);
X = reshape(X(1:end-1,:) .* z, sz);
sz(1) = 1;
z = reshape(z, sz);
end
|
github | ojwoodford/ojwul-master | camera_centers.m | .m | ojwul-master/geometry/camera_centers.m | 700 | utf_8 | 80044a4d4a6d96ed96ca63e3fefb787d | %CAMERA_CENTERS Compute camera centers from projection matrices
%
% C = camera_extrinsics(P, [cam2world])
%
% Given an array of 3x4 camera projection matrices, this function computes
% their camera centers in world coordinates.
%
%IN:
% P - 3x4xM array of camera projection matrices.
% cam2world - logical value indicating if projection matrices are camera
% to world transforms.
%
%OUT:
% C - 3xM array of camera center vectors matrices.
function C = camera_centers(P, cam2world)
if nargin < 2
cam2world = false;
end
for a = size(P, 3):-1:1
[K, R, C(:,a)] = KR_from_P(P(:,:,a));
if cam2world
C(:,a) = R * -C(:,a);
end
end
end
|
github | ojwoodford/ojwul-master | expmap2quat.m | .m | ojwul-master/geometry/expmap2quat.m | 304 | utf_8 | b77537c91f5fd77950dcf3795b2b11d5 | %EXPMAP2QUAT Convert an exponential mapping rotation to a quaternion
%
% Q = expmap2quat(E)
function Q = expmap2quat(E)
theta = sqrt(sum(E .* E));
M = theta > 1e-8;
m = repmat(0.5, size(theta));
m(M) = sin(theta(M) / 2) ./ theta(M);
Q = [cos(theta / 2); bsxfun(@times, m, reshape(E, 3, []))]; |
github | ojwoodford/ojwul-master | quat2rot.m | .m | ojwul-master/geometry/quat2rot.m | 969 | utf_8 | d9a11247636b15f5ba35afd87b83f742 | %QUAT2ROT Convert a quaternion to a 3x3 rotation matrix
%
% R = quat2rot(Q, [w_last])
%
% This function takes in quaternions of the form [w x y z]', such that Q =
% [1 0 0 0]' corresponds to R = eye(3). If w_last is true, quaternions are
% of the form [x y z w].
%
%IN:
% Q - 4xN array of quaternions in the form [w x y z]'.
% w_last - boolean indicating whether quaternions should be of the form
% [x y z w]'. Default: false.
%
%OUT:
% R - 3x3xN array of corresponding rotation matrices.
function R = quat2rot(Q, w_last)
R = quat_norm(Q);
if nargin > 1 && w_last
R = R([4 1:3],:);
end
R = bsxfun(@times, reshape(R, 4, 1, []), reshape(R, 1, 4, []));
R = [R(1,1,:)+R(2,2,:)-R(3,3,:)-R(4,4,:), 2*(R(2,3,:)-R(4,1,:)), 2*(R(2,4,:)+R(3,1,:));
2*(R(2,3,:)+R(4,1,:)), R(1,1,:)-R(2,2,:)+R(3,3,:)-R(4,4,:), 2*(R(3,4,:)-R(2,1,:));
2*(R(2,4,:)-R(3,1,:)), 2*(R(3,4,:)+R(2,1,:)), R(1,1,:)-R(2,2,:)-R(3,3,:)+R(4,4,:)];
end
|
github | ojwoodford/ojwul-master | F_from_P.m | .m | ojwul-master/geometry/F_from_P.m | 491 | utf_8 | 345ef11fa64de08d9c9894dc39518bf1 | %F_FROM_P Compute a fundamental matrix from two projection matrices
%
% F = F_from_P(P)
%
%IN:
% P - 3x4x2 array of two projection matrices.
%
%OUT:
% F - 3x3 fundamental matrix.
function F = F_from_P(F)
X1 = F([2 3],:,1);
X2 = F([3 1],:,1);
X3 = F([1 2],:,1);
Y1 = F([2 3],:,2);
Y2 = F([3 1],:,2);
Y3 = F([1 2],:,2);
F = [det([X1; Y1]) det([X2; Y1]) det([X3; Y1])
det([X1; Y2]) det([X2; Y2]) det([X3; Y2])
det([X1; Y3]) det([X2; Y3]) det([X3; Y3])];
end |
github | ojwoodford/ojwul-master | compute_homography.m | .m | ojwul-master/geometry/compute_homography.m | 1,054 | utf_8 | 7954818e4f2450fc02a71011d85d3f60 | %COMPUTE_HOMOGRAPHY Compute a best fit homography from correspondences
%
% H = compute_homography(X, Y, [normalize])
%
% Compute a hmography from correspondences using the normalized DLT
% algorithm as described in "Multiple View Geometry in Computer Vision".
%
%IN:
% X - 2xN array of points in image one.
% Y - 2xN array of points in image two.
% normalize - boolean flag indicating whether to normalize the inputs.
%
%OUT:
% H - 3x3 best fit homography from X to Y.
function H = compute_homography(X, Y, normalize)
if nargin < 3
normalize = true;
end
if normalize
% Normalize
[X, Tx] = whiten(X);
[Y, Ty] = whiten(Y);
end
% Create the constraints matrix
V = zeros(3, size(X, 2), 3, 3);
X = homg(X);
V(:,:,1,2) = -X;
V(:,:,2,1) = X;
Z = X .* Y(1,:);
V(:,:,2,3) = -Z;
V(:,:,3,2) = Z;
Z = X .* Y(2,:);
V(:,:,1,3) = Z;
V(:,:,3,1) = -Z;
V = reshape(permute(V, [3 2 1 4]), [], 9);
% Decompose
[~, ~, V] = svd(V, 0);
% Extract homography
H = reshape(V(:,9), 3, 3)';
if normalize
% Denormalize
H = Ty \ H * Tx;
end
end |
github | ojwoodford/ojwul-master | P0toC.m | .m | ojwul-master/geometry/P0toC.m | 332 | utf_8 | 51fe9e195c4a10ae282e822c64ec3bc8 | %P0TOC Convert projection matrices' principal points from 0 to centre based
%
% P = P0toC(P, im)
function P = P0toC(P, im)
if numel(im) == 2 || numel(im) == 3
h = im(1);
w = im(2);
else
[h w c] = size(im);
end
K = [1 0 (1-w)/2; 0 1 (1-h)/2; 0 0 1];
for a = 1:size(P, 3)
P(:,:,a) = K * P(:,:,a);
end |
github | ojwoodford/ojwul-master | calibrated_fivepoint_helper.m | .m | ojwul-master/geometry/private/calibrated_fivepoint_helper.m | 292 | utf_8 | 9f053f0467f5d3d87d32dbe5bdae388b | %CALIBRATED_FIVEPOINT_HELPER Helper for the calibrated five point algorithm
function varargout = calibrated_fivepoint_helper(varargin)
sourceList = {'calibrated_fivepoint_helper.c'}; % Cell array of source files
[varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here
return |
github | ojwoodford/ojwul-master | mesh_sample_random.m | .m | ojwul-master/mesh/mesh_sample_random.m | 1,513 | utf_8 | 32282e6edfe831bf30fee01781c6aba8 | %MESH_SAMPLE_RANDOM Randomly sample points on a mesh
%
% [P, N] = mesh_sample_random(V, E, nPts)
%
% Randomly sample points from a uniform distrubution over the surface area
% of a triangulated 3D mesh.
%
%IN:
% V - 3xM matrix of 3D vertex coordinates.
% E - 3xN matrix of the 3 vertex indices for each of N triangles.
% nPts - integer number of points to sample on the mesh.
%
%OUT:
% P - 3x(nPts) matrix of sampled points.
function [P, N] = mesh_sample_random(V, E, nPts)
% Compute a cdf of area of triangles
[A, A] = mesh_area(V, E);
A = cumsum(A);
% Sample nPts and assign to triangles
A = histc(rand(nPts, 1), [0 A ./ A(end)]);
A(end-1) = A(end-1) + A(end);
A(end) = 0;
P = zeros(3, nPts);
N = zeros(3, nPts);
nPts = 0;
% For each triangle...
for a = find(A)'
% Get triangle vertices
V_ = V(:,E(:,a));
% Compute the canonical frame
C = V_(:,[2 3]) - V_(:,[1 1]);
% Compute the normal
N_ = cross(C(:,1), C(:,2));
N_ = N_ / norm(N_);
% Compute random sample points
S = rand(2, A(a));
M = sum(S, 1) > 1;
S(:,M) = 1 - S(:,M);
% Compute the points
P_ = C(:,1) * S(1,:) + C(:,2) * S(2,:);
% Add the canonical frame origin
P_ = bsxfun(@plus, P_, V_(:,1));
% Add the points to the list
I = nPts+1:nPts+size(P_, 2);
P(:,I) = P_;
N(1,I) = N_(1);
N(2,I) = N_(2);
N(3,I) = N_(3);
nPts = nPts + size(P_, 2);
end
end |
github | ojwoodford/ojwul-master | mesh_area.m | .m | ojwul-master/mesh/mesh_area.m | 547 | utf_8 | 91ad16853d5c0df5b926712246af6ac9 | %MESH_AREA Compute the surface area of a triangulated mesh
%
% [a, A] = mesh_area(V, E)
%
% Compute the surface area of a 3D triangulated mesh
%
%IN:
% V - 3xM matrix of 3D vertex coordinates.
% E - 3xN matrix of the 3 vertex indices for each of N triangles.
%
%OUT:
% a - scalar surface area of entire mesh.
% A - 1xN surface area of each triangle.
function [a, A] = mesh_area(V, E)
A = normd(cross(V(:,E(2,:)) - V(:,E(1,:)), V(:,E(3,:)) - V(:,E(1,:))), 1);
a = sum(A) * 0.5;
if nargout > 1
A = A * 0.5;
end
end |
github | ojwoodford/ojwul-master | mesh_sample_regular.m | .m | ojwul-master/mesh/mesh_sample_regular.m | 1,628 | utf_8 | a38dd507da4c7ba30927e37f32533aa1 | %MESH_SAMPLE_REGULAR Regularly sample points on a mesh
%
% [P, I] = mesh_sample_regular(V, E, interval)
%
% Sample points regularly over the surface of a triangulated 3D mesh.
%
%IN:
% V - 3xM matrix of 3D vertex coordinates.
% E - 3xN matrix of the 3 vertex indices for each of N triangles.
% interval - > 0: scalar distance between sample points,
% < 0: a target number of points.
%
%OUT:
% P - 3xQ matrix of sampled points.
% I - 1xQ source face indices.
function [P, J] = mesh_sample_regular(V, E, interval)
J = zeros(1, max(1e7, -interval));
P = zeros(3, numel(J));
if interval < 0
% Estimate an interval based on target number of points
interval = sqrt(mesh_area(V, E) / -interval);
end
% For each triangle...
I = 0;
for a = 1:size(E, 2)
% Get triangle vertices
V_ = V(:,E(:,a));
% Compute the canonical frame
C = V_(:,[2 3]) - V_(:,[1 1]);
N = sum(C .* C, 1);
N(1) = sqrt(N(1));
N(2) = sqrt(N(2) - ((C(:,1)' * C(:,2)) / N(1)) .^ 2);
% Compute regular sample points
S = mod(V(:,1)' * C, interval);
[S, N] = ndgrid((S(1):interval:N(1))/N(1), (S(2):interval:N(2))/N(2));
S = [S(:)'; N(:)'];
S = S(:,sum(S, 1)<1);
if isempty(S)
continue;
end
% Compute the points
P_ = C(:,1) * S(1,:) + C(:,2) * S(2,:);
% Add the canonical frame origin
P_ = bsxfun(@plus, P_, V_(:,1));
% Add the points to the list
I = I(end)+1:I(end)+size(P_, 2);
P(:,I) = P_;
J(I) = a;
end
P = P(:,1:I(end));
J = J(1:I(end));
end |
github | ojwoodford/ojwul-master | render_camera_trajectories.m | .m | ojwul-master/graphics/render_camera_trajectories.m | 985 | utf_8 | af131b75b50439f42713b2dd131470e4 | %RENDER_CAMERA_TRAJECTORIES Render the path of a set of cameras
%
% h = render_camera_tractories(P1, P2, ...)
% h = render_camera_tractories(P1, I1, ...)
%
% Render a set of camera trajectories
%
%IN:
% P1 - 3x4xM camera projection matrices defining a camera trajectory.
% I1 - 1xK indices of keyframes from trajectory P1.
% P2 - 3x4xN camera projection matrices.
% etc.
%
%OUT:
% h - handles to the line objects created for trajectories.
function h = render_camera_trajectories(varargin)
colours = 'brgkmcy';
tf = ishold;
hold on
a = 1;
c = 0;
while a <= nargin
T = camera_centers(varargin{a});
h(a) = plot3(T(1,:)', T(2,:)', T(3,:)', [colours(mod(c, numel(colours))+1) '-']);
a = a + 1;
if a <= nargin && isvector(varargin{a})
h(a) = plot3(T(1,varargin{a})', T(2,varargin{a})', T(3,varargin{a})', [colours(mod(c, numel(colours))+1) 'o']);
a = a + 1;
end
c = c + 1;
end
if ~tf
hold off
end |
github | ojwoodford/ojwul-master | render_depthmap.m | .m | ojwul-master/graphics/render_depthmap.m | 1,363 | utf_8 | 09395644eca8d75d2ada22a002dd739a | %RENDER_DEPTHMAP Renders a coloured depthmap as a point cloud
%
% h = render_depthmap(P, Z, [im, [num_colors, [marker, [marker_size]]]])
%
% Renders a coloured depthmap in world coordinates.
%
%IN:
% P - 3x4 projection matrix from world to image coordinates.
% Z - MxN depthmap.
% im - MxNx3 RGB image. Default: [] (points coloured blue);
% num_colors - scalar indicating the number of colour quantization levels
% (0 for no quantization). Default: 0.
% marker - character representing the marker to use. Default: '.'.
% marker_size - scalar marker size. Default: 6.
%
%OUT:
% h - handle(s) to created graphics object(s).
function h = render_depthmap(P, Z, im, num_colors, marker, marker_size)
% Set defaults
if nargin < 6
marker_size = 6;
if nargin < 5
marker = '.';
if nargin < 4
num_colors = 256;
if nargin < 3
im = [];
end
end
end
end
if isempty(im)
im = 'b';
else
im = im2double(reshape(permute(im, [3 1 2]), 3, []));
end
% Compute the 3D points in world coordinates
[Y, X] = ndgrid(1:size(Z, 1), 1:size(Z, 2));
X = X .* Z;
Y = Y .* Z;
Z = [X(:)'; Y(:)'; Z(:)'];
Z(4,:) = 1;
Z = [P; 0 0 0 1] \ Z;
Z = Z(1:3,:);
% Render
h = render_points(Z, im, num_colors, marker, marker_size);
|
github | ojwoodford/ojwul-master | render_confusion.m | .m | ojwul-master/graphics/render_confusion.m | 3,126 | utf_8 | 20180acf03e7d192dc9ad37694994387 | %RENDER_CONFUSION Render a confusion matrix
%
% render_confusion(M[, class_names])
%
% Renders a confusion matrix into the current axes.
%
%IN:
% M - NxN confusion matrix.
% class_names - Nx1 cell array of class name strings. Default: {} (not
% shown).
function render_confusion(M, class_names, varargin)
% Default optional arguments
opts.cmap = '-gray';
%opts.cmap = '-hot*'; % Alternative option
opts.totals = false;
opts.normalize_rows = true;
opts.labels = true;
opts.font_size = 0.4; % Proportion of box height
opts.font = 'Times';
opts = vgg_argparse(opts, varargin);
% Create a totals row at the bottom
if opts.totals
M(end+1,:) = sum(M, 1);
end
% Create the background image
if opts.normalize_rows
M_ = bsxfun(@times, M, 1./sum(M, 2));
else
M_ = M;
end
im = sc(kron(M_, ones(8)), opts.cmap, [0 1]);
image(im);
im = sc(im(1:8:end,1:8:end,:), 'rgb2gray');
im = im(:,:,1);
% Write the values
[h, w] = size(M);
color = {'k', 'w'};
hold on
for x = 1:w
for y = 1:h
text(x*8-3.5, y*8-3.5, sprintf('%.2g', M(y,x)), 'FontName', opts.font, 'Units', 'Data', 'FontUnits', 'Normalized', 'FontSize', opts.font_size/h, 'Color', color{1+(im(y,x)<0.5)}, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
end
end
hold off
% Write labels
if opts.labels
set(xlabel('Output class'), 'FontName', opts.font, 'FontUnits', 'Normalized', 'FontSize', 1.2*opts.font_size/h);
set(ylabel('Ground truth class'), 'FontName', opts.font, 'FontUnits', 'Normalized', 'FontSize', 1.2*opts.font_size/h);
end
if opts.totals
text(w*8+2, h*8-3.5, 'TOTAL', 'FontName', opts.font, 'Units', 'Data', 'FontUnits', 'Normalized', 'FontSize', opts.font_size/h, 'Color', 'k', 'HorizontalAlignment', 'left', 'VerticalAlignment', 'middle');
end
% Sort out the axes
axis equal tight
set(gca, 'XTick', [], 'YTick', []);
if nargin < 2 || isempty(class_names)
return
end
% Write the class names
hold on
for x = 1:numel(class_names)
if opts.labels
% Right edge
text(w*8+2, x*8-3.5, class_names{x}, 'FontName', opts.font, 'Rotation', 45, 'Units', 'Data', 'FontUnits', 'Normalized', 'FontSize', opts.font_size/h, 'Color', 'k', 'HorizontalAlignment', 'left', 'VerticalAlignment', 'middle');
% Top edge
text(x*8-3.5, -2, class_names{x}, 'FontName', opts.font, 'Rotation', 45, 'Units', 'Data', 'FontUnits', 'Normalized', 'FontSize', opts.font_size/h, 'Color', 'k', 'HorizontalAlignment', 'left', 'VerticalAlignment', 'middle');
else
% Left edge
text(-2, x*8-3.5, class_names{x}, 'FontName', opts.font, 'Rotation', 45, 'Units', 'Data', 'FontUnits', 'Normalized', 'FontSize', opts.font_size/h, 'Color', 'k', 'HorizontalAlignment', 'right', 'VerticalAlignment', 'middle');
% Bottom edge
text(x*8-3.5, h*8+2, class_names{x}, 'FontName', opts.font, 'Rotation', 45, 'Units', 'Data', 'FontUnits', 'Normalized', 'FontSize', opts.font_size/h, 'Color', 'k', 'HorizontalAlignment', 'right', 'VerticalAlignment', 'middle');
end
end
hold off
|
github | ojwoodford/ojwul-master | fill_triangles.m | .m | ojwul-master/graphics/fill_triangles.m | 2,144 | utf_8 | 9f10608ea5309943fb34710bcf314ee8 | %FILL_TRIANGLES Standard, linear interpolation triangle renderer
%
% fill_triangles(I, P, zbuff)
% J = fill_triangles(I, P, zbuff)
%
% A software implementation of a standard, linear interpolation (i.e.
% incorrect for perspective), z-buffered triangle renderer.
%
% IN:
% I - CxMxN double or single input image array. A single array makes the
% rendering faster, but less accurate. C is the number of channels
% to be interpolated. If there are only two dimensions then C is
% assumed to be 1, and M and N the given dimensions. If zbuff != 0
% then the first channel must be the initialised z-buffer. The
% remaining channels are the initial image colours or texture
% vertices, depending on what is being interpolated.
% P - (2+C)x(3T) matrix, of the same type as I. In the first two
% rows are the x and y image coordinates respectively, and the rest
% of the rows are the channel values of each vertex, in the same
% order as in I. The number of columns must be a multiple of 3,
% each group of 3 columns being the 3 verices of a triangle, with T
% triangles in total. Note that shared vertices have multiple
% entries, allowing for flat shaded faces.
% zbuff - 1, 0 or -1. If 0, z-buffering is not used, and pixels are
% simply painted over each other in the order of triangles
% given. 1 means that smaller z-depths are deemed nearer, and
% -1 means that smaller z-depths are deemed further away.
%
% OUT:
% J - CxMxN output image array, of same type as I. Each channel is the
% same as that from I, but updated according to the list of
% triangles provided, and the z-test for each pixel (if z-buffering
% is used). WARNING: If no output argument is provided, the input
% array I is written into directly; use with care!
function varargout = fill_triangles(varargin)
sourceList = {'fill_triangles.cpp'}; % Cell array of source files
[varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here
return |
github | ojwoodford/ojwul-master | add_datatip.m | .m | ojwul-master/graphics/add_datatip.m | 4,135 | utf_8 | 95e2c55fdb8fb5e37a1e2ee4524c7206 | %ADD_DATATIP Add datatip data to graphical objects
%
% h = add_datatip(h, callback_func, value)
% h = add_datatip(h, value)
% h = add_datatip(h, 'Name', value, ...)
% h = add_datatip(h, callback_func, value)
% h = add_datatip(h, callback_func, 'Name', value, ...)
%
% Example:
% add_datatip(plot(rand(3, 1)), @disp, 'Name', {'Tom', 'Dick', 'Harry'});
%
% Add data to graphical objects, for querying using datatips.
%
%IN:
% h - Scalar graphics object handle, to which to add the data.
% value - MxN numeric array or 1xN cell array of data, the ith column or
% cell of which is to be displayed when the ith datapoint is
% selected.
% 'Name' - String indicating the name of the data value, so that
% name/value pairs can be used.
% callback_func - Handle to callback function called with a structure
% holding the data as input.
%
%OUT:
% h - The input scalar graphics handle, for inline usage (see example).
function h = add_datatip(h, varargin)
assert(isscalar(h), 'Only one handle expected');
% Check for a callback
if nargin > 1 && isa(varargin{1}, 'function_handle')
callback = varargin(1);
varargin = varargin(2:end);
else
callback = {};
end
% Check we have name value pairs
if numel(varargin) > 1
varargin = reshape(varargin, 2, []);
assert(all(cellfun(@ischar, varargin(1,:))), 'Name, value pairs expected');
end
% Set the 'UserData' property of this object
set(h, 'UserData', [varargin(:); callback], 'Tag', 'add_datatip');
% Set the data tip function
set(datacursormode(ancestor(h, 'Figure')), 'UpdateFcn', @datatip_txtfun);
end
function str = datatip_txtfun(obj, event)
% Get the position of the object that was clicked
X = event.Position';
% Check if the string is cached
persistent last_pos
persistent last_str
if isequal(last_pos, X)
str = last_str;
return;
end
% Check if this has an add_datatip structure
id = [];
if strcmp(event.Target.Tag, 'add_datatip')
% Find the point that was clicked
hTarg = event.Target;
if numel(X) == 3
Y = [hTarg.XData(:)'; hTarg.YData(:)'; hTarg.ZData(:)'];
else
Y = [hTarg.XData(:)'; hTarg.YData(:)'];
end
[md, id] = sqdist2closest(X, Y);
Z = Y(:,id);
else
% Query all the datatip objects
objs = findobj(ancestor(event.Target, 'Axes'), 'Tag', 'add_datatip');
Z = NaN(size(X, 1), 1);
md = Inf;
for a = 1:numel(objs)
if numel(X) == 3
Y = [objs(a).XData(:)'; objs(a).YData(:)'; objs(a).ZData(:)'];
else
Y = [objs(a).XData(:)'; objs(a).YData(:)'];
end
[d, id] = sqdist2closest(X, Y);
if d < md
md = d;
Z = Y(:,id);
hTarg = objs(a);
end
if md == 0
break;
end
end
end
if isempty(id)
str = '';
return;
end
% Check if the string is cached
if isequal(last_pos, Z)
str = last_str;
obj.Cursor.Position = Z';
return;
end
% Generate the structure to display
str = struct('X', Z(1), 'Y', Z(2));
if numel(X) == 3
str.Z = Z(3);
end
data = hTarg.UserData;
if ~isempty(data)
try
N = numel(data) - isa(data{end}, 'function_handle');
if N > 1
for a = 1:2:N
if iscell(data{a+1})
str.(data{a}) = data{a+1}{id};
else
str.(data{a}) = data{a+1}(:,id)';
end
end
elseif N == 1
if iscell(data{1})
str.Data = data{1}{id};
else
str.Data = data{1}(:,id)';
end
end
if N ~= numel(data)
% Call the callback
data{end}(str, id);
end
catch me
fprintf('Error in datatip callback: %s\n', getReport(me, 'basic'));
fprintf('ID: %d\n', id);
fprintf('Str:\n%s\n', str);
end
end
% Stringify the structure
str = regexprep(evalc('disp(str)'), '\n *', '\n');
% Store to avoid repetition of computation when we move the cursor
last_pos = Z;
last_str = str;
% Set the data cursor position
obj.Cursor.Position = Z';
end
|
github | ojwoodford/ojwul-master | fill_triangles_demo.m | .m | ojwul-master/graphics/fill_triangles_demo.m | 7,810 | utf_8 | 46326f2d8edc46a4fa9a86a36d339bcf | %FILL_TRIANGLES_DEMO Demonstrates fill_triangles
%
% fill_triangles_demo([resolution, [use_single]])
%
% Demonstrates usage of the fill_triangles function by rendering a
% cube with flat shaded, gouraud shaded and texture mapped sides.
%
% Rotate the cube using arrow keys. Quit by pressing q.
%
% IN:
% resolution - resolution of scene to render, in pixels. Default: 200.
% use_single - non-zero if single precision is to be used, otherwise
% (default) double precision is used. Single precision
% approximately doubles the speed of the triangle
% renderer.
function fill_triangles_demo(resolution, use_single)
clf reset;
%set(gcf,'DoubleBuffer','on');
map = jet(256);
map = map(end:-1:1,:);
colormap(map);
map = [];
if nargin < 1
resolution = 400;
end
% Cube vertices
CP = [-1 -1 -1 ; 1 -1 -1 ; 1 1 -1 ; -1 1 -1; ...
-1 -1 1 ; 1 -1 1 ; 1 1 1 ; -1 1 1]';
% Cube vertex colours for gouraud shaded faces
CC = colorcube(8)' * 255;
% Cube triangles (must be clockwise outwards)
T = [1 3 2 ; 1 4 3 ; ...
1 2 5 ; 2 6 5 ; ...
2 3 6 ; 3 7 6 ; ...
3 4 7 ; 4 8 7 ; ...
1 8 4 ; 1 5 8; ...
5 6 7 ; 5 7 8]';
% Initialise parameters
I = zeros(4, resolution, resolution);
I(1,:,:) = 1/6;
Q = zeros(6, 36);
half_res = resolution / 2;
perspective_correct = 1;
% Initialise the gouraud shaded faces
P = CC(:,T);
% Initialise the flat shaded faces
P(:,7:12) = repmat([255 0 0]', [1 6]); % Red
P(:,19:24) = repmat([0 0 255]', [1 6]); % Blue
% Initialise the texture mapped faces
% Face 1
TM1 = double(imread('cameraman.tif'));
TM1 = TM1(:,:,[1 1 1]);
P(1,1:6) = 350; % Index of the texture
TV = [1 1; size(TM1, 2) 1; size(TM1, 2) size(TM1, 1); 1 size(TM1, 1)]';
P(2:3,1:6) = TV(:,T(1:6)); % Coordinates on the texture
% Face 1
TM2 = double(imread('peppers.png'));
P(1,31:36) = 450; % Index of the texture
TV = [1 1 ; size(TM2, 2) 1 ; size(TM2, 2) size(TM2, 1); 1 size(TM2, 1)]';
P(2:3,31:36) = TV(:,T(31:36)-4); % Coordinates on the texture
P = repmat(P, [2 1]);
P = reshape(P, [6 3 12]);
one = 1;
if nargin > 1 && use_single
I = single(I);
P = single(P);
TM1 = single(TM1);
TM2 = single(TM2);
one = single(1);
end
time = zeros(1, 6);
f = 0;
%R = eye(3);
R = [cos(pi/3) -sin(pi/3) 0 ; sin(pi/3) cos(pi/3) 0; 0 0 1] * ...
[cos(-pi/6) 0 -sin(-pi/6) ; 0 1 0 ; sin(-pi/6) 0 cos(-pi/6)] * ...
[1 0 0 ; 0 cos(pi/6) -sin(pi/6) ; 0 sin(pi/6) cos(pi/6)];
incr = pi / 60; % 3 degrees
Rx = [1 0 0 ; 0 cos(incr) -sin(incr) ; 0 sin(incr) cos(incr)];
Ry = [cos(incr) 0 -sin(incr) ; 0 1 0 ; sin(incr) 0 cos(incr)];
lims = [5 - sqrt(3) 6];
lims(2) = 255 / (lims(2) - lims(1));
% Set up the button callback for interactive control
fig_h = gcf;
figure(fig_h);
pos = get(0, 'ScreenSize');
pos = round(pos/2);
pos = [pos(3:4) resolution*2+300 resolution+300];
pos(1:2) = pos(1:2) - round(pos(3:4)/2);
set(fig_h, 'KeyPressFcn', @keypress_callback, 'Units', 'pixels', 'Position', pos);
% Create the plot layout
subplot(121);
H1 = imshow(zeros(resolution, resolution, 3, 'uint8'));
set(gca, 'xlimmode', 'manual', 'ylimmode', 'manual',...
'zlimmode', 'manual', 'climmode', 'manual',...
'alimmode', 'manual');
title({'Cube with 2 flat shaded', '2 gouraud shaded & 2', 'texture mapped sides'});
xlabel({'Use arrow keys', 'to rotate the cube.', 'Press q to quit.', 'Press p to toggle', 'perspective correct', 'interpolation'});
subplot(122);
H2 = imshow(zeros(resolution, resolution, 3, 'uint8'));
set(gca, 'xlimmode', 'manual', 'ylimmode', 'manual',...
'zlimmode', 'manual', 'climmode', 'manual',...
'alimmode', 'manual');
title('Calculated depth map of cube.')
while true
t = tic;
X = R * CP;
X(3,:) = X(3,:) + 5;
X(1,:) = resolution * X(1,:) ./ X(3,:) + half_res;
X(2,:) = resolution * X(2,:) ./ X(3,:) + half_res;
time(6) = time(6) + toc(t);
t = tic;
% Cull back facing triangles
Q = reshape(X(1:2,T), [2 3 12]);
Q(:,1,:) = Q(:,2,:) - Q(:,1,:);
Q(:,2,:) = Q(:,3,:) - Q(:,2,:);
Q = squeeze((Q(1,1,:) .* Q(2,2,:)) - (Q(2,1,:) .* Q(1,2,:)));
L = find(Q < 0);
Q = reshape(P(:,:,L), [6 3*length(L)]);
L = reshape(T(:,L), [1 3*length(L)]);
Q(1:3,:) = X(:,L);
time(5) = time(5) + toc(t);
t = tic;
if perspective_correct
% Ensure perspective correct interpolation by dividing through by depth
V = 1 ./ Q(3,:);
Q(3,:) = V;
for a = 4:size(Q, 1)
Q(a,:) = Q(a,:) .* V;
end
time(2) = time(2) + toc(t);
t = tic;
% Call the triangle renderer
J = fill_triangles(I, Q, -1);
time(1) = time(1) + toc(t);
t = tic;
% Divide through by interpolated inverse depth, for perspective correct
% interpolation
V = one ./ J(1,:);
J(1,:) = V;
for a = 2:size(J, 1)
J(a,:) = J(a,:) .* V;
end
time(2) = time(2) + toc(t);
else
% Call the triangle renderer
J = fill_triangles(I, Q, 0);
time(1) = time(1) + toc(t);
end
t = tic;
% Render the texture mapped surfaces
L = J(2,:,:) > 400;
if any(L(:))
J(2:4,L) = squeeze(ojw_interp2(TM2, J(3,L), J(4,L), 'l', one))';
else
L = J(2,:,:) > 300 & J(2,:,:) <= 400;
if any(L(:))
J(2:4,L) = squeeze(ojw_interp2(TM1, J(3,L), J(4,L), 'l', one))';
end
end
time(3) = time(3) + toc(t);
t = tic;
% Display the output
J = shiftdim(J, 1);
Z = J(:,:,1);
RGB = uint8(J(:,:,2:end));
set(H1, 'CData', RGB);
Z = uint8((Z - lims(1)) * lims(2)) + 1;
set(H2, 'Cdata', Z);
drawnow;
time(4) = time(4) + toc(t);
f = f + 1;
% Get the key press
while true
set(fig_h, 'userData', '')
waitfor(fig_h, 'userData')
button = lower(get(fig_h, 'userData'));
switch button
case 31
R = Rx * R;
break
case 30
R = Rx' * R;
break
case 29
R = Ry * R;
break
case 28
R = Ry' * R;
break
case 'p'
perspective_correct = xor(1, perspective_correct);
if perspective_correct
I(1,:,:) = 1/6;
else
I(1,:,:) = 6;
end
break
case {'q', '', 13}
close(gcf);
total = sum(time);
fprintf('Rendering speed of %0.0f frames per second, with processing time allocated as follows:\n', f / total);
total = total - time(4);
time = time * 100;
fprintf(' Projection - %0.1f%%\n', time(6) / total);
fprintf(' Back face culling - %0.1f%%\n', time(5) / total);
fprintf(' Triangle rendering - %0.1f%%\n', time(1) / total);
fprintf(' Perspective correction - %0.1f%%\n', time(2) / total);
fprintf(' Texture mapping - %0.1f%%\n', time(3) / total);
fprintf('And drawing to the screen accounting for %0.1f times all these time put together!\n', time(4) / (100 * total));
return
end
end
end
return
function keypress_callback(source_handle, event_data)
set(source_handle, 'userData', event_data.Character);
return
|
github | ojwoodford/ojwul-master | render_lines_points.m | .m | ojwul-master/graphics/render_lines_points.m | 3,632 | utf_8 | 888f491af2803912c9d584f8c7b700e8 | %RENDER_LINES_POINTS Renders a set of coloured points and/or lines
%
% h = render_line_points(X, [C, [options]])
%
% Renders a set of coloured 2D or 3D points or lines, either as a set of
% lineseries objects (quantized colours, fast rendering) or as a patch
% object (exact colours, slow rendering), depending on the number of
% colours requested.
%
%IN:
% X - MxNxP set of P M-D points (if N==1) or lines with N-1 segments,
% where M is 2 or 3.
% C - 3xP set of RGB colours for each point/line, or a single colorspec.
% Default: 'b'.
% options - string value pairs:
% NumColors - scalar indicating the number of colour quantization
% levels (0 for no quantization). Default: 0.
% Marker - character representing the marker to use. Default: '.' for
% points, 'none' for lines.
% MarkerSize - scalar marker size. Default: 6.
% LineStyle - line style string. Default: '-'.
% LineWidth - scalar line width. Default: 0.5.
% Alpha - scalar line transparency. Default: 1.
%
%OUT:
% h - handle(s) to created graphics object(s).
function h = render_lines_points(X, C, varargin)
% Set defaults
if size(X, 2) == 1
opts.Marker = '.';
else
opts.Marker = 'none';
end
opts.MarkerSize = 6;
opts.LineStyle = '-';
opts.LineWidth = 0.5;
opts.NumColors = 0;
opts.Alpha = 1;
if nargin < 2
C = 'b';
else
% Parse input options
opts = vgg_argparse(opts, varargin);
end
% Create the options parameters
alpha = opts.Alpha;
if alpha < 1
num_colors = 0;
else
num_colors = opts.NumColors;
end
if size(X, 2) == 1
opts.LineStyle = 'none';
end
opts = {'Marker', opts.Marker, 'MarkerSize', opts.MarkerSize, 'LineWidth', opts.LineWidth, 'LineStyle', opts.LineStyle};
X(:,end+1,:) = NaN;
col = @(X) X(:);
if numel(C) <= 3 && alpha == 1
% One colour, so just plot as a line series
if size(X, 1) < 3
h = plot(col(X(1,:,:)), col(X(2,:,:)), 'b-', 'Color', C(:)', opts{:});
else
h = plot3(col(X(1,:,:)), col(X(2,:,:)), col(X(3,:,:)), 'b-', 'Color', C(:)', opts{:});
end
return;
end
% Colour per point
C = C';
if num_colors < 1
% Plot as a patch object: points are exact colours, but the plot is
% slow to render and manipulate
if isscalar(C)
C = repmat(rem(floor((strfind('kbgcrmyw', C) - 1) * [0.25 0.5 1]), 2), [size(X, 3) 1]);
end
C = repmat(reshape(C, 1, [], 3), [size(X, 2) 1 1]);
if size(X, 1) < 3
h = patch(shiftdim(X(1,:,:), 1), shiftdim(X(2,:,:), 1), C, 'FaceColor', 'none', 'EdgeColor', 'flat', 'MarkerEdgeColor', 'flat', opts{:}, 'EdgeAlpha', alpha);
else
h = patch(shiftdim(X(1,:,:), 1), shiftdim(X(2,:,:), 1), shiftdim(X(3,:,:), 1), C, 'FaceColor', 'none', 'EdgeColor', 'flat', 'MarkerEdgeColor', 'flat', opts{:}, 'EdgeAlpha', alpha);
end
else
% Plot as a set of single colour line objects: colours are quantized
% but the plot is faster to update
[I, C] = rgb2ind(reshape(C, 1, [], 3), num_colors, 'nodither');
num_colors = size(C, 1);
I = accumarray(I(:)+1, (1:size(X, 3))', [num_colors 1], @(I) {I});
tf = ishold();
hold on
for a = num_colors:-1:1
if ~isempty(I{a})
if size(X, 1) < 3
h(a) = plot(col(X(1,:,I{a})), col(X(2,:,I{a})), 'b-', 'Color', C(a,:), opts{:});
else
h(a) = plot3(col(X(1,:,I{a})), col(X(2,:,I{a})), col(X(3,:,I{a})), 'b-', 'Color', C(a,:), opts{:});
end
end
end
if ~tf
hold off
end
end
|
github | ojwoodford/ojwul-master | render_mesh.m | .m | ojwul-master/graphics/render_mesh.m | 1,556 | utf_8 | 2d87007efdf740c405e50b496a7fdd19 | %RENDER_MESH Renders a triangulated mesh
%
% h = render_mesh(vertices, faces)
%
% Renders a triangulated mesh defined by a set of vertices and faces
% containing vertex indices.
%
%IN:
% vertices - Mx3 matrix of triangle vertices (rows).
% faces - Nx3 matrix of vertex indices for each triangle (columns).
% options - string value pairs:
% NumColors - scalar indicating the number of colour quantization
% levels (0 for no quantization). Default: 0.
% Marker - character representing the marker to use. Default: '.' for
% points, 'none' for lines.
% MarkerSize - scalar marker size. Default: 6.
% LineStyle - line style string. Default: '-'.
% LineWidth - scalar line width. Default: 0.5.
% Alpha - scalar line transparency. Default: 1.
%
%OUT:
% h - handle(s) to created graphics object(s).
function h = render_mesh(vertices, faces, varargin)
% Set defaults
opts.Marker = 'none';
opts.MarkerSize = 6;
opts.LineStyle = 'none';
opts.FaceColor = 'flat';
opts.LineWidth = 0.5;
% Parse input options
opts = vgg_argparse(opts, varargin);
% Create the options parameters
opts = {'Marker', opts.Marker, 'MarkerSize', opts.MarkerSize, 'LineWidth', opts.LineWidth, 'LineStyle', opts.LineStyle, 'FaceColor', opts.FaceColor};
h = patch('Vertices', vertices, 'Faces', faces, 'FaceVertexCData', repmat([0.7 0.7 0.7], size(vertices, 1), 1), 'EdgeColor', 'flat', 'MarkerEdgeColor', 'flat', 'BackFaceLighting', 'reverselit', 'FaceLighting', 'phong', opts{:});
end
|
github | ojwoodford/ojwul-master | select3Dpoints.m | .m | ojwul-master/graphics/select3Dpoints.m | 5,519 | utf_8 | 7c40d771619a082531f50c68e2bc788b | %SELECT3DPOINTS Select a subset of 3D points
%
% ind = select3Dpoints(X)
%
% Interactively select a subset of 3D points, by rotating, translating and
% zooming in on the points, then holding down shift and either clicking on
% or drawing round points. Radio buttons allow the user to toggle whether
% selected points are added to or removed from the subset. Close the figure
% to return the selected point indices.
%
%IN:
% X - 3xN set of points to select from.
%
%OUT:
% ind - Indices of the selected set of points.
function ind = select3Dpoints(X)
% Initialize variables
global select3DpointsState
select3DpointsState.X = X';
select3DpointsState.M = false(size(X, 2), 1);
select3DpointsState.lastM = select3DpointsState.M;
select3DpointsState.mode = 0;
select3DpointsState.points = zeros(3, 0);
% Create the figure
select3DpointsState.fig = figure('Color', 'w', 'Name', 'Select 3D points by holding down shift and clicking or drawing round points');
% Create the radio buttons
bg = uibuttongroup('Visible', 'off',...
'Units', 'pixels', ...
'OuterPosition', [0 0 150 70],...
'SelectionChangedFcn', @bselection);
uicontrol(bg,'Style',...
'radiobutton',...
'String','current OR selection',...
'UserData', 0, ...
'Position', [0 50 150 16], ...
'HandleVisibility','off');
uicontrol(bg,'Style',...
'radiobutton',...
'String','current AND selection',...
'UserData', 1, ...
'Position', [0 34 150 16], ...
'HandleVisibility','off');
uicontrol(bg,'Style',...
'radiobutton',...
'String','current OR NOT selection',...
'UserData', 2, ...
'Position', [0 18 150 16], ...
'HandleVisibility','off');
uicontrol(bg,'Style',...
'radiobutton',...
'String','current AND NOT selection',...
'UserData', 3, ...
'Position', [0 2 150 16], ...
'HandleVisibility','off');
set(bg, 'Visible', 'on');
uicontrol('Style', 'pushbutton', 'String', 'Undo', 'Position', [2 72 70 15], 'HandleVisibility','off', 'Callback', @undo);
% Create the plot
select3DpointsState.ax2 = axes('Position', [0 0 1 1]);
select3DpointsState.green = plot(NaN, NaN, 'g-');
xlim([0 1]);
ylim([0 1]);
axis off
select3DpointsState.ax3 = axes('Position', [0 0 1 1]);
select3DpointsState.blue = plot3(select3DpointsState.X(:,1), select3DpointsState.X(:,2), select3DpointsState.X(:,3), 'b.', 'MarkerSize', 1);
hold on;
select3DpointsState.red = plot3(NaN, NaN, NaN, 'r.', 'MarkerSize', 1);
axis equal off
camtarget(median(select3DpointsState.X, 1)');
% Set the callback, pass pointCloud to the callback function
set(select3DpointsState.fig, 'WindowButtonUpFcn', @up, 'WindowButtonDownFcn', @down);
% Require shift to be pressed to select point. Otherwise, control the
% figure.
fcw([0 2 2], '-block');
% Output the selected point indices
ind = find(select3DpointsState.M);
end
function bselection(source, event)
global select3DpointsState
select3DpointsState.mode = event.NewValue.UserData;
end
function render()
global select3DpointsState
X = select3DpointsState.X(~select3DpointsState.M,:);
set(select3DpointsState.blue, 'XData', X(:,1), 'YData', X(:,2), 'ZData', X(:,3));
X = select3DpointsState.X(select3DpointsState.M,:);
set(select3DpointsState.red, 'XData', X(:,1), 'YData', X(:,2), 'ZData', X(:,3));
drawnow();
end
function undo(varargin)
global select3DpointsState
select3DpointsState.M = select3DpointsState.lastM;
render();
end
function up(varargin)
global select3DpointsState
set(select3DpointsState.fig, 'WindowButtonMotionFcn', []);
X = select3DpointsState.points';
% Convert the points to 2d
[x, y] = ds2fig(select3DpointsState.ax3, [select3DpointsState.X(:,1); X(:,1)], [select3DpointsState.X(:,2); X(:,2)], [select3DpointsState.X(:,3); X(:,3)]);
% Scale according to dimensions
set(select3DpointsState.ax3, 'Units', 'pixels');
pos = get(select3DpointsState.ax3, 'Position');
x = pos(3) * x;
y = pos(4) * y;
n = size(X, 1);
select3DpointsState.lastM = select3DpointsState.M;
if n < 3
% Select the closest point
ind = dsearchn([x(1:end-n) y(1:end-n)], [x(end) y(end)]);
M = false(size(select3DpointsState.M));
M(ind) = true;
else
% Select points in the polyshape
M = inpolygon(x(1:end-n), y(1:end-n), x(end-n+1:end), y(end-n+1:end));
end
% Update the point set
if select3DpointsState.mode > 1
M = ~M;
end
if mod(select3DpointsState.mode, 2) == 0
select3DpointsState.M = select3DpointsState.M | M(:);
else
select3DpointsState.M = select3DpointsState.M & M(:);
end
% Update the rendering
set(select3DpointsState.green, 'XData', NaN, 'YData', NaN);
render();
end
function down(varargin)
global select3DpointsState
X = get(select3DpointsState.ax3, 'CurrentPoint');
select3DpointsState.points = X(1,:)';
X = get(select3DpointsState.ax2, 'CurrentPoint');
select3DpointsState.selection = X(1,1:2);
set(select3DpointsState.fig, 'WindowButtonMotionFcn', @move);
end
function move(varargin)
global select3DpointsState
X = get(select3DpointsState.ax3, 'CurrentPoint');
select3DpointsState.points = [select3DpointsState.points X(1,:)'];
X = get(select3DpointsState.ax2, 'CurrentPoint');
select3DpointsState.selection = [select3DpointsState.selection; X(1,1:2)];
set(select3DpointsState.green, 'XData', select3DpointsState.selection(:,1), 'YData', select3DpointsState.selection(:,2));
drawnow();
end |
github | ojwoodford/ojwul-master | render_camera.m | .m | ojwul-master/graphics/render_camera.m | 3,128 | utf_8 | 89969def23d69d6d318684255716a22c | %RENDER_CAMERA Render 3D camera models, given projection matrices
%
% h = render_camera(P, [scale, [colour, [cam2world]])
%
% Render a set of cameras.
%
%IN:
% P - 3x4xN camera projection matrices.
% scale - scalar value indicating the size of the camera. Default: 1.
% colour - 1x3 colour value for the camera. Default: [0.5 0.5 0.5].
% cam2world - logical indicating whether P are given in camera to world
% coordinate frame forms. Default: false.
%
%OUT:
% h - handle to the patch object created.
function h = render_camera(P, scale, colour, cam2world)
% Create a cone
% Vertices
nSegments = 50;
verts = ones(nSegments+1, 3);
x = linspace(0, pi*2, nSegments+1)';
verts(:,1) = 0.5 * cos(x);
verts(:,2) = 0.5 * sin(x);
verts(end,:) = 0; % Camera center / cone point
verts(:,3) = verts(:,3) * 1.6; % Elongate
% Faces
faces = zeros(nSegments, 3);
faces(:,1) = 1:nSegments;
faces(:,2) = faces(:,1) + 1;
faces(:,3) = nSegments+1;
faces(end,3) = 1;
% Create a cube
% Faces
faces(end+1:end+12,:) = [2 1 3; 2 3 4; 6 5 7; 6 7 8; 5 1 2; 5 2 6; 7 3 4; 7 4 8; 3 1 5; 3 5 7; 4 2 6; 4 6 8] + size(verts, 1);
% Vertices
verts(end+1:end+8,:) = (dec2bin(0:7) - '0') - 0.5;
% Add on a vertical pointer
verts(end+1,:) = [0 -1 0];
% Scale
if nargin > 1
verts = verts * scale;
end
if nargin > 0 && size(P, 1) == 3 && size(P, 2) == 4
% Replicate face indices for each camera
c = numel(P) / 12;
nv = size(verts, 1);
faces = reshape(bsxfun(@plus, reshape(faces, [], 1, 3), 0:nv:nv*(c-1)), [], 3);
% Transform the vertices coordinates into each camera frame
V = [verts ones(nv, 1)];
verts = zeros(nv, c, 3);
for a = 1:c
% Extract extrinsics
[K, R, t] = KR_from_P(P(:,:,a));
% Multiply vertices by camera projection matrix
if nargin < 4 || ~cam2world
P_ = [R; t'];
else
P_ = [R'; (R*-t)'];
end
verts(:,a,:) = reshape(V * P_, [], 1, 3);
end
verts = reshape(verts, [], 3);
end
% Compute face normals
N = verts';
N = reshape(N(:,faces'), 3, 3, []);
V1 = squeeze(N(:,2,:) - N(:,1,:));
V2 = squeeze(N(:,3,:) - N(:,1,:));
N = V1([2 3 1],:) .* V2([3 1 2],:) - V2([2 3 1],:) .* V1([3 1 2],:);
clear V1 V2
N = bsxfun(@times, N, 1 ./ sqrt(sum(N .* N, 1)));
% Make vertex normals
normals = zeros(size(verts));
normals(faces(:,1),:) = N';
% Render
if nargin < 3
colour = [0.5 0.5 0.5];
end
if ischar(colour)
colour = str2color(colour);
end
if size(colour, 1) == size(P, 3) && size(colour, 2) == 3
colour = repmat(shiftdim(colour, -1), [nSegments+12 1 1]);
colour = reshape(colour, [], 3);
end
h = patch('Vertices', verts, 'Faces', faces, 'VertexNormals', normals, 'FaceVertexCData', colour, 'FaceColor', 'flat', 'EdgeColor', 'none', 'BackFaceLighting', 'reverselit', 'FaceLighting', 'flat');
% hold on
% verts = reshape(verts, nSegments+10,[], 3);
% plot3([verts(nSegments+1,:,1); verts(end,:,1)], [verts(nSegments+1,:,2); verts(end,:,2)], [verts(nSegments+1,:,3); verts(end,:,3)], 'r-'); |
github | ojwoodford/ojwul-master | render_circles.m | .m | ojwul-master/graphics/render_circles.m | 1,041 | utf_8 | 2099e4c0cbaec1fc2da328f579010de1 | %RENDER_CIRCLES Draw a set of circles
%
% h = render_circles(X, nsides, col)
%
%IN:
% X - 3xN array of circles defined by [center_x; center_y; radius].
% nsides - Scalar indicating the number of sides to use for each polygon.
% Default: 64.
% col - Colour to use for the circles. Default: 'b'.
function h = render_circles(X, nsides, color)
% Default parameters
if nargin < 2
nsides = 64;
end
nsides = max(round(nsides), 3); % Make sure it is an integer >= 3
if nargin < 3
color = [0 0 1];
end
% Compute the coordinates
X = reshape(X, 3, []);
radii = X(3,:);
poly_sides = linspace(0, 2 * pi, nsides)';
Y = bsxfun(@plus, bsxfun(@times, sin(poly_sides), radii), X(2,:));
X = bsxfun(@plus, bsxfun(@times, cos(poly_sides), radii), X(1,:));
% Expand the color
if size(color, 1) ~= size(X, 2)
color = repmat(color, [size(X, 2) 1]);
end
% Render using patch (so can have different coloured circles)
h = patch(X, Y, repmat(shiftdim(color, -1), [size(X, 1) 1 1]), 'FaceColor', 'none', 'EdgeColor', 'flat');
end
|
github | ojwoodford/ojwul-master | ds2fig.m | .m | ojwul-master/graphics/ds2fig.m | 10,583 | utf_8 | 90ecb3172bcb3caf027cd86737d78a7b | function [XFIG, YFIG, DEEP] = ds2fig(varargin)
%DS2FIG Transform data space coordinates to normalized figure coordinates.
% [XFIG,YFIG,DEEP] = DS2FIG(X,Y,Z) transforms corresponding elements of
% data stored in data space coordinates X,Y,Z to normalized figure
% coordinates (XFIG, YFIG). if the point is closer to you, the value
% in DEEP will be bigger. The DEEP value of points which on the view
% plane containing 'CameraTarget' is 0.
% X,Y,Z must be the same size.
% XFIG,YFIG,DEEP will be the same size as X,Y,Z.
% [XFIG,YFIG,DEEP] = DS2FIG(X,Y) use Z always be 0.
% [XFIG,YFIG,DEEP] = DS2FIG(axes_handle,...) use axes_handle instead of gca
%
% Example:
% % create a surface and draw
% [x, y, z] = peaks;
% z = z + 10;
% surf(x, y, z);
% shading interp;
% axis tight;
% set(gca, 'Projection', 'perspective', 'CameraUpVector', [2, 1, 0], ...
% 'XDir', 'reverse', 'ZScale', 'log');
% % find maximum and minimum
% [zMax, maxIdx] = max(z(:));
% [zMin, minIdx] = min(z(:));
% idx = [minIdx, maxIdx];
% % use this function to translate maximum and minimum point
% [xFig, yFig] = ds2fig(x(idx), y(idx), z(idx));
% % annotate it
% annotation('textarrow', [.9, xFig(1)], [.2, yFig(1)], 'String', 'MIN');
% annotation('textarrow', [.2, xFig(2)], [.8, yFig(2)], 'String', 'MAX');
%
% Conditions it will work:
% setting valid properties of axes including: 'Camera*', 'Projection',
% 'View', 'DataAspectRatio*', 'PlotBoxAspectRatio*', 'XLim', 'YLim',
% 'ZLim', 'XDir', 'YDir', 'ZDir', 'XScale', 'YScale', 'ZScale'.
% modify axes appearance by using 'axis *' and 'view(*)'.
% using 'Zoom In', 'Zoom Out', 'Pan', 'Rotate 3D' in Figure Tool.
% Conditions it will not work:
% while using log scale axes, if you set the low boundary of 'XLim' less
% than or equal to 0, then matlab will auto calculate a valid one
% and use it, but this program can't get the actually low boundary.
%
% NOTE:
% This program written through observing the behavior of how matlab render
% axes content into figure. It may not work properly in some cases that
% I omitted. It work fine in MATLAB 8.0, and should work properly at
% other version, since the render algorithm may change rarely.
% Copyright (c) 2013, MinLong Kwong <[email protected]>
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
% Revision history:
% 10/10/2013 Original code release.
% check if axes handle is available
if length(varargin{1}) == 1 && ishandle(varargin{1}) ...
&& strcmp(get(varargin{1}, 'type'), 'axes')
hAxes = varargin{1};
varargin = varargin(2:end);
else
hAxes = gca;
end
% get data space coordinates from arguments
if length(varargin) == 1
error('too fiew arguments');
elseif length(varargin) >= 4
error('too many arguments');
else
X = varargin{1};
Y = varargin{2};
if length(varargin) == 3
Z = varargin{3};
else
Z = zeros(size(X));
end
end
% check if all arguments are same size
dataSize = size(X);
if ~(all(size(Y) == dataSize) && all(size(Z) == dataSize))
error('X,Y,Z should be the same size');
end
% build data space coordinates
X = X(:);
Y = Y(:);
Z = Z(:);
dataCoord = [X, Y, Z, ones(size(X))]';
dataCoord = AdjustLogScaleData(hAxes, dataCoord);
% transform and build figure coordinates
matrixTransform = AxesTransformToFigure(hAxes);
figureCoord = matrixTransform * dataCoord;
% perspective division
XFIG = reshape(figureCoord(1, :) ./ figureCoord(4, :), dataSize);
YFIG = reshape(figureCoord(2, :) ./ figureCoord(4, :), dataSize);
DEEP = reshape(figureCoord(3, :) ./ figureCoord(4, :), dataSize);
end
function coordLiner = AdjustLogScaleData(hAxes, coordLogOrLiner)
% adjust axes data for log scale
coordLiner = coordLogOrLiner;
% obtain data
isLogScale = strcmp(get(hAxes, {'XScale', 'YScale', 'ZScale'}), 'log');
lim = get(gca, {'XLim', 'YLim', 'ZLim'});
% adjust
for i = 1:3
if isLogScale(i)
if lim{i}(1) <= 0
error(['low boundary of ''', 'W'+i, 'Lim'' should not less', ...
' than or equal to 0 in log scale axes, consider set ''', ...
'W'+i, 'LimMode'' to ''auto''.']);
end
rate = (log(coordLogOrLiner(i, :)) - log(lim{i}(1))) ...
/ (log(lim{i}(2)) - log(lim{i}(1)));
coordLiner(i, :) = rate * (lim{i}(2) - lim{i}(1)) + lim{i}(1);
end
end
end
function matrixTransform = AxesTransformToFigure(hAxes)
% get transform matrix which transform axes coordinate to figure coordinate
matrixTransform = [];
%%%% obtain data needed
% camera
viewAngle = get(hAxes, 'CameraViewAngle');
viewTarget = get(hAxes, 'CameraTarget');
viewPosition = get(hAxes, 'CameraPosition');
viewUp = get(hAxes, 'CameraUpVector');
% axes direction
axesDirection = strcmp(get(hAxes, {'XDir', 'YDir', 'ZDir'}), 'normal');
% data scale
dataZLim = get(hAxes, 'ZLim');
dataRatio = get(hAxes, 'DataAspectRatio');
if any(dataRatio == 0), return, end
plotBoxRatio = get(hAxes, 'PlotBoxAspectRatio');
if any(plotBoxRatio == 0), return, end
% is perspective
isPerspective = strcmp(get(hAxes, 'Projection'), 'perspective');
% axes position
axesUnitsOriginal = get(hAxes, 'Units');
set(hAxes, 'Units', 'normalized');
positionNormal = get(hAxes, 'Position');
set(hAxes, 'Units', 'pixels');
positionPixel = get(hAxes, 'Position');
set(hAxes, 'Units', axesUnitsOriginal);
% stretch
stretchMode = strcmp(get(hAxes, {'CameraViewAngleMode', ...
'DataAspectRatioMode', 'PlotBoxAspectRatioMode'}), 'auto');
stretchToFill = all(stretchMode);
stretchToFit = ~stretchToFill && stretchMode(1);
stretchNone = ~stretchToFill && ~stretchToFit;
%%%% model view matrix
% move data space center to viewTarget point
matrixTranslate = eye(4);
matrixTranslate(1:3, 4) = -viewTarget;
% rescale data
% note: matlab will rescale data space by dividing DataAspectRatio
% and normalize z direction to 1 to makeup the 'PlotBox'
scaleFactor = dataRatio / dataRatio(3) * (dataZLim(2) - dataZLim(1));
scaleDirection = axesDirection * 2 - 1;
matrixRescale = diag([scaleDirection ./ scaleFactor, 1]);
% rotate the 'PlotBox'
vecticesZUp = matrixRescale * ...
[matrixTranslate * [viewPosition, 1]', [viewUp, 1]'];
zVector = vecticesZUp(1:3, 1);
upVector = vecticesZUp(1:3, 2);
viewDistance = sqrt(dot(zVector, zVector));
zDirection = zVector / viewDistance;
yVector = upVector - zDirection * dot(zDirection, upVector);
yDirection = yVector / sqrt(dot(yVector, yVector));
matrixRotate = blkdiag( ...
[cross(yDirection, zDirection), yDirection, zDirection]', 1);
%%%% projection matrix
% note: matlab will project the rotated 'PlotBox' to an area of
% [-0.5, 0.5; -0.5, 0.5]
matrixProjection = eye(4);
matrixProjection(4, 3) = -isPerspective / viewDistance;
projectionArea = 2 * tan(viewAngle * pi / 360) * viewDistance;
matrixProjection = diag([ones(1, 3), projectionArea]) * matrixProjection;
%%%% stretch matrix
% stretch the projective 'PlotBox' into the position retangle of the axes
% note: stretch will first detect data region
if stretchToFill || stretchToFit
plotBox = [0 0 0; 0 0 1; 0 1 0; 0 1 1; 1 0 0; 1 0 1; 1 1 0; 1 1 1]' - .5;
plotBox = diag(plotBoxRatio / plotBoxRatio(3)) * plotBox;
edgeVertices = matrixProjection * matrixRotate * [plotBox; ones(1, 8)];
edgeVertices(1, :) = edgeVertices(1, :) ./ edgeVertices(4, :);
edgeVertices(2, :) = edgeVertices(2, :) ./ edgeVertices(4, :);
edgeVertices = edgeVertices(1:2, :)';
% note: the low boundary and the high boundary of data region may be
% difference in perspective projection, so the figure should move
% to center, but here no need to do so, because matlab ignore it
dataRegion = max(edgeVertices) - min(edgeVertices);
% note: matlab have a strange addition stretch in stretch to fit mode.
% one side of the data region will hit the position rectangle,
% and matlab will assume data region of that side to be 1 keeping
% aspect ratio.
if stretchToFit
strangeFactor = dataRegion ./ positionPixel(3:4);
if strangeFactor(1) > strangeFactor(2)
dataRegion = dataRegion / dataRegion(1);
else
dataRegion = dataRegion / dataRegion(2);
end
end
else
% note: if no stretch, it will use projection area as data region
dataRegion = [1, 1];
end
% note: stretch than apply a stretchFactor to the data, such that it fit
% in the axes position retangle
if stretchToFit || stretchNone
stretchFactor = dataRegion ./ positionPixel(3:4);
stretchFactor = stretchFactor / max(stretchFactor);
else
stretchFactor = [1, 1];
end
matrixStretch = diag([stretchFactor ./ dataRegion, 1, 1]);
%%%% view port matrix
matrixViewPort = diag([positionNormal(3:4), 1, 1]);
matrixViewPort(1:2, 4) = positionNormal(1:2) + positionNormal(3:4) / 2;
%%%% return transformation matrix
matrixTransform = matrixViewPort * matrixStretch * matrixProjection * ...
matrixRotate * matrixRescale * matrixTranslate;
end
|
github | ojwoodford/ojwul-master | clickA3DPoint.m | .m | ojwul-master/graphics/clickA3DPoint.m | 4,502 | utf_8 | 4fa9bd3ce294023f769a750970db6966 | function index = clickA3DPoint(pointCloud, faces)
%CLICKA3DPOINT
% H = CLICKA3DPOINT(POINTCLOUD) shows a 3D point cloud and lets the user
% select points by clicking on them. The selected point is highlighted
% and its index in the point cloud will is printed on the screen.
% POINTCLOUD should be a 3*N matrix, represending N 3D points.
% Handle to the figure is returned.
%
% other functions required:
% CALLBACKCLICK3DPOINT mouse click callback function
% ROWNORM returns norms of each row of a matrix
%
% To test this function ...
% pointCloud = rand(3,100)*100;
% h = clickA3DPoint(pointCloud);
%
% now rotate or move the point cloud and try it again.
% (on the figure View menu, turn the Camera Toolbar on, ...)
%
% To turn off the callback ...
% set(h, 'WindowButtonDownFcn','');
%
% by Babak Taati
% http://rcvlab.ece.queensu.ca/~taatib
% Robotics and Computer Vision Laboratory (RCVLab)
% Queen's University
% May 4, 2005
% revised Oct 30, 2007
% revised May 19, 2009
% Copyright (c) 2009, Babak Taati
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
if nargin < 1
error('Requires one input arguments.')
end
if size(pointCloud, 1)~=3
error('Input point cloud must be a 3*N matrix.');
end
% show the point cloud
h = figure();
plot3(pointCloud(1,:), pointCloud(2,:), pointCloud(3,:), 'b.');
cameratoolbar('Show'); % show the camera toolbar
hold on; % so we can highlight clicked points without clearing the figure
if nargin > 1
patch('Vertices', pointCloud', 'Faces', faces', 'FaceVertexCData', repmat([0.7 0.7 0.7], size(pointCloud, 2), 1), 'EdgeColor', 'k', 'LineStyle', '-', 'FaceColor', 'flat');
end
global pointCloudIndex
pointCloudIndex = [];
% set the callback, pass pointCloud to the callback function
set(h, 'WindowButtonDownFcn', {@callbackClickA3DPoint, pointCloud}, 'UserData', []);
% Require shift to be pressed to select point. Otherwise, control the
% figure.
fcw([0 2 2]);
while isempty(pointCloudIndex)
pause(0.1);
end
index = pointCloudIndex;
close(h);
end
function callbackClickA3DPoint(src, eventData, pointCloud)
% CALLBACKCLICK3DPOINT mouse click callback function for CLICKA3DPOINT
%
% The transformation between the viewing frame and the point cloud frame
% is calculated using the camera viewing direction and the 'up' vector.
% Then, the point cloud is transformed into the viewing frame. Finally,
% the z coordinate in this frame is ignored and the x and y coordinates
% of all the points are compared with the mouse click location and the
% closest point is selected.
%
% Babak Taati - May 4, 2005
% revised Oct 31, 2007
% revised Jun 3, 2008
% revised May 19, 2009
ax = gca();
point = get(ax, 'CurrentPoint'); % mouse click position
% Get 2d coordinates in the current view
[x, y] = ds2fig(ax, [pointCloud(1,:) point(1,1)], [pointCloud(2,:) point(1,2)], [pointCloud(3,:) point(1,3)]);
% Scale according to dimensions
set(ax, 'Units', 'pixels');
pos = get(ax, 'Position');
x = pos(3) * x;
y = pos(4) * y;
% find the nearest neighbour to the clicked point
global pointCloudIndex
pointCloudIndex = dsearchn([x(1:end-1)' y(1:end-1)'], [x(end) y(end)]);
end
|
github | ojwoodford/ojwul-master | fcw.m | .m | ojwul-master/graphics/fcw.m | 17,033 | utf_8 | b7936c59c3b9991036fc89d92790ce62 | %FCW Figure Control Widget: Manipulate figures with key and button presses
%
% fcw([fig], [buttons], [modifiers])
% fcw(..., '-link')
% fcw(..., '-block')
%
% Allows the user to rotate, pan and zoom an axes using key presses and
% mouse gestures. Additionally, press q to quit the widget, r to reset the
% axes and escape to close the figure. This function is non-blocking, but
% fixes axes aspect ratios.
%
% This function plays nicely with other figure callbacks, if called after
% other callbacks have been created. Only figure interactions not used by
% fcw() are passed to previously existing callbacks.
%
% IN:
% fig - Handle of the figure to be manipulated (default: gcf).
% buttons - 4x1 cell array indicating the function to associate with
% each mouse button (left to right) and the scroll action.
% Functions can be any of:
% 'rot' - Rotate about x and y axes of viewer's coordinate
% frame
% 'rotz' - Rotate about z axis of viewer's coordinate frame
% 'zoom' - Zoom (change canera view angle)
% 'zoomz' - Move along z axis of viewer's coordinate frame
% 'pan' - Pan
% '' - Don't use that button
% Default: {'rot', 'zoomz', 'pan', 'zoomz'}).
% modifiers - 1x3 numeric vector indicating which of the modifier keys
% (shift, ctrl, alt respectively) should be pressed (1), not
% pressed (0), or can be either (other value), for fcw to
% react to button/key presses. E.g. [0 1 NaN] indicates that
% fcw should react to button/key presses if and only if shift
% is not pressed and ctrl is pressed; alt is ignored.
% Default: [NaN NaN NaN] (i.e. react to all button presses).
% '-link' - Specify each axis in the figure to maintain the same pose
% '-block' - The function doesn't return control to the caller until the
% widget is quit (by pressing 'q') or the function is closed.
% This can be useful if collecting data in another callback,
% to be returned by the calling function.
% (C) Copyright Oliver Woodford 2006-2015
% The initial code came from Torsten Vogel's view3d function, which was in
% turn inspired by rotate3d from The MathWorks, Inc.
% Thanks to Sam Johnson for some bug fixes and good feature requests.
function fcw(varargin)
% Parse input arguments
assert(nargin < 4, 'Too many input arguments');
buttons = {'rot', 'zoomz', 'pan', 'zoom'};
fig = gcf();
link = false;
block = false;
modifiers = NaN(1, 3);
for a = 1:nargin
v = varargin{a};
if ischar(v) && numel(v) > 1 && v(1) == '-'
switch v
case '-link'
link = true;
case '-block'
block = true;
otherwise
error('Unknown option: %s.', v);
end
elseif isscalar(v) && ishandle(v)
fig = ancestor(v, 'figure');
assert(~isempty(fig), 'Unrecognized handle');
elseif iscell(v) && numel(v) == 4 && all(cellfun(@ischar, v))
buttons = v;
elseif isnumeric(v) && numel(v) == 3
modifiers = v(:)';
else
error('Input not recognized');
end
end
% Flush any pending draws
drawnow();
% Clear any visualization modes we might be in
pan(fig, 'off');
zoom(fig, 'off');
rotate3d(fig, 'off');
% Find all the 3D axes
hAx = findobj(fig, 'Type', 'axes', '-depth', 1);
M = false(numel(hAx), 1);
for a = 1:numel(hAx)
zl = zlim(hAx(a));
M(a) = zl(2) ~= 1 || (zl(1) ~= -1 && zl(1) ~= 0);
end
hAx = hAx(M);
% For each set of axes
data.view = containers.Map('KeyType', 'double', 'ValueType', 'any');
for h = hAx'
% Set everything to manual
set(h, 'CameraViewAngleMode', 'manual', 'CameraTargetMode', 'manual', 'CameraPositionMode', 'manual');
% Store the camera viewpoint
data.view(double(h)) = camview(h);
end
% Store the data
% Link if necessary
if link
data.link = linkprop(hAx, {'CameraPosition', 'CameraTarget', 'CameraViewAngle', 'CameraUpVector', 'Projection'});
end
% Get existing callbacks, and quit a previous instance of fcw if running
[prev_mousedown, prev_mouseup, prev_keypress, prev_scroll] = quit_widget(fig);
% Create the data storage object
hData = uipanel(fig, 'Tag', 'fcw_data', 'Visible', 'off', 'Position', [0 0 0 0]);
set(hData, 'UserData', data);
% Create the modifier checking function
M = modifiers == 0 | modifiers == 1;
if ~any(M)
modifiers = @(varargin) false;
else
modifiers = modifiers(M);
mods = {'shift', 'control', 'alt'};
mods = mods(M);
modifiers = @(varargin) ~isequal(ismember(mods, get(fig, 'CurrentModifier')), modifiers);
end
% Initialize the callbacks
set(fig, 'WindowButtonDownFcn', [{@fcw_mousedown, {str2func(['fcw_' buttons{1}]), str2func(['fcw_' buttons{2}]), str2func(['fcw_' buttons{3}])}, modifiers} prev_mousedown], ...
'WindowButtonUpFcn', [{@fcw_mouseup, modifiers} prev_mouseup], ...
'KeyPressFcn', [{@fcw_keypress, modifiers} prev_keypress], ...
'WindowScrollWheelFcn', [{@fcw_scroll, str2func(['fcw_' buttons{4}]), modifiers} prev_scroll], ...
'BusyAction', 'cancel');
if block
% Block until the figure is closed or the widget is quit
while 1
try
pause(0.01);
if isempty(get(hData, 'UserData'))
break;
end
catch
% Figure was closed
break;
end
end
end
end
function tf = isinvalid(cax, map)
tf = isempty(cax) || ~map.isKey(double(cax)) || ~isequal(size(map(double(cax))), [4 4]);
end
function fcw_keypress(src, eventData, modifiers, varargin)
fig = ancestor(src, 'figure');
cax = get(fig, 'CurrentAxes');
hData = findobj(fig, 'Tag', 'fcw_data', '-depth', 1);
if isinvalid(cax, hData.UserData.view) || modifiers() % Check the required modifiers were pressed, else do nothing
% Call the other keypress callbacks
if ~isempty(varargin)
varargin{1}(src, eventData, varargin{2:end});
end
return;
end
step = 1;
if ismember('shift', eventData.Modifier)
step = 2;
end
if ismember('control', eventData.Modifier)
step = step * 4;
end
% Which keys do what
switch eventData.Key
case {'v', 'leftarrow'}
fcw_pan([], [step 0], cax);
case {'g', 'rightarrow'}
fcw_pan([], [-step 0], cax);
case {'b', 'downarrow'}
fcw_pan([], [0 step], cax);
case {'h', 'uparrow'}
fcw_pan([], [0 -step], cax);
case {'n', 'x'}
fcw_rotz([], [0 step], cax);
case {'j', 's'}
fcw_rotz([], [0 -step], cax);
case {'m', 'z'}
fcw_zoom([], [0 -step], cax);
case {'k', 'a'}
fcw_zoom([], [0 step], cax);
case 'l'
fcw_rot([], [0 step], cax);
case 'p'
fcw_rot([], [0 -step], cax);
case 'w'
fcw_rot([], [-step 0], cax);
case 'q'
fcw_rot([], [step 0], cax);
case 'r'
% Reset all the axes
for h = findobj(fig, 'Type', 'axes', '-depth', 1)'
if hData.UserData.view.isKey(double(h))
camview(h, hData.UserData.view(double(h)));
end
end
case 'q'
% Quit the widget
quit_widget(fig);
case 'escape'
close(fig);
otherwise
% Call the other keypress callbacks
if ~isempty(varargin)
varargin{1}(src, eventData, varargin{2:end});
end
end
end
function fcw_mousedown(src, eventData, funcs, modifiers, varargin)
% Check an axes is selected
fig = ancestor(src, 'figure');
cax = get(fig, 'CurrentAxes');
hData = findobj(fig, 'Tag', 'fcw_data', '-depth', 1);
if isinvalid(cax, hData.UserData.view) || modifiers() % Check the required modifiers were pressed, else do nothing
% Call the other mousedown callbacks
% This allows other interactions to be used easily alongside fcw()
if ~isempty(varargin)
varargin{1}(src, eventData, varargin{2:end});
end
return;
end
% Get the button pressed
switch get(fig, 'SelectionType')
case 'extend' % Middle button
method = funcs{2};
case 'alt' % Right hand button
method = funcs{3};
case 'open' % Double click
camview(cax, hData.UserData.view(double(cax)));
return;
otherwise
method = funcs{1};
end
% Set the cursor
switch func2str(method)
case {'fcw_zoom', 'fcw_zoomz'}
shape=[ 2 2 2 2 2 2 2 2 2 2 NaN NaN NaN NaN NaN NaN ;
2 1 1 1 1 1 1 1 1 2 NaN NaN NaN NaN NaN NaN ;
2 1 2 2 2 2 2 2 2 2 NaN NaN NaN NaN NaN NaN ;
2 1 2 1 1 1 1 1 1 2 NaN NaN NaN NaN NaN NaN ;
2 1 2 1 1 1 1 1 2 NaN NaN NaN NaN NaN NaN NaN ;
2 1 2 1 1 1 1 2 NaN NaN NaN NaN NaN NaN NaN NaN ;
2 1 2 1 1 1 1 1 2 NaN NaN NaN 2 2 2 2 ;
2 1 2 1 1 2 1 1 1 2 NaN 2 1 2 1 2 ;
2 1 2 1 2 NaN 2 1 1 1 2 1 1 2 1 2 ;
2 2 2 2 NaN NaN NaN 2 1 1 1 1 1 2 1 2 ;
NaN NaN NaN NaN NaN NaN NaN NaN 2 1 1 1 1 2 1 2 ;
NaN NaN NaN NaN NaN NaN NaN 2 1 1 1 1 1 2 1 2 ;
NaN NaN NaN NaN NaN NaN 2 1 1 1 1 1 1 2 1 2 ;
NaN NaN NaN NaN NaN NaN 2 2 2 2 2 2 2 2 1 2 ;
NaN NaN NaN NaN NaN NaN 2 1 1 1 1 1 1 1 1 2 ;
NaN NaN NaN NaN NaN NaN 2 2 2 2 2 2 2 2 2 2 ];
case 'fcw_pan'
shape=[ NaN NaN NaN NaN NaN NaN NaN 2 2 NaN NaN NaN NaN NaN NaN NaN ;
NaN NaN NaN NaN NaN NaN 2 1 1 2 NaN NaN NaN NaN NaN NaN ;
NaN NaN NaN NaN NaN 2 1 1 1 1 2 NaN NaN NaN NaN NaN ;
NaN NaN NaN NaN NaN 1 1 1 1 1 1 NaN NaN NaN NaN NaN ;
NaN NaN NaN NaN NaN NaN 2 1 1 2 NaN NaN NaN NaN NaN NaN ;
NaN NaN 2 1 NaN NaN 2 1 1 2 NaN NaN 1 2 NaN NaN ;
NaN 2 1 1 2 2 2 1 1 2 2 2 1 1 2 NaN ;
2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 ;
2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 ;
NaN 2 1 1 2 2 2 1 1 2 2 2 1 1 2 NaN ;
NaN NaN 2 1 NaN NaN 2 1 1 2 NaN NaN 1 2 NaN NaN ;
NaN NaN NaN NaN NaN NaN 2 1 1 2 NaN NaN NaN NaN NaN NaN ;
NaN NaN NaN NaN NaN 1 1 1 1 1 1 NaN NaN NaN NaN NaN ;
NaN NaN NaN NaN NaN 2 1 1 1 1 2 NaN NaN NaN NaN NaN ;
NaN NaN NaN NaN NaN NaN 2 1 1 2 NaN NaN NaN NaN NaN NaN ;
NaN NaN NaN NaN NaN NaN NaN 2 2 NaN NaN NaN NaN NaN NaN NaN ];
case {'fcw_rotz', 'fcw_rot'}
% Rotate
shape=[ NaN NaN NaN 2 2 2 2 2 NaN 2 2 NaN NaN NaN NaN NaN ;
NaN NaN NaN 1 1 1 1 1 2 1 1 2 NaN NaN NaN NaN ;
NaN NaN NaN 2 1 1 1 1 2 1 1 1 2 NaN NaN NaN ;
NaN NaN 2 1 1 1 1 1 2 2 1 1 1 2 NaN NaN ;
NaN 2 1 1 1 2 1 1 2 NaN NaN 2 1 1 2 NaN ;
NaN 2 1 1 2 NaN 2 1 2 NaN NaN 2 1 1 2 NaN ;
2 1 1 2 NaN NaN NaN NaN NaN NaN NaN NaN 2 1 1 2 ;
2 1 1 2 NaN NaN NaN NaN NaN NaN NaN NaN 2 1 1 2 ;
2 1 1 2 NaN NaN NaN NaN NaN NaN NaN NaN 2 1 1 2 ;
2 1 1 2 NaN NaN NaN NaN NaN NaN NaN NaN 2 1 1 2 ;
NaN 2 1 1 2 NaN NaN 2 1 2 NaN 2 1 1 2 NaN ;
NaN 2 1 1 2 NaN NaN 2 1 1 2 1 1 1 2 NaN ;
NaN NaN 2 1 1 1 2 2 1 1 1 1 1 2 NaN NaN ;
NaN NaN NaN 2 1 1 1 2 1 1 1 1 2 NaN NaN NaN ;
NaN NaN NaN NaN 2 1 1 2 1 1 1 1 1 NaN NaN NaN ;
NaN NaN NaN NaN NaN 2 2 NaN 2 2 2 2 2 NaN NaN NaN ];
otherwise
return
end
% Record where the pointer is
global FCW_POS
FCW_POS = get(0, 'PointerLocation');
% Set the cursor and callback
set(ancestor(src, 'figure'), 'Pointer', 'custom', 'pointershapecdata', shape, 'WindowButtonMotionFcn', {method, cax});
end
function fcw_mouseup(src, eventData, modifiers, varargin)
if modifiers()
% Call the other mouseup callbacks
% This allows other interactions to be used easily alongside fcw()
if ~isempty(varargin)
varargin{1}(src, eventData, varargin{2:end});
end
return;
end
% Clear the cursor and callback
set(ancestor(src, 'figure'), 'WindowButtonMotionFcn', [], 'Pointer', 'arrow');
end
function fcw_scroll(src, eventData, func, modifiers, varargin)
% Get the axes handle
fig = ancestor(src, 'figure');
cax = get(fig, 'CurrentAxes');
hData = findobj(fig, 'Tag', 'fcw_data', '-depth', 1);
if isinvalid(cax, hData.UserData.view) || modifiers() % Check the required modifiers were pressed, else do nothing
% Call the other mousedown callbacks
% This allows other interactions to be used easily alongside fcw()
if ~isempty(varargin)
varargin{1}(src, eventData, varargin{2:end});
end
return;
end
% Call the scroll function
func([], [0 -10*eventData.VerticalScrollCount], cax);
end
function d = check_vals(s, d)
% Check the inputs to the manipulation methods are valid
global FCW_POS
if ~isempty(s)
% Return the mouse pointers displacement
new_pt = get(0, 'PointerLocation');
d = FCW_POS - new_pt;
FCW_POS = new_pt;
end
end
% Figure manipulation functions
function fcw_rot(s, d, cax)
d = check_vals(s, d);
try
% Rotate XY
camorbit(cax, d(1), d(2), 'camera', [0 0 1]);
catch me
% Error, so release mouse down
fcw_mouseup(cax);
fprintf('%s\n', getReport(me, 'extended'));
end
end
function fcw_rotz(s, d, cax)
d = check_vals(s, d);
try
% Rotate Z
camroll(cax, d(2));
catch me
% Error, so release mouse down
fcw_mouseup(cax);
fprintf('%s\n', getReport(me, 'extended'));
end
end
function fcw_zoom(s, d, cax)
d = check_vals(s, d);
% Zoom
d = (1 - 0.01 * sign(d(2))) ^ abs(d(2));
try
camzoom(cax, d);
catch me
% Error, so release mouse down
fcw_mouseup(cax);
fprintf('%s\n', getReport(me, 'extended'));
end
end
function fcw_zoomz(s, d, cax)
d = check_vals(s, d);
% Zoom by moving towards the camera
d = (1 - 0.01 * sign(d(2))) ^ abs(d(2)) - 1;
try
camdolly(cax, 0, 0, d, 'fixtarget', 'camera');
catch me
% Error, so release mouse down
fcw_mouseup(cax);
fprintf('%s\n', getReport(me, 'extended'));
end
end
function fcw_pan(s, d, cax)
D = check_vals(s, d);
try
% Pan
camdolly(cax, D(1), D(2), 0, 'movetarget', 'pixels');
catch me
% Error, so release mouse down
fcw_mouseup(cax);
fprintf('%s\n', getReport(me, 'extended'));
end
end
function A = to_cell(A)
if ~iscell(A)
if isempty(A)
A = {};
else
A = {A};
end
end
A = reshape(A, 1, []);
end
function [prev_mousedown, prev_mouseup, prev_keypress, prev_scroll] = quit_widget(fig)
% Get the current callbacks
prev_mousedown = to_cell(get(fig, 'WindowButtonDownFcn'));
prev_mouseup = to_cell(get(fig, 'WindowButtonUpFcn'));
prev_keypress = to_cell(get(fig, 'KeyPressFcn'));
prev_scroll = to_cell(get(fig, 'WindowScrollWheelFcn'));
% Remove the fcw callbacks (assuming they're first)
if ~isempty(prev_mousedown) && strcmp('fcw_mousedown', func2str(prev_mousedown{1}))
prev_mousedown = prev_mousedown(4:end);
end
if ~isempty(prev_mouseup) && strcmp('fcw_mouseup', func2str(prev_mouseup{1}))
prev_mouseup = prev_mouseup(2:end);
end
if ~isempty(prev_keypress) && strcmp('fcw_keypress', func2str(prev_keypress{1}))
prev_keypress = prev_keypress(2:end);
end
if ~isempty(prev_scroll) && strcmp('fcw_scroll', func2str(prev_scroll{1}))
prev_scroll = prev_scroll(4:end);
end
% Reset the callbacks
set(fig, 'WindowButtonDownFcn', prev_mousedown, 'WindowButtonUpFcn', prev_mouseup, 'KeyPressFcn', prev_keypress, 'WindowScrollWheelFcn', prev_scroll, 'WindowButtonMotionFcn', [], 'Pointer', 'arrow');
% Flag the end
hData = findobj(fig, 'Tag', 'fcw_data', '-depth', 1);
set(hData, 'UserData', []);
delete(hData);
end
|
github | ojwoodford/ojwul-master | vol3d.m | .m | ojwul-master/graphics/vol3d.m | 7,613 | utf_8 | 2fba9993538c21f421f72e55f2d73836 | %H = VOL3D Volume render 3-D data.
% VOL3D uses the orthogonal plane 2-D texture mapping technique for
% volume rending 3-D data in OpenGL. Use the 'texture' option to fine
% tune the texture mapping technique. This function is best used with
% fast OpenGL hardware.
%
% vol3d Provide a demo of functionality.
%
% H = vol3d('CData',data) Create volume render object from input
% 3-D data. Use interp3 on data to increase volume
% rendering resolution. Returns a struct
% encapsulating the pseudo-volume rendering object.
% XxYxZ array represents scaled colormap indices.
% XxYxZx3 array represents truecolor RGB values for
% each voxel (along the 4th dimension).
%
% vol3d(...,'Alpha',alpha) XxYxZ array of alpha values for each voxel, in
% range [0,1]. Default: data (interpreted as
% scaled alphamap indices).
%
% vol3d(...,'Parent',axH) Specify parent axes. Default: gca.
%
% vol3d(...,'XData',x) 1x2 x-axis bounds. Default: [0 size(data, 2)].
% vol3d(...,'YData',y) 1x2 y-axis bounds. Default: [0 size(data, 1)].
% vol3d(...,'ZData',z) 1x2 z-axis bounds. Default: [0 size(data, 3)].
%
% vol3d(...,'texture','2D') Only render texture planes parallel to nearest
% orthogonal viewing plane. Requires doing
% vol3d(h) to refresh if the view is rotated
% (i.e. using cameratoolbar).
%
% vol3d(...,'texture','3D') Default. Render x,y,z texture planes
% simultaneously. This avoids the need to
% refresh the view but requires faster OpenGL
% hardware peformance.
%
% vol3d(H) Refresh view. Updates rendering of texture planes
% to reduce visual aliasing when using the 'texture'='2D'
% option.
%
% NOTES
% Use vol3dtool (from the original vol3d FEX submission) for editing the
% colormap and alphamap. Adjusting these maps will allow you to explore
% your 3-D volume data at various intensity levels. See documentation on
% alphamap and colormap for more information.
%
% Use interp3 on input date to increase/decrease resolution of data
%
% Examples:
%
% % Visualizing fluid flow
% v = flow(50);
% h = vol3d('cdata',v,'texture','2D');
% view(3);
% % Update view since 'texture' = '2D'
% vol3d(h);
% alphamap('rampdown'), alphamap('decrease'), alphamap('decrease')
%
% % Visualizing MRI data
% load mri.mat
% D = squeeze(D);
% h = vol3d('cdata',D,'texture','3D');
% view(3);
% axis tight; daspect([1 1 .4])
% alphamap('rampup');
% alphamap(.06 .* alphamap);
%
% See also alphamap, colormap, opengl, isosurface
% Copyright Joe Conti, 2004
% Improvements by Oliver Woodford, 2008-2011, with permission of the
% copyright holder.
function model = vol3d(varargin)
if nargin == 0
demo_vol3d;
return
end
if isstruct(varargin{1})
model = varargin{1};
if length(varargin) > 1
varargin = {varargin{2:end}};
end
else
model = localGetDefaultModel();
end
if length(varargin)>1
for n = 1:2:length(varargin)
switch(lower(varargin{n}))
case 'cdata'
model.cdata = varargin{n+1};
case 'parent'
model.parent = varargin{n+1};
case 'texture'
model.texture = varargin{n+1};
case 'alpha'
model.alpha = varargin{n+1};
case 'xdata'
model.xdata = varargin{n+1}([1 end]);
case 'ydata'
model.ydata = varargin{n+1}([1 end]);
case 'zdata'
model.zdata = varargin{n+1}([1 end]);
end
end
end
if isempty(model.parent)
model.parent = gca();
end
[model] = local_draw(model);
%------------------------------------------%
function [model] = localGetDefaultModel()
model.cdata = [];
model.alpha = [];
model.xdata = [];
model.ydata = [];
model.zdata = [];
model.parent = [];
model.handles = [];
model.texture = '3D';
tag = tempname;
model.tag = ['vol3d_' tag(end-11:end)];
%------------------------------------------%
function [model,ax] = local_draw(model)
cdata = model.cdata;
siz = size(cdata);
% Define [x,y,z]data
if isempty(model.xdata)
model.xdata = [0 siz(2)];
end
if isempty(model.ydata)
model.ydata = [0 siz(1)];
end
if isempty(model.zdata)
model.zdata = [0 siz(3)];
end
try
delete(model.handles);
catch
end
ax = model.parent;
cam_dir = camtarget(ax) - campos(ax);
[m,ind] = max(abs(cam_dir));
opts = {'Parent',ax,'cdatamapping',[],'alphadatamapping',[],'facecolor','texturemap','edgealpha',0,'facealpha','texturemap','tag',model.tag};
if ndims(cdata) > 3
opts{4} = 'direct';
else
cdata = double(cdata);
opts{4} = 'scaled';
end
if isempty(model.alpha)
alpha = cdata;
if ndims(model.cdata) > 3
alpha = sqrt(sum(double(alpha).^2, 4));
alpha = alpha - min(alpha(:));
alpha = 1 - alpha / max(alpha(:));
end
opts{6} = 'scaled';
else
alpha = model.alpha;
if ~isequal(siz(1:3), size(alpha))
error('Incorrect size of alphamatte');
end
opts{6} = 'none';
end
h = findobj(ax,'type','surface','tag',model.tag);
for n = 1:length(h)
try
delete(h(n));
catch
end
end
is3DTexture = strcmpi(model.texture,'3D');
handle_ind = 1;
% Create z-slice
if(ind==3 || is3DTexture )
x = [model.xdata(1), model.xdata(2); model.xdata(1), model.xdata(2)];
y = [model.ydata(1), model.ydata(1); model.ydata(2), model.ydata(2)];
z = [model.zdata(1), model.zdata(1); model.zdata(1), model.zdata(1)];
diff = model.zdata(2)-model.zdata(1);
delta = diff/size(cdata,3);
for n = 1:size(cdata,3)
cslice = squeeze(cdata(:,:,n,:));
aslice = double(squeeze(alpha(:,:,n)));
h(handle_ind) = surface(x,y,z,cslice,'alphadata',aslice,opts{:});
z = z + delta;
handle_ind = handle_ind + 1;
end
end
% Create x-slice
if (ind==1 || is3DTexture )
x = [model.xdata(1), model.xdata(1); model.xdata(1), model.xdata(1)];
y = [model.ydata(1), model.ydata(1); model.ydata(2), model.ydata(2)];
z = [model.zdata(1), model.zdata(2); model.zdata(1), model.zdata(2)];
diff = model.xdata(2)-model.xdata(1);
delta = diff/size(cdata,2);
for n = 1:size(cdata,2)
cslice = squeeze(cdata(:,n,:,:));
aslice = double(squeeze(alpha(:,n,:)));
h(handle_ind) = surface(x,y,z,cslice,'alphadata',aslice,opts{:});
x = x + delta;
handle_ind = handle_ind + 1;
end
end
% Create y-slice
if (ind==2 || is3DTexture)
x = [model.xdata(1), model.xdata(1); model.xdata(2), model.xdata(2)];
y = [model.ydata(1), model.ydata(1); model.ydata(1), model.ydata(1)];
z = [model.zdata(1), model.zdata(2); model.zdata(1), model.zdata(2)];
diff = model.ydata(2)-model.ydata(1);
delta = diff/size(cdata,1);
for n = 1:size(cdata,1)
cslice = squeeze(cdata(n,:,:,:));
aslice = double(squeeze(alpha(n,:,:)));
h(handle_ind) = surface(x,y,z,cslice,'alphadata',aslice,opts{:});
y = y + delta;
handle_ind = handle_ind + 1;
end
end
model.handles = h;
function demo_vol3d
figure;
load mri.mat
vol3d('cdata', squeeze(D), 'xdata', [0 1], 'ydata', [0 1], 'zdata', [0 0.7]);
colormap(bone(256));
alphamap([0 linspace(0.1, 0, 255)]);
axis equal off
set(gcf, 'color', 'w');
view(3); |
github | ojwoodford/ojwul-master | imstereo.m | .m | ojwul-master/graphics/imstereo.m | 3,367 | utf_8 | 747884c9db67d08af6d700f8d12eaa44 | function imstereo(A, B)
if ischar(A)
A = imread(A);
end
if nargin > 1
if ischar(B)
B = imread(B);
end
state.sbs = [A B];
else
state.sbs = A;
w = floor(size(A, 2) / 2);
B = A(:,w+1:end,:);
A = A(:,1:w,:);
end
state.state = 1;
state.offset = 0;
% Create the first image
state.hIm = imdisp(state.sbs);
state.hAx = get(state.hIm, 'Parent');
% Move it to the external monitor
hFig = gcf;
mp = get(0, 'MonitorPositions');
if size(mp, 1) > 1
p = get(hFig, 'Position');
p(1:2) = mp(2, 1:2);
set(hFig, 'Position', p);
end
drawnow;
% Maximize it
set(hFig, 'MenuBar', 'none', 'Color', 'k');
maximize(hFig);
drawnow;
% Prepare resized images
state.maxoffset = 200;
dims = get(hFig, 'Position');
dims = dims(3:4);
w = max(size(A, 2), size(B, 2));
h = size(state.sbs, 1);
f = min((dims - [state.maxoffset 0])./[w h]);
h = floor(h * f);
state.resized = cell(2, 1);
state.resize{1} = imresize(A, [h floor(w*f)], 'bicubic');
state.resize{2} = imresize(B, [h floor(size(B, 2)*f)], 'bicubic');
state.pos = [0 0 max(size(state.resize{1}, 2), size(state.resize{2}, 2))+state.maxoffset size(state.resize{1}, 1)];
state.pos(1:2) = ceil((dims - state.pos(3:4))/2) - 1;
% Set the callback for image navigation, and save the image data in the figure
set(hFig, 'KeyPressFcn', @keypress_callback, 'UserData', state, 'Interruptible', 'off', 'BusyAction', 'cancel');
return
% Keypress callback
% The function which does all the display stuff
function keypress_callback(fig, event_data)
% Check what key was pressed and update the image index as necessary
newstate = 0;
off = 0;
flip = 0;
switch event_data.Character
case 27 % Escape
close(fig);
return
case 28 % Left
off = -1;
case 29 % Right
off = 1;
case 30 % Up
off = -10;
case 31 % Down
off = 10;
case 's'
newstate = 1;
case 'h'
newstate = 2;
case 'v'
newstate = 3;
case 'f'
flip = 1;
otherwise
return
end
% Get the state data
state = get(fig, 'UserData');
if newstate == 0
newstate = state.state;
else
state.state = newstate;
end
if flip
state.resize(1:2) = state.resize([2 1]);
end
state.offset = max(min(state.offset + off, state.maxoffset), -state.maxoffset);
% Display the new image
switch newstate
case 1 % Side by side
A = state.sbs;
set(state.hAx);
set(state.hAx, 'Units', 'normalized', 'Position', [0 0 1 1]);
case 2 % Horizontal stripes
A = zeros(state.pos(4), state.pos(3), size(state.resize{1}, 3), class(state.resize{1}));
A(1:2:end,(1:size(state.resize{1}, 2))+floor(state.maxoffset/2)-floor(state.offset/2),:) = state.resize{1}(1:2:end,:,:);
A(2:2:end,(1:size(state.resize{2}, 2))+floor(state.maxoffset/2)+ceil(state.offset/2),:) = state.resize{2}(2:2:end,:,:);
set(state.hAx, 'Units', 'pixels', 'Position', state.pos);
case 3 % Vertical subpixel interleaving
error('Vertical subpixel interleaving not yet supported');
end
% Set the image data
set(state.hIm, 'CData', A);
% Reset the axes limits
set(state.hAx, 'XLim', [0.5 size(A, 2)+0.5], 'YLim', [0.5 size(A, 1)+0.5]);
drawnow;
% Save the current state
set(fig, 'UserData', state);
return |
github | ojwoodford/ojwul-master | ojw_gaussian_pyramid.m | .m | ojwul-master/image/ojw_gaussian_pyramid.m | 1,699 | utf_8 | 0a0ef1ad7c73878bf3ce37d9f1cb06d5 | %OJW_GAUSSIAN_PYRAMID Creates a gaussian image pyramid
%
% B = ojw_gaussian_pyramid(A, max_depths, [F])
%
% Generates the gaussian pyramid of an image of any class.
%
% IN:
% A - MxNxC input image, or Sx1 cell array of input images.
% max_depths - scalar indicating maximum number of additional pyramid
% levels to calculate.
% F - Tx1 filter to apply to image in x and y directions before
% downsampling. Default: fspecial('gaussian', [5 1], 1/sqrt(2)).
%
% OUT:
% B - 1xL (or SxL) cell array, where B{1} == A, and B{2},..,B{L} are the
% subsampled pyramid levels.
function B = ojw_gaussian_pyramid(A, max_depths, F)
if nargin < 3
% Use a separable smoothing filter
F = [0.25 0.5 0.25];
end
% Multi-cell input
if iscell(A)
B = reshape(A, numel(A), 1);
B{1,max_depths+1} = [];
for a = 1:numel(A)
C = ojw_gaussian_pyramid(A{a}, max_depths, F);
B(a,1:numel(C)) = C;
end
return
end
% Calculate number of depths required
d = ceil(log2(max(size(A, 1), size(A, 2))));
if nargin > 1
d = min(d, max_depths);
end
d = d + 1;
% Initialize the first level
B = cell(1, d);
B{1} = A;
% Convert to singles for higher accuracy (especially with logical arrays)
% but leave doubles as they are
in_class = class(A);
if ~isa(A, 'double')
C = single(A);
F = single(F);
else
C = A;
F = double(F);
end
% Calculate other levels
for a = 2:d
% Filter and subsample
C = filter_subsample(C, F);
% Cast image
if strcmp(in_class, 'logical')
B{a} = C > 0.5;
else
B{a} = cast(C, in_class);
end
end
return
|
github | ojwoodford/ojwul-master | imfiltsep.m | .m | ojwul-master/image/imfiltsep.m | 865 | utf_8 | 40f8d90cecc063fe74b4b309e2a7af45 | %IMFILTSEP Fast separable filtering on a multi-channel image
%
% B = imfiltsep(A, fy, fx)
%
% Fast separable filtering of multi-channel images, using symmetric
% padding, providing an output of the same size as the input.
%
%IN:
% A - HxWxC input image.
% fy - filter to apply to the columns.
% fx - filter to apply to the rows.
%
%OUT:
% B - HxWxC filtered output image.
function I = imfiltsep(I, fy, fx)
if nargin < 3
fx = fy;
end
% Compute the padding indices
[H, W, C] = size(I);
sympadding = @(N, n) [ceil(n/2-0.5)+1:-1:2 1:N N-1:-1:N-floor(n/2-0.5)];
Y = sympadding(H, numel(fy));
X = sympadding(W, numel(fx));
% For each channel separately
for c = 1:C
% Compute the padded array
J = I(Y,X,c);
% Convolve
J = conv2(fy(:), fx(:), J, 'valid');
% Insert into array
I(:,:,c) = J;
end
end
|
github | ojwoodford/ojwul-master | imdilate_.m | .m | ojwul-master/image/imdilate_.m | 1,183 | utf_8 | c37726cafa9893163e283d0d65a7061e | %IMDILATE_ Dilate image
%
% B = imdilate_(A, nhood)
%
% This function duplicates behaviour of the IMDILATE function (without
% needing the Image Processing Toolbox) for a subset of inputs. If IMDILATE
% is available, it is used.
%
%IN:
% A - HxW logical or grayscale image.
% nhood - PxQ matrix of 1s and 0s indicating the neighbourhood of a pixel
% to be dilated.
%
%OUT:
% B - HxW dilated image.
function B = imdilate_(A, nhood)
% Use the IPT if available
if license('test', 'image_toolbox')
B = imdilate(A, nhood);
return;
end
% Cache indices for the dilation
persistent cache
if isempty(cache) || ~isequal(nhood, cache.nhood) || ~isequal(size(A), cache.sz)
cache.nhood = nhood;
cache.sz = size(A);
[y, x] = find(nhood);
y = int32(y - ceil(size(nhood, 1) * 0.5 + 0.5));
x = int32(x - ceil(size(nhood, 2) * 0.5 + 0.5)) - int32(1);
[Y, X] = ndgrid(int32(1:cache.sz(1)), int32(1:cache.sz(2)));
X = min(max(X(:)' + x(:), int32(0)), cache.sz(2)-1);
Y = min(max(Y(:)' + y(:), int32(1)), cache.sz(1));
cache.ind = X * int32(cache.sz(1)) + Y;
end
% Perform the dilation
B = reshape(max(A(cache.ind), [], 1), cache.sz);
end |
github | ojwoodford/ojwul-master | imgrad.m | .m | ojwul-master/image/imgrad.m | 4,924 | utf_8 | cd9eb1f9a8f1ad0f709eab8e0ef36557 | %IMGRAD Calculate gradients of an image in x and y directions
%
% [Ix, Iy] = imgrad(I, sigma, [mcm])
% G = imgrad(I, sigma, [mcm])
%
% Computes x and y gradients of an image. The implementation uses
% separable, steerable filters, hence is fast.
%
% For multi-channel images, the gradient is computed in the colour
% direction of greatest change, by defualt, using the method described in:
% DiZenzo, S. [1986]. "A note on the gradient of a multi-image",
% CVGIP, Vol. 33, pp. 116-125.
% Other methods can be selected.
%
% IN:
% I - HxWxC input image.
% filter - String denoting named filter ['Bilinear', 'Central',
% 'Prewitt', 'Sobel', 'Simoncelli'] or scalar value determing
% the scale of the gradient filter (essentially the amount of
% pre-smoothing to apply). If 'Simoncelli', the 7-tap values
% from Farid, H. and Simoncelli, E. "Differentiation of Discrete
% Multi-Dimensional Signals". IEEE Trans. Image Processing.
% 13(4): 496-508 (2004) are used.
% mcm - multi-channel method: 'dizenzo' (default), 'norm', 'pca',
% 'rgb2gray', 'none'.
%
% OUT:
% Ix - HxW array of gradient images in the x direction.
% Iy - HxW array of gradient images in the y direction.
% G - HxWx2 array of gradient images in x and y directions, i.e. cat(3,
% Ix, Iy).
function [Ix, Iy] = imgrad(I, filter, mcm)
% Set the default arguments
if nargin < 3
mcm = 'dizenzo';
end
I = double(I);
[h, w, c] = size(I);
% Convert multi-channel images to single channel, if required
if c > 1
switch lower(mcm)
case 'rgb2gray'
% Standard RGB to grey conversion
assert(c == 3, 'Image must have 3 channels');
I = reshape(reshape(I, h*w, c) * [0.299; 0.587; 0.114], h, w);
c = 1;
case 'pca'
% Compress along the first principle component of colour
I = reshape(I, h*w, c)';
T = pca(I);
I = reshape(T(1,1:end-1) * I, h, w);
c = 1;
end
end
if ischar(filter)
switch lower(filter)
case 'bilinear'
% Gradient resulting from bilinear interpolation
g = [1 1];
gp = [1 -1];
case 'central'
% Central differences
g = 1;
gp = [1 0 -1];
case 'prewitt'
g = [1 1 1];
gp = [1 0 -1];
case 'sobel'
g = [1 2 1];
gp = [1 0 -1];
case 'simoncelli'
% Use 7-tap filter from:
% Farid, H. and Simoncelli, E. "Differentiation of Discrete Multi-Dimensional Signals"
% IEEE Trans. Image Processing. 13(4): 496-508 (2004)
g = [0.004711 0.069321 0.245410 0.361117 0.245410 0.069321 0.004711];
gp = [0.018708 0.125376 0.193091 0.000000 -0.193091 -0.125376 -0.018708];
otherwise
error('Filter %s unrecognized', filter);
end
X = 1:numel(gp);
X = X - mean(X);
else
% Determine necessary filter support (for Gaussian).
X = max(floor((5 / 2) * filter), 1);
X = -X:X;
% Evaluate 1D Gaussian filter (and its derivative).
g = gauss_mask(filter, 0, X);
gp = gauss_mask(filter, 1, X);
end
% Normalize the filters
g = g / sum(g);
gp = gp / sum(abs(gp) .* abs(X));
% Calculate image gradients
Ix = imfiltsep(I, g, gp);
Iy = imfiltsep(I, gp, g);
% Compress multi-channelled images
if c > 1
switch lower(mcm)
case 'dizenzo'
% Compute maximum gradient using method in:
% DiZenzo, S. [1986]. "A note on the gradient of a multi-image",
% CVGIP, Vol. 33, pp. 116-125.
% Compute inner product of Jacobian with itself
J = [shiftdim(sum(Ix .* Ix, 3), -1); shiftdim(sum(Iy .* Iy, 3), -1); shiftdim(sum(Ix .* Iy, 3), -1)];
% Compute the first eigen vector
lambda = J(1,:) - J(2,:);
lambda = 0.5 * (J(1,:) + J(2,:) + sqrt(lambda .* lambda + 4 * (J(3,:) .* J(3,:))));
J_ = [J(2,:)-lambda; -J(3,:)];
J = [-J(3,:); J(1,:)-lambda];
M = sum(J .* J, 1) < sum(J_ .* J_, 1);
J(:,M) = J_(:,M);
J = bsxfun(@times, J, sqrt(lambda) ./ (normd(J, 1) + 1e-100));
Ix = reshape(J(1,:), h, w);
Iy = reshape(J(2,:), h, w);
case 'norm'
% Compute the gradient norm
Ix = sign(sum(Ix, 3)) .* normd(Ix, 3);
Iy = sign(sum(Iy, 3)) .* normd(Iy, 3);
case 'none'
% Leave as is
otherwise
error('Multi-channel method %s not recognized', mcm);
end
end
% Concatenate if necessary
if nargout == 1
Ix = cat(3, Ix, Iy);
end
return |
github | ojwoodford/ojwul-master | ojw_interp2.m | .m | ojwul-master/image/ojw_interp2.m | 1,743 | utf_8 | c89cbb73c375246f6d26894a9f6ecd34 | %OJW_INTERP2 Fast 2d interpolation for images
%
% V = ojw_interp2(A, X, Y)
% V = ojw_interp2(A, X, Y, interp_mode)
% V = ojw_interp2(A, X, Y, interp_mode, oobv)
% V = ojw_interp2(A, X, Y, interp_mode, oobv, max_num_threads)
%
% 2d interpolation on a regular grid - similar to MATLAB's interp2() but
% with much less overhead, and supports multiple channels and types. Note
% that while results of 'linear' and 'nearest' interpolation are the same
% as those of interp2(), those of cubic are not - ojw_interp2 uses a cubic
% hermite spline that is very fast to compute, unlike the natural cubic
% spline employed by interp2(), which does, however, yield a smoother
% interpolation.
%
% If compiled with OpenMP, this function splits the work across N threads,
% where N is the smaller of max_num_threads and omp_get_num_procs().
%
%IN:
% A - HxWxC double, single, uint16, int16, uint8, int8 or Logical array.
% X - MxN horizontal offsets (1 being the centre of the first pixel).
% Y - MxN vertical offsets (1 being the centre of the first pixel).
% interp_mode - string, either 'nearest', 'linear', 'cubic', 'magic',
% '4lanczos', or '6lanczos'. Default: 'linear'.
% oobv - 1x1 Out of bounds value. Default: NaN.
% max_num_threads - 1x1 upper bound on the maximum number of threads to
% be used. Default: 1024^2.
%OUT:
% V - MxNxC interpolated values. Class is the same as that of oobv.
% G - 2xMxNxC array of gradients of V in x and y directions:
% [shiftdim(Vx, -1); shiftdim(Vy, -1)].
function varargout = ojw_interp2(varargin)
sourceList = {'ojw_interp2.cpp', '-Xopenmp', '-Cstd=c++11'}; % Cell array of source files
[varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here
end |
github | ojwoodford/ojwul-master | ojw_box_pyramid.m | .m | ojwul-master/image/ojw_box_pyramid.m | 1,660 | utf_8 | b3cbbd67b60ed5d6b061f81b419c9dc4 | %OJW_BOX_PYRAMID Creates an image pyramid using box filtering
%
% B = ojw_box_pyramid(A, max_depths)
%
% Generates the image pyramid of an image of any class.
%
% IN:
% A - MxNxC input image, or Sx1 cell array of input images.
% max_depths - scalar indicating maximum number of additional pyramid
% levels to calculate.
%
% OUT:
% B - 1xL (or SxL) cell array, where B{1} == A, and B{2},..,B{L} are the
% subsampled pyramid levels.
function B = ojw_box_pyramid(A, max_depths)
% Multi-cell input
if iscell(A)
B = reshape(A, numel(A), 1);
B{1,max_depths+1} = [];
for a = 1:numel(A)
C = ojw_box_pyramid(A{a}, max_depths);
B(a,1:numel(C)) = C;
end
return
end
% Calculate number of depths required
d = ceil(log2(max(size(A, 1), size(A, 2))));
if nargin > 1
d = min(d, max_depths);
end
d = d + 1;
% Initialize the first level
B = cell(1, d);
B{1} = A;
% Convert to singles for higher accuracy (especially with logical arrays)
% but leave doubles as they are
in_class = class(A);
if ~isa(A, 'double')
C = single(A);
else
C = A;
end
% Calculate other levels
for a = 2:d
% Filter and subsample
if mod(size(C, 1), 2)
C = padarray(C, [1 0], 'replicate', 'post');
end
C = C(1:2:end,:,:) + C(2:2:end,:,:);
if mod(size(C, 2), 2)
C = padarray(C, [0 1], 'replicate', 'post');
end
C = C(:,1:2:end,:) + C(:,2:2:end,:);
C = C * 0.25;
% Cast image
if strcmp(in_class, 'logical')
B{a} = C > 0.5;
else
B{a} = cast(C, in_class);
end
end
return
|
github | ojwoodford/ojwul-master | imnonmaxsup.m | .m | ojwul-master/image/imnonmaxsup.m | 1,581 | utf_8 | 3a434f880c28f81007baab20f9b09472 | %IMNONMAXSUP Non-maxima suppression in an image
%
% M = imnonmaxsup(I, [radius, [mask_val]])
%
%IN:
% I - HxW image
% radius - scalar value of radius (in pixels) within which to suppress
% maxima. Default: 1.5.
% mask_val - scalar value which is used to mask previous maxima prior to
% iterating the search for maxima. Default: output single
% iteration maxima only.
%
%OUT:
% M - HxW mask indicating which pixels are local maxima
function M = imnonmaxsup(I, radius, mask_val)
% Set the default radius
if nargin < 2
radius = 1.5;
end
radius2 = radius * radius;
% Find 4-connected maxima (must be greater than neighbours)
M = I(2:end-1,2:end-1);
M = M > I(1:end-2,2:end-1) & ...
M > I(3:end,2:end-1) & ...
M > I(2:end-1,1:end-2) & ...
M > I(2:end-1,3:end);
M = [false(1, size(M, 2)+2); false(size(M, 1), 1) M false(size(M, 1), 1); false(1, size(M, 2)+2)];
if radius2 >= 2 || nargin > 2
% Extended supression required
% Compute the neighbourhood
[y, x] = ndgrid(-floor(radius):floor(radius));
nhood = (y .* y + x .* x) <= radius2;
% Dilate the image
J = imdilate_(I, nhood);
% Return mask of maximal points
M = J == I & M;
if nargin > 2
% Iterate the search
I(imdilate_(M, nhood)) = mask_val;
while any(I(:))
J = imdilate_(I, nhood);
J = (J == I) & (I ~= mask_val);
I(imdilate_(J, nhood)) = mask_val;
M = M | J;
end
end
end
end |
github | ojwoodford/ojwul-master | ojw_interp2_debug.m | .m | ojwul-master/image/ojw_interp2_debug.m | 348 | utf_8 | 7fc44f6c579ad0ad1f6dd7ce07c482d0 | %OJW_INTERP2_DEBUG Image sampling, with plotting of the sample points
function varargout = ojw_interp2_debug(varargin)
% Forward the call, for error checking
[varargout{1:nargout}] = ojw_interp2(varargin{:});
% Render the sample points
figure(7429);
clf reset;
imdisp(varargin{1});
hold on;
plot(double(varargin{2}), double(varargin{3}), 'r.');
end |
github | ojwoodford/ojwul-master | image_alignment_demo.m | .m | ojwul-master/image/image_alignment_demo.m | 2,999 | utf_8 | 7c9011c2a9ac3111d0ff32d10aa8c9e2 | %IMAGE_ALIGNMENT_DEMO Demonstrates image alignment
%
% image_alignment_demo()
%
% This function demonstrates image alignment via a homography, using
% various techniques:
% - Lie algebra: a Lie representation of homography updates.
% - Auto differentiation: automatically compute the Jacobian of residuals.
% - Gauss-Newton: gradient descent with automatic step size computation.
% - Analytic image gradients: fast image & gradient sampling using ojw_interp2.
function image_alignment_demo(A)
if nargin < 1
A = imread('peppers.png');
end
sz = size(A);
render();
% Create a target image
[y, x] = ndgrid(linspace(sz(1)/2-50, sz(1)/2+50, 100), linspace(sz(2)/2-50, sz(2)/2+50, 100));
ref = ojw_interp2(A, x, y); % Did you call "mex ojw_interp2.cpp" first?
% Create a small homography
Hgt = eye(3) + randn(3) * 0.0002;
X = Hgt * [x(:)'; y(:)'; ones(1, numel(x))];
% Use SL(3) representation of a homography
sl3 = lie('sl3');
% Create a cost function
H = eye(3);
for a = 1:100
% Create a delta vector of 8 variables
dH = autodiff(zeros(8, 1)); % The magic line!!!!
% Compute the homgraphy update
dH = exp(sl3, dH);
% Apply the homography
Y = (H * dH) * X;
Y = bsxfun(@times, Y(1:2,:), Y(3,:));
% Sample the image
tgt = ojw_interp2(A, Y(1,:), Y(2,:));
tgt = reshape(tgt, size(ref));
% Compute the residuals
r = tgt - ref;
% Read out the *automagically* computed gradient of the residuals
J = reshape(grad(r), 8, []);
r = double(r);
% Compute the gauss-newton step
step = J' \ r(:);
% Visualization
render(ref, r, tgt);
% Check for convergence
if norm(step) < 1e-12
break;
end
% Apply the step
H = H * exp(sl3, -step);
end
end
function render(ref, r, tgt)
persistent handles
if nargin == 0
handles = [];
return;
end
cost = r(:)' * r(:);
r = log(1 + sum(r .* r, 3));
tgt = double(tgt) / 255;
try
handles.X = [handles.X handles.X(end)+1];
handles.Y = [handles.Y cost];
figure(handles.fig);
set(handles.diff_im, 'CData', r);
set(handles.tgt_im, 'CData', tgt);
set(handles.plot, 'XData', handles.X, 'YData', handles.Y);
catch
handles.fig = figure(5680);
clf;
set(handles.fig, 'Color', 'w');
axes('OuterPosition', [0 0.5 1/3 0.5]);
image(ref/255);
title 'Reference image'
axis equal off
axes('OuterPosition', [1/3 0.5 1/3 0.5]);
handles.diff_im = imagesc(r);
title 'Pixel difference magnitude'
axis equal off
axes('OuterPosition', [2/3 0.5 1/3 0.5]);
handles.tgt_im = image(tgt);
title 'Target image'
axis equal off
axes('OuterPosition', [0 0 1 0.5]);
handles.X = 1;
handles.Y = cost;
handles.plot = plot(handles.X, handles.Y);
xlim([1 100]);
ylim([0 cost*1.05]);
ylabel Cost
xlabel Iteration
end
drawnow;
end
|
github | ojwoodford/ojwul-master | filter_subsample.m | .m | ojwul-master/image/filter_subsample.m | 949 | utf_8 | a5032e2f3563655e0986a6425d71ad82 | %FILTER_SUBSAMPLE Filters and subsamples an image by a factor of 2
%
% B = filter_subsample(A, F)
%
% Given an image and a one dimensional filter, this function convolves the
% image with the filter along its first two dimensions, and then subsamples
% the resulting image by a factor of two in both those dimensions.
%
% Support for new types, and for two filters for non-symmetrical, separable
% filtering can easily be added to this function.
%
% IN:
% A - MxNxC input image.
% F - Lx1 filter to be applied separably to A. F must be double iff A is
% double, otherwise it must be single.
%
% OUT:
% B - (M+1)/2x(N+1)/2xC output image, of the same class as A.
% $Id: filter_subsample.m,v 1.2 2007/08/02 11:34:56 ojw Exp $
function varargout = filter_subsample(varargin)
sourceList = {'filter_subsample.cpp', '-Xopenmp'}; % Cell array of source files
[varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here
return |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.