MeasuredLayers.java 53.5 KB
Newer Older
1
package com.elphel.imagej.tileprocessor;
2 3 4

import com.elphel.imagej.common.PolynomialApproximation;

Andrey Filippov's avatar
Andrey Filippov committed
5 6 7
/**
 ** MeasuredLayer - per-tile measured disparity/strength pairs,
 ** multiple layers can be used for 4-disparity and 2 (hor/vert) pairs
8
 ** separately
Andrey Filippov's avatar
Andrey Filippov committed
9 10 11 12
 **
 ** Copyright (C) 2017 Elphel, Inc.
 **
 ** -----------------------------------------------------------------------------**
13
 **
Andrey Filippov's avatar
Andrey Filippov committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
 **  MeasuredLayer.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/>.
 ** -----------------------------------------------------------------------------**
 **
 */

public class MeasuredLayers {
	private DispStrength [][] layers;
	private int tilesX;
	private int tilesY;
	private int superTileSize;
	private double [][] lapWeight = null;
	public class DispStrength {
		public double disparity = Double.NaN;
		public double strength =  0.0;
		public DispStrength (
				double disparity,
				double strength)
		{
			this.disparity = disparity;
			this.strength = strength;
			if (Double.isNaN(disparity)){
				this.strength = 0.0;
			}
		}
		public double [] getDispStrength()
		{
			double [] ds = {disparity, strength};
			return ds;
		}
		public void setDisparity(double disparity)
		{
			this.disparity = disparity;
			if (Double.isNaN(disparity)){
				this.strength = 0.0;
			}
		}
		public void setStrength(double strength)
		{
			this.strength = strength;
		}
		public double getDisparity()
		{
			return disparity;
		}
		public double getStrength()
		{
			return strength;
		}
	}
	/**
	 * Create a set of measured layers. Several layers can be used to represent alternative measurements
	 * (with different preset disparity) or for different modes (4 pair correlation, vertical, horizontal)
	 * @param num_layers number of alternative layers used (3 for quad, hor, vert)
	 * @param tilesX number of tiles horizontally in the image
	 * @param tilesY number of tiles vertically in the image
	 * @param superTileSize size of the supertile square
	 */
	public MeasuredLayers(
			int num_layers,
			int tilesX,
			int tilesY,
			int superTileSize)
	{
		layers = new DispStrength [num_layers][];
		this.tilesX = tilesX;
		this.tilesY = tilesY;
		this.superTileSize = superTileSize;
		this.lapWeight =  getLapWeights();
	}
94

Andrey Filippov's avatar
Andrey Filippov committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
	/**
	 * Get number of tiles in the image horizontally
	 * @return tilesX
	 */
	public int getTilesX()
	{
			return tilesX;
	}

	/**
	 * Get number of tiles in the image vertically
	 * @return tilesY
	 */
	public int getTilesY()
	{
			return tilesY;
	}
	/**
	 * Get number of tiles in each supertile in eac direction
	 * @return superTileSize
	 */

	public int getSuperTileSize()
	{
			return superTileSize;
	}
121

Andrey Filippov's avatar
Andrey Filippov committed
122
	/**
123
	 * Set measured layer
Andrey Filippov's avatar
Andrey Filippov committed
124 125
	 * @param num_layer number of the layer to set
	 * @param disparity array of per-tile disparity values (linescan order),
126
	 *  NaN deletes the tile
Andrey Filippov's avatar
Andrey Filippov committed
127 128
	 * @param strength array of per-tile disparity values (linescan order),
	 *  0.0 strength is OK - does not delete the tile
129
	 * @param selection optional tile selection (or null). If unselected, tile is deleted
Andrey Filippov's avatar
Andrey Filippov committed
130 131 132 133 134 135
	 */
	public void setLayer (
			int       num_layer,
			double [] disparity,
			double [] strength,
			boolean [] selection) // may be null
136
	{
Andrey Filippov's avatar
Andrey Filippov committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
		if (layers[num_layer] == null) {
			int llen = disparity.length;
			if (layers[num_layer] == null) {
				layers[num_layer] = new DispStrength [llen];
			}
		}
		for (int i = 0; i < disparity.length; i++){
			if ((selection != null) && !selection[i]){
				layers[num_layer][i] = null;
			} else {
				if (Double.isNaN(disparity[i])){
					layers[num_layer][i] = null;
				} else {
					if (layers[num_layer][i] != null){
						layers[num_layer][i].setDisparity(disparity[i]);
						layers[num_layer][i].setStrength(strength[i]);
					} else {
						layers[num_layer][i] = new DispStrength(disparity[i], strength[i]);
					}
				}
			}
		}
	}
160

Andrey Filippov's avatar
Andrey Filippov committed
161
	/**
162
	 * Set disparity values for selected measurement layer
Andrey Filippov's avatar
Andrey Filippov committed
163 164
	 * @param num_layer number of the layer to set
	 * @param disparity array of per-tile disparity values (linescan order),
165
	 *  NaN deletes the tile. New tile set strength = 0.0
Andrey Filippov's avatar
Andrey Filippov committed
166 167 168 169
	 */
	public void setDisparity (
			int       num_layer,
			double [] disparity)
170
	{
Andrey Filippov's avatar
Andrey Filippov committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
		if (layers[num_layer] == null) {
			int llen = disparity.length;
			if (layers[num_layer] == null) {
				layers[num_layer] = new DispStrength [llen];
			}
		}
		for (int i = 0; i < disparity.length; i++){
			if (Double.isNaN(disparity[i])){
				layers[num_layer][i] = null;
			} else {
				if (layers[num_layer][i] != null){
					layers[num_layer][i].setDisparity(disparity[i]);
				} else {
					layers[num_layer][i] = new DispStrength(disparity[i], 0.0);
				}
			}
		}
	}

	/**
	 * Set strength values for selected measurement layer. Does not allocate new tiles
192
	 * if that element was null
Andrey Filippov's avatar
Andrey Filippov committed
193 194 195 196 197 198
	 * @param num_layer number of the layer to set
	 * @param strength array of per-tile strength values (linescan order)
	 */
	public void setStrength (
			int       num_layer,
			double [] strength)
199
	{
Andrey Filippov's avatar
Andrey Filippov committed
200 201 202 203 204 205 206 207
		if (layers[num_layer] != null) {
			for (int i = 0; i < strength.length; i++){
				if (layers[num_layer][i] != null){
					layers[num_layer][i].setStrength(strength[i]);
				}
			}
		}
	}
208

Andrey Filippov's avatar
Andrey Filippov committed
209 210 211 212 213 214 215 216 217
	/**
	 * Change tile selection for the layer. Can only unselect existing tiles, not add new ones
	 * @param num_layer number of the layer to set
	 * @param selection array of per-tile boolean selection values (linescan order),
	 */

	public void setSelection (
			int       num_layer,
			boolean [] selection)
218
	{
Andrey Filippov's avatar
Andrey Filippov committed
219 220 221 222 223 224
		for (int i = 0; i < selection.length; i++){
			if (!selection[i]){
				layers[num_layer][i] = null;
			}
		}
	}
225

Andrey Filippov's avatar
Andrey Filippov committed
226 227 228 229
	/**
	 * Get total number of the measurement layers in this object
	 * @return number of layers (some may be uninitialized
	 */
230

231
	public int getNumLayers()
Andrey Filippov's avatar
Andrey Filippov committed
232 233 234 235 236 237 238 239 240 241 242 243
	{
		if (layers == null){
			return 0;
		} else {
			return layers.length;
		}
	}

	/**
	 * Get array of disparity values for the selected layer
	 * @param num_layer number of the layer to read
	 * @return array of per-tile disparity values (in linescan order),
244
	 *  Double.NaN for missing tiles
Andrey Filippov's avatar
Andrey Filippov committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258
	 */
	public double [] getDisparity(
			int num_layer)
	{
		double [] disparity = new double [layers[num_layer].length];
		for (int i = 0; i < disparity.length; i++){
			if (layers[num_layer][i] == null){
				disparity[i] = Double.NaN;
			} else {
				disparity[i] = layers[num_layer][i].getDisparity();
			}
		}
		return disparity;
	}
259

Andrey Filippov's avatar
Andrey Filippov committed
260 261 262 263
	/**
	 * Get array of correlation strength values for the selected layer
	 * @param num_layer number of the layer to read
	 * @return array of per-tile strength values (in linescan order),
264
	 * 0.0 for missing tiles
Andrey Filippov's avatar
Andrey Filippov committed
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
	 */

	public double [] getStrength(
			int num_layer)
	{
		double [] strength = new double [layers[num_layer].length];
		for (int i = 0; i < strength.length; i++){
			if (layers[num_layer][i] == null){
				strength[i] = 0.0;
			} else {
				strength[i] = layers[num_layer][i].getStrength();
			}
		}
		return strength;
	}
280

Andrey Filippov's avatar
Andrey Filippov committed
281 282 283 284 285 286 287 288 289 290
	/**
	 * Get array of existing tiles for the selected layer
	 * @param num_layer number of the layer to read
	 * @return boolean (per tile) array of existing tiles
	 */
	public boolean [] getSelection(
			int num_layer)
	{
		boolean [] selection = new boolean [layers[num_layer].length];
		for (int i = 0; i < selection.length; i++){
291
			selection[i] = layers[num_layer][i] != null;
Andrey Filippov's avatar
Andrey Filippov committed
292 293 294
		}
		return selection;
	}
295

Andrey Filippov's avatar
Andrey Filippov committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309
	/**
	 * Calculate weights for overlapping supertiles to multiply correlation strengths
	 * @return square 2-d array of weights 0.0 ... 1.0, each dimension twice the
	 * supertile size
	 */
	private double [][] getLapWeights(){
		final double [][] lapWeight = new double [2 * superTileSize][2 * superTileSize];
		final double [] lapWeight1d = new double [superTileSize];
		final int superTileSize2 = 2 * superTileSize;
		for (int i = 0; i < superTileSize; i++){
			lapWeight1d[i] = 0.5*(1.0 - Math.cos((i + 0.5)* Math.PI/superTileSize));
		}
		for (int i = 0; i < superTileSize; i++){
			for (int j = 0; j < superTileSize; j++){
310
				lapWeight[i]                     [                     j] = lapWeight1d[i]*lapWeight1d[j];
Andrey Filippov's avatar
Andrey Filippov committed
311
				lapWeight[superTileSize2 - 1 - i][                     j] = lapWeight[i][j];
312 313
				lapWeight[i]                     [superTileSize2 - 1 - j] = lapWeight[i][j];
				lapWeight[superTileSize2 - 1 - i][superTileSize2 - 1 - j] = lapWeight[i][j];
Andrey Filippov's avatar
Andrey Filippov committed
314 315 316 317 318 319 320 321 322 323 324
			}
		}
		double s = 0.0;
		for (int i = 0; i < superTileSize2; i++){
			for (int j = 0; j < superTileSize2; j++){
				s+=lapWeight[i][j];
			}
		}
		System.out.println("getLapWeights: sum = "+s);
		return lapWeight;
	}
325

326 327 328 329 330 331 332 333 334 335 336
	public double [] getLapWeights1d(){
		int indx = 0;
		final int superTileSize2 = 2 * superTileSize;
		double [] weights = new double [superTileSize2 * superTileSize2];
		for (int i = 0; i < superTileSize2; i++){
			for (int j = 0; j < superTileSize2; j++){
				weights[indx++] = lapWeight[i][j];
			}
		}
		return weights;
	}
337

338 339 340 341 342
	/**
	 * Get window function for tile samples (currently just 3x3) in a line-scan order
	 * @param smplSide square sample side
	 * @return [smplSide * smplSide]array of weights, 1.0 in the center
	 */
343

344
	static double [] getSampleWindow(int smplSide, boolean all1){
345 346 347 348 349 350 351 352
		double [] weights = new double [smplSide * smplSide];
		for (int sy = 0; sy < smplSide; sy++){
			for (int sx = 0; sx < smplSide; sx++){
				weights[sy * smplSide + sx] = all1? 1.0 : Math.sin(Math.PI*(sy+0.5)/smplSide) * Math.sin(Math.PI*(sx+0.5)/smplSide);
			}
		}
		return weights;
	}
353 354 355



Andrey Filippov's avatar
Andrey Filippov committed
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
	/**
	 * Get selection for the specific measurement layer and supertile X,Y coordinates
	 * in the image. Combined with input selection
	 * @param num_layer number of the measurement layer to process
	 * @param stX supertile horizontal position in the image
	 * @param stY supertile vertical position in the image
	 * @param sel_in optional selection for this supertile (linescan, 4 * supetile size)
	 * @param null_if_none return null if there are no selected tiles in teh result selection
	 * @return boolean array [4*superTileSize] of the selected tiles on the specified
	 * measurement layer
	 */
	public boolean [] getSupertileSelection(
			int num_layer,
			int stX,
			int stY,
			boolean [] sel_in,
			double     strength_floor,
			boolean null_if_none)
	{
		if ((layers[num_layer] == null) && null_if_none){
			return null;
		}
		int st2 = 2 * superTileSize;
		int st_half = superTileSize/2;
		boolean [] selection = new boolean [st2 * st2];
		int num_selected = 0;
		if (layers[num_layer] != null) {
			for (int dy = 0; dy < st2; dy ++){
				int y = superTileSize * stY -st_half + dy;
				if ((y >= 0) && (y < tilesY)) {
					for (int dx = 0; dx < st2; dx ++){
						int x = superTileSize * stX -st_half + dx;
						if ((x >= 0) && (x < tilesX)) {
							int indx = y * tilesX + x;
							int indx_st = dy * st2 + dx;
391
							if (((sel_in == null) || sel_in[indx_st]) &&
Andrey Filippov's avatar
Andrey Filippov committed
392 393 394 395 396 397 398 399 400 401 402 403 404
									(layers[num_layer][indx] != null) &&
									(layers[num_layer][indx].getStrength() >= strength_floor)){
								selection[indx_st] = true;
								num_selected ++;
							}
						}
					}
				}
			}
		}
		if (null_if_none && (num_selected == 0)) return null;
		return selection;
	}
405

Andrey Filippov's avatar
Andrey Filippov committed
406 407 408 409 410 411 412 413 414 415 416

	/**
	 * Get selection for the specific measurement layer and supertile X,Y coordinates
	 * in the image and combine with disparity far/near limits. Alse combined with
	 * input selection
	 * @param num_layer number of the measurement layer to process
	 * @param stX supertile horizontal position in the image
	 * @param stY supertile vertical position in the image
	 * @param sel_in optional selection for this supertile (linescan, 4 * supetile size)
	 * @param disp_far lowest acceptable disparity value. Double.NaN - do not check.
	 * @param disp_near highest acceptable disparity value. Double.NaN - do not check.
417
	 * @param null_if_none return null if there are no selected tiles in the result selection
Andrey Filippov's avatar
Andrey Filippov committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
	 * @return boolean array [4*superTileSize] of the selected tiles on the specified
	 * measurement layer
	 */
	public boolean [] getSupertileSelection(
			int        num_layer,
			int        stX,
			int        stY,
			boolean [] sel_in,
			double     disp_far,
			double     disp_near,
			double     strength_floor,
			boolean    null_if_none)
	{
		if ((layers[num_layer] == null) && null_if_none){
			return null;
		}
		int st2 = 2 * superTileSize;
		int st_half = superTileSize/2;
		boolean [] selection = new boolean [st2 * st2];
		int num_selected = 0;
		if (layers[num_layer] != null) {
			for (int dy = 0; dy < st2; dy ++){
				int y = superTileSize * stY -st_half + dy;
				if ((y >= 0) && (y < tilesY)) {
					for (int dx = 0; dx < st2; dx ++){
						int x = superTileSize * stX -st_half + dx;
						if ((x >= 0) && (x < tilesX)) {
							int indx = y * tilesX + x;
							int indx_st = dy * st2 + dx;
							if (((sel_in == null) || sel_in[indx_st]) && (layers[num_layer][indx] != null)){
								if (    (Double.isNaN(disp_far)  || (layers[num_layer][indx].getDisparity() >= disp_far)) &&
										(Double.isNaN(disp_near) || (layers[num_layer][indx].getDisparity() <= disp_near)) &&
										(layers[num_layer][indx].getStrength() >= strength_floor)){
									selection[indx_st] = true;
									num_selected ++;
								}
							}
						}
					}
				}
			}
		}
		if (null_if_none && (num_selected == 0)) return null;
		return selection;
	}
463

464 465 466 467
	/**
	 * Get selection when disparity/strength is already calculated. Useful when
	 * disparity/strength are not just measured values, by sampled over an area
	 * @param disparityStrength array of {disparity, strength} where each is
468
	 *  a linescan data of the (2 * superTileSize) * (2 * superTileSize)
469 470 471 472 473
	 * @param sel_in optional input selection array or null - use all
	 * @param null_if_none return null if selection has no tiles enabled
	 * @return boolean array of per-tile enabled/disabled values in linescan
	 *  order, (2 * superTileSize) * (2 * superTileSize)
	 */
Andrey Filippov's avatar
Andrey Filippov committed
474

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
	public boolean [] getSupertileSelection(
			double [][] disparityStrength,
			boolean [] sel_in,
			boolean null_if_none)
	{
		int st2 = 2 * superTileSize;
		boolean [] selection = new boolean [st2 * st2];
		int num_selected = 0;
		for (int i = 0; i < disparityStrength[1].length; i++){
			if (	(disparityStrength[1][i] > 0.0) &&
					((sel_in == null) || (sel_in[i]))){
				selection[i] = true;
				num_selected ++;
			}
		}
490

491 492 493
		if (null_if_none && (num_selected == 0)) return null;
		return selection;
	}
494

495 496 497 498 499
	/**
	 * Get selection when disparity/strength is already calculated. Useful when
	 * disparity/strength are not just measured values, by sampled over an area
	 * Includes low/high limits for disparity values
	 * @param disparityStrength array of {disparity, strength} where each is
500
	 *  a linescan data of the (2 * superTileSize) * (2 * superTileSize)
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
	 * @param sel_in optional input selection array or null - use all
	 * @param disp_far low limit for disparity, Double.NaN - do not check
	 * @param disp_near high limit for disparity, Double.NaN - do not check
	 * @param null_if_none return null if selection has no tiles enabled
	 * @return boolean array of per-tile enabled/disabled values in linescan
	 *  order, (2 * superTileSize) * (2 * superTileSize)
	 * @return
	 */
	public boolean [] getSupertileSelection(
			double [][] disparityStrength,
			boolean [] sel_in,
			double     disp_far,
			double     disp_near,
			boolean null_if_none)
	{
		int st2 = 2 * superTileSize;
		boolean [] selection = new boolean [st2 * st2];
		int num_selected = 0;
		for (int i = 0; i < disparityStrength[1].length; i++){
			if (	(disparityStrength[1][i] > 0.0) &&
					((sel_in == null) || (sel_in[i]))){
				if (    (Double.isNaN(disp_far)  || (disparityStrength[0][i] >= disp_far)) &&
						(Double.isNaN(disp_near) || (disparityStrength[0][i] <= disp_near))) {
524

525 526 527 528 529
				}
				selection[i] = true;
				num_selected ++;
			}
		}
530

531 532 533
		if (null_if_none && (num_selected == 0)) return null;
		return selection;
	}
534 535 536 537




Andrey Filippov's avatar
Andrey Filippov committed
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
	/**
	 * Get number of "true" elements in a boolean array. Null is OK, it results in 0
	 * @param selected boolean array to count set elements in
	 * @return number of selected elements
	 */
	public static int getNumSelected(
			boolean [] selected)
	{
		if (selected == null) return 0;
		int num_selected = 0;
		for (int i = 0; i < selected.length; i++){
			if (selected[i]) num_selected ++;
		}
		return num_selected;
	}

	public static double getSumStrength(
			double [][] disp_strength)
	{
		if (disp_strength == null) return 0.0;
		double sw = 0.0;
		for (int i = 0; i < disp_strength[1].length; i++){
			sw += disp_strength[1][i];
		}
		return sw;
	}
564 565 566 567 568 569 570 571 572 573 574 575 576
	public static double getSumStrength(
			double [][] disp_strength,
			boolean [] selected)
	{
		if (disp_strength == null) return 0.0;
		double sw = 0.0;
		for (int i = 0; i < disp_strength[1].length; i++){
			if ((selected == null) || selected[i]) {
				sw += disp_strength[1][i];
			}
		}
		return sw;
	}
577

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
	public double[][] getDisparityStrengthML (
			int num_layer,
			int stX,
			int stY,
			boolean [] sel_in,
			MeasuredLayersFilterParameters mlfp,
			boolean null_if_none){
		return getDisparityStrengthML(
				num_layer,
				stX,
				stY,
				sel_in,
				mlfp.strength_floor,
				mlfp.strength_pow,
				null_if_none);
	}

Andrey Filippov's avatar
Andrey Filippov committed
595 596 597 598 599 600 601
	/**
	 * Get disparity and correlation strength for the specific measurement layer and
	 * supertile X,Y coordinates in the image. Combined with input selection
	 * @param num_layer number of the measurement layer to process
	 * @param stX supertile horizontal position in the image
	 * @param stY supertile vertical position in the image
	 * @param sel_in optional selection for this supertile (linescan, 4 * supetile size)
602
	 * @param strength_floor subtract from the correlation strength, limit by 0
Andrey Filippov's avatar
Andrey Filippov committed
603
	 * @param strength_pow Non-linear treatment of correlation strength. Raise data to the strength_pow power
604
	 * @param null_if_none return null if there are no selected tiles in the result selection
Andrey Filippov's avatar
Andrey Filippov committed
605 606 607
	 * @return double [2][4*superTileSize] {disparity[4*superTileSize], strength [4*superTileSize]}
	 */

Andrey Filippov's avatar
Andrey Filippov committed
608
	public double[][] getDisparityStrengthML (
Andrey Filippov's avatar
Andrey Filippov committed
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
			int num_layer,
			int stX,
			int stY,
			boolean [] sel_in,
			double strength_floor,
			double strength_pow,
			boolean null_if_none)
	{
		if ((layers[num_layer] == null) && null_if_none){
			return null;
		}
		int st2 = 2 * superTileSize;
		int st_half = superTileSize/2;
		double [][] ds = new double [2][st2*st2];
		int num_selected = 0;
		if (layers[num_layer] != null) {
			for (int dy = 0; dy < st2; dy ++){
				int y = superTileSize * stY -st_half + dy;
				if ((y >= 0) && (y < tilesY)) {
					for (int dx = 0; dx < st2; dx ++){
						int x = superTileSize * stX -st_half + dx;
						if ((x >= 0) && (x < tilesX)) {
							int indx = y * tilesX + x;
							int indx_st = dy * st2 + dx;
							if (((sel_in == null) || sel_in[indx_st]) && (layers[num_layer][indx] != null)){
								ds[0][indx_st] = layers[num_layer][indx].getDisparity();
								double w = layers[num_layer][indx].getStrength() - strength_floor;
								if (w > 0) {
									if (strength_pow != 1.0) w = Math.pow(w, strength_pow);
									w *= lapWeight[dy][dx];
									ds[0][indx_st] = layers[num_layer][indx].getDisparity();
									ds[1][indx_st] = w;
									num_selected ++;
								}
							}
						}
					}
				}
			}
		}
		if (null_if_none && (num_selected == 0)) return null;
		return ds;
	}
652

653 654 655 656 657 658 659 660 661 662 663
	public double[][] getDisparityStrengthML (
			int num_layer,
			MeasuredLayersFilterParameters mlfp){

		return getDisparityStrengthML(
				num_layer,
				mlfp.strength_floor,
				mlfp.strength_pow);
	}


664 665 666 667 668 669 670 671 672
	/**
	 * Get disparity and correlation strength for the specific measurement layer.
	 * Combined with input selection
	 * @param num_layer number of the measurement layer to process
	 * @param strength_floor subtract from the correlation strength, limit by 0
	 * @param strength_pow Non-linear treatment of correlation strength. Raise data to the strength_pow power
	 * @return double {disparity[tilesX * tilesY], strength[tilesX * tilesY]}
	 */

Andrey Filippov's avatar
Andrey Filippov committed
673
	public double[][] getDisparityStrengthML (
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
			int num_layer,
			double strength_floor,
			double strength_pow)
	{
		if (layers[num_layer] == null){
			return null;
		}
		double [][] ds = {getDisparity(num_layer),getStrength(num_layer)};
		for (int i = 0; i < ds[1].length; i++){
			double w = ds[1][i] - strength_floor;
			if (w > 0) {
				if (strength_pow != 1.0) w = Math.pow(w, strength_pow);
				ds[1][i] = w;
			} else {
				ds[1][i] = 0.0;
			}
		}

		return ds;
	}
694 695 696 697




698 699 700 701
	/**
	 * Get double-size  (for overlapping) array of disparities and strengths for the supertile
	 * Using best (producing lowest disparity variance) subset of neighbor tiles
	 * @param num_layer number of measurement layer (currently 0 - composite, 1 - quad, 2 - horizontal
Andrey Filippov's avatar
Andrey Filippov committed
702
	 * and 3 - vertical pairs correlation
703 704 705 706 707 708 709
	 * @param stX supertile horizontal index
	 * @param stY supertile vertical index
	 * @param sel_in input selection of the output data samples (or null)
	 * @param strength_floor subtract from the correlation strength (limit by 0) before using as a
	 *  sample weight
	 * @param strength_pow raise correlation strength (after subtracting strength_floor) to this power
	 *  to use as a sample weight
710 711
	 * @param smplSide size of the square sample side
	 * @param smplNum number of averaged samples (should be <= smplSide * smplSide and > 1)
712 713
	 * @param smplRms maximal square root of variance (in disparity pixels) to accept the result
	 * @param null_if_none return null if there are no usable tiles in the result
714 715
	 * @param smplWnd multiply samples weights by a window function
	 * @param debugLevel debug level
716 717
	 * @return a pair of arrays (disparity and strengths) in line-scan order each
	 */
718
	public double[][] getDisparityStrength_old (
719 720 721 722
			int num_layer,
			int stX,
			int stY,
			boolean [] sel_in,
723 724 725 726 727 728 729
			MeasuredLayersFilterParameters mlfp,
//			double     strength_floor,
//			double     strength_pow,
//			int        smplSide, //        = 2;      // Sample size (side of a square)
//			int        smplNum, //         = 3;      // Number after removing worst (should be >1)
//			double     smplRms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
//			boolean    smplWnd, //
730 731
			boolean    null_if_none,
			int        debugLevel)
732 733 734 735 736 737 738
	{
		if ((layers[num_layer] == null) && null_if_none){
			return null;
		}
		int st2 = 2 * superTileSize;
		int st_half = superTileSize/2;
		double [][] ds = new double [2][st2*st2];
739
		final int dbg_tile = -1; // = ((stX == 22) && (stY == 19)) ? (5 + 7*16) : -1;// 50397;
740

741
		int num_selected = 0;
742 743 744 745
		int smpl_center = mlfp.smplSide /2;
		int st2e = st2 + mlfp.smplSide;
		int smplLen = mlfp.smplSide*mlfp.smplSide;
		final double [] smpl_weights = getSampleWindow(mlfp.smplSide, !mlfp.smplWnd);
746 747 748

		double [] disp =     new double [st2e * st2e];
		double [] weight = new double [st2e * st2e];
749
		int st_halfe = st_half + smpl_center;
750
		double smplVar = mlfp.smplRms * mlfp.smplRms; // maximal variance (weighted average of the squared difference from the mean)
751 752


753 754 755 756 757 758 759 760 761
		if (layers[num_layer] != null) {
			for (int dy = 0; dy < st2e; dy ++){
				int y = superTileSize * stY -st_halfe + dy;
				if ((y >= 0) && (y < tilesY)) {
					for (int dx = 0; dx < st2e; dx ++){
						int x = superTileSize * stX -st_halfe + dx;
						if ((x >= 0) && (x < tilesX)) {
							int indx = y * tilesX + x;
							int indx_ste = dy * st2e + dx;
762

763 764
							if (layers[num_layer][indx] != null){ // apply sel_in later
								disp[indx_ste] = layers[num_layer][indx].getDisparity();
765
								double w = layers[num_layer][indx].getStrength() - mlfp.strength_floor;
766
								if (w > 0) {
767
									if (mlfp.strength_pow != 1.0) w = Math.pow(w, mlfp.strength_pow);
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
//									w *= lapWeight[dy][dx];
									disp[indx_ste] = layers[num_layer][indx].getDisparity();
									weight[indx_ste] = w;
									num_selected ++;
								}
							}
						}
					}
				}
			}
		}
		if (null_if_none && (num_selected == 0)) return null;
		// now work with disp, strength [st2e*st2de] and filter results to ds[2][st2*st2], applying sel_in
		num_selected = 0;
		for (int dy = 0; dy < st2; dy ++){
			for (int dx = 0; dx < st2; dx ++){
				int indx = dy * st2 + dx;
785
				if (indx == dbg_tile){
Andrey Filippov's avatar
Andrey Filippov committed
786
					System.out.println("getDisparityStrengthML(): stX="+stX+" stY="+stY+" dx="+dx+" dy="+dy);
787
				}
788 789
				if (((sel_in == null) || sel_in[indx])){
					int num_in_sample = 0;
790
					double sum_wnd = 0.0;
791 792 793
					boolean [] smpl_sel = new boolean [smplLen];
					double [] smpl_d =  new double [smplLen];
					double [] smpl_w =  new double [smplLen];
794
					for (int sy = 0; sy < mlfp.smplSide; sy++){
795
						int y = dy + sy; //  - smpl_center;
796
						for (int sx = 0; sx < mlfp.smplSide; sx++){
797 798 799
							int x = dx + sx; // - smpl_center;
							int indxe = y * st2e + x;
							if (weight[indxe] > 0.0){
800
								int indxs = sy * mlfp.smplSide + sx;
801
								smpl_sel[indxs] = true;
802 803
								smpl_d[indxs] = disp[indxe];
								smpl_w[indxs] = weight[indxe] * smpl_weights[indxs];
804
								sum_wnd += smpl_weights[indxs];
805 806 807 808
								num_in_sample ++;
							}
						}
					}
809
					if (num_in_sample >= mlfp.smplNum){ // try, remove worst
810
						// calculate
811 812 813 814 815 816 817 818
						double sd=0.0, sd2 = 0.0, sw = 0.0;
						for (int i = 0; i < smplLen; i++) if (smpl_sel[i]) {
							double dw = smpl_d[i] * smpl_w[i];
							sd += dw;
							sd2 += dw * smpl_d[i];
							sw +=       smpl_w[i];
						}
						// remove worst, update sd2, sd and sw
819
						while ((num_in_sample > mlfp.smplNum) && (sw > 0)){ // try, remove worst
820 821 822 823 824 825 826 827 828 829 830 831
							double d_mean = sd/sw;
							int iworst = -1;
							double dworst2 = 0.0;
							for (int i = 0; i < smplLen; i++) if (smpl_sel[i]) {
								double d2 = (smpl_d[i] - d_mean);
								d2 *=d2;
								if (d2 > dworst2) {
									iworst = i;
									dworst2 = d2;
								}
							}
							if (iworst < 0){
832
								System.out.println("**** this is a BUG1 in getDisparityStrengthML() ****");
833 834 835 836 837
								break;
							}
							// remove worst sample
							smpl_sel[iworst] = false;
							double dw = smpl_d[iworst] * smpl_w[iworst];
838
							sd -= dw;
839 840
							sd2 -= dw * smpl_d[iworst];
							sw -=       smpl_w[iworst];
841
							sum_wnd -= smpl_weights[iworst];
842 843 844 845 846 847 848
							num_in_sample --;
						}
						// calculate variance of the remaining set
						if (sw > 0.0) {
							sd /= sw;
							sd2 /= sw;
							double var = sd2 - sd * sd;
849
							if (var < smplVar) { // good, save in the result array
850
								ds[0][indx] = sd;
851 852
//								ds[1][indx] = sw * lapWeight[dy][dx] /num_in_sample; // average weights, multiply by window //** TODO: change
								ds[1][indx] = sw * lapWeight[dy][dx] /sum_wnd; // average weights, multiply by window //** TODO: change
853 854 855
							}
						} else {
							num_in_sample = 0;
Andrey Filippov's avatar
Andrey Filippov committed
856
							System.out.println("**** this is a BUG in getDisparityStrengthML(), shoud not happen ? ****");
857 858
						}
					}
859
				}
860 861 862 863
			}
		}
		return ds;
	}
864

865
	/**
866
	 * Verify that selected points are not all on the same line
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
	 * @param sel 2-d sample selection in linescan order
	 * @param side square samples side
	 * @return true if there are enough samples for plane extraction, false otherwise
	 */
	public boolean notColinear (
			boolean [] sel,
			int side)
	{
		int indx0, indx1;
		for (indx0 = 0; indx0 < sel.length; indx0++){
			if (sel[indx0]) break;
		}
		for (indx1 = indx0+1; indx1 < sel.length; indx1++){
			if (sel[indx1]) break;
		}
		if (indx1 >= sel.length) return false; // too few points;
		int sx0 = indx0 % side;
		int sy0 = indx0 / side;
		int sx1 = indx1 % side;
		int sy1 = indx1 / side;
		for (int indx = indx1 +1; indx < sel.length; indx++){
			int sx = indx % side;
			int sy = indx / side;
			if ((sx - sx0) * (sy - sy1) != (sx - sx1) * (sy - sy0)){
				return true;
			}
		}
		return false;
	}

	/**
898
	 * Verify that selected points are not all on the same line, even if the specified one is removed
899 900 901 902 903
	 * @param indx index of the point to be removed
	 * @param sel 2-d sample selection in linescan order
	 * @param side square samples side
	 * @return true if there are enough samples for plane extraction, false otherwise
	 */
904

905 906 907 908 909 910 911 912 913 914 915 916 917
	public boolean notColinearWithout (
			int        indx,
			boolean [] sel,
			int side)
	{
		if (!sel[indx]){
			throw new IllegalArgumentException ("notCoplanarWithout(): specified is the non existing index");
		}
		sel[indx] = false;
		boolean rslt = notColinear ( sel, side);
		sel[indx] = true;
		return rslt;
	}
918

919
	// testing - redirecting all existing requests to this one with floating planes
Andrey Filippov's avatar
Andrey Filippov committed
920
	public double[][] getDisparityStrengthMLTilted (
921 922 923 924
			int num_layer,
			int stX,
			int stY,
			boolean [] sel_in,
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
			MeasuredLayersFilterParameters mlfp,     // filter parameters
//			double     strength_floor,
//			double     strength_pow,
//			int        smplSide, //        = 2;      // Sample size (side of a square)
//			int        smplNum, //         = 3;      // Number after removing worst (should be >1)
//			double     smplRms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
//			boolean    smplWnd, //

//  			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
940

941 942 943
			boolean    null_if_none,
			int        debugLevel)
	{
944
		boolean use_new = true; // false;
945

946
		if (use_new) {
Andrey Filippov's avatar
Andrey Filippov committed
947
		return getDisparityStrengthMLTilted (
948 949 950 951
				num_layer,      // int num_layer,
				stX,            // int stX,
				stY,            // int stY,
				sel_in,         // boolean [] sel_in,
952
				null,           // double []  tiltXY, // null - free with limit on both absolute (2.0?) and relative (0.2) values
953 954 955 956 957 958 959 960 961 962 963 964 965 966
				mlfp,     // MeasuredLayersFilterParameters mlfp,     // filter parameters
//				strength_floor, // double     strength_floor,
//				strength_pow,   // double     strength_pow,
//				smplSide,       // int        smplSide, //        = 2;      // Sample size (side of a square)
//				smplNum,        // int        smplNum, //         = 3;      // Number after removing worst (should be >1)
//				smplRms,        // double     smplRms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
//				smplWnd,        // boolean    smplWnd, //
//				max_abs_tilt,   // double     max_abs_tilt, //  = 2.0; // pix per tile
//				max_rel_tilt,   // double     max_rel_tilt, //  = 0.2; // (pix / disparity) per tile
//				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
967 968
				null_if_none,   // boolean    null_if_none,
				debugLevel);    // int        debugLevel)
969 970 971 972 973 974
		} else {
			return getDisparityStrength_old (
					num_layer,      // int num_layer,
					stX,            // int stX,
					stY,            // int stY,
					sel_in,         // boolean [] sel_in,
975
//					null,           // double []  tiltXY, // null - free with limit on both absolute (2.0?) and relative (0.2) values
976 977 978 979 980 981 982
					mlfp,     // MeasuredLayersFilterParameters mlfp,     // filter parameters
//					strength_floor, // double     strength_floor,
//					strength_pow,   // double     strength_pow,
//					smplSide,       // int        smplSide, //        = 2;      // Sample size (side of a square)
//					smplNum,        // int        smplNum, //         = 3;      // Number after removing worst (should be >1)
//					smplRms,        // double     smplRms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
//					smplWnd,        // boolean    smplWnd, //
983 984 985 986
//					2.0,            // double     max_abs_tilt, //  = 2.0; // pix per tile
//					0.2,            // double     max_rel_tilt, //  = 0.2; // (pix / disparity) per tile
					null_if_none,   // boolean    null_if_none,
					debugLevel);    // int        debugLevel)
987

988
		}
989
	}
990 991 992 993 994 995

// Try two modes of operation: Far tiles (disparity <~4?) use power of disparity, no tilts. Near tiles - current.
// For far tiles power can use closest (lowest disparity) - either power or just census or smth.
// Detect strong background?


Andrey Filippov's avatar
Andrey Filippov committed
996
	public double[][] getDisparityStrengthMLTilted (
997 998 999 1000
			int num_layer,
			int stX,
			int stY,
			boolean [] sel_in,
1001 1002 1003
			double [][] atiltXY, // null - free with limit on both absolute (2.0?) and relative (0.2) values
			                     // if it has just one element - apply to all tiles, otherwise it is supposed
			                     // to be per-tile of a supertile array
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
			MeasuredLayersFilterParameters mlfp,
//			double     strength_floor,
//			double     strength_pow,
//			int        smplSide, //        = 3;      // Sample size (side of a square)
//			int        smplNum, //         = 5;      // Number after removing worst (should be >1)
//			double     smplRms, //         = 0.3;    // Maximal RMS of the remaining tiles in a sample
//			boolean    smplWnd, //
//			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
1018 1019 1020
			boolean    null_if_none,
			int        debugLevel)
	{
1021

1022 1023 1024
		if ((layers[num_layer] == null) && null_if_none){
			return null;
		}
1025
		final double [] damping = {mlfp.damp_tilt, mlfp.damp_tilt, 0.0}; // 0.0 will be applied to average value, tilt_cost - to both tilts
1026

1027 1028 1029
		int st2 = 2 * superTileSize;
		int st_half = superTileSize/2;
		double [][] ds = new double [2][st2*st2];
1030
		final int dbg_tile =-1; //  ((stX == 22) && (stY == 19)) ? (5 + 7*16) : -1;// 50397;
1031

1032
		int num_selected = 0;
1033 1034 1035 1036 1037
		int smpl_center = mlfp.smplSide /2;
		double smpl_dcenter = (mlfp.smplSide -1.0) /2;
		int st2e = st2 + mlfp.smplSide;
		int smplLen = mlfp.smplSide*mlfp.smplSide;
		final double [] smpl_weights = getSampleWindow(mlfp.smplSide, !mlfp.smplWnd);
1038 1039 1040

		double [] disp =     new double [st2e * st2e];
		double [] weight = new double [st2e * st2e];
1041
		int st_halfe = st_half + smpl_center;
1042
		double smplVar = mlfp.smplRms * mlfp.smplRms; // maximal variance (weighted average of the squared difference from the mean)
1043 1044 1045
		PolynomialApproximation pa = new PolynomialApproximation();
		double thresholdLin = 1.0E-20;  // threshold ratio of matrix determinant to norm for linear approximation (det too low - fail)
		double thresholdQuad = 1.0E-30; // threshold ratio of matrix determinant to norm for quadratic approximation (det too low - fail)
1046

1047 1048 1049
		double  disp_pwr_far =  mlfp.min_tilt_disp - mlfp.transition/2.0;
		double  disp_pwr_near = mlfp.min_tilt_disp + mlfp.transition/2.0;
		double  disp_pwr_near2 = disp_pwr_near + mlfp.smplRms;
1050
		double [] disp_pwr = null;
1051 1052
		boolean far_mode_en = (mlfp.far_mode == 1) || (mlfp.far_mode == 2);
		boolean remove_far_only = (mlfp.far_mode == 2);
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
		if (far_mode_en) {
			disp_pwr = new double [st2e * st2e];
		}
		int num_far = 0;
		boolean [] smpl_far_sel = null;
		double []  smpl_pwr_d =   null;
		double []  smpl_far_d =   null;
		double []  smpl_far_w =   null;
		int num_in_sample_far = 0;

1063 1064 1065 1066 1067 1068 1069 1070 1071
		if (layers[num_layer] != null) {
			for (int dy = 0; dy < st2e; dy ++){
				int y = superTileSize * stY -st_halfe + dy;
				if ((y >= 0) && (y < tilesY)) {
					for (int dx = 0; dx < st2e; dx ++){
						int x = superTileSize * stX -st_halfe + dx;
						if ((x >= 0) && (x < tilesX)) {
							int indx = y * tilesX + x;
							int indx_ste = dy * st2e + dx;
1072

1073 1074
							if (layers[num_layer][indx] != null){ // apply sel_in later
								disp[indx_ste] = layers[num_layer][indx].getDisparity();
1075
								double w = layers[num_layer][indx].getStrength() - mlfp.strength_floor;
1076
								if (w > 0) {
1077
									if (mlfp.strength_pow != 1.0) w = Math.pow(w, mlfp.strength_pow);
1078
//									w *= lapWeight[dy][dx];
1079
									disp[indx_ste] = layers[num_layer][indx].getDisparity(); // same?
1080 1081
									weight[indx_ste] = w;
									num_selected ++;
1082
									if (far_mode_en && (disp[indx_ste] < disp_pwr_near2)  && (disp[indx_ste] > 0)) {
1083
										disp_pwr[indx_ste] = Math.pow(disp[indx_ste], mlfp.far_power);
1084 1085
										num_far++;
									}
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
								}
							}
						}
					}
				}
			}
		}
		if (null_if_none && (num_selected == 0)) return null;
		// now work with disp, strength [st2e*st2de] and filter results to ds[2][st2*st2], applying sel_in
		num_selected = 0;
		for (int dy = 0; dy < st2; dy ++){
			for (int dx = 0; dx < st2; dx ++){
				int indx = dy * st2 + dx;
				if (indx == dbg_tile){
Andrey Filippov's avatar
Andrey Filippov committed
1100
					System.out.println("getDisparityStrengthML(): stX="+stX+" stY="+stY+" dx="+dx+" dy="+dy);
1101 1102
				}
				if (((sel_in == null) || sel_in[indx])){
1103 1104 1105 1106 1107
					// check if it need filtering
					int indxe_center = (dy + smpl_center)*st2e + (dx + smpl_center);
					if (weight[indxe_center] >= mlfp.strength_sure) { // tile does not need filtering
						ds[0][indx] = disp[indxe_center];
						ds[1][indx] = weight[indxe_center];
1108 1109 1110 1111
						if (Double.isNaN(ds[0][indx])){
							System.out.println("**** this is a BUG6 in getDisparityStrengthML() ****"); // all smpl_d are NaNs
//							break;
						}
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
					} else {
						int num_in_sample = 0;
						double sum_wnd = 0.0;
						boolean [] smpl_sel = new boolean [smplLen];
						double [] smpl_d =  new double [smplLen];
						double [] smpl_p =  new double [smplLen];
						double [] smpl_w =  new double [smplLen];
						if (far_mode_en ) {
							smpl_far_sel =  new boolean [smplLen];
							smpl_pwr_d =  new double [smplLen];
							smpl_far_w =  new double [smplLen];
							num_in_sample_far = 0;
						}
						for (int sy = 0; sy < mlfp.smplSide; sy++){
							int y = dy + sy; //  - smpl_center;
							for (int sx = 0; sx < mlfp.smplSide; sx++){
								int x = dx + sx; // - smpl_center;
								int indxe = y * st2e + x;
								if (weight[indxe] > 0.0){
									int indxs = sy * mlfp.smplSide + sx;
									smpl_sel[indxs] = true;
									smpl_d[indxs] = disp[indxe];
1134 1135 1136 1137
									if (Double.isNaN(smpl_d[indxs])){
										System.out.println("**** this is a BUG5 in getDisparityStrengthML() ****"); // all smpl_d are NaNs
//										break;
									}
1138 1139 1140 1141 1142 1143 1144 1145 1146
									smpl_w[indxs] = weight[indxe] * smpl_weights[indxs];
									sum_wnd += smpl_weights[indxs];
									num_in_sample ++;
									if (far_mode_en && (disp_pwr[indxe]>0.0)) {
										smpl_far_sel[indxs] = true;
										smpl_pwr_d[indxs] =   disp_pwr[indxe];
										smpl_far_w[indxs] = smpl_w[indxs];
										num_in_sample_far++;
									}
1147
								}
1148 1149
							}
						}
1150 1151
						if (far_mode_en ) {
							smpl_far_d = smpl_d.clone();
1152
						}
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
						if (num_in_sample >= mlfp.smplNum){ // try, remove worst
							sample_loop:
							{
							boolean en_tilt = (atiltXY == null);
							if (en_tilt) { // make sure there are enough samples and not all of them are on the same line
								if ((mlfp.damp_tilt == 0.0) && !notColinear(smpl_sel, mlfp.smplSide)){
									en_tilt = false;
								}
							}
							if (en_tilt) { // enable floating tilt
								double sd2 = 0.0, d_center = 0.0,  sw = 0.0;

								// TODO: making simple - recalculate after removing. Can be done more efficient.
								while (num_in_sample >= mlfp.smplNum) { // try, remove worst
									sd2 = 0.0;
									d_center = 0.0;
									sw = 0.0;

									double [][][] mdata = new double [num_in_sample][3][];
									int mindx = 0;
									for (int sy = 0; sy < mlfp.smplSide; sy++){
										for (int sx = 0; sx < mlfp.smplSide; sx++){
											int indxs = sy * mlfp.smplSide + sx;
											if (smpl_sel[indxs]) {
												mdata[mindx][0] = new double [2];
												mdata[mindx][0][0] =  sx - smpl_dcenter;
												mdata[mindx][0][1] =  sy - smpl_dcenter;
												mdata[mindx][1] = new double [1];
												mdata[mindx][1][0] = smpl_d[indxs];
												mdata[mindx][2] = new double [1];
												mdata[mindx][2][0] =  smpl_w[indxs];
												mindx ++;
											}
1186 1187
										}
									}
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
									double[][] approx2d = pa.quadraticApproximation(
											mdata,
											true,          // boolean forceLinear,  // use linear approximation
											damping,       // double [] damping,
											thresholdLin,  // threshold ratio of matrix determinant to norm for linear approximation (det too low - fail)
											thresholdQuad, // threshold ratio of matrix determinant to norm for quadratic approximation (det too low - fail)
											debugLevel);
									if (approx2d == null){
										if (debugLevel > -1){
											System.out.println("getDisparityStrengthML(): can not find linear approximation");
										}
										break sample_loop;
1200
									}
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
									// limit tilt to be within range
									//											double     max_abs_tilt, //  = 2.0; // pix per tile
									//											double     max_rel_tilt, //  = 0.2; // (pix / disparity) per tile
									double max_tilt = Math.min(mlfp.max_abs_tilt, mlfp.max_rel_tilt * approx2d[0][2]);
									boolean overlimit = (Math.abs(approx2d[0][0]) > max_tilt) || (Math.abs(approx2d[0][1]) > max_tilt);
									if (overlimit) {
										approx2d[0][0] = Math.min(approx2d[0][0],  max_tilt);
										approx2d[0][1] = Math.min(approx2d[0][1],  max_tilt);
										approx2d[0][0] = Math.max(approx2d[0][0], -max_tilt);
										approx2d[0][1] = Math.max(approx2d[0][1], -max_tilt);
									}
									// subtract tilt from disparity
									for (int sy = 0; sy < mlfp.smplSide; sy++){
										for (int sx = 0; sx < mlfp.smplSide; sx++){
											int indxs = sy * mlfp.smplSide + sx;
											if (smpl_sel[indxs]) {
												smpl_p[indxs] = approx2d[0][0] * (sx - smpl_dcenter) + approx2d[0][1] * (sy - smpl_dcenter) + approx2d[0][2];
											}
1219 1220
										}
									}
1221

1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
									if (overlimit){ // re-calculate disparity average (in the center)
										double sd=0.0;
										for (int indxs = 0; indxs < smplLen;indxs++) if (smpl_sel[indxs]) {
											double d = smpl_d[indxs] - smpl_p[indxs];
											double dw = d * smpl_w[indxs];
											sd += dw;
											sw += smpl_w[indxs];
										}
										sd /= sw;
										for (int indxs = 0; indxs < smplLen;indxs++) if (smpl_sel[indxs]) {
											smpl_p[indxs] += sd;
										}
										approx2d[0][2] += sd;
									}
									d_center = approx2d[0][2];
									sw = 0.0;
1238 1239 1240
									for (int indxs = 0; indxs < smplLen;indxs++) if (smpl_sel[indxs]) {
										double d = smpl_d[indxs] - smpl_p[indxs];
										double dw = d * smpl_w[indxs];
1241 1242 1243
										//									sd += dw;
										sd2 += dw * smpl_d[indxs];
										sw +=       smpl_w[indxs];
1244
									}
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267


									// remove worst - it should not make remaining set
									if (num_in_sample > mlfp.smplNum) { // remove worst if it is not the last run where only calculations are needed
										//									double d_mean = sd/sw;
										int iworst = -1;
										double dworst2 = 0.0;
										for (int indxs = 0; indxs < smplLen; indxs++) if (smpl_sel[indxs]) {
											//										double d2 = (smpl_d[i] - d_mean);
											double d2 = smpl_d[indxs] - smpl_p[indxs];
											d2 *=d2;
											if (d2 > dworst2) {
												if ((mlfp.damp_tilt !=0.0) || notColinearWithout (
														indxs, // int        indx,
														smpl_sel, // boolean [] sel,
														mlfp.smplSide)) { // int side))
													iworst = indxs;
													dworst2 = d2;
												}
											}
										}
										if (iworst < 0){
											if (debugLevel > 0) {
1268 1269
												System.out.println("**** this may be BUG in getDisparityStrengthML() can not find the worst sample  - all tiles fit perfectly ****, num_in_sample="+
														num_in_sample+", stX="+stX+", stY="+stY);
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
											}
											// this can happen if some samples are the same and all the pixels fit exactly - use all of them
											break;
										}
										// remove worst sample
										smpl_sel[iworst] = false;
										//									double dw = smpl_d[iworst] * smpl_w[iworst];
										//									sd -= dw;
										//									sd2 -= dw * smpl_d[iworst];
										//									sw -=       smpl_w[iworst];
										sum_wnd -= smpl_weights[iworst];
										num_in_sample --;
									} else {
										break;
									}

								} // removing worst tiles, all done,
								// calculate variance of the remaining set
								if (sw > 0.0) {
									//								sd /= sw;
									//								sd2 /= sw;
									double var = sd2/sw; //   - sd * sd;
									if (var < smplVar) { // good, save in the result array
										ds[0][indx] = d_center;
										//								ds[1][indx] = sw * lapWeight[dy][dx] /num_in_sample; // average weights, multiply by window //** TODO: change
										ds[1][indx] = sw * lapWeight[dy][dx] /sum_wnd; // average weights, multiply by window //** TODO: change
1296 1297
									}
								}
1298 1299 1300 1301 1302 1303 1304 1305 1306

							} else { // fixed tilt
								// tilt around center
								double [] tiltXY= {0.0,0.0};
								if (atiltXY != null){ // if null ( free but failed co-linear test - keep both tilts == 0.0
									if (atiltXY.length == 1){
										tiltXY = atiltXY[0]; // common for all tiles (such as constant disparity)
									} else if (atiltXY[indx] != null){
										tiltXY = atiltXY[indx];
1307 1308 1309 1310 1311 1312 1313
										if (Double.isNaN(tiltXY[0]) || Double.isNaN(tiltXY[1])){
											System.out.println("**** this is a BUG4A in getDisparityStrengthML() ****");
											System.out.println("atilt["+indx+"]= {"+tiltXY[0]+","+tiltXY[1]+"}");
											tiltXY[0] = 0.0;
											tiltXY[1] = 0.0;
										}

1314
									}
1315
								}
1316

1317
								if ((tiltXY != null) && (tiltXY[0] != 0.0) && (tiltXY[1] != 0.0)){ // {NaN,NaN}
1318 1319 1320 1321 1322
									for (int sy = 0; sy < mlfp.smplSide; sy++){
										for (int sx = 0; sx < mlfp.smplSide; sx++){
											int indxs = sy * mlfp.smplSide + sx;
											if (smpl_w[indxs] > 0.0) {
												smpl_d[indxs] -= tiltXY[0]* (sx - smpl_dcenter) + tiltXY[1]* (sy - smpl_dcenter);
1323 1324 1325 1326 1327
												if (Double.isNaN(smpl_d[indxs])){
													System.out.println("**** this is a BUG4 in getDisparityStrengthML() ****"); // all smpl_d are NaNs
//													break;
												}

1328 1329 1330 1331
											}
										}
									}
								}
1332

1333 1334 1335 1336

								// calculate
								double sd=0.0, sd2 = 0.0, sw = 0.0;
								for (int i = 0; i < smplLen; i++) if (smpl_sel[i]) {
1337 1338 1339 1340 1341
									if (Double.isNaN(smpl_d[i])){
										System.out.println("**** this is a BUG3 in getDisparityStrengthML() ****"); // all smpl_d are NaNs
//										break;
									}

1342 1343 1344 1345 1346 1347 1348 1349
									double dw = smpl_d[i] * smpl_w[i];
									sd += dw;
									sd2 += dw * smpl_d[i];
									sw +=       smpl_w[i];
								}
								// remove worst, update sd2, sd and sw
								while ((num_in_sample > mlfp.smplNum) && (sw > 0)){ // try, remove worst
									double d_mean = sd/sw;
1350 1351
									int iworst = -1;
									double dworst2 = 0.0;
1352 1353
									for (int i = 0; i < smplLen; i++) if (smpl_sel[i]) {
										double d2 = (smpl_d[i] - d_mean);
1354 1355
										d2 *=d2;
										if (d2 > dworst2) {
1356 1357
											iworst = i;
											dworst2 = d2;
1358
										}
1359
										//remove_far_only
1360 1361
									}
									if (iworst < 0){
1362 1363
										System.out.println("**** this may be BUG2 in getDisparityStrengthML() can not find the worst sample  - all tiles fit perfectly ****, num_in_sample="+
												num_in_sample+", stX="+stX+", stY="+stY);
1364 1365 1366 1367
										break;
									}
									// remove worst sample
									smpl_sel[iworst] = false;
1368 1369 1370 1371
									double dw = smpl_d[iworst] * smpl_w[iworst];
									sd -= dw;
									sd2 -= dw * smpl_d[iworst];
									sw -=       smpl_w[iworst];
1372 1373 1374
									sum_wnd -= smpl_weights[iworst];
									num_in_sample --;
								}
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
								// calculate variance of the remaining set
								if (sw > 0.0) {
									sd /= sw;
									sd2 /= sw;
									double var = sd2 - sd * sd;
									if (var < smplVar) { // good, save in the result array
										ds[0][indx] = sd;
										//								ds[1][indx] = sw * lapWeight[dy][dx] /num_in_sample; // average weights, multiply by window //** TODO: change
										ds[1][indx] = sw * lapWeight[dy][dx] /sum_wnd; // average weights, multiply by window //** TODO: change
									}
								} else {
									num_in_sample = 0;
1387
									System.out.println("**** this is a BUG in getDisparityStrengthML(), should not happen ? ****");
1388 1389
								}
							}
1390
							}
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
						}
						// now apply far if needed
						if (num_in_sample_far > 0) { // calculate small far disparity, then merge with normal one
							// remove extra
							// smpl_pwr_d - disparity to power
							// smpl_far_d - just disparity
							if (num_in_sample_far >= mlfp.smplNum){ // try, remove worst
								double sd=0.0, sd2 = 0.0, sw = 0.0;
								double sdp =0.0; // , sdp2 = 0.0;
								for (int i = 0; i < smplLen; i++) if (smpl_far_sel[i]) {
									double dw = smpl_far_d[i] * smpl_far_w[i];
									sd += dw;
									sd2 += dw * smpl_far_d[i];
									sw +=       smpl_far_w[i];
									double dpw = smpl_pwr_d[i] * smpl_far_w[i];
									sdp += dpw;
									//								sdp2 += dpw * smpl_pwr_d[i];
1408 1409 1410
								}


1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
								// remove worst (before power), update sd2, sd and sw
								while ((num_in_sample_far > mlfp.smplNum) && (sw > 0)){ // try, remove worst
									double d_mean = sd/sw;
									int iworst = -1;
									double dworst2 = 0.0;
									for (int i = 0; i < smplLen; i++) if (smpl_far_sel[i]) {
										double d2 = (smpl_far_d[i] - d_mean);
										d2 *=d2;
										if ((d2 > dworst2) && (!remove_far_only ||(smpl_far_d[i] < d_mean))) {
											iworst = i;
											dworst2 = d2;
										}
1423
									}
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
									if (iworst < 0){
										System.out.println("**** this is a BUG3 in getDisparityStrengthML() ****");
										break;
									}
									// remove worst sample
									smpl_far_sel[iworst] = false;
									double dw = smpl_far_d[iworst] * smpl_far_w[iworst];
									sd -= dw;
									sd2 -= dw * smpl_far_d[iworst];
									sw -=       smpl_far_w[iworst];
									sum_wnd -= smpl_weights[iworst];
									num_in_sample_far --;
1436

1437
									// Remove from the power average too
1438

1439
									sdp -= smpl_pwr_d[iworst] * smpl_far_w[iworst];
1440
								}
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
								// calculate variance of the remaining set
								if (sw > 0.0) {
									sd /= sw;
									sd2 /= sw;
									double var = sd2 - sd * sd;
									if (var < smplVar) { // good, save in the result array (here use linear disparity
										// here need to combine two filtering modes - "tilted" and "far"
										sdp = Math.pow(sdp/sw, 1.0/mlfp.far_power);
										if (sdp < disp_pwr_near) { // otherwise keep tilted mode result
											double far_w = sw * lapWeight[dy][dx] /sum_wnd; // average weights, multiply by window //** TODO: change
											if (sdp < disp_pwr_far) {
												ds[0][indx] = sdp;
												ds[1][indx] = far_w;
											} else { // interpolate
												double k = (sdp - disp_pwr_far) / mlfp.transition;
												ds[0][indx] = (1.0 - k) * sdp +   k * ds[0][indx];
												ds[1][indx] = (1.0 - k) * far_w + k * ds[1][indx];
											}
1459
										}
1460 1461
										ds[0][indx] = sd;
										ds[1][indx] = sw * lapWeight[dy][dx] /sum_wnd; // average weights, multiply by window //** TODO: change
1462 1463 1464 1465 1466 1467

										if ((ds[0][indx] ==0.0) && (ds[0][indx] ==0.0)) {
											System.out.println("**** this may be BUG5 in getDisparityStrengthML()  ****, num_in_sample="+
													num_in_sample+", stX="+stX+", stY="+stY+" ds[0]["+indx+"]="+ds[0][indx]+", ds[1]["+indx+"]="+ds[1][indx]);
											ds[1][indx] = 0.0;
										}
1468
									}
1469 1470 1471
								} else {
									num_in_sample = 0;
									System.out.println("**** this is a BUG4 in getDisparityStrengthML(), shoud not happen ? ****");
1472 1473 1474 1475
								}
							}
						}
					}
1476
				} // end of tile
1477 1478 1479 1480 1481
			}
		}
		return ds;
	}

1482 1483 1484 1485




1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
	public void growSelection(
			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
			boolean [] tiles,
			boolean [] prohibit)
	{
		boolean [] src_tiles = tiles.clone(); // just in case
		// grow
		boolean hor = true;
		for (; grow > 0; grow--){
			boolean single = (grow ==1) && hor;
			src_tiles = tiles.clone();
			if (hor){
				for (int tileY = 0; tileY < tilesY; tileY++){
					for (int tileX = 0; tileX < (tilesX - 1); tileX++){
						int tindx = tileY * tilesX + tileX;
						if ((prohibit == null) || (!prohibit[tindx] && !prohibit[tindx + 1])) {
1502
							tiles[tindx + 1] |= src_tiles[tindx];
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
						}

					}
					for (int tileX = 1; tileX < tilesX; tileX++){
						int tindx = tileY * tilesX + tileX;
						if ((prohibit == null) || (!prohibit[tindx] && !prohibit[tindx - 1])) {
							tiles[tindx - 1] |= src_tiles[tindx];
						}
					}
				}
			}
			if (!hor || single){ // do vertically, but from previous state
				for (int tileX = 0; tileX < tilesX; tileX++){
					for (int tileY = 0; tileY < (tilesY - 1); tileY++){
						int tindx = tileY * tilesX + tileX;
						if ((prohibit == null) || (!prohibit[tindx] && !prohibit[tindx + tilesX])) {
							tiles[tindx + tilesX] |= src_tiles[tindx];
						}

					}
					for (int tileY = 1; tileY < tilesY; tileY++){
						int tindx = tileY * tilesX + tileX;
						if ((prohibit == null) || (!prohibit[tindx] && !prohibit[tindx - tilesX])) {
							tiles[tindx - tilesX] |= src_tiles[tindx];
						}
					}
				}
			}
			hor = !hor;
		}
	}
1534

Andrey Filippov's avatar
Andrey Filippov committed
1535
}