source: proiecte/pmake3d/make3d_original/Make3dSingleImageStanford_version0.1/LearningCode/Inference/ReportPlaneParaMRF_Conditioned_trianglate.m @ 37

Last change on this file since 37 was 37, checked in by (none), 14 years ago

Added original make3d

File size: 50.9 KB
Line 
1% *  This code was used in the following articles:
2% *  [1] Learning 3-D Scene Structure from a Single Still Image,
3% *      Ashutosh Saxena, Min Sun, Andrew Y. Ng,
4% *      In ICCV workshop on 3D Representation for Recognition (3dRR-07), 2007.
5% *      (best paper)
6% *  [2] 3-D Reconstruction from Sparse Views using Monocular Vision,
7% *      Ashutosh Saxena, Min Sun, Andrew Y. Ng,
8% *      In ICCV workshop on Virtual Representations and Modeling
9% *      of Large-scale environments (VRML), 2007.
10% *  [3] 3-D Depth Reconstruction from a Single Still Image,
11% *      Ashutosh Saxena, Sung H. Chung, Andrew Y. Ng.
12% *      International Journal of Computer Vision (IJCV), Aug 2007.
13% *  [6] Learning Depth from Single Monocular Images,
14% *      Ashutosh Saxena, Sung H. Chung, Andrew Y. Ng.
15% *      In Neural Information Processing Systems (NIPS) 18, 2005.
16% *
17% *  These articles are available at:
18% *  http://make3d.stanford.edu/publications
19% *
20% *  We request that you cite the papers [1], [3] and [6] in any of
21% *  your reports that uses this code.
22% *  Further, if you use the code in image3dstiching/ (multiple image version),
23% *  then please cite [2].
24% * 
25% *  If you use the code in third_party/, then PLEASE CITE and follow the
26% *  LICENSE OF THE CORRESPONDING THIRD PARTY CODE.
27% *
28% *  Finally, this code is for non-commercial use only.  For further
29% *  information and to obtain a copy of the license, see
30% *
31% *  http://make3d.stanford.edu/publications/code
32% *
33% *  Also, the software distributed under the License is distributed on an
34% * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
35% *  express or implied.   See the License for the specific language governing
36% *  permissions and limitations under the License.
37% *
38% */
39function  [Position3DFited FitDepthPPCP] = ReportPlaneParaMRF_Conditioned_trianglate...
40          (Default, Rotation, Translation, appendOpt, ...
41          RayMatched, ClosestDepth, SupMatched, ...
42          SampledGroundRayMatched, SampledGroundClosestDepth, SampledGroundSupMatched, ...
43          DepthFolder,...
44          Sup, SupOri, MedSup,depthMap,VarMap,RayOri, Ray, SupNeighborTable,...
45          MedRay,maskSky,maskG,Algo,k, CornerList, OccluList,...
46          MultiScaleSupTable, StraightLineTable, HBrokeBook, VBrokeBook,previoslyStored,...
47          baseline, CoordinateFromRef, y0);
48% This function runs the RMF over the plane parameter of each superpixels
49
50if nargin <20
51   baseline = 0;
52end
53if isempty(CoordinateFromRef)
54   CoordinateFromRef = eye(3);
55end
56solverVerboseLevel = 0;
57
58inferenceTime = tic;
59
60fprintf(['\n     : Building Matrices....       ']);
61
62% initialize parameters
63GridFlag = 0;
64NOYALMIP = 1;
65NoSecondStep = 0;
66Dual = false;
67displayFlag = false;
68RenderVrmlFlag = true;
69PlaneParaSegmentationFlag = false;
70
71scale = 1;
72StickHori = 5;  %0.1; % sticking power in horizontal direction
73StickVert = 10;     % sticking power in vertical direction
74Center = 2; % Co-Planar weight at the Center of each superpixel
75TriangulatedWeight = 20;
76SampledGroundWeight = 10;
77GroundLevelWright = 500;
78HoriConf = 1; % set the confidant of the learned depth at the middle in Horizontal direction of the image
79VertConf = 0.01; % set the confidant of the learned depth at the top of the image
80BandWith = 1; % Nov29 1 Nov30 0.1 check result change to 0.1 12/1 0.1 lost detail
81mapVert = linspace(VertConf,1,Default.VertYNuDepth); % modeling the gravity prior
82mapHori = [linspace(HoriConf,1,round(Default.HoriXNuDepth/2)) fliplr(linspace(HoriConf,1,Default.HoriXNuDepth-round(Default.HoriXNuDepth/2)))];
83
84% ========set the range of depth that our model in
85ClosestDist = 1;
86% set the FarestDist to very 5 times to median depth
87FarestDist = 1.5*median(depthMap(:)); % tried on university % nogood effect but keep it since usually it the rangelike this   % change to 1.5 for church
88% ================================================
89
90ceiling = 0*Default.VertYNuDepth; % set the position of the ceiling, related to No plane coming back constrain % changed for newchurch
91Name{1} = 'FraWOPri';
92Name{2} = 'FraCoP';
93if isempty(MultiScaleSupTable)
94   Name{3} = 'Var_FraStickCoP';
95else
96   Name{3} = 'Var_FraStickCoPSTasCoP';
97end
98if ~isempty(MultiScaleSupTable)
99   MultiScaleFlag = true;
100   WeiV = 2*ones(1,size(MultiScaleSupTable,2)-1);
101else
102   MultiScaleFlag = false;
103   WeiV = 1;
104end
105WeiV(1,1:2:end) = 6; % emphasize the middle scale three times smaller than large scale
106WeiV = WeiV./sum(WeiV);% normalize if pair of superpixels have same index in all the scale, their weight will be 10
107ShiftStick = -.1;  % between -1 and 0, more means more smoothing.
108ShiftCoP = -.5;  % between -1 and 0, more means more smoothing.
109gravity =true; % if true, apply the HoriConf and VertConf linear scale weight
110CoPST = true; % if true, apply the Straight line prior as the Co-Planar constrain
111
112%ConerImprove = false;
113%FractionalDepthError = true;
114
115
116% get rid of the error point and sky point in the depthMap
117% set every depth bigger than FarestDistmeter to FarestDistmeters
118%CleanedDepthMap = (depthMapif ~previoslyStored >80).*medfilt2(depthMap,[4 4])+(depthMap<=80).*depthMap;
119CleanedDepthMap = depthMap;
120%CleanedDepthMap(depthMap>FarestDist) = FarestDist; % don't clean the point >80 sometimes it occlusion
121%disp('Nu of depthMap>FarestDist');
122%sum(sum(depthMap>FarestDist))
123CleanedDepthMap(depthMap>FarestDist) = NaN; % don't clean the point >80 sometimes it occlusion
124Posi3D = im_cr2w_cr(CleanedDepthMap,permute(Ray,[2 3 1]));
125
126if ~previoslyStored
127
128   %NewMap = [rand(max(Sup(:)),3); [0 0 0]];
129   
130   % Clean the Sup near sky
131   maskSky = Sup == 0;
132   maskSkyEroded = imerode(maskSky, strel('disk', 4) );
133   SupEpand = ExpandSup2Sky(Sup,maskSkyEroded);
134   NuPatch = Default.HoriXNuDepth*Default.VertYNuDepth-sum(maskSky(:));
135
136   NuSup = setdiff(unique(Sup)',0);
137   NuSup = sort(NuSup);
138   NuSupSize = size(NuSup,2);
139
140   % Sup index and planeParameter index inverse map
141   Sup2Para = sparse(1,max(Sup(:)));
142   Sup2Para(NuSup) = 1:NuSupSize;
143
144   % constructinf the Straight line prior matrix Will be add in the CoPlane matrix
145   NuLine = size(StraightLineTable,2);
146   CoPSTList = [];
147
148   for i = 1:NuLine
149       L = StraightLineTable{i};
150       X = L(1:(end-1))';
151       Y = L(2:end)';
152       if isempty(X)
153          continue;
154       end
155       for j = 1:size(X,1)
156           if X(j)~=Y(j)
157              CoPSTList = [CoPSTList; X(j) Y(j)];
158           end
159       end
160   end
161end
162
163% Generate the Matrix for MRF
164 % ===========================================================================================================================================
165groundThreshold = cos([ zeros(1, Default.VertYNuDepth - ceil(Default.VertYNuDepth/2)+10) ...
166                                linspace(0,15,ceil(Default.VertYNuDepth/2)-10)]*pi/180);
167    %  v1 15 v2 20 too big v3 20 to ensure non misclassified as ground.
168    %  verticalThreshold = cos(linspace(5,55,Default.VertYNuDepth)*pi/180); % give a vector of size 55 in top to down :
169verticalThreshold = cos([ 5*ones(1,Default.VertYNuDepth - ceil(Default.VertYNuDepth/2)) ...
170                                linspace(5,55,ceil(Default.VertYNuDepth/2))]*pi/180);
171        % give a vector of size 55 in top to down :
172        % 50 means suface norm away from y axis more than 50 degree
173 % ===========================================================================================================================================
174
175PosiM = sparse(0,0);
176VarM = sparse(0,0);
177RayMd = sparse(0,0);
178RayAllOriM = sparse(0,0);
179RayAllM = sparse(0,0);
180RayMtilt = sparse(0,0);
181RayMCent = sparse(0,0);
182DepthInverseMCent = [];
183DepthInverseM = [];
184YPointer = [];
185YPosition = [];
186beta = [];
187EmptyIndex = [];
188
189for i = NuSup
190%    mask = Sup ==i;
191    mask = SupEpand ==i; % include the Ray that will be use to expand the NonSky
192    RayAllOriM = blkdiag( RayAllOriM, RayOri(:,mask)');
193    RayAllM = blkdiag( RayAllM, Ray(:,mask)');
194    mask = Sup ==i; % Not include the Ray that will be use to expand the NonSky   
195    [yt x] = find(mask);
196    CenterX = round(median(x));
197    CenterY = round(median(yt));
198    YPointer = [YPointer; CenterY >= ceiling]; % Y is zero in the top ceiling default to be 0 as the top row in the image
199    YPosition = [YPosition; CenterY];
200    mask(isnan(CleanedDepthMap)) = false;
201    SupNuPatch(i) = sum(mask(:));
202%    if sum(mask(:)) < 5
203%       EmptyIndex = [EmptyIndex; i];
204%       mask(:) = false;
205%    end
206    % find center point
207    [yt x] = find(mask);
208    CenterX = round(median(x));
209    CenterY = round(median(yt));
210 
211  if ~all(mask(:)==0)
212    if gravity
213      if any(CleanedDepthMap(mask) <=0)
214         CleanedDepthMap(mask)
215%         pause
216      end
217      Pa2CenterRatio = median(CleanedDepthMap(mask))./CleanedDepthMap(mask);
218      if sum(mask(:)) > 0
219         RayMtilt = blkdiag(RayMtilt, ...
220             ( Pa2CenterRatio(:,[1 1 1]).*repmat(RayOri(:,CenterY,CenterX)',[ SupNuPatch(i) 1])- RayOri(:,mask)'));
221      else
222         RayMtilt = blkdiag(RayMtilt, RayOri(:,mask)');
223      end
224      RayMCent = blkdiag(RayMCent, RayOri(:,CenterY,CenterX)'*SupNuPatch(i)*mapVert(CenterY)*mapHori(CenterX));
225      PosiM = blkdiag(PosiM,Posi3D(:,mask)');%.*repmat( mapVert(yt)',[1 3]).*repmat( mapHori(x)',[1 3]));
226      VarM = [VarM; VarMap(mask).*(mapVert(yt)').*( mapHori(x)')];
227      RayMd = blkdiag(RayMd,RayOri(:,mask)'.*repmat( mapVert(yt)',[1 3]).*repmat( mapHori(x)',[1 3]));
228      DepthInverseMCent = [DepthInverseMCent; 1./median(CleanedDepthMap(mask)).*SupNuPatch(i)* mapVert(CenterY)'*mapHori(CenterX)];
229      DepthInverseM = [DepthInverseM; 1./CleanedDepthMap(mask).* mapVert(yt)'.*mapHori(x)'];
230    else
231      Pa2CenterRatio = CleanedDepthMap(CenterY,CenterX)./CleanedDepthMap(mask);
232      if sum(mask(:)) > 0
233         RayMtilt = blkdiag(RayMtilt, ...
234             ( Pa2CenterRatio(:,[1 1 1]).*repmat(RayOri(:,CenterY,CenterX)',[ SupNuPatch(i) 1])- RayOri(:,mask)'));
235      else
236         RayMtilt = blkdiag(RayMtilt, RayOri(:,mask)');
237      end
238      RayMCent = blkdiag(RayMCent, RayOri(:,CenterY,CenterX)'*SupNuPatch(i));
239      PosiM = blkdiag(PosiM,Posi3D(:,mask)');
240      VarM = [VarM; VarMap(mask)];
241      RayMd = blkdiag(RayMd,RayOri(:,mask)');
242      DepthInverseMCent = [DepthInverseMCent; 1./median(CleanedDepthMap(mask)).*SupNuPatch(i)];
243      DepthInverseM = [DepthInverseM; 1./CleanedDepthMap(mask)];
244    end
245  else
246     RayMtilt = blkdiag(RayMtilt, RayOri(:,mask)');
247     RayMCent = blkdiag(RayMCent, RayOri(:,mask)');
248     PosiM = blkdiag(PosiM, Posi3D(:,mask)');
249     VarM = [VarM; VarMap(mask)];
250     RayMd = blkdiag(RayMd, RayOri(:,mask)');
251  end
252end
253YPointer(YPointer==0) = -1;
254
255% =================Building up the triangulated  and sampled ground constrain ========================================
256PosiTriangulatedM = sparse( 0, 3*NuSupSize);
257count = 1;
258for i = SupMatched'
259    temp = sparse(1, 3*NuSupSize);
260    if Sup2Para(i)*3>3*NuSupSize || Sup2Para(i)*3-2<0
261       Sup2Para(i)
262       NuSupSize
263    end
264    temp( (Sup2Para(i)*3-2):(Sup2Para(i)*3) ) = RayMatched(count,:)*ClosestDepth(count);
265    PosiTriangulatedM = [PosiTriangulatedM; temp];
266    count = count + 1;
267end
268PosiSampledGroundM = sparse( 0, 3*NuSupSize);
269count = 1;
270for i = SampledGroundSupMatched'
271    temp = sparse(1, 3*NuSupSize);
272    if (Sup2Para(i)*3)>(3*NuSupSize) || (Sup2Para(i)*3-2)<0
273       Sup2Para(i)
274       NuSupSize
275    end
276    temp( (Sup2Para(i)*3-2):(Sup2Para(i)*3) ) = SampledGroundRayMatched(count,:)*SampledGroundClosestDepth(count);
277    PosiSampledGroundM = [PosiSampledGroundM; temp];
278    count = count + 1;
279end
280
281% ================================================================================================
282
283% buliding CoPlane Matrix=========================================================================
284
285NuSTList = 0;
286if CoPST
287   NuSTList = size(CoPSTList,1);
288   if ~isempty(CoPSTList)
289      [V H] = size(SupNeighborTable);
290      SupNeighborTable( CoPSTList(:,1)*V + CoPSTList(:,2)) = 1;
291      SupNeighborTable( CoPSTList(:,2)*V + CoPSTList(:,1)) = 1;
292%   ClosestNList = [ClosestNList; CoPSTList];
293   end
294end
295CoPM1 = sparse(0,3*NuSupSize);
296CoPM2 = sparse(0,3*NuSupSize);
297CoPEstDepth = sparse(0,0);
298CoPNorM = [];
299WeiCoP = [];
300
301for i = NuSup
302    Neighbor = find( SupNeighborTable(i,:) ~=0);
303    Neighbor = Neighbor( Neighbor> i);
304    for j = Neighbor
305        %  if ~CornerList(i)
306        mask = Sup == i;
307        SizeMaskAll = sum(mask(:));
308        [y x] = find(mask);
309        CenterX = round(median(x));
310        CenterY = round(median(y));
311        y = find(mask(:,CenterX));
312        if ~isempty(y)
313           CenterY = round(median(y));
314        end
315   
316        temp1 = sparse(1, 3*NuSupSize);
317        temp2 = sparse(1, 3*NuSupSize);
318        temp1(:,(Sup2Para( i)*3-2): Sup2Para( i)*3) = ...
319                                                   Ray(:,CenterY,CenterX)';
320        temp2(:,(Sup2Para( j)*3-2): Sup2Para( j)*3) = ...
321                                                   Ray(:,CenterY,CenterX)';
322    %NuNei-NuSTList
323
324%        if i < NuNei-NuSTList % only immediate connecting superpixels are weighted using MultiScaleSup
325%       wei = WeiV*10;%*(MultiScaleSupTable(Sup2Para(ClosestNList(i,1)),2:end) == MultiScaleSupTable(Sup2Para(ClosestNList(i,2)),2:end))'; 
326           if MultiScaleFlag
327              vector = (MultiScaleSupTable(Sup2Para( i),2:end) == MultiScaleSupTable(Sup2Para( j),2:end));
328              expV = exp(-10*(WeiV*vector' + ShiftCoP) );
329              wei = 1/(1+expV);
330           else
331              wei = 1;
332           end
333%        else
334%           wei = 1;
335%        end
336        oneRay1 = temp1*wei;
337        oneRay2 = temp2*wei;
338    %CoPM1 = [CoPM1; temp1*wei];
339    %CoPM2 = [CoPM2; temp2*wei];
340
341   
342        tempWeiCoP = [SizeMaskAll];
343        CoPEstDepth = [CoPEstDepth; max(median(CleanedDepthMap(mask)),ClosestDist)];
344   
345        mask = Sup == j;
346        SizeMaskAll = sum(mask(:));
347        [y x] = find(mask);
348        CenterX = round(median(x));
349        CenterY = round(median(y));
350        y = find(mask(:,CenterX));
351        if ~isempty(y)
352           CenterY = round(median(y));
353        end
354
355        temp1 = sparse(1, 3*NuSupSize);
356        temp2 = sparse(1, 3*NuSupSize);
357        temp1(:,(Sup2Para( i)*3-2): Sup2Para( i)*3) = ...
358                                                            Ray(:,CenterY,CenterX)';
359        temp2(:,(Sup2Para( j)*3-2): Sup2Para( j)*3) = ...
360                                                            Ray(:,CenterY,CenterX)';
361   
362    % Instead of having separate L-1 terms for symmetric co-planar constraint; do the following:
363    % If the penaly was ||.||_2^2 + ||.||_2^2; then the co-efficients are
364    % some kind of average of two rays.  For one norm; we take its average.
365    % (do not divide by 2 because the penalty should be double.
366   
367       CoPM1 = [CoPM1; temp1*wei + oneRay1 ];
368       CoPM2 = [CoPM2; temp2*wei + oneRay2 ];
369   
370       tempWeiCoP = [tempWeiCoP; SizeMaskAll];
371       WeiCoP = [WeiCoP; tempWeiCoP];
372       CoPEstDepth = [CoPEstDepth; max(median(CleanedDepthMap(mask)),ClosestDist)];
373  end
374end%=========================================================================================================
375
376%== find the boundary point that might need to be stick ot each other==========================================
377HoriStickM_i = sparse(0,3*NuSupSize);
378HoriStickM_j = sparse(0,3*NuSupSize);
379HoriStickPointInd = [];
380EstDepHoriStick = [];
381
382MAX_POINTS_STITCH_HORI = 2;    % the actual code will be modified in another copy of the file
383MIN_POINTS_STITCH = 2;      % ERROR:  not used.
384
385% ================================================================
386% NOTE: The actual algorithm should be picking precisely 2 points which are
387% FARTHEST away from the candidate set of neighbors.  This algorithm
388% will ALWAYS work and produce no surprising results.
389
390% In some cases, one may experiment with picking only 1 point when the 2
391% points are too close ---- this will make the algorithm faster; but might
392% produce surprising (e.g. a triangle sticking out) sometimes.
393% An ideal algorithm will reduce the number of points by checking for loops
394% passing through 3 or less superpixels through this matrix; and removing
395% them such that the smallest loop passes through 4 superpixels. (see EE263
396% for a quick algorithm to do this -- involves product of matrices.
397% ==================================================================
398
399DIST_STICHING_THRESHOLD_HORI = 0.4;   
400DIST_STICHING_THRESHOLD_HORI_ONLYCOL = -0.5;    % effectively not used,
401
402SupPixelNeighborList = sparse( max(Sup(:)), max(Sup(:)) );
403SupPixelParsedList = sparse( max(Sup(:)), max(Sup(:)) );
404recordAdded1 = sparse( max(Sup(:)), max(Sup(:)) );
405recordAdded2 = sparse( max(Sup(:)), max(Sup(:)) );
406addedIndexList = [ ];
407
408BounaryPHori = conv2(Sup,[1 -1],'same') ~=0;
409BounaryPHori(:,end) = 0;
410BounaryPVert = conv2(Sup,[1; -1],'same') ~=0;
411BounaryPVert(end,:) = 0;
412boundariesHoriIndex = find(BounaryPHori==1)';
413for i = boundariesHoriIndex
414    j = i+Default.VertYNuDepth;
415    if Sup(i) == 0 || Sup(j) == 0
416       continue;
417    end
418    SupPixelParsedList(Sup(i),Sup(j)) = SupPixelParsedList(Sup(i),Sup(j)) + 1;
419   
420    if SupPixelNeighborList(Sup(i),Sup(j)) == 0
421        recordAdded1(Sup(i),Sup(j)) = i;     
422    elseif SupPixelNeighborList(Sup(i),Sup(j)) >= MAX_POINTS_STITCH_HORI
423        continue;
424    elseif SupPixelNeighborList(Sup(i),Sup(j)) == 1  % inside this remove the close stiching terms
425        rowN = ceil(i/55);      colN = rem(i,55);
426        rowN_older = ceil( recordAdded1(Sup(i),Sup(j)) / 55);
427        colN_older = rem( recordAdded1(Sup(i),Sup(j)), 55);
428        if abs(rowN - rowN_older) + (55/305)*abs(colN - colN_older) > DIST_STICHING_THRESHOLD_HORI && ...
429            abs(colN - colN_older) > DIST_STICHING_THRESHOLD_HORI_ONLYCOL
430            recordAdded2(Sup(i),Sup(j)) = i;
431        else
432            continue;
433        end
434    elseif SupPixelNeighborList(Sup(i),Sup(j)) == 2     %Assuming MAX_POINTS_STITCH = 3
435        rowN = ceil(i/55);      colN = rem(i,55);
436        rowN_older1 = ceil( recordAdded1(Sup(i),Sup(j)) / 55);
437        colN_older1 = rem( recordAdded1(Sup(i),Sup(j)), 55);
438        rowN_older2 = ceil( recordAdded2(Sup(i),Sup(j)) / 55);
439        colN_older2 = rem( recordAdded2(Sup(i),Sup(j)), 55);
440       
441        if abs(rowN - rowN_older1) + (55/305)*abs(colN - colN_older1) > DIST_STICHING_THRESHOLD_HORI && ...
442            abs(rowN - rowN_older2) + (55/305)*abs(colN - colN_older2) > DIST_STICHING_THRESHOLD_HORI
443            ;
444        else
445            continue;
446        end   
447    end
448
449    % If you come here, it means you are probably adding it.
450    SupPixelNeighborList(Sup(i),Sup(j)) = SupPixelNeighborList(Sup(i),Sup(j)) + 1;
451    addedIndexList = [addedIndexList i];
452end
453
454
455WeightHoriNeighborStitch = [ ];
456
457for i = addedIndexList
458    j = i+Default.VertYNuDepth;
459   
460    WeightHoriNeighborStitch = [WeightHoriNeighborStitch;  SupPixelParsedList(Sup(i),Sup(j)) / ...
461                                            SupPixelNeighborList(Sup(i),Sup(j)) ];
462
463    Target(1) = Sup2Para(Sup(i));
464    Target(2) = Sup2Para(Sup(j));
465    rayBoundary(:,1) =  Ray(:,i);
466    rayBoundary(:,2) =  Ray(:,i);
467%    betaTemp = StickHori;%*(DistStickLengthNormWei.^2)*beta(Target(I));
468%    betaTemp = StickHori*WeiV;%*(MultiScaleSupTable(Sup2Para(Sup(i)),2:end) == MultiScaleSupTable(Sup2Para(Sup(j)),2:end))';%*(DistStickLengthNormWei.^2)*beta(Target(I));
469    if MultiScaleFlag
470          vector = (MultiScaleSupTable(Sup2Para(Sup(i)),2:end) == MultiScaleSupTable(Sup2Para(Sup(j)),2:end));
471          expV = exp(-10*(WeiV*vector' + ShiftStick) );
472       betaTemp = StickHori*(0.5+1/(1+expV)); %*(DistStickLengthNormWei.^2)*beta(Target(I));
473       % therr should always be sticking (know don't care about occlusion)
474    else
475       betaTemp = StickHori;
476    end
477    temp = sparse(3,NuSupSize);
478    temp(:,Target(1)) = rayBoundary(:,1);
479    HoriStickM_i = [HoriStickM_i; betaTemp*temp(:)'];
480    temp = sparse(3,NuSupSize);
481    temp(:,Target(2)) = rayBoundary(:,2);
482    HoriStickM_j = [HoriStickM_j; betaTemp*temp(:)'];
483    EstDepHoriStick = [EstDepHoriStick; sqrt(max(CleanedDepthMap(i),ClosestDist)*max(CleanedDepthMap(j),ClosestDist))];
484    HoriStickPointInd = [HoriStickPointInd i ];
485
486end
487% ==============================================
488
489
490
491% ======== finding the unucessary stiching points in Vertical direction ====
492VertStickM_i = sparse(0,3*NuSupSize);
493VertStickM_j = sparse(0,3*NuSupSize);
494VertStickPointInd = [];
495EstDepVertStick = [];
496
497MAX_POINTS_STITCH_VERT = 4;     %3
498DIST_STICHING_THRESHOLD_VERT = 0.1;     %0.3
499DIST_STICHING_THRESHOLD_VERT_ONLYCOL = -0.5;    % effectively not used, ideally should be 0.5; i.e., the point should be farther in col direction because that is the direction of the edge.
500
501SupPixelNeighborList = sparse( max(Sup(:)), max(Sup(:)) );
502SupPixelParsedList = sparse( max(Sup(:)), max(Sup(:)) );
503recordAdded1 = sparse( max(Sup(:)), max(Sup(:)) );
504recordAdded2 = sparse( max(Sup(:)), max(Sup(:)) );
505addedIndexList = [ ];
506
507for i = find(BounaryPVert==1)'
508    j = i+1;
509    if Sup(i) == 0 || Sup(j) == 0
510       continue;
511    end
512    SupPixelParsedList(Sup(i),Sup(j)) = SupPixelParsedList(Sup(i),Sup(j)) + 1;
513   
514    if SupPixelNeighborList(Sup(i),Sup(j)) == 0
515        recordAdded1(Sup(i),Sup(j)) = i;
516    elseif SupPixelNeighborList(Sup(i),Sup(j)) >= MAX_POINTS_STITCH_VERT
517        continue;
518    elseif SupPixelNeighborList(Sup(i),Sup(j)) == 1  % inside this remove the close stiching terms
519        rowN = ceil(i/55);      colN = rem(i,55);
520        rowN_older = ceil( recordAdded1(Sup(i),Sup(j)) / 55);
521        colN_older = rem( recordAdded1(Sup(i),Sup(j)), 55);
522        if abs(rowN - rowN_older) + (55/305)*abs(colN - colN_older) > DIST_STICHING_THRESHOLD_VERT && ...
523                 abs(colN - colN_older) > DIST_STICHING_THRESHOLD_VERT_ONLYCOL
524            recordAdded2(Sup(i),Sup(j)) = i;
525        else
526            continue;
527        end
528    elseif SupPixelNeighborList(Sup(i),Sup(j)) == 2     %Assuming MAX_POINTS_STITCH = 3
529        rowN = ceil(i/55);      colN = rem(i,55);
530        rowN_older1 = ceil( recordAdded1(Sup(i),Sup(j)) / 55);
531        colN_older1 = rem( recordAdded1(Sup(i),Sup(j)), 55);
532        rowN_older2 = ceil( recordAdded2(Sup(i),Sup(j)) / 55);
533        colN_older2 = rem( recordAdded2(Sup(i),Sup(j)), 55);
534       
535        if abs(rowN - rowN_older1) + (55/305)*abs(colN - colN_older1) > DIST_STICHING_THRESHOLD_VERT && ...
536            abs(rowN - rowN_older2) + (55/305)*abs(colN - colN_older2) > DIST_STICHING_THRESHOLD_VERT
537            ;
538        else
539            continue;
540        end       
541     end
542
543    % If you come here, it means you are probably adding it.
544    SupPixelNeighborList(Sup(i),Sup(j)) = SupPixelNeighborList(Sup(i),Sup(j)) + 1;
545    addedIndexList = [addedIndexList i];
546end
547
548
549WeightVertNeighborStitch = [ ];
550
551for i = addedIndexList
552    j = i+1;
553   
554     WeightVertNeighborStitch = [WeightVertNeighborStitch;  SupPixelParsedList(Sup(i),Sup(j)) / ...
555                                            SupPixelNeighborList(Sup(i),Sup(j)) ];
556
557    Target(1) = Sup2Para(Sup(i));
558    Target(2) = Sup2Para(Sup(j));
559    rayBoundary(:,1) =  Ray(:,i);
560    rayBoundary(:,2) =  Ray(:,i);
561    if MultiScaleFlag
562       vector = (MultiScaleSupTable(Sup2Para(Sup(i)),2:end) == MultiScaleSupTable(Sup2Para(Sup(j)),2:end));
563       expV = exp(-10*(WeiV*vector' + ShiftStick) );
564       betaTemp = StickVert*(0.5+1/(1+expV));
565       % therr should always be sticking (know don't care about occlusion)
566    else
567       betaTemp = StickVert;
568    end
569    temp = sparse(3,NuSupSize);
570    temp(:,Target(1)) = rayBoundary(:,1);
571    VertStickM_i = [VertStickM_i; betaTemp*temp(:)'];
572    temp = sparse(3,NuSupSize);
573    temp(:,Target(2)) = rayBoundary(:,2);
574    VertStickM_j = [VertStickM_j; betaTemp*temp(:)'];
575    EstDepVertStick = [EstDepVertStick; sqrt(max(CleanedDepthMap(i),ClosestDist)*max(CleanedDepthMap(j),ClosestDist))];
576    VertStickPointInd = [VertStickPointInd i ];
577
578end
579% ====finished finding the unucessary stiching points in Vertical direction ===
580
581
582% ======================================Finish building up matrix=====================hard work======================
583
584
585
586% ================================================================================================================
587depthfile = strrep(Default.filename{k},'img','depth_learned'); %
588
589
590% Start Decompose the image align with superpixels ==================================================================================
591% define the decomposition in X direction only
592
593% ============== parameters for the decomposition problem
594% Optimal parameters for current code:
595% For one machine: Sedumi: (1,1)        Lpsolve:(3,1)
596% Multiple machines: Sedumi: (4,1)      LPsolve:(3,1)
597% lpsolve running time is 22 seconds for (4,2) arrangement; but numerical
598% accuracy needs to be resolved first.
599XNuDecompose = 2;       
600YNuDecompose = 1;
601% ============ parameters for the decomposition problem
602
603
604 
605TotalRectX = 2*XNuDecompose-1;
606TotalRectY= 2*YNuDecompose-1;
607PlanePara = NaN*ones(3*NuSupSize,1); % setup the lookuptable for the solved plane parameter
608
609 opt = sdpsettings('solver','sedumi','cachesolvers',1,'sedumi.eps',1e-6,'verbose',solverVerboseLevel);
610%     opt = sdpsettings('solver','lpsolve','cachesolvers',1,'verbose',5);
611%     opt = sdpsettings('solver','lpsolve','cachesolvers',1,'showprogress',1, 'verbose',4);
612%    opt = sdpsettings('solver','glpk','cachesolvers',1, 'usex0', 1);   
613%    opt = sdpsettings('solver','glpk', 'usex0', 1);   
614    %opt = sdpsettings('solver','linprog','cachesolvers',1);   
615%    opt = sdpsettings('solver','bpmpd');
616   
617for k = 0:(TotalRectX-1)
618  l = rem(k*2,(TotalRectX));
619  RangeX = (1+ceil(Default.HoriXNuDepth/XNuDecompose)*l/2):...
620            min((1+ceil(Default.HoriXNuDepth/XNuDecompose)*(l/2+1)),Default.HoriXNuDepth);
621  RangeX = ceil(RangeX);
622  for q = 0:(TotalRectY-1)
623    l = rem(q*2,(TotalRectY));
624    RangeY = (1+ceil(Default.VertYNuDepth/YNuDecompose)*l/2):...
625              min((1+ceil(Default.VertYNuDepth/YNuDecompose)*(l/2+1)),Default.VertYNuDepth);
626    RangeY = ceil(RangeY);
627    mask = zeros(size(Sup));
628    mask(RangeY,RangeX) = 1;
629    mask =logical(mask);
630    SubSup = sort(setdiff(unique( reshape( Sup(RangeY,RangeX),1,[])),0));
631    BoundarySup = [];
632%    for m = SubSup
633    if any(SubSup <=0)
634       SubSup(SubSup<=0)
635    end
636    BoundarySup = find(sum(SupNeighborTable(SubSup,:), 1) ~=0);
637    BoundarySup = unique(setdiff(BoundarySup,[0 SubSup] ));
638
639    % chech if BoundarySup non-NaN in PlanePara
640    checkNoNNaN = ~isnan(PlanePara(Sup2Para(BoundarySup)*3));
641    BoundarySup = BoundarySup(checkNoNNaN);
642    TotalSup = sort([SubSup BoundarySup]);
643
644    SubSupPtr = [ Sup2Para(SubSup)*3-2;...
645                    Sup2Para(SubSup)*3-1;...
646                    Sup2Para(SubSup)*3];
647    SubSupPtr = SubSupPtr(:);
648    BoundarySupPtr = [ Sup2Para(BoundarySup)*3-2;...
649                       Sup2Para(BoundarySup)*3-1;...
650                       Sup2Para(BoundarySup)*3];
651    BoundarySupPtr = BoundarySupPtr(:);
652    NuSubSupSize = size(SubSup,2);
653    NewRayAllM = RayAllM(:,SubSupPtr);
654    tar = sum(NewRayAllM ~= 0,2) == 3;
655    NewRayAllM = NewRayAllM(tar,:);
656    NewPosiM = PosiM(:,SubSupPtr);
657    tar = sum(NewPosiM ~= 0,2) == 3;
658    NewPosiM = NewPosiM(tar,:);
659    NewVarM = VarM(tar);
660    NewPosiTriangulatedM = PosiTriangulatedM(:,SubSupPtr);
661    tar = sum(NewPosiTriangulatedM ~= 0,2) == 3;
662    NewPosiTriangulatedM = NewPosiTriangulatedM(tar,:);
663    NewPosiSampledGroundM = PosiSampledGroundM(:,SubSupPtr);
664    tar = sum(NewPosiSampledGroundM ~= 0,2) == 3;
665    NewPosiSampledGroundM = NewPosiSampledGroundM(tar,:);
666   
667    NewCoPM = CoPM1(:,SubSupPtr) - CoPM2(:,SubSupPtr);
668    NewCoPMBound = CoPM1(:,BoundarySupPtr) - CoPM2(:,BoundarySupPtr);
669    tar = sum(NewCoPM ~= 0,2) + sum(NewCoPMBound ~= 0,2)==6;
670    NewCoPMBound = NewCoPMBound*PlanePara(BoundarySupPtr);
671    NewCoPM = NewCoPM(tar,:);
672    NewCoPMBound = NewCoPMBound(tar);
673    NewCoPEstDepth = CoPEstDepth(tar);   
674
675    NewHoriStickM = HoriStickM_i(:,SubSupPtr)-HoriStickM_j(:,SubSupPtr);
676    NewHoriStickMBound = HoriStickM_i(:,BoundarySupPtr)-HoriStickM_j(:,BoundarySupPtr);
677    tar = sum(NewHoriStickM ~= 0,2)+  sum(NewHoriStickMBound ~= 0,2) ==6;
678    NewHoriStickM = NewHoriStickM(tar,:);   
679    NewEstDepHoriStick = EstDepHoriStick(tar);
680    NewHoriStickMBound = NewHoriStickMBound*PlanePara(BoundarySupPtr);
681    NewHoriStickMBound = NewHoriStickMBound(tar);
682        NewWeightHoriNeighborStitch = WeightHoriNeighborStitch(tar);
683
684    NewVertStickM = VertStickM_i(:,SubSupPtr)-VertStickM_j(:,SubSupPtr);
685    NewVertStickMBound = VertStickM_i(:,BoundarySupPtr)-VertStickM_j(:,BoundarySupPtr);
686    tar = sum(NewVertStickM ~= 0,2) + sum(NewVertStickMBound ~= 0,2)==6;
687    NewVertStickM = NewVertStickM(tar,:);
688    NewEstDepVertStick = EstDepVertStick(tar);
689    NewVertStickMBound = NewVertStickMBound*PlanePara(BoundarySupPtr);
690    NewVertStickMBound = NewVertStickMBound(tar);
691        NewWeightVertNeighborStitch = WeightVertNeighborStitch(tar);
692 
693        ParaPPCP = sdpvar(3*NuSubSupSize,1);
694        F = set(ParaPPCP(3*(1:NuSubSupSize)-1).*YPointer(Sup2Para(SubSup))<=0)...
695            +set(NewRayAllM*ParaPPCP <=1/ClosestDist)...
696            +set(NewRayAllM*ParaPPCP >=1/FarestDist);
697
698% ================================================================
699
700        WeightsSelfTerm = 1 ./ exp(abs(NewVarM)/BandWith);
701   
702% ============ solver specific options ======
703   if strcmp(opt.solver, 'glpk')
704      disp('Using x0 for GPLK');
705      ParaPPCP = NewPosiM \ ones(size(NewPosiM,1),1);
706   end
707   fprintf(['     ' num2str( toc(inferenceTime) ) '\n     : In 1st level Optimization, using ' opt.solver '.  ' ...
708            '(' num2str(k+1) '/' num2str((TotalRectX-1)+1) ',' num2str(l+1) '/' num2str((TotalRectY-1)+1) ')']);
709
710          sol = solvesdp(F, norm( (NewPosiM*ParaPPCP-ones(size(NewPosiM,1),1)) .* WeightsSelfTerm,1)...
711                        + TriangulatedWeight*norm( NewPosiTriangulatedM*ParaPPCP-ones(size(NewPosiTriangulatedM,1), 1), 1)+...
712                        + SampledGroundWeight*norm( NewPosiSampledGroundM*ParaPPCP-ones(size(NewPosiSampledGroundM,1), 1), 1)+...
713                        + Center*norm(((NewCoPM)*ParaPPCP + NewCoPMBound).*NewCoPEstDepth, 1)...
714                        + norm(((NewHoriStickM)*ParaPPCP + NewHoriStickMBound).*...
715                                 NewEstDepHoriStick.*NewWeightHoriNeighborStitch,1)...
716                        + norm(((NewVertStickM)*ParaPPCP + NewVertStickMBound).*...
717                                 NewEstDepVertStick.*NewWeightVertNeighborStitch,1) ...
718                        , opt);
719
720    ParaPPCP = double(ParaPPCP);
721%     sum(isnan(ParaPPCP))
722    yalmip('clear');
723    PlanePara(SubSupPtr) = ParaPPCP;
724
725  end
726end
727
728% build the whole image
729    PlanePara = reshape(PlanePara,3,[]);
730    %any(any(isnan(PlanePara)))
731    % porject the ray on planes to generate the ProjDepth
732    FitDepthPPCP = FarestDist*ones(1,Default.VertYNuDepth*Default.HoriXNuDepth);
733    FitDepthPPCP(~maskSkyEroded) = (1./sum(PlanePara(:,Sup2Para(SupEpand(~maskSkyEroded ))).*Ray(:,~maskSkyEroded ),1))';
734    FitDepthPPCP = reshape(FitDepthPPCP,Default.VertYNuDepth,[]);
735
736    % =====================================================
737    [Position3DFitedPPCP] = im_cr2w_cr(FitDepthPPCP,permute(Ray,[2 3 1]));
738    if NoSecondStep %RenderVrmlFlag && i==3
739         [a b c] = size(Position3DFitedPPCP);
740         % ============transfer to world coordinate
741         Position3DFitedPPCP = Rotation*Position3DFitedPPCP(:,:) + repmat(Translation, 1, length(Position3DFitedPPCP(:,:)));
742         Position3DFitedPPCP = reshape(Position3DFitedPPCP, a, b, []);
743         % ========================================
744         Position3DFitedPPCP(3,:) = -Position3DFitedPPCP(3,:);
745         Position3DFitedPPCP = permute(Position3DFitedPPCP,[2 3 1]);
746         RR =permute(Ray,[2 3 1]);
747         temp = RR(:,:,1:2)./repmat(RR(:,:,3),[1 1 2]);
748         PositionTex = permute(temp./repmat(cat(3,Default.a_default,Default.b_default),[Default.VertYNuDepth Default.HoriXNuDepth 1])+repmat(cat(3,Default.Ox_default,Default.Oy_default),[Default.VertYNuDepth Default.HoriXNuDepth 1]),[3 1 2]);
749         PositionTex = permute(PositionTex,[2 3 1]);
750         WrlFacestHroiReduce(Position3DFitedPPCP,PositionTex,SupOri, [ Default.filename{1} '1st'],[ Default.Wrlname{1} '1st'], ...
751                             Default.OutPutFolder, GridFlag, appendOpt);
752         system(['gzip -9 -c ' Default.OutPutFolder Default.filename{1} '1st.wrl > ' ...
753                Default.OutPutFolder Default.filename{1} '1st.wrl.gz']);
754         system(['cp '  Default.OutPutFolder Default.filename{1} '1st.wrl.gz ' ...
755                Default.OutPutFolder Default.filename{1} '1st.wrl']);
756         delete([Default.OutPutFolder Default.filename{1} '1st.wrl.gz']);
757    end
758
759    % Trial for segmentaion of the plane parameters
760    if PlaneParaSegmentationFlag
761       TempSup = Sup;%imresize(Sup,[330 610]);
762       TempSup(TempSup==0) = max(TempSup(:))+1;
763       TempSup2Para = Sup2Para;
764       TempSup2Para(end+1) = size(PlanePara,2);
765       TempPlanePara = PlanePara;
766       TempPlanePara(:,end+1) = 0;
767       PlaneParaPics = TempPlanePara(:,TempSup2Para( TempSup));
768       PlaneParaPics = PlaneParaPics./repmat( 2*max(abs(PlaneParaPics),[],2), 1, size(PlaneParaPics,2));
769       PlaneParaPics = permute( reshape( PlaneParaPics, 3, 55, []), [2 3 1])+0.5;
770       MergedPlaneParaPics = segmentImgOpt( Default.sigm*scale, Default.k*scale, Default.minp*10*scale, PlaneParaPics, '', 0) + 1;
771       if Default.Flag.DisplayFlag
772          figure(400);
773          imaegsc( PlaneParaPics);
774          imaegsc( MergedPlaneParaPics);
775       end
776       save('/afs/cs/group/reconstruction3d/scratch/testE/PlaneParaPics.mat','PlaneParaPics','MergedPlaneParaPics');
777    end
778
779%return;
780%==================Finished for one step MRF==========================================================================================================
781
782if NoSecondStep
783        return;
784end
785
786% ====================================following are 2nd step MRF to give more visually pleasing result=======================================
787;% generating new PosiMPPCP using the new position
788
789% save([Default.ScratchDataFolder '/data/VertShiftVrml.mat' ] );
790%  groundThreshold = cos(5*pi/180);  % make small range
791%  verticalThreshold = cos(50*pi/180);
792  normPara = norms(PlanePara);
793  normalizedPara = PlanePara ./ repmat( normPara, [3 1]);
794  %groundPara = abs(normalizedPara(2,:)) >= groundThreshold(YPosition); % assuming ground has [0; 1; 0] surface norm
795  groundPara = abs(CoordinateFromRef(:,2)'*normalizedPara) >= groundThreshold(YPosition); % CoordinateFromRef(:,2) is the new ground surface norm
796  groundParaInd = find(groundPara);
797%  verticalPara = abs(normalizedPara(2,:)) <= verticalThreshold(YPosition); % ssuming ground has [0; 1; 0] surface norm
798  verticalPara = abs( CoordinateFromRef(:,2)'*normalizedPara) <= verticalThreshold(YPosition); % CoordinateFromRef(:,2) is the new ground surface norm
799  verticalParaInd = find(verticalPara);
800
801  indexVertical = find( verticalPara)*3-1;
802  indexGroundX = find( groundPara)*3-2;
803  indexGroundZ = find( groundPara)*3;
804
805  PosiMPPCP = sparse(0,0);
806  VarM2 = sparse(0,0);
807  %  VertVar = 10^(-2);
808  % forming new supporting matrix using new depth and get rid of the support of the vertical plane
809  for i = NuSup
810      mask = Sup == i;
811      if any(verticalParaInd == Sup2Para(i))
812         mask = logical(zeros(size(Sup)));
813      end
814         PosiMPPCP = blkdiag(PosiMPPCP, Posi3D(:,mask)');
815         VarM2 = [VarM2; VarMap(mask)];         
816  end
817
818% Start Decompose image =========================
819  XNuDecompose = 2;
820  YNuDecompose = 1;
821  TotalRectX = 2*XNuDecompose-1;
822  TotalRectY = 2*YNuDecompose-1;
823  PlanePara = NaN*ones(3*NuSupSize,1); % setup the lookuptable for the solved plane parameter
824
825  opt = sdpsettings('solver','sedumi','cachesolvers',1, 'verbose', solverVerboseLevel);
826  %     opt = sdpsettings('solver','lpsolve','cachesolvers',1);
827  %    opt = sdpsettings('solver','glpk','cachesolvers',1);   
828
829  for k = 0:(TotalRectX-1)
830    l = rem(k*2,(TotalRectX));
831    RangeX = (1+ceil(Default.HoriXNuDepth/XNuDecompose)*l/2):...
832              min((1+ceil(Default.HoriXNuDepth/XNuDecompose)*(l/2+1)),Default.HoriXNuDepth);
833    RangeX = ceil(RangeX);
834    for q = 0:(TotalRectY-1)
835      l = rem(q*2,(TotalRectY));
836      RangeY = (1+ceil(Default.VertYNuDepth/YNuDecompose)*l/2):...
837                min((1+ceil(Default.VertYNuDepth/YNuDecompose)*(l/2+1)),Default.VertYNuDepth);
838      RangeY = ceil(RangeY);
839      mask = zeros(size(Sup));
840      mask(RangeY,RangeX) = 1;
841      mask =logical(mask);
842%       SubSup = sort(setdiff(reshape( Sup(RangeY,RangeX),[],1),0))';
843      SubSup = sort(setdiff( unique( reshape( Sup(RangeY,RangeX),1,[])),0));
844      BoundarySup = [];
845%      for m = SubSup
846      BoundarySup = find(sum(SupNeighborTable(SubSup,:), 1) ~=0);
847%          maskList = ClosestNList(:,1) == m;
848%          BoundarySup = [ BoundarySup ClosestNList(maskList,2)'];
849%      end
850      BoundarySup = unique(setdiff(BoundarySup,[0 SubSup] ));
851
852      % chech if BoundarySup non-NaN in PlanePara
853      checkNoNNaN = ~isnan(PlanePara(Sup2Para(BoundarySup)*3));
854      BoundarySup = BoundarySup(checkNoNNaN);
855      TotalSup = sort([SubSup BoundarySup]);
856
857%      TotalSupPtr = [ Sup2Para(TotalSup)*3-2;...
858%                      Sup2Para(TotalSup)*3-1;...
859%                      Sup2Para(TotalSup)*3];
860%      TotalSupPtr = TotalSupPtr(:);
861      SubSupPtr = [ Sup2Para(SubSup)*3-2;...
862                    Sup2Para(SubSup)*3-1;...
863                    Sup2Para(SubSup)*3];
864      SubSupPtr = SubSupPtr(:);
865      BoundarySupPtr = [ Sup2Para(BoundarySup)*3-2;...
866                         Sup2Para(BoundarySup)*3-1;...
867                         Sup2Para(BoundarySup)*3];
868      BoundarySupPtr =BoundarySupPtr(:);
869%      NuSubSupSize = size(TotalSup,2);
870      NuSubSupSize = size(SubSup,2);
871%      TotalSup2Para = sparse(1,max(TotalSup));
872%      TotalSup2Para(TotalSup) = 1:NuSubSupSize;
873      SubSup2Para = sparse(1,max(SubSup));
874      SubSup2Para(SubSup) = 1:NuSubSupSize;
875%      BoundarySupPtrSub = [ TotalSup2Para(BoundarySup)*3-2;...
876%                            TotalSup2Para(BoundarySup)*3-1;...
877%                            TotalSup2Para(BoundarySup)*3];
878%      BoundarySupPtrSub =BoundarySupPtrSub(:);
879%      SubSupPtrSub = [ TotalSup2Para(SubSup)*3-2;...
880%                       TotalSup2Para(SubSup)*3-1;...
881%                       TotalSup2Para(SubSup)*3];
882%      SubSupPtrSub =SubSupPtrSub(:);
883   
884      % clearn RayAllM PosiM CoPM1 HoriStickM_i VertStickM_i
885%      NewRayAllM = RayAllM(:,TotalSupPtr);
886      NewRayAllM = RayAllM(:,SubSupPtr);
887      tar = sum(NewRayAllM ~= 0,2) ==3;
888      NewRayAllM = NewRayAllM(tar,:);
889
890%      NewPosiMPPCP = PosiMPPCP(:,TotalSupPtr);
891      NewPosiMPPCP = PosiMPPCP(:,SubSupPtr);
892      tar = sum(NewPosiMPPCP ~= 0,2) ==3;
893      NewPosiMPPCP = NewPosiMPPCP(tar,:);
894      NewVarM = VarM2(tar);
895      NewPosiTriangulatedM = PosiTriangulatedM(:,SubSupPtr);
896      tar = sum(NewPosiTriangulatedM ~= 0,2) == 3;
897      NewPosiTriangulatedM = NewPosiTriangulatedM(tar,:);
898      NewPosiSampledGroundM = PosiSampledGroundM(:,SubSupPtr);
899      tar = sum(NewPosiSampledGroundM ~= 0,2) == 3;
900      NewPosiSampledGroundM = NewPosiSampledGroundM(tar,:);
901   
902%      NewCoPM = CoPM1(:,TotalSupPtr) - CoPM2(:,TotalSupPtr);
903      NewCoPM = CoPM1(:,SubSupPtr) - CoPM2(:,SubSupPtr);
904      NewCoPMBound = CoPM1(:,BoundarySupPtr) - CoPM2(:,BoundarySupPtr);
905%      tar = sum( NewCoPM ~= 0,2)  ==6;
906      tar = sum( NewCoPM ~= 0,2) + sum( NewCoPMBound ~= 0,2) ==6;
907      NewCoPM = NewCoPM(tar,:);
908      NewCoPMBound = NewCoPMBound*PlanePara(BoundarySupPtr); % column vertor
909      NewCoPMBound = NewCoPMBound(tar);
910      NewCoPEstDepth = CoPEstDepth(tar);   
911
912%      NewHoriStickM = HoriStickM_i(:,TotalSupPtr)-HoriStickM_j(:,TotalSupPtr);
913      NewHoriStickM = HoriStickM_i(:,SubSupPtr)-HoriStickM_j(:,SubSupPtr);
914      NewHoriStickMBound = HoriStickM_i(:,BoundarySupPtr)-HoriStickM_j(:,BoundarySupPtr);
915%      tar = sum(NewHoriStickM ~= 0,2) ==6;
916      tar = sum(NewHoriStickM ~= 0,2) + sum( NewHoriStickMBound ~= 0,2)==6;
917      NewHoriStickM = NewHoriStickM(tar,:);
918      NewHoriStickMBound = NewHoriStickMBound*PlanePara(BoundarySupPtr); % column vertor
919      NewHoriStickMBound = NewHoriStickMBound(tar);
920      NewEstDepHoriStick = EstDepHoriStick(tar);
921         NewWeightHoriNeighborStitch = WeightHoriNeighborStitch(tar);
922
923%      NewVertStickM = VertStickM_i(:,TotalSupPtr)-VertStickM_j(:,TotalSupPtr);
924      NewVertStickM = VertStickM_i(:,SubSupPtr)-VertStickM_j(:,SubSupPtr);
925      NewVertStickMBound = VertStickM_i(:, BoundarySupPtr)-VertStickM_j(:,BoundarySupPtr);
926%      tar = sum(NewVertStickM ~= 0,2) ==6;
927      tar = sum(NewVertStickM ~= 0,2) + sum(NewVertStickMBound ~= 0,2)==6;
928      NewVertStickM = NewVertStickM(tar,:);
929      NewVertStickMBound = NewVertStickMBound*PlanePara(BoundarySupPtr); % column vertor
930      NewVertStickMBound = NewVertStickMBound(tar);
931      NewEstDepVertStick = EstDepVertStick(tar);
932         NewWeightVertNeighborStitch = WeightVertNeighborStitch(tar);
933
934%    try reduce the vertical constrain
935     %NonVertPtr = setdiff( 1:(3*NuSubSupSize), SubSup2Para( NuSup( (intersect( indexVertical,SubSupPtr ) +1)/3))*3-1 );
936     YNoComingBack = YPointer(Sup2Para(SubSup));
937%     YNoComingBack(SubSup2Para( NuSup( (intersect( indexVertical,SubSupPtr ) +1)/3))) = [];
938%     YCompMask = zeros(1,3*NuSubSupSize);
939%     YCompMask(3*(1:NuSubSupSize)-1) = 1;
940%     YCompMask = YCompMask(NonVertPtr);
941     XCompMask = zeros(1,3*NuSubSupSize);
942%     XCompMask( SubSup2Para( NuSup( (intersect( indexGroundX,SubSupPtr ) +2)/3))*3-2 ) = 1;
943     XCompMask = SubSup2Para( NuSup( (intersect( indexGroundX,SubSupPtr ) +2)/3));
944     VertMask = intersect( find(verticalPara), ( SubSupPtr( 3:3:( size(SubSupPtr,1)) )/3 ) ) ;
945%     XCompMask = XCompMask(NonVertPtr);
946     YCompMask = zeros(1,3*NuSubSupSize);
947     YCompMask = SubSup2Para( NuSup( (intersect( indexVertical,SubSupPtr )+1 )/3));
948%     ZCompMask = ZCompMask(NonVertPtr);
949     GroundMask = intersect( find(groundPara), ( SubSupPtr( 3:3:( size(SubSupPtr,1)) )/3 ) ) ;
950
951      Para = sdpvar( 3*NuSubSupSize,1);
952%      F = set(Para(3*(1:NuSubSupSize)-1).*YPointer(Sup2Para(SubSup))<=0)...
953%          +set( Para( SubSup2Para( NuSup( (intersect( indexVertical,SubSupPtr ) +1)/3))*3-1) == 0);
954%          +set(Para(BoundarySupPtrSub) == PlanePara(BoundarySupPtr) )...
955          % Special constrain for decomp fix the solved neighbor plane parameter       
956
957          %      +set(Para(indexGroundX) == 0)...
958          %      +set(Para(indexGroundZ) == 0);
959
960%       if FractionalDepthError
961% %         size(PosiMPPCP)
962
963    fprintf([ '     ' num2str( toc(inferenceTime) ) '\n     : In 2nd level Optimization, using ' opt.solver '.  ' ...
964                     '(' num2str(k+1) '/' num2str((TotalRectX-1)+1) ',' num2str(l+1) '/' num2str((TotalRectY-1)+1) ')']);
965    if ~isempty(y0)   
966      disp('y0 constrain');
967      F = set( CoordinateFromRef(:,2)'*reshape(Para,3,[]).*YNoComingBack'<=0)...
968          +set(NewRayAllM*Para <=1/ClosestDist)...
969          +set(NewRayAllM*Para >=1/FarestDist)...
970          ;
971%          +set( Para( XCompMask*3-2) == Rotation(2,1)'./(y0 - Translation(2)) )...
972%          +set( Para( XCompMask*3-1) == Rotation(2,2)'./(y0 - Translation(2)) )...
973%          +set( Para( XCompMask*3) == Rotation(2,3)'./(y0 - Translation(2)) )...
974       sol=solvesdp(F,norm( ( NewPosiMPPCP*Para-ones(size(NewPosiMPPCP,1),1))./exp(abs(NewVarM)/BandWith),1)...
975                   +TriangulatedWeight*norm( NewPosiTriangulatedM*Para-ones(size(NewPosiTriangulatedM,1), 1), 1)+...
976                   +SampledGroundWeight*norm( NewPosiSampledGroundM*Para-ones(size(NewPosiSampledGroundM,1), 1), 1)+...
977                   +Center*norm(( NewCoPM*Para + NewCoPMBound).*NewCoPEstDepth, 1)...
978                   +norm(( NewHoriStickM*Para + NewHoriStickMBound).*...
979                           NewEstDepHoriStick.*NewWeightHoriNeighborStitch,1)...
980                   +norm(( NewVertStickM*Para + NewVertStickMBound).*...
981                           NewEstDepVertStick.*NewWeightVertNeighborStitch,1)...
982                   +10*norm( ( CoordinateFromRef(:,1)'*reshape( Para( reshape( [XCompMask*3-2; XCompMask*3-1 ;XCompMask*3], [], 1) ) , 3, []) )./...
983                              normPara( GroundMask ), 1)...
984                   +10*norm( ( CoordinateFromRef(:,3)'*reshape( Para( reshape( [XCompMask*3-2; XCompMask*3-1 ;XCompMask*3], [], 1) ) , 3, []))./...
985                              normPara( GroundMask ), 1) ...
986                   +10*norm( ( CoordinateFromRef(:,2)'*reshape( Para( reshape( [YCompMask*3-2; YCompMask*3-1 ;YCompMask*3], [], 1) ) , 3, []))./...
987                              normPara( VertMask ), 1) ...
988                   +GroundLevelWright*norm( Para( XCompMask*3-2) - Rotation(2,1)'./(y0 - Translation(2)), 1)...
989                   +GroundLevelWright*norm( Para( XCompMask*3-1) - Rotation(2,2)'./(y0 - Translation(2)), 1)...
990                   +GroundLevelWright*norm( Para( XCompMask*3) - Rotation(2,3)'./(y0 - Translation(2)), 1)...
991                   , opt);
992    else
993      F = set( CoordinateFromRef(:,2)'*reshape(Para,3,[]).*YNoComingBack'<=0)...
994          +set(NewRayAllM*Para <=1/ClosestDist)...
995          +set(NewRayAllM*Para >=1/FarestDist);
996       sol=solvesdp(F,norm( ( NewPosiMPPCP*Para-ones(size(NewPosiMPPCP,1),1))./exp(abs(NewVarM)/BandWith),1)...
997                   +TriangulatedWeight*norm( NewPosiTriangulatedM*Para-ones(size(NewPosiTriangulatedM,1), 1), 1)+...
998                   +SampledGroundWeight*norm( NewPosiSampledGroundM*Para-ones(size(NewPosiSampledGroundM,1), 1), 1)+...
999                   +Center*norm(( NewCoPM*Para + NewCoPMBound).*NewCoPEstDepth, 1)...
1000                   +norm(( NewHoriStickM*Para + NewHoriStickMBound).*...
1001                           NewEstDepHoriStick.*NewWeightHoriNeighborStitch,1)...
1002                   +norm(( NewVertStickM*Para + NewVertStickMBound).*...
1003                           NewEstDepVertStick.*NewWeightVertNeighborStitch,1)...
1004                   +10*norm( ( CoordinateFromRef(:,1)'*reshape( Para( reshape( [XCompMask*3-2; XCompMask*3-1 ;XCompMask*3], [], 1) ) , 3, []) )./...
1005                              normPara( GroundMask ), 1)...
1006                   +10*norm( ( CoordinateFromRef(:,3)'*reshape( Para( reshape( [XCompMask*3-2; XCompMask*3-1 ;XCompMask*3], [], 1) ) , 3, []))./...
1007                              normPara( GroundMask ), 1) ...
1008                   +10*norm( ( CoordinateFromRef(:,2)'*reshape( Para( reshape( [YCompMask*3-2; YCompMask*3-1 ;YCompMask*3], [], 1) ) , 3, []))./...
1009                              normPara( VertMask ), 1) ...
1010                   , opt);
1011    end
1012% ==============not used ============
1013%                 +10*norm( ( Para( XCompMask ))./...
1014%                            normPara( intersect( find(groundPara), ( SubSupPtr( 3:3:( size(SubSupPtr,1)) )/3 ) ) )', 1)...
1015%                 +10*norm( ( Para( ZCompMask))./...
1016%                            normPara( intersect( find(groundPara), ( SubSupPtr( 3:3:( size(SubSupPtr,1)) )/3 ) ) )', 1) ...
1017
1018             
1019             
1020             %             sqrt( max(CoPM1*ParaPPCP(:), 1/FarestDist).*max(CoPM2*ParaPPCP(:), 1/FarestDist)), 1)...
1021%             +norm(((VertStickM_i-VertStickM_j)*Para)./...
1022%             sqrt( max(VertStickM_i*ParaPPCP(:), 1/FarestDist).*max(VertStickM_j*ParaPPCP(:), 1/FarestDist)),1)...
1023%   pause;
1024    %         +1000*norm( Para(indexVertical)./ normPara( find(verticalPara) )',1) ...
1025%            +norm(((HoriStickM_i-HoriStickM_j)*Para)./sqrt((VertStickM_i*ParaPPCP(:)).*(VertStickM_j*ParaPPCP(:))),1)...
1026% %       else % not used anymore
1027%          solvesdp(F,norm( RayMd*Para - DepthInverseM,1)...
1028%                  +Center*norm((CoPM1 - CoPM2)*Para,1)...
1029%                  +norm((VertStickM_i-VertStickM_j)*Para,1)...
1030%                  +norm((HoriStickM_i-HoriStickM_j)*Para,1)...
1031%                  +1000*norm( Para(indexVertical)./ normPara( find(verticalPara) )',1) ...
1032%                  +1000*norm( Para(indexGroundX)./ normPara( find(groundPara) )', 1)  ...
1033%                  +1000*norm( Para(indexGroundZ)./ normPara( find(groundPara) )', 1) ...
1034%                  , opt);
1035% %         +0.01*norm( RayMtilt*ParaPPCP,1)...       
1036% %         +norm(spdiags(WeiCoP,0,size(CoPM1,1),size(CoPM1,1))*(CoPM1 - CoPM2)*ParaPPCP,1)...
1037% %         +norm( (CoPM1 - CoPM2)*ParaPPCP,1 )...
1038%      end
1039% ==================================
1040     Para = double(Para);
1041     %sum(isnan(Para))
1042     yalmip('clear');
1043     tempPara = zeros(3*NuSubSupSize,1);
1044     tempPara = Para;     
1045%      tempPara(NonVertPtr) = Para;
1046%     PlanePara(TotalSupPtr) = Para;
1047     PlanePara(SubSupPtr) = tempPara;
1048    end
1049  end
1050
1051  %pause
1052  PlanePara = reshape(PlanePara,3,[]);
1053  FitDepth = FarestDist*ones(1,Default.VertYNuDepth*Default.HoriXNuDepth);
1054  FitDepth(~maskSkyEroded) = (1./sum(PlanePara(:,Sup2Para(SupEpand(~maskSkyEroded))).*Ray(:,~maskSkyEroded),1))';
1055  FitDepth = reshape(FitDepth,Default.VertYNuDepth,[]);
1056 
1057  % ==========Storage ==============
1058  if Default.Flag.AfterInferenceStorage
1059     save([ Default.ScratchFolder '/' strrep( Default.filename{1},'.jpg','') '_AInf.mat' ], 'FitDepth', ...
1060            'Sup', 'SupOri', 'MedSup', 'RayOri','Ray','SupNeighborTable','maskSky','maskG','MultiScaleSupTable');
1061  end
1062  % ===============================
1063  %sum(isnan(FitDepth(:)))
1064  [Position3DFited] = im_cr2w_cr(FitDepth,permute(Ray,[2 3 1]));
1065  [a b c] = size(Position3DFited);
1066  % ============transfer to world coordinate
1067  Position3DFited = Rotation*Position3DFited(:,:) + repmat(Translation, 1, length(Position3DFited(:,:)));
1068  Position3DFited = reshape(Position3DFited, a, b, []);
1069  % ========================================
1070  Position3DFited(3,:) = -Position3DFited(3,:);
1071  Position3DFited = permute(Position3DFited,[2 3 1]);
1072  RR =permute(Ray,[2 3 1]);
1073  temp = RR(:,:,1:2)./repmat(RR(:,:,3),[1 1 2]);
1074  PositionTex = permute(temp./repmat(cat(3,Default.a_default,Default.b_default),...
1075                [Default.VertYNuDepth Default.HoriXNuDepth 1])...
1076                +repmat(cat(3,Default.Ox_default,Default.Oy_default),...
1077                [Default.VertYNuDepth Default.HoriXNuDepth 1]),[3 1 2]);
1078  PositionTex = permute(PositionTex,[2 3 1]);
1079
1080
1081  fprintf(['     ' num2str( toc(inferenceTime) ) '\n     : Writing WRL.']);
1082  WrlFacestHroiReduce(Position3DFited, PositionTex, SupOri, Default.filename{1}, Default.Wrlname{1}, ...
1083      Default.OutPutFolder, GridFlag, appendOpt);
1084 
1085%   system(['gzip -9 -c ' Default.OutPutFolder Default.Wrlname{1} '.wrl > ' ...
1086%          Default.OutPutFolder Default.Wrlname{1} '.wrl.gz']);
1087%   system(['cp '  Default.OutPutFolder Default.Wrlname{1} '.wrl.gz ' ...
1088%           Default.OutPutFolder Default.Wrlname{1} '.wrl']);
1089%   delete([Default.OutPutFolder Default.Wrlname{1} '.wrl.gz']);
1090
1091    % Trial for segmentaion of the plane parameters
1092    if PlaneParaSegmentationFlag
1093       TempSup = Sup;%imresize(Sup,[330 610]);
1094       TempSup(TempSup==0) = max(TempSup(:))+1;
1095       TempSup2Para = Sup2Para;
1096       TempSup2Para(end+1) = size(PlanePara,2);
1097       TempPlanePara = PlanePara;
1098       TempPlanePara(:,end+1) = 0;
1099       PlaneParaPics = TempPlanePara(:,TempSup2Para( TempSup));
1100       PlaneParaPics = PlaneParaPics./repmat( 2*max(abs(PlaneParaPics),[],2), 1, size(PlaneParaPics,2));
1101       PlaneParaPics2 = permute( reshape( PlaneParaPics, 3, 55, []), [2 3 1])+0.5;
1102       MergedPlaneParaPics = segmentImgOpt( Default.sigm*scale, Default.k*scale, Default.minp*10*scale, PlaneParaPics, '', 0) + 1;
1103       if Default.Flag.DisplayFlag
1104          figure(400);
1105          imaegsc( PlaneParaPics);
1106          imaegsc( MergedPlaneParaPics);
1107       end
1108       save('/afs/cs/group/reconstruction3d/scratch/testE/PlaneParaPics2.mat','PlaneParaPics2','MergedPlaneParaPics');
1109    end
1110% save depth Map ++++++++++++++++
1111%       depthMap = FitDepth;
1112%       system(['mkdir ' Default.ScratchDataFolder '/VNonSupport_' DepthFolder '/']);
1113%       save([Default.ScratchDataFolder '/VNonSupport_' DepthFolder '/' depthfile '.mat'],'depthMap');
1114% =============================
1115% return;
Note: See TracBrowser for help on using the repository browser.