Subversion Repositories seema-scanner

Rev

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

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

Generated by GNU Enscript 1.6.6.
612

Generated by GNU Enscript 1.6.6.
615
 
613
 
616
 
614
 
617
 
615