Subversion Repositories seema-scanner

Rev

Rev 219 | Rev 237 | 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
236 jakw 39
%for i=5:5
211 jakw 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
 
236 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
236 jakw 187
    g = rgb2gray(frame);
188
    g(g>254) = 0;
189
    bw = imbinarize(g, 'adaptive', 'Sensitivity', 10^(-50));
211 jakw 190
    cc = bwconncomp(bw);
191
    rp = regionprops(cc, 'Area', 'Solidity', 'Eccentricity', 'Centroid');
213 jakw 192
    idx = ([rp.Area] > 100 & [rp.Area] < 1000 & [rp.Solidity] > 0.9);
211 jakw 193
 
213 jakw 194
    initialGuesses = cat(1, rp(idx).Centroid);
195
 
196
    [e, ~] = detectMarkersSubpix(frame, initialGuesses, P, pointCloud);
197
 
198
    figure; 
199
    imshow(frame);
200
        hold('on');
201
    plot(e(:,1), e(:,2), 'rx', 'MarkerSize', 15);
202
    drawnow;
211 jakw 203
end
204
 
213 jakw 205
function e = manuallyDetectMarkers(frame, P, pointCloud)
211 jakw 206
 
212 jakw 207
    e = [];
213 jakw 208
	%edges = edge(rgb2gray(frame), 'Canny', [0.08 0.1], 2);
212 jakw 209
 
211 jakw 210
    figure; 
212 jakw 211
    hold('on');
211 jakw 212
    imshow(frame);
212 jakw 213
    title('Close figure to end.');
214
    set(gcf, 'pointer', 'crosshair'); 
215
    set(gcf, 'WindowButtonDownFcn', @clickCallback);
216
 
217
    uiwait;
211 jakw 218
 
213 jakw 219
    function clickCallback(caller, ~)
212 jakw 220
 
221
        p = get(gca, 'CurrentPoint'); 
222
        p = p(1, 1:2);
211 jakw 223
 
213 jakw 224
        [el, ~] = detectMarkersSubpix(frame, p, P, pointCloud);
212 jakw 225
        e = [e; el(:, 1:2)];
213 jakw 226
 
227
        if(not(isempty(el)))
228
            figure(caller);
229
            hold('on');
230
            plot(el(1), el(2), 'rx', 'MarkerSize', 15);
231
        end
212 jakw 232
    end
233
 
234
end
211 jakw 235
 
212 jakw 236
function [e, conf] = detectMarkersSubpix(frame, initGuesses, P, Q)
211 jakw 237
 
212 jakw 238
    % create mask based on morphology
236 jakw 239
    g = rgb2gray(frame);
240
    g(g>254) = 0;
241
    bw = imbinarize(g);
212 jakw 242
    cc = bwconncomp(bw);
243
    labels = labelmatrix(cc);
211 jakw 244
 
212 jakw 245
    % project point cloud into image
246
    q = [Q ones(size(Q,1),1)]*P;
247
    q = q./[q(:,3) q(:,3) q(:,3)];
248
 
213 jakw 249
    e = zeros(size(initGuesses));
250
    conf = zeros(size(initGuesses, 1), 1);
251
 
252
    nMarkersFound = 0;
253
 
212 jakw 254
    for i=1:size(initGuesses, 1)
255
 
256
        labelId = labels(round(initGuesses(i,2)), round(initGuesses(i,1)));
257
        labelMask = (labels == labelId);
258
        labelMask = imdilate(labelMask, strel('disk', 3, 0));
259
 
213 jakw 260
        if(sum(sum(labelMask)) < 10 || sum(sum(labelMask)) > 1000)
261
            continue;
262
        end
263
 
212 jakw 264
        % determine 3D points that are part of the marker
213 jakw 265
        % note: we should probably undistort labelMask
212 jakw 266
        pointMask = false(size(q, 1), 1);
267
        for j=1:size(q,1)
215 jakw 268
            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)
269
                continue;
270
            end
271
 
212 jakw 272
            if(labelMask(round(q(j,2)), round(q(j,1))))
273
                pointMask(j) = true;
274
            end
275
        end
276
 
215 jakw 277
        if(sum(pointMask)) < 10
213 jakw 278
            continue;
279
        end
212 jakw 280
 
213 jakw 281
        % project 3D points onto local plane
282
        [~, sc, ~] = pca(Q(pointMask, :));
283
        Qlocal = sc(:, 1:2);
284
 
285
        % synthetic marker in high res. space
286
        m = zeros(151, 151);
287
        [x, y] = meshgrid(1:151, 1:151);
288
        m((x(:)-76).^2 + (y(:)-76).^2 <= 50^2) = 1.0;
289
 
290
        % relation between marker space (px) and true marker/local plane(mm)
291
        % true marker diameter is 1.75mm
236 jakw 292
        mScale = 101/1.4; %px/mm
213 jakw 293
        mShift = 76; %px
294
 
295
        % build homography from image to marker space
236 jakw 296
        H = fitgeotrans(q(pointMask, 1:2), mScale*Qlocal+mShift,  'projective');
297
        %Hdlt = Hest_DLT([mScale*Qlocal+mShift, ones(size(Qlocal, 1), 1)]', q(pointMask,:)');
298
        %H = projective2d(Hdlt');
213 jakw 299
 
300
        % bring image of marker into marker space
301
        imMarkerSpace = imwarp(frame, H, 'OutputView', imref2d(size(m)));
302
        imMarkerSpace = rgb2gray(im2double(imMarkerSpace));
303
 
304
        %figure; imshowpair(imMarkerSpace, m);
305
 
306
        % perform image registration
214 jakw 307
        % might be better off using subpixel image correlation
308
        [opt, met] = imregconfig('multimodal');
218 jakw 309
        T = imregtform(m, imMarkerSpace, 'translation', opt, met, 'DisplayOptimization', false);
213 jakw 310
 
311
        rege = imwarp(m, T, 'OutputView', imref2d(size(m)));
312
        %figure; imshowpair(imMarkerSpace, rege);
313
 
314
        % measure of correlation
315
        confI = sum(sum(imMarkerSpace .* rege))/sqrt(sum(sum(imMarkerSpace) * sum(sum(rege))));
236 jakw 316
        %confI = 1.0;
213 jakw 317
 
318
        if confI<0.4
319
            continue;
320
        end
321
 
322
        fprintf('Found marker with confidence: %f\n', confI);
323
 
324
        % transform marker space coordinates (76,76) to frame space
325
        el = T.transformPointsForward([76, 76]);
326
        el = H.transformPointsInverse(el);
327
 
328
        nMarkersFound = nMarkersFound+1;
329
        e(nMarkersFound,:) = el;
330
        conf(nMarkersFound) = confI;
211 jakw 331
    end
332
 
213 jakw 333
    e = e(1:nMarkersFound, :);
334
    conf = conf(1:nMarkersFound);
211 jakw 335
end
336
 
212 jakw 337
function E = projectOntoPointCloud(e, P, pointCloud)
211 jakw 338
 
212 jakw 339
    q = [pointCloud ones(size(pointCloud,1),1)]*P;
211 jakw 340
    q = q(:,1:2)./[q(:,3) q(:,3)];
341
 
342
    E = nan(size(e,1), 3);
343
 
344
    for i=1:size(e, 1)
345
        sqDists = sum((q - repmat(e(i,:), size(q, 1), 1)).^2, 2);
346
 
216 jakw 347
        [sqDistsSorted, sortIdx] = sort(sqDists);
211 jakw 348
 
216 jakw 349
        neighbors = (sqDistsSorted < 4.0^2);
350
 
351
        distsSorted = sqrt(sqDistsSorted(neighbors));
352
        invDistsSorted = 1.0/distsSorted;
353
        sortIdx = sortIdx(neighbors);
354
 
355
        nNeighbors = sum(neighbors);
356
 
357
        if(nNeighbors >= 2)
358
            E(i, :) = 0;
359
            for j=1:nNeighbors
360
                E(i, :) = E(i, :) + invDistsSorted(j)/sum(invDistsSorted) * pointCloud(sortIdx(j), :);
361
            end
211 jakw 362
        end
363
 
364
    end    
365
end
366
 
219 jakw 367
function H = Hest_DLT(q1, q2)
368
    % Estimate the homography between a set of point correspondences using the 
369
    % direct linear transform algorithm.
370
    %
371
    % Input:
372
    %           q1: 3xN matrix of homogenous point coordinates from camera 1. 
373
    %           q2: 3xN matrix of corresponding points from camera 2.
374
    % Output:
375
    %           H: 3x3 matrix. The Fundamental Matrix estimate. 
376
    %
377
    % Note that N must be at least 4.
378
    % See derivation in Aanaes, Lecture Notes on Computer Vision, 2011
379
 
380
    % Normalize points
381
    [T1,invT1] = normalizationMat(q1);
382
    q1_tilde = T1*q1;
383
 
384
    T2 = normalizationMat(q2);
385
    q2_tilde = T2*q2;
386
 
387
    % DLT estimation
388
    N = size(q1_tilde,2);
389
    assert(size(q2_tilde,2)==N);
390
 
391
    B = zeros(3*N,9);
392
 
393
    for i=1:N
394
        q1i = q1_tilde(:,i);
395
        q2i = q2_tilde(:,i);
396
        q1_x = [0 -q1i(3) q1i(2); q1i(3) 0 -q1i(1); -q1i(2) q1i(1) 0];
397
        biT = kron(q2i', q1_x); 
398
        B(3*(i-1)+1:3*i, :) = biT;
399
    end
400
 
401
    [U,S,~] = svd(B');
402
 
403
    [~,idx] = min(diag(S));
404
    h = U(:,idx);
405
 
406
    H_tilde = reshape(h, 3, 3);
407
 
408
    % Unnormalize H
409
    H = invT1*H_tilde*T2;
410
 
411
    % Arbitrarily chose scale
412
    H = H * 1/H(3,3);
413
end
414
 
415
function [T,invT] = normalizationMat(q)
416
    % Gives a normalization matrix for homogeneous coordinates
417
    % such that T*q will have zero mean and unit variance.
418
    % See Aanaes, Computer Vision Lecture Notes 2.8.2
419
    %
420
    % q: (M+1)xN matrix of N MD points in homogenous coordinates
421
    %
422
    % Extended to also efficiently compute the inverse matrix
423
    % DTU, 2013, Jakob Wilm
424
 
425
    [M,N] = size(q);
426
    M = M-1;
427
 
428
    mu = mean(q(1:M,:),2);
429
 
430
    q_bar = q(1:M,:)-repmat(mu,1,N);
431
 
432
    s = mean(sqrt(diag(q_bar'*q_bar)))/sqrt(2);
433
 
434
    T = [eye(M)/s, -mu/s; zeros(1,M) 1];
435
 
436
    invT = [eye(M)*s, mu; zeros(1,M) 1];
437
end