Subversion Repositories seema-scanner

Rev

Rev 239 | Rev 241 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 239 Rev 240
1
function MSE = alignSubScansMarkers(calibrationFileName, alnFileName)
1
function MSE = alignSubScansMarkers(calibrationFileName, alnFileName)
2
%ALIGNSUBSCANSMARKERS Determines an exact alignment of sub scans (scans
2
%ALIGNSUBSCANSMARKERS Determines an exact alignment of sub scans (scans
3
% from e.g. one revolution of the rotation stage). 
3
% from e.g. one revolution of the rotation stage). 
4
% The method searches for circular white markers of a specific diameter.
4
% The method searches for circular white markers of a specific diameter.
5
% White frames corresponding to each sub scan must be available.
5
% White frames corresponding to each sub scan must be available.
6
% A coarse alignment in the form of an aln-file must be provided. 
6
% A coarse alignment in the form of an aln-file must be provided. 
7
%
7
%
8
% 2017 Jakob Wilm, DTU
8
% 2017 Jakob Wilm, DTU
9
 
9
 
10
initialAlign = readMeshLabALN(alnFileName);
10
initialAlign = readMeshLabALN(alnFileName);
11
[alnFilePath, ~, ~] = fileparts(alnFileName);
11
[alnFilePath, ~, ~] = fileparts(alnFileName);
12
 
12
 
13
calibration = readOpenCVXML(calibrationFileName);
13
calibration = readOpenCVXML(calibrationFileName);
14
 
14
 
15
% correct for Matlab 1-indexing in principle point coordinates
15
% correct for Matlab 1-indexing in principle point coordinates
16
calibration.K0(1:2, 3) = calibration.K0(1:2, 3)+1;
16
calibration.K0(1:2, 3) = calibration.K0(1:2, 3)+1;
17
calibration.K1(1:2, 3) = calibration.K1(1:2, 3)+1;
17
calibration.K1(1:2, 3) = calibration.K1(1:2, 3)+1;
18
 
18
 
19
% full projection matrices in Matlab convention
19
% full projection matrices in Matlab convention
20
P0 = transpose(calibration.K0*[eye(3) zeros(3,1)]);
20
P0 = transpose(calibration.K0*[eye(3) zeros(3,1)]);
21
P1 = transpose(calibration.K1*[calibration.R1 calibration.T1']);
21
P1 = transpose(calibration.K1*[calibration.R1 calibration.T1']);
22
 
22
 
23
% matlab cam params for undistortion
23
% matlab cam params for undistortion
24
camParams0 = cameraParameters('IntrinsicMatrix', calibration.K0', 'RadialDistortion', calibration.k0([1 2 5]), 'TangentialDistortion', calibration.k0([3 4]));
24
camParams0 = cameraParameters('IntrinsicMatrix', calibration.K0', 'RadialDistortion', calibration.k0([1 2 5]), 'TangentialDistortion', calibration.k0([3 4]));
25
camParams1 = cameraParameters('IntrinsicMatrix', calibration.K1', 'RadialDistortion', calibration.k1([1 2 5]), 'TangentialDistortion', calibration.k1([3 4]));
25
camParams1 = cameraParameters('IntrinsicMatrix', calibration.K1', 'RadialDistortion', calibration.k1([1 2 5]), 'TangentialDistortion', calibration.k1([3 4]));
26
 
26
 
27
% matlab struct for triangulation
27
% matlab struct for triangulation
28
camStereoParams = stereoParameters(camParams0, camParams1, calibration.R1', calibration.T1');
28
camStereoParams = stereoParameters(camParams0, camParams1, calibration.R1', calibration.T1');
29
 
29
 
30
nSubScans = length(initialAlign);
30
nSubScans = length(initialAlign);
31
 
31
 
32
% 3D coordinates of markers in local camera frame
32
% 3D coordinates of markers in local camera frame
33
E = cell(nSubScans, 1);
33
E = cell(nSubScans, 1);
34
 
34
 
35
% 3D coordinates of markers in global initial alignment
35
% 3D coordinates of markers in global initial alignment
36
Eg = cell(size(E));
36
Eg = cell(size(E));
37
 
37
 
38
% find 3D markers coordinates 
38
% find 3D markers coordinates 
39
for i=1:nSubScans
39
for i=1:nSubScans
40
%for i=5:5
40
%for i=5:5
41
    % load point cloud
41
    % load point cloud
42
    pcFileName = fullfile(alnFilePath, initialAlign(i).FileName);
42
    pcFileName = fullfile(alnFilePath, initialAlign(i).FileName);
43
    pcFilePath = fileparts(pcFileName);
43
    pcFilePath = fileparts(pcFileName);
44
    pc = pcread(pcFileName);
44
    pc = pcread(pcFileName);
45
    Q = pc.Location;
45
    Q = pc.Location;
46
    idString = strsplit(initialAlign(i).FileName, {'.ply', '_'});
46
    idString = strsplit(initialAlign(i).FileName, {'.ply', '_'});
47
    idString = idString{end-1};
47
    idString = idString{end-1};
48
    
48
    
49
    % load white frames
49
    % load white frames
50
    frame0 = imread(fullfile(pcFilePath, ['sequence_' idString], 'frames0_0.png'));
50
    frame0 = imread(fullfile(pcFilePath, ['sequence_' idString], 'frames0_0.png'));
51
    frame1 = imread(fullfile(pcFilePath, ['sequence_' idString], 'frames1_0.png'));
51
    frame1 = imread(fullfile(pcFilePath, ['sequence_' idString], 'frames1_0.png'));
52
 
52
 
53
    e0Coords = autoDetectMarkers(frame0);
53
    e0Coords = autoDetectMarkers(frame0);
54
    e1Coords = autoDetectMarkers(frame1);
54
    e1Coords = autoDetectMarkers(frame1);
55
    
55
    
56
    %e0Coords = manuallyDetectMarkers(frame0);
56
    %e0Coords = manuallyDetectMarkers(frame0);
57
    %e1Coords = manuallyDetectMarkers(frame1);
57
    %e1Coords = manuallyDetectMarkers(frame1);
58
    
58
    
59
    %[e0Coords, conf0] = detectMarkersSubpix(frame0, e0Coords, P0, Q);
59
    %[e0Coords, conf0] = detectMarkersSubpix(frame0, e0Coords, P0, Q);
60
    %[e1Coords, conf1] = detectMarkersSubpix(frame1, e1Coords, P1, Q);
60
    %[e1Coords, conf1] = detectMarkersSubpix(frame1, e1Coords, P1, Q);
61
 
61
 
62
    if(length(e0Coords) < 1 || length(e1Coords) < 1)
62
    if(length(e0Coords) < 1 || length(e1Coords) < 1)
63
        continue;
63
        continue;
64
    end
64
    end
65
    
65
    
66
%     figure; 
66
%     figure; 
67
%     subplot(1,2,1);
67
%     subplot(1,2,1);
68
%     imshow(frame0);
68
%     imshow(frame0);
69
%     hold('on');
69
%     hold('on');
70
%     plot(e0Coords(:,1), e0Coords(:,2), 'rx', 'MarkerSize', 15);
70
%     plot(e0Coords(:,1), e0Coords(:,2), 'rx', 'MarkerSize', 15);
71
%     subplot(1,2,2);
71
%     subplot(1,2,2);
72
%     imshow(frame1);
72
%     imshow(frame1);
73
%     hold('on');
73
%     hold('on');
74
%     plot(e1Coords(:,1), e1Coords(:,2), 'rx', 'MarkerSize', 15);
74
%     plot(e1Coords(:,1), e1Coords(:,2), 'rx', 'MarkerSize', 15);
75
%     drawnow;
75
%     drawnow;
76
    
76
    
77
    e0Coords = undistortPointsFast(e0Coords, camParams0);
77
    e0Coords = undistortPointsFast(e0Coords, camParams0);
78
    e1Coords = undistortPointsFast(e1Coords, camParams1);
78
    e1Coords = undistortPointsFast(e1Coords, camParams1);
79
 
79
 
80
    % match ellipse candidates between cameras based on projection
80
    % match ellipse candidates between cameras based on projection
81
    E0 = projectOntoPointCloud(e0Coords, P0, Q);
81
    E0 = projectOntoPointCloud(e0Coords, P0, Q);
82
    E1 = projectOntoPointCloud(e1Coords, P1, Q);
82
    E1 = projectOntoPointCloud(e1Coords, P1, Q);
83
 
83
 
84
    matchedPairs = nan(size(E0, 1), 2);
84
    matchedPairs = nan(size(E0, 1), 2);
85
    nMatchedPairs = 0;
85
    nMatchedPairs = 0;
86
    for j=1:size(E0, 1)
86
    for j=1:size(E0, 1)
87
        
87
        
88
        % should use pdist2 instead..
88
        % should use pdist2 instead..
89
        sqDists = sum((E1 - repmat(E0(j,:), size(E1, 1), 1)).^2, 2);
89
        sqDists = sum((E1 - repmat(E0(j,:), size(E1, 1), 1)).^2, 2);
90
        
90
        
91
        [minSqDist, minSqDistIdx] = min(sqDists);
91
        [minSqDist, minSqDistIdx] = min(sqDists);
92
 
92
 
93
        if(minSqDist < 1^2)
93
        if(minSqDist < 1^2)
94
            nMatchedPairs = nMatchedPairs + 1;
94
            nMatchedPairs = nMatchedPairs + 1;
95
            matchedPairs(nMatchedPairs, :) = [j, minSqDistIdx];
95
            matchedPairs(nMatchedPairs, :) = [j, minSqDistIdx];
96
        end
96
        end
97
    end
97
    end
98
    matchedPairs = matchedPairs(1:nMatchedPairs, :);
98
    matchedPairs = matchedPairs(1:nMatchedPairs, :);
99
    
99
    
100
    figure; 
100
    figure; 
101
    subplot(1,2,1);
101
    subplot(1,2,1);
102
    imshow(frame0);
102
    imshow(frame0);
103
    hold('on');
103
    hold('on');
104
    plot(e0Coords(matchedPairs(:, 1),1), e0Coords(matchedPairs(:, 1),2), 'rx', 'MarkerSize', 15);
104
    plot(e0Coords(matchedPairs(:, 1),1), e0Coords(matchedPairs(:, 1),2), 'rx', 'MarkerSize', 15);
105
    subplot(1,2,2);
105
    subplot(1,2,2);
106
    imshow(frame1);
106
    imshow(frame1);
107
    hold('on');
107
    hold('on');
108
    plot(e1Coords(matchedPairs(:, 2),1), e1Coords(matchedPairs(:, 2),2), 'rx', 'MarkerSize', 15);
108
    plot(e1Coords(matchedPairs(:, 2),1), e1Coords(matchedPairs(:, 2),2), 'rx', 'MarkerSize', 15);
109
    drawnow;
109
    drawnow;
110
    
110
    
111
%     % triangulate marker centers (lens correction has been performed)
111
%     % triangulate marker centers (lens correction has been performed)
112
%     [E{i}, e] = triangulate(e0Coords(matchedPairs(:, 1),:), e1Coords(matchedPairs(:, 2),:), camStereoParams);
112
%     [E{i}, e] = triangulate(e0Coords(matchedPairs(:, 1),:), e1Coords(matchedPairs(:, 2),:), camStereoParams);
113
%     E{i} = E{i}(e<3.0, :);
113
%     E{i} = E{i}(e<3.0, :);
114
%     display(e);
114
%     display(e);
115
    
115
    
116
    [E{i}, e] = detectMarkersStereoSubpix(frame0, frame1, E0(matchedPairs(:, 1), :), camStereoParams, pc);
116
    [E{i}, e] = detectMarkersStereoSubpix(frame0, frame1, E0(matchedPairs(:, 1), :), camStereoParams, pc);
117
    display(e);
117
    display(e);
118
    
118
    
119
    % write point cloud with marker (debugging)
119
    % write point cloud with marker (debugging)
120
    pcDebug = pointCloud([pc.Location; E{i}], 'Color', [pc.Color; repmat([255, 0, 0], size(E{i}, 1), 1)]);
120
    pcDebug = pointCloud([pc.Location; E{i}], 'Color', [pc.Color; repmat([255, 0, 0], size(E{i}, 1), 1)]);
121
    pcwrite(pcDebug, 'pcDebug.ply');
121
    pcwrite(pcDebug, 'pcDebug.ply');
122
    
122
    
123
    % bring markers into initial alignment
123
    % bring markers into initial alignment
124
    [U,~,V] = svd(initialAlign(i).Rotation);
124
    [U,~,V] = svd(initialAlign(i).Rotation);
125
    Ri = U*V';
125
    Ri = U*V';
126
    Ti = initialAlign(i).Translation;
126
    Ti = initialAlign(i).Translation;
127
    
127
    
128
    Eg{i} = E{i}*Ri' + repmat(Ti', size(E{i}, 1), 1);
128
    Eg{i} = E{i}*Ri' + repmat(Ti', size(E{i}, 1), 1);
129
end
129
end
130
 
130
 
131
% show found markers in initial alignment
131
% show found markers in initial alignment
132
figure;
132
figure;
133
hold('on');
133
hold('on');
134
for i=1:nSubScans
134
for i=1:nSubScans
135
    % fix Ri to be orthogonal
135
    % fix Ri to be orthogonal
136
    [U,~,V] = svd(initialAlign(i).Rotation);
136
    [U,~,V] = svd(initialAlign(i).Rotation);
137
    Ri = U*V';
137
    Ri = U*V';
138
    
138
    
139
    % bring point cloud into initial alignment
139
    % bring point cloud into initial alignment
140
    pcFileName = fullfile(alnFilePath, initialAlign(i).FileName);
140
    pcFileName = fullfile(alnFilePath, initialAlign(i).FileName);
141
    pc = pcread(pcFileName);
141
    pc = pcread(pcFileName);
142
    tform = affine3d([Ri' [0;0;0]; initialAlign(i).Translation' 1]);
142
    tform = affine3d([Ri' [0;0;0]; initialAlign(i).Translation' 1]);
143
    pcg = pctransform(pc, tform);
143
    pcg = pctransform(pc, tform);
144
   
144
   
145
    pcshow(pcg);
145
    pcshow(pcg);
146
    xlabel('x');
146
    xlabel('x');
147
    ylabel('y');
147
    ylabel('y');
148
    zlabel('z');
148
    zlabel('z');
149
    
149
    
150
    plot3(Eg{i}(:,1), Eg{i}(:,2), Eg{i}(:,3), '.', 'MarkerSize', 15);
150
    plot3(Eg{i}(:,1), Eg{i}(:,2), Eg{i}(:,3), '.', 'MarkerSize', 15);
151
    title('Initial Alignment');
151
    title('Initial Alignment');
152
end
152
end
153
 
153
 
154
% match markers between poses using initial alignment
154
% match markers between poses using initial alignment
155
Pg = {};
155
Pg = {};
156
P = {};
156
P = {};
157
for i=1:nSubScans
157
for i=1:nSubScans
158
    for j=1:size(Eg{i}, 1)
158
    for j=1:size(Eg{i}, 1)
159
        pg = Eg{i}(j,:);
159
        pg = Eg{i}(j,:);
160
        p = E{i}(j,:);
160
        p = E{i}(j,:);
161
        matched = false;
161
        matched = false;
162
        for k=1:size(Pg, 2)
162
        for k=1:size(Pg, 2)
163
            clusterCenter = mean(cat(1, Pg{:,k}), 1);
163
            clusterCenter = mean(cat(1, Pg{:,k}), 1);
164
            if(sum((pg - clusterCenter).^2) < 3^2)
164
            if(sum((pg - clusterCenter).^2) < 3^2)
165
                % store in global frame
165
                % store in global frame
166
                Pg{i,k} = pg;
166
                Pg{i,k} = pg;
167
                % store in local frame
167
                % store in local frame
168
                P{i,k} = p;
168
                P{i,k} = p;
169
                matched = true;
169
                matched = true;
170
                break;
170
                break;
171
            end
171
            end
172
        end
172
        end
173
        % create new cluster
173
        % create new cluster
174
        if(not(matched))
174
        if(not(matched))
175
            Pg{i,end+1} = pg;
175
            Pg{i,end+1} = pg;
176
            P{i,end+1} = p;
176
            P{i,end+1} = p;
177
        end 
177
        end 
178
    end
178
    end
179
end
179
end
180
 
180
 
181
% run optimization
181
% run optimization
182
alignment = groupwiseOrthogonalProcrustes(P, initialAlign);
182
alignment = groupwiseOrthogonalProcrustes(P, initialAlign);
183
 
183
 
184
% show found markers in optimized alignment
184
% show found markers in optimized alignment
185
figure;
185
figure;
186
hold('on');
186
hold('on');
187
for i=1:nSubScans
187
for i=1:nSubScans
188
    % fix Ri to be orthogonal
188
    % fix Ri to be orthogonal
189
    [U,~,V] = svd(alignment(i).Rotation);
189
    [U,~,V] = svd(alignment(i).Rotation);
190
    Ri = U*V';
190
    Ri = U*V';
191
    Ti = alignment(i).Translation;
191
    Ti = alignment(i).Translation;
192
    
192
    
193
    Ea = E{i}*Ri' + repmat(Ti', size(E{i}, 1), 1);
193
    Ea = E{i}*Ri' + repmat(Ti', size(E{i}, 1), 1);
194
    
194
    
195
    % bring point cloud into optimized alignment
195
    % bring point cloud into optimized alignment
196
    pc = pcread(initialAlign(i).FileName);
196
    pc = pcread(initialAlign(i).FileName);
197
    tform = affine3d([Ri' [0;0;0]; initialAlign(i).Translation' 1]);
197
    tform = affine3d([Ri' [0;0;0]; initialAlign(i).Translation' 1]);
198
    pcg = pctransform(pc, tform);
198
    pcg = pctransform(pc, tform);
199
   
199
   
200
    pcshow(pcg);
200
    pcshow(pcg);
201
    xlabel('x');
201
    xlabel('x');
202
    ylabel('y');
202
    ylabel('y');
203
    zlabel('z');
203
    zlabel('z');
204
    
204
    
205
    plot3(Ea(:,1), Ea(:,2), Ea(:,3), '.', 'MarkerSize', 15);
205
    plot3(Ea(:,1), Ea(:,2), Ea(:,3), '.', 'MarkerSize', 15);
206
    title('Optimized Alignment');
206
    title('Optimized Alignment');
207
end
207
end
208
 
208
 
209
% write to ALN file
209
% write to ALN file
210
for i=1:length(alignment)
210
for i=1:length(alignment)
211
    alignment(i).FileName = initialAlign(i).FileName;
211
    alignment(i).FileName = initialAlign(i).FileName;
212
end
212
end
213
 
213
 
214
writeMeshLabALN(alignment, strrep(alnFileName, '.aln', 'Optimized.aln'));
214
writeMeshLabALN(alignment, strrep(alnFileName, '.aln', 'Optimized.aln'));
215
 
215
 
216
end
216
end
217
 
217
 
218
function e = autoDetectMarkers(frame, P, pointCloud)
218
function e = autoDetectMarkers(frame, P, pointCloud)
219
 
219
 
220
    % create mask based on morphology
220
    % create mask based on morphology
221
    g = rgb2gray(frame);
221
    g = rgb2gray(frame);
222
    % g(g>254) = 0;
222
    % g(g>254) = 0;
223
    % bw = imbinarize(g, 'adaptive', 'Sensitivity', 10^(-50));
223
    % bw = imbinarize(g, 'adaptive', 'Sensitivity', 10^(-50));
224
    bw = imbinarize(g, 0.10);
224
    bw = imbinarize(g, 0.10);
225
    cc = bwconncomp(bw);
225
    cc = bwconncomp(bw);
226
    rp = regionprops(cc, 'Area', 'Solidity', 'Eccentricity', 'Centroid');
226
    rp = regionprops(cc, 'Area', 'Solidity', 'Eccentricity', 'Centroid');
227
    idx = ([rp.Area] > 100 & [rp.Area] < 1000 & [rp.Solidity] > 0.9);
227
    idx = ([rp.Area] > 100 & [rp.Area] < 1000 & [rp.Solidity] > 0.9);
228
    
228
    
229
    e = cat(1, rp(idx).Centroid);
229
    e = cat(1, rp(idx).Centroid);
230
 
230
 
231
end
231
end
232
 
232
 
233
function e = manuallyDetectMarkers(frame, P, pointCloud)
233
function e = manuallyDetectMarkers(frame, P, pointCloud)
234
    
234
    
235
    e = [];
235
    e = [];
236
	%edges = edge(rgb2gray(frame), 'Canny', [0.08 0.1], 2);
236
	%edges = edge(rgb2gray(frame), 'Canny', [0.08 0.1], 2);
237
 
237
 
238
    figure; 
238
    figure; 
239
    hold('on');
239
    hold('on');
240
    imshow(frame);
240
    imshow(frame);
241
    title('Close figure to end.');
241
    title('Close figure to end.');
242
    set(gcf, 'pointer', 'crosshair'); 
242
    set(gcf, 'pointer', 'crosshair'); 
243
    set(gcf, 'WindowButtonDownFcn', @clickCallback);
243
    set(gcf, 'WindowButtonDownFcn', @clickCallback);
244
    
244
    
245
    uiwait;
245
    uiwait;
246
 
246
 
247
    function clickCallback(caller, ~)
247
    function clickCallback(caller, ~)
248
        
248
        
249
        p = get(gca, 'CurrentPoint'); 
249
        p = get(gca, 'CurrentPoint'); 
250
        p = p(1, 1:2);
250
        p = p(1, 1:2);
251
 
251
 
252
        e = [e; p(:, 1:2)];
252
        e = [e; p(:, 1:2)];
253
        
253
        
254
        if(not(isempty(el)))
254
        if(not(isempty(el)))
255
            figure(caller);
255
            figure(caller);
256
            hold('on');
256
            hold('on');
257
            plot(el(1), el(2), 'rx', 'MarkerSize', 15);
257
            plot(el(1), el(2), 'rx', 'MarkerSize', 15);
258
        end
258
        end
259
    end
259
    end
260
    
260
    
261
end
261
end
262
 
262
 
263
function [e, conf] = detectMarkersSubpix(frame, initGuesses, P, Q)
263
function [e, conf] = detectMarkersSubpix(frame, initGuesses, P, Q)
264
% Detect a marker in a single frame by rectifying to the image and
264
% Detect a marker in a single frame by rectifying to the image and
265
% performing image registration.
265
% performing image registration.
266
 
266
 
267
    % create mask based on morphology
267
    % create mask based on morphology
268
    g = rgb2gray(frame);
268
    g = rgb2gray(frame);
269
    g(g>254) = 0;
269
    g(g>254) = 0;
270
    bw = imbinarize(g);
270
    bw = imbinarize(g);
271
    cc = bwconncomp(bw);
271
    cc = bwconncomp(bw);
272
    labels = labelmatrix(cc);
272
    labels = labelmatrix(cc);
273
 
273
 
274
    % project point cloud into image
274
    % project point cloud into image
275
    q = [Q ones(size(Q,1),1)]*P;
275
    q = [Q ones(size(Q,1),1)]*P;
276
    q = q./[q(:,3) q(:,3) q(:,3)];
276
    q = q./[q(:,3) q(:,3) q(:,3)];
277
    
277
    
278
    e = zeros(size(initGuesses));
278
    e = zeros(size(initGuesses));
279
    conf = zeros(size(initGuesses, 1), 1);
279
    conf = zeros(size(initGuesses, 1), 1);
280
    
280
    
281
    nMarkersFound = 0;
281
    nMarkersFound = 0;
282
    
282
    
283
    for i=1:size(initGuesses, 1)
283
    for i=1:size(initGuesses, 1)
284
        
284
        
285
        labelId = labels(round(initGuesses(i,2)), round(initGuesses(i,1)));
285
        labelId = labels(round(initGuesses(i,2)), round(initGuesses(i,1)));
286
        labelMask = (labels == labelId);
286
        labelMask = (labels == labelId);
287
        labelMask = imdilate(labelMask, strel('disk', 3, 0));
287
        labelMask = imdilate(labelMask, strel('disk', 3, 0));
288
        
288
        
289
        if(sum(sum(labelMask)) < 10 || sum(sum(labelMask)) > 1000)
289
        if(sum(sum(labelMask)) < 10 || sum(sum(labelMask)) > 1000)
290
            continue;
290
            continue;
291
        end
291
        end
292
        
292
        
293
        % determine 3D points that are part of the marker
293
        % determine 3D points that are part of the marker
294
        % note: we should probably undistort labelMask
294
        % note: we should probably undistort labelMask
295
        pointMask = false(size(q, 1), 1);
295
        pointMask = false(size(q, 1), 1);
296
        for j=1:size(q,1)
296
        for j=1:size(q,1)
297
            if(round(q(j,2)) > size(labelMask, 1) || round(q(j,1)) > size(labelMask, 2) || round(q(j,2)) < 1 || round(q(j,1)) < 1)
297
            if(round(q(j,2)) > size(labelMask, 1) || round(q(j,1)) > size(labelMask, 2) || round(q(j,2)) < 1 || round(q(j,1)) < 1)
298
                continue;
298
                continue;
299
            end
299
            end
300
            
300
            
301
            if(labelMask(round(q(j,2)), round(q(j,1))))
301
            if(labelMask(round(q(j,2)), round(q(j,1))))
302
                pointMask(j) = true;
302
                pointMask(j) = true;
303
            end
303
            end
304
        end
304
        end
305
        
305
        
306
        if(sum(pointMask)) < 10
306
        if(sum(pointMask)) < 10
307
            continue;
307
            continue;
308
        end
308
        end
309
        
309
        
310
        % project 3D points onto local plane
310
        % project 3D points onto local plane
311
        [~, sc, ~] = pca(Q(pointMask, :));
311
        [~, sc, ~] = pca(Q(pointMask, :));
312
        Qlocal = sc(:, 1:2);
312
        Qlocal = sc(:, 1:2);
313
        
313
        
314
        % synthetic marker in high res. space
314
        % synthetic marker in high res. space
315
        m = zeros(151, 151);
315
        m = zeros(151, 151);
316
        [x, y] = meshgrid(1:151, 1:151);
316
        [x, y] = meshgrid(1:151, 1:151);
317
        m((x(:)-76).^2 + (y(:)-76).^2 <= 50^2) = 1.0;
317
        m((x(:)-76).^2 + (y(:)-76).^2 <= 50^2) = 1.0;
318
        
318
        
319
        % relation between marker space (px) and true marker/local plane(mm)
319
        % relation between marker space (px) and true marker/local plane(mm)
320
        % true marker diameter is 1.75mm
320
        % true marker diameter is 1.75mm
321
        mScale = 101/1.4; %px/mm
321
        mScale = 101/1.4; %px/mm
322
        mShift = 76; %px
322
        mShift = 76; %px
323
        
323
        
324
        % build homography from image to marker space
324
        % build homography from image to marker space
325
        H = fitgeotrans(q(pointMask, 1:2), mScale*Qlocal+mShift,  'projective');
325
        H = fitgeotrans(q(pointMask, 1:2), mScale*Qlocal+mShift,  'projective');
326
        %Hdlt = Hest_DLT([mScale*Qlocal+mShift, ones(size(Qlocal, 1), 1)]', q(pointMask,:)');
326
        %Hdlt = Hest_DLT([mScale*Qlocal+mShift, ones(size(Qlocal, 1), 1)]', q(pointMask,:)');
327
        %H = projective2d(Hdlt');
327
        %H = projective2d(Hdlt');
328
        
328
        
329
        % bring image of marker into marker space
329
        % bring image of marker into marker space
330
        imMarkerSpace = imwarp(frame, H, 'OutputView', imref2d(size(m)));
330
        imMarkerSpace = imwarp(frame, H, 'OutputView', imref2d(size(m)));
331
        imMarkerSpace = rgb2gray(im2double(imMarkerSpace));
331
        imMarkerSpace = rgb2gray(im2double(imMarkerSpace));
332
        
332
        
333
        %figure; imshowpair(imMarkerSpace, m);
333
        %figure; imshowpair(imMarkerSpace, m);
334
        
334
        
335
        % perform image registration
335
        % perform image registration
336
        % might be better off using subpixel image correlation
336
        % might be better off using subpixel image correlation
337
        [opt, met] = imregconfig('multimodal');
337
        [opt, met] = imregconfig('multimodal');
338
        T = imregtform(m, imMarkerSpace, 'translation', opt, met, 'DisplayOptimization', false);
338
        T = imregtform(m, imMarkerSpace, 'translation', opt, met, 'DisplayOptimization', false);
339
        
339
        
340
        rege = imwarp(m, T, 'OutputView', imref2d(size(m)));
340
        rege = imwarp(m, T, 'OutputView', imref2d(size(m)));
341
        %figure; imshowpair(imMarkerSpace, rege);
341
        %figure; imshowpair(imMarkerSpace, rege);
342
        
342
        
343
        % measure of correlation
343
        % measure of correlation
344
        confI = sum(sum(imMarkerSpace .* rege))/sqrt(sum(sum(imMarkerSpace) * sum(sum(rege))));
344
        confI = sum(sum(imMarkerSpace .* rege))/sqrt(sum(sum(imMarkerSpace) * sum(sum(rege))));
345
        %confI = 1.0;
345
        %confI = 1.0;
346
        
346
        
347
        if confI<0.4
347
        if confI<0.4
348
            continue;
348
            continue;
349
        end
349
        end
350
        
350
        
351
        fprintf('Found marker with confidence: %f\n', confI);
351
        fprintf('Found marker with confidence: %f\n', confI);
352
            
352
            
353
        % transform marker space coordinates (76,76) to frame space
353
        % transform marker space coordinates (76,76) to frame space
354
        el = T.transformPointsForward([76, 76]);
354
        el = T.transformPointsForward([76, 76]);
355
        el = H.transformPointsInverse(el);
355
        el = H.transformPointsInverse(el);
356
        
356
        
357
        nMarkersFound = nMarkersFound+1;
357
        nMarkersFound = nMarkersFound+1;
358
        e(nMarkersFound,:) = el;
358
        e(nMarkersFound,:) = el;
359
        conf(nMarkersFound) = confI;
359
        conf(nMarkersFound) = confI;
360
    end
360
    end
361
    
361
    
362
    e = e(1:nMarkersFound, :);
362
    e = e(1:nMarkersFound, :);
363
    conf = conf(1:nMarkersFound);
363
    conf = conf(1:nMarkersFound);
364
end
364
end
365
 
365
 
366
function [E, conf] = detectMarkersStereoSubpix(frame0, frame1, initGuesses, camStereoParams, pc)
366
function [E, conf] = detectMarkersStereoSubpix(frame0, frame1, initGuesses, camStereoParams, pc)
367
% Detect a marker in stereo frame set by minimizing the difference to
367
% Detect a marker in stereo frame set by minimizing the difference to
368
% projected images of 3d marker
368
% projected images of 3d marker
369
    
369
    
370
    normals = pcnormals(pc, 6);
370
    normals = pcnormals(pc, 6);
371
    
371
    
372
    frame0 = rgb2gray(frame0);
372
    frame0 = rgb2gray(frame0);
373
    frame1 = rgb2gray(frame1);
373
    frame1 = rgb2gray(frame1);
374
 
374
 
375
    nMarkers = size(initGuesses, 2);
375
    nMarkers = size(initGuesses, 2);
376
    
376
    
377
    E = zeros(nMarkers, 3);
377
    E = zeros(nMarkers, 3);
378
    conf = zeros(nMarkers, 1);
378
    conf = zeros(nMarkers, 1);
379
    
379
    
380
    for i=1:nMarkers
380
    for i=1:nMarkers
381
        
381
        
382
        pI = initGuesses(i,:);
382
        pI = initGuesses(i,:);
383
    	
383
    	
384
        e0 = camStereoParams.CameraParameters1.worldToImage(eye(3,3), zeros(3,1), pI);
384
        e0 = camStereoParams.CameraParameters1.worldToImage(eye(3,3), zeros(3,1), pI);
385
        e1 = camStereoParams.CameraParameters2.worldToImage(camStereoParams.RotationOfCamera2, camStereoParams.TranslationOfCamera2, pI);
385
        e1 = camStereoParams.CameraParameters2.worldToImage(camStereoParams.RotationOfCamera2, camStereoParams.TranslationOfCamera2, pI);
386
        
386
        
387
        % center of support region
387
        % center of support region
388
        e0Center = round(e0);
388
        e0Center = round(e0);
389
        e1Center = round(e1);
389
        e1Center = round(e1);
390
        
390
        
391
        % find initial normal
391
        % find initial normal
392
        idx = pc.findNearestNeighbors(pI, 1);
392
        idx = pc.findNearestNeighbors(pI, 1);
393
        nI = double(normals(idx, :));
393
        nI = double(normals(idx, :));
394
        
394
        
395
        margin = 25;
395
        margin = 25;
396
        
396
        
397
        [x,y] = meshgrid(e0Center(1)-margin:e0Center(1)+margin, e0Center(2)-margin:e0Center(2)+margin);
397
        [x,y] = meshgrid(e0Center(1)-margin:e0Center(1)+margin, e0Center(2)-margin:e0Center(2)+margin);
398
        e0ImCoords = [x(:), y(:)];
398
        e0ImCoords = [x(:), y(:)];
399
       
399
       
400
        [x,y] = meshgrid(e1Center(1)-margin:e1Center(1)+margin, e1Center(2)-margin:e1Center(2)+margin);
400
        [x,y] = meshgrid(e1Center(1)-margin:e1Center(1)+margin, e1Center(2)-margin:e1Center(2)+margin);
401
        e1ImCoords = [x(:), y(:)];
401
        e1ImCoords = [x(:), y(:)];
402
        
402
        
403
        e0UndistImCoords = undistortPointsFast(e0ImCoords, camStereoParams.CameraParameters1);
403
        e0UndistImCoords = undistortPointsFast(e0ImCoords, camStereoParams.CameraParameters1);
404
        e0NormImCoords = camStereoParams.CameraParameters1.pointsToWorld(eye(3,3), [0, 0, 1], e0UndistImCoords);
404
        e0NormImCoords = camStereoParams.CameraParameters1.pointsToWorld(eye(3,3), [0, 0, 1], e0UndistImCoords);
405
        e1UndistImCoords = undistortPointsFast(e1ImCoords, camStereoParams.CameraParameters2);
405
        e1UndistImCoords = undistortPointsFast(e1ImCoords, camStereoParams.CameraParameters2);
406
        e1NormImCoords = camStereoParams.CameraParameters2.pointsToWorld(eye(3,3), [0, 0, 1], e1UndistImCoords);
406
        e1NormImCoords = camStereoParams.CameraParameters2.pointsToWorld(eye(3,3), [0, 0, 1], e1UndistImCoords);
407
 
407
 
408
        x0 = [pI nI(1:2)/nI(3) 70.0 70.0];
408
        x0 = [pI nI(1:2)/nI(3) 70.0 70.0];
409
        
409
        
-
 
410
        r = circleResiduals(x0);
-
 
411
        figure; 
-
 
412
        subplot(2,2,1);
-
 
413
        imagesc(reshape(r(1:length(e0NormImCoords)), 2*margin+1, 2*margin+1), [-50 50]);
-
 
414
        subplot(2,2,2);
-
 
415
        imagesc(reshape(r(length(e0NormImCoords)+1:end), 2*margin+1, 2*margin+1), [-50 50]);
-
 
416
        drawnow;
-
 
417
 
410
        options = optimset('Algorithm', 'levenberg-marquardt', 'Display', 'iter-detailed', 'OutputFcn', @out, 'MaxIter', 30, 'TolFun', 10^(-5), 'TolX', 0);
418
        options = optimset('Algorithm', 'levenberg-marquardt', 'Display', 'iter-detailed', 'OutputFcn', @out, 'MaxIter', 30, 'TolFun', 10^(-5), 'TolX', 0);
411
        [x, conf(i), ~] = lsqnonlin(@circleResiduals, x0, [], [], options);
419
        [x, conf(i), ~] = lsqnonlin(@circleResiduals, x0, [], [], options);
412
        
420
        
-
 
421
        r = circleResiduals(x);
-
 
422
        subplot(2,2,3);
-
 
423
        imagesc(reshape(r(1:length(e0NormImCoords)), 2*margin+1, 2*margin+1), [-50 50]);
-
 
424
        subplot(2,2,4);
-
 
425
        imagesc(reshape(r(length(e0NormImCoords)+1:end), 2*margin+1, 2*margin+1), [-50 50]);
413
        display(x);
426
        drawnow;
-
 
427
        
414
        E(i,:) = x(1:3);
428
        E(i,:) = x(1:3);
415
 
429
 
416
    end
430
    end
417
    
431
    
418
    function stop = out(x, optimValues, state)
432
    function stop = out(x, optimValues, state)
419
        
433
        
420
%         r = optimValues.residual;
434
%         r = optimValues.residual;
421
%         
435
%         
422
%         figure; 
436
%         figure; 
423
%         subplot(1,2,1);
437
%         subplot(1,2,1);
424
%         imagesc(reshape(r(1:length(e0NormImCoords)), 2*margin+1, 2*margin+1), [-50 50]);
438
%         imagesc(reshape(r(1:length(e0NormImCoords)), 2*margin+1, 2*margin+1), [-50 50]);
425
%         subplot(1,2,2);
439
%         subplot(1,2,2);
426
%         imagesc(reshape(r(length(e0NormImCoords)+1:end), 2*margin+1, 2*margin+1), [-50 50]);
440
%         imagesc(reshape(r(length(e0NormImCoords)+1:end), 2*margin+1, 2*margin+1), [-50 50]);
427
%         drawnow;
441
%         drawnow;
428
%         
442
%         
429
%         display(x);
443
%         display(x);
430
        
444
        
431
        stop = false;
445
        stop = false;
432
    end
446
    end
433
 
447
 
434
    function r = circleResiduals(x)
448
    function r = circleResiduals(x)
435
        
449
        
436
        p0 = x(1:3);
450
        p0 = x(1:3);
437
        p1 = x(1:3) * camStereoParams.RotationOfCamera2 + camStereoParams.TranslationOfCamera2;
451
        p1 = x(1:3) * camStereoParams.RotationOfCamera2 + camStereoParams.TranslationOfCamera2;
438
        n0 = [x(4:5) 1.0];
452
        n0 = [x(4:5) 1.0];
439
        n0 = 1.0/norm(n0) * n0;
453
        n0 = 1.0/norm(n0) * n0;
440
        n1 = n0 * camStereoParams.RotationOfCamera2;
454
        n1 = n0 * camStereoParams.RotationOfCamera2;
441
        
455
        
442
        r = zeros(length(e0NormImCoords) + length(e1NormImCoords), 1);
456
        r = zeros(length(e0NormImCoords) + length(e1NormImCoords), 1);
443
        
457
        
444
        % norminal radius of markers
458
        % norminal radius of markers
445
        markerRadius = 1.4/2.0; %mm
459
        markerRadius = 1.4/2.0; %mm
446
        
460
        
447
        % half-width of ramp
461
        % half-width of ramp
448
        w = 0.3; %mm
462
        w = 0.3; %mm
449
 
463
 
450
        p0n0 = (p0*n0');
464
        p0n0 = (p0*n0');
451
        p1n1 = (p1*n1');
465
        p1n1 = (p1*n1');
452
        
466
        
453
        for k=1:length(e0NormImCoords)
467
        for k=1:length(e0NormImCoords)
454
 
468
 
455
            % dermine homogenous coordinate on the hypothesized plane
469
            % dermine homogenous coordinate on the hypothesized plane
456
            t = p0n0/([e0NormImCoords(k,:), 1]*n0');
470
            t = p0n0/([e0NormImCoords(k,:), 1]*n0');
457
            
471
            
458
            d = norm(p0 - t*[e0NormImCoords(k,:), 1.0]);
472
            d = norm(p0 - t*[e0NormImCoords(k,:), 1.0]);
459
            
473
            
460
            imVal = double(frame0(e0ImCoords(k,2), e0ImCoords(k,1)));
474
            imVal = double(frame0(e0ImCoords(k,2), e0ImCoords(k,1)));
461
            
475
            
462
            % "saturated" ramp function for marker disc shape
476
            % "saturated" ramp function for marker disc shape
463
            weight = max(min(1.0, -1.0/(2*w)*(d-markerRadius)+0.5), 0.0);
477
            weight = max(min(1.0, -1.0/(2*w)*(d-markerRadius)+0.5), 0.0);
464
            
478
            
465
            r(k) = x(6)*weight - imVal;
479
            r(k) = x(6)*weight - imVal;
466
            
480
            
467
        end
481
        end
468
        
482
        
469
        for k=1:length(e1NormImCoords)
483
        for k=1:length(e1NormImCoords)
470
 
484
 
471
            % dermine z coordinate on the hypothesized plane
485
            % dermine z coordinate on the hypothesized plane
472
            t = p1n1/([e1NormImCoords(k,:), 1]*n1');
486
            t = p1n1/([e1NormImCoords(k,:), 1]*n1');
473
            
487
            
474
            d = norm(p1 - t*[e1NormImCoords(k,:), 1.0]);
488
            d = norm(p1 - t*[e1NormImCoords(k,:), 1.0]);
475
            
489
            
476
            imVal = double(frame1(e1ImCoords(k,2), e1ImCoords(k,1)));
490
            imVal = double(frame1(e1ImCoords(k,2), e1ImCoords(k,1)));
477
            
491
            
478
            % "saturated" ramp function for marker disc shape
492
            % "saturated" ramp function for marker disc shape
479
            weight = max(min(1.0, -1.0/(2*w)*(d-markerRadius)+0.5), 0.0);
493
            weight = max(min(1.0, -1.0/(2*w)*(d-markerRadius)+0.5), 0.0);
480
            
494
            
481
            r(length(e0NormImCoords)+k) = x(7)*weight - imVal;
495
            r(length(e0NormImCoords)+k) = x(7)*weight - imVal;
482
 
496
 
483
        end
497
        end
484
        
498
        
485
        
499
        
486
%         figure; 
500
%         figure; 
487
%         subplot(1,2,1);
501
%         subplot(1,2,1);
488
%         imagesc(reshape(r(1:length(e0NormImCoords)), 2*margin+1, 2*margin+1), [-50 50]);
502
%         imagesc(reshape(r(1:length(e0NormImCoords)), 2*margin+1, 2*margin+1), [-50 50]);
489
%         subplot(1,2,2);
503
%         subplot(1,2,2);
490
%         imagesc(reshape(r(length(e0NormImCoords)+1:end), 2*margin+1, 2*margin+1), [-50 50]);
504
%         imagesc(reshape(r(length(e0NormImCoords)+1:end), 2*margin+1, 2*margin+1), [-50 50]);
491
%         drawnow;
505
%         drawnow;
492
        
506
        
493
    end
507
    end
494
    
508
    
495
end
509
end
496
 
510
 
497
function E = projectOntoPointCloud(e, P, pointCloud)
511
function E = projectOntoPointCloud(e, P, pointCloud)
498
% Project 2d point coordinates onto pointCloud to find corresponding 3d
512
% Project 2d point coordinates onto pointCloud to find corresponding 3d
499
% point coordinates.
513
% point coordinates.
500
 
514
 
501
    q = [pointCloud ones(size(pointCloud,1),1)]*P;
515
    q = [pointCloud ones(size(pointCloud,1),1)]*P;
502
    q = q(:,1:2)./[q(:,3) q(:,3)];
516
    q = q(:,1:2)./[q(:,3) q(:,3)];
503
 
517
 
504
    E = nan(size(e,1), 3);
518
    E = nan(size(e,1), 3);
505
    
519
    
506
    for i=1:size(e, 1)
520
    for i=1:size(e, 1)
507
        sqDists = sum((q - repmat(e(i,:), size(q, 1), 1)).^2, 2);
521
        sqDists = sum((q - repmat(e(i,:), size(q, 1), 1)).^2, 2);
508
        
522
        
509
        [sqDistsSorted, sortIdx] = sort(sqDists);
523
        [sqDistsSorted, sortIdx] = sort(sqDists);
510
        
524
        
511
        neighbors = (sqDistsSorted < 4.0^2);
525
        neighbors = (sqDistsSorted < 4.0^2);
512
        
526
        
513
        distsSorted = sqrt(sqDistsSorted(neighbors));
527
        distsSorted = sqrt(sqDistsSorted(neighbors));
514
        invDistsSorted = 1.0/distsSorted;
528
        invDistsSorted = 1.0/distsSorted;
515
        sortIdx = sortIdx(neighbors);
529
        sortIdx = sortIdx(neighbors);
516
        
530
        
517
        nNeighbors = sum(neighbors);
531
        nNeighbors = sum(neighbors);
518
        
532
        
519
        if(nNeighbors >= 2)
533
        if(nNeighbors >= 2)
520
            E(i, :) = 0;
534
            E(i, :) = 0;
521
            for j=1:nNeighbors
535
            for j=1:nNeighbors
522
                E(i, :) = E(i, :) + invDistsSorted(j)/sum(invDistsSorted) * pointCloud(sortIdx(j), :);
536
                E(i, :) = E(i, :) + invDistsSorted(j)/sum(invDistsSorted) * pointCloud(sortIdx(j), :);
523
            end
537
            end
524
        end
538
        end
525
            
539
            
526
    end    
540
    end    
527
end
541
end
528
 
542
 
529
function H = Hest_DLT(q1, q2)
543
function H = Hest_DLT(q1, q2)
530
    % Estimate the homography between a set of point correspondences using the 
544
    % Estimate the homography between a set of point correspondences using the 
531
    % direct linear transform algorithm.
545
    % direct linear transform algorithm.
532
    %
546
    %
533
    % Input:
547
    % Input:
534
    %           q1: 3xN matrix of homogenous point coordinates from camera 1. 
548
    %           q1: 3xN matrix of homogenous point coordinates from camera 1. 
535
    %           q2: 3xN matrix of corresponding points from camera 2.
549
    %           q2: 3xN matrix of corresponding points from camera 2.
536
    % Output:
550
    % Output:
537
    %           H: 3x3 matrix. The Fundamental Matrix estimate. 
551
    %           H: 3x3 matrix. The Fundamental Matrix estimate. 
538
    %
552
    %
539
    % Note that N must be at least 4.
553
    % Note that N must be at least 4.
540
    % See derivation in Aanaes, Lecture Notes on Computer Vision, 2011
554
    % See derivation in Aanaes, Lecture Notes on Computer Vision, 2011
541
 
555
 
542
    % Normalize points
556
    % Normalize points
543
    [T1,invT1] = normalizationMat(q1);
557
    [T1,invT1] = normalizationMat(q1);
544
    q1_tilde = T1*q1;
558
    q1_tilde = T1*q1;
545
 
559
 
546
    T2 = normalizationMat(q2);
560
    T2 = normalizationMat(q2);
547
    q2_tilde = T2*q2;
561
    q2_tilde = T2*q2;
548
 
562
 
549
    % DLT estimation
563
    % DLT estimation
550
    N = size(q1_tilde,2);
564
    N = size(q1_tilde,2);
551
    assert(size(q2_tilde,2)==N);
565
    assert(size(q2_tilde,2)==N);
552
 
566
 
553
    B = zeros(3*N,9);
567
    B = zeros(3*N,9);
554
 
568
 
555
    for i=1:N
569
    for i=1:N
556
        q1i = q1_tilde(:,i);
570
        q1i = q1_tilde(:,i);
557
        q2i = q2_tilde(:,i);
571
        q2i = q2_tilde(:,i);
558
        q1_x = [0 -q1i(3) q1i(2); q1i(3) 0 -q1i(1); -q1i(2) q1i(1) 0];
572
        q1_x = [0 -q1i(3) q1i(2); q1i(3) 0 -q1i(1); -q1i(2) q1i(1) 0];
559
        biT = kron(q2i', q1_x); 
573
        biT = kron(q2i', q1_x); 
560
        B(3*(i-1)+1:3*i, :) = biT;
574
        B(3*(i-1)+1:3*i, :) = biT;
561
    end
575
    end
562
 
576
 
563
    [U,S,~] = svd(B');
577
    [U,S,~] = svd(B');
564
 
578
 
565
    [~,idx] = min(diag(S));
579
    [~,idx] = min(diag(S));
566
    h = U(:,idx);
580
    h = U(:,idx);
567
 
581
 
568
    H_tilde = reshape(h, 3, 3);
582
    H_tilde = reshape(h, 3, 3);
569
 
583
 
570
    % Unnormalize H
584
    % Unnormalize H
571
    H = invT1*H_tilde*T2;
585
    H = invT1*H_tilde*T2;
572
 
586
 
573
    % Arbitrarily chose scale
587
    % Arbitrarily chose scale
574
    H = H * 1/H(3,3);
588
    H = H * 1/H(3,3);
575
end
589
end
576
 
590
 
577
function [T,invT] = normalizationMat(q)
591
function [T,invT] = normalizationMat(q)
578
    % Gives a normalization matrix for homogeneous coordinates
592
    % Gives a normalization matrix for homogeneous coordinates
579
    % such that T*q will have zero mean and unit variance.
593
    % such that T*q will have zero mean and unit variance.
580
    % See Aanaes, Computer Vision Lecture Notes 2.8.2
594
    % See Aanaes, Computer Vision Lecture Notes 2.8.2
581
    %
595
    %
582
    % q: (M+1)xN matrix of N MD points in homogenous coordinates
596
    % q: (M+1)xN matrix of N MD points in homogenous coordinates
583
    %
597
    %
584
    % Extended to also efficiently compute the inverse matrix
598
    % Extended to also efficiently compute the inverse matrix
585
    % DTU, 2013, Jakob Wilm
599
    % DTU, 2013, Jakob Wilm
586
 
600
 
587
    [M,N] = size(q);
601
    [M,N] = size(q);
588
    M = M-1;
602
    M = M-1;
589
 
603
 
590
    mu = mean(q(1:M,:),2);
604
    mu = mean(q(1:M,:),2);
591
 
605
 
592
    q_bar = q(1:M,:)-repmat(mu,1,N);
606
    q_bar = q(1:M,:)-repmat(mu,1,N);
593
 
607
 
594
    s = mean(sqrt(diag(q_bar'*q_bar)))/sqrt(2);
608
    s = mean(sqrt(diag(q_bar'*q_bar)))/sqrt(2);
595
 
609
 
596
    T = [eye(M)/s, -mu/s; zeros(1,M) 1];
610
    T = [eye(M)/s, -mu/s; zeros(1,M) 1];
597
 
611
 
598
    invT = [eye(M)*s, mu; zeros(1,M) 1];
612
    invT = [eye(M)*s, mu; zeros(1,M) 1];
599
end
613
end
600
 
614
 
601

Generated by GNU Enscript 1.6.6.
615

Generated by GNU Enscript 1.6.6.
602
 
616
 
603
 
617
 
604
 
618