Subversion Repositories seema-scanner

Rev

Rev 216 | Rev 219 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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