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

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

Added original make3d

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