Subversion Repositories seema-scanner

Rev

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

Rev 216 Rev 218
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
 
11
 
12
calibration = readOpenCVXML(calibrationFileName);
12
calibration = readOpenCVXML(calibrationFileName);
13
 
13
 
14
% correct for Matlab 1-indexing in principle point coordinates
14
% correct for Matlab 1-indexing in principle point coordinates
15
calibration.K0(1:2, 3) = calibration.K0(1:2, 3)+1;
15
calibration.K0(1:2, 3) = calibration.K0(1:2, 3)+1;
16
calibration.K1(1:2, 3) = calibration.K1(1:2, 3)+1;
16
calibration.K1(1:2, 3) = calibration.K1(1:2, 3)+1;
17
 
17
 
18
% full projection matrices in Matlab convention
18
% full projection matrices in Matlab convention
19
P0 = transpose(calibration.K0*[eye(3) zeros(3,1)]);
19
P0 = transpose(calibration.K0*[eye(3) zeros(3,1)]);
20
P1 = transpose(calibration.K1*[calibration.R1 calibration.T1']);
20
P1 = transpose(calibration.K1*[calibration.R1 calibration.T1']);
21
 
21
 
22
% matlab cam params for undistortion
22
% matlab cam params for undistortion
23
camParams0 = cameraParameters('IntrinsicMatrix', calibration.K0', 'RadialDistortion', calibration.k0([1 2 5]), 'TangentialDistortion', calibration.k0([3 4]));
23
camParams0 = cameraParameters('IntrinsicMatrix', calibration.K0', 'RadialDistortion', calibration.k0([1 2 5]), 'TangentialDistortion', calibration.k0([3 4]));
24
camParams1 = cameraParameters('IntrinsicMatrix', calibration.K1', 'RadialDistortion', calibration.k1([1 2 5]), 'TangentialDistortion', calibration.k1([3 4]));
24
camParams1 = cameraParameters('IntrinsicMatrix', calibration.K1', 'RadialDistortion', calibration.k1([1 2 5]), 'TangentialDistortion', calibration.k1([3 4]));
25
 
25
 
26
% matlab struct for triangulation
26
% matlab struct for triangulation
27
camStereoParams = stereoParameters(camParams0, camParams1, calibration.R1', calibration.T1');
27
camStereoParams = stereoParameters(camParams0, camParams1, calibration.R1', calibration.T1');
28
 
28
 
29
nSubScans = length(initialAlign);
29
nSubScans = length(initialAlign);
30
 
30
 
31
% 3D coordinates of markers in local camera frame
31
% 3D coordinates of markers in local camera frame
32
E = cell(nSubScans, 1);
32
E = cell(nSubScans, 1);
33
 
33
 
34
% 3D coordinates of markers in global initial alignment
34
% 3D coordinates of markers in global initial alignment
35
Eg = cell(size(E));
35
Eg = cell(size(E));
36
 
36
 
37
% find 3D markers coordinates 
37
% find 3D markers coordinates 
38
for i=1:nSubScans
38
for i=1:nSubScans
39
 
39
 
40
    % load point cloud
40
    % load point cloud
41
    pc = pcread(initialAlign(i).FileName);
41
    pc = pcread(initialAlign(i).FileName);
42
    Q = pc.Location;
42
    Q = pc.Location;
43
    idString = strsplit(initialAlign(i).FileName, {'.ply', '_'});
43
    idString = strsplit(initialAlign(i).FileName, {'.ply', '_'});
44
    idString = idString{end-1};
44
    idString = idString{end-1};
45
    
45
    
46
    % load white frames
46
    % load white frames
47
    scanDir = strsplit(initialAlign(i).FileName, '/');
47
    scanDir = strsplit(initialAlign(i).FileName, '/');
48
    scanDir = fullfile(scanDir{1:end-1});
48
    scanDir = fullfile(scanDir{1:end-1});
49
    frame0 = imread(fullfile(scanDir, ['sequence_' idString], 'frames0_0.png'));
49
    frame0 = imread(fullfile(scanDir, ['sequence_' idString], 'frames0_0.png'));
50
    frame1 = imread(fullfile(scanDir, ['sequence_' idString], 'frames1_0.png'));
50
    frame1 = imread(fullfile(scanDir, ['sequence_' idString], 'frames1_0.png'));
51
 
51
 
52
    e0Coords = autoDetectMarkers(frame0, P0, Q);
52
    e0Coords = autoDetectMarkers(frame0, P0, Q);
53
    e1Coords = autoDetectMarkers(frame1, P1, Q);
53
    e1Coords = autoDetectMarkers(frame1, P1, Q);
54
    
54
    
55
    %e0Coords = manuallyDetectMarkers(frame0, P0, Q);
55
    %e0Coords = manuallyDetectMarkers(frame0, P0, Q);
56
    %e1Coords = manuallyDetectMarkers(frame1, P1, Q);
56
    %e1Coords = manuallyDetectMarkers(frame1, P1, Q);
57
    
57
    
58
    e0Coords = undistortPoints(e0Coords, camParams0);
58
    %e0Coords = undistortPoints(e0Coords, camParams0);
59
    e1Coords = undistortPoints(e1Coords, camParams1);
59
    %e1Coords = undistortPoints(e1Coords, camParams1);
60
 
60
 
61
    % match ellipse candidates between cameras based on projection
61
    % match ellipse candidates between cameras based on projection
62
    E0 = projectOntoPointCloud(e0Coords, P0, Q);
62
    E0 = projectOntoPointCloud(e0Coords, P0, Q);
63
    E1 = projectOntoPointCloud(e1Coords, P1, Q);
63
    E1 = projectOntoPointCloud(e1Coords, P1, Q);
64
 
64
 
65
    matchedPairs = nan(size(E0, 1), 2);
65
    matchedPairs = nan(size(E0, 1), 2);
66
    nMatchedPairs = 0;
66
    nMatchedPairs = 0;
67
    for j=1:size(E0, 1)
67
    for j=1:size(E0, 1)
68
        
68
        
69
        % should use pdist2 instead..
69
        % should use pdist2 instead..
70
        sqDists = sum((E1 - repmat(E0(j,:), size(E1, 1), 1)).^2, 2);
70
        sqDists = sum((E1 - repmat(E0(j,:), size(E1, 1), 1)).^2, 2);
71
        
71
        
72
        [minSqDist, minSqDistIdx] = min(sqDists);
72
        [minSqDist, minSqDistIdx] = min(sqDists);
73
 
73
 
74
        if(minSqDist < 1^2)
74
        if(minSqDist < 1^2)
75
            nMatchedPairs = nMatchedPairs + 1;
75
            nMatchedPairs = nMatchedPairs + 1;
76
            matchedPairs(nMatchedPairs, :) = [j, minSqDistIdx];
76
            matchedPairs(nMatchedPairs, :) = [j, minSqDistIdx];
77
        end
77
        end
78
    end
78
    end
79
    matchedPairs = matchedPairs(1:nMatchedPairs, :);
79
    matchedPairs = matchedPairs(1:nMatchedPairs, :);
80
    
80
    
81
    % triangulate marker centers (lens correction has been performed)
81
    % triangulate marker centers (lens correction has been performed)
82
    [E{i}, e] = triangulate(e0Coords(matchedPairs(:, 1),:), e1Coords(matchedPairs(:, 2),:), camStereoParams);
82
    [E{i}, e] = triangulate(e0Coords(matchedPairs(:, 1),:), e1Coords(matchedPairs(:, 2),:), camStereoParams);
83
    E{i} = E{i}(e<1.0, :);
83
    E{i} = E{i}(e<3.0, :);
-
 
84
    display(e);
84
    
85
    
85
    % write point cloud with marker (debugging)
86
    % write point cloud with marker (debugging)
86
    pcDebug = pointCloud([pc.Location; E{i}], 'Color', [pc.Color; repmat([255, 0, 0], size(E{i}, 1), 1)]);
87
    pcDebug = pointCloud([pc.Location; E{i}], 'Color', [pc.Color; repmat([255, 0, 0], size(E{i}, 1), 1)]);
87
    pcwrite(pcDebug, 'pcDebug.ply');
88
    pcwrite(pcDebug, 'pcDebug.ply');
88
    
89
    
89
    % bring markers into initial alignment
90
    % bring markers into initial alignment
90
    [U,~,V] = svd(initialAlign(i).Rotation);
91
    [U,~,V] = svd(initialAlign(i).Rotation);
91
    Ri = U*V';
92
    Ri = U*V';
92
    Ti = initialAlign(i).Translation;
93
    Ti = initialAlign(i).Translation;
93
    
94
    
94
    Eg{i} = E{i}*Ri' + repmat(Ti', size(E{i}, 1), 1);
95
    Eg{i} = E{i}*Ri' + repmat(Ti', size(E{i}, 1), 1);
95
end
96
end
96
 
97
 
97
% show found markers in initial alignment
98
% show found markers in initial alignment
98
figure;
99
figure;
99
hold('on');
100
hold('on');
100
for i=1:nSubScans
101
for i=1:nSubScans
101
    % fix Ri to be orthogonal
102
    % fix Ri to be orthogonal
102
    [U,~,V] = svd(initialAlign(i).Rotation);
103
    [U,~,V] = svd(initialAlign(i).Rotation);
103
    Ri = U*V';
104
    Ri = U*V';
104
    
105
    
105
    % bring point cloud into initial alignment
106
    % bring point cloud into initial alignment
106
    pc = pcread(initialAlign(i).FileName);
107
    pc = pcread(initialAlign(i).FileName);
107
    tform = affine3d([Ri' [0;0;0]; initialAlign(i).Translation' 1]);
108
    tform = affine3d([Ri' [0;0;0]; initialAlign(i).Translation' 1]);
108
    pcg = pctransform(pc, tform);
109
    pcg = pctransform(pc, tform);
109
   
110
   
110
    pcshow(pcg);
111
    pcshow(pcg);
111
    xlabel('x');
112
    xlabel('x');
112
    ylabel('y');
113
    ylabel('y');
113
    zlabel('z');
114
    zlabel('z');
114
    
115
    
115
    plot3(Eg{i}(:,1), Eg{i}(:,2), Eg{i}(:,3), '.', 'MarkerSize', 15);
116
    plot3(Eg{i}(:,1), Eg{i}(:,2), Eg{i}(:,3), '.', 'MarkerSize', 15);
116
    title('Initial Alignment');
117
    title('Initial Alignment');
117
end
118
end
118
 
119
 
119
% match markers between poses using initial alignment
120
% match markers between poses using initial alignment
120
Pg = {};
121
Pg = {};
121
P = {};
122
P = {};
122
for i=1:nSubScans
123
for i=1:nSubScans
123
    for j=1:size(Eg{i}, 1)
124
    for j=1:size(Eg{i}, 1)
124
        pg = Eg{i}(j,:);
125
        pg = Eg{i}(j,:);
125
        p = E{i}(j,:);
126
        p = E{i}(j,:);
126
        matched = false;
127
        matched = false;
127
        for k=1:size(Pg, 2)
128
        for k=1:size(Pg, 2)
128
            clusterCenter = mean(cat(1, Pg{:,k}), 1);
129
            clusterCenter = mean(cat(1, Pg{:,k}), 1);
129
            if(sum((pg - clusterCenter).^2) < 3^2)
130
            if(sum((pg - clusterCenter).^2) < 3^2)
130
                % store in global frame
131
                % store in global frame
131
                Pg{i,k} = pg;
132
                Pg{i,k} = pg;
132
                % store in local frame
133
                % store in local frame
133
                P{i,k} = p;
134
                P{i,k} = p;
134
                matched = true;
135
                matched = true;
135
                break;
136
                break;
136
            end
137
            end
137
        end
138
        end
138
        % create new cluster
139
        % create new cluster
139
        if(not(matched))
140
        if(not(matched))
140
            Pg{i,end+1} = pg;
141
            Pg{i,end+1} = pg;
141
            P{i,end+1} = p;
142
            P{i,end+1} = p;
142
        end 
143
        end 
143
    end
144
    end
144
end
145
end
145
 
146
 
146
% run optimization
147
% run optimization
147
alignment = groupwiseOrthogonalProcrustes(P, initialAlign);
148
alignment = groupwiseOrthogonalProcrustes(P, initialAlign);
148
 
149
 
149
% show found markers in optimized alignment
150
% show found markers in optimized alignment
150
figure;
151
figure;
151
hold('on');
152
hold('on');
152
for i=1:nSubScans
153
for i=1:nSubScans
-
 
154
    % fix Ri to be orthogonal
153
    Ri = alignment(i).Rotation;
155
    [U,~,V] = svd(alignment(i).Rotation);
-
 
156
    Ri = U*V';
154
    Ti = alignment(i).Translation;
157
    Ti = alignment(i).Translation;
155
    
158
    
156
    Ea = E{i}*Ri' + repmat(Ti', size(E{i}, 1), 1);
159
    Ea = E{i}*Ri' + repmat(Ti', size(E{i}, 1), 1);
157
    
160
    
158
    % bring point cloud into optimized alignment
161
    % bring point cloud into optimized alignment
159
    pc = pcread(initialAlign(i).FileName);
162
    pc = pcread(initialAlign(i).FileName);
160
    tform = affine3d([Ri' [0;0;0]; initialAlign(i).Translation' 1]);
163
    tform = affine3d([Ri' [0;0;0]; initialAlign(i).Translation' 1]);
161
    pcg = pctransform(pc, tform);
164
    pcg = pctransform(pc, tform);
162
   
165
   
163
    pcshow(pcg);
166
    pcshow(pcg);
164
    xlabel('x');
167
    xlabel('x');
165
    ylabel('y');
168
    ylabel('y');
166
    zlabel('z');
169
    zlabel('z');
167
    
170
    
168
    plot3(Ea(:,1), Ea(:,2), Ea(:,3), '.', 'MarkerSize', 15);
171
    plot3(Ea(:,1), Ea(:,2), Ea(:,3), '.', 'MarkerSize', 15);
169
    title('Optimized Alignment');
172
    title('Optimized Alignment');
170
end
173
end
171
 
174
 
172
% write to ALN file
175
% write to ALN file
173
for i=1:length(alignment)
176
for i=1:length(alignment)
174
    alignment(i).FileName = initialAlign(i).FileName;
177
    alignment(i).FileName = initialAlign(i).FileName;
175
end
178
end
176
 
179
 
177
writeMeshLabALN(alignment, strrep(alnFileName, '.aln', 'Optimized.aln'));
180
writeMeshLabALN(alignment, strrep(alnFileName, '.aln', 'Optimized.aln'));
178
 
181
 
179
end
182
end
180
 
183
 
181
function e = autoDetectMarkers(frame, P, pointCloud)
184
function e = autoDetectMarkers(frame, P, pointCloud)
182
 
185
 
183
    % create mask based on morphology
186
    % create mask based on morphology
184
    bw = imbinarize(rgb2gray(frame));
187
    bw = imbinarize(rgb2gray(frame));
185
    cc = bwconncomp(bw);
188
    cc = bwconncomp(bw);
186
    rp = regionprops(cc, 'Area', 'Solidity', 'Eccentricity', 'Centroid');
189
    rp = regionprops(cc, 'Area', 'Solidity', 'Eccentricity', 'Centroid');
187
    idx = ([rp.Area] > 100 & [rp.Area] < 1000 & [rp.Solidity] > 0.9);
190
    idx = ([rp.Area] > 100 & [rp.Area] < 1000 & [rp.Solidity] > 0.9);
188
    
191
    
189
    initialGuesses = cat(1, rp(idx).Centroid);
192
    initialGuesses = cat(1, rp(idx).Centroid);
190
 
193
 
191
    [e, ~] = detectMarkersSubpix(frame, initialGuesses, P, pointCloud);
194
    [e, ~] = detectMarkersSubpix(frame, initialGuesses, P, pointCloud);
192
 
195
 
193
    figure; 
196
    figure; 
194
    imshow(frame);
197
    imshow(frame);
195
        hold('on');
198
        hold('on');
196
    plot(e(:,1), e(:,2), 'rx', 'MarkerSize', 15);
199
    plot(e(:,1), e(:,2), 'rx', 'MarkerSize', 15);
197
    drawnow;
200
    drawnow;
198
end
201
end
199
 
202
 
200
function e = manuallyDetectMarkers(frame, P, pointCloud)
203
function e = manuallyDetectMarkers(frame, P, pointCloud)
201
    
204
    
202
    e = [];
205
    e = [];
203
	%edges = edge(rgb2gray(frame), 'Canny', [0.08 0.1], 2);
206
	%edges = edge(rgb2gray(frame), 'Canny', [0.08 0.1], 2);
204
 
207
 
205
    figure; 
208
    figure; 
206
    hold('on');
209
    hold('on');
207
    imshow(frame);
210
    imshow(frame);
208
    title('Close figure to end.');
211
    title('Close figure to end.');
209
    set(gcf, 'pointer', 'crosshair'); 
212
    set(gcf, 'pointer', 'crosshair'); 
210
    set(gcf, 'WindowButtonDownFcn', @clickCallback);
213
    set(gcf, 'WindowButtonDownFcn', @clickCallback);
211
    
214
    
212
    uiwait;
215
    uiwait;
213
 
216
 
214
    function clickCallback(caller, ~)
217
    function clickCallback(caller, ~)
215
        
218
        
216
        p = get(gca, 'CurrentPoint'); 
219
        p = get(gca, 'CurrentPoint'); 
217
        p = p(1, 1:2);
220
        p = p(1, 1:2);
218
 
221
 
219
        [el, ~] = detectMarkersSubpix(frame, p, P, pointCloud);
222
        [el, ~] = detectMarkersSubpix(frame, p, P, pointCloud);
220
        e = [e; el(:, 1:2)];
223
        e = [e; el(:, 1:2)];
221
        
224
        
222
        if(not(isempty(el)))
225
        if(not(isempty(el)))
223
            figure(caller);
226
            figure(caller);
224
            hold('on');
227
            hold('on');
225
            plot(el(1), el(2), 'rx', 'MarkerSize', 15);
228
            plot(el(1), el(2), 'rx', 'MarkerSize', 15);
226
        end
229
        end
227
    end
230
    end
228
    
231
    
229
end
232
end
230
 
233
 
231
function [e, conf] = detectMarkersSubpix(frame, initGuesses, P, Q)
234
function [e, conf] = detectMarkersSubpix(frame, initGuesses, P, Q)
232
 
235
 
233
    % create mask based on morphology
236
    % create mask based on morphology
234
    bw = imbinarize(rgb2gray(frame));
237
    bw = imbinarize(rgb2gray(frame));
235
    cc = bwconncomp(bw);
238
    cc = bwconncomp(bw);
236
    labels = labelmatrix(cc);
239
    labels = labelmatrix(cc);
237
 
240
 
238
    % project point cloud into image
241
    % project point cloud into image
239
    q = [Q ones(size(Q,1),1)]*P;
242
    q = [Q ones(size(Q,1),1)]*P;
240
    q = q./[q(:,3) q(:,3) q(:,3)];
243
    q = q./[q(:,3) q(:,3) q(:,3)];
241
    
244
    
242
    e = zeros(size(initGuesses));
245
    e = zeros(size(initGuesses));
243
    conf = zeros(size(initGuesses, 1), 1);
246
    conf = zeros(size(initGuesses, 1), 1);
244
    
247
    
245
    nMarkersFound = 0;
248
    nMarkersFound = 0;
246
    
249
    
247
    for i=1:size(initGuesses, 1)
250
    for i=1:size(initGuesses, 1)
248
        
251
        
249
        labelId = labels(round(initGuesses(i,2)), round(initGuesses(i,1)));
252
        labelId = labels(round(initGuesses(i,2)), round(initGuesses(i,1)));
250
        labelMask = (labels == labelId);
253
        labelMask = (labels == labelId);
251
        labelMask = imdilate(labelMask, strel('disk', 3, 0));
254
        labelMask = imdilate(labelMask, strel('disk', 3, 0));
252
        
255
        
253
        if(sum(sum(labelMask)) < 10 || sum(sum(labelMask)) > 1000)
256
        if(sum(sum(labelMask)) < 10 || sum(sum(labelMask)) > 1000)
254
            continue;
257
            continue;
255
        end
258
        end
256
        
259
        
257
        % determine 3D points that are part of the marker
260
        % determine 3D points that are part of the marker
258
        % note: we should probably undistort labelMask
261
        % note: we should probably undistort labelMask
259
        pointMask = false(size(q, 1), 1);
262
        pointMask = false(size(q, 1), 1);
260
        for j=1:size(q,1)
263
        for j=1:size(q,1)
261
            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)
264
            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)
262
                continue;
265
                continue;
263
            end
266
            end
264
            
267
            
265
            if(labelMask(round(q(j,2)), round(q(j,1))))
268
            if(labelMask(round(q(j,2)), round(q(j,1))))
266
                pointMask(j) = true;
269
                pointMask(j) = true;
267
            end
270
            end
268
        end
271
        end
269
        
272
        
270
        if(sum(pointMask)) < 10
273
        if(sum(pointMask)) < 10
271
            continue;
274
            continue;
272
        end
275
        end
273
        
276
        
274
        % project 3D points onto local plane
277
        % project 3D points onto local plane
275
        [~, sc, ~] = pca(Q(pointMask, :));
278
        [~, sc, ~] = pca(Q(pointMask, :));
276
        Qlocal = sc(:, 1:2);
279
        Qlocal = sc(:, 1:2);
277
        
280
        
278
        % synthetic marker in high res. space
281
        % synthetic marker in high res. space
279
        m = zeros(151, 151);
282
        m = zeros(151, 151);
280
        [x, y] = meshgrid(1:151, 1:151);
283
        [x, y] = meshgrid(1:151, 1:151);
281
        m((x(:)-76).^2 + (y(:)-76).^2 <= 50^2) = 1.0;
284
        m((x(:)-76).^2 + (y(:)-76).^2 <= 50^2) = 1.0;
282
        
285
        
283
        % relation between marker space (px) and true marker/local plane(mm)
286
        % relation between marker space (px) and true marker/local plane(mm)
284
        % true marker diameter is 1.75mm
287
        % true marker diameter is 1.75mm
285
        mScale = 101/1.8; %px/mm
288
        mScale = 101/1.8; %px/mm
286
        mShift = 76; %px
289
        mShift = 76; %px
287
        
290
        
288
        % build homography from image to marker space
291
        % build homography from image to marker space
289
        H = fitgeotrans(q(pointMask, 1:2), mScale*Qlocal+mShift,  'projective');
292
        H = fitgeotrans(q(pointMask, 1:2), mScale*Qlocal+mShift,  'projective');
290
        
293
        
291
        % bring image of marker into marker space
294
        % bring image of marker into marker space
292
        imMarkerSpace = imwarp(frame, H, 'OutputView', imref2d(size(m)));
295
        imMarkerSpace = imwarp(frame, H, 'OutputView', imref2d(size(m)));
293
        imMarkerSpace = rgb2gray(im2double(imMarkerSpace));
296
        imMarkerSpace = rgb2gray(im2double(imMarkerSpace));
294
        
297
        
295
        %figure; imshowpair(imMarkerSpace, m);
298
        %figure; imshowpair(imMarkerSpace, m);
296
        
299
        
297
        % perform image registration
300
        % perform image registration
298
        % might be better off using subpixel image correlation
301
        % might be better off using subpixel image correlation
299
        [opt, met] = imregconfig('multimodal');
302
        [opt, met] = imregconfig('multimodal');
300
        T = imregtform(m, imMarkerSpace, 'translation', opt, met, 'DisplayOptimization', true);
303
        T = imregtform(m, imMarkerSpace, 'translation', opt, met, 'DisplayOptimization', false);
301
        
304
        
302
        rege = imwarp(m, T, 'OutputView', imref2d(size(m)));
305
        rege = imwarp(m, T, 'OutputView', imref2d(size(m)));
303
        %figure; imshowpair(imMarkerSpace, rege);
306
        %figure; imshowpair(imMarkerSpace, rege);
304
        
307
        
305
        % measure of correlation
308
        % measure of correlation
306
        confI = sum(sum(imMarkerSpace .* rege))/sqrt(sum(sum(imMarkerSpace) * sum(sum(rege))));
309
        confI = sum(sum(imMarkerSpace .* rege))/sqrt(sum(sum(imMarkerSpace) * sum(sum(rege))));
307
        
310
        
308
        if confI<0.4
311
        if confI<0.4
309
            continue;
312
            continue;
310
        end
313
        end
311
        
314
        
312
        fprintf('Found marker with confidence: %f\n', confI);
315
        fprintf('Found marker with confidence: %f\n', confI);
313
            
316
            
314
        % transform marker space coordinates (76,76) to frame space
317
        % transform marker space coordinates (76,76) to frame space
315
        el = T.transformPointsForward([76, 76]);
318
        el = T.transformPointsForward([76, 76]);
316
        el = H.transformPointsInverse(el);
319
        el = H.transformPointsInverse(el);
317
        
320
        
318
        nMarkersFound = nMarkersFound+1;
321
        nMarkersFound = nMarkersFound+1;
319
        e(nMarkersFound,:) = el;
322
        e(nMarkersFound,:) = el;
320
        conf(nMarkersFound) = confI;
323
        conf(nMarkersFound) = confI;
321
    end
324
    end
322
    
325
    
323
    e = e(1:nMarkersFound, :);
326
    e = e(1:nMarkersFound, :);
324
    conf = conf(1:nMarkersFound);
327
    conf = conf(1:nMarkersFound);
325
end
328
end
326
 
329
 
327
function E = projectOntoPointCloud(e, P, pointCloud)
330
function E = projectOntoPointCloud(e, P, pointCloud)
328
 
331
 
329
    q = [pointCloud ones(size(pointCloud,1),1)]*P;
332
    q = [pointCloud ones(size(pointCloud,1),1)]*P;
330
    q = q(:,1:2)./[q(:,3) q(:,3)];
333
    q = q(:,1:2)./[q(:,3) q(:,3)];
331
 
334
 
332
    E = nan(size(e,1), 3);
335
    E = nan(size(e,1), 3);
333
    
336
    
334
    for i=1:size(e, 1)
337
    for i=1:size(e, 1)
335
        sqDists = sum((q - repmat(e(i,:), size(q, 1), 1)).^2, 2);
338
        sqDists = sum((q - repmat(e(i,:), size(q, 1), 1)).^2, 2);
336
        
339
        
337
        [sqDistsSorted, sortIdx] = sort(sqDists);
340
        [sqDistsSorted, sortIdx] = sort(sqDists);
338
        
341
        
339
        neighbors = (sqDistsSorted < 4.0^2);
342
        neighbors = (sqDistsSorted < 4.0^2);
340
        
343
        
341
        distsSorted = sqrt(sqDistsSorted(neighbors));
344
        distsSorted = sqrt(sqDistsSorted(neighbors));
342
        invDistsSorted = 1.0/distsSorted;
345
        invDistsSorted = 1.0/distsSorted;
343
        sortIdx = sortIdx(neighbors);
346
        sortIdx = sortIdx(neighbors);
344
        
347
        
345
        nNeighbors = sum(neighbors);
348
        nNeighbors = sum(neighbors);
346
        
349
        
347
        if(nNeighbors >= 2)
350
        if(nNeighbors >= 2)
348
            E(i, :) = 0;
351
            E(i, :) = 0;
349
            for j=1:nNeighbors
352
            for j=1:nNeighbors
350
                E(i, :) = E(i, :) + invDistsSorted(j)/sum(invDistsSorted) * pointCloud(sortIdx(j), :);
353
                E(i, :) = E(i, :) + invDistsSorted(j)/sum(invDistsSorted) * pointCloud(sortIdx(j), :);
351
            end
354
            end
352
        end
355
        end
353
            
356
            
354
    end    
357
    end    
355
end
358
end
356
 
359
 
357
 
360