Subversion Repositories seema-scanner

Rev

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

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