TilePlanes.java 231 KB
Newer Older
1
package com.elphel.imagej.tileprocessor;
Andrey Filippov's avatar
Andrey Filippov committed
2 3 4 5 6 7 8
/**
 **
 ** TilePlanes - detect planes in tile clusters
 **
 ** Copyright (C) 2017 Elphel, Inc.
 **
 ** -----------------------------------------------------------------------------**
9
 **
Andrey Filippov's avatar
Andrey Filippov committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 **  TilePlanes.java is free software: you can redistribute it and/or modify
 **  it under the terms of the GNU General Public License as published by
 **  the Free Software Foundation, either version 3 of the License, or
 **  (at your option) any later version.
 **
 **  This program is distributed in the hope that it will be useful,
 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 **  GNU General Public License for more details.
 **
 **  You should have received a copy of the GNU General Public License
 **  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ** -----------------------------------------------------------------------------**
 **
 */
Andrey Filippov's avatar
Andrey Filippov committed
25
import java.awt.Point;
Andrey Filippov's avatar
Andrey Filippov committed
26 27 28
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
29
import java.util.HashSet;
Andrey Filippov's avatar
Andrey Filippov committed
30

Andrey Filippov's avatar
Andrey Filippov committed
31
import com.elphel.imagej.common.DoubleGaussianBlur;
32
import com.elphel.imagej.common.ShowDoubleFloatArrays;
Andrey Filippov's avatar
Andrey Filippov committed
33

Andrey Filippov's avatar
Andrey Filippov committed
34 35 36
import Jama.EigenvalueDecomposition;
import Jama.Matrix;

Andrey Filippov's avatar
Andrey Filippov committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

public class TilePlanes {
	private int tileSize = 0; // 8;
	private int stSize =   0; // 8;
	GeometryCorrection   geometryCorrection = null;
	public TilePlanes(
			int tileSize,
			int stSize,
			GeometryCorrection geometryCorrection){
		this.tileSize = tileSize;
		this.stSize = stSize;
		this.geometryCorrection =geometryCorrection;
	}
	public TilePlanes(
			int tileSize,
			int stSize){
		this.tileSize = tileSize;
		this.geometryCorrection = null;
	}
	public class PlaneData{
		GeometryCorrection   geometryCorrection = null;
		boolean     correctDistortions = false;
59
		// just for visualization - no there can be several measured layers and same tile can be used multiple times. Will just logical or
60 61
		boolean []  plane_sel =  null; // tile selection - has twice supertile size in each direction
		double []   zxy =        null; // [3] - plane center point {disparity, x, y), x=0, y=0 is a 4,4 point of an 8x8 supertile (in pixels, relative to this supertile center)
Andrey Filippov's avatar
Andrey Filippov committed
62 63 64 65
		double [][] vectors =    null; // [3][3] - re-ordered/re-directed eigenvectors(transposed): [0] - plane normal, most Z-like, towards camera, [1] - X-like, [2] - Y-like
		double []   values =     null; // [3] -eigenvalues
		int         num_points = 0;
		double      weight =     0.0;
66
		double []   center_xyz = null; // center of this this "plane" (ellipsoid) center in world coordinates
Andrey Filippov's avatar
Andrey Filippov committed
67
		double []   world_xyz =  null; // world coordinates of the nearest point of the plane, in meters
68
		double []   world_v1 =   null; // world in-plane vector, corresponding to vectors[1]
69
		double []   world_v2 =   null; // world in-plane vector, corresponding to vectors[2]
70
//		double []   daxy      =  null; // disparity and 2 relative angles (ax and ay) corresponding to fisheye view, near (0,0) scale is pixel size
71
		// for now keeping both weighted and equal weight merged value - later remove less useful
72 73
		double [][] merged_eig_val = null; // for each of the directions (N, NE, .. NW) quality match for each layer
		double [][] merged_eig_eq =  null; // for each of the directions (N, NE, .. NW) quality match for each layer - ignoring weights
74
		boolean [][] merged_valid = null; // for each of the directions (N, NE, .. NW) if it is possible to connect with link swaps
Andrey Filippov's avatar
Andrey Filippov committed
75 76
		boolean [][] merged_strong_valid = null; // for each of the directions (N, NE, .. NW) if it is possible to connect with link swaps (no "discounts"
		// for low weight(s)
77 78

		int    []   neib_best =  null; // new int [8]; // for each of the directions (N, NE, .. NW) index of best match, -1 if none
79 80
// stores "worsening" of merging 2 	planes. if L1,L2,L = values[0] of plane1, plane2 plane composite: w1, w2 - weights for plane1, plane2
//		Lav = Math.sqrt((L1 * L1 * w1 + L2 * L2 * w2)/(w1 + w2))
81 82
// worsening_12 = (L - Lav) * (w1 + w2) * (w1 + w2) / (Lav * x1 * w2)

Andrey Filippov's avatar
Andrey Filippov committed
83 84
		int         tileSize;
		int         superTileSize;
Andrey Filippov's avatar
Andrey Filippov committed
85
		int []      sTileXY =    null; // X and Y indices of this superTile in the image
86

87 88 89
		MeasuredLayers measuredLayers     =  null;
		boolean [][] measuredSelection =     null; // [number of layers in measuredLayers][2*superTileSize * 2*superTileSize]
		boolean   [] sel_mask          =     null; // selection mask - may be used for splitting plane along a line - each half can have mask
Andrey Filippov's avatar
Andrey Filippov committed
90 91 92
		double       min_weight =            0.0;  // minimal weight of the ellipsoid
		int          min_tiles =             10;
		double       dispNorm =              5.0;  //  Normalize disparities to the average if above
93
		boolean      smplMode =              true;   // Use sample mode (false - regular tile mode)
94 95 96
		boolean      fronto =                false; // this plane is almost fronto
		boolean      horizontal =            false; // plane created as horizontal, can not be fronto
		double       fronto_rms =            Double.NaN; // temporary, for debugging
97
		MeasuredLayersFilterParameters mlfp = new MeasuredLayersFilterParameters();     // filter parameters
98

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
//		double       measured_strength_pow = 1.0;
//		double       strength_floor =        0.0;

//		int          smplSide = 2;      // Sample size (side of a square)
//		int          smplNum  = 3;      // Number after removing worst
//		double       smplRms  = 0.1;    // Maximal RMS of the remaining tiles in a sample
//		boolean      smplWnd =  false;   // Use sample mode (false - regular tile mode)

//		double       max_abs_tilt  = 2.0; // Maximal absolute tilt in pixels/tile
//		double       max_rel_tilt  = 0.2; // Maximal relative tilt in pixels/tile/disparity
//		double       damp_tilt  =    0.001; // Damp tilt to handle insufficient  (co-linear)data
//		double       min_tilt_disp = 4.0; // Disparity switch between filtering modes - near objects use tilts, far - use max disparity
//		double       transition    = 1.0; // Mode transition range (between tilted and maximal disparity)
//		int          far_mode  =     1;   // Far objects filtering mode (0 - off, 1 - power of disparity)
//		double       far_power =     1.0; // Raise disparity to this power before averaging for far objects
114 115 116



117 118 119 120
		double [] starValueWeight = null;
		PlaneData starPlane = null;
		PlaneData nonexclusiveStar =   null;
		PlaneData nonexclusiveStarEq = null;
121 122 123

		double    conn_density = Double.NaN; //

Andrey Filippov's avatar
Andrey Filippov committed
124
		boolean      preferDisparity = false;
125

126
		// alternative "plane" calculations in the world coordinates
127 128 129
		double []    wxyz =        null; // [3] - plane center point when calculated in world coordinates (x, y , z)
		double [][]  wvectors =    null; // [3][3] - eigenvectors calculated in the real world
		double []    wvalues =     null; // [3] -eigenvalues calculated in the real world
130
		double [][]  merged_weig_val = null; // for each of the directions (N, NE, .. NW) quality match for each layer
131 132
		double [][]  merged_weig_eq =  null; // for each of the directions (N, NE, .. NW) quality match for each layer - ignoring weights
		double [][]  link_costs; // for each of the directions (N, NE, .. NW) composite cost of connection
133

Andrey Filippov's avatar
Andrey Filippov committed
134
		int mark0 = -1; // just for temporary labeling the plane
135 136

		@Override
137 138 139 140 141
		public PlaneData clone(){
			PlaneData pd = new PlaneData(
					this.sTileXY,
					this.tileSize,
					this.superTileSize,
142 143 144
					this.geometryCorrection,
					this.correctDistortions);
//			pd.correctDistortions = this.correctDistortions;
145 146
			pd.num_points = this.num_points;
			pd.weight =     this.weight;
147 148 149 150
			if (this.plane_sel != null)  pd.plane_sel =  this.plane_sel.clone();
			if (this.values != null)     pd.values =     this.values.clone();
			if (this.zxy != null)        pd.zxy =        this.zxy.clone();
			// World calculations should be invalidated during cloning?
151 152 153 154 155 156
			if (this.vectors != null) {
				pd.vectors = new double[3][];
				pd.vectors[0] = this.vectors[0].clone();
				pd.vectors[1] = this.vectors[1].clone();
				pd.vectors[2] = this.vectors[2].clone();
			}
157 158 159 160 161
			// Adding cloning of the calculated center_xyz and world_xyz (normal). Check that it did not break anything
			if (this.center_xyz != null) pd.center_xyz = this.center_xyz.clone();
			if (this.world_xyz != null) pd.world_xyz = this.world_xyz.clone();
			if (this.world_v1 != null) pd.world_v1 = this.world_v1.clone();
			if (this.world_v2 != null) pd.world_v2 = this.world_v2.clone();
162

Andrey Filippov's avatar
Andrey Filippov committed
163
			if (this.measuredLayers != null) pd.measuredLayers = this.measuredLayers;
164

165
			pd.setMeasSelection(this.measuredSelection);
166

167
			if (this.sel_mask != null) pd.sel_mask = this.sel_mask.clone();
168

Andrey Filippov's avatar
Andrey Filippov committed
169 170 171
			pd.min_weight =            this.min_weight;
			pd.min_tiles =             this.min_tiles;
			pd.dispNorm =              this.dispNorm;
172

173
			pd.smplMode =              this.smplMode;
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

			pd.mlfp = this.mlfp.clone();
//			pd.measured_strength_pow = this.measured_strength_pow;
//			pd.strength_floor =        this.strength_floor;

//			pd.smplSide =              this.smplSide;
//			pd.smplNum =               this.smplNum;
//			pd.smplRms =               this.smplRms;

//			pd.max_abs_tilt =          this.max_abs_tilt;
//			pd.max_rel_tilt =          this.max_rel_tilt;
//			pd.damp_tilt =             this.damp_tilt;
//			pd.min_tilt_disp =         this.min_tilt_disp;
//			pd.transition =            this.transition;
//			pd.far_mode =              this.far_mode;
//			pd.far_power =             this.far_power;
190

191
			pd.preferDisparity =       this.preferDisparity;
192

Andrey Filippov's avatar
Andrey Filippov committed
193
			copyNeib(this,pd);
194
			copyStar(this,pd);
195
/*
196 197 198
			if (starValueWeight != null){
				pd.starValueWeight = starValueWeight.clone();
			}
199 200 201
			if (this.starPlane !=          null) pd.starPlane =          this.starPlane;
			if (this.nonexclusiveStar !=   null) pd.nonexclusiveStar =   this.nonexclusiveStar;
			if (this.nonexclusiveStarEq != null) pd.nonexclusiveStarEq = this.nonexclusiveStarEq;
202 203
			pd.conn_density =          this.conn_density;
*/
204 205
			pd.num_points =            this.num_points; // restore, maybe remove from copy_neib?
//
206 207 208 209 210 211 212 213 214 215
			if (this.wxyz != null)        pd.wxyz =        this.wxyz.clone();

			if (this.wvalues != null)     pd.wvalues =     this.wvalues.clone();

			if (this.wvectors != null) {
				pd.wvectors = new double[3][];
				pd.wvectors[0] = this.wvectors[0].clone();
				pd.wvectors[1] = this.wvectors[1].clone();
				pd.wvectors[2] = this.wvectors[2].clone();
			}
216 217 218
			pd.mark0 =  this.mark0;
			pd.fronto = this.fronto;
			pd.horizontal = this.horizontal;
219 220
			return pd;
		}
221

Andrey Filippov's avatar
Andrey Filippov committed
222 223 224
		public int getMark0(){
			return this.mark0;
		}
225

Andrey Filippov's avatar
Andrey Filippov committed
226 227 228
		public void setMark0(int mark0){
			this.mark0 = mark0;
		}
229

Andrey Filippov's avatar
Andrey Filippov committed
230 231 232
		public boolean getPreferDisparity(){
			return this.preferDisparity;
		}
233

234 235 236
		public String getNeibString()
		{
			if (neib_best == null) {
237
				return "[      undefined       ] ";
238 239 240 241 242 243 244 245
			}
			String s = "[";
			for (int dir = 0; dir < 8; dir++){
				s += (neib_best[dir]>=0) ? neib_best[dir]:"x";
				if (dir < 7) s += ", ";
			}
			s+= "] ";
			return s;
246

247
		}
248
/*
249
		public boolean isHorizontalW(){
250
			if (wvectors != null){
251 252 253 254
				return (Math.abs(wvectors[0][1]) > 0.99) && (checkBadPlate(false) < 0.2);
			}
			return false;
		}
255
*/
256 257
		public boolean isHorizontal(){
			if (world_xyz != null){
258
				double norm = world_xyz[1] / Math.sqrt(world_xyz[0]*world_xyz[0] + world_xyz[1]*world_xyz[1] + world_xyz[2]*world_xyz[2]);
259
				return (Math.abs(norm) > 0.99) && (checkBadPlate(false) < 0.2);
260 261 262
			}
			return false;
		}
263

Andrey Filippov's avatar
Andrey Filippov committed
264 265 266 267
		public double get2dRatio(){
			if (wvalues != null) return Math.sqrt(wvalues[1]/wvalues[0]);
			return Double.NaN;
		}
268 269 270 271 272 273 274 275 276
		/**
		 * Verify plane normal in real world and calculated from pixels/disparity
		 * Use to check consistency
		 * @return sin squared of the angle between 2 normals, or NaN if there is no data to calculate it
		 */
		public double checkBadPlate(boolean force)
		{
			if (!force && (world_xyz == null)) return Double.NaN;
			if (wvectors == null) return Double.NaN;
277 278 279
			double [] anorm_disp = this.getWorldXYZ(this.correctDistortions, 0);
			if (anorm_disp == null) return Double.NaN;
			Matrix norm_disp =  new Matrix(anorm_disp,3); // normal to plane from disparity space
280 281 282 283 284 285 286
			Matrix norm_world =  new Matrix(wvectors[0],3); // normal to plane from disparity space
			Matrix cp = cross3d(norm_disp, norm_world);
			double cp2 = cp.transpose().times(cp).get(0, 0);
			double this_wv2 = norm_disp.transpose().times(norm_disp).get(0, 0);
			double other_wv2 = norm_world.transpose().times(norm_world).get(0, 0);
			return cp2/(this_wv2 * other_wv2);
		}
287

288 289 290 291 292 293 294 295 296 297 298 299
		public double checkBadStick(boolean force)
		{
			if (!force && (world_xyz == null)) return Double.NaN;
			if (wvectors == null) return Double.NaN;
			Matrix long_disp =  new Matrix(this.getWorldV12(true,this.correctDistortions, 0),3); // normal to plane from disparity space
			Matrix long_world =  new Matrix(wvectors[2],3); // normal to plane from disparity space
			Matrix cp = cross3d(long_disp, long_world);
			double cp2 = cp.transpose().times(cp).get(0, 0);
			double this_wv2 = long_disp.transpose().times(long_disp).get(0, 0);
			double other_wv2 = long_world.transpose().times(long_world).get(0, 0);
			return cp2/(this_wv2 * other_wv2);
		}
300 301

		@Override
302 303
		public String toString()
		{
304

305 306 307 308 309
			String s = "          ";
			s += getNeibString();
			if (isHorizontal()){
				s+= "HORIZONTAL ";
			}
310 311 312
			if (fronto){
				s+= String.format("FRONTO (%6.4f)",fronto_rms);
			}
313
			s += String.format("2d=%4.1f ", get2dRatio());
314 315
			s += String.format( "np=%3d weight= %8.5f", num_points, weight);
			if (starValueWeight != null) s += String.format(" star=[%8.5f, %8.5f]", starValueWeight[0], starValueWeight[1]);
316
			else                         s +=               " star=  null";
317
			s += String.format(" dens=%8.5f", conn_density);
Andrey Filippov's avatar
Andrey Filippov committed
318 319
			double [] px_py = getCenterPxPy();
			if (zxy != null) s += String.format("\nzxy =     [%8.3f, %8.3f, %8.3f] (pix)",zxy[0],zxy[1]+px_py[0],zxy[2]+px_py[1]);
320
			else  s +=                          "\nzxy =     null";
321
			if (values != null)	s += String.format(", values = [%8.5f, %8.4f, %8.3f] (%8.3f) pix^2",values[0],values[1],values[2], getNormValue());
322 323 324 325 326
			else  s +=                             " values = null";
			if (vectors != null) s += String.format("\nvectors = [%8.5f, %8.5f, %8.5f], [%8.5f, %8.5f, %8.5f], [%8.5f, %8.5f, %8.5f]",
					vectors[0][0],vectors[0][1],vectors[0][2], vectors[1][0],vectors[1][1],vectors[1][2], vectors[2][0],vectors[2][1],vectors[2][2]);
			if (center_xyz != null) s += String.format("\ncenter =  [%8.2f, %8.2f, %8.2f]",center_xyz[0],center_xyz[1],center_xyz[2]);
			else  s +=                                 "\ncenter =   null";
327

328 329
			if (world_xyz != null)  s += String.format(" normal = [%8.2f, %8.2f, %8.2f] (m)",world_xyz[0],world_xyz[1],world_xyz[2]);
			else s +=                                  " normal =   null";
330

331 332 333 334 335 336 337 338 339 340 341
			double bad_plate = checkBadPlate(false);
			if (!Double.isNaN(bad_plate)){
				s+=String.format(" bad_plate=%6.4f", bad_plate);
			}
			double bad_stick = checkBadStick(false);
			if (!Double.isNaN(bad_plate)){
				s+=String.format(" bad_stick=%6.4f", bad_stick);
			}
			double [] world_xyz_w = getWorldXYZFromWorld();
			if (world_xyz_w != null) s += String.format("\n%34s world normal = [%8.2f, %8.2f, %8.2f] (m)","",world_xyz_w[0],world_xyz_w[1],world_xyz_w[2]);

342 343
			if (wxyz != null)       s += String.format("\nwxyz =    [%8.2f, %8.2f, %8.2f] (m)",wxyz[0],wxyz[1],wxyz[2]);
			else s +=                                  "\nwxyz =  null";
Andrey Filippov's avatar
Andrey Filippov committed
344
			if (wvalues != null)    s += String.format(" wvals = [%8.4f, %8.3f, %8.2f] (m^2)",wvalues[0],wvalues[1],wvalues[2]);
345 346 347 348 349 350 351 352 353
			else  s +=                                 " wvals =  null";
			if (wvectors != null) s += String.format("\nwvect =   [%8.5f, %8.5f, %8.5f], [%8.5f, %8.5f, %8.5f], [%8.5f, %8.5f, %8.5f]",
					wvectors[0][0],wvectors[0][1],wvectors[0][2], wvectors[1][0],wvectors[1][1],wvectors[1][2], wvectors[2][0],wvectors[2][1],wvectors[2][2]);
			if (nonexclusiveStar != null){
				s+= "\nweighted: ";
				s+= nonexclusiveStar.getNeibString();
				if (nonexclusiveStar.isHorizontal()){
					s+= "HORIZONTAL ";
				}
354
				s += String.format("2d=%4.1f ", nonexclusiveStar.get2dRatio());
355
				s += String.format( "np=%3d weight= %8.5f", nonexclusiveStar.num_points, nonexclusiveStar.weight);
Andrey Filippov's avatar
Andrey Filippov committed
356
				double [] ne_px_py = getCenterPxPy();
357
				if (nonexclusiveStar.center_xyz != null) s += String.format("\n--center =[%8.2f, %8.2f, %8.2f]",
Andrey Filippov's avatar
Andrey Filippov committed
358 359 360
						nonexclusiveStar.center_xyz[0],
						nonexclusiveStar.center_xyz[1], //  + ne_px_py[0],
						nonexclusiveStar.center_xyz[2]); //  + ne_px_py[1]);
361 362 363 364
				else  s +=                                 "\n--ncenter =   null";
				if (nonexclusiveStar.world_xyz != null)  s += String.format(" normal = [%8.2f, %8.2f, %8.2f] (m)",
						nonexclusiveStar.world_xyz[0],nonexclusiveStar.world_xyz[1],nonexclusiveStar.world_xyz[2]);
				else s +=                                  " normal =   null";
365 366 367 368 369 370 371 372
				bad_plate = nonexclusiveStar.checkBadPlate(false);
				if (!Double.isNaN(bad_plate)){
					s+=String.format(" bad_plate=%6.4f", bad_plate);
				}
				bad_stick = nonexclusiveStar.checkBadStick(false);
				if (!Double.isNaN(bad_plate)){
					s+=String.format(" bad_stick=%6.4f", bad_stick);
				}
373

374 375 376 377
			}
			if (nonexclusiveStarEq != null){
				s+= "\nequalized:";
				s+= nonexclusiveStarEq.getNeibString();
Andrey Filippov's avatar
Andrey Filippov committed
378
				if (nonexclusiveStarEq.isHorizontal()){
379 380
					s+= "HORIZONTAL ";
				}
381
				s += String.format("2d=%4.1f ", nonexclusiveStarEq.get2dRatio());
382
				s += String.format( "np=%3d weight= %8.5f", nonexclusiveStarEq.num_points, nonexclusiveStarEq.weight);
Andrey Filippov's avatar
Andrey Filippov committed
383
				double [] ne_px_py = getCenterPxPy();
384
				if (nonexclusiveStarEq.center_xyz != null) s += String.format("\n--center =[%8.2f, %8.2f, %8.2f]",
Andrey Filippov's avatar
Andrey Filippov committed
385 386 387
						nonexclusiveStarEq.center_xyz[0],
						nonexclusiveStarEq.center_xyz[1], //  + ne_px_py[0],
						nonexclusiveStarEq.center_xyz[2]); //  + ne_px_py[1]);
388 389 390 391
				else  s +=                                 "\n--ncenter =   null";
				if (nonexclusiveStarEq.world_xyz != null)  s += String.format(" normal = [%8.2f, %8.2f, %8.2f] (m)",
						nonexclusiveStarEq.world_xyz[0],nonexclusiveStarEq.world_xyz[1],nonexclusiveStarEq.world_xyz[2]);
				else s +=                                  " normal =   null";
392 393 394 395 396 397 398 399
				bad_plate = nonexclusiveStarEq.checkBadPlate(false);
				if (!Double.isNaN(bad_plate)){
					s+=String.format(" bad_plate=%6.4f", bad_plate);
				}
				bad_stick = nonexclusiveStarEq.checkBadStick(false);
				if (!Double.isNaN(bad_plate)){
					s+=String.format(" bad_stick=%6.4f", bad_stick);
				}
400
			}
Andrey Filippov's avatar
Andrey Filippov committed
401 402 403 404 405 406 407 408 409 410 411 412 413 414
			s+="\n";
			if (link_costs != null){
				for (int dir = 0; dir < link_costs.length; dir++){
					s+=String.format("dir=%d: ", dir);
					if (link_costs[dir] != null) {
						int best_np = -1;
						for (int np = 0; np < link_costs[dir].length; np++){
							if (!Double.isNaN(link_costs[dir][np]) && ((best_np < 0) || (link_costs[dir][np] < link_costs[dir][best_np]))){
								best_np = np;
							}
						}
						for (int np = 0; np < link_costs[dir].length; np++){
							if (np == best_np){
								s+=String.format("%7.3f[%d] ", link_costs[dir][np],np);
415

Andrey Filippov's avatar
Andrey Filippov committed
416 417 418 419 420 421 422 423
							} else {
								s+=String.format("%7.3f    ", link_costs[dir][np]);
							}
						}
					}
					s+="\n";
				}
			}
424
//			s+="\n";
425 426
			return s;
		}
427

428 429 430 431
		public PlaneData getNonexclusiveStar()
		{
			return this.nonexclusiveStar;
		}
432 433 434 435 436
		public PlaneData getNonexclusiveStarFb() // fallback to this plane if nonexclusiveStar is not available
		{
			if (this.nonexclusiveStar != null) return this.nonexclusiveStar;
			return this;
		}
437

438 439 440 441 442 443 444 445 446
		public void setNonexclusiveStar( PlaneData pd)
		{
			this.nonexclusiveStar = pd;
		}

		public PlaneData getNonexclusiveStarEq()
		{
			return this.nonexclusiveStarEq;
		}
447 448 449 450 451 452

		public PlaneData getNonexclusiveStarEqFb() // fallback to this plane if nonexclusiveStarEq is not available
		{
			if (this.nonexclusiveStarEq != null) return this.nonexclusiveStarEq;
			return this;
		}
453 454


455 456 457 458 459 460 461 462 463 464 465 466 467 468
		public void setNonexclusiveStarEq( PlaneData pd)
		{
			this.nonexclusiveStarEq = pd;
		}

		public PlaneData getStarPlane()
		{
			return this.starPlane;
		}
		public void setStarPlane( PlaneData pd)
		{
			this.starPlane = pd;
		}

469

470 471
		public double getConnectionDensity(){
			return conn_density;
472
		}
473

474 475

		public void setStarValueWeight(double[] val_weight){
476 477 478 479 480 481 482
			this.starValueWeight = new double[2];
			this.starValueWeight[0] = val_weight[0];
			this.starValueWeight[1] = val_weight[1];
			this.conn_density = 0.0;
//			if (val_weight.length > 2){
			this.conn_density = val_weight[2];
//			}
483 484 485 486 487 488
		}

		public double [] getStarValueWeight()
		{
			return starValueWeight;
		}
489 490 491 492 493
		public double [] getStarValueWeightDensity()
		{
			double [] vwd = {starValueWeight[0], starValueWeight[1], conn_density};
			return vwd;
		}
494 495


496 497 498 499 500 501 502 503
		public void setSelMask (boolean []sel_mask)
		{
			this.sel_mask = sel_mask;
		}
		public boolean [] getSelMask ()
		{
			return this.sel_mask;
		}
504

505 506
		public void setMeasSelection(boolean [][] meas_sel)
		{
507
			if (meas_sel == null)
508 509 510 511 512 513 514 515 516 517
				this.measuredSelection = null;
			else {
				this.measuredSelection = meas_sel.clone();
				for (int i = 0; i < meas_sel.length; i++){
					if (meas_sel[i] != null) {
						this.measuredSelection[i] = meas_sel[i].clone();
					}
				}
			}
		}
518 519 520

		public void orMeasSelection(boolean [][] meas_sel)
		{
521
			if (meas_sel == null)
522 523 524 525 526 527 528 529 530 531 532 533 534 535
				this.measuredSelection = null;
			else {
				if (this.measuredSelection == null) {
					this.measuredSelection = meas_sel.clone();
				}
				for (int i = 0; i < meas_sel.length; i++){
					if (meas_sel[i] != null) {
						if (this.measuredSelection[i] == null) {
							this.measuredSelection[i] = meas_sel[i].clone();
						} else {
							for (int j = 0; j < meas_sel[i].length; j++){
								this.measuredSelection[i][j] |= meas_sel[i][j];
							}
						}
536
					}
537 538 539
				}
			}
		}
540 541 542



543 544 545 546 547 548
		public boolean [] getMeasSelection(int nl){
			if (this.measuredSelection == null) {
				return null;
			}
			return 	this.measuredSelection[nl];
		}
549 550 551 552

		public boolean [][] getMeasSelection(){
			return 	this.measuredSelection;
		}
553 554


555 556 557 558
		public MeasuredLayers getMeasuredLayers()
		{
			return this.measuredLayers;
		}
559

560 561 562 563
		public void copyStar(
				PlaneData src,
				PlaneData dst)

564

565 566 567 568 569 570 571 572 573
		{
			if (src.starValueWeight != null){
				dst.starValueWeight = src.starValueWeight.clone();
			}
			if (src.starPlane !=          null) dst.starPlane =          src.starPlane;
			if (src.nonexclusiveStar !=   null) dst.nonexclusiveStar =   src.nonexclusiveStar;
			if (src.nonexclusiveStarEq != null) dst.nonexclusiveStarEq = src.nonexclusiveStarEq;
			dst.conn_density =          src.conn_density;
		}
574

Andrey Filippov's avatar
Andrey Filippov committed
575 576 577 578 579 580 581 582 583 584 585 586
		public void copyNeib(
				PlaneData src,
				PlaneData dst)
		{
			if (src.merged_eig_val != null){
				dst.merged_eig_val = src.merged_eig_val.clone();
				for (int i = 0; i < src.merged_eig_val.length; i++){
					if (src.merged_eig_val[i] != null){
						dst.merged_eig_val[i] = src.merged_eig_val[i].clone();
					}
				}
			}
587

588 589 590 591 592 593 594 595
			if (src.merged_eig_eq != null){
				dst.merged_eig_eq = src.merged_eig_eq.clone();
				for (int i = 0; i < src.merged_eig_eq.length; i++){
					if (src.merged_eig_eq[i] != null){
						dst.merged_eig_eq[i] = src.merged_eig_eq[i].clone();
					}
				}
			}
596

597 598 599 600 601 602 603 604
			if (src.merged_weig_val != null){
				dst.merged_weig_val = src.merged_weig_val.clone();
				for (int i = 0; i < src.merged_weig_val.length; i++){
					if (src.merged_weig_val[i] != null){
						dst.merged_weig_val[i] = src.merged_weig_val[i].clone();
					}
				}
			}
605

606 607 608 609 610 611 612 613
			if (src.merged_weig_eq != null){
				dst.merged_weig_eq = src.merged_weig_eq.clone();
				for (int i = 0; i < src.merged_weig_eq.length; i++){
					if (src.merged_weig_eq[i] != null){
						dst.merged_weig_eq[i] = src.merged_weig_eq[i].clone();
					}
				}
			}
614

615 616 617 618 619 620 621 622
			if (src.merged_valid != null){
				dst.merged_valid = src.merged_valid.clone();
				for (int i = 0; i < src.merged_valid.length; i++){
					if (src.merged_valid[i] != null){
						dst.merged_valid[i] = src.merged_valid[i].clone();
					}
				}
			}
Andrey Filippov's avatar
Andrey Filippov committed
623 624 625 626 627 628 629 630 631 632

			if (src.merged_strong_valid != null){
				dst.merged_strong_valid = src.merged_strong_valid.clone();
				for (int i = 0; i < src.merged_strong_valid.length; i++){
					if (src.merged_strong_valid[i] != null){
						dst.merged_strong_valid[i] = src.merged_strong_valid[i].clone();
					}
				}
			}

633 634 635 636 637 638 639 640
			if (src.link_costs != null){
				dst.link_costs = src.link_costs.clone();
				for (int i = 0; i < src.link_costs.length; i++){
					if (src.link_costs[i] != null){
						dst.link_costs[i] = src.link_costs[i].clone();
					}
				}
			}
641 642


Andrey Filippov's avatar
Andrey Filippov committed
643
			if (src.neib_best != null) dst.neib_best = src.neib_best.clone();
644

Andrey Filippov's avatar
Andrey Filippov committed
645
			// also copy original plane parameters - tile selection and number of points
646 647 648

//			dst.num_points = src.num_points;
			if (src.plane_sel != null)  dst.plane_sel =  src.plane_sel.clone();
Andrey Filippov's avatar
Andrey Filippov committed
649
		}
650

Andrey Filippov's avatar
Andrey Filippov committed
651 652 653 654
		public void invalidateCalculated()
		{
			this.center_xyz = null; // center of this supertile this plane center in world coordinates
			this.world_xyz =  null; // world coordinates of the nearest point of the plane, in meters
655
			this.world_v1 =   null; // world in-plane vector, corresponding to vectors[1]
Andrey Filippov's avatar
Andrey Filippov committed
656 657
			this.world_v2 =   null; // world in-plane vector, corresponding to vectors[1]
		}
658 659


Andrey Filippov's avatar
Andrey Filippov committed
660
		public PlaneData (
661
				int [] sTileXY,
Andrey Filippov's avatar
Andrey Filippov committed
662 663
				int tileSize,
				int superTileSize,
664 665
				GeometryCorrection   geometryCorrection,
				boolean              correctDistortions)
Andrey Filippov's avatar
Andrey Filippov committed
666 667
		{
			this.geometryCorrection = geometryCorrection;
668
			this.correctDistortions = correctDistortions;
Andrey Filippov's avatar
Andrey Filippov committed
669 670 671 672
			this.tileSize = tileSize;
			this.superTileSize = superTileSize;
			this.sTileXY = sTileXY.clone();
		}
Andrey Filippov's avatar
Andrey Filippov committed
673 674

		public PlaneData (
675
				int [] sTileXY,
Andrey Filippov's avatar
Andrey Filippov committed
676 677
				int tileSize,
				GeometryCorrection   geometryCorrection,
678
				boolean              correctDistortions,
Andrey Filippov's avatar
Andrey Filippov committed
679 680 681 682
				MeasuredLayers measuredLayers,
				boolean preferDisparity)
		{
			this.geometryCorrection = geometryCorrection;
683
			this.correctDistortions = correctDistortions;
Andrey Filippov's avatar
Andrey Filippov committed
684 685 686 687 688 689
			this.tileSize = tileSize;
			this.superTileSize = measuredLayers.getSuperTileSize();
			this.sTileXY = sTileXY.clone();
			this.measuredLayers = measuredLayers;
			this.preferDisparity = preferDisparity;
		}
690 691

		/**
692
		 * Create separation masks for two crossing planes. Uses neighbors connections to distinguish between concave and convex
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
		 * @param pd1 first plane data instance to create sel_mak
		 * @param pd2 second plane data instance to create sel_mak
		 * @param tolerance disparity tolerance for separation (will be normalized by dispNorm for large disparities)
		 * @param min_tiles minimal number of tiles in each half
		 * @param debugLevel debug level
		 * @return true if OK, false if the planes are not crossing (masks not created)
		 */
		public boolean calcSelMasks(
				PlaneData pd1,
				PlaneData pd2,
				double    tolerance,
				int       min_tiles,
				int       debugLevel
				)
		{
			int st2 = 2 * superTileSize;
			int [] dirs = {-st2, -st2 + 1, 1, st2 + 1, st2, st2 - 1, -1, -st2 - 1};
			double [][] planes = {
					pd1.getDoublePlaneDisparity(false),
					pd2.getDoublePlaneDisparity(false)};
			PlaneData [] pair = {pd1,pd2};
			int len2 = planes[0].length;
			boolean [][] sel_masks = new boolean [2][len2];
			double concave = 0; // positive - concave, negative - convex
			int cent_indx = (st2/2 -1) * (st2+1);
			for (int np = 0; np < 2; np++){
				int [] neibs = pair[np].getNeibBest();
				for (int dir = 0; dir < dirs.length; dir++) {
					if (neibs[dir] >= 0) { // neighbor connected
						int indx = cent_indx + dirs[dir];
						concave += (planes[np][indx] - planes[np][cent_indx]) - (planes[1 - np][indx] - planes[1 - np][cent_indx]);
					}
				}
			}
			// swap plane selections for convex plane intersection (edge is the closest)
			int first = (concave < 0) ? 1 : 0;
			int [] nums = {0, 0};
730

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
			for (int i = 0; i <len2; i++){
				double d_av = 0.5 * (planes[0][i] + planes[1][i]);
				double diff = planes[0][i] - planes[1][i];
				if ((dispNorm > 0.0) && (d_av > dispNorm)){
					diff *= dispNorm/d_av;
				}
				if (diff > -tolerance) {
					sel_masks[first][i] = true;
					nums[first] ++;
				}
				if (-diff > -tolerance) {
					sel_masks[1-first][i] = true;
					nums[1-first] ++;
				}
			}
			if ((nums[0] < min_tiles) || (nums[1] < min_tiles)){
				return false;
			}
			// apply selections
			pd1.setSelMask(sel_masks[0]);
			pd2.setSelMask(sel_masks[1]);
			return true;
		}
754

755 756 757 758 759 760 761 762
		/**
		 * Spit tiles belonging to this between multiple PlaneData instances
		 * @param pd_set array of plane data instances
		 * @param single_plane it is a single plane to split - use all tiles, not just previously
		 *  selected
		 * @param max_diff maximal normalized disparity difference from the plane to consider
		 * @param other_diff maximal difference of the added tile ratio to the average
		 *  disparity difference of the exclusively selected tiles
763
		 *
764 765
		 * @param non_exclusive allow the same tile data to belong to multiple PD instances
		 * @param use_other_planes allow the same tile not included in this PD to be used
766 767 768
		 * @param smplMode use square sample mode, false - single-tile samples
		 * @param smplSide size of the square sample side
		 * @param smplNum number of averaged samples (should be <= smplSide * smplSide and > 1)
769
		 * @param smplRms maximal square root of variance (in disparity pixels) to accept the result
770 771 772 773 774 775
		 * @param measSel (with use_other_planes) select measurements for supertiles :
		 *  +1 - combo, +2 - quad +4 - hor +8 - vert
		 * @param allow_parallel allow parallel shift of each plane before adding more data
		 * @param debugLevel debug level
		 * @return true if OK
		 */
776

777 778 779 780
		public boolean splitPlaneTiles (
				PlaneData [] pd_set,
				boolean      single_plane,
				double       max_diff, // maximal disparity difference (0 - any), will be normalized by dispNorm
781
				double       other_diff,
782 783
				boolean      non_exclusive,
				boolean      use_other_planes,
784
				boolean      smplMode, //        = true;   // Use sample mode (false - regular tile mode)
785 786 787 788 789 790 791 792 793 794 795 796 797 798

				MeasuredLayersFilterParameters mlfp,
//				int          smplSide, //        = 2;      // Sample size (side of a square)
//				int          smplNum, //         = 3;      // Number after removing worst
//				double       smplRms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
//				boolean      smplWnd,  // use window functions for the samples

//	  			double       max_abs_tilt,  //  2.0;   // pix per tile
//				double       max_rel_tilt,  //  0.2;   // (pix / disparity) per tile
//				double       damp_tilt,     //  0.001; // Damp tilt to handle insufficient  (co-linear)data
//				double       min_tilt_disp, //  4.0;   // Disparity switch between filtering modes - near objects use tilts, far - use max disparity
//				double       transition,    //  1.0;   // Mode transition range (between tilted and maximal disparity)
//				int          far_mode,      //  1;     // Far objects filtering mode (0 - off, 1 - power of disparity)
//				double       far_power,     //  3.0;   // Raise disparity to this power before averaging for far objects
799

800 801 802 803 804 805 806
				int          measSel, // Select measurements for supertiles : +1 - combo, +2 - quad +4 - hor +8 - vert
				boolean      allow_parallel,
				int          debugLevel)
		{
			if (debugLevel>0){
				System.out.println("splitPlaneTiles");
			}
807

808 809 810 811 812 813 814 815 816 817 818 819 820 821
			double [][] planes = new double [pd_set.length][];
			boolean [][][] tsel = new boolean [pd_set.length][measuredLayers.getNumLayers()][];
			boolean [][] sel_masks = new boolean [pd_set.length][];
			for (int np = 0; np < pd_set.length; np ++) if (pd_set[np] != null){
				planes[np] = pd_set[np].getDoublePlaneDisparity(false);
				sel_masks[np] = pd_set[np].getSelMask();
				for (int nl = 0; nl < measuredLayers.getNumLayers(); nl++){
					if (measuredSelection[nl] != null){
						tsel[np][nl] = new boolean [measuredSelection[nl].length];
					}
				}
//				pd_set[np].setMeasSelection(measuredSelection); // copy same selection to all planes
			}
			double max_diff2 = max_diff * max_diff;
822
			double other_diff2 =other_diff * other_diff;
823 824 825 826 827 828 829
			double [] sd2 = new double[pd_set.length];
			double [] sd2_av = new double[pd_set.length];
			double [] sw =  new double[pd_set.length];
			double [][][] disp_strength = new double[measuredLayers.getNumLayers()][][];
			// split exclusively, calculate rms for each, then add others if RMS is not increased
			for (int nl = 0; nl < measuredLayers.getNumLayers(); nl ++){
				if ((measuredSelection[nl] != null) &&  ((measSel & (1 << nl)) !=0)) {
830
					if (smplMode) {
831
						disp_strength[nl] = measuredLayers.getDisparityStrengthMLTilted( // expensive to calculate (improve removing outliers
832 833 834 835
								nl, // int num_layer,
								getSTileXY()[0],        // int stX,
								getSTileXY()[1],        // int stY,
								(single_plane ? null : measuredSelection[nl]),  // boolean [] sel_in,
836 837 838 839 840 841 842 843 844 845 846 847 848 849
								mlfp,
//								strength_floor,
//								measured_strength_pow, //
//								smplSide, //        = 2;      // Sample size (side of a square)
//								smplNum, //         = 3;      // Number after removing worst
//								smplRms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
//								smplWnd,  // use window functions for the samples
//								max_abs_tilt,  // 2.0; // Maximal absolute tilt in pixels/tile
//								max_rel_tilt,  // 0.2; // Maximal relative tilt in pixels/tile/disparity
//								damp_tilt,     //    0.001; // Damp tilt to handle insufficient  (co-linear)data
//								min_tilt_disp, // 4.0; // Disparity switch between filtering modes - near objects use tilts, far - use max disparity
//								transition,    // 1.0; // Mode transition range (between tilted and maximal disparity)
//								far_mode,      //     1;   // Far objects filtering mode (0 - off, 1 - power of disparity)
//								far_power,     //    1.0; // Raise disparity to this power before averaging for far objects
850 851
								true, // boolean null_if_none)
								debugLevel);
852
					} else {
Andrey Filippov's avatar
Andrey Filippov committed
853
						disp_strength[nl] = measuredLayers.getDisparityStrengthML(
854 855 856 857
								nl,                     // int num_layer,
								getSTileXY()[0],        // int stX,
								getSTileXY()[1],        // int stY,
								(single_plane ? null : measuredSelection[nl]),  // boolean [] sel_in,
858 859 860
								mlfp,
//								strength_floor,         //  double strength_floor,
//								measured_strength_pow,  // double strength_pow,
861 862
								true);                  // boolean null_if_none);
					}
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
					if (disp_strength[nl] != null) {
						for (int indx = 0; indx < disp_strength[nl][1].length; indx++){
							double w = disp_strength[nl][1][indx];
							if (w > 0.0){
								double d = disp_strength[nl][0][indx];
								double d2_best = Double.NaN;
								int np_best = 0;
								for (int np = 0; np < planes.length; np++) if (planes[np] != null){
									if ((sel_masks[np] == null) || sel_masks[np][indx]) {
										double d_av = 0.5 * (d + planes[np][indx]);
										double d2 = (d - planes[np][indx]);
										if ((dispNorm > 0.0) && (d_av > dispNorm)){
											d2 *= dispNorm/d_av;
										}
										d2 *= d2;
										if (!(d2 >= d2_best)){ // so d2_best NaN is OK
											d2_best = d2;
											np_best = np;
										}
									}
								}
								if ((max_diff2 == 0.0) || (d2_best < max_diff2)) {
									tsel[np_best][nl][indx] = true;
									sd2[np_best] += w * d2_best;
									sw[np_best] += w;
								}
							}
						}
					}
				}
			}
			for (int np = 0; np < planes.length; np++) if (planes[np] != null){
				if (sw[np] > 0.0){
					sd2_av[np] = sd2[np] / sw[np];
				}
			}
			double [] sd = new double[pd_set.length]; // will be all 0.0;

			if (allow_parallel && (non_exclusive || use_other_planes)){
				for (int nl = 0; nl < measuredLayers.getNumLayers(); nl ++){
					if (disp_strength[nl] != null) {
						for (int indx = 0; indx < disp_strength[nl][1].length; indx++){
							double w = disp_strength[nl][1][indx];
							if (w > 0.0){
								double d = disp_strength[nl][0][indx];
								for (int np = 0; np < planes.length; np++) if (planes[np] != null){
									if (!tsel[np][nl][indx]) { // not already in that plane
										sd[np] += w * d;
									}
								}
							}
						}
					}
				}
				for (int np = 0; np < planes.length; np++) if (planes[np] != null){
					if (sw[np] > 0.0){
						sd[np] /= sw[np];
						sd2_av[np] -= sd[np] * sd[np];
921
						sd2[np] = sd2_av[np] * sw[np]; // to add more
922 923
					}
				}
924

925
			}
926 927


928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
			if (non_exclusive) {
				for (int nl = 0; nl < measuredLayers.getNumLayers(); nl ++){
					if ((measuredSelection[nl] != null) &&  ((measSel & (1 << nl)) !=0)) {
						if (disp_strength[nl] != null) {
							for (int indx = 0; indx < disp_strength[nl][1].length; indx++){
								double w = disp_strength[nl][1][indx];
								if (w > 0.0){
									double d = disp_strength[nl][0][indx];
									for (int np = 0; np < planes.length; np++) if (planes[np] != null){
										if ((sel_masks[np] == null) || sel_masks[np][indx]) {
											if (!tsel[np][nl][indx]) { // not already in that plane
												double d_av = 0.5 * (d - planes[np][indx]);
												double d2 = (d - planes[np][indx]);
												d2 -= sd[np]; // subtract parallel shift
												if ((dispNorm > 0.0) && (d_av > dispNorm)){
													d2 *= dispNorm/d_av;
												}
												d2 *= d2;
946
												if (d2 <= sd2_av[np] * other_diff2) { // not more than exclusive tile variance
947 948 949 950 951 952 953 954
													tsel[np][nl][indx] = true;
													sd2[np] += w * d2;
													sw[np] += w;
												}
											}
										}
									}
								}
955
							}
956 957 958 959
						}
					}
				}
			}
960

961 962 963 964
			if (use_other_planes && !single_plane) { // no need if single_plane - it already got all planes it could
				for (int nl = 0; nl < measuredLayers.getNumLayers(); nl ++){
					if ((measuredSelection[nl] != null) &&  ((measSel & (1 << nl)) !=0)) {
						// recalculate for all measure tiles, not just selected in the original PD
965
						if (smplMode) {
966
							disp_strength[nl] = measuredLayers.getDisparityStrengthMLTilted( // expensive to calculate (improve removing outliers
967 968 969 970
									nl, // int num_layer,
									getSTileXY()[0],        // int stX,
									getSTileXY()[1],        // int stY,
									null,  // boolean [] sel_in,
971 972 973 974 975 976 977 978 979 980 981 982 983 984
									mlfp,
//									strength_floor,
//									measured_strength_pow, //
//									smplSide, //        = 2;      // Sample size (side of a square)
//									smplNum, //         = 3;      // Number after removing worst
//									smplRms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
//									smplWnd,  // use window functions for the samples
//									max_abs_tilt,  // 2.0; // Maximal absolute tilt in pixels/tile
//									max_rel_tilt,  // 0.2; // Maximal relative tilt in pixels/tile/disparity
//									damp_tilt,     //    0.001; // Damp tilt to handle insufficient  (co-linear)data
//									min_tilt_disp, // 4.0; // Disparity switch between filtering modes - near objects use tilts, far - use max disparity
//									transition,    // 1.0; // Mode transition range (between tilted and maximal disparity)
//									far_mode,      //     1;   // Far objects filtering mode (0 - off, 1 - power of disparity)
//									far_power,     //    1.0; // Raise disparity to this power before averaging for far objects
985 986
									true, // boolean null_if_none)
									debugLevel);
987
						} else {
Andrey Filippov's avatar
Andrey Filippov committed
988
							disp_strength[nl] = measuredLayers.getDisparityStrengthML(
989 990 991 992
									nl,                     // int num_layer,
									getSTileXY()[0],        // int stX,
									getSTileXY()[1],        // int stY,
									null,  // boolean [] sel_in,
993 994 995
									mlfp,
//									strength_floor,         //  double strength_floor,
//									measured_strength_pow,  // double strength_pow,
996 997
									true);                  // boolean null_if_none);
						}
Andrey Filippov's avatar
Andrey Filippov committed
998
						//disp_strength[nl] = measuredLayers.getDisparityStrengthML(
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
						for (int indx = 0; indx < disp_strength[nl][1].length; indx++){
							double w = disp_strength[nl][1][indx];
							if (w > 0.0){
								double d = disp_strength[nl][0][indx];
								for (int np = 0; np < planes.length; np++) if (planes[np] != null){
									if ((sel_masks[np] == null) || sel_masks[np][indx]) {
										if (!tsel[np][nl][indx]) { // not already in that plane
											double d_av = 0.5 * (d - planes[np][indx]);
											double d2 = (d - planes[np][indx]);
											d2 -= sd[np]; // subtract parallel shift
											if ((dispNorm >0.0) && (d_av > dispNorm)){
												d2 *= dispNorm/d_av;
											}
											d2 *= d2;
1013
											if (d2 <= sd2_av[np]  * other_diff2) { // not more than exclusive tile variance
1014 1015 1016 1017 1018 1019 1020 1021
												tsel[np][nl][indx] = true;
												sd2[np] += w * d2;
												sw[np] += w;
											}
										}
									}
								}
							}
1022
						}
1023 1024 1025
					}
				}
			}
1026

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
			// re-calculate variance (just for debug, not needed
			for (int np = 0; np < planes.length; np++)  if (planes[np] != null){
				if (sw[np] > 0.0){
					sd2_av[np] = sd2[np] / sw[np];
				}
			}
			// apply selections to each PD
			for (int np = 0; np < planes.length; np++)  if (planes[np] != null){
				pd_set[np].setMeasSelection(tsel[np]);
			}
			// need to re-calculate new planes, remove outliers
			return true;
		}
1040

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
		/**
		 * This method is used to filter sample plates by averaging subset of the square
		 * sample and removing outliers. Currently only constant disparity and horizontal
		 * surfaces are used, this method is used for horizontal ones to find tilts
		 * d_disp/d_tx, d_disp/d_ty measured in pixels per tile
		 * @param world_normal_xyz world space normal vector, currently only "up" - (0,1,0) is used
		 * @param tile_disp_strengths [0] - unfiltered disparities for the supertile,
		 *                            [1] - unfiltered correlation strengths for the
		 *                                  supertile (just 0/non-0)
		 * @param debugLevel
		 * @return per tile arrays of either nulls or tilt-x, tilt-y pairs
		 */
1053

1054 1055 1056 1057 1058 1059
		public double [][] getDisparityTilts(
				double []     world_normal_xyz,
				double [][]   tile_disp_strengths,
				int           debugLevel)
		{
			final int stSize2 = 2* stSize;
1060
			final int stCenter = (stSize2 + 1) * superTileSize / 2;
1061 1062
			final double [][] tile_tilts = new double [stSize2*stSize2][];
			final double [] apy_vector = {0.0, 0.0, 1.0};
1063 1064
			final Matrix py_vector = new Matrix(apy_vector,3);
			invalidateCalculated();
1065 1066 1067
			double [] px_py = getCenterPxPy();
			Matrix normal_row = new Matrix(world_normal_xyz,1); // 1x3
			Matrix normal_col = new Matrix(world_normal_xyz,3); // 3x1
1068

1069
			// find world coordinates of the center of tile intersection with the plane
1070 1071
			// disparity 0.0 is invalid, but it somehow got here
			for (int lTile = 0; lTile < tile_disp_strengths[1].length; lTile++) if ((tile_disp_strengths[1][lTile] > 0.0) && (tile_disp_strengths[0][lTile] > 0.0)){
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
				int tY = lTile / stSize2;
				int tX = lTile % stSize2;
				double px = px_py[0] + tX - stCenter;
				double py = px_py[1] + tY - stCenter;
				double disp = tile_disp_strengths[0][lTile];
				// get world coordinates for each tile as determined individually
				Matrix t_xyz = new Matrix(geometryCorrection.getWorldCoordinates(
						px,
						px,
						disp,
						this.correctDistortions),3);
//				double n_by_w =  normal_row.times(t_xyz).get(0, 0);
				// take pixel vector parallel to py and convert it to the world space
				Matrix jacobian =  new Matrix(geometryCorrection.getWorldJacobian(
						px,
						py,
						disp,
						this.correctDistortions,
						(debugLevel > 2)
						));
				Matrix inv_jacobian = jacobian.inverse();
				Matrix wpy_vector = jacobian.times(py_vector); // 3 rows, 1 column py vector in the real world
				// get 2 in-plane vectors in the real world
1095
				Matrix  wv1 = cross3d(normal_col, wpy_vector);
1096
				Matrix  wv2 = cross3d(normal_col, wv1);
1097

1098
				// convert then to pixel space
1099
				Matrix pv1 = inv_jacobian.times(wv1);
1100
				Matrix pv2 = inv_jacobian.times(wv2);
1101

1102 1103
				// Get plane normal in the pixel space
				Matrix pn = cross3d(pv1, pv2);
1104

1105 1106 1107 1108
				// convert to the two tilts (d/dpx, d/dpy). We will need in pix/tile, not pix/pix
				double [] txty = {
						-pn.get(1, 0)/pn.get(0, 0)*stSize,
						-pn.get(2, 0)/pn.get(0, 0)*stSize};
1109 1110 1111 1112 1113 1114 1115 1116 1117

				if (Double.isNaN(txty[0]) || Double.isNaN(txty[1])){
					System.out.println("**** this is a BUG in getDisparityTilts() ****");
					System.out.println("txty= {"+txty[0]+","+txty[1]+"}");
					jacobian.print(10, 5);
					txty = null;
				}
				tile_tilts[lTile] = txty; // some are nulls?

1118
			}
1119

1120 1121 1122 1123
//			if (debugLevel > 1) {
//				System.out.println("st_xyz = {"+st_xyz.get(0, 0)+","+st_xyz.get(1, 0)+","+st_xyz.get(2, 0)+"}"+" ="+n_by_w);
//			}
			return tile_tilts;
1124

1125
		}
1126 1127 1128 1129
		/**
		 * Tilt disparity values around the supertile center (this.zxy) so constant disparity in the output
		 * corresponds to the real world plane parallel to the provided one. Used to discriminate tiles by
		 * the effective disparity value (disparity in the center of the supertile of the parallel plane)
1130 1131
		 * Adding protection from behind the horizon - areas where disparity is negative zero the
		 * result strengths
1132 1133 1134 1135 1136 1137 1138
		 * @param world_normal_xyz real world 3d vector of the plane normal (0.0, 1.0, 0.0 - horizontal)
		 * @param disp_center dispariy in at the center of the supertile (to rotate around)
		 * @param tile_sel multi-layer tile selection (or null to use all available tiles)
		 * @param disp_str multi-layer disparity/strength array
		 * @param debugLevel
		 * @return same
		 */
1139

1140 1141 1142 1143
		public double [][][] getDisparityToPlane(
				double []     world_normal_xyz,
				double        disp_center,
				boolean [][]  tile_sel, // null - do not use, {} use all (will be modified)
1144
				double [][][] disp_str, // calculate just once if null
1145 1146 1147
				int           debugLevel)
		{
			final int stSize2 = 2* stSize;
1148
			invalidateCalculated();
1149
			double [] px_py = getCenterPxPy(); // tile center
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
			// find world coordinates of the center of tile intersection with the plane
			Matrix st_xyz = new Matrix(geometryCorrection.getWorldCoordinates(
						px_py[0],
						px_py[1],
						disp_center,
						this.correctDistortions),3);
			Matrix normal_row = new Matrix(world_normal_xyz,1); // 1x3
			double [][][] eff_disp_str = disp_str.clone();
			for (int ml = 0; ml < disp_str.length; ml++) {
				if (disp_str[ml] != null){
					eff_disp_str[ml] =    new double [2][];
					eff_disp_str[ml][0] = new double [disp_str[ml][0].length];
					eff_disp_str[ml][1] = disp_str[ml][1]; // keep same strengths
				}
			}
			double n_by_w =  normal_row.times(st_xyz).get(0, 0);
1166 1167 1168
			if (debugLevel > 1) {
				System.out.println("st_xyz = {"+st_xyz.get(0, 0)+","+st_xyz.get(1, 0)+","+st_xyz.get(2, 0)+"}"+" ="+n_by_w);
			}
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
			for (int ml = 0; ml < disp_str.length; ml++) if (disp_str[ml] != null){
				for (int dy = 0; dy < stSize2; dy ++ ){
					double y = (dy -  stSize + 0.5) * tileSize;
					for (int dx = 0; dx < stSize2; dx ++ ){
						double x = (dx -  stSize + 0.5) * tileSize;
						int indx = dy * stSize2 + dx;
						if ((disp_str[ml][1][indx] > 0) && ((tile_sel == null) || ((tile_sel[ml] != null) && tile_sel[ml][indx]))){ // do not bother with zero-strength
							// Find world coordinates of a measured tile
							Matrix w_xyz = new Matrix(geometryCorrection.getWorldCoordinates(
									px_py[0] + x,
									px_py[1] + y,
									disp_str[ml][0][indx],
									this.correctDistortions),3);
							// now find intersection of the view line (0,0,0) to world_xyz with a plane through wxyz perpendicular to world_normal_xyz
							// then calculate disparity from z of that point
							// inner product of transposed
							double n_by_p = normal_row.times(w_xyz).get(0, 0);
							if (disp_str[ml][1][indx] > 0){ // do not bother with zero-strength
1187
								double z;
1188
								if ((n_by_p * n_by_w) > 0.0) {
1189 1190 1191 1192 1193 1194 1195
									z = st_xyz.get(2, 0)*n_by_p / n_by_w;
									// convert z to disparity
									eff_disp_str[ml][0][indx] = geometryCorrection.getDisparityFromZ (-z);
								} else {
									z = 0.0;
									eff_disp_str[ml][1][indx] = 0.0; // behind the horizon
								}
1196 1197 1198 1199
								if (debugLevel > 1) {
									System.out.println("dy = "+dy+", dx=" + dx+ " {"+w_xyz.get(0, 0)+","+w_xyz.get(1, 0)+","+w_xyz.get(2, 0)+"}"+" z="+z+" n_by_p = "+n_by_p
											+" disp = "+disp_str[ml][0][indx]+" px = "+(px_py[0] + x)+" py = "+(px_py[1] + y));
								}
1200 1201 1202 1203 1204 1205 1206
							}
						}
					}
				}
			}
			return eff_disp_str;
		}
1207

1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
		public boolean isFronto(
				double fronto_tol,
				double [][][] disp_str,
				int debugLevel)
		{
			if (horizontal || isHorizontal()) {
				this.fronto = false;
				return this.fronto;
			}
			boolean almost_fronto = false;
			double [] zxy0 = getZxy();
			if (disp_str == null) {
				disp_str =      new double [measuredSelection.length][][];
				for (int nl = 0; nl < measuredSelection.length; nl++){
					if (measuredSelection[nl] != null){
						if (smplMode) {
1224
							disp_str[nl] = measuredLayers.getDisparityStrengthMLTilted( // expensive to calculate (improve removing outliers
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
									nl, // int num_layer,
									sTileXY[0], // int stX,
									sTileXY[1], // int stY,
									null, // measuredSelection[nl], // boolean [] sel_in,
									this.mlfp,
									true,     // boolean null_if_none)
									debugLevel);
						} else {
							disp_str[nl] = measuredLayers.getDisparityStrengthML(
									nl, // int num_layer,
									sTileXY[0], // int stX,
									sTileXY[1], // int stY,
									null, // measuredSelection[nl], // boolean [] sel_in,
									this.mlfp,
									true); // boolean null_if_none)
						}
					}
				}
			}

			if (fronto_tol > 0) {
				// see if the plane is almost fronto
				double fronto_tol2 = fronto_tol*fronto_tol;
				// do not use fronto for near tiles - at least do not increase tolerance
//				if ((dispNorm > 0.0) && (zxy[0] > dispNorm)){
//					fronto_tol2 *= zxy[0]/dispNorm;
//				}
				double sw = 0.0, swd2 = 0.0;
				for (int nl = 0; nl < measuredSelection.length; nl++){
					if (measuredSelection[nl] != null){
						// already calculated, but not masked by selection!
						if (disp_str[nl] != null) {
							for (int indx = 0; indx < disp_str[nl][0].length; indx++){
								double w = disp_str[nl][1][indx];
								if (measuredSelection[nl][indx] && (w > 0.0)){
									double d = disp_str[nl][0][indx]-zxy0[0];
									double wd2 = w*d*d;
									sw+=w;
									swd2 += wd2;
								}
							}
						}
					}
				}
				if (sw> 0.0) {
//					swd2 /= sw;
					almost_fronto = (swd2 / sw) <= (getValue() + fronto_tol2);
				}
				if (debugLevel > 2){
					System.out.println("isFronto("+sTileXY[0]+":"+sTileXY[1]+"): "+
							" eigenValue = " + getValue()+" (swd2 / sw) = " + (swd2 / sw)+" fronto_tol2 = "+fronto_tol2+
							" almost_fronto="+almost_fronto);
				}
				this.fronto_rms = Math.sqrt(swd2 / sw);

			}
			if ((dispNorm > 0.0) && (zxy[0] > dispNorm)) {
1282
//				almost_fronto = false; // disable fronto for near objects completely
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
			}
			this.fronto = almost_fronto;
			return almost_fronto;
		}

		/**
		 * Grow measured selection (mostly fill gaps) for fronto planes
		 * @param min_neib minimal number of previously selected neighbors
		 * @param max_over_avg only add if new tile disparity is not higher than average of the neighbors plus this.
		 * @param max_under_avg only add if new tile disparity is not lower than average of the neighbors minus this.
		 */
		public int growFrontoSelection(
				int           min_neib,
				double        max_over_avg,
				double        max_under_avg,
				double [][][] disp_str)
		{
			TileNeibs tn = new TileNeibs(2*superTileSize,2*superTileSize);
			int num_new=0;
			for (int nl = 0; nl < measuredSelection.length; nl++) if (measuredSelection[nl] != null){
				boolean [] sel =      measuredSelection[nl].clone();
				boolean [] was_sel =  measuredSelection[nl].clone();
				tn.growSelection(2, sel, null);
				double sw0=0.0, swd0=0.0;
				for (int indx = 0; indx < sel.length; indx++) if (was_sel[indx] && (disp_str[nl][1][indx] > 0.0)) {
					sw0+= disp_str[nl][1][indx];
					swd0+=disp_str[nl][1][indx]*disp_str[nl][0][indx];
				}
				if (sw0 <=0.0) continue;
				swd0 /= sw0; // average disparity for all tiles
				for (int indx = 0; indx < sel.length; indx++) if (sel[indx] && !was_sel[indx] && (disp_str[nl][1][indx] > 0.0)) {
					int num_neibs = 0;
					double sw = 0.0, swd = 0.0;
					for (int dir = 0; dir <8; dir++) {
						int neib = tn.getNeibIndex(indx, dir);
						if ((neib >= 0) && was_sel[neib] && (disp_str[nl][1][neib] > 0.0) ) {
							num_neibs++;
							sw += disp_str[nl][1][neib];
							swd += disp_str[nl][1][neib] * disp_str[nl][0][neib];
						}
					}
					if (num_neibs >= min_neib) {
						swd /= sw;
					}
					if (	(disp_str[nl][0][indx] >= swd0) && // more than average
							(disp_str[nl][0][indx] >= (swd - max_under_avg)) &&
							(disp_str[nl][0][indx] <= (swd  + max_over_avg)) ){
						measuredSelection[nl][indx] = true;
						num_new++;
					}
				}
			}
			return num_new;
		}


Andrey Filippov's avatar
Andrey Filippov committed
1339 1340 1341
		/**
		 * Remove outliers from the set of tiles contributing to a single plane ellipsoid
		 * Should run after getPlaneFromMeas as some parameter4s will be copied from that run
1342 1343 1344 1345
		 * @param fronto_tol parameter to treat almost fronto planes as fronto (worst tiles are have extreme disparities,
		 * not distance from the tilted planes). Tolerance is measured in disparity pixel and is scaled for high disparities
		 * @param fronto_rms target rms for the fronto planes - same as sqrt(plMaxEigen) for other planes. May be tighter
		 * @param fronto_offs increasing weight of the near tiles by using difference between the reduced average as weight. <= 0 - disable
1346 1347 1348
		 * @param disp_str - pre-calculated array or null (will be calculated). disp_str
		 * has the same format as the output of getPlaneFromMeas - [measurement layer][2][tile index],
		 * so it can be used for input.
Andrey Filippov's avatar
Andrey Filippov committed
1349 1350 1351
		 * @param targetEigen Target value for the lowest eigenvalue (thickness of the ellipsoid)
		 * @param maxRemoved maximal number of tiles to be removed
		 * @param debugLevel debug level
1352
		 * @return true if OK (currently false is when a program bug happens), TODO: change to "goal reached"
Andrey Filippov's avatar
Andrey Filippov committed
1353
		 */
1354

Andrey Filippov's avatar
Andrey Filippov committed
1355
		public boolean removeOutliers( // getPlaneFromMeas should already have run
1356 1357 1358
				double        fronto_tol,  // fronto tolerance (pix) - treat almost fronto as fronto (constant disparity). <= 0 - disable this feature
				double        fronto_rms,  // Target rms for the fronto planes - same as sqrt(plMaxEigen) for other planes. May be tighter
				double        fronto_offs,   //        =   0.2;  // increasing weight of the near tiles by using difference between the reduced average as weight. <= 0 - disable
1359
				double        fronto_pow,    //        =   1.0;  // increase weight even more
1360 1361 1362 1363
				double [][][] disp_str,    // calculate just once when removing outliers (null - OK, will generate it)
				double        inTargetEigen, // target eigenvalue for primary axis (is disparity-dependent, so is non-constant)
				int           maxRemoved,  // maximal number of tiles to remove (not a constant)
				int           debugLevel)
Andrey Filippov's avatar
Andrey Filippov committed
1364 1365
		{
			int stSize2 = 2 * stSize;
1366
			double fronto_bonus_near = 3.0;
Andrey Filippov's avatar
Andrey Filippov committed
1367
			if (maxRemoved > (getNumPoints() - this.min_tiles)) maxRemoved = getNumPoints() - this.min_tiles;
1368
//			boolean need_disp_str = false;
1369 1370 1371 1372 1373
			if (disp_str == null) {
				disp_str =      new double [measuredSelection.length][][];
				for (int nl = 0; nl < measuredSelection.length; nl++){
					if (measuredSelection[nl] != null){
						if (smplMode) {
1374
//							if (need_disp_str) {
1375
								disp_str[nl] = measuredLayers.getDisparityStrengthMLTilted( // expensive to calculate (improve removing outliers
1376 1377 1378 1379
										nl, // int num_layer,
										sTileXY[0], // int stX,
										sTileXY[1], // int stY,
										null, // measuredSelection[nl], // boolean [] sel_in,
1380
										this.mlfp,
1381 1382
										true,     // boolean null_if_none)
										debugLevel);
1383
//							}
1384
						} else {
Andrey Filippov's avatar
Andrey Filippov committed
1385
							disp_str[nl] = measuredLayers.getDisparityStrengthML(
1386 1387 1388 1389
									nl, // int num_layer,
									sTileXY[0], // int stX,
									sTileXY[1], // int stY,
									null, // measuredSelection[nl], // boolean [] sel_in,
1390
									this.mlfp,
1391 1392 1393 1394 1395
									true); // boolean null_if_none)
						}
					}
				}
			}
Andrey Filippov's avatar
Andrey Filippov committed
1396 1397
			int numRemoved = 0;
			boolean no_bugs = true;
1398 1399 1400 1401 1402 1403 1404
			// calculate if it is fronto, check after each pass if it was not
			boolean almost_fronto = isFronto(
					fronto_tol,    // double fronto_tol,
					disp_str,      // double [][][] disp_str,
					debugLevel);   // int debugLevel);
			double targetEigen = almost_fronto ? (fronto_rms*fronto_rms): inTargetEigen;

1405
			for (; (getNormValue() > targetEigen) && (numRemoved < maxRemoved); numRemoved++){
Andrey Filippov's avatar
Andrey Filippov committed
1406 1407
				// make a plane and find the worst (largest disparity difference) tile
				// z = -(x*Vx + y*Vy)/Vz
1408
// may become fronto after removing some tiles
Andrey Filippov's avatar
Andrey Filippov committed
1409 1410
				double worst_d2 = 0.0;
				int [] worst_layer_index = {-1,-1};
Andrey Filippov's avatar
Andrey Filippov committed
1411
				// TODO: Add vertical planes here set v[1] = 0.0;
Andrey Filippov's avatar
Andrey Filippov committed
1412 1413
				double [] v = getVector();
				double [] zxy0 = getZxy();
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
				if (!almost_fronto ) {
					almost_fronto = isFronto(
							fronto_tol,    // double fronto_tol,
							disp_str,      // double [][][] disp_str,
							debugLevel);   // int debugLevel);
					if (almost_fronto) {
						targetEigen = fronto_rms*fronto_rms;
					}
				}

				if (debugLevel > 2){
					System.out.println("removePlaneOutliers("+sTileXY[0]+":"+sTileXY[1]+"): numRemoved = "+numRemoved+
							" eigenValue = " + getValue()+" norm eigenValue = " + getNormValue()+" target = "+targetEigen+
							" almost_fronto="+almost_fronto);
				}

Andrey Filippov's avatar
Andrey Filippov committed
1430 1431
				for (int nl = 0; nl < measuredSelection.length; nl++){
					if (measuredSelection[nl] != null){
1432
						// already calculated, but not masked by selection!
Andrey Filippov's avatar
Andrey Filippov committed
1433 1434 1435
						if (disp_str[nl] != null) {
							for (int indx = 0; indx < disp_str[nl][0].length; indx++){
								double w = disp_str[nl][1][indx];
1436
								if (measuredSelection[nl][indx] && (w > 0.0)){
Andrey Filippov's avatar
Andrey Filippov committed
1437 1438
									double d = disp_str[nl][0][indx];
									d -= zxy0[0];
1439 1440 1441 1442 1443
									if (!almost_fronto) { // compare to a distance from a tilted plane or to a constant disparity (almost_fronto)
										double x = ((indx % stSize2) - stSize) - zxy0[1];
										double y = ((indx / stSize2) - stSize) - zxy0[2];
										d += (x * v[1]+y*v[2])/v[0];
									}
Andrey Filippov's avatar
Andrey Filippov committed
1444
									double d2 = d*d;
1445 1446 1447
									if (almost_fronto && (d > 0)) {
										d2 /= fronto_bonus_near; // if tile is nearer, decrease effective error
									}
Andrey Filippov's avatar
Andrey Filippov committed
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
									if (d2 > worst_d2){
										worst_d2 = d2;
										worst_layer_index[0] = nl;
										worst_layer_index[1] = indx;
									}
								}
							}
						}
					}
				}
				if (worst_layer_index[0] < 0) {
					System.out.println("This is a BUG in removePlaneOutliers()");
					no_bugs = false;
					break;
				}
				measuredSelection[worst_layer_index[0]][worst_layer_index[1]] = false;
				if (debugLevel > 2){
					System.out.println("removePlaneOutliers() worst_layer="+worst_layer_index[0]+", worst_index="+worst_layer_index[1]);
				}
1467

1468 1469
				boolean OK = (getPlaneFromMeas(
						measuredSelection, // null,            // boolean [][] tile_sel, // null - do not use, {} use all (will be modified)
1470
						disp_str,
Andrey Filippov's avatar
Andrey Filippov committed
1471 1472 1473 1474
						Double.NaN,      // double       disp_far, // minimal disparity to select (or NaN)
						Double.NaN,      // double       disp_near, // maximal disparity to select (or NaN)
						this.dispNorm,   // double       dispNorm,   //  Normalize disparities to the average if above
						this.min_weight, // double       min_weight,
1475
						this.min_tiles,  // int          min_tiles,
1476
						this.smplMode,
1477 1478 1479

						almost_fronto, // boolean      fronto_mode,
						fronto_offs,   // double       fronto_offs,   //        =   0.2;  // increasing weight of the near tiles by using difference between the reduced average as weight. <= 0 - disable
1480
						fronto_pow,      // double       fronto_pow,    //        =   1.0;  // increase weight even more
1481
						this.mlfp,
1482
						debugLevel-1) != null);
1483

Andrey Filippov's avatar
Andrey Filippov committed
1484 1485
				if (!OK){ // restore last selection, re-run getPlaneFromMeas
					measuredSelection[worst_layer_index[0]][worst_layer_index[1]] = true;
1486 1487
					OK = (getPlaneFromMeas(
							measuredSelection, // null,            // boolean [][] tile_sel, // null - do not use, {} use all (will be modified)
1488
							disp_str,
Andrey Filippov's avatar
Andrey Filippov committed
1489 1490 1491 1492
							Double.NaN,      // double       disp_far, // minimal disparity to select (or NaN)
							Double.NaN,      // double       disp_near, // maximal disparity to select (or NaN)
							this.dispNorm,   // double       dispNorm,   //  Normalize disparities to the average if above
							this.min_weight, // double       min_weight,
1493
							this.min_tiles,  // int          min_tiles,
1494 1495
							this.smplMode,
							this.mlfp,
1496
							debugLevel-1) != null);
Andrey Filippov's avatar
Andrey Filippov committed
1497 1498 1499 1500 1501 1502
					if (!OK) {
						System.out.println("This is a BUG in removePlaneOutliers() - run with previous selection and failed");
						no_bugs = false;
					}
					break;
				}
1503
			}
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
			if (debugLevel > 2){
				System.out.println("removePlaneOutliers("+sTileXY[0]+":"+sTileXY[1]+"): numRemoved = "+numRemoved+
						" eigenValue = " + getValue()+" norm eigenValue = " + getNormValue()+" target = "+targetEigen+
						" almost_fronto="+almost_fronto);
			}
// FIXME: May be removed, just to update fronto_rms:
			almost_fronto = isFronto(
					fronto_tol,    // double fronto_tol,
					disp_str,      // double [][][] disp_str,
					debugLevel);   // int debugLevel);
			if (almost_fronto) {
				boolean OK = (getPlaneFromMeas(
						measuredSelection, // null,            // boolean [][] tile_sel, // null - do not use, {} use all (will be modified)
						disp_str,
						Double.NaN,      // double       disp_far, // minimal disparity to select (or NaN)
						Double.NaN,      // double       disp_near, // maximal disparity to select (or NaN)
						this.dispNorm,   // double       dispNorm,   //  Normalize disparities to the average if above
						this.min_weight, // double       min_weight,
						this.min_tiles,  // int          min_tiles,
						this.smplMode,
						almost_fronto,   // boolean      fronto_mode,
						fronto_offs,     //						double       fronto_offs,   //        =   0.2;  // increasing weight of the near tiles by using difference between the reduced average as weight. <= 0 - disable
1526 1527
						fronto_pow,      // double       fronto_pow,    //        =   1.0;  // increase weight even more

1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
						this.mlfp,
						debugLevel-0) != null); // will show image
				if (!OK) { // restore how it was
					getPlaneFromMeas(
							measuredSelection, // null,            // boolean [][] tile_sel, // null - do not use, {} use all (will be modified)
							disp_str,
							Double.NaN,      // double       disp_far, // minimal disparity to select (or NaN)
							Double.NaN,      // double       disp_near, // maximal disparity to select (or NaN)
							this.dispNorm,   // double       dispNorm,   //  Normalize disparities to the average if above
							this.min_weight, // double       min_weight,
							this.min_tiles,  // int          min_tiles,
							this.smplMode,
							this.mlfp,
							debugLevel-0);
				}
			}

Andrey Filippov's avatar
Andrey Filippov committed
1545 1546
			return no_bugs;
		}
1547

1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
		public double [][][] getPlaneFromMeas(
				boolean [][] tile_sel, // null - do not use, {} use all (will be modified)
				double [][][] disp_str, // calculate just once when removing outliers
				double       disp_far, // minimal disparity to select (or NaN)
				double       disp_near, // maximal disparity to select (or NaN)
				double       dispNorm,   //  Normalize disparities to the average if above
				double       min_weight,
				int          min_tiles,
				boolean      smplMode, //        = true;   // Use sample mode (false - regular tile mode)
//				boolean      fronto_mode,
//				double       fronto_offs,   //        =   0.2;  // increasing weight of the near tiles by using difference between the reduced average as weight. <= 0 - disable
				MeasuredLayersFilterParameters mlfp,
				int          debugLevel)
		{
			return getPlaneFromMeas(
					tile_sel, // null - do not use, {} use all (will be modified)
					disp_str, // calculate just once when removing outliers
					disp_far, // minimal disparity to select (or NaN)
					disp_near, // maximal disparity to select (or NaN)
					dispNorm,   //  Normalize disparities to the average if above
					min_weight,
					min_tiles,
					smplMode, //        = true;   // Use sample mode (false - regular tile mode)

1572 1573 1574 1575
					false,   // boolean      fronto_mode,
					0.0,     // double       fronto_offs,   //        =   0.2;  // increasing weight of the near tiles by using difference between the reduced average as weight. <= 0 - disable
					1.0,     // double       fronto_pow,    //        =   1.0;  // increase weight even more

1576 1577 1578 1579
					mlfp,
					debugLevel);

		}
Andrey Filippov's avatar
Andrey Filippov committed
1580 1581 1582 1583 1584 1585
		/**
		 * Get "plane" - ellipsoid from covariance matrix of measured data
		 * @param tile_sel multi-layer selection of the tiles to use (first dimension should
		 *                 match number of measurement layers. each element can be either:
		 *                 a) boolean array 4* superTileSize * superTileSize length
		 *                 b) zero-length array - it will be calculated from all measurement
1586
		 *                    data on that layer matching optional disparity limits
1587
		 *                 c) null - this measuremen5t layer will not be used
1588 1589
		 * @param disp_str - pre-calculated array or null (will be calculated). disp_str
		 * has the same format as the output [measurement layer][2][tile index]
Andrey Filippov's avatar
Andrey Filippov committed
1590 1591
		 * @param disp_far optional low limit for tile disparity (NaN - do not check)
		 * @param disp_near optional high limit for tile disparity (NaN - do not check)
1592
		 * @param dispNorm reduce scale of the disparity differences for ellipsoids with
Andrey Filippov's avatar
Andrey Filippov committed
1593 1594 1595 1596
		 *                 disparity center above that value
		 * @param min_weight minimal total weight of the ellipsoid do process
		 * @param min_tiles minimal number of tiles used for calculation
		 * @param strength_pow raise correlation strength to this power
1597 1598 1599
		 * @param smplMode use square sample mode, false - single-tile samples
		 * @param smplSide size of the square sample side
		 * @param smplNum number of averaged samples (should be <= smplSide * smplSide and > 1)
1600
		 * @param smplRms maximal square root of variance (in disparity pixels) to accept the result
1601
		 * @param smplWnd  use window functions for the samples
1602 1603
		 * @param fronto_mode  enforce plane orthogonal to disparity axis
		 * @param fronto_offs increasing weight of the near tiles by using difference between the reduced average as weight. <= 0 - disable
Andrey Filippov's avatar
Andrey Filippov committed
1604
		 * @param debugLevel debug level
1605 1606
		 * @return per measurement layer : x,y,z, weight, or null if failed. This
		 * value may be re-used in subsequent refinements (as removing outliers)
Andrey Filippov's avatar
Andrey Filippov committed
1607
		 */
1608
		public double [][][] getPlaneFromMeas(
Andrey Filippov's avatar
Andrey Filippov committed
1609
				boolean [][] tile_sel, // null - do not use, {} use all (will be modified)
1610
				double [][][] disp_str, // calculate just once when removing outliers
Andrey Filippov's avatar
Andrey Filippov committed
1611 1612 1613 1614 1615
				double       disp_far, // minimal disparity to select (or NaN)
				double       disp_near, // maximal disparity to select (or NaN)
				double       dispNorm,   //  Normalize disparities to the average if above
				double       min_weight,
				int          min_tiles,
1616
				boolean      smplMode, //        = true;   // Use sample mode (false - regular tile mode)
1617 1618 1619

				boolean      fronto_mode,
				double       fronto_offs,   //        =   0.2;  // increasing weight of the near tiles by using difference between the reduced average as weight. <= 0 - disable
1620
				double       fronto_pow,    //        =   1.0;  // increase weight even more
1621

1622
				MeasuredLayersFilterParameters mlfp,
Andrey Filippov's avatar
Andrey Filippov committed
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
				int          debugLevel)
		{
			double mindet = 1E-15;
			int stSize2 = 2 * stSize;
			int num_tiles = 0;
			double sw = 0.0;
			if (tile_sel != null) {
				this.measuredSelection =      tile_sel;
			} else {
				tile_sel = this.measuredSelection;
			}
1634

Andrey Filippov's avatar
Andrey Filippov committed
1635 1636 1637
			this.min_weight =             min_weight;
			this.min_tiles =              min_tiles;
			this.dispNorm =               dispNorm;
1638
			this.smplMode =               smplMode; //        = true;   // Use sample mode (false - regular tile mode)
1639
			this.mlfp =                   mlfp.clone();
1640 1641


1642
			if (debugLevel > 2){
1643
				System.out.println("getPlaneFromMeas(): fronto_mode="+fronto_mode+", fronto_offs="+fronto_offs);
Andrey Filippov's avatar
Andrey Filippov committed
1644
			}
1645 1646 1647 1648 1649
			boolean need_disp_str = false;
			if (disp_str == null) {
				disp_str =      new double [tile_sel.length][][];
				need_disp_str = true;
			}
Andrey Filippov's avatar
Andrey Filippov committed
1650 1651
			for (int nl = 0; nl < tile_sel.length; nl++){
				if (tile_sel[nl] != null){
1652 1653
					if (smplMode) {
						if (need_disp_str) {
1654
							disp_str[nl] = measuredLayers.getDisparityStrengthMLTilted( // expensive to calculate (improve removing outliers
1655 1656 1657 1658 1659
									nl, // int num_layer,
									sTileXY[0], // int stX,
									sTileXY[1], // int stY,
									((tile_sel[nl].length == 0)? null:tile_sel[nl]), // boolean [] sel_in,
									//tile_sel[nl], // boolean [] sel_in,
1660
									mlfp,
1661 1662
									true, // boolean null_if_none)
									debugLevel);
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
						}
						if (disp_str[nl] == null)	continue;
						if (Double.isNaN(disp_far) && Double.isNaN(disp_near)){
							tile_sel[nl] =  measuredLayers.getSupertileSelection(
									disp_str[nl],
									((tile_sel[nl].length == 0)? null:tile_sel[nl]), // boolean [] sel_in,
									true); // boolean null_if_none)
						} else {
							tile_sel[nl] =  measuredLayers.getSupertileSelection(
									disp_str[nl],
									((tile_sel[nl].length == 0)? null:tile_sel[nl]), // boolean [] sel_in,
									disp_far,      // 		double     disp_far,
									disp_near,     // double     disp_near,
									true);         // boolean null_if_none)
						}
						sw += MeasuredLayers.getSumStrength(disp_str[nl],tile_sel[nl]);
						num_tiles += MeasuredLayers.getNumSelected(tile_sel[nl]);
1680

Andrey Filippov's avatar
Andrey Filippov committed
1681
					} else {
1682 1683 1684 1685 1686 1687
						if (Double.isNaN(disp_far) && Double.isNaN(disp_near)){
							tile_sel[nl] =  measuredLayers.getSupertileSelection(
									nl, // int num_layer,
									sTileXY[0], // int stX,
									sTileXY[1], // int stY,
									((tile_sel[nl].length == 0)? null:tile_sel[nl]), // boolean [] sel_in,
1688
									mlfp.strength_floor,
1689 1690 1691 1692 1693 1694 1695 1696 1697
									true); // boolean null_if_none)
						} else {
							tile_sel[nl] =  measuredLayers.getSupertileSelection(
									nl,            // int num_layer,
									sTileXY[0],    // int stX,
									sTileXY[1],    // int stY,
									((tile_sel[nl].length == 0)? null:tile_sel[nl]), // boolean [] sel_in,
									disp_far,      // 		double     disp_far,
									disp_near,     // double     disp_near,
1698
									mlfp.strength_floor,
1699
									true);         // boolean null_if_none)
Andrey Filippov's avatar
Andrey Filippov committed
1700

1701 1702 1703
						}
						num_tiles += MeasuredLayers.getNumSelected(tile_sel[nl]);
						if (tile_sel[nl] != null){
Andrey Filippov's avatar
Andrey Filippov committed
1704
							disp_str[nl] = measuredLayers.getDisparityStrengthML(
1705 1706 1707 1708
									nl, // int num_layer,
									sTileXY[0], // int stX,
									sTileXY[1], // int stY,
									tile_sel[nl], // boolean [] sel_in,
1709
									mlfp,
1710 1711 1712
									true); // boolean null_if_none)
							sw += MeasuredLayers.getSumStrength(disp_str[nl]);
						}
Andrey Filippov's avatar
Andrey Filippov committed
1713
					}
1714 1715


Andrey Filippov's avatar
Andrey Filippov committed
1716
					if ((debugLevel > 3) && (disp_str[nl] != null)){
1717
//					if ((debugLevel > 1) && (disp_str[nl] != null)){
1718
						  ShowDoubleFloatArrays sdfa_instance = new ShowDoubleFloatArrays();
Andrey Filippov's avatar
Andrey Filippov committed
1719 1720 1721 1722
						  double [][] dbg_img = new double [3][];
						  dbg_img[0] = disp_str[nl][0];
						  dbg_img[1] = disp_str[nl][1];
						  dbg_img[2] = new double [stSize2*stSize2];
1723 1724 1725 1726
						  if (tile_sel[nl] != null) {
							  for (int i = 0; i < dbg_img[2].length; i++){
								  dbg_img[2][i] = tile_sel[nl][i]?1.0:0.0; // exception here?
							  }
Andrey Filippov's avatar
Andrey Filippov committed
1727
						  }
1728
						  sdfa_instance.showArrays(dbg_img,  stSize2, stSize2, true, "disp_str_x"+sTileXY[0]+"_y"+sTileXY[1]+"_"+nl);
Andrey Filippov's avatar
Andrey Filippov committed
1729 1730 1731
					}
				}
			}
1732 1733
			this.measuredSelection =      tile_sel; // it may be modified

Andrey Filippov's avatar
Andrey Filippov committed
1734 1735 1736 1737
			if ((sw < min_weight) || (num_tiles < min_tiles)) {
				if (debugLevel > 1){
					System.out.println("getPlaneFromMeas():return false");
				}
1738
				return null; // too weak plane or too few tiles selected
Andrey Filippov's avatar
Andrey Filippov committed
1739
			}
1740

1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
			double fronto_near_diff =   0.02; // edge tile has to have neib with disparity higher by this
			double fronto_far_diff =    0.1;  // edge tile has to have neib with disparity lower by this
			double fronto_edge_weight = 0.1;  // weight of edge tiles
			boolean [][] edge_tiles = null; // new boolean[]
			if (fronto_mode) {
				edge_tiles =  new boolean[disp_str.length][];
				TileNeibs tileNeibs = new TileNeibs(stSize2, stSize2);
				for (int nl = 0; nl < edge_tiles.length; nl++) if (disp_str[nl] != null){
					edge_tiles[nl] = new boolean [disp_str[nl][0].length];
					for (int indx = 0; indx < edge_tiles[nl].length; indx++)  if (disp_str[nl][1][indx] > 0.0){
						boolean has_near = false, has_far = false;
						double high = disp_str[nl][0][indx];
						double low = high - fronto_far_diff;
						high += fronto_near_diff;
						for (int dir = 0; dir < 8; dir++){
							int indx1 = tileNeibs.getNeibIndex(indx, dir);
							if ((indx1 >= 0) && (disp_str[nl][1][indx1] >0)) {
								if (disp_str[nl][0][indx1] > high) {
									has_near = true;
									if (has_far) {
										edge_tiles[nl][indx] = true;
										break;
									}
								} else if (disp_str[nl][0][indx1] < low) {
									has_far = true;
									if (has_near) {
										edge_tiles[nl][indx] = true;
										break;
									}
								}
							}
						}
					}
				}
			}

1777

Andrey Filippov's avatar
Andrey Filippov committed
1778 1779 1780 1781 1782 1783
			double [][] acovar = new double [3][3];
			double swz = 0.0, swx = 0.0, swy = 0.0;
			sw =0.0;
			for (int nl = 0; nl < tile_sel.length; nl++){
				if (disp_str[nl] != null) {
					for (int indx = 0; indx < disp_str[nl][0].length; indx++){
1784 1785
						if (tile_sel[nl][indx]) {
							double w = disp_str[nl][1][indx];
1786 1787 1788
							if (fronto_mode &&  edge_tiles[nl][indx]) {
								w *= fronto_edge_weight;
							}
1789 1790 1791
							if (w > 0.0){
								double d = disp_str[nl][0][indx];
								// referencing samples to centers of pixels
1792 1793
								double x = ((indx % stSize2) - stSize + 0.5) * tileSize; // in pixels, not in tiles
								double y = ((indx / stSize2) - stSize + 0.5) * tileSize;
1794 1795 1796 1797 1798
								sw  += w;
								swz += w * d;
								swx += w * x;
								swy += w * y;
							}
Andrey Filippov's avatar
Andrey Filippov committed
1799 1800 1801 1802 1803
						}
					}
				}
			}
			if (sw == 0.0) {
1804
				return null; //
Andrey Filippov's avatar
Andrey Filippov committed
1805 1806 1807 1808 1809
			}
			swz /= sw;
			swx /= sw;
			swy /= sw;

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
			if (fronto_mode && (fronto_offs > 0.0)) {
				// recalculate offset swz, set modified tiles weights
				double [][][] disp_str_actual = disp_str;
				disp_str = new double [disp_str_actual.length][][];
				for (int nl = 0; nl < disp_str.length; nl++) {
					if (disp_str_actual[nl] != null) {
						disp_str[nl] = new double [2][];
						disp_str[nl][0] = disp_str_actual[nl][0].clone();
						disp_str[nl][1] = new double [disp_str_actual[nl][1].length];
					}
				}
				double swz0 = swz;
				double sw0 = sw;
				swz = 0.0;
				sw = 0.0;
				double d0 = swz - fronto_offs;
				for (int nl = 0; nl < tile_sel.length; nl++){
					if (disp_str[nl] != null) {
						for (int indx = 0; indx < disp_str[nl][0].length; indx++){
							if (tile_sel[nl][indx]) {
								double w = disp_str_actual[nl][1][indx];
								if (fronto_mode &&  edge_tiles[nl][indx]) {
									w *= fronto_edge_weight;
								}

								if (w > 0.0){
									double d = disp_str[nl][0][indx];
									if (d > d0) {
1838 1839 1840 1841 1842
										double kw = (d-d0)/fronto_offs; // more weight of the near pixels, same weight of the centre pixels
										if (fronto_pow != 1.00) {
											kw = Math.pow(kw,  fronto_pow);
										}
										w *= kw; // increase influence of near pixels even more
1843 1844 1845 1846 1847 1848 1849 1850 1851
										disp_str[nl][1][indx] = w;
										sw  += w;
										swz += w * d;
									}
								}
							}
						}
						if ((debugLevel > 2) && (disp_str[nl] != null)){
							//						if ((debugLevel > 1) && (disp_str[nl] != null)){
1852
							ShowDoubleFloatArrays sdfa_instance = new ShowDoubleFloatArrays();
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
							double [][] dbg_img = new double [4][];
							dbg_img[0] = disp_str[nl][0];
							dbg_img[1] = disp_str[nl][1];
							dbg_img[2] = disp_str_actual[nl][1];
							dbg_img[3] = new double [stSize2*stSize2];
							if (tile_sel[nl] != null) {
								for (int i = 0; i < dbg_img[3].length; i++){
									dbg_img[3][i] = tile_sel[nl][i]?(edge_tiles[nl][i]?0.5:1.0):0.0; // exception here?
								}
							}
							sdfa_instance.showArrays(dbg_img,  stSize2, stSize2, true, "fronto-disp_str_x"+sTileXY[0]+"_y"+sTileXY[1]+"_"+nl);
						}
					}
				}

				if (sw == 0.0) {
					return null;
				}
				swz /= sw; // new center (higher than older swz
				if (debugLevel > 0){
					System.out.println("getPlaneFromMeas(): Using fronto mode, num_tiles="+num_tiles+", sw0 = "+sw0 +", swz0 = "+swz0 +", swz = "+swz);
				}
			} else {
				if (debugLevel > 2){
					for (int nl = 0; nl < tile_sel.length; nl++) if (disp_str[nl] != null) {
1878
						ShowDoubleFloatArrays sdfa_instance = new ShowDoubleFloatArrays();
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
						double [][] dbg_img = new double [3][];
						dbg_img[0] = disp_str[nl][0];
						dbg_img[1] = disp_str[nl][1];
						dbg_img[2] = new double [stSize2*stSize2];
						if (tile_sel[nl] != null) {
							for (int i = 0; i < dbg_img[2].length; i++){
								dbg_img[2][i] = tile_sel[nl][i]?1.0:0.0;
							}
						}
						sdfa_instance.showArrays(dbg_img,  stSize2, stSize2, true, "non-fronto-disp_str_x"+sTileXY[0]+"_y"+sTileXY[1]+"_"+nl);
					}
				}
				if (debugLevel > 2){
					System.out.println("getPlaneFromMeas(): num_tiles="+num_tiles+", sw = "+sw +", swz = "+swz +", swx = "+swx +", swy = "+swy); // +", kz="+kz);
				}
Andrey Filippov's avatar
Andrey Filippov committed
1894 1895 1896
			}

			// TODO: scale disparity to make same scale for 3 axes?
1897

Andrey Filippov's avatar
Andrey Filippov committed
1898 1899 1900
			for (int nl = 0; nl < tile_sel.length; nl++){
				if (disp_str[nl] != null) {
					for (int indx = 0; indx < disp_str[nl][0].length; indx++){
1901 1902
						if (tile_sel[nl][indx]) {
							double w = disp_str[nl][1][indx] / sw;
1903 1904 1905
							if (fronto_mode &&  edge_tiles[nl][indx]) {
								w *= fronto_edge_weight;
							}
1906
							if (w > 0.0){
1907
								double d =  disp_str[nl][0][indx] - swz;
1908
								double wd = w*d;
1909 1910
								double x = ((indx % stSize2) - stSize + 0.5) * tileSize  - swx;
								double y = ((indx / stSize2) - stSize + 0.5) * tileSize  - swy;
1911 1912 1913 1914 1915 1916 1917
								acovar [0][0] += wd * d;
								acovar [0][1] += wd * x;
								acovar [0][2] += wd * y;
								acovar [1][1] += w * x * x;
								acovar [1][2] += w * x * y;
								acovar [2][2] += w * y * y;
							}
Andrey Filippov's avatar
Andrey Filippov committed
1918 1919 1920 1921
						}
					}
				}
			}
1922 1923 1924 1925 1926
			if (fronto_mode) { // enforce fronto
				acovar [0][1] = 0.0; // wdx
				acovar [0][2] = 0.0; // wdy
			}

1927 1928
			acovar [1][0] = acovar [0][1];
			acovar [2][0] = acovar [0][2];
Andrey Filippov's avatar
Andrey Filippov committed
1929 1930 1931 1932 1933 1934 1935 1936
			acovar [2][1] = acovar [1][2];
			Matrix covar = new Matrix(acovar);

			EigenvalueDecomposition eig = covar.eig();
			if (Double.isNaN(eig.getV().get(0, 0))){
				System.out.println("getCovar(): Double.isNaN(eig.getV().get(0, 0))");
				debugLevel = 20;
			}
1937

1938
			if (debugLevel > 3){
Andrey Filippov's avatar
Andrey Filippov committed
1939 1940 1941 1942 1943 1944 1945 1946 1947
				System.out.println("getCovar(): sw = "+sw +", swz = "+swz +", swx = "+swx +", swy = "+swy +", covar.det() = "+covar.det());
				System.out.println("getCovar(): covarianvce matrix, number of used points:"+num_tiles);
				covar.print(10, 6); // w,d
				System.out.println("getCovar(): eigenvalues");
				eig.getD().print(10, 6); // w,d
				System.out.println("getCovar(): eigenvectors");
				eig.getV().print(10, 6); // w,d
			}
			if ((eig.getD().get(0, 0) == 0.0) || (Math.abs(covar.det()) < mindet)) {
1948
				return null; // testing with zero eigenvalue
Andrey Filippov's avatar
Andrey Filippov committed
1949 1950 1951 1952 1953 1954 1955 1956
				// Problem with zero eigenvalue is with derivatives and coordinate conversion
			}

			double [][] eig_val =  eig.getD().getArray(); // rslt[0];
			double [][] eig_vect = eig.getV().getArray(); // rslt[1];
			// find vector most orthogonal to view // (anyway it all works with that assumption), make it first
			// TODO normalize to local linear scales
			int oindx = 0;
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
			if (preferDisparity) {
				for (int i = 1; i <3; i++){
					if (Math.abs(eig_vect[0][i]) > Math.abs(eig_vect[0][oindx])){
						oindx = i;
					}
				}
			} else {
				for (int i = 1; i < 3 ; i++){
					if (eig_val[i][i] < eig_val[oindx][oindx]){
						oindx = i;
					}
				}
			}
			if (eig_val[oindx][oindx] == 0.0){
				System.out.println("getPlane(): zero eigenvalue!!");
			}
1973

1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
			// select 2 other axes for increasing eigenvalues (so v is short axis, h  is the long one)
			int vindx = (oindx == 0)? 1 : 0;
			int hindx = (oindx == 0)? 2 : ((oindx == 1) ? 2 : 1);
			if (eig_val[vindx][vindx] > eig_val[hindx][hindx]){
				int tmp = vindx;
				vindx = hindx;
				hindx = tmp;
			}

			double [][] plane = {
					{eig_vect[0][oindx],eig_vect[1][oindx],eig_vect[2][oindx]},  // plane normal to camera
					{eig_vect[0][vindx],eig_vect[1][vindx],eig_vect[2][vindx]},  // "horizontal" axis // to detect skinny planes and poles
					{eig_vect[0][hindx],eig_vect[1][hindx],eig_vect[2][hindx]}}; //  "vertical"   axis  // to detect skinny planes and poles

			// Make normal be towards camera (positive disparity), next vector - positive in X direction (right)
			for (int v = 0; v < 2; v++) {
				if (plane[v][v] < 0.0) for (int i = 0; i < 3; i ++) plane[v][i] = -plane[v][i];
			}
1992 1993

			// make  direction last vector so px (x) py (.) disp < 0 (left-hand coordinate system)
1994 1995 1996
			if (new Matrix(plane).det() > 0){
				for (int i = 0; i < 3; i ++) plane[2][i] = -plane[2][i];
			}
1997

1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
			setZxy(swz, swx, swy);
			setWeight(sw);
			setValues(eig_val[oindx][oindx],eig_val[vindx][vindx],eig_val[hindx][hindx]); // eigenvalues [0] - thickness, 2 other to detect skinny (poles)
			setVectors   (plane);
			setNumPoints (num_tiles);
			boolean [] plane_sel = null;
			boolean need_clone = true;
			for (int nl = 0; nl < tile_sel.length; nl++){
				if (tile_sel[nl] != null) {
					if (plane_sel == null) {
						plane_sel = tile_sel[nl];
					} else {
						if (need_clone) {
							plane_sel = plane_sel.clone();
							need_clone = false;
						}
						for (int i = 0; i < plane_sel.length; i++){
							plane_sel[i] |=  tile_sel[nl][i];
						}
2017
					}
2018 2019
				}
			}
2020

2021 2022 2023 2024
			setPlaneSelection(plane_sel);
			return disp_str;
		}

2025

2026 2027 2028 2029
		// similar to getPlaneFromMeas, but building ellipsoids in the real world space
		public double [][][] getWorldPlaneFromMeas(
				boolean [][] tile_sel, // null - do not use, {} use all (will be modified)
				// TODO: mame it accept tiles_xyzw (same as output)
2030
				double [][][] disp_str, // calculate just once when removing outliers
2031 2032 2033 2034 2035 2036
				double       disp_far, // minimal disparity to select (or NaN)
				double       disp_near, // maximal disparity to select (or NaN)
				double       dispNorm,   //  Normalize disparities to the average if above
				double       min_weight,
				int          min_tiles,
				boolean      smplMode, //        = true;   // Use sample mode (false - regular tile mode)
2037
				MeasuredLayersFilterParameters mlfp,
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
				int          debugLevel)
		{
			double mindet = 1E-15;
			int stSize2 = 2 * stSize;
			int num_tiles = 0;
			double sw = 0.0;
			if (tile_sel != null) {
				this.measuredSelection =      tile_sel;
			} else {
				tile_sel = this.measuredSelection;
			}
2049

2050 2051 2052 2053
			this.min_weight =             min_weight;
			this.min_tiles =              min_tiles;
			this.dispNorm =               dispNorm;
			this.smplMode =               smplMode; //        = true;   // Use sample mode (false - regular tile mode)
2054
			this.mlfp = mlfp.clone();
2055

2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
			if (debugLevel > 2){
				System.out.println("getWorldPlaneFromMeas()");
			}
			boolean need_disp_str = false;
			if (disp_str == null) {
				disp_str =      new double [tile_sel.length][][];
				need_disp_str = true;
			}
			// TODO: Code duplication with getWorldPlaneFromMeas() - extract common part
			for (int nl = 0; nl < tile_sel.length; nl++){
				if (tile_sel[nl] != null){
					if (smplMode) {
						if (need_disp_str) {
2069
							disp_str[nl] = measuredLayers.getDisparityStrengthMLTilted( // expensive to calculate (improve removing outliers
2070 2071 2072 2073 2074
									nl, // int num_layer,
									sTileXY[0], // int stX,
									sTileXY[1], // int stY,
									((tile_sel[nl].length == 0)? null:tile_sel[nl]), // boolean [] sel_in,
									//tile_sel[nl], // boolean [] sel_in,
2075
									mlfp,
2076 2077
									true,     // boolean null_if_none)
									debugLevel);
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
						}
						if (disp_str[nl] == null)	continue;
						if (Double.isNaN(disp_far) && Double.isNaN(disp_near)){
							tile_sel[nl] =  measuredLayers.getSupertileSelection(
									disp_str[nl],
									((tile_sel[nl].length == 0)? null:tile_sel[nl]), // boolean [] sel_in,
									true); // boolean null_if_none)
						} else {
							tile_sel[nl] =  measuredLayers.getSupertileSelection(
									disp_str[nl],
									((tile_sel[nl].length == 0)? null:tile_sel[nl]), // boolean [] sel_in,
									disp_far,      // 		double     disp_far,
									disp_near,     // double     disp_near,
									true);         // boolean null_if_none)
						}
						sw += MeasuredLayers.getSumStrength(disp_str[nl],tile_sel[nl]);
						num_tiles += MeasuredLayers.getNumSelected(tile_sel[nl]);
2095

2096 2097 2098 2099 2100 2101 2102
					} else {
						if (Double.isNaN(disp_far) && Double.isNaN(disp_near)){
							tile_sel[nl] =  measuredLayers.getSupertileSelection(
									nl, // int num_layer,
									sTileXY[0], // int stX,
									sTileXY[1], // int stY,
									((tile_sel[nl].length == 0)? null:tile_sel[nl]), // boolean [] sel_in,
2103
									mlfp.strength_floor,
2104 2105 2106 2107 2108 2109 2110 2111 2112
									true); // boolean null_if_none)
						} else {
							tile_sel[nl] =  measuredLayers.getSupertileSelection(
									nl,            // int num_layer,
									sTileXY[0],    // int stX,
									sTileXY[1],    // int stY,
									((tile_sel[nl].length == 0)? null:tile_sel[nl]), // boolean [] sel_in,
									disp_far,      // 		double     disp_far,
									disp_near,     // double     disp_near,
2113
									mlfp.strength_floor,
2114 2115 2116 2117 2118
									true);         // boolean null_if_none)

						}
						num_tiles += MeasuredLayers.getNumSelected(tile_sel[nl]);
						if (tile_sel[nl] != null){
Andrey Filippov's avatar
Andrey Filippov committed
2119
							disp_str[nl] = measuredLayers.getDisparityStrengthML(
2120 2121 2122 2123
									nl, // int num_layer,
									sTileXY[0], // int stX,
									sTileXY[1], // int stY,
									tile_sel[nl], // boolean [] sel_in,
2124
									mlfp,
2125 2126 2127 2128
									true); // boolean null_if_none)
							sw += MeasuredLayers.getSumStrength(disp_str[nl]);
						}
					}
2129

2130 2131
//					if ((debugLevel > 2) && (disp_str[nl] != null)){
					if ((debugLevel > 3) && (disp_str[nl] != null)){
2132
						  ShowDoubleFloatArrays sdfa_instance = new ShowDoubleFloatArrays();
2133 2134 2135 2136
						  double [][] dbg_img = new double [3][];
						  dbg_img[0] = disp_str[nl][0];
						  dbg_img[1] = disp_str[nl][1];
						  dbg_img[2] = new double [stSize2*stSize2];
2137 2138 2139 2140
						  if (tile_sel[nl] != null) {
							  for (int i = 0; i < dbg_img[2].length; i++){
								  dbg_img[2][i] = tile_sel[nl][i]?1.0:0.0;
							  }
2141 2142 2143 2144 2145
						  }
						  sdfa_instance.showArrays(dbg_img,  stSize2, stSize2, true, "disp_str_x"+sTileXY[0]+"_y"+sTileXY[1]+"_"+nl);
					}
				}
			}
2146 2147 2148
			this.measuredSelection =      tile_sel; // it may be modified


2149 2150 2151 2152 2153 2154
			if ((sw < min_weight) || (num_tiles < min_tiles)) {
				if (debugLevel > 1){
					System.out.println("getWorldPlaneFromMeas():return false");
				}
				return null; // too weak plane or too few tiles selected
			}
2155

2156 2157 2158 2159 2160 2161 2162 2163
			double [][][] tiles_xyzw = new double [disp_str.length][][];
			for (int nl = 0; nl < tile_sel.length; nl++) if (disp_str[nl] != null) {
				tiles_xyzw[nl] = new double [disp_str[nl][0].length][];
			}
			double [][] acovar = new double [3][3];
			double swz = 0.0, swx = 0.0, swy = 0.0;
			sw =0.0;
			double [] px_py = getCenterPxPy();
2164

2165 2166 2167 2168 2169
			for (int nl = 0; nl < tile_sel.length; nl++){
				if (disp_str[nl] != null) {
					for (int indx = 0; indx < disp_str[nl][0].length; indx++){
						if (tile_sel[nl][indx]) {
							double w = disp_str[nl][1][indx];
2170 2171
							if ((w > 0.0) && !(disp_str[nl][0][indx] > 0.0)) {
								System.out.println("BUG!!!: getPlaneFromMeas(): disp_str[nl][0]["+indx+"]="+disp_str[nl][0][indx]+", disp_str[nl][1]["+indx+"]="+disp_str[nl][1][indx]);
2172 2173
								w = 0.0;
								disp_str[nl][1][indx] = 0.0;
2174 2175
								continue;
							}
2176 2177 2178 2179
							if (w > 0.0){
								tiles_xyzw[nl][indx] = new double [4];
								double d = disp_str[nl][0][indx];
								// referencing samples to centers of pixels
2180 2181 2182 2183
//								double x = ((indx % stSize2) - stSize + 0.5) * tileSize + 0.5 + px_py[0]; // in pixels, not in tiles
//								double y = ((indx / stSize2) - stSize + 0.5) * tileSize + 0.5 + px_py[1];
								double x = ((indx % stSize2) - stSize + 0.5) * tileSize + px_py[0]; // in pixels, not in tiles
								double y = ((indx / stSize2) - stSize + 0.5) * tileSize + px_py[1];
2184 2185 2186 2187 2188 2189
								// difference from getPlaneFromMeas
								double [] wxyz = geometryCorrection.getWorldCoordinates(
										x,
										y,
										d,
										this.correctDistortions);
Andrey Filippov's avatar
Andrey Filippov committed
2190

2191 2192 2193 2194 2195 2196 2197 2198
								tiles_xyzw[nl][indx][0] = wxyz[0];
								tiles_xyzw[nl][indx][1] = wxyz[1];
								tiles_xyzw[nl][indx][2] = wxyz[2];
								tiles_xyzw[nl][indx][3] = w;
								sw  += w;
								swz += w * wxyz[2];
								swx += w * wxyz[0];
								swy += w * wxyz[1];
Andrey Filippov's avatar
Andrey Filippov committed
2199 2200 2201 2202 2203 2204 2205 2206
								if (Double.isNaN(tiles_xyzw[nl][indx][0])) {
									System.out.println("--*--BUG! tiles_xyzw[nl][indx][0] is NaN");
								}
								if (Double.isInfinite(swx) || Double.isInfinite(swz)  || Double.isInfinite(w)) {
									System.out.println("BUG!!!: getPlaneFromMeas(): num_tiles="+num_tiles+", sw = "+sw +", swz = "+swz +", swx = "+swx +", swy = "+swy);
								}


2207 2208 2209 2210
								// end of difference from getPlaneFromMeas
							}
						}
					}
2211
					if ((debugLevel > 3) && (disp_str[nl] != null)){
2212
						ShowDoubleFloatArrays sdfa_instance = new ShowDoubleFloatArrays();
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
						double [][] dbg_img = new double [4][stSize2*stSize2];
						for (int indx = 0; indx < dbg_img[0].length; indx++){
							if (tiles_xyzw[nl][indx] != null) {
							dbg_img[0][indx] = tiles_xyzw[nl][indx][0];
							dbg_img[1][indx] = tiles_xyzw[nl][indx][1];
							dbg_img[2][indx] = tiles_xyzw[nl][indx][2];
							dbg_img[3][indx] = tiles_xyzw[nl][indx][3];
							} else {
								dbg_img[0][indx] = Double.NaN;
								dbg_img[1][indx] = Double.NaN;
								dbg_img[2][indx] = Double.NaN;
								dbg_img[3][indx] = Double.NaN;
							}
						}
						sdfa_instance.showArrays(dbg_img,  stSize2, stSize2, true, "world_x"+sTileXY[0]+"_y"+sTileXY[1]+"_"+nl);
					}
2229 2230 2231 2232 2233
				}
			}
			if (sw == 0.0) {
				return null; //
			}
Andrey Filippov's avatar
Andrey Filippov committed
2234 2235 2236
			if (Double.isInfinite(swx)) {
				System.out.println("BUG!!!: getPlaneFromMeas(): num_tiles="+num_tiles+", sw = "+sw +", swz = "+swz +", swx = "+swx +", swy = "+swy);
			}
2237 2238 2239 2240
			swz /= sw;
			swx /= sw;
			swy /= sw;
			setWxyz(swx, swy, swz);
Andrey Filippov's avatar
Andrey Filippov committed
2241 2242 2243
			if (Double.isInfinite(swx)) {
				System.out.println("BUG!!!: getPlaneFromMeas(): num_tiles="+num_tiles+", sw = "+sw +", swz = "+swz +", swx = "+swx +", swy = "+swy);
			}
2244

2245 2246
//			double kz = ((dispNorm > 0.0) && (swz > dispNorm)) ? (dispNorm / swz) : 1.0;

2247 2248 2249 2250 2251
			if (debugLevel > 0){
				System.out.println("getPlaneFromMeas(): num_tiles="+num_tiles+", sw = "+sw +", swz = "+swz +", swx = "+swx +", swy = "+swy);
			}

			// TODO: scale disparity to make same scale for 3 axes?
2252

2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
			for (int nl = 0; nl < tile_sel.length; nl++){
				if (disp_str[nl] != null) {
					for (int indx = 0; indx < disp_str[nl][0].length; indx++){
						if (tiles_xyzw[nl][indx] != null) {
							double w = tiles_xyzw[nl][indx][3] / sw;
							if (w > 0.0){
								double x = tiles_xyzw[nl][indx][0] - swx;
								double y = tiles_xyzw[nl][indx][1] - swy;
								double z = tiles_xyzw[nl][indx][2] - swz;
								acovar [0][0] += w * x * x;
								acovar [0][1] += w * x * y;
								acovar [0][2] += w * x * z;
								acovar [1][1] += w * y * y;
								acovar [1][2] += w * y * z;
								acovar [2][2] += w * z * z;
Andrey Filippov's avatar
Andrey Filippov committed
2268 2269
								if (Double.isNaN(acovar [0][0])) {
									System.out.println("--*--BUG! acovar[0][0] is NaN");
2270
									return null;
Andrey Filippov's avatar
Andrey Filippov committed
2271
								}
2272 2273 2274 2275 2276
							}
						}
					}
				}
			}
2277 2278
			acovar [1][0] = acovar [0][1];
			acovar [2][0] = acovar [0][2];
2279
			acovar [2][1] = acovar [1][2];
Andrey Filippov's avatar
Andrey Filippov committed
2280

2281 2282 2283 2284 2285 2286 2287
			Matrix covar = new Matrix(acovar);

			EigenvalueDecomposition eig = covar.eig();
			if (Double.isNaN(eig.getV().get(0, 0))){
				System.out.println("getCovar(): Double.isNaN(eig.getV().get(0, 0))");
				debugLevel = 20;
			}
2288

2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
			if (debugLevel > 3){
//				if (debugLevel > 0){
				System.out.println("getCovar(): sw = "+sw +", swz = "+swz +", swx = "+swx +", swy = "+swy +", covar.det() = "+covar.det());
				System.out.println("getCovar(): covarianvce matrix, number of used points:"+num_tiles);
				covar.print(10, 6); // w,d
				System.out.println("getCovar(): eigenvalues");
				eig.getD().print(10, 6); // w,d
				System.out.println("getCovar(): eigenvectors");
				eig.getV().print(10, 6); // w,d
			}
			if ((eig.getD().get(0, 0) == 0.0) || (Math.abs(covar.det()) < mindet)) {
				return null; // testing with zero eigenvalue
				// Problem with zero eigenvalue is with derivatives and coordinate conversion
			}

			double [][] eig_val =  eig.getD().getArray(); // rslt[0];
			double [][] eig_vect = eig.getV().getArray(); // rslt[1];
			// find vector most orthogonal to view // (anyway it all works with that assumption), make it first
			// TODO normalize to local linear scales
2308 2309


2310 2311
			// probably this reordering is not needed as they are already ordered
			// for world coordinates the sequence is normal x,y,z (not d,x,y)
2312

2313 2314 2315 2316
			int oindx = 0;
			for (int i = 1; i < 3 ; i++){
				if (eig_val[i][i] < eig_val[oindx][oindx]){
					oindx = i;
Andrey Filippov's avatar
Andrey Filippov committed
2317 2318 2319 2320 2321
				}
			}
			if (eig_val[oindx][oindx] == 0.0){
				System.out.println("getPlane(): zero eigenvalue!!");
			}
2322

Andrey Filippov's avatar
Andrey Filippov committed
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
			// select 2 other axes for increasing eigenvalues (so v is short axis, h  is the long one)
			int vindx = (oindx == 0)? 1 : 0;
			int hindx = (oindx == 0)? 2 : ((oindx == 1) ? 2 : 1);
			if (eig_val[vindx][vindx] > eig_val[hindx][hindx]){
				int tmp = vindx;
				vindx = hindx;
				hindx = tmp;
			}

			double [][] plane = {
					{eig_vect[0][oindx],eig_vect[1][oindx],eig_vect[2][oindx]},  // plane normal to camera
					{eig_vect[0][vindx],eig_vect[1][vindx],eig_vect[2][vindx]},  // "horizontal" axis // to detect skinny planes and poles
					{eig_vect[0][hindx],eig_vect[1][hindx],eig_vect[2][hindx]}}; //  "vertical"   axis  // to detect skinny planes and poles

			// Make normal be towards camera (positive disparity), next vector - positive in X direction (right)
2338 2339 2340 2341 2342 2343 2344 2345
			double from = 0.0; // see if the first vector ("plane" normal) is away from the camera
			for (int i = 0; i < 3; i++) {
				from += this.wxyz[i]*plane[0][i];
			}
			if (from > 0.0){ // reverse the first vector to be towards the camera
				for (int i = 0; i < 3; i++) {
					plane[0][i] = -plane[0][i];
				}
Andrey Filippov's avatar
Andrey Filippov committed
2346
			}
2347 2348

			// make  direction last vector so px (x) py (.) disp < 0 (left-hand coordinate system)
Andrey Filippov's avatar
Andrey Filippov committed
2349 2350 2351
			if (new Matrix(plane).det() > 0){
				for (int i = 0; i < 3; i ++) plane[2][i] = -plane[2][i];
			}
2352

2353 2354
//			setZxy(swz, swx, swy);
			setWeight(sw); // should be the same
2355

2356 2357 2358
			setWValues(eig_val[oindx][oindx],eig_val[vindx][vindx],eig_val[hindx][hindx]); // eigenvalues [0] - thickness, 2 other to detect skinny (poles)
			setWVectors   (plane);
			setNumPoints (num_tiles);  // should be the same
Andrey Filippov's avatar
Andrey Filippov committed
2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
			boolean [] plane_sel = null;
			boolean need_clone = true;
			for (int nl = 0; nl < tile_sel.length; nl++){
				if (tile_sel[nl] != null) {
					if (plane_sel == null) {
						plane_sel = tile_sel[nl];
					} else {
						if (need_clone) {
							plane_sel = plane_sel.clone();
							need_clone = false;
						}
						for (int i = 0; i < plane_sel.length; i++){
							plane_sel[i] |=  tile_sel[nl][i];
						}
2373
					}
Andrey Filippov's avatar
Andrey Filippov committed
2374 2375
				}
			}
2376

Andrey Filippov's avatar
Andrey Filippov committed
2377
			setPlaneSelection(plane_sel);
2378
//			return disp_str;
2379
			return disp_str;
2380

Andrey Filippov's avatar
Andrey Filippov committed
2381
		}
2382 2383 2384



Andrey Filippov's avatar
Andrey Filippov committed
2385
		public double [][] initMergedValue()
2386
		{
2387 2388 2389 2390 2391
			this.merged_eig_val =      new double[8][];
			this.merged_eig_eq =       new double[8][];
			this.merged_weig_val =     new double[8][];
			this.merged_weig_eq =      new double[8][];
			this.merged_valid =        new boolean[8][];
Andrey Filippov's avatar
Andrey Filippov committed
2392
			this.merged_strong_valid = new boolean[8][];
Andrey Filippov's avatar
Andrey Filippov committed
2393
			return this.merged_eig_val;
2394
		}
Andrey Filippov's avatar
Andrey Filippov committed
2395
		public double [][] getMergedValue()
2396
		{
Andrey Filippov's avatar
Andrey Filippov committed
2397
			return this.merged_eig_val;
2398
		}
2399 2400 2401 2402 2403 2404

		public double [][] getMergedValueEq()
		{
			return this.merged_eig_eq;
		}

2405 2406 2407 2408 2409 2410 2411 2412 2413
		public double [][] getMergedWValue()
		{
			return this.merged_weig_val;
		}

		public double [][] getMergedWValueEq()
		{
			return this.merged_weig_eq;
		}
2414 2415 2416 2417 2418 2419
		public double [][] getLinkCosts()
		{
			return this.link_costs;
		}
		public double [] getLinkCosts(int dir)
		{
2420 2421 2422
			if ((link_costs==null) || (link_costs[dir] == null)){
				return null;
			}
2423 2424 2425 2426
			return this.link_costs[dir];
		}
		public double getLinkCosts(int dir, int np)
		{
2427 2428 2429
			if ((link_costs==null) || (link_costs[dir] == null)){
				return Double.MAX_VALUE;
			}
2430 2431
			return this.link_costs[dir][np];
		}
2432

2433 2434 2435 2436
		public void setLinkCosts(int dir, int plane, double value)
		{
			this.link_costs[dir][plane] = value;
		}
2437

Andrey Filippov's avatar
Andrey Filippov committed
2438
		public double [] initMergedValue(int dir, int leng)
2439
		{
Andrey Filippov's avatar
Andrey Filippov committed
2440 2441 2442 2443 2444 2445
			this.merged_eig_val[dir] =        new double[leng];
			this.merged_eig_eq[dir] =         new double[leng];
			this.merged_weig_val[dir] =       new double[leng];
			this.merged_weig_eq[dir] =        new double[leng];
			this.merged_valid[dir] =          new boolean[leng];
			this.merged_strong_valid[dir] =   new boolean[leng];
2446
			for (int i = 0; i < leng; i++) {
2447 2448 2449 2450
				this.merged_eig_val[dir][i] =  Double.NaN;
				this.merged_eig_eq[dir][i] =   Double.NaN;
				this.merged_weig_val[dir][i] = Double.NaN;
				this.merged_weig_eq[dir][i] =  Double.NaN;
2451
			}
Andrey Filippov's avatar
Andrey Filippov committed
2452
			return getMergedValue(dir);
2453 2454
		}

2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
		public double [][] initLinkCosts(){
			this.link_costs =          new double[8][];
			return link_costs;
		}
		public double [] initLinkCosts(int dir, int leng)
		{
			this.link_costs[dir] =            new double[leng];
			for (int i = 0; i < leng; i++) {
				this.link_costs[dir][i] =      Double.NaN;
			}
			return getLinkCosts(dir);
		}
2467

Andrey Filippov's avatar
Andrey Filippov committed
2468
		public double [] getMergedValue(int dir)
2469
		{
Andrey Filippov's avatar
Andrey Filippov committed
2470
			if (this.merged_eig_val == null) {
2471 2472
				return null;
			}
Andrey Filippov's avatar
Andrey Filippov committed
2473
			return this.merged_eig_val[dir];
2474 2475
		}

2476 2477 2478 2479 2480 2481 2482
		public double [] getMergedValueEq(int dir)
		{
			if (this.merged_eig_eq == null) {
				return null;
			}
			return this.merged_eig_eq[dir];
		}
2483

2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
		public double [] getMergedWValue(int dir)
		{
			if (this.merged_weig_val == null) {
				return null;
			}
			return this.merged_weig_val[dir];
		}

		public double [] getMergedWValueEq(int dir)
		{
			if (this.merged_weig_eq == null) {
				return null;
			}
			return this.merged_weig_eq[dir];
		}

2500 2501


Andrey Filippov's avatar
Andrey Filippov committed
2502
		public double getMergedValue(int dir, int plane)
2503
		{
Andrey Filippov's avatar
Andrey Filippov committed
2504
			if ((this.merged_eig_val == null) ||(this.merged_eig_val[dir] == null)){
2505 2506
				return Double.NaN;
			}
Andrey Filippov's avatar
Andrey Filippov committed
2507
			return this.merged_eig_val[dir][plane];
2508
		}
2509 2510 2511 2512 2513 2514 2515 2516

		public double getMergedValueEq(int dir, int plane)
		{
			if ((this.merged_eig_eq == null) ||(this.merged_eig_eq[dir] == null)){
				return Double.NaN;
			}
			return this.merged_eig_eq[dir][plane];
		}
2517

2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
		public double getMergedWValue(int dir, int plane)
		{
			if ((this.merged_weig_val == null) || (this.merged_weig_val[dir] == null)){
				return Double.NaN;
			}
			return this.merged_weig_val[dir][plane];
		}

		public double getMergedWValueEq(int dir, int plane)
		{
			if ((this.merged_weig_eq == null) ||(this.merged_weig_eq[dir] == null)){
				return Double.NaN;
			}
			return this.merged_weig_eq[dir][plane];
		}
2533

2534 2535
		public void setNeibMatch(int dir, int plane, double value)
		{
Andrey Filippov's avatar
Andrey Filippov committed
2536
			this.merged_eig_val[dir][plane] = value;
2537
		}
2538 2539 2540 2541
		public void setNeibMatchEq(int dir, int plane, double value)
		{
			this.merged_eig_eq[dir][plane] = value;
		}
2542

2543 2544 2545 2546 2547 2548 2549 2550
		public void setNeibWMatch(int dir, int plane, double value)
		{
			this.merged_weig_val[dir][plane] = value;
		}
		public void setNeibWMatchEq(int dir, int plane, double value)
		{
			this.merged_weig_eq[dir][plane] = value;
		}
2551

2552 2553 2554 2555
		public boolean [][] getMergedValid()
		{
			return this.merged_valid;
		}
2556

2557 2558 2559 2560 2561 2562 2563
		public boolean [] getMergedValid(int dir)
		{
			if (this.merged_valid == null) {
				return null;
			}
			return this.merged_valid[dir];
		}
2564

2565 2566 2567 2568 2569 2570 2571 2572
		public boolean hasMergedValid(int dir){
			if ((this.merged_valid == null) || (this.merged_valid[dir] == null)){
				return false;
			}
			for (int np = 0; np < this.merged_valid[dir].length; np++){
				if (this.merged_valid[dir][np]) return true;
			}
			return false;
2573

2574
		}
2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
		public boolean isMergedValid(int dir, int plane)
		{
			if ((this.merged_valid == null) || (this.merged_valid[dir] == null)){
				return false;
			}
			return this.merged_valid[dir][plane];
		}

		public void setMergedValid(int dir, int plane, boolean valid)
		{
			this.merged_valid[dir][plane] = valid;
		}

		public void setMergedValid(int dir, int plane, boolean valid, int leng)
		{
			if (this.merged_valid == null){
				this.merged_valid = new boolean[8][];
			}
			if (this.merged_valid[dir] == null){
				this.merged_valid[dir] = new boolean[leng];
			}
			this.merged_valid[dir][plane] = valid;
		}
2598 2599


Andrey Filippov's avatar
Andrey Filippov committed
2600 2601 2602 2603
		public boolean [][] getMergedStrongValid()
		{
			return this.merged_strong_valid;
		}
2604

Andrey Filippov's avatar
Andrey Filippov committed
2605 2606 2607 2608 2609 2610 2611
		public boolean [] getMergedStrongValid(int dir)
		{
			if (this.merged_strong_valid == null) {
				return null;
			}
			return this.merged_strong_valid[dir];
		}
2612

Andrey Filippov's avatar
Andrey Filippov committed
2613 2614 2615 2616 2617 2618 2619 2620
		public boolean hasMergedStrongValid(int dir){
			if ((this.merged_strong_valid == null) || (this.merged_strong_valid[dir] == null)){
				return false;
			}
			for (int np = 0; np < this.merged_strong_valid[dir].length; np++){
				if (this.merged_strong_valid[dir][np]) return true;
			}
			return false;
2621

Andrey Filippov's avatar
Andrey Filippov committed
2622 2623 2624 2625 2626 2627 2628 2629
		}
		public boolean isMergedStrongValid(int dir, int plane)
		{
			if ((this.merged_strong_valid == null) || (this.merged_strong_valid[dir] == null)){
				return false;
			}
			return this.merged_strong_valid[dir][plane];
		}
2630

Andrey Filippov's avatar
Andrey Filippov committed
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
		public void setMergedStrongValid(int dir, int plane, boolean valid)
		{
			this.merged_strong_valid[dir][plane] = valid;
		}

		public void setMergedStrongValid(int dir, int plane, boolean valid, int leng)
		{
			if (this.merged_strong_valid == null){
				this.merged_strong_valid = new boolean[8][];
			}
			if (this.merged_strong_valid[dir] == null){
				this.merged_strong_valid[dir] = new boolean[leng];
			}
			this.merged_strong_valid[dir][plane] = valid;
		}
2646

2647 2648 2649
		public int [] initNeibBest()
		{
			this.neib_best = new int[8];
2650
			for (int i = 0; i < 8; i++) this.neib_best[i] = -1;
2651 2652 2653 2654 2655 2656 2657 2658
			return this.neib_best;
		}

		public int [] getNeibBest()
		{
			return this.neib_best;
		}

2659 2660 2661 2662 2663 2664 2665 2666 2667
		public int getNumNeibBest()
		{
			if (this.neib_best == null) {
				return 0;
			}
			int num = 0;
			for (int i = 0; i < this.neib_best.length; i++) if (this.neib_best[i] >= 0) num++;
			return num;
		}
2668

2669 2670 2671 2672 2673 2674 2675 2676
		public int getNeibBest(int dir)
		{
			if (this.neib_best == null) {
				return -1;
			}
			return this.neib_best[dir];
		}

2677 2678 2679 2680 2681
		public void setNeibBest(int [] vals)
		{
			this.neib_best = vals;
		}

2682 2683 2684 2685 2686
		public void setNeibBest(int dir, int val)
		{
			this.neib_best[dir] = val;
		}

2687 2688 2689



Andrey Filippov's avatar
Andrey Filippov committed
2690 2691 2692 2693 2694 2695 2696 2697
		public void setCorrectDistortions(
				boolean correctDistortions)
		{
			this.correctDistortions = correctDistortions;
		}
		public boolean getCorrectDistortions() {
			return correctDistortions;
		}
2698

2699 2700 2701 2702 2703 2704
		public boolean [] getPlaneSelection(){
			return plane_sel;
		}
		public void setPlaneSelection(boolean [] plane_sel){
			this.plane_sel = plane_sel;
		}
2705

Andrey Filippov's avatar
Andrey Filippov committed
2706 2707 2708 2709 2710 2711
		public int[] getSTileXY() {
			return sTileXY;
		}
		public double[] getZxy() {
			return zxy;
		}
2712 2713


Andrey Filippov's avatar
Andrey Filippov committed
2714 2715 2716
		public void setZxy(double[] zxy) {
			this.zxy = zxy;
		}
Andrey Filippov's avatar
Andrey Filippov committed
2717 2718 2719 2720 2721 2722 2723 2724
		public void setZxy(
				double z,
				double x,
				double y) {
			this.zxy = new double [3];
			this.zxy[0] = z;
			this.zxy[1] = x;
			this.zxy[2] = y;
2725

Andrey Filippov's avatar
Andrey Filippov committed
2726
		}
2727

Andrey Filippov's avatar
Andrey Filippov committed
2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
		public double[][] getVectors() {
			return vectors;
		}
		public double[] getVector() {
			return vectors[0];
		}
		public void setVectors(double[][] vectors) {
			this.vectors = vectors;
		}
		public double[] getValues() {
			return values;
		}
		public double getValue() {
			return values[0];
		}
2743

2744 2745 2746 2747 2748 2749 2750 2751
		/**
		 * Return "normalized" main eigenvalue - it is reduced for high disparities
		 * @return normalized main eigenvalue
		 */
		public double getNormValue(){
			double val = values[0];
			if ((dispNorm > 0.0) && (zxy[0] > dispNorm)){
				double k = dispNorm / zxy[0];
2752 2753
//				val *= k*k;
				val *= k ; // reducing correction for the large disparities (making it sqrt() )
2754 2755 2756
			}
			return val;
		}
2757

Andrey Filippov's avatar
Andrey Filippov committed
2758 2759 2760 2761 2762 2763 2764 2765 2766
		public void setValues(double[] values) {
			this.values = values;
		}
		public void setValues(double v1, double v2, double v3) {
			this.values = new double[3];
			this.values[0] = v1;
			this.values[1] = v2;
			this.values[2] = v3;
		}
2767 2768 2769 2770 2771


		public double[] getWxyz() {
			return wxyz;
		}
2772 2773


2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
		public void setWxyz(double[] wxyz) {
			this.wxyz = wxyz;
		}
		public void setWxyz(
				double x,
				double y,
				double z) {
			this.wxyz = new double [3];
			this.wxyz[0] = x;
			this.wxyz[1] = y;
			this.wxyz[2] = z;
		}
2786 2787 2788 2789




2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813
		public double[][] getWVectors() {
			return wvectors;
		}
		public double[] getWVector() {
			return wvectors[0];
		}
		public void setWVectors(double[][] wvectors) {
			this.wvectors = wvectors;
		}
		public double[] getWValues() {
			return wvalues;
		}
		public double getWValue() {
			return wvalues[0];
		}
		public void setWValues(double[] wvalues) {
			this.wvalues = wvalues;
		}
		public void setWValues(double wv1, double wv2, double wv3) {
			this.wvalues = new double[3];
			this.wvalues[0] = wv1;
			this.wvalues[1] = wv2;
			this.wvalues[2] = wv3;
		}
2814

Andrey Filippov's avatar
Andrey Filippov committed
2815 2816 2817 2818
		public int getNumPoints() {
			return num_points;
		}
		public void setNumPoints(int num_points) {
2819 2820 2821
			if (num_points < 0){
				System.out.println("setNumPoints(): Setting negative number of tiles in a plane: "+num_points);
			}
Andrey Filippov's avatar
Andrey Filippov committed
2822 2823 2824 2825 2826 2827 2828 2829
			this.num_points = num_points;
		}
		public double getWeight() {
			return weight;
		}
		public void setWeight(double weight) {
			this.weight = weight;
		}
2830 2831 2832
		public void scaleWeight(double scale) {
			this.weight *= scale;
		}
2833

Andrey Filippov's avatar
Andrey Filippov committed
2834 2835 2836 2837
		public double [] getWorldXYZ(boolean correct_distortions)
		{
			return getWorldXYZ(correct_distortions,0);
		}
2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
		public double [] getCenterPxPy() // supertile center (not plane center)
		{
			double [] px_py = {
					tileSize*(superTileSize * sTileXY[0] + superTileSize/2), // + zxy[1],
					tileSize*(superTileSize * sTileXY[1] + superTileSize/2)}; //  + zxy[2]};
			return px_py;
		}
		public GeometryCorrection getGeometryCorrection() {
			return geometryCorrection;
		}
		public void setGeometryCorrection(GeometryCorrection geometryCorrection) {
			this.geometryCorrection = geometryCorrection;
		}
2851

2852 2853 2854 2855 2856
		/**
		 * Get disparity values for the tiles of this supertile as [superTileSize*superTileSize] array
		 * @param useNaN replace unselected tiles with Double.NaN
		 * @return array of disparity values for the plane (not including overlapped areas)
		 */
2857
		public double[] getSinglePlaneDisparity( // getPlaneDisparity(
2858 2859 2860 2861 2862 2863 2864 2865
				boolean useNaN)
		{
			double [] disparities = new double[superTileSize*superTileSize];
			int indx = 0;
			double [] normal = getVector();
			double [] zxy =    getZxy(); // {disparity, x center in pixels, y center in pixels (relative to a supertile center)
			for (int sy = -superTileSize/2; sy < superTileSize/2; sy++){
				int indx_sel = (2*sy + superTileSize) * superTileSize + superTileSize/2;
Andrey Filippov's avatar
Andrey Filippov committed
2866 2867
				// adding half-tile and half-pixel to match the center of the pixel. Supertile center is between
				// pixel 31 and pixel 32 (counting from 0) in both directions
2868 2869
//				double y = tileSize * (sy + 0.5) + 0.5  - zxy[2];
				double y = tileSize * (sy + 0.5)  - zxy[2];
2870
				for (int sx = -superTileSize/2; sx < superTileSize/2; sx++){
2871 2872
//					double x = tileSize * (sx + 0.5) + 0.5 - zxy[1];
					double x = tileSize * (sx + 0.5) - zxy[1];
2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
					if (plane_sel[indx_sel] || !useNaN ||  (plane_sel==null)){
						disparities[indx] = zxy[0] - (normal[1] * x + normal[2] * y)/normal[0];
					} else {
						disparities[indx] = Double.NaN;
					}
					indx++;
					indx_sel++;
				}
			}
			return disparities;
		}
Andrey Filippov's avatar
Andrey Filippov committed
2884

2885 2886 2887 2888 2889 2890 2891
		public double[] getDoublePlaneDisparity(
				boolean useNaN)
		{
			return getDoublePlaneDisparity(
					true,
					useNaN);
		}
2892

Andrey Filippov's avatar
Andrey Filippov committed
2893 2894
		/**
		 * Get disparity values for the tiles of this overlapping supertile as [2*superTileSize * 2*superTileSize] array
2895
		 * @param useWorld calculate disparity in the real world (false - just px, py, disparity plane)
Andrey Filippov's avatar
Andrey Filippov committed
2896 2897 2898 2899
		 * @param useNaN replace unselected tiles with Double.NaN
		 * @return array of disparity values for the plane (not including overlapped areas)
		 */
		public double[] getDoublePlaneDisparity(
2900
				boolean useWorld,
Andrey Filippov's avatar
Andrey Filippov committed
2901 2902 2903 2904 2905 2906
				boolean useNaN)
		{
			double [] disparities = new double[4*superTileSize*superTileSize];
			int indx = 0;
			double [] normal = getVector();
			double [] zxy =    getZxy(); // {disparity, x center in pixels, y center in pixels (relative to a supertile center)
2907
			double [] pxyc = getCenterPxPy(); // center of this supertile, not plane center
Andrey Filippov's avatar
Andrey Filippov committed
2908 2909 2910
			for (int sy = -superTileSize; sy < superTileSize; sy++){
				// adding half-tile and half-pixel to match the center of the pixel. Supertile center is between
				// pixel 31 and pixel 32 (counting from 0) in both directions
2911 2912
//				double y = tileSize * (sy + 0.5) + 0.5  - zxy[2];
				double y = tileSize * (sy + 0.5)   - zxy[2];
Andrey Filippov's avatar
Andrey Filippov committed
2913
				for (int sx = -superTileSize; sx < superTileSize; sx++){
2914 2915
//					double x = tileSize * (sx + 0.5) + 0.5 - zxy[1];
					double x = tileSize * (sx + 0.5) - zxy[1];
Andrey Filippov's avatar
Andrey Filippov committed
2916
					if (plane_sel[indx] || !useNaN ||  (plane_sel==null)){
2917 2918 2919 2920 2921 2922 2923 2924 2925
						if (useWorld) {
							disparities[indx] = geometryCorrection.getPlaneDisparity( // disparity (at this center) for crossing other supertile plane
									getWorldXYZ(this.correctDistortions), // will calculate if not yet done so. Should it use otherPd, not pd? and then clone later?
									x + pxyc[0] + zxy[1],
									y + pxyc[1] + zxy[2],
									this.correctDistortions);
						} else {
							disparities[indx] = zxy[0] - (normal[1] * x + normal[2] * y)/normal[0];
						}
2926

Andrey Filippov's avatar
Andrey Filippov committed
2927 2928 2929 2930 2931 2932 2933 2934
					} else {
						disparities[indx] = Double.NaN;
					}
					indx++;
				}
			}
			return disparities;
		}
2935

Andrey Filippov's avatar
Andrey Filippov committed
2936 2937 2938 2939
		public double[] getDoublePlaneDisparity(
				int     dir,
				boolean useNaN)
		{
2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951
			return getDoublePlaneDisparity(
					true,
					dir,
					useNaN);
		}

		public double[] getDoublePlaneDisparity(
				boolean useWorld,
				int     dir,
				boolean useNaN)
		{
			double [] plane_all = getDoublePlaneDisparity(useWorld,useNaN);
Andrey Filippov's avatar
Andrey Filippov committed
2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968
			double [] plane = new double [superTileSize * superTileSize];
			int [] start_index = {
					superTileSize/2,                            // N    4
					superTileSize,                              // NE   8
					(superTileSize + 1) * superTileSize,        // E   72
					(2* superTileSize + 1) * superTileSize,     // SE 136
					(4* superTileSize + 1) * superTileSize / 2, // S  132
					2* superTileSize * superTileSize,           // SW 128
					superTileSize * superTileSize,              // W   64
					0};                                         // NW   0
			for (int y = 0; y < superTileSize; y++) {
				System.arraycopy(plane_all, start_index[dir] + 2 * superTileSize * y, plane,  superTileSize * y, superTileSize);
			}
			return plane;
		}

		public double[] getTriplePlaneDisparity()
2969 2970 2971 2972 2973 2974
		{
			return getTriplePlaneDisparity(true);
		}

		public double[] getTriplePlaneDisparity(
				boolean   useWorld)
Andrey Filippov's avatar
Andrey Filippov committed
2975 2976 2977 2978 2979
		{
			double [] disparities = new double[9*superTileSize*superTileSize];
			int indx = 0;
			double [] normal = getVector();
			double [] zxy =    getZxy(); // {disparity, x center in pixels, y center in pixels (relative to a supertile center)
2980
			double [] pxyc = getCenterPxPy(); // center of this supertile, not plane center
Andrey Filippov's avatar
Andrey Filippov committed
2981 2982 2983
			for (int sy = -3 * superTileSize / 2; sy < 3* superTileSize / 2; sy++){
				// adding half-tile and half-pixel to match the center of the pixel. Supertile center is between
				// pixel 31 and pixel 32 (counting from 0) in both directions
2984 2985
//				double y = tileSize * (sy + 0.5) + 0.5  - zxy[2];
				double y = tileSize * (sy + 0.5)  - zxy[2];
Andrey Filippov's avatar
Andrey Filippov committed
2986
				for (int sx = -3 * superTileSize/2; sx < 3 * superTileSize / 2; sx++){
2987 2988
//					double x = tileSize * (sx + 0.5) + 0.5 - zxy[1];
					double x = tileSize * (sx + 0.5) - zxy[1];
2989 2990 2991 2992 2993 2994 2995 2996 2997
					if (useWorld) {
						disparities[indx] = geometryCorrection.getPlaneDisparity( // disparity (at this center) for crossing other supertile plane
								getWorldXYZ(this.correctDistortions), // will calculate if not yet done so. Should it use otherPd, not pd? and then clone later?
								x + pxyc[0] + zxy[1],
								y + pxyc[1] + zxy[2],
								this.correctDistortions);
					} else {
						disparities[indx] = zxy[0] - (normal[1] * x + normal[2] * y)/normal[0];
					}
Andrey Filippov's avatar
Andrey Filippov committed
2998 2999 3000 3001 3002
					indx++;
				}
			}
			return disparities;
		}
3003

Andrey Filippov's avatar
Andrey Filippov committed
3004 3005 3006
		public double[] getTriplePlaneDisparity(
				int     dir)
		{
3007 3008 3009 3010 3011 3012 3013 3014
			return getTriplePlaneDisparity(true, dir);
		}

		public double[] getTriplePlaneDisparity(
				boolean   useWorld,
				int     dir)
		{
			double [] plane_all = getTriplePlaneDisparity(useWorld);
Andrey Filippov's avatar
Andrey Filippov committed
3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029
			double [] plane = new double [superTileSize * superTileSize];
			int [] start_index = {
					superTileSize,                               // N    8
					2 * superTileSize,                           // NE  16
					(3 * superTileSize + 2) * superTileSize,     // E  208
					(3 * superTileSize + 1) * superTileSize * 2, // SE 400
					(6 * superTileSize + 1) * superTileSize ,    // S  392
					6 * superTileSize * superTileSize,           // SW 384
					3 * superTileSize * superTileSize,           // W  192
					0};                                          // NW   0
			for (int y = 0; y < superTileSize; y++) {
				System.arraycopy(plane_all, start_index[dir] + 3 * superTileSize * y, plane,  superTileSize * y, superTileSize);
			}
			return plane;
		}
3030

3031
		public double[][] getDoublePlaneDisparityStrengthOld(
3032 3033 3034 3035 3036
				double [] window,
				boolean   use_sel,
				boolean   divide_by_area,
				double    scale_projection,
				int       debugLevel)
3037
		{		return getDoublePlaneDisparityStrengthOld(
3038 3039 3040 3041 3042 3043
				true,
				window,
				use_sel,
				divide_by_area,
				scale_projection,
				debugLevel);
3044
		}
3045

3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064
		public EigenvalueDecomposition get2dDecomposition()
		{
			double [] vals3d =      getValues();
			double [][] vectors3d = getVectors();
			double [][] acovar = new double [2][2];
			for (int i = 0; i < 2; i++){
				for (int j = i; j < 2; j++){
					acovar[i][j] = 0.0;
					for (int k = 0; k < 3; k++){
						acovar[i][j] += vals3d[k] * vectors3d[k][i+1] * vectors3d[k][j+1]; // 0 - z, disparity == 0
					}
					if (i != j) {
						acovar[j][i] =acovar[i][j];
					}
				}
			}
			Matrix covar = new Matrix(acovar); // 2d, x y only
			return covar.eig();
		}
3065

3066 3067 3068 3069
		/**
		 * Get disparity values for the tiles of this overlapping supertile as [2*superTileSize * 2*superTileSize] array
		 * and weights combined from provided window function, optional selection and using ellipsoid projection on the
		 * px, py plane (constant disparity
3070
		 * Sharp weights - when selecting the best match - use exponent of (delta_disp) ^2 ?
3071 3072
		 * Or divide weight by ellipse area?
		 * @param useWorld calculate disparity in the real world (false - just px, py, disparity plane)
3073 3074
		 * @param window null or window function as [2*superTileSize * 2*superTileSize] array
		 * @param use_sel use plane selection (this.sel_mask) to select only some part of the plane
3075
		 * @param divide_by_area divide weights by ellipsoid area
3076
		 * @param scale_projection use plane ellipsoid projection for weight: 0 - do not use, > 0 linearly scale ellipsoid
3077
		 * @return a pair of arrays {disparity, strength}, each [2*superTileSize * 2*superTileSize]
3078
		 */
3079
		// obsolete, convert to another version ?
3080
		public double[][] getDoublePlaneDisparityStrengthOld(
3081
				boolean   useWorld,
3082 3083
				double [] window,
				boolean   use_sel,
3084
				boolean   divide_by_area,
3085 3086 3087 3088 3089 3090 3091 3092 3093 3094
				double    scale_projection,
				int       debugLevel)
		{
			double [][] disp_strength = new double[2][4*superTileSize*superTileSize];
			double [] normal = getVector();
			double [] zxy =    getZxy(); // {disparity, x center in pixels, y center in pixels (relative to a supertile center)
			double    weight = getWeight();
			double k_gauss = 0;
			Matrix val2d = null, vect2d = null;
			if (scale_projection > 0.0){
3095
				EigenvalueDecomposition eig = get2dDecomposition();
3096 3097 3098
				val2d = eig.getD();
				vect2d = eig.getV().transpose();
				k_gauss = 0.5/(scale_projection*scale_projection);
3099 3100 3101 3102 3103 3104
				if (divide_by_area) {
					double area = Math.sqrt(val2d.get(0, 0)*val2d.get(1, 1));
					if (area > 0){
						weight /= area;
					}
				}
3105
			}
3106 3107 3108 3109 3110 3111 3112 3113 3114
			double [] pxyc = getCenterPxPy(); // center of this supertile, not plane center
			if (debugLevel > 0) {
				double world_disp = geometryCorrection.getPlaneDisparity( // disparity (at this center) for crossing other supertile plane
						getWorldXYZ(this.correctDistortions), // will calculate if not yet done so. Should it use otherPd, not pd? and then clone later?
						zxy[1] + pxyc[0],
						zxy[2] + pxyc[1],
						this.correctDistortions);
				System.out.println("getDoublePlaneDisparityStrength(): zxy = ["+zxy[0]+", "+zxy[1]+", "+zxy[2]+"], disp = "+world_disp);
			}
3115
			int indx = 0;
3116 3117 3118
			for (int sy = -superTileSize; sy < superTileSize; sy++){
				// adding half-tile and half-pixel to match the center of the pixel. Supertile center is between
				// pixel 31 and pixel 32 (counting from 0) in both directions
3119 3120
//				double y = tileSize * (sy + 0.5) + 0.5 - zxy[2];
				double y = tileSize * (sy + 0.5) - zxy[2];
3121
				for (int sx = -superTileSize; sx < superTileSize; sx++){
3122 3123
//					double x = tileSize * (sx + 0.5) + 0.5 - zxy[1];
					double x = tileSize * (sx + 0.5) - zxy[1];
3124 3125 3126 3127 3128 3129 3130 3131 3132
					if (useWorld) {
						disp_strength[0][indx] = geometryCorrection.getPlaneDisparity( // disparity (at this center) for crossing other supertile plane
								getWorldXYZ(this.correctDistortions), // will calculate if not yet done so. Should it use otherPd, not pd? and then clone later?
								x + pxyc[0] + zxy[1],
								y + pxyc[1] + zxy[2],
								this.correctDistortions);
					} else {
						disp_strength[0][indx] = zxy[0] - (normal[1] * x + normal[2] * y)/normal[0];
					}
3133

3134 3135 3136 3137 3138 3139
					double w = weight;
					if (window != null) w *= window[indx];
					if (use_sel && (sel_mask != null) && !(sel_mask[indx])) w = 0.0;
					if ((w > 0.0) && (scale_projection > 0.0)){
						double [] xy = {x,y};
						Matrix vxy = vect2d.times(new Matrix(xy,2)); // verify if it is correct
3140
						double r2 = 0;
3141 3142 3143 3144
						for (int i = 0; i <2; i++){
							double d = vxy.get(i,0);
							r2 += d * d / val2d.get(i, i);
						}
3145
						w *= Math.exp(-k_gauss*r2);
3146
					}
3147 3148 3149 3150 3151 3152 3153
					disp_strength[1][indx] = w;
					indx++;
				}
			}
			return disp_strength;
		}

3154 3155 3156 3157 3158 3159 3160 3161
		public double[][] getDoublePlaneDisparityStrength(
				double [] window,
				int       dir,
				boolean   use_sel,
				boolean   divide_by_area,
				double    scale_projection,
				double    fraction_uni,
				int       debugLevel)
3162
		{
3163 3164 3165 3166 3167 3168 3169 3170 3171 3172
			return getDoublePlaneDisparityStrength(
					true,
					window,
					dir,
					use_sel,
					divide_by_area,
					scale_projection,
					fraction_uni,
					debugLevel);
		}
3173

3174 3175 3176 3177 3178 3179
		/**
		 * Get disparity values for the tiles of this overlapping supertile as [2*superTileSize * 2*superTileSize] array
		 * and weights combined from provided window function, optional selection and using ellipsoid projection on the
		 * px, py plane (constant disparity
		 * Sharp weights - when selecting the best match - use exponent of (delta_disp) ^2 ?
		 * Or divide weight by ellipse area?
3180
		 * @param useWorld calculate disparity in the real world (false - just px, py, disparity plane)
3181 3182 3183 3184
		 * @param window null or window function as [2*superTileSize * 2*superTileSize] array
		 * @param dir - source tile shift from the target: -1 center, 0 - N, 1 - NE
		 * @param use_sel use plane selection (this.sel_mask) to select only some part of the plane
		 * @param divide_by_area divide weights by ellipsoid area
3185
		 * @param scale_projection use plane ellipsoid projection for weight: 0 - do not use, > 0 linearly scale ellipsoid
3186
		 * @param fraction_uni add fraction of the total weight to each tile
3187 3188
		 * @return a pair of arrays {disparity, strength}, each [2 * superTileSize * 2 * superTileSize], only 1/2 or 1/4 used for offset tiles\
		 * TODO: add a combination of the ellipses and infinite planes?
3189
		 *
3190 3191
		 */
		public double[][] getDoublePlaneDisparityStrength(
3192
				boolean   useWorld,
3193 3194 3195 3196 3197
				double [] window,
				int       dir,
				boolean   use_sel,
				boolean   divide_by_area,
				double    scale_projection,
3198
				double    fraction_uni,
3199 3200
				int       debugLevel)
		{
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210
			return  getDoublePlaneDisparityStrength(
					useWorld ? getWorldXYZ(this.correctDistortions) : null, // will calculate if not yet done so. Should it use otherPd, not pd? and then clone later?
					window,
					dir,
					use_sel,
					divide_by_area,
					scale_projection,
					fraction_uni,
					debugLevel);
		}
3211

3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222
		public double [] getWorldXYZFromWorld()
		{
			double []   wxyz = getWxyz();
			double [][] wvectors = getWVectors();
			if ((wxyz == null) || (wvectors == null)  || (wvectors[0] == null)) return null;
			double normal_dot_normal = 0.0; // supposed to be unit length, but we'll still re-normalize it
			double center_dot_normal = 0.0;
			for (int i = 0; i < 3; i++){
				normal_dot_normal += wvectors[0][i] *  wvectors[0][i];
				center_dot_normal += wxyz[i] *  wvectors[0][i];
			}
3223
			double scale = center_dot_normal / normal_dot_normal;
3224 3225 3226 3227 3228 3229
			double [] rslt = wvectors[0].clone();
			for (int i = 0; i < 3; i++){
				rslt[i] *= scale;
			}
			return rslt;
		}
3230

3231 3232 3233 3234 3235 3236 3237 3238 3239
		public double[][] getDoublePlaneWorldDisparityStrength(
				double [] window,
				int       dir,
				boolean   use_sel,
				boolean   divide_by_area,
				double    scale_projection,
				double    fraction_uni,
				int       debugLevel)
		{
3240

3241 3242 3243 3244 3245 3246 3247 3248 3249 3250
			return  getDoublePlaneDisparityStrength(
					getWorldXYZFromWorld(),
					window,
					dir,
					use_sel,
					divide_by_area,
					scale_projection,
					fraction_uni,
					debugLevel);
		}
3251

3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
		/**
		 * Get disparity values for the tiles of this overlapping supertile as [2*superTileSize * 2*superTileSize] array
		 * and weights combined from provided window function, optional selection and using ellipsoid projection on the
		 * px, py plane (constant disparity
		 * Sharp weights - when selecting the best match - use exponent of (delta_disp) ^2 ?
		 * Or divide weight by ellipse area?
		 * @param world_normal Noral vector to the plane from the origin, or null to stay in pixel/disparity space.
		 * @param window null or window function as [2*superTileSize * 2*superTileSize] array
		 * @param dir - source tile shift from the target: -1 center, 0 - N, 1 - NE
		 * @param use_sel use plane selection (this.sel_mask) to select only some part of the plane
		 * @param divide_by_area divide weights by ellipsoid area
3263
		 * @param scale_projection use plane ellipsoid projection for weight: 0 - do not use, > 0 linearly scale ellipsoid
3264 3265 3266
		 * @param fraction_uni add fraction of the total weight to each tile
		 * @return a pair of arrays {disparity, strength}, each [2 * superTileSize * 2 * superTileSize], only 1/2 or 1/4 used for offset tiles\
		 * TODO: add a combination of the ellipses and infinite planes?
3267
		 *
3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
		 */
		public double[][] getDoublePlaneDisparityStrength(
				double [] world_normal, // either real world normal vector from (0,0,0) to the plane or null, in that case will stay n disparity space
				double [] window,
				int       dir,
				boolean   use_sel,
				boolean   divide_by_area,
				double    scale_projection,
				double    fraction_uni,
				int       debugLevel)
		{
			double [][] disp_strength = new double[2][4*superTileSize*superTileSize];
			double [] normal = getVector();
			double [] zxy =    getZxy(); // {disparity, x center in pixels, y center in pixels (relative to a supertile center)
			double    weight = getWeight();
			double k_gauss = 0;
			Matrix val2d = null, vect2d = null;
			if (scale_projection > 0.0){
				EigenvalueDecomposition eig = get2dDecomposition();
				val2d = eig.getD();
				vect2d = eig.getV().transpose();
				k_gauss = 0.5/(scale_projection*scale_projection);
				if (divide_by_area) {
					double area = Math.sqrt(val2d.get(0, 0)*val2d.get(1, 1));
					if (area > 0){
						weight /= area;
					}
				}
			}
			int ss2 = superTileSize;
			int ss4 = 2 * superTileSize;
3299 3300


3301 3302
			int [][] offsets = {
					// ymin, ymax, xmin,xmax, offsy, offsx
3303 3304 3305 3306 3307 3308 3309 3310
					{  0, ss4,   0, ss4,    0,    0 },  // center
					{ss2, ss4,   0, ss4, -ss2,    0 },  // N
					{ss2, ss4,   0, ss2, -ss2,  ss2 },  // NE
					{  0, ss4,   0, ss2,    0,  ss2 },  // E
					{  0, ss2,   0, ss2,  ss2,  ss2 },  // SE
					{  0, ss2,   0, ss4,  ss2,    0 },  // S
					{  0, ss2, ss2, ss4,  ss2, -ss2 },  // SW
					{  0, ss4, ss2, ss4,    0, -ss2 },  // W
3311 3312
					{ss2, ss4, ss2, ss4, -ss2, -ss2 }}; // NW
			int dir1 = dir + 1;
3313
			double [] pxyc = getCenterPxPy(); // center of this supertile, not plane center
3314 3315 3316
			for (int iy = offsets[dir1][0]; iy < offsets[dir1][1]; iy++){
				// adding half-tile and half-pixel to match the center of the pixel. Supertile center is between
				// pixel 31 and pixel 32 (counting from 0) in both directions
3317 3318
//				double y = tileSize * (iy - ss2 + 0.5) + 0.5  - zxy[2];
				double y = tileSize * (iy - ss2 + 0.5)  - zxy[2];
3319 3320
				int oy = iy + offsets[dir1][4]; //vert index in the result tile
				for (int ix = offsets[dir1][2]; ix < offsets[dir1][3]; ix++){
3321 3322
//					double x = tileSize * (ix - ss2 + 0.5) + 0.5 - zxy[1];
					double x = tileSize * (ix - ss2 + 0.5) - zxy[1];
3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337
					int indx = ss4 * oy + ix + offsets[dir1][5];
					int indx_i = iy * ss4 + ix; // input index
					if (world_normal != null) {
						disp_strength[0][indx] = geometryCorrection.getPlaneDisparity( // disparity (at this center) for crossing other supertile plane
								world_normal,
								x + pxyc[0] + zxy[1],
								y + pxyc[1] + zxy[2],
								this.correctDistortions);
					} else {
						disp_strength[0][indx] = zxy[0] - (normal[1] * x + normal[2] * y)/normal[0];
					}
					double w = weight;
					if ((w > 0.0) && (scale_projection > 0.0)){
						double [] xy = {x,y};
						Matrix vxy = vect2d.times(new Matrix(xy,2)); // verify if it is correct
3338
						double r2 = 0;
3339 3340 3341 3342 3343
						for (int i = 0; i <2; i++){
							double d = vxy.get(i,0);
							r2 += d * d / val2d.get(i, i);
						}
						w *= ((1.0 - fraction_uni) * Math.exp(-k_gauss*r2) + fraction_uni);
3344

3345 3346
						if (window != null) w *= window[indx_i];
						if (use_sel && (sel_mask != null) && !(sel_mask[indx_i])) w = 0.0;
3347
					}
3348 3349 3350 3351
					disp_strength[1][indx] = w;
				}
			}
			return disp_strength;
3352
		}
3353

3354 3355


3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372
		public double[][] getSinglePlaneDisparityStrength(
				double [] window,
				int       dir,
				boolean   use_sel,
				boolean   divide_by_area,
				double    scale_projection,
				int       debugLevel)
		{
			return getSinglePlaneDisparityStrength(
					true,
					window,
					dir,
					use_sel,
					divide_by_area,
					scale_projection,
					debugLevel);
		}
3373 3374 3375 3376 3377
		/**
		 * Get disparity values for the tiles of this overlapping supertile as [superTileSize * superTileSize] array
		 * and weights combined from provided window function, optional selection and using ellipsoid projection on the
		 * px, py plane (constant disparity
		 * Sharp weights - when selecting the best match - use exponent of (delta_disp) ^2 ?
3378
		 * Or divide weight by ellipse area?
3379
		 * @param useWorld calculate disparity in the real world (false - just px, py, disparity plane)
3380
		 * @param window null or window function as [2*superTileSize * 2*superTileSize] array
3381
		 * @param dir - source tile shift from the target: -1 center, 0 - N, 1 - NE
3382 3383
		 * @param use_sel use plane selection (this.sel_mask) to select only some part of the plane
		 * @param divide_by_area divide weights by ellipsoid area
3384
		 * @param scale_projection use plane ellipsoid projection for weight: 0 - do not use, > 0 linearly scale ellipsoid
3385 3386
		 * @return a pair of arrays {disparity, strength}, each [superTileSize * superTileSize], only 1/2 or 1/4 used for offset tiles\
		 * TODO: add a combination of the ellipses and infinite planes?
3387
		 *
3388 3389
		 */
		public double[][] getSinglePlaneDisparityStrength(
3390
				boolean   useWorld,
3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404
				double [] window,
				int       dir,
				boolean   use_sel,
				boolean   divide_by_area,
				double    scale_projection,
				int       debugLevel)
		{
			double [][] disp_strength = new double[2][superTileSize*superTileSize];
			double [] normal = getVector();
			double [] zxy =    getZxy(); // {disparity, x center in pixels, y center in pixels (relative to a supertile center)
			double    weight = getWeight();
			double k_gauss = 0;
			Matrix val2d = null, vect2d = null;
			if (scale_projection > 0.0){
3405
				EigenvalueDecomposition eig = get2dDecomposition();
3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419
				val2d = eig.getD();
				vect2d = eig.getV().transpose();
				k_gauss = 0.5/(scale_projection*scale_projection);
				if (divide_by_area) {
					double area = Math.sqrt(val2d.get(0, 0)*val2d.get(1, 1));
					if (area > 0){
						weight /= area;
					}
				}
			}
			int ss1 = superTileSize / 2;
			int ss2 = superTileSize;
			int ss3 = 3 *ss1;
			int ss4 = 2 * superTileSize;
3420 3421


3422 3423
			int [][] offsets = {
					// ymin, ymax, xmin,xmax, offsy, offsx
3424 3425 3426 3427 3428 3429 3430 3431
					{ss1, ss3, ss1, ss3, -ss1, -ss1 },  // center
					{ss3, ss4, ss1, ss3, -ss3, -ss1 },  // N
					{ss3, ss4,   0, ss1, -ss3,  ss1 },  // NE
					{ss1, ss3,   0, ss1, -ss1,  ss1 },  // E
					{  0, ss1,   0, ss1,  ss1,  ss1 },  // SE
					{  0, ss1, ss1, ss3,  ss1, -ss1 },  // S
					{  0, ss1, ss3, ss4,  ss1, -ss3 },  // SW
					{ss1, ss3, ss3, ss4, -ss1, -ss3 },  // W
3432 3433
					{ss3, ss4, ss3, ss4, -ss3, -ss3 }}; // NW
			int dir1 = dir + 1;
3434
			double [] pxyc = getCenterPxPy(); // center of this supertile, not plane center
3435 3436 3437
			for (int iy = offsets[dir1][0]; iy < offsets[dir1][1]; iy++){
				// adding half-tile and half-pixel to match the center of the pixel. Supertile center is between
				// pixel 31 and pixel 32 (counting from 0) in both directions
3438 3439
//				double y = tileSize * (iy - ss2 + 0.5) + 0.5  - zxy[2];
				double y = tileSize * (iy - ss2 + 0.5)  - zxy[2];
3440 3441
				int oy = iy + offsets[dir1][4]; //vert index in the result tile
				for (int ix = offsets[dir1][2]; ix < offsets[dir1][3]; ix++){
3442 3443
//					double x = tileSize * (ix - ss2 + 0.5) + 0.5 - zxy[1];
					double x = tileSize * (ix - ss2 + 0.5) - zxy[1];
3444 3445
					int indx = ss2 * oy + ix + offsets[dir1][5];
					int indx_i = iy * ss4 + ix; // ss2;
3446 3447 3448 3449 3450 3451 3452 3453 3454
					if (useWorld) {
						disp_strength[0][indx] = geometryCorrection.getPlaneDisparity( // disparity (at this center) for crossing other supertile plane
								getWorldXYZ(this.correctDistortions), // will calculate if not yet done so. Should it use otherPd, not pd? and then clone later?
								x + pxyc[0] + zxy[1],
								y + pxyc[1] + zxy[2],
								this.correctDistortions);
					} else {
						disp_strength[0][indx] = zxy[0] - (normal[1] * x + normal[2] * y)/normal[0];
					}
3455

3456 3457 3458 3459 3460 3461
					double w = weight;
					if (window != null) w *= window[indx_i];
					if (use_sel && (sel_mask != null) && !(sel_mask[indx_i])) w = 0.0;
					if ((w > 0.0) && (scale_projection > 0.0)){
						double [] xy = {x,y};
						Matrix vxy = vect2d.times(new Matrix(xy,2)); // verify if it is correct
3462
						double r2 = 0;
3463 3464 3465 3466 3467
						for (int i = 0; i <2; i++){
							double d = vxy.get(i,0);
							r2 += d * d / val2d.get(i, i);
						}
						w *= Math.exp(-k_gauss*r2);
3468
					}
3469 3470 3471 3472 3473 3474
					disp_strength[1][indx] = w;
				}
			}
			return disp_strength;
		}

3475 3476 3477



Andrey Filippov's avatar
Andrey Filippov committed
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493
		/**
		 * Cross product of 2 3-d vectors as column matrices
		 * @param v1
		 * @param v2
		 * @return v1 x v2 as a column (3x1) matrix
		 */
		public Matrix cross3d (Matrix v1, Matrix v2)
		{
			double [][]av1 = v1.getArray();
			double [][]av2 = v2.getArray();
			double [][] ar = {
					{av1[1][0]*av2[2][0] - av1[2][0]*av2[1][0]},
					{av1[2][0]*av2[0][0] - av1[0][0]*av2[2][0]},
					{av1[0][0]*av2[1][0] - av1[1][0]*av2[0][0]}};
			return new Matrix (ar);
		}
3494

3495
		/**
3496 3497
		 * Get sin squared of the angle between planes in the real world
		 * @param otherPd other plane data
3498
		 * @param correct_distortions true if the lens distortions should be corrected
3499 3500 3501 3502 3503 3504
		 * @return sine squared of the angle between normals to the planes
		 */
		public double getWorldSin2(
				PlaneData otherPd,
				boolean correct_distortions)
		{
3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515
			try {
				Matrix this_wv =  new Matrix(this.getWorldXYZ(correct_distortions, 0),3);
				Matrix other_wv = new Matrix(otherPd.getWorldXYZ(correct_distortions, 0),3); // FIXME: this caused null pointer
				Matrix cp = cross3d(this_wv, other_wv);
				double cp2 = cp.transpose().times(cp).get(0, 0);
				double this_wv2 = this_wv.transpose().times(this_wv).get(0, 0);
				double other_wv2 = other_wv.transpose().times(other_wv).get(0, 0);
				return cp2/(this_wv2 * other_wv2);
			} catch (Exception e) {
				System.out.println("Problem in getWorldSin2():");
				// TODO Auto-generated catch block
Andrey Filippov's avatar
Andrey Filippov committed
3516
//				e.printStackTrace();
3517 3518 3519
				// do nothing, just keep
				return 1.0;
			}
3520 3521 3522 3523 3524 3525 3526 3527
		}
		public double getWorldSin2(
				PlaneData otherPd)
		{
			return getWorldSin2(otherPd, this.correctDistortions);
		}

		/**
3528
		 * Get distance squared from the other plane and the center of the current "plane" (ellipsoid)
3529
		 * @param otherPd other plane data
3530
		 * @param correct_distortions true if the lens distortions should be corrected
3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542
		 * @return distance squared from other plane to the (ellipsoid) center of this one (in meters)
		 */
		public double getWorldPlaneDist2(
				PlaneData otherPd,
				boolean correct_distortions)
		{
			Matrix this_center =  new Matrix(this.getCenterXYZ(correct_distortions, 0),3);
			Matrix other_wv =     new Matrix(otherPd.getWorldXYZ(correct_distortions, 0),3);
			double w_dot_w = other_wv.transpose().times(other_wv).get(0, 0);
			double w_dot_p = other_wv.transpose().times(this_center).get(0, 0);
			return (w_dot_w - w_dot_p)*(w_dot_w - w_dot_p)/w_dot_w;
		}
3543

3544 3545 3546 3547 3548
		public double getWorldPlaneDist2(
				PlaneData otherPd)
		{
			return getWorldPlaneDist2(otherPd, this.correctDistortions);
		}
3549

3550
		/**
3551
		 * Get squared relative (to the z of the center) distance from the other plane to the center of the current "plane" (ellipsoid)
3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562
		 * @param otherPd other plane data
		 * @return squared ratio of the distance the other plane to the (ellipsoid) center of this one over Z-distance
		 */
		public double getWorldPlaneRDist2(
				PlaneData otherPd)
		{
			double dist2 = getWorldPlaneDist2(otherPd, this.correctDistortions);
			double z =getCenterXYZ(this.correctDistortions, 0)[2];
			return dist2/(z*z);
		}

3563 3564


3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577
		/**
		 * Combine 2 Plane instances using centers, eigenvalues eihenvectors and total weights of this and other PlaneData objects
		 * other plane should already be transformed to the same supertile coordinate system (with getPlaneToThis() method)
		 * @param otherPd PlaneData object to merge with. Should be transformed to the same supertile ( same sTileXY values)
		 * @param scale_other scale total weight of the other PlaneData object
		 * @param ignore_weights assume original weights of the planes where equal, only use scale_other
		 * @param debugLevel debug level
		 * @return PlaneData object representing merged planes with combined weight (scale_other*otherPd.weight + this.weight),
		 * recalculated center, eigenvalues and eigenvectors
		 */
		public PlaneData mergePlaneToThis(
				PlaneData otherPd,
				double    scale_other,
3578
				double    starWeightPwr,    // Use this power of tile weight when calculating connection cost
3579
				boolean   ignore_weights,
3580
				boolean   sum_weights,
3581
				boolean   preferDisparity, // Always start with disparity-most axis (false - lowest eigenvalue)
3582 3583 3584 3585 3586
				int       debugLevel)
		{
			if (debugLevel > 0) {
				System.out.println("mergePlaneToThis()");
			}
3587 3588 3589
			if (values == null ) {
				System.out.println("mergePlaneToThis(): values=null:\n"+toString());
				return null;
3590

3591 3592 3593 3594 3595
			}
			if (otherPd.values == null ) {
				System.out.println("mergePlaneToThis(): otherPd.values=null:\n"+otherPd.toString());
				return null;
			}
3596

3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607
			double [][] this_eig_avals = {
					{values[0], 0.0,       0.0},
					{0.0,       values[1], 0.0},
					{0.0,       0.0,       values[2]}};
			double [][] other_eig_avals = {
					{otherPd.values[0], 0.0,               0.0},
					{0.0,               otherPd.values[1], 0.0},
					{0.0,               0.0,               otherPd.values[2]}};
			Matrix this_eig_vals =     new Matrix(this_eig_avals);
			Matrix other_eig_vals =    new Matrix(other_eig_avals);
			Matrix other_eig_vectors = new Matrix(otherPd.vectors).transpose(); // vectors are saved as rows
3608
			Matrix this_eig_vectors =  new Matrix(this.vectors).transpose();    // vectors are saved as rows
3609 3610
			Matrix this_center    =    new Matrix(this.getZxy(),3);
			Matrix other_center    =   new Matrix(otherPd.getZxy(),3); // should already be relative to this supertile center
3611 3612 3613 3614 3615 3616 3617 3618
			double this_weight = this.weight;
			double other_weight = otherPd.weight;
			if (starWeightPwr == 0){
				ignore_weights = true;
			} else if (starWeightPwr != 1.0){
				this_weight =  Math.pow(this_weight, starWeightPwr);
				other_weight = Math.pow(other_weight,starWeightPwr);
			}
3619

3620
			double sum_weight =      scale_other *  other_weight + this_weight;// should be the same for
3621
			double other_fraction = ignore_weights? (scale_other/(scale_other + 1.0)): ((scale_other *  other_weight) / sum_weight);
3622
			Matrix common_center =  this_center.times(1.0 - other_fraction).plus(other_center.times(other_fraction));
3623 3624 3625 3626 3627
			Matrix other_offset =   other_center.minus(this_center); // other center from this center
			if ((this.values[0] == 0.0) || (otherPd.values[0] == 0.0)) {
				System.out.println("Zero eigenvalue");
				debugLevel = 10;
			}
3628
			if (debugLevel > 1) {
3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646
				System.out.println("other_eig_vals");
				other_eig_vals.print(8, 6);
				System.out.println("this_eig_vals");
				this_eig_vals.print(8, 6);
				System.out.println("other_eig_vectors");
				other_eig_vectors.print(8, 6);
				System.out.println("this_eig_vectors");
				this_eig_vectors.print(8, 6);
				System.out.println("other_center");
				other_center.print(8, 6);
				System.out.println("this_center");
				this_center.print(8, 6);
				System.out.println("common_center");
				common_center.print(8, 6);
				System.out.println("other_offset");
				other_offset.print(8, 6);
				System.out.println("other_fraction="+other_fraction);
			}
3647

3648 3649 3650 3651 3652
			double [][] acovar = { // covariance matrix of center masses (not yet scaled by weight)
					{other_offset.get(0,0)*other_offset.get(0,0), other_offset.get(0,0)*other_offset.get(1,0), other_offset.get(0,0)*other_offset.get(2,0)},
					{other_offset.get(1,0)*other_offset.get(0,0), other_offset.get(1,0)*other_offset.get(1,0), other_offset.get(1,0)*other_offset.get(2,0)},
					{other_offset.get(2,0)*other_offset.get(0,0), other_offset.get(2,0)*other_offset.get(1,0), other_offset.get(2,0)*other_offset.get(2,0)}};

3653
			Matrix other_covar = other_eig_vectors.times(other_eig_vals.times(other_eig_vectors.transpose()));
3654 3655
			Matrix this_covar =  this_eig_vectors.times(this_eig_vals.times(this_eig_vectors.transpose()));
			Matrix covar = (new Matrix(acovar)).times(other_fraction*(1.0-other_fraction)); // only centers with all masses
3656
			if (debugLevel > 1) {
3657 3658 3659 3660 3661 3662
				System.out.println("other_covar");
				other_covar.print(8, 6);
				System.out.println("this_covar");
				this_covar.print(8, 6);
				System.out.println("covar");
				covar.print(8, 6);
3663
			}
3664

3665
			covar.plusEquals(other_covar.times(other_fraction));
3666
			if (debugLevel > 1) {
3667 3668 3669 3670
				System.out.println("covar with other_covar");
				covar.print(8, 6);
			}
			covar.plusEquals(this_covar.times(1.0 - other_fraction));
3671
			if (debugLevel > 1) {
3672 3673 3674
				System.out.println("covar with other_covar and this_covar");
				covar.print(8, 6);
			}
3675
			if (Double.isNaN(covar.get(0, 0))){
3676
				System.out.println("covar is NaN 1 !");
3677
				covar.print(8, 6);
3678
				return null;
3679
			}
3680
			// extract new eigenvalues, eigenvectors
3681
			EigenvalueDecomposition eig = covar.eig(); // verify NaN - it gets stuck
3682 3683
			//			eig.getD().getArray(),
			//			eig.getV().getArray(),
3684
			if (debugLevel > 1) {
3685 3686 3687 3688 3689 3690
				System.out.println("eig.getV()");
				eig.getV().print(8, 6);
				System.out.println("eig.getD()");
				eig.getD().print(8, 6);
			}

3691 3692


3693 3694 3695
			double [][] eig_vect = eig.getV().getArray();
			double [][] eig_val = eig.getD().getArray();
			// make towards camera, left coordinate system
3696
			/*
3697 3698 3699 3700 3701 3702
			int oindx = 0;
			for (int i = 1; i <3; i++){
				if (Math.abs(eig_vect[0][i]) > Math.abs(eig_vect[0][oindx])){
					oindx = i;
				}
			}
3703
			 */
3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718
			int oindx = 0;
			if (preferDisparity) {
				for (int i = 1; i <3; i++){
					if (Math.abs(eig_vect[0][i]) > Math.abs(eig_vect[0][oindx])){
						oindx = i;
					}
				}
			} else {
				for (int i = 1; i <3; i++){
					if (eig_val[i][i] < eig_val[oindx][oindx]){
						oindx = i;
					}
				}

			}
3719

3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736
			// select 2 other axes for increasing eigenvalues (so v is short axis, h  is the long one)
			int vindx = (oindx == 0)? 1 : 0;
			int hindx = (oindx == 0)? 2 : ((oindx == 1) ? 2 : 1);
			if (eig_val[vindx][vindx] > eig_val[hindx][hindx]){
				int tmp = vindx;
				vindx = hindx;
				hindx = tmp;
			}

			double [][] plane = {
					{eig_vect[0][oindx],eig_vect[1][oindx],eig_vect[2][oindx]},  // plane normal to camera
					{eig_vect[0][vindx],eig_vect[1][vindx],eig_vect[2][vindx]},  // "horizontal" axis // to detect skinny planes and poles
					{eig_vect[0][hindx],eig_vect[1][hindx],eig_vect[2][hindx]}}; //  "vertical"   axis  // to detect skinny planes and poles
			// Make normal be towards camera (positive disparity), next vector - positive in X direction (right)
			for (int v = 0; v < 2; v++) {
				if (plane[v][v] < 0.0) for (int i = 0; i < 3; i ++) plane[v][i] = -plane[v][i];
			}
3737

3738
			// make  direction last vector so px (x) py (.) disp < 0 (left-hand coordinate system)
3739 3740 3741
			if (new Matrix(plane).det() > 0){
				for (int i = 0; i < 3; i ++) plane[2][i] = -plane[2][i];
			}
3742 3743


3744
			PlaneData pd = this.clone(); // will copy selections too
Andrey Filippov's avatar
Andrey Filippov committed
3745
			pd.invalidateCalculated();   // real world vectors
3746 3747
			pd.setValues(eig_val[oindx][oindx],eig_val[vindx][vindx],eig_val[hindx][hindx]); // eigenvalues [0] - thickness, 2 other to detect skinny (poles)
			pd.setVectors(plane);
3748

3749 3750 3751
			pd.setZxy(common_center.getColumnPackedCopy()); // set new center
			// what weight to use? cloned is original weight for this supertile
			// or use weighted average like below?
3752 3753
			double new_weight;
			if (sum_weights) {
3754
				new_weight = sum_weight; // normalize while averaging by the caller
3755 3756 3757 3758 3759 3760 3761
			} else { // how it was before
				new_weight = other_fraction * other_weight + (1.0 - other_fraction) * this_weight;
			}
			if (!ignore_weights && ((starWeightPwr != 1.0))){
				new_weight = Math.pow(new_weight,1.0/starWeightPwr);
			}
			pd.setWeight(new_weight);
3762 3763
			pd.setNumPoints(otherPd.getNumPoints()+this.getNumPoints());
			// Repeat merging for world-based planes
3764
			return mergePlaneToThisWorld(
3765
					otherPd, // PlaneData otherPd,
3766
					pd,      // PlaneData pd_partial, // disparity-based data is already merged
3767 3768 3769 3770 3771 3772
					scale_other,
					starWeightPwr,    // Use this power of tile weight when calculating connection cost
					ignore_weights,
					sum_weights,
					preferDisparity, // Always start with disparity-most axis (false - lowest eigenvalue)
					debugLevel);
3773
//			return pd;
3774
		}
3775

3776 3777 3778 3779

		// only handles wxyz, wvalues,wvectors - the rest should be done with mergePlaneToThis()
		private PlaneData mergePlaneToThisWorld(
				PlaneData otherPd,
3780
				PlaneData pd_partial, // disparity-based data is already merged
3781 3782 3783 3784 3785 3786 3787
				double    scale_other,
				double    starWeightPwr,    // Use this power of tile weight when calculating connection cost
				boolean   ignore_weights,
				boolean   sum_weights,
				boolean   preferDisparity, // Always start with disparity-most axis (false - lowest eigenvalue)
				int       debugLevel)
		{
3788
			if (debugLevel > 1) {
3789 3790
				System.out.println("mergePlaneToThisWorld()");
			}
3791
			if (wvalues == null ) {
3792 3793 3794
				if (debugLevel > -2) {
					System.out.println("mergePlaneToThisWorld(): wvalues=null:\n"+toString());
				}
3795
				return null;
3796

3797 3798
			}
			if (otherPd.wvalues == null ) {
3799
				if (debugLevel > -1) System.out.println("mergePlaneToThisWorld(): otherPd.wvalues=null:\n"+otherPd.toString());
3800 3801
				return null;
			}
3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812
			double [][] this_eig_avals = {
					{wvalues[0], 0.0,        0.0},
					{0.0,        wvalues[1], 0.0},
					{0.0,        0.0,        wvalues[2]}};
			double [][] other_eig_avals = {
					{otherPd.wvalues[0], 0.0,                0.0},
					{0.0,                otherPd.wvalues[1], 0.0},
					{0.0,                0.0,                otherPd.wvalues[2]}};
			Matrix this_eig_vals =     new Matrix(this_eig_avals);
			Matrix other_eig_vals =    new Matrix(other_eig_avals);
			Matrix other_eig_vectors = new Matrix(otherPd.wvectors).transpose(); // vectors are saved as rows
3813
			Matrix this_eig_vectors =  new Matrix(this.wvectors).transpose();    // vectors are saved as rows
3814 3815 3816 3817 3818 3819 3820 3821 3822 3823
			Matrix this_center    =    new Matrix(this.getWxyz(),3);
			Matrix other_center    =   new Matrix(otherPd.getWxyz(),3); // should already be relative to this supertile center
			double this_weight = this.weight;
			double other_weight = otherPd.weight;
			if (starWeightPwr == 0){
				ignore_weights = true;
			} else if (starWeightPwr != 1.0){
				this_weight =  Math.pow(this_weight, starWeightPwr);
				other_weight = Math.pow(other_weight,starWeightPwr);
			}
3824

3825
			double sum_weight =      scale_other *  other_weight + this_weight;// should be the same for
3826
			double other_fraction = ignore_weights? (scale_other/(scale_other + 1.0)): ((scale_other *  other_weight) / sum_weight);
3827 3828 3829 3830 3831 3832
			Matrix common_center =  this_center.times(1.0 - other_fraction).plus(other_center.times(other_fraction));
			Matrix other_offset =   other_center.minus(this_center); // other center from this center
			if ((this.values[0] == 0.0) || (otherPd.values[0] == 0.0)) {
				System.out.println("Zero eigenvalue");
				debugLevel = 10;
			}
3833
			if (debugLevel > 1) {
3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857
				System.out.println("other_eig_vals");
				other_eig_vals.print(8, 6);
				System.out.println("this_eig_vals");
				this_eig_vals.print(8, 6);
				System.out.println("other_eig_vectors");
				other_eig_vectors.print(8, 6);
				System.out.println("this_eig_vectors");
				this_eig_vectors.print(8, 6);
				System.out.println("other_center");
				other_center.print(8, 6);
				System.out.println("this_center");
				this_center.print(8, 6);
				System.out.println("common_center");
				common_center.print(8, 6);
				System.out.println("other_offset");
				other_offset.print(8, 6);
				System.out.println("other_fraction="+other_fraction);
			}

			double [][] acovar = { // covariance matrix of center masses (not yet scaled by weight)
					{other_offset.get(0,0)*other_offset.get(0,0), other_offset.get(0,0)*other_offset.get(1,0), other_offset.get(0,0)*other_offset.get(2,0)},
					{other_offset.get(1,0)*other_offset.get(0,0), other_offset.get(1,0)*other_offset.get(1,0), other_offset.get(1,0)*other_offset.get(2,0)},
					{other_offset.get(2,0)*other_offset.get(0,0), other_offset.get(2,0)*other_offset.get(1,0), other_offset.get(2,0)*other_offset.get(2,0)}};

3858
			Matrix other_covar = other_eig_vectors.times(other_eig_vals.times(other_eig_vectors.transpose()));
3859 3860
			Matrix this_covar =  this_eig_vectors.times(this_eig_vals.times(this_eig_vectors.transpose()));
			Matrix covar = (new Matrix(acovar)).times(other_fraction*(1.0-other_fraction)); // only centers with all masses
3861
			if (debugLevel > 1) {
3862 3863 3864 3865 3866 3867
				System.out.println("other_covar");
				other_covar.print(8, 6);
				System.out.println("this_covar");
				this_covar.print(8, 6);
				System.out.println("covar");
				covar.print(8, 6);
3868
			}
3869 3870

			covar.plusEquals(other_covar.times(other_fraction));
3871
			if (debugLevel > 1) {
3872 3873 3874 3875
				System.out.println("covar with other_covar");
				covar.print(8, 6);
			}
			covar.plusEquals(this_covar.times(1.0 - other_fraction));
3876
			if (debugLevel > 1) {
3877 3878 3879 3880
				System.out.println("covar with other_covar and this_covar");
				covar.print(8, 6);
			}
			if (Double.isNaN(covar.get(0, 0))){
3881
				System.out.println("covar is NaN 2!");
3882
				covar.print(8, 6);
3883
				return null;
3884 3885 3886 3887 3888
			}
			// extract new eigenvalues, eigenvectors
			EigenvalueDecomposition eig = covar.eig(); // verify NaN - it gets stuck
			//			eig.getD().getArray(),
			//			eig.getV().getArray(),
3889
			if (debugLevel > 1) {
3890 3891 3892 3893 3894 3895 3896 3897 3898 3899
				System.out.println("eig.getV()");
				eig.getV().print(8, 6);
				System.out.println("eig.getD()");
				eig.getD().print(8, 6);
			}



			double [][] eig_vect = eig.getV().getArray();
			double [][] eig_val = eig.getD().getArray();
3900

3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921
			// probably this reordering is not needed as they are already ordered
			// for world coordinates the sequence is normal x,y,z (not d,x,y)
			int oindx = 0;
			for (int i = 1; i <3; i++){
				if (eig_val[i][i] < eig_val[oindx][oindx]){
					oindx = i;
				}
			}
			// select 2 other axes for increasing eigenvalues (so v is short axis, h  is the long one)
			int vindx = (oindx == 0)? 1 : 0;
			int hindx = (oindx == 0)? 2 : ((oindx == 1) ? 2 : 1);
			if (eig_val[vindx][vindx] > eig_val[hindx][hindx]){
				int tmp = vindx;
				vindx = hindx;
				hindx = tmp;
			}

			double [][] plane = {
					{eig_vect[0][oindx],eig_vect[1][oindx],eig_vect[2][oindx]},  // plane normal to camera
					{eig_vect[0][vindx],eig_vect[1][vindx],eig_vect[2][vindx]},  // "horizontal" axis // to detect skinny planes and poles
					{eig_vect[0][hindx],eig_vect[1][hindx],eig_vect[2][hindx]}}; //  "vertical"   axis  // to detect skinny planes and poles
3922

3923 3924
			// make towards camera, left coordinate system

3925

3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936
			// Make normal be towards camera (positive disparity), next vector - positive in X direction (right)
			double from = 0.0; // see if the first vector ("plane" normal) is away from the camera
			for (int i = 0; i < 3; i++) {
				from += this.wxyz[i]*plane[0][i];
			}
			if (from > 0.0){ // reverse the first vector to be towards the camera
				for (int i = 0; i < 3; i++) {
					plane[0][i] = -plane[0][i];
				}
			}

3937
			// make  direction last vector so px (x) py (.) disp < 0 (left-hand coordinate system)
3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950
			if (new Matrix(plane).det() > 0){
				for (int i = 0; i < 3; i ++) plane[2][i] = -plane[2][i];
			}

			pd_partial.setWValues(eig_val[oindx][oindx],eig_val[vindx][vindx],eig_val[hindx][hindx]); // eigenvalues [0] - thickness, 2 other to detect skinny (poles)
			pd_partial.setWVectors(plane);

			pd_partial.setWxyz(common_center.getColumnPackedCopy()); // set new center
			// what weight to use? cloned is original weight for this supertile
			// or use weighted average like below?
			if (debugLevel < -1000) { // already done in mergePlaneToThis() that call this method
				double new_weight;
				if (sum_weights) {
3951
					new_weight = sum_weight; // normalize while averaging by the caller
3952 3953 3954 3955 3956 3957 3958 3959
				} else { // how it was before
					new_weight = other_fraction * other_weight + (1.0 - other_fraction) * this_weight;
				}
				if (!ignore_weights && ((starWeightPwr != 1.0))){
					new_weight = Math.pow(new_weight,1.0/starWeightPwr);
				}
				pd_partial.setWeight(new_weight);
			}
3960 3961 3962 3963 3964
			if (debugLevel > 2) {
				double L1 = getWValue();
				double L2 = otherPd.getWValue();
				double W1 = 1.0 - other_fraction;
				double W2 = other_fraction;
3965
				double Lav = (L1*W1 + L2*W2)/(W1+W2);
3966 3967 3968 3969 3970 3971 3972
				double L = pd_partial.getWValue();
				if ((L*1.000001 < Lav) || (debugLevel > 0)){
					System.out.println("========== mergePlaneToThisWorld(): L1="+L1+", L2 = "+L2+", W1="+W1+", W2="+W2+", Lav = "+Lav+", L="+L+
							", L-Lav="+(L-Lav)+", scale_other="+scale_other+", other_fraction="+other_fraction);
					System.out.println();
				}
			}
3973

3974 3975
			return pd_partial;
		}
3976 3977 3978 3979




3980 3981 3982 3983 3984 3985
		/**
		 * Convert plane data from other supertile to this one (disparity, px, py) for the center of this supertile
		 * through the plane in world coordinates. orientation of the "main" eigenvector (most disparity-like) is
		 * calculated, two other axes preserve just px/py ratio.
		 * Transformed center is calculated for original px, py of the center and recalculated plane to get disparity value
		 * The converted plane data can be combined with the current one to get plane data for combined tiles.
3986
		 * Converted disparity is not limited to positive values.
3987
		 * @param otherPd other supertile plane data (will not be modified)
3988
		 * @return plane data converted to local supertile disparity, px, py (center and eigenvectors)
3989 3990 3991 3992 3993
		 */
		public PlaneData getPlaneToThis(
				PlaneData otherPd,
				int       debugLevel)
		{
Andrey Filippov's avatar
Andrey Filippov committed
3994 3995
			PlaneData pd = otherPd.clone(); // TODO: use clone of this, copy only needed info from otherPD
			// keep world vectors from otherPd
3996 3997 3998
			if (debugLevel > 0) {
				System.out.println("getPlaneToThis()");
			}
3999

4000 4001 4002 4003 4004
			double [] px_py = getCenterPxPy(); // this supertile center
			double [] px_py_other = pd.getCenterPxPy(); // other supertile center
			double [] wv1 = otherPd.getWorldV12( // 1-st in-plane vector will calculate, but that will not be used below?
					false, // false - first, true - second vector
					this.correctDistortions);
4005

4006 4007 4008 4009 4010 4011 4012 4013
			double [] wv2 = otherPd.getWorldV12( // 2-nd in-plane vector
					true, // false - first, true - second vector
					this.correctDistortions);
			double disp = geometryCorrection.getPlaneDisparity( // disparity (at this center) for crossing other supertile plane
					pd.getWorldXYZ(this.correctDistortions), // will calculate if not yet done so. Should it use otherPd, not pd? and then clone later?
					px_py[0],
					px_py[1],
					this.correctDistortions);
4014 4015 4016 4017
			if (Double.isNaN(disp)) {
				System.out.println("getPlaneToThis(), px_py = {"+px_py[0]+", "+px_py[1]+"}, px_py_other = {"+px_py_other[0]+", "+px_py_other[1]+"}");
				System.out.println("getPlaneToThis(), disp = "+disp);
				System.out.println("getPlaneToThis(), pd="+ pd.toString());
4018
//				System.out.println("getPlaneToThis(), otherPd="+ otherPd.toString());
4019 4020 4021
//				System.out.println("getPlaneToThis(), pd.getWorldXYZ(this.correctDistortions)="+ pd.getWorldXYZ(this.correctDistortions));
//				System.out.println("getPlaneToThis(), wv1 = {"+ wv1[0]+", "+ wv1[1]+", "+ wv1[2]+"}");
//				System.out.println("getPlaneToThis(), wv2 = {"+ wv2[0]+", "+ wv2[1]+", "+ wv2[2]+"}");
4022
				double [] norm_xyz = pd.getWorldXYZ(this.correctDistortions);
4023
//				System.out.println("getPlaneToThis(),norm_xyz="+ norm_xyz);
4024 4025 4026 4027 4028 4029 4030
				disp = geometryCorrection.getPlaneDisparity( // disparity (at this center) for crossing other supertile plane
						norm_xyz, // will calculate if not yet done so. Should it use otherPd, not pd? and then clone later?
						px_py[0],
						px_py[1],
						this.correctDistortions);

			}
4031 4032 4033 4034 4035 4036
			if (debugLevel > 0) {
				System.out.println("getPlaneToThis(), px_py = {"+px_py[0]+", "+px_py[1]+"}, px_py_other = {"+px_py_other[0]+", "+px_py_other[1]+"}");
				System.out.println("getPlaneToThis(), disp = "+disp);
				System.out.println("getPlaneToThis(), wv1 = {"+ wv1[0]+", "+ wv1[1]+", "+ wv1[2]+"}");
				System.out.println("getPlaneToThis(), wv2 = {"+ wv2[0]+", "+ wv2[1]+", "+ wv2[2]+"}");
			}
4037

4038 4039 4040 4041 4042 4043 4044 4045 4046 4047
			// find world coodinates of the center of tile intersection with the plane
			Matrix xyz = new Matrix(geometryCorrection.getWorldCoordinates(
						px_py[0],
						px_py[1],
						disp,
						this.correctDistortions),3);
			if (debugLevel > 0) {
				System.out.println("getPlaneToThis(), Matrix xyz=");
				xyz.print(10,6);
			}
4048 4049

			// Jacobian to convert world vectors to
4050 4051 4052 4053
			Matrix img_jacobian =  new Matrix(geometryCorrection.getImageJacobian(
					xyz.getColumnPackedCopy(),
					this.correctDistortions,
					1)); // debug_level
4054

4055 4056 4057 4058
			if (debugLevel > 0) {
				System.out.println("getPlaneToThis(), Matrix img_jacobian=");
				img_jacobian.print(10,6);
			}
4059 4060


4061 4062 4063
			// now get both in-plane vectors transformed to this supertile disparity, px, py
			Matrix v1 = img_jacobian.times(new Matrix(wv1,3)); // 3 rows, 1 column
			Matrix v2 = img_jacobian.times(new Matrix(wv2,3)); // 3 rows, 1 column
4064 4065
//			Matrix v0 = cross3d(v1,v2); // orthogonal to both - this is a plane normal vector in local supertile disparity, px. py
			Matrix v0 = cross3d(v2,v1); // orthogonal to both - this is a plane normal vector in local supertile disparity, px. py
4066

4067 4068


4069 4070 4071 4072 4073 4074 4075 4076
			if (debugLevel > 0) {
				System.out.println("getPlaneToThis(), Matrix v0 =");
				v0.print(10,6);
				System.out.println("getPlaneToThis(), Matrix v1 =");
				v1.print(10,6);
				System.out.println("getPlaneToThis(), Matrix v2 =");
				v2.print(10,6);
			}
4077 4078 4079


			// normalize v0, update v1, v2 to be orthonormal with v0
4080 4081 4082 4083 4084 4085
			v0.timesEquals(1.0/v0.normF()); // unity vector;
			v1.minusEquals(v0.times(v0.transpose().times(v1)));
			v1.timesEquals(1.0/v1.normF()); // unity vector;
			v2.minusEquals(v0.times(v0.transpose().times(v2)));
			v2.minusEquals(v1.times(v1.transpose().times(v2)));
			v2.timesEquals(1.0/v2.normF()); // unity vector;
4086

4087 4088 4089 4090 4091 4092 4093 4094
			if (debugLevel > 0) {
				System.out.println("getPlaneToThis(), ortho-normalized Matrix v0 =");
				v0.print(10,6);
				System.out.println("getPlaneToThis(), ortho-normalized Matrix v1 =");
				v1.print(10,6);
				System.out.println("getPlaneToThis(), ortho-normalized Matrix v2 =");
				v2.print(10,6);
			}
4095 4096


4097 4098 4099
			pd.vectors[0] = v0.getColumnPackedCopy();
			pd.vectors[1] = v1.getColumnPackedCopy();
			pd.vectors[2] = v2.getColumnPackedCopy();
4100

4101 4102 4103 4104 4105
			if (debugLevel > 0) {
				System.out.println("getPlaneToThis(), pd.vectors[0] = {"+ pd.vectors[0][0]+", "+ pd.vectors[0][1]+", "+ pd.vectors[0][2]+"}");
				System.out.println("getPlaneToThis(), pd.vectors[1] = {"+ pd.vectors[1][0]+", "+ pd.vectors[1][1]+", "+ pd.vectors[1][2]+"}");
				System.out.println("getPlaneToThis(), pd.vectors[2] = {"+ pd.vectors[2][0]+", "+ pd.vectors[2][1]+", "+ pd.vectors[2][2]+"}");
			}
4106 4107


4108 4109 4110 4111 4112
//			double [] dxy = otherPd.getZxy(); // {disparity, px, py}  px, py in pixels, relative to the other supertile center
			double [] dxy = pd.getZxy(); // {disparity, px, py}  px, py in pixels, relative to the other supertile center
			if (debugLevel > 0) {
				System.out.println("getPlaneToThis(), otherPd.getZxy() = {"+ dxy[0]+", "+ dxy[1]+", "+ dxy[2]+"}");
			}
4113 4114 4115



4116 4117 4118 4119
			dxy[1] += px_py_other[0] - px_py[0]; // relative to this tile
			dxy[2] += px_py_other[1] - px_py[1]; // relative to this tile
// find center of plane segment - get intersection of the plane orthogonal to v0 through the point px_py to the point pd.
			dxy[0] = disp - (pd.vectors[0][1]*dxy[1] + pd.vectors[0][2]*dxy[2]) / pd.vectors[0][0];
4120
			if (debugLevel > 0) {
4121 4122
				System.out.println("getPlaneToThis(), dxy(modified) = {"+ dxy[0]+", "+ dxy[1]+", "+ dxy[2]+"}");
			}
4123
			pd.sTileXY = this.sTileXY;
4124 4125 4126 4127 4128 4129 4130
			if (pd.vectors[0][0] > 0) {
//				System.out.println("getPlaneToThis(): "+pd.sTileXY[0]+":"+pd.sTileXY[1]+" -> "+pd.vectors[0][0]+", disp = "+disp+
//						", other_det = "+((new Matrix(otherPd.vectors).det()) +", pdr_det = "+((new Matrix(pd.vectors).det()))));
			} else {
//				System.out.println("getPlaneToThis(): "+pd.sTileXY[0]+":"+pd.sTileXY[1]+" -> "+pd.vectors[0][0]+", disp = "+disp+
//						", other_det = "+((new Matrix(otherPd.vectors).det()) +", pdr_det = "+((new Matrix(pd.vectors).det()))));
			}
Andrey Filippov's avatar
Andrey Filippov committed
4131
			copyNeib(this, pd);
4132 4133
			pd.num_points = otherPd.num_points; // restore, maybe remove from copy_neib?
// copy other data from this tile
4134 4135 4136 4137
			pd.setMeasSelection(this.measuredSelection);
			if (this.measuredLayers != null) pd.measuredLayers = this.measuredLayers;
			if (this.sel_mask != null)       pd.sel_mask = this.sel_mask.clone();
			copyStar(this,pd);
4138
			return pd; // make sure pd are updated // "this" is not used. Should it be used instead of pd?
4139
		}
4140 4141


4142 4143 4144 4145 4146 4147
		public double [] getWorldV12(
				boolean v2, // false - first, true - second vector
				boolean correct_distortions)
		{
			return getWorldV12(v2, correct_distortions,0);
		}
4148

4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169
		public double [] getWorldV12(
				boolean v2, // false - first, true - second vector
				boolean correct_distortions,
				int debugLevel)
		{
			if (v2) {
				if (world_v2 == null){
					getWorldXYZ(
							correct_distortions,
							debugLevel);
				}
				return world_v2;
			} else {
				if (world_v1 == null){
					getWorldXYZ(
							correct_distortions,
							debugLevel);
				}
				return world_v1;
			}
		}
4170

4171 4172 4173 4174 4175
		//this.correctDistortions
		public double [] getCenterXYZ(
				int debugLevel){
			return getCenterXYZ(this.correctDistortions, debugLevel);
		}
4176

4177 4178 4179 4180
		public double [] getCenterXYZ(
				boolean correct_distortions,
				int debugLevel)
		{
4181
//			double delta = 0.0001;
4182 4183 4184 4185
			if (center_xyz != null) return center_xyz;
			setCorrectDistortions(correct_distortions);
			// get pixel coordinates of the plane origin point
			double [] px_py = getCenterPxPy();
4186

4187 4188 4189 4190 4191 4192 4193 4194 4195 4196
			double px = px_py[0] + zxy[1];
			double py = px_py[1] + zxy[2];
			double disp =  zxy[0];
			center_xyz = geometryCorrection.getWorldCoordinates(
					px,
					py,
					disp,
					this.correctDistortions);
			return center_xyz;
		}
4197

4198 4199 4200 4201
		public double [] getWorldXYZ(
				int debugLevel){
			return getWorldXYZ(this.correctDistortions, debugLevel);
		}
4202
		/**
4203
		 * Get vector from the camera perpendicular to the plane converted to the real world
4204 4205 4206 4207
		 * @param correct_distortions
		 * @param debugLevel
		 * @return
		 */
4208

Andrey Filippov's avatar
Andrey Filippov committed
4209 4210 4211 4212 4213
		public double [] getWorldXYZ(
				boolean correct_distortions,
				int debugLevel)
		{
			double delta = 0.0001;
4214 4215 4216 4217
			// debugging:
			if (world_xyz != null) {
				double l2 = world_xyz[0]*world_xyz[0] + world_xyz[1]*world_xyz[1]+world_xyz[2]*world_xyz[2];
				if (l2 < 0.5) {
4218
					if (debugLevel > 0) { // -1
4219 4220
						System.out.println("getWorldXYZ(): l2="+l2); // +" this=\n"+this.toString());
					}
4221 4222 4223 4224
					world_xyz = null;
				}
			}

Andrey Filippov's avatar
Andrey Filippov committed
4225 4226 4227
			if (world_xyz != null) return world_xyz;
			setCorrectDistortions(correct_distortions);
			// get pixel coordinates of the plane origin point
4228 4229 4230
			double [] px_py = getCenterPxPy();
			double px = px_py[0] + zxy[1];
			double py = px_py[1] + zxy[2];
Andrey Filippov's avatar
Andrey Filippov committed
4231
			double disp =  zxy[0];
4232
			center_xyz = geometryCorrection.getWorldCoordinates(
Andrey Filippov's avatar
Andrey Filippov committed
4233 4234 4235
					px,
					py,
					disp,
4236 4237
					this.correctDistortions);
			Matrix xyz = new Matrix(center_xyz, 3); // column matrix
Andrey Filippov's avatar
Andrey Filippov committed
4238 4239 4240
			Matrix dpxpy = new Matrix(vectors[0],3); // 3 rows, 1 column
			if (debugLevel > 0){
				System.out.println("getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"), correctDistortions="+correctDistortions+", xyz= {"+
4241
						xyz.get(0, 0)+","+xyz.get(1, 0)+","+xyz.get(2, 0)+"}, weight = "+getWeight());
4242

Andrey Filippov's avatar
Andrey Filippov committed
4243
				System.out.println("getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"): disp, px, py="+disp+","+px+","+py); // + ", reversed:"+dpxpy[0]+","+dpxpy[1]+","+dpxpy[2]);
4244

Andrey Filippov's avatar
Andrey Filippov committed
4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261
				Matrix xyz1 = new Matrix(geometryCorrection.getWorldCoordinates(
						px + delta * dpxpy.get(1, 0),
						py + delta * dpxpy.get(2, 0),
						disp + delta * dpxpy.get(0, 0),
						this.correctDistortions),3); // column matrix
				System.out.println("getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+") delta diff: {"+
						((xyz1.get(0, 0)- xyz.get(0, 0))/delta)+","+
						((xyz1.get(1, 0)- xyz.get(1, 0))/delta)+","+
						((xyz1.get(2, 0)- xyz.get(2, 0))/delta)+"}");
			}
			Matrix jacobian =  new Matrix(geometryCorrection.getWorldJacobian(
					px,
					py,
					disp,
					this.correctDistortions,
					(debugLevel > 2)
					));
4262

Andrey Filippov's avatar
Andrey Filippov committed
4263 4264 4265
			// convert both orthogonal axes, normalize their cross product
			Matrix v1 = jacobian.times(new Matrix(vectors[1],3)); // 3 rows, 1 column
			Matrix v2 = jacobian.times(new Matrix(vectors[2],3)); // 3 rows, 1 column
4266

4267 4268
			world_v1 = v1.getColumnPackedCopy();
			world_v2 = v2.getColumnPackedCopy();
4269

Andrey Filippov's avatar
Andrey Filippov committed
4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295
			Matrix norm_xyz =  cross3d(v1,v2);
			if (debugLevel > 0){
				System.out.println("getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"): norm_xyz={"+
						norm_xyz.get(0, 0)+", "+norm_xyz.get(1, 0)+", "+norm_xyz.get(2, 0)+"}, (dpxpy={"+
						dpxpy.get(0, 0)+   ", "+dpxpy.get(1, 0)+   ", "+dpxpy.get(2, 0)+"})");
			}
			if (debugLevel > 2){
				System.out.println("getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"): dpxpy=");
				dpxpy.print(10, 6); // w,d
				System.out.println("getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"): jacobian=");
				jacobian.print(10, 6); // w,d
			}
			if (debugLevel > 2){
				System.out.println("getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"): norm_xyz=");
				norm_xyz.print(10, 6); // w,d
			}
			if (debugLevel > 2){
				System.out.println("getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"): image jacobian=");
				Matrix img_jacobian =  new Matrix(geometryCorrection.getImageJacobian(
						xyz.getColumnPackedCopy(),
						this.correctDistortions,
						1));
				img_jacobian.print(10, 6); // w,d
				System.out.println("getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"): jacobian.times(image_jacobian)=");
				jacobian.times(img_jacobian).print(10, 6); // w,d
			}
4296

4297
			norm_xyz.timesEquals(1.0/norm_xyz.normF()); // unity normal vector;
Andrey Filippov's avatar
Andrey Filippov committed
4298
			if (debugLevel > 1){
Andrey Filippov's avatar
Andrey Filippov committed
4299 4300
				System.out.println("+getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"): unit plane normal={"+
						norm_xyz.get(0, 0)+", "+norm_xyz.get(1, 0)+", "+norm_xyz.get(2, 0)+"})");
4301 4302 4303 4304 4305
				double dotprod = xyz.transpose().times(norm_xyz).get(0,0);
				Matrix wn = norm_xyz.times(dotprod);
				System.out.println(":getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"): xyz.transpose().times(norm_xyz).get(0,0) ="+dotprod);
				System.out.println("?getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"):  plane normal={"+
						wn.get(0, 0)+", "+wn.get(1, 0)+", "+wn.get(2, 0)+"})");
Andrey Filippov's avatar
Andrey Filippov committed
4306
			}
4307 4308


Andrey Filippov's avatar
Andrey Filippov committed
4309 4310 4311 4312 4313
			if (debugLevel > 2){
				System.out.println("getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"): norm_xyz (normalized) =");
				norm_xyz.print(10, 6); // w,d
				System.out.println("getWorldXYZ("+sTileXY[0]+","+sTileXY[1]+"): xyz.times(norm_xyz.transpose()).get(0,0) ="+xyz.times(norm_xyz.transpose()).get(0,0));
			}
4314

Andrey Filippov's avatar
Andrey Filippov committed
4315 4316
			// convert plane normal vector to world coordinates
			//world_xyz
4317
			world_xyz = norm_xyz.times((xyz.transpose().times(norm_xyz).get(0,0))).getColumnPackedCopy();
4318 4319
			double l2 = world_xyz[0]*world_xyz[0] + world_xyz[1]*world_xyz[1]+world_xyz[2]*world_xyz[2];
			if (l2 < 0.5) {
4320
				if (debugLevel > 0) { // -1
4321 4322
					System.out.println("getWorldXYZ(): l2="+l2); // +" this=\n"+this.toString());
				}
4323
			}
Andrey Filippov's avatar
Andrey Filippov committed
4324 4325
			return world_xyz;
		}
4326

4327
		public ArrayList<PlaneData> createTilePlanesFromSelections(
Andrey Filippov's avatar
Andrey Filippov committed
4328 4329
				String        suffix,
				boolean [][][] plane_selections, //  = new boolean [nStiles][][][]; // num_tiles
4330
				boolean []     hor_planes,
4331
				double  [][][] disp_strength,
Andrey Filippov's avatar
Andrey Filippov committed
4332 4333 4334 4335 4336 4337 4338
				double       dispNorm,   //  Normalize disparities to the average if above
				int          min_tiles,
				double       plTargetEigen, //        =   0.1;  // Remove outliers until main axis eigenvalue (possibly scaled by plDispNorm) gets below
				double       plFractOutliers, //      =   0.3;  // Maximal fraction of outliers to remove
				int          plMaxOutliers, //        =    20;  // Maximal number of outliers to remove
				boolean      correct_distortions,
				boolean      smplMode, //        = true;   // Use sample mode (false - regular tile mode)
4339
				MeasuredLayersFilterParameters mlfp,
4340 4341 4342
				double       fronto_tol, // fronto tolerance (pix) - treat almost fronto as fronto (constant disparity). <= 0 - disable this feature
				double       fronto_rms,  // Target rms for the fronto planes - same as sqrt(plMaxEigen) for other planes. May be tighter
				double       fronto_offs,   //        =   0.2;  // increasing weight of the near tiles by using difference between the reduced average as weight. <= 0 - disable
4343
				double       fronto_pow,    //        =   1.0;  // increase weight even more
Andrey Filippov's avatar
Andrey Filippov committed
4344 4345
				int          debugLevel)
		{
4346 4347 4348
			if (debugLevel > 2) {
				debugLevel += 0; // +=1 // no show all eigen stuff (debugLevel > 3)
			}
4349
			if (debugLevel > 0) {
4350
				System.out.println("createTilePlanesFromSelections(): debugLevel="+debugLevel); // +=1 // no show all eigen stuff (debugLevel > 3)
4351
			}
4352

Andrey Filippov's avatar
Andrey Filippov committed
4353
			// first make a plane from all tiles
4354
			ArrayList<PlaneData> st_planes = new ArrayList<PlaneData>();
4355
			if (debugLevel > 2) {
4356
				ShowDoubleFloatArrays sdfa_instance = new ShowDoubleFloatArrays();
4357 4358 4359 4360 4361 4362 4363 4364 4365 4366
				double [][] dbg_img = new double [plane_selections.length][];
				for (int ps = 0; ps < plane_selections.length; ps++) {
					dbg_img[ps] = new double [plane_selections[ps][0].length];
					for (int i = 0; i < dbg_img[ps].length; i++) {
						dbg_img[ps][i] = plane_selections[ps][0][i]? 1.0: 0.0;
					}
				}
				sdfa_instance.showArrays(dbg_img,  stSize * 2, stSize * 2, true, "selections_x"+sTileXY[0]+"_y"+sTileXY[1]+"-"+suffix);
			}

4367

Andrey Filippov's avatar
Andrey Filippov committed
4368 4369
			// iterate through all plane selections
			for (int ps = 0; ps < plane_selections.length; ps++) {
4370
				PlaneData pd = this.clone();
Andrey Filippov's avatar
Andrey Filippov committed
4371 4372 4373 4374 4375 4376 4377 4378 4379
				boolean OK = (pd.getPlaneFromMeas(
						plane_selections[ps], // tile_sel,       // boolean [][] tile_sel, // null - do not use, {} use all (will be modified)
						disp_strength,
						Double.NaN,    // double       disp_far, // minimal disparity to select (or NaN)
						Double.NaN,    // double       disp_near, // maximal disparity to select (or NaN)
						dispNorm,    // 0.0,            // plDispNorm,  // double       dispNorm,   //  Normalize disparities to the average if above
						0.0,            // double       min_weight,
						min_tiles,    // int          min_tiles,
						smplMode,
4380
						mlfp,
Andrey Filippov's avatar
Andrey Filippov committed
4381 4382 4383 4384 4385
						debugLevel) != null);            // int          debugLevel)
				if (OK) {
					if (debugLevel > 0) {
						if (pd.getWeight() > 1.0) {
							System.out.println("Processing subplane "+ suffix+
4386
									(((hor_planes == null) || !hor_planes[ps])?"(horizontal) ":"(vertical) ")+
Andrey Filippov's avatar
Andrey Filippov committed
4387 4388 4389 4390 4391 4392 4393
									", numPoints="+ pd.getNumPoints()+
									", swc = "+pd.getWeight()+
									", center=["+pd.getZxy()[0]+","+pd.getZxy()[1]+","+pd.getZxy()[2]+"]"+
									", eig_val = {"+pd.getValues()[0]+","+pd.getValues()[1]+","+pd.getValues()[2]+"}"+
									", eig_vect[0] = {"+pd.getVector()[0]+","+pd.getVector()[1]+","+pd.getVector()[2]+"}");
						}
					}
4394 4395

//					double targetV = plTargetEigen;
4396

4397
					/* Does it needs to be twice?
Andrey Filippov's avatar
Andrey Filippov committed
4398
					double z0 = pd.getZxy()[0];
4399
					if ((dispNorm > 0.0) && (z0 > dispNorm)) { // not needed ?
Andrey Filippov's avatar
Andrey Filippov committed
4400 4401 4402
						double dd = (dispNorm + z0)/ dispNorm; // > 1
						targetV *= dd * dd; // > original
					}
4403
					*/
4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430
					if ((hor_planes != null) && hor_planes[ps]) {
						pd.horizontal = true;
					}
					boolean almost_fronto = pd.isFronto(
							fronto_tol,    // double fronto_tol,
							disp_strength,      // double [][][] disp_str,
							debugLevel);   // int debugLevel);
					double targetEigen = almost_fronto ? (fronto_rms*fronto_rms): plTargetEigen;
					// now try to remove outliers
					// FIXME: temporary - make a configurable parameter
					double fronto_fract_outliers = 0.8; // 2 * inFractOutliers;
					double fractOutliers = almost_fronto ? (fronto_fract_outliers) : plFractOutliers;

					int max_outliers = (int) Math.round(pd.getNumPoints() * fractOutliers); // plFractOutliers);
					if (max_outliers > plMaxOutliers) max_outliers = plMaxOutliers;
					// in fronto mode - run at least once
//					if ((this_pd.getNormValue() > targetEigen) || almost_fronto) { // targetV) {
					if (almost_fronto) {
						pd.growFrontoSelection(
								5, // 4,              // int           min_neib,
								0.1,            // double        max_over_avg,
								0.00,           // double        max_under_avg,
								disp_strength); // double [][][] disp_str)
					}


					if ((pd.getNormValue() > targetEigen) || almost_fronto) { // targetV) {
Andrey Filippov's avatar
Andrey Filippov committed
4431
						OK = pd.removeOutliers( // getPlaneFromMeas should already have run
4432 4433 4434 4435
								fronto_tol,     // double        fronto_tol, // fronto tolerance (pix) - treat almost fronto as fronto (constant disparity). <= 0 - disable this feature
								fronto_rms,     // double        fronto_rms,  // Target rms for the fronto planes - same as sqrt(plMaxEigen) for other planes. May be tighter
								fronto_offs,    //double        fronto_offs,   //        =   0.2;  // increasing weight of the near tiles by using difference between the reduced average as weight. <= 0 - disable
								fronto_pow,     // double       fronto_pow,    //        =   1.0;  // increase weight even more
4436
								disp_strength,
4437 4438 4439
								plTargetEigen,  // targetV,      // double     targetEigen, // target eigenvalue for primary axis (is disparity-dependent, so is non-constant)
								max_outliers,   // int        maxRemoved,  // maximal number of tiles to remove (not a constant)
								debugLevel);    // int        debugLevel)
Andrey Filippov's avatar
Andrey Filippov committed
4440 4441 4442 4443
						if (!OK) {
							continue;
						}
						if (debugLevel > 0) {
4444
							if (pd.getWeight() > 0.0) { // 1.0) {
Andrey Filippov's avatar
Andrey Filippov committed
4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461
								System.out.println("Removed outliers "+ suffix +
										", numPoints="+ pd.getNumPoints()+
										", swc = "+pd.getWeight()+
										", center=["+pd.getZxy()[0]+","+pd.getZxy()[1]+","+pd.getZxy()[2]+"]"+
										", eig_val = {"+pd.getValues()[0]+","+pd.getValues()[1]+","+pd.getValues()[2]+"}"+
										", eig_vect[0] = {"+pd.getVector()[0]+","+pd.getVector()[1]+","+pd.getVector()[2]+"}");
							}
						}
					}
					double [] norm_xyz = pd.getWorldXYZ(
							correct_distortions);
					st_planes.add(pd);
					if (debugLevel > 0) {
						System.out.println("World normal " + suffix + " = {"+
								norm_xyz[0]+", "+norm_xyz[1]+", "+norm_xyz[2]+"}");

					}
4462
					// calculate the world planes too
4463 4464 4465 4466 4467 4468 4469 4470 4471 4472
					pd.getWorldPlaneFromMeas(
							// use current selection, possibly reduced after removeOutliers()
							null, // plane_selections[ps], // tile_sel,       // boolean [][] tile_sel, // null - do not use, {} use all (will be modified)
							disp_strength,
							Double.NaN,    // double       disp_far, // minimal disparity to select (or NaN)
							Double.NaN,    // double       disp_near, // maximal disparity to select (or NaN)
							dispNorm,      // 0.0,            // plDispNorm,  // double       dispNorm,   //  Normalize disparities to the average if above
							0.0,            // double       min_weight,
							min_tiles,      // int          min_tiles,
							smplMode,
4473
							mlfp,
4474
							debugLevel);
Andrey Filippov's avatar
Andrey Filippov committed
4475 4476 4477 4478
				}
			}
			if (st_planes.size() > 0){
				// sort planes by increasing disparity (tile center or plane center ? ) Using plane center
4479
				Collections.sort(st_planes, new Comparator<PlaneData>() {
Andrey Filippov's avatar
Andrey Filippov committed
4480
					@Override
4481
					public int compare(PlaneData lhs, PlaneData rhs) {
Andrey Filippov's avatar
Andrey Filippov committed
4482 4483 4484 4485 4486 4487
						// -1 - less than, 1 - greater than, 0 - equal
						return (rhs.getZxy()[0] > lhs.getZxy()[0]) ? -1 : (rhs.getZxy()[0] < lhs.getZxy()[0] ) ? 1 : 0;
					}
				});
				return st_planes;
			}
4488
			return null;
Andrey Filippov's avatar
Andrey Filippov committed
4489
		}
4490

4491 4492
		public boolean [][][]  reDiscriminateTiles_0(
				String           prefix,
4493
				final PlaneData  [] planes,
4494 4495 4496
				final int        stMeasSel, //            = 1;      // Select measurements for supertiles : +1 - combo, +2 - quad +4 - hor +8 - vert

				final boolean    smplMode, //        = true;   // Use sample mode (false - regular tile mode)
4497
				final MeasuredLayersFilterParameters mlfp,
4498
				final double     max_disp_diff,    // maximal disparity difference from the plane to consider tile
4499 4500
				final double     disp_range,       // parallel move known planes around original know value for the best overall fit
				final int        amplitude_steps,  // number of steps (each direction) for each plane to search for the best fit (0 - single, 1 - 1 each side)
4501
				final int        num_variants,     // total number of variants to try (protect from too many planes)
4502 4503 4504
				final int        mode, // 0 - weighted, 1 - equalized, 2 - best, 3 - combined
				final int        debugLevel)
		{
4505 4506 4507
			final int size2 = 4 * superTileSize*superTileSize;
			final double max_disp_diff2 = max_disp_diff*max_disp_diff;
			TileNeibs tileNeibs = new TileNeibs(2 * stSize, 2 * stSize);
4508 4509 4510 4511 4512 4513 4514 4515
			if (planes == null) return null;
			// create a list of usable planes according to the mode
			ArrayList<PlaneData> tilePlanes = new ArrayList<PlaneData>();
			for (int np = 0; np < planes.length; np++) if (planes[np] != null){
				PlaneData weighted_pd = planes[np].getNonexclusiveStar();
				PlaneData equal_pd =    planes[np].getNonexclusiveStarEq();
				switch (mode){
				case 0:
4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527
					if (weighted_pd == null){
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null, trying getNonexclusiveStarEq");
						if (equal_pd == null) {
							if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, using plane itself");
							tilePlanes.add(planes[np]);
						} else {
							tilePlanes.add(equal_pd);
						}
//						throw new IllegalArgumentException ("refineDiscriminateTiles(): getNonexclusiveStar() returned null");
					} else  {
						tilePlanes.add(weighted_pd);
					}
4528 4529
					break;
				case 1:
4530 4531 4532 4533 4534 4535 4536 4537
					if (equal_pd == null) { //throw new IllegalArgumentException ("refineDiscriminateTiles(): getNonexclusiveStarEq() returned null");
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, trying getNonexclusiveStar");
						if (weighted_pd == null) {
							if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null, using plane itself");
							tilePlanes.add(planes[np]);
						} else {
							tilePlanes.add(weighted_pd);
						}
4538

4539 4540 4541
					} else {
						tilePlanes.add(equal_pd);
					}
4542 4543
					break;
				case 2:
4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558
					if (weighted_pd == null) { //throw new IllegalArgumentException ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null");
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null, trying getNonexclusiveStarEq");
						if (equal_pd == null) {
							if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, using plane itself");
							tilePlanes.add(planes[np]);
						} else {
							tilePlanes.add(equal_pd);
						}
						break;
					}
					if (equal_pd == null) { //throw new IllegalArgumentException ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null");
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, trying getNonexclusiveStar");
						tilePlanes.add(weighted_pd);
						break;
					}
4559 4560 4561 4562
					if (weighted_pd.getWeight() > equal_pd.getWeight()) tilePlanes.add(weighted_pd);
					else                                                tilePlanes.add(equal_pd);
					break;
				case 3:
4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577
					if (weighted_pd == null) { //throw new IllegalArgumentException ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null");
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null, trying getNonexclusiveStarEq");
						if (equal_pd == null) {
							if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, using plane itself");
							tilePlanes.add(planes[np]);
						} else {
							tilePlanes.add(equal_pd);
						}
						break;
					}
					if (equal_pd == null) { //throw new IllegalArgumentException ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null");
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, trying getNonexclusiveStar");
						tilePlanes.add(weighted_pd);
						break;
					}
4578 4579 4580 4581 4582 4583 4584
					PlaneData combo_pd =  weighted_pd.mergePlaneToThis(
							equal_pd, // PlaneData otherPd,
							1.0,      // double    scale_other,
							1.0,      // double    starWeightPwr,    // Use this power of tile weight when calculating connection cost
							false,    // boolean   ignore_weights,
							true,     // boolean   sum_weights,
							preferDisparity, // boolean   preferDisparity, // Always start with disparity-most axis (false - lowest eigenvalue)
4585 4586
							debugLevel - 3); // int       debugLevel)
					 tilePlanes.add(combo_pd);
4587 4588
					break;
				default:
4589
		    		throw new IllegalArgumentException ("refineDiscriminateTiles() "+prefix+":"+np+": invalid mode="+mode);
4590
				}
Andrey Filippov's avatar
Andrey Filippov committed
4591
			}
4592 4593 4594
			if (tilePlanes.isEmpty()){
				return null;
			}
4595 4596 4597
			if (debugLevel > 1)	{
				System.out.println ("refineDiscriminateTiles() "+prefix+" - step 1");
			}
4598

4599 4600 4601 4602
           // get measured disparity/strength data, filtered, not tilted
			double [][][] disp_strength = new double[measuredLayers.getNumLayers()][][];
			for (int ml = 0; ml < disp_strength.length; ml++) if ((stMeasSel & ( 1 << ml)) != 0){
				if (smplMode) {
4603
					disp_strength[ml] = measuredLayers.getDisparityStrengthMLTilted( // expensive to calculate (improve removing outliers
4604 4605 4606
							ml, // int num_layer,
							getSTileXY()[0],        // int stX,
							getSTileXY()[1],        // int stY,
4607
							null,                   // boolean [] sel_in, - use all
4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622
							mlfp,
//							strength_floor,
//							measured_strength_pow,  //
//							smplSide,               // = 2;      // Sample size (side of a square)
//							smplNum,                // = 3;      // Number after removing worst
//							smplRms,                // = 0.1;    // Maximal RMS of the remaining tiles in a sample
//							smplWnd,                // use window functions for the samples

//							max_abs_tilt,  // 2.0; // Maximal absolute tilt in pixels/tile
//							max_rel_tilt,  // 0.2; // Maximal relative tilt in pixels/tile/disparity
//							damp_tilt,     //    0.001; // Damp tilt to handle insufficient  (co-linear)data
//							min_tilt_disp, // 4.0; // Disparity switch between filtering modes - near objects use tilts, far - use max disparity
//							transition,    // 1.0; // Mode transition range (between tilted and maximal disparity)
//							far_mode,      //     1;   // Far objects filtering mode (0 - off, 1 - power of disparity)
//							far_power,     //    1.0; // Raise disparity to this power before averaging for far objects
4623

4624 4625
							true,                   // boolean null_if_none)
							debugLevel);
4626
				} else {
Andrey Filippov's avatar
Andrey Filippov committed
4627
					disp_strength[ml] = measuredLayers.getDisparityStrengthML(
4628 4629 4630 4631
							ml,                     // int num_layer,
							getSTileXY()[0],        // int stX,
							getSTileXY()[1],        // int stY,
							null,                   // boolean [] sel_in, - use all
4632 4633 4634
							mlfp,
//							strength_floor,         //  double strength_floor,
//							measured_strength_pow,  // double strength_pow,
4635 4636 4637
							true);                  // boolean null_if_none);
				}
			}
4638 4639 4640 4641
//			double [] window =	getWindow (2 * superTileSize);
			if (debugLevel > 1)	{
				System.out.println ("refineDiscriminateTiles() "+prefix+" - step 2");
			}
4642
			// get all original planes
4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655
			int num_planes = tilePlanes.size();
			double [][][] pds = new double [num_planes][][];
			for (int np = 0; np < pds.length; np++){
				PlaneData pd = tilePlanes.get(np);
				pds[np] = pd.getDoublePlaneDisparityStrength(
						false, // boolean   useWorld,
						null, // double [] window,
						-1, // int       dir,
						false, // boolean   use_sel,
						false, // boolean   divide_by_area,
						1.0, // double    scale_projection,
						0.0, // double    fraction_uni,
						0); // int       debugLevel)
4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684
			}
			double [][][] flatness = new double [num_planes][disp_strength.length][];
			int [][][] num_cells = new int [num_planes][disp_strength.length][];
			for (int np = 0; np < pds.length; np++){
				for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
					flatness[np][ml] = new double[size2];
					num_cells[np][ml] = new int[size2];
					for (int indx = 0; indx < size2; indx++) if (disp_strength[ml][1][indx] > 0.0){
						double d0 = pds[np][0][indx]; // disp_strength[ml][0][indx];
						double sw = disp_strength[ml][1][indx], sd = 0.0, sd2 = 0.0;
						num_cells[np][ml][indx]++;
						for (int dir = 0; dir<8; dir++){
							int indx1 = tileNeibs.getNeibIndex(indx, dir);
							if (indx1 >= 0){
								double w =  disp_strength[ml][1][indx1];
								if (w > 0.0){
									double d = disp_strength[ml][0][indx1] - d0;
									sw += w;
									sd += w * d;
									sd2 += w * d * d;
									num_cells[np][ml][indx]++;
								}
							}
						}
						if (sw > 0.0) {
							sd /= sw;
							sd2 /= sw;
							sd2 -= sd * sd;
						}
4685
						flatness[np][ml][indx] = sd2;
4686 4687
					}
				}
4688
			}
4689 4690 4691 4692 4693 4694
			if (debugLevel > 2){
				int dbg_ml = 0; // to protect from different layer configuration
				for (; dbg_ml < disp_strength.length;  dbg_ml++){
					if (disp_strength[dbg_ml] != null) break;
				}
				//disp_strength[dbg_ml][0], disp_strength[dbg_ml][1] * 10, disp_strength[dbg_ml][0] - pds[np][0], pds[np][0]
4695
				String [] dbg_titles = new String[2 + 5 * num_planes];
4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723
				double [][] dbg_img = new double [dbg_titles.length][];
				dbg_titles[0] = "disp_"+dbg_ml;
				dbg_titles[1] = "str_"+dbg_ml;
				dbg_img[0] = disp_strength[dbg_ml][0];
				dbg_img[1] = disp_strength[dbg_ml][1];
				for (int np = 0; np < num_planes; np++){
					dbg_titles[2 + 0 * num_planes + np] = "pln_"+np;
					dbg_titles[2 + 1 * num_planes + np] = "diff_"+np;
					dbg_titles[2 + 2 * num_planes + np] = "flat_"+np;
					dbg_titles[2 + 3 * num_planes + np] = "rflat_"+np;
					dbg_titles[2 + 3 * num_planes + np] = "nrflat_"+np;
					dbg_img[2 + 0 * num_planes + np] = pds[np][0];
					dbg_img[2 + 1 * num_planes + np] = disp_strength[dbg_ml][0].clone();
					dbg_img[2 + 2 * num_planes + np] = flatness[np][dbg_ml];
					dbg_img[2 + 3 * num_planes + np] = new double[size2];
					dbg_img[2 + 4 * num_planes + np] = new double[size2];
					for (int i = 0; i < size2; i++) {
						dbg_img[2 + 1 * num_planes + np][i] -= pds[np][0][i];
						dbg_img[2 + 3 * num_planes + np][i] = 1.0 / (flatness[np][dbg_ml][i] + 0.001);
						dbg_img[2 + 4 * num_planes + np][i] = num_cells[np][dbg_ml][i] * 1.0 / (flatness[np][dbg_ml][i] + 0.001);
						if (disp_strength[dbg_ml][1][i] == 0.0){
							dbg_img[2 + 1 * num_planes + np][i] = Double.NaN;
							dbg_img[2 + 2 * num_planes + np][i] = Double.NaN;
							dbg_img[2 + 3 * num_planes + np][i] = Double.NaN;
							dbg_img[2 + 4 * num_planes + np][i] = Double.NaN;
						}
					}
				}
4724
				ShowDoubleFloatArrays sdfa_instance = new ShowDoubleFloatArrays();
4725 4726
				sdfa_instance.showArrays(dbg_img,     2 * superTileSize, 2 * superTileSize, true, "refine-"+prefix,dbg_titles);
			}
4727 4728 4729 4730




4731 4732 4733 4734 4735 4736 4737
			// calculate number of the variants for each plane
			int  extra_vars = (((int) Math.pow(num_variants, 1.0/num_planes)) - 1) / 2; // 0 - single, 1 - 3 (1 each direction), ...
			if (extra_vars > amplitude_steps) extra_vars = amplitude_steps; //
			int steps = 2 * extra_vars + 1;
			double [] disps = new double [steps];
			disps[0] = 0.0; // center
			for (int i = 0; i < extra_vars; i++){
4738 4739
				disps[2 * i + 1] =  (disp_range * (i + 1)) / extra_vars;
				disps[2 * i + 2] = -disps[2 * i + 1];
4740 4741
			}
			int [] state = new int [num_planes]; // variants counter
4742 4743 4744 4745 4746 4747
			boolean [][][] best_selections = null;
//			int best_num_tiles = 0;
			double best_cost = Double.NaN;
			if (debugLevel > 1)	{
				System.out.println ("refineDiscriminateTiles() "+prefix+" - step 3");
			}
4748
			while (true){
4749 4750 4751 4752 4753 4754 4755
				if (debugLevel > 1)	{
					System.out.print ("refineDiscriminateTiles() "+prefix+" - state:");
					for (int np = 0; np < num_planes; np++){
						System.out.print(" "+state[np]);
					}
					System.out.println();
				}
4756 4757
				// evaluate current variant
				double [] weights = new double [num_planes];
4758
				double [] diffs0  = new double [num_planes];
4759
				boolean [][][] var_sels = new boolean [num_planes][disp_strength.length][];
4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785
				for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
					for (int nTile = 0; nTile < size2; nTile++) if (disp_strength[ml][1][nTile] != 0){
						// find best fit
						int best_np = -1;
						double best_err2 = max_disp_diff2;
						for (int np = 0; np < num_planes; np++){
							double e2 = disp_strength[ml][0][nTile] - (pds[np][0][nTile] + disps[state[np]]);
							e2 *= e2;
							if (e2 < best_err2){
								best_np = np;
								best_err2 = e2;
							}
						}
						if (best_np >= 0) { // found acceptable assignment
							double w = disp_strength[ml][1][nTile]; //  * window[nTile];
							double d = disp_strength[ml][0][nTile] - (pds[best_np][0][nTile] + disps[state[best_np]]);
							weights[best_np] +=  w;
							diffs0[best_np] +=  w*d;
						}
					}
				}
				if (debugLevel > 1)	{
					System.out.println ("refineDiscriminateTiles() "+prefix+" - pass1 DONE");
				}
					// second pass - use new averages disparity offsets, that may change assignments
				for (int np = 0; np < num_planes; np++){
4786
					if (weights[np] > 0.0) diffs0[np] /= weights[np];
4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823
				}
				weights =           new double [num_planes];
				double [] diffs  =  new double [num_planes];
				double [] diffs2  = new double [num_planes];
				int    [] ntiles =  new int [num_planes];
				int num_tiles = 0;
				for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
					for (int np = 0; np < num_planes; np++){
						var_sels[np][ml] = new boolean [size2];
					}
					for (int nTile = 0; nTile < size2; nTile++) if (disp_strength[ml][1][nTile] != 0){
						// find best fit
						int best_np = -1;
						double best_err2 = max_disp_diff2;
						for (int np = 0; np < num_planes; np++){
							double e2 = disp_strength[ml][0][nTile] - (pds[np][0][nTile] + disps[state[np]]+ diffs0[np]);
							e2 *= e2;
							if (e2 < best_err2){
								best_np = np;
								best_err2 = e2;
							}
						}
						if (best_np >= 0) { // found acceptable assignment
							double w = disp_strength[ml][1][nTile]; //  * window[nTile];
							double d = disp_strength[ml][0][nTile] - (pds[best_np][0][nTile] + disps[state[best_np]]);
							weights[best_np] +=  w;
							diffs[best_np] +=    w*d;
							diffs2[best_np] +=   w*d*d;
							ntiles[best_np]++;
							var_sels[best_np][ml][nTile] = true;
							num_tiles ++;
						}
					}
				}
				for (int np = 0; np < num_planes; np++) if (weights[np] > 0.0){
					diffs[np] /= weights[np];
					diffs2[np] /= weights[np];
4824
					diffs2[np] -= diffs[np]*diffs[np];
4825 4826 4827 4828 4829 4830 4831 4832 4833
				}
				// How to decide if this variant is better? Have number of tiles that fit, per-plane weights and per-plane rms=sqrt(diffs2)
				// start with just number of tiles fit
				double cost = 0;
				double weight = 0.0;
				for (int np = 0; np < num_planes; np++) {
					weight += weights[np];
					cost += weights[np]*diffs2[np];
				}
4834

4835 4836 4837 4838 4839 4840 4841 4842 4843
				if ((weight > 0.0) && (num_tiles > 0)){
					double corr_cost = cost/num_tiles;
					if (debugLevel > 1)	{
						System.out.print ("refineDiscriminateTiles() "+prefix+": [");
						for (int np = 0; np < num_planes; np++){
							System.out.print (" "+state[np]);
						}
						System.out.println ("] num_tiles = "+num_tiles+" weight="+weight+" corr_cost="+corr_cost+" cost="+cost);
					}
4844

4845 4846 4847 4848 4849 4850
					if (Double.isNaN(best_cost) || (best_cost > corr_cost)) {
						best_cost = corr_cost;
						best_selections = var_sels;

					}
				}
4851

4852 4853 4854 4855 4856 4857 4858
//				if (num_tiles > best_num_tiles) {
//					best_num_tiles = num_tiles;
//					best_selections = var_sels;
//				}
				if (debugLevel > 1)	{
					System.out.println ("refineDiscriminateTiles() "+prefix+" - pass2 DONE");
				}
4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872
				//  calculate next variant
				boolean all_done = true;
				for (int i = 0; i < num_planes; i ++){
					if (state[i] < (steps - 1)){
						state[i] ++;
						for (int j = 0; j < i; j++){
							state[j] = 0;
						}
						all_done = false;
						break;
					}
				}
				if (all_done){
					break;
4873
				}
4874

4875
			}
4876 4877 4878 4879 4880
			return best_selections;
		}

		/**
		 * re-discriminate tiles between supertiles in the list using hints from the already calculated planes and their neighbors
4881 4882
		 * @param prefix text to be used in debug output (such as supertile number)
		 * @param planes array of PlaneData instances of the current supertile to be used as hints
Andrey Filippov's avatar
Andrey Filippov committed
4883
		 * @param merge_planes should be initilaized to int[2], will return indices of planes suggested to be merged or [-1, -1]
4884
		 * @param stMeasSel select measurements for supertiles : +1 - combo, +2 - quad +4 - hor +8 - vert
4885 4886 4887 4888 4889
		 * @param dispNorm normalize disparities to the average if above
		 * @param smplMode use sample mode (false - each tile independent)
		 * @param smplSide sample size (side of a square)
		 * @param smplNum number after removing worst
		 * @param smplRms maximal RMS of the remaining tiles in a sample
4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900
		 * @param smplWnd use window functions for the samples
		 *
		 * @param max_abs_tilt pix per tile
		 * @param max_rel_tilt pix / disparity) per tile
		 * @param damp_tilt Damp tilt to handle insufficient  (co-linear)data
		 * @param min_tilt_disp Disparity switch between filtering modes - near objects use tilts, far - use max disparity
		 * @param transition Mode transition range (between tilted and maximal disparity)
		 * @param far_mode Far objects filtering mode (0 - off, 1 - power of disparity)
		 * @param far_power Raise disparity to this power before averaging for far objects
		 *
		 * @param disp_tolerance maximal disparity difference from the plane to consider tile
4901
		 * @param disp_var_floor squared add to variance to calculate reverse flatness (used mostly for single-cell clusters) (reuse disp_sigma)?
4902
		 * @param disp_sigma Gaussian sigma to compare how measured data is attracted to planes
4903 4904 4905 4906
		 * @param disp_range full range of the parallel plane shifts to evaluate (histograms full range)
		 * @param amplitude_steps numer of histogram steps in each direction from the center
		 * @param hist_blur histogram LPF sigma
		 * @param exclusivity 1.0 - tile belongs to one plane only, 0.0 - regardless of others
4907
		 * @param exclusivity2 when exclusivity > 1.0, add tiles to the existing clusters if attraction > this relaxed level
Andrey Filippov's avatar
Andrey Filippov committed
4908 4909 4910 4911
		 * @param exclusivity_strict do not add to the clusters if there is a single offending neighbor (false just more of the these neighbors than offenders)
		 * @param attractionCorrMax do not discriminate if at least one pair has attraction correlation above this level
         * @param attractionCorrMerge attraction to different planes correlation that is high enough to merge planes
         * @param plDiscrSteal if offender has this number of tiles (including center) the cell can not be used
4912
         * @param plDiscrGrown only use tiles within this range from original selection, < 0 - disable this filter
Andrey Filippov's avatar
Andrey Filippov committed
4913
         * @param outliersXMedian remove outliers from the final selection that have distance more than scaled median
4914 4915
		 * @param mode what neighbor-dependent pre-calculated plane to use as hints: 0 - weighted, 1 - equalized, 2 - best, 3 - combined
		 * @param debugLevel debug level
Andrey Filippov's avatar
Andrey Filippov committed
4916 4917
		 * @return per-plane, per-measurement layer, per tile index - use this tile. Return null if could not discriminate,
		 *         in that case merge_planes may contain non-negative indices to be merged and the whole method re-ran
4918 4919 4920
		 */
		public boolean [][][]  reDiscriminateTiles(
				String           prefix,
Andrey Filippov's avatar
Andrey Filippov committed
4921 4922
				final PlaneData  [] planes,
				final int []     merge_planes, // indices of planes suggested to be merged
4923 4924 4925 4926
				final int        stMeasSel, //            = 1;      // Select measurements for supertiles : +1 - combo, +2 - quad +4 - hor +8 - vert
				final double     dispNorm,   //  Normalize disparities to the average if above

				final boolean    smplMode, //        = true;   // Use sample mode (false - regular tile mode)
4927
				final MeasuredLayersFilterParameters mlfp,
4928
				final double     disp_tolerance,   // maximal disparity difference from the plane to consider tile
4929
				final double     disp_var_floor,   // squared add to variance to calculate reverse flatness (used mostly for single-cell clusters)
4930
				final double     disp_sigma,       // G.sigma to compare how measured data is attracted to planes
4931 4932 4933 4934
				final double     disp_range,       // parallel move known planes around original know value for the best overall fit
				final int        amplitude_steps,  // number of steps (each direction) for each plane to search for the best fit (0 - single, 1 - 1 each side)
				final double     hist_blur,        // Sigma to blur histogram
				final double     exclusivity,      // 1.0 - tile belongs to one plane only, 0.0 - regardless of others
Andrey Filippov's avatar
Andrey Filippov committed
4935 4936
			    final double     exclusivity2,        //        =   0.8;   // For second pass if exclusivity > 1.0 - will assign only around strong neighbors
			    final boolean    exclusivity_strict,  //         = true;   // When growing selection do not allow any offenders around (false - more these than others)
4937
				final double     attractionCorrMax,   //         = 0.7;   // Attraction to different planes correlation that is too high for re-discrimination.
Andrey Filippov's avatar
Andrey Filippov committed
4938 4939 4940 4941
				final double     attractionCorrMerge, //         = 0.85;  // Attraction to different planes correlation that is high enough to merge planes
				final int        plDiscrSteal,        //         =   4;     // If offender has this number of tiles (including center) the cell can not be used
				final int        plDiscrGrown,        //         =   0;     // Only use tiles within this range from original selection
				final double     outliersXMedian,     //         = 1.5;   // Remove outliers from the final selection that have distance more than scaled median
4942

4943 4944 4945 4946 4947 4948 4949
				final int        mode, // 0 - weighted, 1 - equalized, 2 - best, 3 - combined
				final int        debugLevel)
		{
			final int size2 = 4 * superTileSize*superTileSize;
			final double disp_tolerance2 = disp_tolerance * disp_tolerance;
			final double floor2 = disp_var_floor * disp_var_floor;
			final double ksigma = 0.5/(disp_sigma * disp_sigma);
4950

4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981
			TileNeibs tileNeibs = new TileNeibs(2 * stSize, 2 * stSize);
			if (planes == null) return null;
			// create a list of usable planes according to the mode
			ArrayList<PlaneData> tilePlanes = new ArrayList<PlaneData>();
			for (int np = 0; np < planes.length; np++) if (planes[np] != null){
				PlaneData weighted_pd = planes[np].getNonexclusiveStar();
				PlaneData equal_pd =    planes[np].getNonexclusiveStarEq();
				switch (mode){
				case 0:
					if (weighted_pd == null){
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null, trying getNonexclusiveStarEq");
						if (equal_pd == null) {
							if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, using plane itself");
							tilePlanes.add(planes[np]);
						} else {
							tilePlanes.add(equal_pd);
						}
//						throw new IllegalArgumentException ("refineDiscriminateTiles(): getNonexclusiveStar() returned null");
					} else  {
						tilePlanes.add(weighted_pd);
					}
					break;
				case 1:
					if (equal_pd == null) { //throw new IllegalArgumentException ("refineDiscriminateTiles(): getNonexclusiveStarEq() returned null");
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, trying getNonexclusiveStar");
						if (weighted_pd == null) {
							if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null, using plane itself");
							tilePlanes.add(planes[np]);
						} else {
							tilePlanes.add(weighted_pd);
						}
4982

4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034
					} else {
						tilePlanes.add(equal_pd);
					}
					break;
				case 2:
					if (weighted_pd == null) { //throw new IllegalArgumentException ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null");
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null, trying getNonexclusiveStarEq");
						if (equal_pd == null) {
							if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, using plane itself");
							tilePlanes.add(planes[np]);
						} else {
							tilePlanes.add(equal_pd);
						}
						break;
					}
					if (equal_pd == null) { //throw new IllegalArgumentException ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null");
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, trying getNonexclusiveStar");
						tilePlanes.add(weighted_pd);
						break;
					}
					if (weighted_pd.getWeight() > equal_pd.getWeight()) tilePlanes.add(weighted_pd);
					else                                                tilePlanes.add(equal_pd);
					break;
				case 3:
					if (weighted_pd == null) { //throw new IllegalArgumentException ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null");
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStar() returned null, trying getNonexclusiveStarEq");
						if (equal_pd == null) {
							if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, using plane itself");
							tilePlanes.add(planes[np]);
						} else {
							tilePlanes.add(equal_pd);
						}
						break;
					}
					if (equal_pd == null) { //throw new IllegalArgumentException ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null");
						if (debugLevel > 0)	System.out.println ("refineDiscriminateTiles() "+prefix+":"+np+": getNonexclusiveStarEq() returned null, trying getNonexclusiveStar");
						tilePlanes.add(weighted_pd);
						break;
					}
					PlaneData combo_pd =  weighted_pd.mergePlaneToThis(
							equal_pd, // PlaneData otherPd,
							1.0,      // double    scale_other,
							1.0,      // double    starWeightPwr,    // Use this power of tile weight when calculating connection cost
							false,    // boolean   ignore_weights,
							true,     // boolean   sum_weights,
							preferDisparity, // boolean   preferDisparity, // Always start with disparity-most axis (false - lowest eigenvalue)
							debugLevel - 3); // int       debugLevel)
					 tilePlanes.add(combo_pd);
					break;
				default:
		    		throw new IllegalArgumentException ("refineDiscriminateTiles() "+prefix+":"+np+": invalid mode="+mode);
				}
Andrey Filippov's avatar
Andrey Filippov committed
5035
				tilePlanes.get(tilePlanes.size()-1).setMark0(np);
5036 5037 5038 5039 5040 5041 5042
			}
			if (tilePlanes.isEmpty()){
				return null;
			}
			if (debugLevel > 1)	{
				System.out.println ("refineDiscriminateTiles() "+prefix+" - step 1");
			}
5043

5044 5045 5046 5047
           // get measured disparity/strength data, filtered, not tilted
			double [][][] disp_strength = new double[measuredLayers.getNumLayers()][][];
			for (int ml = 0; ml < disp_strength.length; ml++) if ((stMeasSel & ( 1 << ml)) != 0){
				if (smplMode) {
5048
					disp_strength[ml] = measuredLayers.getDisparityStrengthMLTilted( // expensive to calculate (improve removing outliers
5049 5050 5051
							ml, // int num_layer,
							getSTileXY()[0],        // int stX,
							getSTileXY()[1],        // int stY,
5052
							null,                   // boolean [] sel_in, - use all
5053
							mlfp,
5054 5055
							true,                  // boolean null_if_none)
							debugLevel);
5056
				} else {
Andrey Filippov's avatar
Andrey Filippov committed
5057
					disp_strength[ml] = measuredLayers.getDisparityStrengthML(
5058 5059 5060 5061
							ml,                     // int num_layer,
							getSTileXY()[0],        // int stX,
							getSTileXY()[1],        // int stY,
							null,                   // boolean [] sel_in, - use all
5062
							mlfp,
5063 5064 5065 5066 5067 5068 5069
							true);                  // boolean null_if_none);
				}
			}
			double [] window =	getWindow (2 * superTileSize);
			if (debugLevel > 1)	{
				System.out.println ("refineDiscriminateTiles() "+prefix+" - step 2");
			}
5070
			// get all original planes
5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084
			int num_planes = tilePlanes.size();
			double [][][] pds = new double [num_planes][][];
			for (int np = 0; np < pds.length; np++){
				PlaneData pd = tilePlanes.get(np);
				pds[np] = pd.getDoublePlaneDisparityStrength(
						false, // boolean   useWorld,
						null, // double [] window,
						-1, // int       dir,
						false, // boolean   use_sel,
						false, // boolean   divide_by_area,
						1.0, // double    scale_projection,
						0.0, // double    fraction_uni,
						0); // int       debugLevel)
			}
Andrey Filippov's avatar
Andrey Filippov committed
5085
			// Create enable and disable masks
5086

Andrey Filippov's avatar
Andrey Filippov committed
5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097
			boolean [][] prev_used = new boolean [num_planes][size2];
			boolean [][] mask =      new boolean [num_planes][];
			boolean [][] used_strong = new boolean [num_planes][size2];
			for (int np = 0; np < num_planes; np++){
				boolean [][] meas_sel = tilePlanes.get(np).getMeasSelection();
				for (int ml = 0; ml < meas_sel.length; ml++) if (meas_sel[ml] != null){
					for (int indx = 0; indx < size2; indx++){
						prev_used[np][indx] |= meas_sel[ml][indx];
					}
				}
				mask[np] = prev_used[np].clone();
5098
				if (plDiscrGrown > 100) { // >0
Andrey Filippov's avatar
Andrey Filippov committed
5099 5100 5101 5102
					tileNeibs.growSelection(
							plDiscrGrown, // int        grow,           // grow tile selection by 1 over non-background tiles 1: 4 directions, 2 - 8 directions, 3 - 8 by 1, 4 by 1 more
							mask[np], // boolean [] tiles,
							null); // boolean [] prohibit)
5103
				} else if (plDiscrGrown < 100){ //< 0
Andrey Filippov's avatar
Andrey Filippov committed
5104
					for (int indx = 0; indx < size2; indx++) mask[np][indx] = true;
5105

Andrey Filippov's avatar
Andrey Filippov committed
5106 5107 5108 5109 5110 5111 5112
				}
				if (plDiscrSteal > 0){
					for (int indx = 0; indx < size2; indx++) if (prev_used[np][indx]){
						int num_neibs = 1;
						for (int dir = 0; dir < 8; dir++){
							int indx1 = tileNeibs.getNeibIndex(indx, dir);
							if ((indx1 >=0) && prev_used[np][indx1]){
5113
								num_neibs++;
Andrey Filippov's avatar
Andrey Filippov committed
5114 5115 5116 5117 5118
							}
						}
						used_strong[np][indx] = (num_neibs >= plDiscrSteal);
					}
				}
5119
			}
5120
			if (0 * plDiscrSteal > 0){ // 0*
Andrey Filippov's avatar
Andrey Filippov committed
5121 5122 5123 5124 5125 5126 5127
				for (int np = 0; np < num_planes; np++){
					for (int np1 = 0; np1 < num_planes; np1++) if (np1 != np){
						for (int indx = 0; indx < size2; indx++){
							mask[np][indx] &= !used_strong[np1][indx];
						}
					}
				}
5128 5129
			}

5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161
			double [][][] flatness = new double [num_planes][disp_strength.length][];
			double [][][] norm_flatness = new double [num_planes][disp_strength.length][];
			int [][][] num_cells = new int [num_planes][disp_strength.length][];
			for (int np = 0; np < pds.length; np++){
				for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
					flatness[np][ml] = new double[size2];
					norm_flatness[np][ml] = new double[size2];
					num_cells[np][ml] = new int[size2];
					for (int indx = 0; indx < size2; indx++) if (disp_strength[ml][1][indx] > 0.0){
						double d0 = pds[np][0][indx]; // disp_strength[ml][0][indx];
						double sw = disp_strength[ml][1][indx]/window[indx], sd = 0.0, sd2 = 0.0;
						num_cells[np][ml][indx]++;
						for (int dir = 0; dir<8; dir++){
							int indx1 = tileNeibs.getNeibIndex(indx, dir);
							if (indx1 >= 0){
								double w =  disp_strength[ml][1][indx1]/window[indx1];
								if (w > 0.0){
									double d = disp_strength[ml][0][indx1] - d0;
									sw += w;
									sd += w * d;
									sd2 += w * d * d;
									num_cells[np][ml][indx]++;
								}
							}
						}
						if (sw > 0.0) {
							sd /= sw;
							sd2 /= sw;
							sd2 -= sd * sd;
						}
						double rms = Math.sqrt(sd2);
						flatness[np][ml][indx] = rms; // sd2; // will not be used
Andrey Filippov's avatar
Andrey Filippov committed
5162 5163 5164
						if (rms < disp_var_floor){
							rms = disp_var_floor;
						}
5165 5166 5167 5168 5169 5170 5171 5172
						norm_flatness[np][ml][indx] = (num_cells[np][ml][indx] > 1) ? (1.0/rms): (1.0/disp_var_floor);
					}
				}
			}
			// calculate histograms for each plane, combining weight with flatness
			final int steps = amplitude_steps * 2 + 1;
			double bin_size = disp_range/(2 * amplitude_steps);
			double k_bin = 2 * amplitude_steps /  disp_range; // 1/bin_size
5173 5174
			double [][] histograms = new double [num_planes][steps];

5175 5176 5177 5178 5179
			for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
				for (int indx = 0; indx < size2; indx++){
					double weight = disp_strength[ml][1][indx];
					if (weight > 0.0) {
						double disp =   disp_strength[ml][0][indx];
Andrey Filippov's avatar
Andrey Filippov committed
5180
						for (int np = 0; np < num_planes; np++) if (mask[np][indx]){
5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194
							double d = disp - pds[np][0][indx];
							double db = d * k_bin + amplitude_steps;
							int bin = (int) Math.round (db);
							if ((bin >= 0) && (bin < steps)) {
								// combine correlation weight, variance between valid neighbors and number of valid neighbors
								double w = weight * norm_flatness[np][ml][indx]; // TODO: tweak?
								histograms[np][bin] += w;
							}
						}
					}
				}
			}
			// Raise weight of the center part of the histogram - there can be originally distinct parallel planes
			// alternatively - use planes_mod or star* and no histograms at all?
5195
			final double initial_trust_sigma = 0.3 * disp_tolerance; // TODO: use dispNorm !
5196 5197 5198 5199 5200 5201
			for (int np = 0; np < num_planes; np++) {
				double k_sigma = 0.5/(initial_trust_sigma*initial_trust_sigma);
				for (int nb = 0; nb < steps; nb++) {
					double offs = bin_size * (nb - amplitude_steps);
					histograms[np][nb] *= Math.exp(-k_sigma*offs*offs);
				}
5202 5203
			}

5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234
			// normalize histograms
			for (int np = 0; np < num_planes; np++) {
				double s = 0.0;
				for (int nb = 0; nb < steps; nb++)
					s += histograms[np][nb];
				if (s > 0.0) {
					for (int nb = 0; nb < steps; nb++)
						histograms[np][nb] /= s;
				}
			}
			if (debugLevel > 2) {
				System.out.println("refineDiscriminateTiles() histograms raw:");
				System.out.print("disparity: ");
				for (int nb = 0; nb < steps; nb++) {
					System.out.print(bin_size * (nb - amplitude_steps));
					if (nb < (steps - 1))
						System.out.print(", ");
				}
				System.out.println();
				for (int np = 0; np < num_planes; np++) {
					System.out.print(np + ": ");
					for (int nb = 0; nb < steps; nb++) {
						System.out.print(histograms[np][nb]);
						if (nb < (steps - 1))
							System.out.print(", ");
					}
					System.out.println();
				}
				System.out.println();
				System.out.println();
			}
5235

5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261
			// Add LPF here?
			if (hist_blur > 0.0) {
				DoubleGaussianBlur gb=new DoubleGaussianBlur();
				for (int np = 0; np < num_planes; np++) {
					gb.blur1Direction(histograms[np], steps, 1, hist_blur/bin_size, 0.01,true);
				}
				if (debugLevel > 2) {
					System.out.println("refineDiscriminateTiles() histograms blured:");
					System.out.print("disparity: ");
					for (int nb = 0; nb < steps; nb++) {
						System.out.print(bin_size * (nb - amplitude_steps));
						if (nb < (steps - 1))
							System.out.print(", ");
					}
					System.out.println();
					for (int np = 0; np < num_planes; np++) {
						System.out.print(np + ": ");
						for (int nb = 0; nb < steps; nb++) {
							System.out.print(histograms[np][nb]);
							if (nb < (steps - 1))
								System.out.print(", ");
						}
						System.out.println();
					}
					System.out.println();
				}
5262

5263
			}
5264 5265


5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281
			// For each plane, regardless of others
			double [] offsets = new double [num_planes];
			for (int np = 0; np < num_planes; np++) {
				int max_bin = 0;
				for (int nb = 1; nb < steps; nb++){
					if (histograms[np][nb] > histograms[np][max_bin]){
						max_bin = nb;
					}
				}
				// improve max by second degree polynomial
				 offsets[np] = bin_size * (max_bin - amplitude_steps);
				if ((max_bin > 0) && (max_bin < (steps-1))){
					offsets[np] += bin_size * 0.5 *(histograms[np][max_bin + 1] - histograms[np][max_bin - 1]) /
							(histograms[np][max_bin + 1] + histograms[np][max_bin - 1] - 2 * histograms[np][max_bin]);
				}
			}
5282

5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293
			// for each tile, each plane calculate "attraction" of the tile to each plane, where attraction is defined by Gaussian
			// of normalized disparity difference and "flatness" for each plane. Then, if the attraction exceeds "exclusivity" times
			// best competitor - include this tile for that plane
			double  [][][] attractions = new double[num_planes][disp_strength.length][];
			for (int np = 0; np < num_planes; np++) {
				for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
					attractions[np][ml] = new double[size2];
				}
			}
			for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
				for (int indx = 0; indx < size2; indx++) if (disp_strength[ml][1][indx] > 0){
Andrey Filippov's avatar
Andrey Filippov committed
5294
					for (int np = 0; np < num_planes; np++) if (mask[np][indx]){
5295 5296 5297 5298 5299 5300 5301 5302
						double d1 = pds[np][0][indx] + offsets[np]; // shifted plane
						double d2 = disp_strength[ml][0][indx];
						double dav = 0.5 * (d1 + d2);
						double diff = d2 - d1;
						if (dav > dispNorm) diff *= dispNorm/dav;
						double diff2 = diff * diff;
						if (diff2 <= disp_tolerance2) {
							attractions[np][ml][indx] = Math.exp(-ksigma*diff2) * norm_flatness[np][ml][indx];
5303

5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328
						}
					}
				}
			}
			double [][] attr_corr = new double [num_planes][num_planes];
			for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
				for (int indx = 0; indx < size2; indx++) if (disp_strength[ml][1][indx] > 0){
					for (int np = 0; np < num_planes; np++) {
						for (int np1 = np; np1 < num_planes; np1++) {
							attr_corr[np][np1] += attractions[np][ml][indx] * attractions[np1][ml][indx];
							if (np1 > np){
								attr_corr[np1][np] = attr_corr[np][np1];
							}
						}
					}
				}
			}
			for (int np = 0; np < num_planes; np++) {
				for (int np1 = np+1; np1 < num_planes; np1++) {
					if ((attr_corr[np][np] > 0.0) && (attr_corr[np1][np1] > 0.0)){
						attr_corr[np][np1] /= Math.sqrt(attr_corr[np][np] * attr_corr[np1][np1]);
						attr_corr[np1][np] = attr_corr[np][np1];
					}
				}
				attr_corr[np][np] = 1.0;
Andrey Filippov's avatar
Andrey Filippov committed
5329

5330
			}
Andrey Filippov's avatar
Andrey Filippov committed
5331 5332 5333 5334 5335 5336 5337 5338
			double max_attr_corr = 0.0;
			int [] merge_pair = {-1,-1};
			for (int np = 0; np < num_planes; np++) {
				for (int np1 = np + 1; np1 < num_planes; np1++) {
					if (attr_corr[np][np1] > max_attr_corr) {
						max_attr_corr = attr_corr[np][np1];
						merge_pair[0] = np;
						merge_pair[1] = np1;
5339 5340 5341
					}
				}
			}
5342 5343


5344 5345 5346 5347 5348 5349 5350 5351 5352 5353
			// discriminate
			boolean [][][] best_selections = new boolean[num_planes][disp_strength.length][];
			for (int np = 0; np < num_planes; np++) {
				for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
					best_selections[np][ml] = new boolean[size2];
				}
			}
			for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
				for (int indx = 0; indx < size2; indx++) if (disp_strength[ml][1][indx] > 0){
					if (num_planes == 1){
5354
						best_selections[0][ml][indx] = attractions[0][ml][indx] > 0.0;
5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365
					} else { // find to best candidates
						int best_np = 0;
						for (int np = 1; np < num_planes; np++) if (attractions[np][ml][indx] > attractions[best_np][ml][indx]){
							best_np = np;
						}
						int best_np2 = (best_np ==0) ? 1:0;
						for (int np = 1; np < num_planes; np++) if ((np != best_np ) && (attractions[np][ml][indx] > attractions[best_np2][ml][indx])){
							best_np2 = np;
						}
						for (int np = 0; np < num_planes; np++){
							int np_other = (np == best_np) ? best_np2 : best_np;
5366
							best_selections[np][ml][indx] = attractions[np][ml][indx] > exclusivity * attractions[np_other][ml][indx];
5367 5368 5369 5370 5371 5372 5373 5374 5375 5376
						}
					}
				}
			}
			if ((exclusivity > 1.0) && (exclusivity2 > 0.0) && (num_planes > 1)) { // second pass - lower threshold but depend on neighbors
				boolean changed = true;
				while (changed) {
					changed = false;
					boolean [][][] best_selections_prev = best_selections.clone();
					for (int np = 0; np < num_planes; np++) {
5377
						best_selections_prev[np] = best_selections[np].clone();
5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427
						for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
							best_selections_prev[np][ml] = best_selections[np][ml].clone();
						}
					}

					for (int ml = 0; ml < disp_strength.length; ml++) if (disp_strength[ml] != null){
						for (int indx = 0; indx < size2; indx++) if (disp_strength[ml][1][indx] > 0){
							int best_np = 0;
							for (int np = 1; np < num_planes; np++) if (attractions[np][ml][indx] > attractions[best_np][ml][indx]){
								best_np = np;
							}
							int best_np2 = (best_np ==0) ? 1:0;
							for (int np = 1; np < num_planes; np++) if ((np != best_np ) && (attractions[np][ml][indx] > attractions[best_np2][ml][indx])){
								best_np2 = np;
							}
							for (int np = 0; np < num_planes; np++) if (!best_selections_prev[np][ml][indx]){ // only new
								int np_other = (np == best_np) ? best_np2 : best_np;
								if (attractions[np][ml][indx] > exclusivity2 * attractions[np_other][ml][indx]) {
									int num_this = 0;
									int num_other = 0;
									boolean used_by_other = false;
									for (int np1 = 0; np1 < num_planes; np1++) if (np1 != np){
										if (best_selections_prev[np1][ml][indx]) {
											used_by_other = true;
											break;
										}
									}
									if (! used_by_other) {
										for (int dir = 0; dir < 8; dir++){
											int indx1 = tileNeibs.getNeibIndex(indx, dir);
											if (indx1 >= 0){
												if (best_selections_prev[np][ml][indx1]) num_this ++;
												for (int np1 = 0; np1 < num_planes; np1++) if (np1 != np){
													if (best_selections_prev[np1][ml][indx1]) {
														num_other ++;
														break;
													}
												}
											}
										}
										if ((num_this > num_other) && (!exclusivity_strict || (num_other == 0))){ // make it stricter and require num_other==0 ?
											best_selections[np][ml][indx] = true;
											changed = true;
										}
									}
								}
							}
						}
					}
				}
5428

5429
			}
Andrey Filippov's avatar
Andrey Filippov committed
5430 5431 5432 5433 5434 5435 5436
			boolean [][][] all_best_selections = null;
			if (outliersXMedian > 0.0) {
				all_best_selections = best_selections.clone();
				for (int np = 0; np < num_planes; np++) if (best_selections[np] != null){
					all_best_selections[np] = best_selections[np].clone();
					for (int ml = 0; ml < best_selections[np].length; ml++) if (best_selections[np][ml] != null){
						all_best_selections[np][ml] = best_selections[np][ml].clone();
5437
					}
Andrey Filippov's avatar
Andrey Filippov committed
5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470
				}
				// from each plane remove outliers (without re-calculating mean value) that are farther from the mean than scaled median distance
				class ValIndex {
					int ml;
					int indx;
					double val;
					ValIndex(int ml, int indx, double val){
						this.ml = ml;
						this.indx = indx;
						this.val =  val;
					}
				}
				for (int np = 0; np < num_planes; np++) if (best_selections[np] != null){
					ArrayList<ValIndex> tile_list = new ArrayList<ValIndex>();
					for (int ml = 0; ml < best_selections[np].length; ml++) if (best_selections[np][ml] != null){
						for (int indx = 0; indx < best_selections[np][ml].length; indx++) if (best_selections[np][ml][indx]){
							double d1 = pds[np][0][indx] + offsets[np]; // shifted plane
							double d2 = disp_strength[ml][0][indx];
							double diff = d2 - d1;
//							double dav = 0.5 * (d1 + d2);
//							if (dav > dispNorm) diff *= dispNorm/dav;
							double diff2 = diff * diff;
							tile_list.add(new ValIndex(ml,indx,diff2));
						}
					}
					if (!tile_list.isEmpty()){
						Collections.sort(tile_list, new Comparator<ValIndex>() {
							@Override
							public int compare(ValIndex lhs, ValIndex rhs) {
								// -1 - less than, 1 - greater than, 0 - equal
								return (rhs.val > lhs.val) ? -1 : (rhs.val < lhs.val ) ? 1 : 0;
							}
						});
5471 5472
						int size = tile_list.size();
						double threshold =tile_list.get(size/2).val * outliersXMedian * outliersXMedian *1.0;
Andrey Filippov's avatar
Andrey Filippov committed
5473 5474 5475 5476 5477 5478 5479
						for (int i = (outliersXMedian > 1.0) ? (size / 2 + 1) : 0; i < size; i++){
							if (tile_list.get(i).val > threshold) {
								best_selections[np][tile_list.get(i).ml][tile_list.get(i).indx] = false;
							}
						}
					}
					// now restore outliers if they had non-outliers neighbors
5480
					ArrayList<Point> to_resore_list = new ArrayList<Point>();
Andrey Filippov's avatar
Andrey Filippov committed
5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498
					for (int ml = 0; ml < best_selections[np].length; ml++) if (best_selections[np][ml] != null){
						for (int indx = 0; indx < best_selections[np][ml].length; indx++) {
							if (all_best_selections[np][ml][indx] && !best_selections[np][ml][indx]){ // removed as outliers
								for (int dir = 0; dir<8; dir++){
									int indx1 = tileNeibs.getNeibIndex(indx, dir);
									if ((indx1 >= 0) && best_selections[np][ml][indx1]){
										to_resore_list.add(new Point(ml, indx));
										break;
									}
								}
							}
						}
					}
					for (Point p:to_resore_list) {
						best_selections[np][p.x][p.y] = true;
					}
				}
			}
5499 5500 5501 5502 5503 5504
			if (debugLevel > 2){
				int dbg_ml = 0; // to protect from different layer configuration
				for (; dbg_ml < disp_strength.length;  dbg_ml++){
					if (disp_strength[dbg_ml] != null) break;
				}
				//disp_strength[dbg_ml][0], disp_strength[dbg_ml][1] * 10, disp_strength[dbg_ml][0] - pds[np][0], pds[np][0]
5505
				String [] dbg_titles = new String[2 + 10 * num_planes];
5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516
				double [][] dbg_img = new double [dbg_titles.length][];
				dbg_titles[0] = "disp_"+dbg_ml;
				dbg_titles[1] = "str_"+dbg_ml;
				dbg_img[0] = disp_strength[dbg_ml][0];
				dbg_img[1] = disp_strength[dbg_ml][1];
				for (int np = 0; np < num_planes; np++){
					dbg_titles[2 + 0 * num_planes + np] = "pln_"+np;
					dbg_titles[2 + 1 * num_planes + np] = "diff_"+np;
					dbg_titles[2 + 2 * num_planes + np] = "flat_"+np;
					dbg_titles[2 + 3 * num_planes + np] = "rflat_"+np;
					dbg_titles[2 + 4 * num_planes + np] = "nrflat_"+np;
Andrey Filippov's avatar
Andrey Filippov committed
5517 5518 5519 5520 5521
					dbg_titles[2 + 5 * num_planes + np] = "mask_"+np;
					dbg_titles[2 + 6 * num_planes + np] = "attr_"+np;
					dbg_titles[2 + 7 * num_planes + np] = "pre_sel_"+np; // before outliers
					dbg_titles[2 + 8 * num_planes + np] = "sel_"+np; // add also old selection?
					dbg_titles[2 + 9 * num_planes + np] = "oldsel_"+np; // add also old selection?
5522 5523 5524 5525 5526
					dbg_img[2 + 0 * num_planes + np] = pds[np][0];
					dbg_img[2 + 1 * num_planes + np] = disp_strength[dbg_ml][0].clone();
					dbg_img[2 + 2 * num_planes + np] = flatness[np][dbg_ml];
					dbg_img[2 + 3 * num_planes + np] = new double[size2];
					dbg_img[2 + 4 * num_planes + np] = norm_flatness[np][dbg_ml];
Andrey Filippov's avatar
Andrey Filippov committed
5527 5528
					dbg_img[2 + 5 * num_planes + np] = new double[size2];
					dbg_img[2 + 6 * num_planes + np] = attractions[np][dbg_ml];
5529
					dbg_img[2 + 7 * num_planes + np] = new double[size2];
Andrey Filippov's avatar
Andrey Filippov committed
5530 5531
					dbg_img[2 + 8 * num_planes + np] = new double[size2];
					dbg_img[2 + 9 * num_planes + np] = new double[size2];
5532 5533 5534
					for (int i = 0; i < size2; i++) {
						dbg_img[2 + 1 * num_planes + np][i] -= pds[np][0][i];
						dbg_img[2 + 3 * num_planes + np][i] = (num_cells[np][dbg_ml][i] > 1) ? (1.0/flatness[np][dbg_ml][i]): (1.0/disp_var_floor); // floor2);
Andrey Filippov's avatar
Andrey Filippov committed
5535 5536 5537 5538 5539 5540
						dbg_img[2 + 5 * num_planes + np][i] =  mask[np][i] ? 1.0 : 0.0;
						if (all_best_selections != null) {
							dbg_img[2 + 7 * num_planes + np][i] = all_best_selections[np][dbg_ml][i] ? 1.0 : 0.0;
						}
						dbg_img[2 + 8 * num_planes + np][i] = best_selections[np][dbg_ml][i] ? 1.0 : 0.0;
						dbg_img[2 + 9 * num_planes + np][i] = planes[np+1].measuredSelection[dbg_ml][i]? 1.0:0.0; // temporarily
5541

5542 5543 5544 5545 5546
						if (disp_strength[dbg_ml][1][i] == 0.0){
							dbg_img[2 + 1 * num_planes + np][i] = Double.NaN;
							dbg_img[2 + 2 * num_planes + np][i] = Double.NaN;
							dbg_img[2 + 3 * num_planes + np][i] = Double.NaN;
							dbg_img[2 + 5 * num_planes + np][i] = Double.NaN;
Andrey Filippov's avatar
Andrey Filippov committed
5547
							dbg_img[2 + 6 * num_planes + np][i] = Double.NaN;
5548 5549 5550
						}
					}
				}
5551
				ShowDoubleFloatArrays sdfa_instance = new ShowDoubleFloatArrays();
5552 5553 5554 5555 5556
				sdfa_instance.showArrays(dbg_img,     2 * superTileSize, 2 * superTileSize, true, "refine-"+prefix,dbg_titles);
			}
			if (debugLevel > 1)	{
				System.out.println ("refineDiscriminateTiles() "+prefix+" - step 3");
			}
Andrey Filippov's avatar
Andrey Filippov committed
5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568
			// moved here to debug
			if  (merge_planes != null) {
				if ((max_attr_corr > attractionCorrMax) && (max_attr_corr > attractionCorrMerge)) { // attractionCorrMerge can be ==0, then all >..Max will be merged
					tilePlanes.get(merge_pair[0]).getMark0();

					merge_planes[0] = tilePlanes.get(merge_pair[0]).getMark0(); // merge_pair[0];
					merge_planes[1] = tilePlanes.get(merge_pair[1]).getMark0(); // merge_pair[1];
				} else {
					merge_planes[0] = -1;
					merge_planes[1] = -1;
				}
			}
5569

5570
			if (((debugLevel > 0) && ((debugLevel > 1) || (max_attr_corr > attractionCorrMax)) )&& (num_planes > 1)){
Andrey Filippov's avatar
Andrey Filippov committed
5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585
				String dbg_s = "refineDiscriminateTiles() plane attraction correlation for "+prefix+": maximal="+max_attr_corr;
				for (int np = 0; np < num_planes; np++) {
					for (int np1 = np + 1; np1 < num_planes; np1++) {
						dbg_s += String.format(" %d-%d:%6.3f",np,np1,attr_corr[np][np1]);
					}
				}
				if (merge_planes[0] >= 0) {
					dbg_s += " will merge pair: ["+merge_pair[0]+", "+merge_pair[1]+"],"+
							" planes["+tilePlanes.get(merge_pair[0]).getMark0()+"] and"+
							" planes["+tilePlanes.get(merge_pair[1]).getMark0()+"] ";
				} else if (max_attr_corr > attractionCorrMax){
					dbg_s += " KEEPENG original tile selections";
				}
				System.out.println(dbg_s);
			}
5586

Andrey Filippov's avatar
Andrey Filippov committed
5587 5588 5589
			if (max_attr_corr > attractionCorrMax) {
				return null;
			}
5590
			return best_selections;
5591
		}
5592 5593


5594 5595 5596 5597 5598
		// detect and split/eliminate planes that are use disconnected tiles
		// and are not separated by higher disparity planes
		// return planes/selections (no remove outliers!)
		boolean[][][] filterBridges(
				ArrayList<PlaneData> tilePlanes,
5599
				boolean [][]     hor_planes,   // specify which selections correspond to horizontal planes
5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620
				int max_grow_these,
				int max_grow_far,
				int debugLevel)
		{
			double [][] pds = new double [tilePlanes.size()][];
			double [] max_disp = null;
			boolean [][] selections = new boolean[pds.length][];
			final int tsize = 4 * stSize * stSize;
			for (int np = 0; np < pds.length; np++){
				PlaneData pd = tilePlanes.get(np);
				if (pd != null){
					pds[np] = pd.getDoublePlaneDisparityStrength(
							false, // boolean   useWorld,
							null, // double [] window,
							-1, // int       dir,
							false, // boolean   use_sel,
							false, // boolean   divide_by_area,
							1.0, // double    scale_projection,
							0.0, // double    fraction_uni,
							0)[0]; // int       debugLevel)
					if (max_disp == null){
5621
						max_disp = pds[np].clone();
5622 5623 5624 5625 5626 5627 5628 5629 5630
					} else {
						for (int i = 0; i < max_disp.length; i++){
							max_disp[i] = Math.max(max_disp[i], pds[np][i]);
						}
					}
					boolean [][] ms = pd.getMeasSelection(); // should not be null
					// combine selections from all measurement layers
					for (int ml = 0; ml < ms.length; ml++) if (ms[ml] != null){
						if (selections[np] == null) {
5631
							selections[np] = ms[ml].clone();
5632 5633 5634 5635 5636
						} else {
							for (int i = 0; i < ms[ml].length; i++) {
								selections[np][i] |= ms[ml][i];
							}
						}
Andrey Filippov's avatar
Andrey Filippov committed
5637 5638 5639
					}
				}
			}
5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689
			class TileSelections{
				int        np;   // number of original plane
				boolean [] mask; // selection mask to apply to measurement layers
				TileSelections(int nl, boolean [] mask){
					this.np = nl;
					this.mask = mask;
				}
			}
			ArrayList<TileSelections> split_planes = new ArrayList<TileSelections>();
			TileNeibs tileNeibs = new TileNeibs(2 * stSize, 2 * stSize);
			HashSet<Integer> old_planes = new HashSet<Integer>();
			for (int np = 0; np < pds.length; np++){
				PlaneData pd = tilePlanes.get(np);
				if (pd != null){
					old_planes.add(np);
					// see if all the plane tiles have other planes with higher disparity
					boolean all_far = true;
					for (int i = 0; i < max_disp.length; i++)if (selections[np][i]){
						if (pds[np][i] == max_disp[i]){
							all_far = false;
							break;
						}
					}
					if (!all_far){
						boolean [] grown_sel = selections[np].clone();
						tileNeibs.growSelection( //
								max_grow_these,  // int        grow,           // grow tile selection by 1 over non-background tiles 1: 4 directions, 2 - 8 directions, 3 - 8 by 1, 4 by 1 more
								grown_sel, // boolean [] tiles,
								null);      // boolean [] prohibit,
						int [] clusters = tileNeibs.enumerateClusters(
								grown_sel, // boolean [] tiles,
								false); // boolean ordered)

						int num_clusters = tileNeibs.getMax(
								clusters); // int [] data)
						if (num_clusters > 1){
							boolean [] dbg_grown_sel =grown_sel.clone();
							// determine area that should have connections between these clusters, not blocked by known
							// tiles with lower disparity
							boolean [] bound_octo= tileNeibs.boundShape(
									selections[np], // boolean [] selection,
									true); // boolean octo)
							// now combine all "offending" selections - known tiles belonging to farther planes
							boolean [] sel_offend = new boolean[tsize];
							for (int np_other = 0; np_other < pds.length; np_other++) if ((selections[np_other] != null) && (np_other != np)){
								for (int i = 0; i < tsize; i++) if (selections[np_other][i]){
									sel_offend [i] |= (pds[np][i] > pds[np_other][i]);
								}
							}
							// now grow offending selections to fill gaps
5690
							boolean [] dbg_sel_offend = sel_offend.clone();
5691 5692 5693 5694 5695
							tileNeibs.growSelection( //
									max_grow_far,  // int        grow,           // grow tile selection by 1 over non-background tiles 1: 4 directions, 2 - 8 directions, 3 - 8 by 1, 4 by 1 more
									sel_offend, // boolean [] tiles,
									null);      // boolean [] prohibit,
							// create prohibited mask - all not in grown selection that are outside bounding octagon or belong to grown offenders
5696

5697 5698
							boolean [] prohibit = new boolean [tsize];
							for (int i = 0; i < prohibit.length; i++) {
5699
								prohibit[i] = !grown_sel[i] && (!bound_octo[i] || sel_offend[i] ); // (pds[np][i] > max_disp[i]);
5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710
							}
							tileNeibs.growSelection( //
									stSize,     // int        grow,           // grow tile selection by 1 over non-background tiles 1: 4 directions, 2 - 8 directions, 3 - 8 by 1, 4 by 1 more
									grown_sel,  // boolean [] tiles,
									prohibit);      // boolean [] prohibit,
							// re-clusterize what is remaining
							int [] dbg_clusters = clusters.clone();
							clusters = tileNeibs.enumerateClusters(
									grown_sel, // boolean [] tiles,
									false); // boolean ordered)
							num_clusters = tileNeibs.getMax(
5711
									clusters);
5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726
							if (num_clusters > 1){
								boolean [][] cluster_sels = new boolean [num_clusters][selections[np].length];
								for (int i = 0; i < selections[np].length; i++) if (selections[np][i]){
									cluster_sels[clusters[i]-1][i] = true;
								}
								for (int nc = 0; nc < num_clusters; nc++){
									split_planes.add(new TileSelections(np, cluster_sels[nc]));
								}
								old_planes.remove(np);
							}
							if (debugLevel > 2) {
								String [] dbg_titles = {"sel","grown", "clust0","bound","offend","off_grown", "prohibit", "clusters","clus_masked"};
								double [][] dbg_img =  new double [dbg_titles.length][tsize];
								double lon = 3.0;
								for (int i = 0; i < tsize; i++) {
5727 5728 5729 5730 5731 5732 5733 5734 5735
									dbg_img[0][i] = selections[np][i] ? lon: 0.0;
									dbg_img[1][i] = dbg_grown_sel[i] ? lon: 0.0;
									dbg_img[2][i] = dbg_clusters[i];
									dbg_img[3][i] = bound_octo[i] ? lon: 0.0;
									dbg_img[4][i] = dbg_sel_offend[i] ? lon: 0.0;
									dbg_img[5][i] = sel_offend[i] ? lon: 0.0;
									dbg_img[6][i] = prohibit[i] ? lon: 0.0;
									dbg_img[7][i] = clusters[i];
									dbg_img[8][i] = selections[np][i] ? clusters[i] : 0.0;
5736
								}
5737

5738
								ShowDoubleFloatArrays sdfa_instance = new ShowDoubleFloatArrays();
5739 5740 5741 5742 5743 5744
								sdfa_instance.showArrays(dbg_img, 2 * superTileSize, 2* superTileSize, true, "bridges-"+np+"-"+debugLevel,dbg_titles);
								sdfa_instance.showArrays(pds,     2 * superTileSize, 2* superTileSize, true, "pds-bridges-"+np+"-"+debugLevel,dbg_titles);
							}
						}
					}
				}
Andrey Filippov's avatar
Andrey Filippov committed
5745
			}
5746 5747
			if (!split_planes.isEmpty()){
				boolean [][][] split_selections = new boolean [old_planes.size() + split_planes.size()][][];
5748 5749 5750
				if (hor_planes != null) {
					hor_planes[0] = new boolean[old_planes.size() + split_planes.size()];
				}
5751 5752
				int ns = 0;
				for (Integer np: old_planes){
5753 5754 5755
					if (hor_planes != null) {
						hor_planes[0][ns] = tilePlanes.get(np).horizontal || tilePlanes.get(np).isHorizontal();
					}
5756 5757
					split_selections[ns++] = tilePlanes.get(np).getMeasSelection();
				}
5758
				// Split planes have unknown horizontal status
5759
				for (TileSelections ts: split_planes){
5760
//					PlaneData pd = tilePlanes.get(ts.np);
5761 5762 5763 5764 5765 5766 5767 5768 5769 5770
					boolean [][] ms = tilePlanes.get(ts.np).getMeasSelection().clone();
					for (int ml = 0; ml < ms.length; ml++) if (ms[ml] != null){
						ms[ml] = ms[ml].clone();
						for (int i = 0; i < ms[ml].length; i++){
							ms[ml][i] &= ts.mask[i];
						}
					}
					split_selections[ns++] = ms;
				}
				return split_selections;
5771

Andrey Filippov's avatar
Andrey Filippov committed
5772
			}
5773 5774 5775 5776 5777 5778 5779 5780 5781
			return null; // no changes
		}

		public double [] getWindow (
				int size)
		{
			double [] wnd1d = new double [size];
			for (int i = 0; i < size/2; i++){
				wnd1d[i] = 0.5 * (1.0 - Math.cos(2*Math.PI*(i+0.5)/size));
5782
				wnd1d[size - i -1] = wnd1d[i];
5783 5784 5785 5786 5787 5788 5789
			}
			double [] wnd = new double [size * size];
			int indx = 0;
			for (int i = 0; i < size; i++){
				for (int j = 0; j < size; j++){
					wnd[indx++] = wnd1d[i]*wnd1d[j];
				}
5790
			}
5791
			return wnd;
Andrey Filippov's avatar
Andrey Filippov committed
5792
		}
5793

5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826
		public boolean isWeakForeground(
				final PlaneData fg_plane,
//				final int stMeasSel, //            = 1;      // Select measurements for supertiles : +1 - combo, +2 - quad +4 - hor +8 - vert
				final int outliers,  // remove any glitches?
				double min_fg_strength,
				final int debugLevel)
		{
			double [][] bg_ds = getDoublePlaneDisparityStrength(
					false, // boolean   useWorld,
					null, // double [] window,
					-1, // int       dir,
					false, // boolean   use_sel,
					false, // boolean   divide_by_area,
					1.0, // double    scale_projection,
					0.0, // double    fraction_uni,
					0); // int       debugLevel)
			double [][] fg_ds = fg_plane.getDoublePlaneDisparityStrength(
					false, // boolean   useWorld,
					null, // double [] window,
					-1, // int       dir,
					false, // boolean   use_sel,
					false, // boolean   divide_by_area,
					1.0, // double    scale_projection,
					0.0, // double    fraction_uni,
					0); // int       debugLevel)
			boolean [][] fg_sel = fg_plane.getMeasSelection();
			for (int ml = 0; ml < fg_sel.length; ml++) if (fg_sel[ml] != null){ // if ((stMeasSel & ( 1 << ml)) != 0){
				for (int indx = 0; indx < bg_ds[0].length; indx++) if (fg_sel[ml][indx]) {
					if (fg_ds[0][indx] < bg_ds[0][indx]) {
						return false;  // not a foreground
					}
				}
			}
5827

5828
			// it is foreground, now get measured data and find maximal strength (remove outliers?
5829 5830 5831
			double [] lap_weights = measuredLayers.getLapWeights1d();
			double [][][] disp_strength = new double[measuredLayers.getNumLayers()][][];
			for (int ml = 0; ml < disp_strength.length; ml++) if (fg_sel[ml] != null){ //  if ((stMeasSel & ( 1 << ml)) != 0) {
5832
				if (this.smplMode) {
5833
					disp_strength[ml] = measuredLayers.getDisparityStrengthMLTilted( // expensive to calculate (improve removing outliers
5834 5835 5836
							ml, // int num_layer,
							getSTileXY()[0],        // int stX,
							getSTileXY()[1],        // int stY,
5837
							null,                   // boolean [] sel_in, - use all
5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851
							this.mlfp,
//							strength_floor,
//							measured_strength_pow,  //
//							smplSide,               // = 2;      // Sample size (side of a square)
//							smplNum,                // = 3;      // Number after removing worst
//							smplRms,                // = 0.1;    // Maximal RMS of the remaining tiles in a sample
//							smplWnd,                // use window functions for the samples
//							max_abs_tilt,           // 2.0; // Maximal absolute tilt in pixels/tile
//							max_rel_tilt,           // 0.2; // Maximal relative tilt in pixels/tile/disparity
//							damp_tilt,              //    0.001; // Damp tilt to handle insufficient  (co-linear)data
//							min_tilt_disp,          // 4.0; // Disparity switch between filtering modes - near objects use tilts, far - use max disparity
//							transition,             // 1.0; // Mode transition range (between tilted and maximal disparity)
//							far_mode,               //     1;   // Far objects filtering mode (0 - off, 1 - power of disparity)
//							far_power,              //    1.0; // Raise disparity to this power before averaging for far objects
5852
							true,                   // boolean null_if_none)
5853
							debugLevel);
5854
				} else {
Andrey Filippov's avatar
Andrey Filippov committed
5855
					disp_strength[ml] = measuredLayers.getDisparityStrengthML(
5856 5857 5858 5859
							ml,                     // int num_layer,
							getSTileXY()[0],        // int stX,
							getSTileXY()[1],        // int stY,
							null,                   // boolean [] sel_in, - use all
5860 5861 5862
							this.mlfp,
//							strength_floor,         //  double strength_floor,
//							measured_strength_pow,  // double strength_pow,
5863 5864 5865 5866 5867
							true);                  // boolean null_if_none);
				}
			}
			ArrayList<Double> fg_strengths = new ArrayList<Double>();
			for (int ml = 0; ml < disp_strength.length; ml++)  if (fg_sel[ml] != null){ //  if ((stMeasSel & ( 1 << ml)) != 0) {
5868
				double [] strength = disp_strength[ml][1];
5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887
				for (int indx = 0; indx < strength.length; indx ++)  if (fg_sel[ml][indx]) {
					fg_strengths.add(strength[indx]/lap_weights[indx]); // strengths were already masked by a window
				}
			}
			if (fg_strengths.isEmpty()){
				return true; // should not happen, but it is OK to merge empty plane
			}
			Collections.sort(fg_strengths);
			int indx = fg_strengths.size() - outliers -1;
			if (indx < 0) indx = 0;
			if (debugLevel > 0) {
				if (fg_strengths.get(indx) >= min_fg_strength) {
					System.out.println("strong pair: "+fg_strengths.get(indx)+" >= "+min_fg_strength);
				} else {
					System.out.println("weak pair: "+fg_strengths.get(indx)+" < "+min_fg_strength);
				}
			}
			return (fg_strengths.get(indx) < min_fg_strength);
		}
Andrey Filippov's avatar
Andrey Filippov committed
5888 5889
	}
}