TwoQuadCLT.java 575 KB
Newer Older
1
package com.elphel.imagej.tileprocessor;
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/**
 ** TwoQuadCLT - Process images from a pair of Quad/Octal cameras
 **
 ** Copyright (C) 2018 Elphel, Inc.
 **
 ** -----------------------------------------------------------------------------**
 **
 **  TwoQuadCLT.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/>.
 ** -----------------------------------------------------------------------------**
 **
 */
24
import java.awt.Rectangle;
Andrey Filippov's avatar
Andrey Filippov committed
25
import java.io.DataOutputStream;
26
import java.io.File;
27
import java.io.FileInputStream;
28 29
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
30
import java.io.IOException;
31
import java.io.OutputStream;
32 33
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
34
import java.nio.FloatBuffer;
35
import java.nio.channels.Channels;
36
import java.nio.channels.FileChannel;
37
import java.nio.channels.WritableByteChannel;
38 39
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
40
import java.util.ArrayList;
41 42 43
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
44
import java.util.Properties;
45
import java.util.Random;
46

47 48
import com.elphel.imagej.cameras.CLTParameters;
import com.elphel.imagej.cameras.ColorProcParameters;
49
import com.elphel.imagej.cameras.EyesisCorrectionParameters;
50
import com.elphel.imagej.common.GenericJTabbedDialog;
51
import com.elphel.imagej.common.ShowDoubleFloatArrays;
52
import com.elphel.imagej.correction.CorrectionColorProc;
Andrey Filippov's avatar
Andrey Filippov committed
53
import com.elphel.imagej.gpu.GPUTileProcessor;
Andrey Filippov's avatar
Andrey Filippov committed
54
import com.elphel.imagej.jp4.JP46_Reader_camera;
55

56 57 58 59 60
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.Prefs;
import ij.io.FileSaver;
61 62

public class TwoQuadCLT {
63 64 65 66 67 68 69
	public static  int DSI_DISPARITY_MAIN = 0;
	public static  int DSI_DISPARITY_AUX =  1;
	public static  int DSI_DISPARITY_RIG =  2;
	public static  int DSI_DISPARITY_X3D =  3;
	public static  int DSI_STRENGTH_MAIN =  4;
	public static  int DSI_STRENGTH_AUX =   5;
	public static  int DSI_STRENGTH_RIG =   6;
70 71 72 73

	public static String DSI_COMBO_SUFFIX = "-DSI_COMBO";
	public static String DSI_MAIN_SUFFIX =  "-DSI_MAIN";

74 75 76 77 78 79 80 81 82
	public static String [] DSI_SLICES =
		{       "disparity_main",
				"disparity_aux",
				"disparity_rig",
				"disparity_x3d",
			    "strength_main",
			    "strength_aux",
			    "strength_rig"};

83 84 85
	public long                                            startTime;     // start of batch processing
	public long                                            startSetTime;  // start of set processing
	public long                                            startStepTime; // start of step processing
86
	public BiCamDSI                                        biCamDSI_persistent; // may be removed later to save memory, now to be able to continue
87
	PoleProcessor                                          poleProcessor_persistent;
88 89
	public QuadCLT quadCLT_main =  null;
	public QuadCLT quadCLT_aux =   null;
90
	public double [][] dsi = new double [DSI_SLICES.length][];
91
	public double [][] dsi_aux_from_main; // Main camera DSI converted into the coordinates of the AUX one (see QuadCLT.FGBG_TITLES)-added two slises from aux ds
92 93 94 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 121 122 123 124 125 126 127 128 129 130

	public TwoQuadCLT(
			QuadCLT quadCLT_main,
			QuadCLT quadCLT_aux)
	{
		this.quadCLT_main = quadCLT_main;
		this.quadCLT_aux =  quadCLT_aux;
	}
	public QuadCLT getMain()
	{
		return quadCLT_main;
	}
	public QuadCLT getAux()
	{
		return quadCLT_aux;
	}
	public void resetRig(boolean all_cams)
	{
		biCamDSI_persistent = null;
		poleProcessor_persistent = null;
		if (all_cams) {
			if ((quadCLT_main != null) && (quadCLT_main.tp != null)) {
				quadCLT_main.tp.resetCLTPasses();
			}
			if ((quadCLT_aux != null) && (quadCLT_aux.tp != null)) {
				quadCLT_aux.tp.resetCLTPasses();
			}

		}
	}

	public BiScan getBiScan(int indx) {
		if ((biCamDSI_persistent == null) ||
				(biCamDSI_persistent.biScans == null) ||
				(biCamDSI_persistent.biScans.size() <= indx)) {
			return null;
		}
		return biCamDSI_persistent.biScans.get(indx);
	}
131 132
/*
	public void processCLTTwoQuadCorrs( // not referenced?
133 134
			QuadCLT quadCLT_main,
			QuadCLT quadCLT_aux,
135
			CLTParameters       clt_parameters,
136
			EyesisCorrectionParameters.DebayerParameters   debayerParameters,
137 138
			ColorProcParameters                            colorProcParameters,
			ColorProcParameters                            colorProcParameters_aux,
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
			CorrectionColorProc.ColorGainsParameters       channelGainParameters_main,
			CorrectionColorProc.ColorGainsParameters       channelGainParameters_aux,
			EyesisCorrectionParameters.RGBParameters       rgbParameters,
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel) throws Exception
	{

		this.startTime=System.nanoTime();
		String [] sourceFiles=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		QuadCLT.SetChannels [] set_channels_aux =  quadCLT_aux.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0) || (set_channels_aux == null) || (set_channels_aux.length==0)) {
			System.out.println("No files to process (of "+sourceFiles.length+")");
			return;
		}
		double [] referenceExposures_main = quadCLT_main.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		double [] referenceExposures_aux =  quadCLT_aux.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		for (int nSet = 0; nSet < set_channels_main.length; nSet++){
			// check it is the same set for both cameras
			if (set_channels_aux.length <= nSet ) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: nothing");
			}
			if (!set_channels_main[nSet].name().equals(set_channels_aux[nSet].name())) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: '"+set_channels_main[nSet].name()+"'");
			}

			int [] channelFiles_main = set_channels_main[nSet].fileNumber();
			int [] channelFiles_aux =  set_channels_aux[nSet].fileNumber();
			boolean [][] saturation_imp_main = (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			boolean [][] saturation_imp_aux =  (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			double [] scaleExposures_main = new double[channelFiles_main.length];
			double [] scaleExposures_aux =  new double[channelFiles_main.length];

			ImagePlus [] imp_srcs_main = quadCLT_main.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
175 176
				    colorProcParameters,            //  ColorProcParameters                       colorProcParameters, //

177 178 179 180 181 182 183 184 185 186
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_main[nSet].name(), // String                                    set_name,
					referenceExposures_main,        // double []                                 referenceExposures,
					channelFiles_main,              // int []                                    channelFiles,
					scaleExposures_main,            //output  // double [] scaleExposures
					saturation_imp_main,            //output  // boolean [][]                              saturation_imp,
					debugLevel); // int                                       debugLevel);

			ImagePlus [] imp_srcs_aux = quadCLT_aux.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
187
					colorProcParameters_aux,        //  ColorProcParameters                       colorProcParameters, //
188 189 190 191 192 193 194 195
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_aux[nSet].name(), // String                                    set_name,
					referenceExposures_aux,        // double []                                 referenceExposures,
					channelFiles_aux,              // int []                                    channelFiles,
					scaleExposures_aux,            //output  // double [] scaleExposures
					saturation_imp_aux,            //output  // boolean [][]                              saturation_imp,
					debugLevel); // int                                       debugLevel);

196
			// Temporarily processing individaully with the old code
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
			quadCLT_main.processCLTQuadCorr( // returns ImagePlus, but it already should be saved/shown
					imp_srcs_main, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
					saturation_imp_main, // boolean [][] saturation_imp, // (near) saturated pixels or null
					clt_parameters,
					debayerParameters,
					colorProcParameters,
					channelGainParameters_main,
					rgbParameters,
					scaleExposures_main,
					false, // apply_corr, // calculate and apply additional fine geometry correction
					false, // infinity_corr, // calculate and apply geometry correction at infinity
					threadsMax,  // maximal number of threads to launch
					updateStatus,
					debugLevel);

			Runtime.getRuntime().gc();
			if (debugLevel >-1) System.out.println("Processing set "+(nSet+1)+" (of "+set_channels_main.length+") finished at "+
					IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

			quadCLT_aux.processCLTQuadCorr( // returns ImagePlus, but it already should be saved/shown
					imp_srcs_aux, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
					saturation_imp_aux, // boolean [][] saturation_imp, // (near) saturated pixels or null
					clt_parameters,
					debayerParameters,
221
					colorProcParameters_aux,
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
					channelGainParameters_aux,
					rgbParameters,
					scaleExposures_aux,
					false, // apply_corr, // calculate and apply additional fine geometry correction
					false, // infinity_corr, // calculate and apply geometry correction at infinity
					threadsMax,  // maximal number of threads to launch
					updateStatus,
					debugLevel);

			Runtime.getRuntime().gc();
			if (debugLevel >-1) System.out.println("Processing set "+(nSet+1)+" (of "+set_channels_aux.length+") finished at "+
					IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

			if (quadCLT_aux.eyesisCorrections.stopRequested.get()>0) {
				System.out.println("User requested stop");
				System.out.println("Processing "+(nSet + 1)+" file sets (of "+set_channels_main.length+") finished at "+
						IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");
				return;
			}
		}
242
		System.out.println("processCLTTwoQuadCorrs(): processing "+(quadCLT_main.getTotalFiles(set_channels_main)+quadCLT_aux.getTotalFiles(set_channels_aux))+" files ("+set_channels_main.length+" file sets) finished at "+
243 244 245 246
				IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

	}

247
*/
248 249 250



251
	public void processCLTQuadCorrPairs(
252 253
			QuadCLT                                        quadCLT_main,
			QuadCLT                                        quadCLT_aux,
254
			CLTParameters       clt_parameters,
255
			EyesisCorrectionParameters.DebayerParameters   debayerParameters,
256 257
			ColorProcParameters                            colorProcParameters,
			ColorProcParameters                            colorProcParameters_aux,
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
			EyesisCorrectionParameters.RGBParameters       rgbParameters,
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel) throws Exception
	{

		this.startTime=System.nanoTime();
		String [] sourceFiles=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		QuadCLT.SetChannels [] set_channels_aux =  quadCLT_aux.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0) || (set_channels_aux == null) || (set_channels_aux.length==0)) {
			System.out.println("No files to process (of "+sourceFiles.length+")");
			return;
		}
		double [] referenceExposures_main = quadCLT_main.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		double [] referenceExposures_aux =  quadCLT_aux.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		for (int nSet = 0; nSet < set_channels_main.length; nSet++){
			// check it is the same set for both cameras
			if (set_channels_aux.length <= nSet ) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: nothing");
			}
			if (!set_channels_main[nSet].name().equals(set_channels_aux[nSet].name())) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: '"+set_channels_main[nSet].name()+"'");
			}

			int [] channelFiles_main = set_channels_main[nSet].fileNumber();
			int [] channelFiles_aux =  set_channels_aux[nSet].fileNumber();
			boolean [][] saturation_imp_main = (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			boolean [][] saturation_imp_aux =  (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			double [] scaleExposures_main = new double[channelFiles_main.length];
			double [] scaleExposures_aux =  new double[channelFiles_main.length];

			ImagePlus [] imp_srcs_main = quadCLT_main.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
292
					colorProcParameters,            //  ColorProcParameters                       colorProcParameters, //
293 294 295 296 297 298
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_main[nSet].name(), // String                                    set_name,
					referenceExposures_main,        // double []                                 referenceExposures,
					channelFiles_main,              // int []                                    channelFiles,
					scaleExposures_main,            //output  // double [] scaleExposures
					saturation_imp_main,            //output  // boolean [][]                              saturation_imp,
299
					threadsMax,                 // int                                       threadsMax,
300 301 302 303
					debugLevel); // int                                       debugLevel);

			ImagePlus [] imp_srcs_aux = quadCLT_aux.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
304
					colorProcParameters_aux,        //  ColorProcParameters                       colorProcParameters, //
305 306 307 308 309 310
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_aux[nSet].name(), // String                                    set_name,
					referenceExposures_aux,        // double []                                 referenceExposures,
					channelFiles_aux,              // int []                                    channelFiles,
					scaleExposures_aux,            //output  // double [] scaleExposures
					saturation_imp_aux,            //output  // boolean [][]                              saturation_imp,
311
					threadsMax,                 // int                                       threadsMax,
312 313 314 315 316 317 318 319 320 321 322 323 324
					debugLevel); // int                                       debugLevel);

			// Tempporarily processing individaully with the old code
			processCLTQuadCorrPair(
					quadCLT_main,               // QuadCLT                                        quadCLT_main,
					quadCLT_aux,                // QuadCLT                                        quadCLT_aux,
					imp_srcs_main,              // ImagePlus []                                   imp_quad_main,
					imp_srcs_aux,               // ImagePlus []                                   imp_quad_aux,
					saturation_imp_main,        // boolean [][]                                   saturation_main, // (near) saturated pixels or null
					saturation_imp_aux,         // boolean [][]                                   saturation_aux, // (near) saturated pixels or null
					clt_parameters,             // EyesisCorrectionParameters.CLTParameters       clt_parameters,
					debayerParameters,          // EyesisCorrectionParameters.DebayerParameters   debayerParameters,
					colorProcParameters,        // EyesisCorrectionParameters.ColorProcParameters colorProcParameters,
325
					colorProcParameters_aux,
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
					rgbParameters,              // EyesisCorrectionParameters.RGBParameters       rgbParameters,
					scaleExposures_main,        // double []	                                     scaleExposures_main, // probably not needed here - restores brightness of the final image
					scaleExposures_aux,         // double []	                                     scaleExposures_aux, // probably not needed here - restores brightness of the final image
					false,                      //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
					// averages measurements
					clt_parameters.rig.lt_avg_radius,// final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using

					//			  final boolean    apply_corr, // calculate and apply additional fine geometry correction
					//			  final boolean    infinity_corr, // calculate and apply geometry correction at infinity
					threadsMax,                 // final int        threadsMax,  // maximal number of threads to launch
					updateStatus,               // final boolean    updateStatus,
					debugLevel);                // final int        debugLevel);

			Runtime.getRuntime().gc();
			if (debugLevel >-1) System.out.println("Processing set "+(nSet+1)+" (of "+set_channels_aux.length+") finished at "+
					IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

			if (quadCLT_aux.eyesisCorrections.stopRequested.get()>0) {
				System.out.println("User requested stop");
				System.out.println("Processing "+(nSet + 1)+" file sets (of "+set_channels_main.length+") finished at "+
						IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");
				return;
			}
		}
350
		System.out.println("processCLTQuadCorrPairs(): processing "+(quadCLT_main.getTotalFiles(set_channels_main)+quadCLT_aux.getTotalFiles(set_channels_aux))+" files ("+set_channels_main.length+" file sets) finished at "+
351 352 353 354
				IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

	}

355
	public void prepareFilesForGPUDebug(
356
			String                                         save_prefix, // absolute path to the cuda project root
357 358
			QuadCLT                                        quadCLT_main,
			QuadCLT                                        quadCLT_aux,
359
			CLTParameters       clt_parameters,
360
			EyesisCorrectionParameters.DebayerParameters   debayerParameters,
361 362
			ColorProcParameters                            colorProcParameters,
			ColorProcParameters                            colorProcParameters_aux,
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 391 392 393 394 395 396
			EyesisCorrectionParameters.RGBParameters       rgbParameters,
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel) throws Exception
	{

		this.startTime=System.nanoTime();
		String [] sourceFiles=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		QuadCLT.SetChannels [] set_channels_aux =  quadCLT_aux.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0) || (set_channels_aux == null) || (set_channels_aux.length==0)) {
			System.out.println("No files to process (of "+sourceFiles.length+")");
			return;
		}
		double [] referenceExposures_main = quadCLT_main.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		double [] referenceExposures_aux =  quadCLT_aux.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		for (int nSet = 0; nSet < set_channels_main.length; nSet++){
			// check it is the same set for both cameras
			if (set_channels_aux.length <= nSet ) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: nothing");
			}
			if (!set_channels_main[nSet].name().equals(set_channels_aux[nSet].name())) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: '"+set_channels_main[nSet].name()+"'");
			}

			int [] channelFiles_main = set_channels_main[nSet].fileNumber();
			int [] channelFiles_aux =  set_channels_aux[nSet].fileNumber();
			boolean [][] saturation_imp_main = (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			boolean [][] saturation_imp_aux =  (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			double [] scaleExposures_main = new double[channelFiles_main.length];
			double [] scaleExposures_aux =  new double[channelFiles_main.length];

			ImagePlus [] imp_srcs_main = quadCLT_main.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
397
					colorProcParameters,            //  ColorProcParameters                       colorProcParameters, //
398 399 400 401 402 403
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_main[nSet].name(), // String                                    set_name,
					referenceExposures_main,        // double []                                 referenceExposures,
					channelFiles_main,              // int []                                    channelFiles,
					scaleExposures_main,            //output  // double [] scaleExposures
					saturation_imp_main,            //output  // boolean [][]                              saturation_imp,
404
					threadsMax,                 // int                                       threadsMax,
405 406 407 408
					debugLevel); // int                                       debugLevel);

			ImagePlus [] imp_srcs_aux = quadCLT_aux.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
409
					colorProcParameters_aux,        //  ColorProcParameters                       colorProcParameters, //
410 411 412 413 414 415
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_aux[nSet].name(), // String                                    set_name,
					referenceExposures_aux,        // double []                                 referenceExposures,
					channelFiles_aux,              // int []                                    channelFiles,
					scaleExposures_aux,            //output  // double [] scaleExposures
					saturation_imp_aux,            //output  // boolean [][]                              saturation_imp,
416
					threadsMax,                 // int                                       threadsMax,
417 418
					debugLevel); // int                                       debugLevel);

419
			// Tempporarily processing individually with the old code
420
			processCLTQuadCorrPairForGPU(
421
					save_prefix,                // String save_prefix,
422 423 424 425 426 427 428 429 430
					quadCLT_main,               // QuadCLT                                        quadCLT_main,
					quadCLT_aux,                // QuadCLT                                        quadCLT_aux,
					imp_srcs_main,              // ImagePlus []                                   imp_quad_main,
					imp_srcs_aux,               // ImagePlus []                                   imp_quad_aux,
					saturation_imp_main,        // boolean [][]                                   saturation_main, // (near) saturated pixels or null
					saturation_imp_aux,         // boolean [][]                                   saturation_aux, // (near) saturated pixels or null
					clt_parameters,             // EyesisCorrectionParameters.CLTParameters       clt_parameters,
					debayerParameters,          // EyesisCorrectionParameters.DebayerParameters   debayerParameters,
					colorProcParameters,        // EyesisCorrectionParameters.ColorProcParameters colorProcParameters,
431
					colorProcParameters_aux,        // EyesisCorrectionParameters.ColorProcParameters colorProcParameters,
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
					rgbParameters,              // EyesisCorrectionParameters.RGBParameters       rgbParameters,
					scaleExposures_main,        // double []	                                     scaleExposures_main, // probably not needed here - restores brightness of the final image
					scaleExposures_aux,         // double []	                                     scaleExposures_aux, // probably not needed here - restores brightness of the final image
					false,                      //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
					// averages measurements
					clt_parameters.rig.lt_avg_radius,// final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using

					//			  final boolean    apply_corr, // calculate and apply additional fine geometry correction
					//			  final boolean    infinity_corr, // calculate and apply geometry correction at infinity
					threadsMax,                 // final int        threadsMax,  // maximal number of threads to launch
					updateStatus,               // final boolean    updateStatus,
					debugLevel);                // final int        debugLevel);

			Runtime.getRuntime().gc();
			if (debugLevel >-1) System.out.println("Processing set "+(nSet+1)+" (of "+set_channels_aux.length+") finished at "+
					IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

			if (quadCLT_aux.eyesisCorrections.stopRequested.get()>0) {
				System.out.println("User requested stop");
				System.out.println("Processing "+(nSet + 1)+" file sets (of "+set_channels_main.length+") finished at "+
						IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");
				return;
			}
		}
456
		System.out.println("prepareFilesForGPUDebug(): processing "+(quadCLT_main.getTotalFiles(set_channels_main)+quadCLT_aux.getTotalFiles(set_channels_aux))+" files ("+set_channels_main.length+" file sets) finished at "+
457 458 459 460
				IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

	}

461
	public void processCLTQuadCorrPairsGpu(
462 463
			GPUTileProcessor.GpuQuad                        gpuQuad_main,
			GPUTileProcessor.GpuQuad                        gpuQuad_aux,
464 465
			QuadCLT                                         quadCLT_main,
			QuadCLT                                         quadCLT_aux,
466
			CLTParameters       clt_parameters,
467 468 469 470 471 472 473 474
			EyesisCorrectionParameters.CorrectionParameters ecp,
			EyesisCorrectionParameters.DebayerParameters    debayerParameters,
			ColorProcParameters                             colorProcParameters,
			ColorProcParameters                             colorProcParameters_aux,
			EyesisCorrectionParameters.RGBParameters        rgbParameters,
			final int                                       threadsMax,  // maximal number of threads to launch
			final boolean                                   updateStatus,
			final int                                       debugLevel) throws Exception
475
	{
476
//		TwoQuadGPU twoQuadGPU = new TwoQuadGPU(this);
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
		this.startTime=System.nanoTime();
		String [] sourceFiles=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		QuadCLT.SetChannels [] set_channels_aux =  quadCLT_aux.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0) || (set_channels_aux == null) || (set_channels_aux.length==0)) {
			System.out.println("No files to process (of "+sourceFiles.length+")");
			return;
		}
		double [] referenceExposures_main = quadCLT_main.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		double [] referenceExposures_aux =  quadCLT_aux.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		for (int nSet = 0; nSet < set_channels_main.length; nSet++){
			// check it is the same set for both cameras
			if (set_channels_aux.length <= nSet ) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: nothing");
			}
492 493 494 495 496 497 498 499 500 501 502 503 504
			if (!set_channels_main[nSet].name().equals(set_channels_aux[nSet].name())) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: '"+set_channels_main[nSet].name()+"'");
			}

			int [] channelFiles_main = set_channels_main[nSet].fileNumber();
			int [] channelFiles_aux =  set_channels_aux[nSet].fileNumber();
			boolean [][] saturation_imp_main = (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			boolean [][] saturation_imp_aux =  (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			double [] scaleExposures_main = new double[channelFiles_main.length];
			double [] scaleExposures_aux =  new double[channelFiles_main.length];

			ImagePlus [] imp_srcs_main = quadCLT_main.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
505
					colorProcParameters,            //  ColorProcParameters                       colorProcParameters, //
506 507 508 509 510 511
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_main[nSet].name(), // String                                    set_name,
					referenceExposures_main,        // double []                                 referenceExposures,
					channelFiles_main,              // int []                                    channelFiles,
					scaleExposures_main,            //output  // double [] scaleExposures
					saturation_imp_main,            //output  // boolean [][]                              saturation_imp,
512
					threadsMax,                 // int                                       threadsMax,
513 514 515 516
					debugLevel); // int                                       debugLevel);

			ImagePlus [] imp_srcs_aux = quadCLT_aux.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
517
					colorProcParameters_aux,        //  ColorProcParameters                       colorProcParameters, //
518 519 520 521 522 523
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_aux[nSet].name(), // String                                    set_name,
					referenceExposures_aux,        // double []                                 referenceExposures,
					channelFiles_aux,              // int []                                    channelFiles,
					scaleExposures_aux,            //output  // double [] scaleExposures
					saturation_imp_aux,            //output  // boolean [][]                              saturation_imp,
524
					threadsMax,                 // int                                       threadsMax,
525 526 527
					debugLevel); // int                                       debugLevel);

			// Tempporarily processing individaully with the old code
528 529 530
			QuadCLT.processCLTQuadCorrPairGpu(
//					gpuQuad_main,               // GPUTileProcessor.GpuQuad                       gpuQuad_main,
//					gpuQuad_aux,                // GPUTileProcessor.GpuQuad                       gpuQuad_aux,
531 532 533 534 535 536 537
					quadCLT_main,               // QuadCLT                                        quadCLT_main,
					quadCLT_aux,                // QuadCLT                                        quadCLT_aux,
					imp_srcs_main,              // ImagePlus []                                   imp_quad_main,
					imp_srcs_aux,               // ImagePlus []                                   imp_quad_aux,
					saturation_imp_main,        // boolean [][]                                   saturation_main, // (near) saturated pixels or null
					saturation_imp_aux,         // boolean [][]                                   saturation_aux, // (near) saturated pixels or null
					clt_parameters,             // EyesisCorrectionParameters.CLTParameters       clt_parameters,
538
					ecp,                        // EyesisCorrectionParameters.CorrectionParameters ecp,
539 540
					debayerParameters,          // EyesisCorrectionParameters.DebayerParameters   debayerParameters,
					colorProcParameters,        // EyesisCorrectionParameters.ColorProcParameters colorProcParameters,
541
					colorProcParameters_aux,    // EyesisCorrectionParameters.ColorProcParameters colorProcParameters_aux,
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
					rgbParameters,              // EyesisCorrectionParameters.RGBParameters       rgbParameters,
					scaleExposures_main,        // double []	                                     scaleExposures_main, // probably not needed here - restores brightness of the final image
					scaleExposures_aux,         // double []	                                     scaleExposures_aux, // probably not needed here - restores brightness of the final image
					false,                      //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
					// averages measurements
					clt_parameters.rig.lt_avg_radius,// final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using

					//			  final boolean    apply_corr, // calculate and apply additional fine geometry correction
					//			  final boolean    infinity_corr, // calculate and apply geometry correction at infinity
					threadsMax,                 // final int        threadsMax,  // maximal number of threads to launch
					updateStatus,               // final boolean    updateStatus,
					debugLevel);                // final int        debugLevel);

			Runtime.getRuntime().gc();
			if (debugLevel >-1) System.out.println("Processing set "+(nSet+1)+" (of "+set_channels_aux.length+") finished at "+
					IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

			if (quadCLT_aux.eyesisCorrections.stopRequested.get()>0) {
				System.out.println("User requested stop");
				System.out.println("Processing "+(nSet + 1)+" file sets (of "+set_channels_main.length+") finished at "+
						IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");
				return;
			}
		}
566
		System.out.println("processCLTQuadCorrPairsGpu(): processing "+(quadCLT_main.getTotalFiles(set_channels_main)+quadCLT_aux.getTotalFiles(set_channels_aux))+" files ("+set_channels_main.length+" file sets) finished at "+
567 568 569
				IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

	}
570
	
571 572 573 574 575 576 577
	public ImagePlus [] processCLTQuadCorrPair(
			QuadCLT                                        quadCLT_main,
			QuadCLT                                        quadCLT_aux,
			ImagePlus []                                   imp_quad_main,
			ImagePlus []                                   imp_quad_aux,
			boolean [][]                                   saturation_main, // (near) saturated pixels or null
			boolean [][]                                   saturation_aux, // (near) saturated pixels or null
578
			CLTParameters       clt_parameters,
579
			EyesisCorrectionParameters.DebayerParameters   debayerParameters,
580 581
			ColorProcParameters                            colorProcParameters,
			ColorProcParameters                            colorProcParameters_aux,
582 583 584 585 586 587 588 589 590 591 592 593 594 595
			EyesisCorrectionParameters.RGBParameters       rgbParameters,
			double []	                                     scaleExposures_main, // probably not needed here - restores brightness of the final image
			double []	                                     scaleExposures_aux, // probably not needed here - restores brightness of the final image
			boolean                                        notch_mode, // use pole-detection mode for inter-camera correlation
			final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel){
		final boolean      batch_mode = clt_parameters.batch_run; //disable any debug images
		final boolean get_ers = !batch_mode;
		//		  boolean batch_mode = false;
		boolean infinity_corr = false;
		double [][] scaleExposures= {scaleExposures_main, scaleExposures_aux};
		boolean toRGB=     quadCLT_main.correctionsParameters.toRGB;
596
		ShowDoubleFloatArrays sdfa_instance = new ShowDoubleFloatArrays(); // just for debugging? - TODO - move where it belongs
597 598 599 600 601 602 603 604 605 606 607 608 609
		// may use this.StartTime to report intermediate steps execution times
		String name=quadCLT_main.correctionsParameters.getModelName((String) imp_quad_main[0].getProperty("name"));
		String path= (String) imp_quad_main[0].getProperty("path"); // Only for debug output
		ImagePlus [] results = new ImagePlus[imp_quad_main.length + imp_quad_main.length];
		for (int i = 0; i < results.length; i++) {
			if (i< imp_quad_main.length) {
				results[i] = imp_quad_main[i];
			} else {
				results[i] = imp_quad_main[i-imp_quad_main.length];
			}
			results[i].setTitle(results[i].getTitle()+"RAW");
		}
		if (debugLevel>1) System.out.println("processing: "+path);
610
/*		// 08/12/2020 Moved to conditionImageSet		
611 612 613 614 615 616 617 618 619 620
		getRigImageStacks(
				clt_parameters,  // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				quadCLT_main,    // QuadCLT                                         quadCLT_main,
				quadCLT_aux,     // QuadCLT                                          quadCLT_aux,
				imp_quad_main,   // ImagePlus []                                   imp_quad_main,
				imp_quad_aux,    // ImagePlus []                                    imp_quad_aux,
				saturation_main, // boolean [][]        saturation_main, // (near) saturated pixels or null
				saturation_aux, // boolean [][]        saturation_aux, // (near) saturated pixels or null
				threadsMax,      // maximal number of threads to launch
				debugLevel);     // final int        debugLevel);
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 652 653 654 655
		// temporary setting up tile task file (one integer per tile, bitmask
		// for testing defined for a window, later the tiles to process will be calculated based on previous passes results

		int [][]    tile_op_main = quadCLT_main.tp.setSameTileOp(clt_parameters,  clt_parameters.tile_task_op, debugLevel);
		//		  int [][]    tile_op_aux =  quadCLT_aux.tp.setSameTileOp (clt_parameters,  clt_parameters.tile_task_op, debugLevel);

		double [][] disparity_array_main = quadCLT_main.tp.setSameDisparity(clt_parameters.disparity); // [tp.tilesY][tp.tilesX] - individual per-tile expected disparity
		//TODO: Add array of default disparity - use for combining images in force disparity mode (no correlation), when disparity is predicted from other tiles
		// start with all old arrays, remove some later
		double [][][][]     clt_corr_combo =        null;
		double [][][][]     texture_tiles_main =    null; // [tp.tilesY][tp.tilesX]["RGBA".length()][]; // tiles will be 16x16, 2 visualization mode full 16 or overlapped
		double [][][][]     texture_tiles_aux =     null; // [tp.tilesY][tp.tilesX]["RGBA".length()][]; // tiles will be 16x16, 2 visualization mode full 16 or overlapped
		// undecided, so 2 modes of combining alpha - same as rgb, or use center tile only
		// Assuming same size of both image sets
		final int tilesX = quadCLT_main.tp.getTilesX();
		final int tilesY = quadCLT_main.tp.getTilesY();

		final boolean keep_lt_corr_combo = clt_parameters.corr_keep;
		// FIXME: Remove those huge arrays when not needed!
		if (clt_parameters.correlate){
			if (keep_lt_corr_combo) clt_corr_combo =    new double [ImageDtt.TCORR_TITLES.length][tilesY][tilesX][];
			texture_tiles_main =     new double [tilesY][tilesX][][]; // ["RGBA".length()][];
			texture_tiles_aux =     new double [tilesY][tilesX][][]; // ["RGBA".length()][];
			for (int i = 0; i < tilesY; i++){
				for (int j = 0; j < tilesX; j++){
					if (keep_lt_corr_combo) for (int k = 0; k<clt_corr_combo.length; k++) clt_corr_combo[k][i][j] = null;
					texture_tiles_main[i][j] = null;
					texture_tiles_aux[i][j] = null;
				}
			}
		}

		double [][] disparity_bimap  = new double [ImageDtt.BIDISPARITY_TITLES.length][]; //[0] -residual disparity, [1] - orthogonal (just for debugging) last 4 - max pixel differences

656 657 658
		ImageDtt image_dtt = new ImageDtt(
				clt_parameters.transform_size,
				quadCLT_main.isMonochrome(),
659
				quadCLT_main.isLwir(),
660
				clt_parameters.getScaleStrength(false));
661

662 663 664 665 666 667 668 669
		double [][] ml_data = null;
//		int [][] woi_tops = {quadCLT_main.woi_tops,quadCLT_aux.woi_tops};
		final double [][][]       ers_delay = get_ers?(new double [2][][]):null;


		final double [][][][][][][] clt_bidata = // new double[2][quad][nChn][tilesY][tilesX][][]; // first index - main/aux
				image_dtt.clt_bi_quad (
						clt_parameters,                       // final EyesisCorrectionParameters.CLTParameters       clt_parameters,
670
						clt_parameters.getFatZero(image_dtt.isMonochrome()),  // final double              fatzero,         // May use correlation fat zero from 2 different parameters - fat_zero and rig.ml_fatzero
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
						notch_mode,                           //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
						lt_rad,                               // final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
						// first measurement - use default setting
						clt_parameters.rig.no_int_x0, // boolean   no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
						tile_op_main,                         // final int [][]            tile_op_main,    // [tilesY][tilesX] - what to do - 0 - nothing for this tile
						disparity_array_main,                 // final double [][]         disparity_array, // [tilesY][tilesX] - individual per-tile expected disparity
						quadCLT_main.image_data,              // final double [][][]       image_data_main, // first index - number of image in a quad
						quadCLT_aux.image_data,               // final double [][][]       image_data_aux,  // first index - number of image in a quad
						quadCLT_main.saturation_imp,          // final boolean [][]        saturation_main, // (near) saturated pixels or null
						quadCLT_aux.saturation_imp,           // final boolean [][]        saturation_aux,  // (near) saturated pixels or null
						// correlation results - combo will be for the correation between two quad cameras
						clt_corr_combo,                       // final double [][][][]     clt_corr_combo,  // [type][tilesY][tilesX][(2*transform_size-1)*(2*transform_size-1)] // if null - will not calculate
						// [type][tilesY][tilesX] should be set by caller
						// types: 0 - selected correlation (product+offset), 1 - sum
						disparity_bimap,                      // final double [][]    disparity_bimap, // [23][tilesY][tilesX]
						ml_data,                              // 	final double [][]         ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
						texture_tiles_main,                   // final double [][][][]     texture_tiles_main, // [tilesY][tilesX]["RGBA".length()][];  null - will skip images combining
						texture_tiles_aux,                    // final double [][][][]     texture_tiles_aux,  // [tilesY][tilesX]["RGBA".length()][];  null - will skip images combining
						imp_quad_main[0].getWidth(),          // final int                 width,
						quadCLT_main.getGeometryCorrection(), // final GeometryCorrection  geometryCorrection_main,
						quadCLT_aux.getGeometryCorrection(),  // final GeometryCorrection  geometryCorrection_aux,
						quadCLT_main.getCLTKernels(),         // final double [][][][][][] clt_kernels_main, // [channel_in_quad][color][tileY][tileX][band][pixel] , size should match image (have 1 tile around)
						quadCLT_aux.getCLTKernels(),          // final double [][][][][][] clt_kernels_aux,  // [channel_in_quad][color][tileY][tileX][band][pixel] , size should match image (have 1 tile around)
						clt_parameters.corr_magic_scale,      // final double              corr_magic_scale, // still not understood coefficient that reduces reported disparity value.  Seems to be around 0.85
						true,                                 // 	final boolean             keep_clt_data,
//						woi_tops,                             // final int [][]            woi_tops,
						ers_delay,                            // final double [][][]       ers_delay,        // if not null - fill with tile center acquisition delay
						threadsMax,                           // final int                 threadsMax,  // maximal number of threads to launch
						debugLevel);                          // final int                 globalDebugLevel);


		if (ers_delay !=null) {
			showERSDelay(ers_delay);
		}

		double [][] texture_nonoverlap_main = null;
		double [][] texture_nonoverlap_aux = null;
		double [][] texture_overlap_main = null;
		double [][] texture_overlap_aux = null;
		String [] rgba_titles = {"red","blue","green","alpha"};
		String [] rgba_weights_titles = {"red","blue","green","alpha","port0","port1","port2","port3","r-rms","b-rms","g-rms","w-rms"};
		if ((texture_tiles_main != null) && (texture_tiles_aux != null)){
			if (clt_parameters.show_nonoverlap){
714
				texture_nonoverlap_main = image_dtt.combineRBGATiles(
715
						texture_tiles_main,                 // array [tp.tilesY][tp.tilesX][4][4*transform_size] or [tp.tilesY][tp.tilesX]{null}
716
//						image_dtt.transform_size,
717 718 719 720 721 722
						false,                         // when false - output each tile as 16x16, true - overlap to make 8x8
						clt_parameters.sharp_alpha,    // combining mode for alpha channel: false - treat as RGB, true - apply center 8x8 only
						threadsMax,                    // maximal number of threads to launch
						debugLevel);
				sdfa_instance.showArrays(
						texture_nonoverlap_main,
723 724
						tilesX * (2 * image_dtt.transform_size),
						tilesY * (2 * image_dtt.transform_size),
725 726 727 728
						true,
						name + "-TXTNOL-D"+clt_parameters.disparity+"-MAIN",
						(clt_parameters.keep_weights?rgba_weights_titles:rgba_titles));

729
				texture_nonoverlap_aux = image_dtt.combineRBGATiles(
730
						texture_tiles_aux,                 // array [tp.tilesY][tp.tilesX][4][4*transform_size] or [tp.tilesY][tp.tilesX]{null}
731
//						image_dtt.transform_size,
732 733 734 735 736 737
						false,                         // when false - output each tile as 16x16, true - overlap to make 8x8
						clt_parameters.sharp_alpha,    // combining mode for alpha channel: false - treat as RGB, true - apply center 8x8 only
						threadsMax,                    // maximal number of threads to launch
						debugLevel);
				sdfa_instance.showArrays(
						texture_nonoverlap_aux,
738 739
						tilesX * (2 * image_dtt.transform_size),
						tilesY * (2 * image_dtt.transform_size),
740 741 742 743 744 745
						true,
						name + "-TXTNOL-D"+clt_parameters.disparity+"-AUX",
						(clt_parameters.keep_weights?rgba_weights_titles:rgba_titles));
			}
			if (!infinity_corr && (clt_parameters.show_overlap || clt_parameters.show_rgba_color)){
				int alpha_index = 3;
746
				texture_overlap_main = image_dtt.combineRBGATiles(
747
						texture_tiles_main,                 // array [tp.tilesY][tp.tilesX][4][4*transform_size] or [tp.tilesY][tp.tilesX]{null}
748
//						image_dtt.transform_size,
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
						true,                         // when false - output each tile as 16x16, true - overlap to make 8x8
						clt_parameters.sharp_alpha,    // combining mode for alpha channel: false - treat as RGB, true - apply center 8x8 only
						threadsMax,                    // maximal number of threads to launch
						debugLevel);
				if (clt_parameters.alpha1 > 0){ // negative or 0 - keep alpha as it was
					double scale = (clt_parameters.alpha1 > clt_parameters.alpha0) ? (1.0/(clt_parameters.alpha1 - clt_parameters.alpha0)) : 0.0;
					for (int i = 0; i < texture_overlap_main[alpha_index].length; i++){
						double d = texture_overlap_main[alpha_index][i];
						if      (d >=clt_parameters.alpha1) d = 1.0;
						else if (d <=clt_parameters.alpha0) d = 0.0;
						else d = scale * (d- clt_parameters.alpha0);
						texture_overlap_main[alpha_index][i] = d;
					}
				}

764
				texture_overlap_aux = image_dtt.combineRBGATiles(
765
						texture_tiles_aux,                 // array [tp.tilesY][tp.tilesX][4][4*transform_size] or [tp.tilesY][tp.tilesX]{null}
766
//						image_dtt.transform_size,
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
						true,                         // when false - output each tile as 16x16, true - overlap to make 8x8
						clt_parameters.sharp_alpha,    // combining mode for alpha channel: false - treat as RGB, true - apply center 8x8 only
						threadsMax,                    // maximal number of threads to launch
						debugLevel);
				if (clt_parameters.alpha1 > 0){ // negative or 0 - keep alpha as it was
					double scale = (clt_parameters.alpha1 > clt_parameters.alpha0) ? (1.0/(clt_parameters.alpha1 - clt_parameters.alpha0)) : 0.0;
					for (int i = 0; i < texture_overlap_aux[alpha_index].length; i++){
						double d = texture_overlap_aux[alpha_index][i];
						if      (d >=clt_parameters.alpha1) d = 1.0;
						else if (d <=clt_parameters.alpha0) d = 0.0;
						else d = scale * (d- clt_parameters.alpha0);
						texture_overlap_aux[alpha_index][i] = d;
					}
				}

				if (!batch_mode && clt_parameters.show_overlap) {
					sdfa_instance.showArrays(
							texture_overlap_main,
785 786
							tilesX * image_dtt.transform_size,
							tilesY * image_dtt.transform_size,
787 788 789 790 791 792 793
							true,
							name + "-TXTOL-D"+clt_parameters.disparity+"-MAIN",
							(clt_parameters.keep_weights?rgba_weights_titles:rgba_titles));
				}
				if (!batch_mode && clt_parameters.show_overlap) {
					sdfa_instance.showArrays(
							texture_overlap_aux,
794 795
							tilesX * image_dtt.transform_size,
							tilesY * image_dtt.transform_size,
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
							true,
							name + "-TXTOL-D"+clt_parameters.disparity+"-AUX",
							(clt_parameters.keep_weights?rgba_weights_titles:rgba_titles));
				}


				if (!batch_mode && clt_parameters.show_rgba_color) {
					// for now - use just RGB. Later add option for RGBA
					double [][] texture_rgb_main = {texture_overlap_main[0],texture_overlap_main[1],texture_overlap_main[2]};
					double [][] texture_rgba_main = {texture_overlap_main[0],texture_overlap_main[1],texture_overlap_main[2],texture_overlap_main[3]};
					double [][] texture_rgb_aux = {texture_overlap_aux[0],texture_overlap_aux[1],texture_overlap_aux[2]};
					double [][] texture_rgba_aux = {texture_overlap_aux[0],texture_overlap_aux[1],texture_overlap_aux[2],texture_overlap_aux[3]};
					ImagePlus imp_texture_main = quadCLT_main.linearStackToColor(
							clt_parameters,
							colorProcParameters,
							rgbParameters,
							name+"-texture", // String name,
							"-D"+clt_parameters.disparity+"-MAIN", //String suffix, // such as disparity=...
							toRGB,
							!quadCLT_main.correctionsParameters.jpeg, // boolean bpp16, // 16-bit per channel color mode for result
							false, // true, // boolean saveShowIntermediate, // save/show if set globally
							false, // true, // boolean saveShowFinal,        // save/show result (color image?)
							((clt_parameters.alpha1 > 0)? texture_rgba_main: texture_rgb_main),
819 820
							tilesX *  image_dtt.transform_size,
							tilesY *  image_dtt.transform_size,
821 822 823 824
							1.0,         // double scaleExposure, // is it needed?
							debugLevel );
					ImagePlus imp_texture_aux = quadCLT_aux.linearStackToColor(
							clt_parameters,
825
							colorProcParameters_aux,
826 827 828 829 830 831 832 833
							rgbParameters,
							name+"-texture", // String name,
							"-D"+clt_parameters.disparity+"-AUX", //String suffix, // such as disparity=...
							toRGB,
							!quadCLT_aux.correctionsParameters.jpeg, // boolean bpp16, // 16-bit per channel color mode for result
							false, // true, // boolean saveShowIntermediate, // save/show if set globally
							false, // true, // boolean saveShowFinal,        // save/show result (color image?)
							((clt_parameters.alpha1 > 0)? texture_rgba_aux: texture_rgb_aux),
834 835
							tilesX *  image_dtt.transform_size,
							tilesY *  image_dtt.transform_size,
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 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
							1.0,         // double scaleExposure, // is it needed?
							debugLevel );
					int width = imp_texture_main.getWidth();
					int height =imp_texture_main.getHeight();
					ImageStack texture_stack=new ImageStack(width,height);
					texture_stack.addSlice("main",      imp_texture_main.getProcessor().getPixels());
					texture_stack.addSlice("auxiliary", imp_texture_aux. getProcessor().getPixels());
					ImagePlus imp_texture_stack = new ImagePlus(name+"-TEXTURES-D"+clt_parameters.disparity, texture_stack);
					imp_texture_stack.getProcessor().resetMinAndMax();
					//					  imp_texture_stack.updateAndDraw();
					imp_texture_stack.show();
				}
			}
		}
		// visualize correlation results (will be for inter-pair correlation)
		if (clt_corr_combo!=null){
			if (disparity_bimap != null){
				if (!batch_mode && clt_parameters.show_map &&  (debugLevel > -2)){
					sdfa_instance.showArrays(
							disparity_bimap,
							tilesX,
							tilesY,
							true,
							name+"-DISP_MAP-D"+clt_parameters.disparity,
							ImageDtt.BIDISPARITY_TITLES);
					boolean [] trusted = 	  getTrustedDisparity(
							quadCLT_main,  // QuadCLT            quadCLT_main,  // tiles should be set
							quadCLT_aux,   // QuadCLT            quadCLT_aux,
							true,          // boolean            use_individual,
							0.14,          // double             min_combo_strength,    // check correlation strength combined for all 3 correlations
							clt_parameters.grow_disp_trust,       // double             max_trusted_disparity, // 4.0 -> change to rig_trust
							1.0,           // double             trusted_tolerance,
							null,          // boolean []         was_trusted,
							disparity_bimap ); // double [][]        bimap // current state of measurements
					for (int layer = 0; layer < disparity_bimap.length; layer ++) if (disparity_bimap[layer] != null){
						for (int nTile = 0; nTile < disparity_bimap[layer].length; nTile++) {
							if (!trusted[nTile]) disparity_bimap[layer][nTile] = Double.NaN;
						}
					}
					sdfa_instance.showArrays(
							disparity_bimap,
							tilesX,
							tilesY,
							true,
							name+"-DISP_MAP_TRUSTED-D"+clt_parameters.disparity,
							ImageDtt.BIDISPARITY_TITLES);
				}
			}

			if (!batch_mode && !infinity_corr && clt_parameters.corr_show && (debugLevel > -2)){
				double [][] corr_rslt = new double [clt_corr_combo.length][];
				String [] titles = new String[clt_corr_combo.length]; // {"combo","sum"};
				for (int i = 0; i< titles.length; i++) titles[i] = ImageDtt.TCORR_TITLES[i];
				for (int i = 0; i<corr_rslt.length; i++) {
					corr_rslt[i] = image_dtt.corr_dbg(
							clt_corr_combo[i],
892
							2*image_dtt.transform_size - 1,
893 894 895 896 897 898 899
							clt_parameters.corr_border_contrast,
							threadsMax,
							debugLevel);
				}

				sdfa_instance.showArrays(
						corr_rslt,
900 901
						tilesX*(2*image_dtt.transform_size),
						tilesY*(2*image_dtt.transform_size),
902 903 904
						true,
						name + "-CORR-D"+clt_parameters.disparity,
						titles );
905
			}
906 907 908 909
		}
		//		  final double [][][][][][][] clt_bidata = // new double[2][quad][nChn][tilesY][tilesX][][]; // first index - main/aux
		int quad_main = clt_bidata[0].length;
		int quad_aux =  clt_bidata[1].length;
910

911 912 913 914 915
		if (!infinity_corr && (clt_parameters.gen_chn_img || clt_parameters.gen_4_img || clt_parameters.gen_chn_stacks)) {
			ImagePlus [] imps_RGB = new ImagePlus[quad_main+quad_aux];
			for (int iQuadComb = 0; iQuadComb < imps_RGB.length; iQuadComb++){
				int iAux = (iQuadComb >= quad_main) ? 1 : 0;
				int iSubCam= iQuadComb - iAux * quad_main;
916

917 918 919
				// Uncomment to have master/aux names
				//				  String title=name+"-"+String.format("%s%02d", ((iAux>0)?"A":"M"),iSubCam);
				String title=name+"-"+String.format("%02d", iQuadComb);
920

921
				if (clt_parameters.getCorrSigma(image_dtt.isMonochrome()) > 0){ // no filter at all
922 923
					for (int chn = 0; chn < clt_bidata[iAux][iSubCam].length; chn++) {
						image_dtt.clt_lpf(
924
								clt_parameters.getCorrSigma(image_dtt.isMonochrome()),
925
								clt_bidata[iAux][iSubCam][chn],
926
//								image_dtt.transform_size,
927 928 929 930
								threadsMax,
								debugLevel);
					}
				}
931

932 933 934 935 936 937 938 939 940 941 942 943 944
				if (debugLevel > 0){
					System.out.println("--tilesX="+tilesX);
					System.out.println("--tilesY="+tilesY);
				}
				if (!batch_mode && (debugLevel > 0)){
					double [][] clt = new double [clt_bidata[iAux][iSubCam].length*4][];
					for (int chn = 0; chn < clt_bidata[iAux][iSubCam].length; chn++) {
						double [][] clt_set = image_dtt.clt_dbg(
								clt_bidata[iAux][iSubCam][chn],
								threadsMax,
								debugLevel);
						for (int ii = 0; ii < clt_set.length; ii++) clt[chn*4+ii] = clt_set[ii];
					}
945

946 947
					if (debugLevel > 0){
						sdfa_instance.showArrays(clt,
948 949
								tilesX*image_dtt.transform_size,
								tilesY*image_dtt.transform_size,
950 951 952 953 954 955 956 957
								true,
								results[iQuadComb].getTitle()+"-CLT-D"+clt_parameters.disparity);
					}
				}
				double [][] iclt_data = new double [clt_bidata[iAux][iSubCam].length][];
				for (int chn=0; chn<iclt_data.length;chn++){
					iclt_data[chn] = image_dtt.iclt_2d(
							clt_bidata[iAux][iSubCam][chn], // scanline representation of dcd data, organized as dct_size x dct_size tiles
958
//							image_dtt.transform_size,  // final int
959 960 961 962 963
							clt_parameters.clt_window,      // window_type
							15,                             // clt_parameters.iclt_mask,       //which of 4 to transform back
							0,                              // clt_parameters.dbg_mode,        //which of 4 to transform back
							threadsMax,
							debugLevel);
964

965 966 967
				}

				if (clt_parameters.gen_chn_stacks) sdfa_instance.showArrays(iclt_data,
968 969
						(tilesX + 0) * image_dtt.transform_size,
						(tilesY + 0) * image_dtt.transform_size,
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
						true,
						results[iQuadComb].getTitle()+"-ICLT-RGB-D"+clt_parameters.disparity);
				if (!clt_parameters.gen_chn_img) continue;

				imps_RGB[iQuadComb] = quadCLT_main.linearStackToColor( // probably no need to separate and process the second half with quadCLT_aux
						clt_parameters,
						colorProcParameters,
						rgbParameters,
						title, // String name,
						"-D"+clt_parameters.disparity, //String suffix, // such as disparity=...
						toRGB,
						!quadCLT_main.correctionsParameters.jpeg, // boolean bpp16, // 16-bit per channel color mode for result
						!batch_mode, // true, // boolean saveShowIntermediate, // save/show if set globally
						false, // boolean saveShowFinal,        // save/show result (color image?)
						iclt_data,
985 986
						tilesX *  image_dtt.transform_size,
						tilesY *  image_dtt.transform_size,
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
						scaleExposures[iAux][iSubCam], // double scaleExposure, // is it needed?
						debugLevel );
			} // end of generating shifted channel images



			if (clt_parameters.gen_chn_img) {
				// combine to a sliced color image
				// assuming total number of images to be multiple of 4
				//			  int [] slice_seq = {0,1,3,2}; //clockwise
				int [] slice_seq = new int[results.length];
				for (int i = 0; i < slice_seq.length; i++) {
					slice_seq[i] = i ^ ((i >> 1) & 1); // 0,1,3,2,4,5,7,6, ...
				}
				int width = imps_RGB[0].getWidth();
				int height = imps_RGB[0].getHeight();
				ImageStack array_stack=new ImageStack(width,height);
				for (int i = 0; i<slice_seq.length; i++){
					if (imps_RGB[slice_seq[i]] != null) {
						array_stack.addSlice("port_"+slice_seq[i], imps_RGB[slice_seq[i]].getProcessor().getPixels());
					} else {
						array_stack.addSlice("port_"+slice_seq[i], results[slice_seq[i]].getProcessor().getPixels());
					}
				}
				ImagePlus imp_stack = new ImagePlus(name+"-SHIFTED-D"+clt_parameters.disparity, array_stack);
				imp_stack.getProcessor().resetMinAndMax();
				if (!batch_mode) {
					imp_stack.updateAndDraw();
				}
				//imp_stack.getProcessor().resetMinAndMax();
				//imp_stack.show();
				//				  eyesisCorrections.saveAndShow(imp_stack, this.correctionsParameters);
				quadCLT_main.eyesisCorrections.saveAndShowEnable(
						imp_stack,  // ImagePlus             imp,
						quadCLT_main.correctionsParameters, // EyesisCorrectionParameters.CorrectionParameters  correctionsParameters,
						true, // boolean               enableSave,
						!batch_mode) ;// boolean               enableShow);
			}
			if (clt_parameters.gen_4_img) {
				// Save as individual JPEG images in the model directory
				String x3d_path= quadCLT_main.correctionsParameters.selectX3dDirectory(
						name, // quad timestamp. Will be ignored if correctionsParameters.use_x3d_subdirs is false
						quadCLT_main.correctionsParameters.x3dModelVersion,
						true,  // smart,
						true);  //newAllowed, // save
				for (int sub_img = 0; sub_img < imps_RGB.length; sub_img++){
					quadCLT_main.eyesisCorrections.saveAndShow(
							imps_RGB[sub_img],
							x3d_path,
							quadCLT_main.correctionsParameters.png && !clt_parameters.black_back,
							!batch_mode && clt_parameters.show_textures,
							quadCLT_main.correctionsParameters.JPEG_quality, // jpegQuality); // jpegQuality){//  <0 - keep current, 0 - force Tiff, >0 use for JPEG
							(debugLevel > 0) ? debugLevel : 1); // int debugLevel (print what it saves)
				}
				String model_path= quadCLT_main.correctionsParameters.selectX3dDirectory(
						name, // quad timestamp. Will be ignored if correctionsParameters.use_x3d_subdirs is false
						null,
						true,  // smart,
						true);  //newAllowed, // save

				quadCLT_main.createThumbNailImage(
						imps_RGB[0],
						model_path,
						"thumb",
						debugLevel);
1052 1053 1054 1055

			}
		}

1056
		return results;
1057 1058
	}

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
	public static void showImageFromGPU() {
		int width =  2592+8;
		int height = 1936+8;
		int l = width*height;
		String path = "/home/eyesis/workspace-python3/nvidia_dct8x8/clt/main_chn0.rbg";
		String [] titles= {"R","B","G"};
		float [] img_rbg = getFloatsFromFile(path);
		float [][] img = new float [3][l];
		for(int nc = 0; nc < 3; nc++) {
			System.arraycopy(img_rbg, l * nc, img[nc], 0 ,l);
		}

1071
		(new ShowDoubleFloatArrays()).showArrays(
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
				img,
				width,
				height,
				true,
				"RBG",
				titles);

	}

	public static float [] getFloatsFromFile(String filepath) {
		float [] fdata  = null;
		try {
			FileInputStream inFile = new FileInputStream(filepath);
//			DataInputStream din = new DataInputStream(inFile);
			FileChannel inChannel = inFile.getChannel();
			int cl = (int) inChannel.size();
			ByteBuffer buffer = ByteBuffer.allocateDirect(cl); //1024*1024*60);
			buffer.order(ByteOrder.LITTLE_ENDIAN);
			buffer.clear();
			inChannel.read(buffer);
			buffer.flip();
			FloatBuffer fb = buffer.asFloatBuffer();
			fdata = new float[fb.limit()];
			fb.get(fdata);
//			fdata = fb.array();
			inFile.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return fdata;

	}

Andrey Filippov's avatar
Andrey Filippov committed
1110 1111 1112 1113 1114
	public void saveFloatKernels(String file_prefix,
			                     double [][][][][][] clt_kernels,
			                     double [][][]       image_data,
			                     double [][][]       port_xy,
			                     boolean transpose) throws IOException {
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 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
		if (clt_kernels != null) {
			for (int chn = 0; chn < clt_kernels.length; chn++) {
				String kern_path = file_prefix+"_chn"+chn+(transpose?"_transposed":"")+".kernel";
				String offs_path = file_prefix+"_chn"+chn+(transpose?"_transposed":"")+".kernel_offsets";
				FileOutputStream fos = new FileOutputStream(kern_path);
				DataOutputStream dos = new DataOutputStream(fos);
				WritableByteChannel channel = Channels.newChannel(dos);
				int float_buffer_size = clt_kernels[chn].length * clt_kernels[chn][0].length* clt_kernels[chn][0][0].length * 4 * 64;
				ByteBuffer bb = ByteBuffer.allocate(float_buffer_size * 4);
				bb.order(ByteOrder.LITTLE_ENDIAN);
				bb.clear();
				for (int ty = 0; ty <  clt_kernels[chn][0].length; ty++) {
					for (int tx = 0; tx <  clt_kernels[chn][0][ty].length; tx++) {
						for (int col = 0; col <  clt_kernels[chn].length; col++) {
							for (int p = 0; p < 4; p++) {
								double [] pa = clt_kernels[chn][col][ty][tx][p];
								for (int i0 = 0; i0 < 64; i0++) {
									int i;
									if (transpose) {
										i = ((i0 & 7) << 3) + ((i0 >>3) & 7);
									} else {
										i = i0;
									}
//									dos.writeFloat((float)pa[i]);
									bb.putFloat((float)pa[i]);
								}
							}
						}
					}
				}
				bb.flip();
				channel.write(bb);
				dos.close();

				fos = new FileOutputStream(offs_path);
				dos = new DataOutputStream(fos);
				channel = Channels.newChannel(dos);
				float_buffer_size = clt_kernels[chn][0].length * clt_kernels[chn][0].length* clt_kernels[chn][0][0].length * 4 * clt_kernels[chn][0][0][0][4].length;
				bb = ByteBuffer.allocate(float_buffer_size * 4);
				bb.order(ByteOrder.LITTLE_ENDIAN);
				bb.clear();
				for (int ty = 0; ty <  clt_kernels[chn][0].length; ty++) {
					for (int tx = 0; tx <  clt_kernels[chn][0][ty].length; tx++) {
						for (int col = 0; col <  clt_kernels[chn].length; col++) {
							double [] pa = clt_kernels[chn][col][ty][tx][4];
							for (int i = 0; i < pa.length; i++) {
//								dos.writeFloat((float)pa[i]);
								bb.putFloat((float)pa[i]);
							}
						}
					}
				}
				bb.flip();
				channel.write(bb);
				dos.close();
			}
		}

		if (image_data != null) {
			for (int chn = 0; chn < image_data.length; chn++) {
				String img_path =  file_prefix+"_chn"+chn+".bayer";
				FileOutputStream fos = new FileOutputStream(img_path);
				DataOutputStream dos = new DataOutputStream(fos);
				WritableByteChannel channel = Channels.newChannel(dos);
				ByteBuffer bb = ByteBuffer.allocate(image_data[chn][0].length * 4);
				bb.order(ByteOrder.LITTLE_ENDIAN);
				bb.clear();
				for (int i = 0; i <  image_data[chn][0].length; i++) {
//					dos.writeFloat((float) (image_data[chn][0][i] + image_data[chn][1][i] + image_data[chn][2][i]));
1184 1185 1186 1187 1188 1189
					double d = 0;
					for (int c = 0; c < image_data[chn].length; c++) {
						d += image_data[chn][c][i];
					}
//					bb.putFloat((float) (image_data[chn][0][i] + image_data[chn][1][i] + image_data[chn][2][i]));
					bb.putFloat((float) d);
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
				}
				bb.flip();
				channel.write(bb);
				dos.close();
			}
		}
		if (port_xy != null) {
			for (int chn = 0; chn < port_xy[0].length; chn++) {
				String img_path =  file_prefix+"_chn"+chn+".portsxy";
				FileOutputStream fos = new FileOutputStream(img_path);
				DataOutputStream dos = new DataOutputStream(fos);
				WritableByteChannel channel = Channels.newChannel(dos);
				ByteBuffer bb = ByteBuffer.allocate(port_xy.length * 2 * 4);
				bb.order(ByteOrder.LITTLE_ENDIAN);
				bb.clear();
				for (int i = 0; i <  port_xy.length; i++) {
					bb.putFloat((float) (port_xy[i][chn][0])); // x-offset
					bb.putFloat((float) (port_xy[i][chn][1])); // y-offset
				}
				bb.flip();
				channel.write(bb);
				dos.close();
			}
		}
	}



	public void saveFloatKernelsBigEndian(String file_prefix,
			double [][][][][][] clt_kernels,
			double [][][]       image_data,
			double [][][]       port_xy,
			boolean transpose) throws IOException {
Andrey Filippov's avatar
Andrey Filippov committed
1223 1224 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
		if (clt_kernels != null) {
			for (int chn = 0; chn < clt_kernels.length; chn++) {
				String kern_path = file_prefix+"_chn"+chn+(transpose?"_transposed":"")+".kernel";
				String offs_path = file_prefix+"_chn"+chn+(transpose?"_transposed":"")+".kernel_offsets";
				FileOutputStream fos = new FileOutputStream(kern_path);
				DataOutputStream dos = new DataOutputStream(fos);
				for (int ty = 0; ty <  clt_kernels[chn][0].length; ty++) {
					for (int tx = 0; tx <  clt_kernels[chn][0][ty].length; tx++) {
						for (int col = 0; col <  clt_kernels[chn].length; col++) {
							for (int p = 0; p < 4; p++) {
								double [] pa = clt_kernels[chn][col][ty][tx][p];
								for (int i0 = 0; i0 < 64; i0++) {
									int i;
									if (transpose) {
										i = ((i0 & 7) << 3) + ((i0 >>3) & 7);
									} else {
										i = i0;
									}
									dos.writeFloat((float)pa[i]);
								}
							}
						}
					}
				}
				dos.close();
				fos = new FileOutputStream(offs_path);
				dos = new DataOutputStream(fos);

				for (int ty = 0; ty <  clt_kernels[chn][0].length; ty++) {
					for (int tx = 0; tx <  clt_kernels[chn][0][ty].length; tx++) {
						for (int col = 0; col <  clt_kernels[chn].length; col++) {
							double [] pa = clt_kernels[chn][col][ty][tx][4];
							for (int i = 0; i < pa.length; i++) {
								dos.writeFloat((float)pa[i]);
							}
						}
					}
				}
1261

Andrey Filippov's avatar
Andrey Filippov committed
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
				dos.close();
			}
		}

		if (image_data != null) {
			for (int chn = 0; chn < image_data.length; chn++) {
				String img_path =  file_prefix+"_chn"+chn+".bayer";
				FileOutputStream fos = new FileOutputStream(img_path);
				DataOutputStream dos = new DataOutputStream(fos);
				for (int i = 0; i <  image_data[chn][0].length; i++) {
					dos.writeFloat((float) (image_data[chn][0][i] + image_data[chn][1][i] + image_data[chn][2][i]));
				}
				dos.close();
			}
		}
		if (port_xy != null) {
			for (int chn = 0; chn < port_xy[0].length; chn++) {
				String img_path =  file_prefix+"_chn"+chn+".portsxy";
				FileOutputStream fos = new FileOutputStream(img_path);
				DataOutputStream dos = new DataOutputStream(fos);
				for (int i = 0; i <  port_xy.length; i++) {
					dos.writeFloat((float) (port_xy[i][chn][0])); // x-offset
					dos.writeFloat((float) (port_xy[i][chn][1])); // y-offset
				}
				dos.close();
			}

		}

	}
1292

1293

1294
	public ImagePlus [] processCLTQuadCorrPairForGPU(
1295
			String                                         save_prefix,
1296 1297 1298 1299 1300 1301
			QuadCLT                                        quadCLT_main,
			QuadCLT                                        quadCLT_aux,
			ImagePlus []                                   imp_quad_main,
			ImagePlus []                                   imp_quad_aux,
			boolean [][]                                   saturation_main, // (near) saturated pixels or null
			boolean [][]                                   saturation_aux, // (near) saturated pixels or null
1302
			CLTParameters       clt_parameters,
1303
			EyesisCorrectionParameters.DebayerParameters   debayerParameters,
1304 1305
			ColorProcParameters                            colorProcParameters,
			ColorProcParameters                            colorProcParameters_aux,
1306 1307 1308 1309 1310 1311 1312 1313 1314
			EyesisCorrectionParameters.RGBParameters       rgbParameters,
			double []	                                     scaleExposures_main, // probably not needed here - restores brightness of the final image
			double []	                                     scaleExposures_aux, // probably not needed here - restores brightness of the final image
			boolean                                        notch_mode, // use pole-detection mode for inter-camera correlation
			final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel){
		final boolean      batch_mode = clt_parameters.batch_run; //disable any debug images
1315
		final boolean get_ers = !batch_mode;
1316 1317 1318 1319
		//		  boolean batch_mode = false;
		boolean infinity_corr = false;
		double [][] scaleExposures= {scaleExposures_main, scaleExposures_aux};
		boolean toRGB=     quadCLT_main.correctionsParameters.toRGB;
1320
		ShowDoubleFloatArrays sdfa_instance = new ShowDoubleFloatArrays(); // just for debugging? - TODO - move where it belongs
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
		// may use this.StartTime to report intermediate steps execution times
		String name=quadCLT_main.correctionsParameters.getModelName((String) imp_quad_main[0].getProperty("name"));
		String path= (String) imp_quad_main[0].getProperty("path"); // Only for debug output
		ImagePlus [] results = new ImagePlus[imp_quad_main.length + imp_quad_main.length];
		for (int i = 0; i < results.length; i++) {
			if (i< imp_quad_main.length) {
				results[i] = imp_quad_main[i];
			} else {
				results[i] = imp_quad_main[i-imp_quad_main.length];
			}
			results[i].setTitle(results[i].getTitle()+"RAW");
		}
		if (debugLevel>1) System.out.println("processing: "+path);
1334
/*		// 08/12/2020 Moved to conditionImageSet		
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
		getRigImageStacks(
				clt_parameters,  // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				quadCLT_main,    // QuadCLT                                         quadCLT_main,
				quadCLT_aux,     // QuadCLT                                          quadCLT_aux,
				imp_quad_main,   // ImagePlus []                                   imp_quad_main,
				imp_quad_aux,    // ImagePlus []                                    imp_quad_aux,
				saturation_main, // boolean [][]        saturation_main, // (near) saturated pixels or null
				saturation_aux, // boolean [][]        saturation_aux, // (near) saturated pixels or null
				threadsMax,      // maximal number of threads to launch
				debugLevel);     // final int        debugLevel);
1345
*/
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
		// temporary setting up tile task file (one integer per tile, bitmask
		// for testing defined for a window, later the tiles to process will be calculated based on previous passes results

		int [][]    tile_op_main = quadCLT_main.tp.setSameTileOp(clt_parameters,  clt_parameters.tile_task_op, debugLevel);
		//		  int [][]    tile_op_aux =  quadCLT_aux.tp.setSameTileOp (clt_parameters,  clt_parameters.tile_task_op, debugLevel);

		double [][] disparity_array_main = quadCLT_main.tp.setSameDisparity(clt_parameters.disparity); // [tp.tilesY][tp.tilesX] - individual per-tile expected disparity

		//TODO: Add array of default disparity - use for combining images in force disparity mode (no correlation), when disparity is predicted from other tiles

		// start with all old arrays, remove some later
		double [][][][]     clt_corr_combo =        null;
		double [][][][]     texture_tiles_main =    null; // [tp.tilesY][tp.tilesX]["RGBA".length()][]; // tiles will be 16x16, 2 visualization mode full 16 or overlapped
		double [][][][]     texture_tiles_aux =     null; // [tp.tilesY][tp.tilesX]["RGBA".length()][]; // tiles will be 16x16, 2 visualization mode full 16 or overlapped
		// undecided, so 2 modes of combining alpha - same as rgb, or use center tile only
		// Assuming same size of both image sets
		final int tilesX = quadCLT_main.tp.getTilesX();
		final int tilesY = quadCLT_main.tp.getTilesY();

		final boolean keep_lt_corr_combo = clt_parameters.corr_keep;
		// FIXME: Remove those huge arrays when not needed!
		if (clt_parameters.correlate){
			if (keep_lt_corr_combo) clt_corr_combo =    new double [ImageDtt.TCORR_TITLES.length][tilesY][tilesX][];
			texture_tiles_main =     new double [tilesY][tilesX][][]; // ["RGBA".length()][];
			texture_tiles_aux =     new double [tilesY][tilesX][][]; // ["RGBA".length()][];
			for (int i = 0; i < tilesY; i++){
				for (int j = 0; j < tilesX; j++){
					if (keep_lt_corr_combo) for (int k = 0; k<clt_corr_combo.length; k++) clt_corr_combo[k][i][j] = null;
					texture_tiles_main[i][j] = null;
					texture_tiles_aux[i][j] = null;
				}
			}

		}
		double [][] disparity_bimap  = new double [ImageDtt.BIDISPARITY_TITLES.length][]; //[0] -residual disparity, [1] - orthogonal (just for debugging) last 4 - max pixel differences
1381 1382 1383
		ImageDtt image_dtt = new ImageDtt(
				clt_parameters.transform_size,
				quadCLT_main.isMonochrome(),
1384
				quadCLT_main.isLwir(),
1385
				clt_parameters.getScaleStrength(false));
1386
		double [][] ml_data = null;
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
		double [][][]       ers_delay = get_ers?(new double [2][][]):null;
		// here all data is ready (images, kernels) to try GPU code
		float [][] main_bayer = new float [quadCLT_main.image_data.length][quadCLT_main.image_data[0][0].length];
		float [][] dst_bayer =  new float [quadCLT_main.image_data.length][quadCLT_main.image_data[0][0].length];
		for (int nc = 0; nc < main_bayer.length; nc++) {
			int nc1 = (nc +1) % 4;
			for (int i = 0; i < main_bayer[nc].length; i++) {
				main_bayer[nc1][i] = (float) (quadCLT_main.image_data[nc][0][i] + quadCLT_main.image_data[nc][1][i] + quadCLT_main.image_data[nc][2][i]);
				dst_bayer[nc][i]= nc*main_bayer[nc].length + i;
			}
		}
1398

Andrey Filippov's avatar
Andrey Filippov committed
1399
		double [][][]       port_xy_main_dbg = new double [tilesX*tilesY][][];
1400 1401
		double [][][]       port_xy_aux_dbg =  new double [tilesX*tilesY][][];
//		double [][][]       corr2ddata =       new double [1][][];
Andrey Filippov's avatar
Andrey Filippov committed
1402
		double [][] disparity_map = new double [ImageDtt.DISPARITY_TITLES.length][];
1403 1404

		final double [][][][][][][] clt_bidata = // new double[2][quad][nChn][tilesY][tilesX][][]; // first index - main/aux
Andrey Filippov's avatar
Andrey Filippov committed
1405
				image_dtt.clt_bi_quad_dbg (
1406
						clt_parameters,                       // final EyesisCorrectionParameters.CLTParameters       clt_parameters,
1407
						clt_parameters.getFatZero(image_dtt.isMonochrome()),              // final double              fatzero,         // May use correlation fat zero from 2 different parameters - fat_zero and rig.ml_fatzero
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
						notch_mode,                           //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
						lt_rad,                               // final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
						// first measurement - use default setting
						clt_parameters.rig.no_int_x0, // boolean   no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
						tile_op_main,                         // final int [][]            tile_op_main,    // [tilesY][tilesX] - what to do - 0 - nothing for this tile
						disparity_array_main,                 // final double [][]         disparity_array, // [tilesY][tilesX] - individual per-tile expected disparity
						quadCLT_main.image_data,              // final double [][][]       image_data_main, // first index - number of image in a quad
						quadCLT_aux.image_data,               // final double [][][]       image_data_aux,  // first index - number of image in a quad
						quadCLT_main.saturation_imp,          // final boolean [][]        saturation_main, // (near) saturated pixels or null
						quadCLT_aux.saturation_imp,           // final boolean [][]        saturation_aux,  // (near) saturated pixels or null
						// correlation results - combo will be for the correation between two quad cameras
						clt_corr_combo,                       // final double [][][][]     clt_corr_combo,  // [type][tilesY][tilesX][(2*transform_size-1)*(2*transform_size-1)] // if null - will not calculate
						// [type][tilesY][tilesX] should be set by caller
						// types: 0 - selected correlation (product+offset), 1 - sum
						disparity_bimap,                      // final double [][]    disparity_bimap, // [23][tilesY][tilesX]
						ml_data,                              // 	final double [][]         ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
Andrey Filippov's avatar
Andrey Filippov committed
1424
						disparity_map,                        // final double [][]         disparity_map,   // [8][tilesY][tilesX], only [6][] is needed on input or null - do not calculate
1425 1426 1427 1428 1429 1430 1431 1432 1433
						texture_tiles_main,                   // final double [][][][]     texture_tiles_main, // [tilesY][tilesX]["RGBA".length()][];  null - will skip images combining
						texture_tiles_aux,                    // final double [][][][]     texture_tiles_aux,  // [tilesY][tilesX]["RGBA".length()][];  null - will skip images combining
						imp_quad_main[0].getWidth(),          // final int                 width,
						quadCLT_main.getGeometryCorrection(), // final GeometryCorrection  geometryCorrection_main,
						quadCLT_aux.getGeometryCorrection(),  // final GeometryCorrection  geometryCorrection_aux,
						quadCLT_main.getCLTKernels(),         // final double [][][][][][] clt_kernels_main, // [channel_in_quad][color][tileY][tileX][band][pixel] , size should match image (have 1 tile around)
						quadCLT_aux.getCLTKernels(),          // final double [][][][][][] clt_kernels_aux,  // [channel_in_quad][color][tileY][tileX][band][pixel] , size should match image (have 1 tile around)
						clt_parameters.corr_magic_scale,      // final double              corr_magic_scale, // still not understood coefficient that reduces reported disparity value.  Seems to be around 0.85
						true,                                 // 	final boolean             keep_clt_data,
1434
						ers_delay,                            // final double [][][]       ers_delay,        // if not null - fill with tile center acquisition delay
1435
						threadsMax,                           // final int                 threadsMax,  // maximal number of threads to launch
Andrey Filippov's avatar
Andrey Filippov committed
1436 1437
						debugLevel,                           // final int                 globalDebugLevel);
						port_xy_main_dbg,                     // final double [][][]       port_xy_main_dbg, // for each tile/port save x,y pixel coordinates (gpu code development)
1438 1439
						port_xy_aux_dbg);                      // final double [][][]       port_xy_aux_dbg) // for each tile/port save x,y pixel coordinates (gpu code development)

Andrey Filippov's avatar
Andrey Filippov committed
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
/////		  double [][] disparity_map = new double [ImageDtt.DISPARITY_TITLES.length][]; //[0] -residual disparity, [1] - orthogonal (just for debugging)

		String [] sub_titles = new String [GPUTileProcessor.NUM_CAMS * (GPUTileProcessor.NUM_COLORS+1)];
		double [][] sub_disparity_map = new double [sub_titles.length][];
		for (int ncam = 0; ncam < GPUTileProcessor.NUM_CAMS; ncam++) {
			sub_disparity_map[ncam] = disparity_map[ncam + ImageDtt.IMG_DIFF0_INDEX];
			sub_titles[ncam] = ImageDtt.DISPARITY_TITLES[ncam + ImageDtt.IMG_DIFF0_INDEX];
			for (int ncol = 0; ncol < GPUTileProcessor.NUM_COLORS; ncol++) {
				sub_disparity_map[ncam + (ncol + 1)* GPUTileProcessor.NUM_CAMS] =
						disparity_map[ncam +ncol* GPUTileProcessor.NUM_CAMS+ ImageDtt.IMG_TONE_RGB];
				sub_titles[ncam + (ncol + 1)* GPUTileProcessor.NUM_CAMS] =
						ImageDtt.DISPARITY_TITLES[ncam +ncol* GPUTileProcessor.NUM_CAMS+ ImageDtt.IMG_TONE_RGB];
			}
		}
//		String [] sub_titles = {ImageDtt.DISPARITY_TITLES[ImageDtt.IMG_DIFF0_INDEX]
1455

Andrey Filippov's avatar
Andrey Filippov committed
1456 1457 1458 1459 1460 1461 1462
		(new ShowDoubleFloatArrays()).showArrays(
				sub_disparity_map,
	    		tilesX,
	    		tilesY,
				true,
				name + "-CPU-EXTRA-D"+clt_parameters.disparity,
				sub_titles);
1463 1464 1465 1466 1467 1468 1469 1470
		// Create list of all correlation pairs
		double [][][][][][] clt_data = clt_bidata[0];
		int numTiles = tilesX * tilesY;
		int numPairs = GPUTileProcessor.NUM_PAIRS;
		int [] corr_indices = new int [numTiles * numPairs];
		int indx=0;
		for (int i = 0; i < numTiles; i++) {
			for (int j = 0; j < numPairs; j++) {
1471
				corr_indices[indx++] = (i << GPUTileProcessor.CORR_NTILE_SHIFT) + j;
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
			}
		}
		double [][] corrs2d = image_dtt.get2DCorrs(
				clt_parameters,  // final CLTParameters       clt_parameters,
				clt_data,        // final double [][][][][][] clt_data, // [channel_in_quad][color][tileY][tileX][band][pixel];
				corr_indices,      // final int    []           pairs_list,
				threadsMax,      // final int                 threadsMax,  // maximal number of threads to launch
				debugLevel);     // final int                 debugLevel
		float [][] fcorrs2d = new float [corrs2d.length][corrs2d[0].length];
		// for compatibility with the actual GPUI output
		for (int n = 0; n < corrs2d.length; n++) {
			for (int i = 0; i < corrs2d[0].length; i++) {
				fcorrs2d[n][i] = (float) corrs2d[n][i];
			}
		}
		int [] wh = new int[2];
		double [][] dbg_corr = GPUTileProcessor.getCorr2DView(
	    		tilesX,
	    		tilesY,
	    		corr_indices,
	    		fcorrs2d,
	    		wh);
		(new ShowDoubleFloatArrays()).showArrays(
				dbg_corr,
				wh[0],
				wh[1],
				true,
Andrey Filippov's avatar
Andrey Filippov committed
1499
				name + "-CPU-CORR2D-D"+clt_parameters.disparity,
1500
				GPUTileProcessor.getCorrTitles());
1501

1502
		if ((save_prefix != null) && (save_prefix != "")) {
Andrey Filippov's avatar
Andrey Filippov committed
1503

1504 1505 1506
			if (debugLevel < -1000) {
				return null;
			}
Andrey Filippov's avatar
Andrey Filippov committed
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 1534 1535 1536 1537 1538 1539
			String kernel_dir = save_prefix+"clt/";
			File kdir = new File(kernel_dir);
			kdir.mkdir();
			//		boolean [][] what_to_save = {{false,false,true}, {false,false,true}};
			boolean [][] what_to_save = {{true,true,true}, {true,true,true}};
			try {
				saveFloatKernels(
						kernel_dir +"main", // String file_prefix,
//						(what_to_save[0][0]?clt_kernels_main:null), // double [][][][][][] clt_kernels, // null
						(what_to_save[0][0]?quadCLT_main.getCLTKernels():null), // double [][][][][][] clt_kernels, // null
						(what_to_save[0][1]?quadCLT_main.image_data:null),
						(what_to_save[0][2]?port_xy_main_dbg:null), // double [][][]       port_xy,
						true);
			} catch (IOException e) {
				System.out.println("Failed to save flattened kernels tp "+kernel_dir);
				// TODO Auto-generated catch block
				e.printStackTrace();
			} // boolean transpose);

			try {
				saveFloatKernels(
						kernel_dir +"aux", // String file_prefix,
//						(what_to_save[1][0]?clt_kernels_aux:null), // double [][][][][][] clt_kernels, // null
						(what_to_save[1][0]?quadCLT_aux.getCLTKernels():null), // double [][][][][][] clt_kernels, // null
						(what_to_save[1][1]?quadCLT_aux.image_data:null),
						(what_to_save[1][2]?port_xy_aux_dbg:null), // double [][][]       port_xy,
						true);
			} catch (IOException e) {
				System.out.println("Failed to save flattened kernels tp "+kernel_dir);
				e.printStackTrace();
			} // boolean transpose);

1540 1541 1542
			try {
				quadCLT_main.getGeometryCorrection().saveFloatsGPU(kernel_dir +"main");
			} catch (IOException e) {
1543
				System.out.println("Failed to save geometry correction data (float) to "+kernel_dir);
1544 1545 1546
				e.printStackTrace();
			}

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
			try {
				quadCLT_main.getGeometryCorrection().saveDoublesGPU(kernel_dir +"main");
			} catch (IOException e) {
				System.out.println("Failed to save geometry correction data (double) to "+kernel_dir);
				e.printStackTrace();
			}

			quadCLT_main.getGeometryCorrection().getCorrVector().getRotMatricesDbg();
			quadCLT_main.getGeometryCorrection().getCorrVector().getRotDeriveMatricesDbg();

1557 1558 1559 1560 1561 1562
			if (debugLevel < -1000) {
				return null;
			}
			if (ers_delay !=null) {
				showERSDelay(ers_delay);
			}
1563

1564
		}
1565 1566 1567 1568 1569 1570 1571
		double [][] texture_nonoverlap_main = null;
		double [][] texture_nonoverlap_aux = null;
		double [][] texture_overlap_main = null;
		double [][] texture_overlap_aux = null;
		String [] rgba_titles = {"red","blue","green","alpha"};
		String [] rgba_weights_titles = {"red","blue","green","alpha","port0","port1","port2","port3","r-rms","b-rms","g-rms","w-rms"};
		if ((texture_tiles_main != null) && (texture_tiles_aux != null)){
1572
			if ((debugLevel > -1) && (clt_parameters.tileX >= 0) && (clt_parameters.tileY >= 0) && (clt_parameters.tileX < tilesX) && (clt_parameters.tileY < tilesY)) {
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
				double [][] texture_tile = texture_tiles_main[clt_parameters.tileY][clt_parameters.tileX];
				int tile = +clt_parameters.tileY * tilesX  +clt_parameters.tileX;
    			System.out.println("=== tileX= "+clt_parameters.tileX+" tileY= "+clt_parameters.tileY+" tile="+tile+" ===");

    			for (int slice =0; slice < texture_tile.length; slice++) {
    				System.out.println("\n=== Slice="+slice+" ===");
    				for (int i = 0; i < 2 * GPUTileProcessor.DTT_SIZE; i++) {
    					for (int j = 0; j < 2 * GPUTileProcessor.DTT_SIZE; j++) {
    						System.out.print(String.format("%10.4f ",
    								texture_tile[slice][2 * GPUTileProcessor.DTT_SIZE * i + j]));
    					}
    					System.out.println();
    				}
    			}
    			(new ShowDoubleFloatArrays()).showArrays(
						texture_tile,
						2 * image_dtt.transform_size,
						2 * image_dtt.transform_size,
						true,
						name + "-TXTNOL-CPU-D"+clt_parameters.disparity+"-X"+clt_parameters.tileX+"-Y"+clt_parameters.tileY,
						(clt_parameters.keep_weights?rgba_weights_titles:rgba_titles));

			}

1597
			if (clt_parameters.show_nonoverlap){
1598
				texture_nonoverlap_main = image_dtt.combineRBGATiles(
1599
						texture_tiles_main,                 // array [tp.tilesY][tp.tilesX][4][4*transform_size] or [tp.tilesY][tp.tilesX]{null}
1600
//						image_dtt.transform_size,
1601 1602 1603 1604 1605 1606
						false,                         // when false - output each tile as 16x16, true - overlap to make 8x8
						clt_parameters.sharp_alpha,    // combining mode for alpha channel: false - treat as RGB, true - apply center 8x8 only
						threadsMax,                    // maximal number of threads to launch
						debugLevel);
				sdfa_instance.showArrays(
						texture_nonoverlap_main,
1607 1608
						tilesX * (2 * image_dtt.transform_size),
						tilesY * (2 * image_dtt.transform_size),
1609 1610 1611 1612
						true,
						name + "-TXTNOL-D"+clt_parameters.disparity+"-MAIN",
						(clt_parameters.keep_weights?rgba_weights_titles:rgba_titles));

1613
				texture_nonoverlap_aux = image_dtt.combineRBGATiles(
1614
						texture_tiles_aux,                 // array [tp.tilesY][tp.tilesX][4][4*transform_size] or [tp.tilesY][tp.tilesX]{null}
1615
//						image_dtt.transform_size,
1616 1617 1618 1619 1620 1621
						false,                         // when false - output each tile as 16x16, true - overlap to make 8x8
						clt_parameters.sharp_alpha,    // combining mode for alpha channel: false - treat as RGB, true - apply center 8x8 only
						threadsMax,                    // maximal number of threads to launch
						debugLevel);
				sdfa_instance.showArrays(
						texture_nonoverlap_aux,
1622 1623
						tilesX * (2 * image_dtt.transform_size),
						tilesY * (2 * image_dtt.transform_size),
1624 1625 1626 1627 1628 1629
						true,
						name + "-TXTNOL-D"+clt_parameters.disparity+"-AUX",
						(clt_parameters.keep_weights?rgba_weights_titles:rgba_titles));
			}
			if (!infinity_corr && (clt_parameters.show_overlap || clt_parameters.show_rgba_color)){
				int alpha_index = 3;
1630
				texture_overlap_main = image_dtt.combineRBGATiles(
1631
						texture_tiles_main,                 // array [tp.tilesY][tp.tilesX][4][4*transform_size] or [tp.tilesY][tp.tilesX]{null}
1632
//						image_dtt.transform_size,
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
						true,                         // when false - output each tile as 16x16, true - overlap to make 8x8
						clt_parameters.sharp_alpha,    // combining mode for alpha channel: false - treat as RGB, true - apply center 8x8 only
						threadsMax,                    // maximal number of threads to launch
						debugLevel);
				if (clt_parameters.alpha1 > 0){ // negative or 0 - keep alpha as it was
					double scale = (clt_parameters.alpha1 > clt_parameters.alpha0) ? (1.0/(clt_parameters.alpha1 - clt_parameters.alpha0)) : 0.0;
					for (int i = 0; i < texture_overlap_main[alpha_index].length; i++){
						double d = texture_overlap_main[alpha_index][i];
						if      (d >=clt_parameters.alpha1) d = 1.0;
						else if (d <=clt_parameters.alpha0) d = 0.0;
						else d = scale * (d- clt_parameters.alpha0);
						texture_overlap_main[alpha_index][i] = d;
					}
				}
1647

1648
				texture_overlap_aux = image_dtt.combineRBGATiles(
1649
						texture_tiles_aux,                 // array [tp.tilesY][tp.tilesX][4][4*transform_size] or [tp.tilesY][tp.tilesX]{null}
1650
//						image_dtt.transform_size,
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
						true,                         // when false - output each tile as 16x16, true - overlap to make 8x8
						clt_parameters.sharp_alpha,    // combining mode for alpha channel: false - treat as RGB, true - apply center 8x8 only
						threadsMax,                    // maximal number of threads to launch
						debugLevel);
				if (clt_parameters.alpha1 > 0){ // negative or 0 - keep alpha as it was
					double scale = (clt_parameters.alpha1 > clt_parameters.alpha0) ? (1.0/(clt_parameters.alpha1 - clt_parameters.alpha0)) : 0.0;
					for (int i = 0; i < texture_overlap_aux[alpha_index].length; i++){
						double d = texture_overlap_aux[alpha_index][i];
						if      (d >=clt_parameters.alpha1) d = 1.0;
						else if (d <=clt_parameters.alpha0) d = 0.0;
						else d = scale * (d- clt_parameters.alpha0);
						texture_overlap_aux[alpha_index][i] = d;
					}
				}
1665

1666 1667 1668
				if (!batch_mode && clt_parameters.show_overlap) {
					sdfa_instance.showArrays(
							texture_overlap_main,
1669 1670
							tilesX * image_dtt.transform_size,
							tilesY * image_dtt.transform_size,
1671 1672 1673 1674 1675 1676 1677
							true,
							name + "-TXTOL-D"+clt_parameters.disparity+"-MAIN",
							(clt_parameters.keep_weights?rgba_weights_titles:rgba_titles));
				}
				if (!batch_mode && clt_parameters.show_overlap) {
					sdfa_instance.showArrays(
							texture_overlap_aux,
1678 1679
							tilesX * image_dtt.transform_size,
							tilesY * image_dtt.transform_size,
1680 1681 1682 1683
							true,
							name + "-TXTOL-D"+clt_parameters.disparity+"-AUX",
							(clt_parameters.keep_weights?rgba_weights_titles:rgba_titles));
				}
1684 1685


1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
				if (!batch_mode && clt_parameters.show_rgba_color) {
					// for now - use just RGB. Later add option for RGBA
					double [][] texture_rgb_main = {texture_overlap_main[0],texture_overlap_main[1],texture_overlap_main[2]};
					double [][] texture_rgba_main = {texture_overlap_main[0],texture_overlap_main[1],texture_overlap_main[2],texture_overlap_main[3]};
					double [][] texture_rgb_aux = {texture_overlap_aux[0],texture_overlap_aux[1],texture_overlap_aux[2]};
					double [][] texture_rgba_aux = {texture_overlap_aux[0],texture_overlap_aux[1],texture_overlap_aux[2],texture_overlap_aux[3]};
					ImagePlus imp_texture_main = quadCLT_main.linearStackToColor(
							clt_parameters,
							colorProcParameters,
							rgbParameters,
							name+"-texture", // String name,
1697
							"-D"+clt_parameters.disparity+"-MAINCPU", //String suffix, // such as disparity=...
1698 1699 1700 1701 1702
							toRGB,
							!quadCLT_main.correctionsParameters.jpeg, // boolean bpp16, // 16-bit per channel color mode for result
							false, // true, // boolean saveShowIntermediate, // save/show if set globally
							false, // true, // boolean saveShowFinal,        // save/show result (color image?)
							((clt_parameters.alpha1 > 0)? texture_rgba_main: texture_rgb_main),
1703 1704
							tilesX *  image_dtt.transform_size,
							tilesY *  image_dtt.transform_size,
1705 1706 1707 1708
							1.0,         // double scaleExposure, // is it needed?
							debugLevel );
					ImagePlus imp_texture_aux = quadCLT_aux.linearStackToColor(
							clt_parameters,
1709
							colorProcParameters_aux,
1710 1711 1712 1713 1714 1715 1716 1717
							rgbParameters,
							name+"-texture", // String name,
							"-D"+clt_parameters.disparity+"-AUX", //String suffix, // such as disparity=...
							toRGB,
							!quadCLT_aux.correctionsParameters.jpeg, // boolean bpp16, // 16-bit per channel color mode for result
							false, // true, // boolean saveShowIntermediate, // save/show if set globally
							false, // true, // boolean saveShowFinal,        // save/show result (color image?)
							((clt_parameters.alpha1 > 0)? texture_rgba_aux: texture_rgb_aux),
1718 1719
							tilesX *  image_dtt.transform_size,
							tilesY *  image_dtt.transform_size,
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 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
							1.0,         // double scaleExposure, // is it needed?
							debugLevel );
					int width = imp_texture_main.getWidth();
					int height =imp_texture_main.getHeight();
					ImageStack texture_stack=new ImageStack(width,height);
					texture_stack.addSlice("main",      imp_texture_main.getProcessor().getPixels());
					texture_stack.addSlice("auxiliary", imp_texture_aux. getProcessor().getPixels());
					ImagePlus imp_texture_stack = new ImagePlus(name+"-TEXTURES-D"+clt_parameters.disparity, texture_stack);
					imp_texture_stack.getProcessor().resetMinAndMax();
					//					  imp_texture_stack.updateAndDraw();
					imp_texture_stack.show();
				}
			}
		}
		// visualize correlation results (will be for inter-pair correlation)
		if (clt_corr_combo!=null){
			if (disparity_bimap != null){
				if (!batch_mode && clt_parameters.show_map &&  (debugLevel > -2)){
					sdfa_instance.showArrays(
							disparity_bimap,
							tilesX,
							tilesY,
							true,
							name+"-DISP_MAP-D"+clt_parameters.disparity,
							ImageDtt.BIDISPARITY_TITLES);
					boolean [] trusted = 	  getTrustedDisparity(
							quadCLT_main,  // QuadCLT            quadCLT_main,  // tiles should be set
							quadCLT_aux,   // QuadCLT            quadCLT_aux,
							true,          // boolean            use_individual,
							0.14,          // double             min_combo_strength,    // check correlation strength combined for all 3 correlations
							clt_parameters.grow_disp_trust,       // double             max_trusted_disparity, // 4.0 -> change to rig_trust
							1.0,           // double             trusted_tolerance,
							null,          // boolean []         was_trusted,
							disparity_bimap ); // double [][]        bimap // current state of measurements
					for (int layer = 0; layer < disparity_bimap.length; layer ++) if (disparity_bimap[layer] != null){
						for (int nTile = 0; nTile < disparity_bimap[layer].length; nTile++) {
							if (!trusted[nTile]) disparity_bimap[layer][nTile] = Double.NaN;
						}
					}
					sdfa_instance.showArrays(
							disparity_bimap,
							tilesX,
							tilesY,
							true,
							name+"-DISP_MAP_TRUSTED-D"+clt_parameters.disparity,
							ImageDtt.BIDISPARITY_TITLES);
				}
			}

			if (!batch_mode && !infinity_corr && clt_parameters.corr_show && (debugLevel > -2)){
				double [][] corr_rslt = new double [clt_corr_combo.length][];
				String [] titles = new String[clt_corr_combo.length]; // {"combo","sum"};
				for (int i = 0; i< titles.length; i++) titles[i] = ImageDtt.TCORR_TITLES[i];
				for (int i = 0; i<corr_rslt.length; i++) {
					corr_rslt[i] = image_dtt.corr_dbg(
							clt_corr_combo[i],
1776
							2*image_dtt.transform_size - 1,
1777 1778 1779 1780
							clt_parameters.corr_border_contrast,
							threadsMax,
							debugLevel);
				}
1781

1782 1783
				sdfa_instance.showArrays(
						corr_rslt,
1784 1785
						tilesX*(2*image_dtt.transform_size),
						tilesY*(2*image_dtt.transform_size),
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
						true,
						name + "-CORR-D"+clt_parameters.disparity,
						titles );
			}
		}
		//		  final double [][][][][][][] clt_bidata = // new double[2][quad][nChn][tilesY][tilesX][][]; // first index - main/aux
		int quad_main = clt_bidata[0].length;
		int quad_aux =  clt_bidata[1].length;

		if (!infinity_corr && (clt_parameters.gen_chn_img || clt_parameters.gen_4_img || clt_parameters.gen_chn_stacks)) {
			ImagePlus [] imps_RGB = new ImagePlus[quad_main+quad_aux];
			for (int iQuadComb = 0; iQuadComb < imps_RGB.length; iQuadComb++){
				int iAux = (iQuadComb >= quad_main) ? 1 : 0;
				int iSubCam= iQuadComb - iAux * quad_main;

				// Uncomment to have master/aux names
				//				  String title=name+"-"+String.format("%s%02d", ((iAux>0)?"A":"M"),iSubCam);
				String title=name+"-"+String.format("%02d", iQuadComb);
1804
				if (clt_parameters.getCorrSigma(image_dtt.isMonochrome()) > 0){ // no filter at all
1805
					for (int chn = 0; chn < clt_bidata[iAux][iSubCam].length; chn++) {
Andrey Filippov's avatar
Andrey Filippov committed
1806
		                int debug_lpf = ((iQuadComb ==0) && (chn==0))?3: debugLevel;
1807
						image_dtt.clt_lpf(
1808
								clt_parameters.getCorrSigma(image_dtt.isMonochrome()),
1809
								clt_bidata[iAux][iSubCam][chn],
1810
//								image_dtt.transform_size,
1811
								threadsMax,
Andrey Filippov's avatar
Andrey Filippov committed
1812
								debug_lpf);
1813 1814
					}
				}
1815

1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
				if (debugLevel > 0){
					System.out.println("--tilesX="+tilesX);
					System.out.println("--tilesY="+tilesY);
				}
				if (!batch_mode && (debugLevel > 0)){
					double [][] clt = new double [clt_bidata[iAux][iSubCam].length*4][];
					for (int chn = 0; chn < clt_bidata[iAux][iSubCam].length; chn++) {
						double [][] clt_set = image_dtt.clt_dbg(
								clt_bidata[iAux][iSubCam][chn],
								threadsMax,
								debugLevel);
						for (int ii = 0; ii < clt_set.length; ii++) clt[chn*4+ii] = clt_set[ii];
					}

					if (debugLevel > 0){
						sdfa_instance.showArrays(clt,
1832 1833
								tilesX*image_dtt.transform_size,
								tilesY*image_dtt.transform_size,
1834 1835 1836 1837 1838 1839
								true,
								results[iQuadComb].getTitle()+"-CLT-D"+clt_parameters.disparity);
					}
				}
				double [][] iclt_data = new double [clt_bidata[iAux][iSubCam].length][];
				for (int chn=0; chn<iclt_data.length;chn++){
1840
					iclt_data[chn] = image_dtt.iclt_2d_debug_gpu(
1841
							clt_bidata[iAux][iSubCam][chn], // scanline representation of dcd data, organized as dct_size x dct_size tiles
1842
//							image_dtt.transform_size,  // final int
1843 1844 1845 1846
							clt_parameters.clt_window,      // window_type
							15,                             // clt_parameters.iclt_mask,       //which of 4 to transform back
							0,                              // clt_parameters.dbg_mode,        //which of 4 to transform back
							threadsMax,
1847 1848 1849
							debugLevel,
							clt_parameters.tileX,           // final int                 debug_tileX
							clt_parameters.tileY);          // final int                 debug_tileY
1850

1851
				}
1852

1853
				if (clt_parameters.gen_chn_stacks) sdfa_instance.showArrays(iclt_data,
1854 1855
						(tilesX + 0) * image_dtt.transform_size,
						(tilesY + 0) * image_dtt.transform_size,
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
						true,
						results[iQuadComb].getTitle()+"-ICLT-RGB-D"+clt_parameters.disparity);
				if (!clt_parameters.gen_chn_img) continue;

				imps_RGB[iQuadComb] = quadCLT_main.linearStackToColor( // probably no need to separate and process the second half with quadCLT_aux
						clt_parameters,
						colorProcParameters,
						rgbParameters,
						title, // String name,
						"-D"+clt_parameters.disparity, //String suffix, // such as disparity=...
						toRGB,
						!quadCLT_main.correctionsParameters.jpeg, // boolean bpp16, // 16-bit per channel color mode for result
						!batch_mode, // true, // boolean saveShowIntermediate, // save/show if set globally
						false, // boolean saveShowFinal,        // save/show result (color image?)
						iclt_data,
1871 1872
						tilesX *  image_dtt.transform_size,
						tilesY *  image_dtt.transform_size,
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
						scaleExposures[iAux][iSubCam], // double scaleExposure, // is it needed?
						debugLevel );
			} // end of generating shifted channel images



			if (clt_parameters.gen_chn_img) {
				// combine to a sliced color image
				// assuming total number of images to be multiple of 4
				//			  int [] slice_seq = {0,1,3,2}; //clockwise
				int [] slice_seq = new int[results.length];
				for (int i = 0; i < slice_seq.length; i++) {
					slice_seq[i] = i ^ ((i >> 1) & 1); // 0,1,3,2,4,5,7,6, ...
				}
				int width = imps_RGB[0].getWidth();
				int height = imps_RGB[0].getHeight();
				ImageStack array_stack=new ImageStack(width,height);
				for (int i = 0; i<slice_seq.length; i++){
					if (imps_RGB[slice_seq[i]] != null) {
						array_stack.addSlice("port_"+slice_seq[i], imps_RGB[slice_seq[i]].getProcessor().getPixels());
					} else {
						array_stack.addSlice("port_"+slice_seq[i], results[slice_seq[i]].getProcessor().getPixels());
					}
				}
				ImagePlus imp_stack = new ImagePlus(name+"-SHIFTED-D"+clt_parameters.disparity, array_stack);
				imp_stack.getProcessor().resetMinAndMax();
				if (!batch_mode) {
					imp_stack.updateAndDraw();
				}
				//imp_stack.getProcessor().resetMinAndMax();
				//imp_stack.show();
				//				  eyesisCorrections.saveAndShow(imp_stack, this.correctionsParameters);
				quadCLT_main.eyesisCorrections.saveAndShowEnable(
						imp_stack,  // ImagePlus             imp,
						quadCLT_main.correctionsParameters, // EyesisCorrectionParameters.CorrectionParameters  correctionsParameters,
						true, // boolean               enableSave,
						!batch_mode) ;// boolean               enableShow);
			}
			if (clt_parameters.gen_4_img) {
				// Save as individual JPEG images in the model directory
				String x3d_path= quadCLT_main.correctionsParameters.selectX3dDirectory(
						name, // quad timestamp. Will be ignored if correctionsParameters.use_x3d_subdirs is false
						quadCLT_main.correctionsParameters.x3dModelVersion,
						true,  // smart,
						true);  //newAllowed, // save
				for (int sub_img = 0; sub_img < imps_RGB.length; sub_img++){
					quadCLT_main.eyesisCorrections.saveAndShow(
							imps_RGB[sub_img],
							x3d_path,
							quadCLT_main.correctionsParameters.png && !clt_parameters.black_back,
							!batch_mode && clt_parameters.show_textures,
							quadCLT_main.correctionsParameters.JPEG_quality, // jpegQuality); // jpegQuality){//  <0 - keep current, 0 - force Tiff, >0 use for JPEG
							(debugLevel > 0) ? debugLevel : 1); // int debugLevel (print what it saves)
				}
				String model_path= quadCLT_main.correctionsParameters.selectX3dDirectory(
						name, // quad timestamp. Will be ignored if correctionsParameters.use_x3d_subdirs is false
						null,
						true,  // smart,
						true);  //newAllowed, // save

				quadCLT_main.createThumbNailImage(
						imps_RGB[0],
						model_path,
						"thumb",
						debugLevel);

			}
		}

		return results;
	}
1944
	
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
	public void showERSDelay(double [][][] ers_delay)
	{
		int tilesX = quadCLT_main.tp.getTilesX();
		int tilesY = quadCLT_main.tp.getTilesY();
		int nTiles = tilesX * tilesY;
		int nchn_main = ers_delay[0].length;
		int nchn_aux =  ers_delay[1].length;
		double [][] dbg_img = new double[nchn_main + nchn_aux][tilesX*tilesY];
		for (int nTile = 0; nTile< nTiles; nTile++) {
			double avg_dly = 0;
			for (int i = 0; i < nchn_main; i++) {
				avg_dly += ers_delay[0][i][nTile];
			}
			avg_dly /= nchn_main;
			for (int i = 0; i < nchn_main; i++) {
				dbg_img[i][nTile] = ers_delay[0][i][nTile] - avg_dly;
			}
			for (int i = 0; i < nchn_aux; i++) {
				dbg_img[i + nchn_main][nTile] = ers_delay[1][i][nTile] - avg_dly;
			}
		}
1966
		(new ShowDoubleFloatArrays()).showArrays(
1967 1968 1969 1970 1971 1972
				dbg_img,
				tilesX,
				tilesY,
				true,
				"ERS_DELAYS");
	}
1973 1974 1975


	//	  public double [][][][] getRigImageStacks(
1976 1977 1978
// 08/12/2020 Moved to conditionImageSet
/*	
	public void getRigImageStacks( // Removed all references
1979
			CLTParameters       clt_parameters,
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
			QuadCLT                                        quadCLT_main,
			QuadCLT                                        quadCLT_aux,
			ImagePlus []                                   imp_quad_main,
			ImagePlus []                                   imp_quad_aux,
			boolean [][]                                   saturation_main, // (near) saturated pixels or null
			boolean [][]                                   saturation_aux, // (near) saturated pixels or null
			int                                            threadsMax,  // maximal number of threads to launch
			int                                            debugLevel){
		double [][][] double_stacks_main = new double [imp_quad_main.length][][];
		for (int i = 0; i < double_stacks_main.length; i++){
			double_stacks_main[i] = quadCLT_main.eyesisCorrections.bayerToDoubleStack(
					imp_quad_main[i], // source Bayer image, linearized, 32-bit (float))
1992 1993
					  null, // no margins, no oversample
					  quadCLT_main.is_mono);
1994 1995 1996 1997 1998 1999
		}

		double [][][] double_stacks_aux = new double [imp_quad_aux.length][][];
		for (int i = 0; i < double_stacks_aux.length; i++){
			double_stacks_aux[i] = quadCLT_aux.eyesisCorrections.bayerToDoubleStack(
					imp_quad_aux[i], // source Bayer image, linearized, 32-bit (float))
2000 2001
					  null, // no margins, no oversample
					  quadCLT_aux.is_mono);
2002 2003 2004 2005 2006 2007 2008
		}

		for (int i = 0; i < double_stacks_main.length; i++){
			for (int j =0 ; j < double_stacks_main[i][0].length; j++){
				double_stacks_main[i][2][j]*=0.5; // Scale green 0.5 to compensate more pixels than R,B
			}
		}
2009

2010
		for (int i = 0; i < double_stacks_aux.length; i++){
2011 2012 2013 2014
			if (double_stacks_aux[i].length > 2) { // skip for monochrome, only if color
				for (int j =0 ; j < double_stacks_aux[i][0].length; j++){
					double_stacks_aux[i][2][j]*=0.5; // Scale green 0.5 to compensate more pixels than R,B
				}
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
			}
		}
		quadCLT_main.setTiles (imp_quad_main[0], // set global tp.tilesX, tp.tilesY
				clt_parameters,
				threadsMax);
		quadCLT_aux.setTiles (imp_quad_aux[0], // set global tp.tilesX, tp.tilesY
				clt_parameters,
				threadsMax);
		String name_main = (String) imp_quad_main[0].getProperty("name");
		String name_aux =  (String) imp_quad_main[0].getProperty("name");
		quadCLT_main.image_name =     name_main;
		quadCLT_aux.image_name =      name_aux;
		quadCLT_main.image_data =     double_stacks_main;
		quadCLT_aux.image_data =      double_stacks_aux;
		quadCLT_main.saturation_imp = saturation_main;
		quadCLT_aux.saturation_imp =  saturation_aux;
		//		  quadCLT_main.tp.resetCLTPasses();
		quadCLT_main.tp.setTrustedCorrelation(clt_parameters.grow_disp_trust);
		quadCLT_aux.tp.setTrustedCorrelation(clt_parameters.grow_disp_trust);
	}
2035
*/
2036 2037 2038 2039

	public void processInfinityRigs( // actually there is no sense to process multiple image sets. Combine with other processing?
			QuadCLT quadCLT_main,
			QuadCLT quadCLT_aux,
2040 2041 2042
			CLTParameters       clt_parameters,
			ColorProcParameters                            colorProcParameters, //
			ColorProcParameters                            colorProcParameters_aux, //
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel) throws Exception
	{

		this.startTime=System.nanoTime();
		String [] sourceFiles=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		QuadCLT.SetChannels [] set_channels_aux =  quadCLT_aux.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0) || (set_channels_aux == null) || (set_channels_aux.length==0)) {
			System.out.println("No files to process (of "+sourceFiles.length+")");
			return;
		}
		double [] referenceExposures_main = quadCLT_main.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		double [] referenceExposures_aux =  quadCLT_aux.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		for (int nSet = 0; nSet < set_channels_main.length; nSet++){
			// check it is the same set for both cameras
			if (set_channels_aux.length <= nSet ) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: nothing");
			}
			if (!set_channels_main[nSet].name().equals(set_channels_aux[nSet].name())) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: '"+set_channels_main[nSet].name()+"'");
			}

			int [] channelFiles_main = set_channels_main[nSet].fileNumber();
			int [] channelFiles_aux =  set_channels_aux[nSet].fileNumber();
			boolean [][] saturation_imp_main = (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			boolean [][] saturation_imp_aux =  (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			double [] scaleExposures_main = new double[channelFiles_main.length];
			double [] scaleExposures_aux =  new double[channelFiles_main.length];

			ImagePlus [] imp_srcs_main = quadCLT_main.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
2076
					colorProcParameters,            //  ColorProcParameters                       colorProcParameters, //
2077 2078 2079 2080 2081 2082
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_main[nSet].name(), // String                                    set_name,
					referenceExposures_main,        // double []                                 referenceExposures,
					channelFiles_main,              // int []                                    channelFiles,
					scaleExposures_main,            //output  // double [] scaleExposures
					saturation_imp_main,            //output  // boolean [][]                              saturation_imp,
2083
					threadsMax,                 // int                                       threadsMax,
2084 2085 2086 2087
					debugLevel); // int                                       debugLevel);

			ImagePlus [] imp_srcs_aux = quadCLT_aux.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
2088
					colorProcParameters_aux,        //  ColorProcParameters                       colorProcParameters, //
2089 2090 2091 2092 2093 2094
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_aux[nSet].name(), // String                                    set_name,
					referenceExposures_aux,        // double []                                 referenceExposures,
					channelFiles_aux,              // int []                                    channelFiles,
					scaleExposures_aux,            //output  // double [] scaleExposures
					saturation_imp_aux,            //output  // boolean [][]                              saturation_imp,
2095
					threadsMax,                 // int                                       threadsMax,
2096 2097
					debugLevel); // int                                       debugLevel);

2098
			// Temporary processing individually with the old code
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
			processInfinityRig(
					quadCLT_main,               // QuadCLT                                        quadCLT_main,
					quadCLT_aux,                // QuadCLT                                        quadCLT_aux,
					imp_srcs_main,              // ImagePlus []                                   imp_quad_main,
					imp_srcs_aux,               // ImagePlus []                                   imp_quad_aux,
					saturation_imp_main,        // boolean [][]                                   saturation_main, // (near) saturated pixels or null
					saturation_imp_aux,         // boolean [][]                                   saturation_aux, // (near) saturated pixels or null
					clt_parameters,             // EyesisCorrectionParameters.CLTParameters       clt_parameters,
					threadsMax,                 // final int        threadsMax,  // maximal number of threads to launch
					updateStatus,               // final boolean    updateStatus,
					debugLevel);                // final int        debugLevel);


			Runtime.getRuntime().gc();
			if (debugLevel >-1) System.out.println("Processing set "+(nSet+1)+" (of "+set_channels_aux.length+") finished at "+
					IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

			if (quadCLT_aux.eyesisCorrections.stopRequested.get()>0) {
				System.out.println("User requested stop");
				System.out.println("Processing "+(nSet + 1)+" file sets (of "+set_channels_main.length+") finished at "+
						IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");
				return;
			}
		}
2123
		System.out.println("processInfinityRigs(): processing "+(quadCLT_main.getTotalFiles(set_channels_main)+quadCLT_aux.getTotalFiles(set_channels_aux))+" files ("+set_channels_main.length+" file sets) finished at "+
2124 2125 2126
				IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

	}
2127 2128


2129
	// use macro mode (strengths with limited disparity) to align at infinity if it is way off.
2130 2131 2132
	public boolean prealignInfinityRig(
			QuadCLT                                        quadCLT_main,
			QuadCLT                                        quadCLT_aux,
2133
			CLTParameters       clt_parameters,
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel){
		double [][] disparity_bimap = measureNewRigDisparity(
				quadCLT_main,      // QuadCLT             quadCLT_main,    // tiles should be set
				quadCLT_aux,       // QuadCLT             quadCLT_aux,
				null,              // double [][]         src_bimap,       // current state of measurements (or null for new measurement)
				0.0,               // double              disparity,
				null,              // ArrayList<Integer>  tile_list,       // or null. If non-null - do not remeasure members of the list
				clt_parameters,    // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				false,             //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				0,                              // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				// first measurement - use default setting
				clt_parameters.rig.no_int_x0, // boolean   no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,        // final int           threadsMax,      // maximal number of threads to launch
				updateStatus,      // final boolean       updateStatus,
				debugLevel);       // final int           debugLevel);
		// create two arrays of main and aux strengths and small disparity
		//	public double  inf_max_disp_main =         0.15;
		//	public double  inf_max_disp_aux =          0.15;
		final int tilesX = quadCLT_main.tp.getTilesX();
		final int tilesY = quadCLT_main.tp.getTilesY();
		final int tile_op_all = clt_parameters.tile_task_op; //FIXME Use some constant?
		double max_main_disparity = 3* clt_parameters.rig.inf_max_disp_main;
		double max_aux_disparity = 3* clt_parameters.rig.inf_max_disp_aux;
		double min_strength_main =0.2;
		double min_strength_aux =0.2;

		int numTiles = disparity_bimap[ImageDtt.BI_STR_FULL_INDEX].length;
		double [][][] macro_pair = new double[2][1][numTiles]; // second index for compatibility with multiple colors
		for (int nTile = 0; nTile < numTiles; nTile++) {
			double d_main= disparity_bimap[ImageDtt.BI_DISP_FULL_INDEX ][nTile];
			double d_aux=  disparity_bimap[ImageDtt.BI_ADISP_FULL_INDEX][nTile];
			double s_main= disparity_bimap[ImageDtt.BI_STR_FULL_INDEX ][nTile];
			double s_aux=  disparity_bimap[ImageDtt.BI_ASTR_FULL_INDEX][nTile];
			if ((Math.abs(d_main) <= max_main_disparity) && (s_main > min_strength_main)) macro_pair[0][0][nTile] = s_main-min_strength_main;
			if ((Math.abs(d_aux)  <= max_aux_disparity)  && (s_aux  > min_strength_aux))  macro_pair[1][0][nTile] = s_aux- min_strength_aux;
			//			  macro_pair[0][0][nTile] = s_main;
			//			  macro_pair[1][0][nTile] = s_aux;
		}
		if (debugLevel >-2) {
			double [][] dbg_macro = {macro_pair[0][0],macro_pair[1][0]};
2176
			(new ShowDoubleFloatArrays()).showArrays(
2177 2178 2179 2180 2181 2182 2183
					dbg_macro,
					tilesX,
					tilesY,
					true,
					"MACRO-INPUT");
		}

2184 2185 2186
		ImageDtt image_dtt = new ImageDtt(
				clt_parameters.transform_size,
				quadCLT_main.isMonochrome(),
2187
				quadCLT_main.isLwir(),
2188 2189 2190
				clt_parameters.getScaleStrength(false));

		int macro_scale = image_dtt.transform_size;
2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
		int mTilesX = tilesX/macro_scale;
		int mTilesY = tilesY/macro_scale;
		int [][] mtile_op = new int [mTilesY][mTilesX];
		for (int mTileY=0; mTileY < mTilesY; mTileY++) {
			for (int mTileX=0; mTileX < mTilesX; mTileX++) {
				mtile_op[mTileY][mTileX] = tile_op_all;
			}
		}
		double [][] mdisparity_array = new double [mTilesY][mTilesX]; // keep all zeros
		double [][] mdisparity_bimap = new double [ImageDtt.BIDISPARITY_TITLES.length][];
		image_dtt.clt_bi_macro(
				clt_parameters,                       // final EyesisCorrectionParameters.CLTParameters       clt_parameters,
2203
				clt_parameters.getFatZero(image_dtt.isMonochrome()),              // final double              fatzero,         // May use correlation fat zero from 2 different parameters - fat_zero and rig.ml_fatzero
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
				macro_scale, // final int                 macro_scale,
				mtile_op, // final int [][]            tile_op,         // [tilesY][tilesX] - what to do - 0 - nothing for this tile
				mdisparity_array, // final double [][]         disparity_array, // [tilesY][tilesX] - individual per-tile expected disparity
				macro_pair, // 	final double [][][]       image_rig_data,  // [2][1][pixels] (single color channel)
				mdisparity_bimap, // final double [][]         disparity_bimap, // [23][tilesY][tilesX], only [6][] is needed on input or null - do not calculate
				tilesX, // 	final int                 width,
				quadCLT_main.getGeometryCorrection(), // final GeometryCorrection  geometryCorrection_main,
				quadCLT_aux.getGeometryCorrection(),  // final GeometryCorrection  geometryCorrection_aux,
				clt_parameters.corr_magic_scale,      //  final double              corr_magic_scale, // still not understood coefficient that reduces reported disparity value.  Seems to be around 0.85
				threadsMax,        // final int           threadsMax,      // maximal number of threads to launch
				debugLevel + 1);       // final int           debugLevel);
		// Display macro correlation results (later convert to a full size disparity_bimap for compatibility with infinity alignment
		if (debugLevel > -2) {
2217
			(new ShowDoubleFloatArrays()).showArrays(
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
					mdisparity_bimap,
					mTilesX,
					mTilesY,
					true,
					"MACRO-DISP_MAP",
					ImageDtt.BIDISPARITY_TITLES);
		}

		/*
		 * ImageDtt.BIDISPARITY_TITLES.length
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
	public void  clt_bi_macro(
			final EyesisCorrectionParameters.CLTParameters       clt_parameters,
			final int                 macro_scale,
			final int [][]            tile_op,         // [tilesY][tilesX] - what to do - 0 - nothing for this tile
			final double [][]         disparity_array, // [tilesY][tilesX] - individual per-tile expected disparity
			final double [][][]       image_rig_data,  // [2][1][pixels] (single color channel)
			final double [][]         disparity_bimap, // [23][tilesY][tilesX], only [6][] is needed on input or null - do not calculate
			final int                 width,
			final GeometryCorrection  geometryCorrection_main,
			final GeometryCorrection  geometryCorrection_aux, // it has rig offset)
			final double              corr_magic_scale, // still not understood coefficient that reduces reported disparity value.  Seems to be around 0.85
			final int                 threadsMax,  // maximal number of threads to launch
			final int                 debugLevel)
2241

2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
		 */
		return true;
	}

	public boolean processInfinityRig(
			QuadCLT                                        quadCLT_main,
			QuadCLT                                        quadCLT_aux,
			ImagePlus []                                   imp_quad_main,
			ImagePlus []                                   imp_quad_aux,
			boolean [][]                                   saturation_main, // (near) saturated pixels or null
			boolean [][]                                   saturation_aux, // (near) saturated pixels or null
2253
			CLTParameters       clt_parameters,
2254 2255 2256 2257 2258
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel0){
		final int        debugLevel = debugLevel0 + (clt_parameters.rig.rig_mode_debug?2:0);
		//		  double [][][][] double_stacks =
2259
/*		// 08/12/2020 Moved to condifuinImageSet				  		
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
		getRigImageStacks(
				clt_parameters,  // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				quadCLT_main,    // QuadCLT                                         quadCLT_main,
				quadCLT_aux,     // QuadCLT                                          quadCLT_aux,
				imp_quad_main,   // ImagePlus []                                   imp_quad_main,
				imp_quad_aux,    // ImagePlus []                                    imp_quad_aux,
				saturation_main, // boolean [][]        saturation_main, // (near) saturated pixels or null
				saturation_aux, // boolean [][]        saturation_aux, // (near) saturated pixels or null
				threadsMax,      // maximal number of threads to launch
				debugLevel);     // final int        debugLevel);

		quadCLT_main.tp.resetCLTPasses();
		quadCLT_aux.tp.resetCLTPasses();
2273
*/		
2274
		/*
2275 2276 2277 2278 2279 2280 2281 2282 2283
FIXME - make it work
 		  prealignInfinityRig(
 				  quadCLT_main, // QuadCLT                                        quadCLT_main,
 				  quadCLT_aux, // QuadCLT                                        quadCLT_aux,
 				  clt_parameters,    // EyesisCorrectionParameters.CLTParameters       clt_parameters,
 				  threadsMax,      // maximal number of threads to launch
 				  updateStatus,    // final boolean    updateStatus,
 				  debugLevel);     // final int        debugLevel);
if (debugLevel > -100) return true; // temporarily !
2284
		 */
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
		double disparity_correction_main = 0.0; // actual disparity in main camera pixels for "infinity" objects
		if (clt_parameters.infinity_distace_map.containsKey(quadCLT_main.image_name)){
			double infinity_distance = clt_parameters.infinity_distace_map.get(quadCLT_main.image_name);
			disparity_correction_main = quadCLT_main.geometryCorrection.getDisparityFromZ(infinity_distance);
			if (debugLevel > -5) {
				System.out.println("Found infinity distance record for "+quadCLT_main.image_name+", it is "+infinity_distance+
						" m, corresponding to "+disparity_correction_main+" pixels of the main camera.");
			}
		} else {
			if (debugLevel > -5) {
				System.out.println("No infinity distance record for "+quadCLT_main.image_name+" found, considering far objects to be true infinity");
			}
		}
		if (debugLevel > -5) {
			System.out.println("disparity_correction_main= "+disparity_correction_main);
		}

2302 2303 2304 2305 2306 2307
		final int tilesX = quadCLT_main.tp.getTilesX();

		// perform full re-measure cycles
		double [][] disparity_bimap = null;
		int [] num_new = new int[1];
		for (int num_full_cycle = 0; num_full_cycle < clt_parameters.rig.rig_adjust_full_cycles;num_full_cycle++) {
2308 2309 2310 2311
			if (debugLevel > -5) {
				System.out.println("processInfinityRig(), reselecting and re-measuring tiles (may increase RMS), full_cycle "+
						(num_full_cycle + 1)+" of "+clt_parameters.rig.rig_adjust_full_cycles);
			}
2312 2313 2314 2315
			disparity_bimap = null;
			ArrayList<Integer> tile_list = new ArrayList<Integer>();
			// measure and refine
			for (int disp_step = 0; disp_step < clt_parameters.rig.rig_num_disp_steps; disp_step++) {
2316 2317 2318
				double disparity = disparity_correction_main;
				if (disp_step > 0) {
					disparity += disp_step * clt_parameters.rig.rig_disp_range/(clt_parameters.rig.rig_num_disp_steps -1);
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
				}
				disparity_bimap = measureNewRigDisparity(
						quadCLT_main,      // QuadCLT             quadCLT_main,    // tiles should be set
						quadCLT_aux,       // QuadCLT             quadCLT_aux,
						disparity_bimap,   // double [][]         src_bimap,       // current state of measurements (or null for new measurement)
						disparity,         // double              disparity,
						tile_list,         // ArrayList<Integer>  tile_list,       // or null. If non-null - do not remeasure members of the list
						clt_parameters,    // EyesisCorrectionParameters.CLTParameters       clt_parameters,
						false,             //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
						0,                 // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
						// first measurement - use default setting
						clt_parameters.rig.no_int_x0, // boolean   no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
						threadsMax,        // final int           threadsMax,      // maximal number of threads to launch
						updateStatus,      // final boolean       updateStatus,
						debugLevel);       // final int           debugLevel);

				if (disparity_bimap != null){
2336
					if (clt_parameters.show_map &&  (debugLevel > -2) && clt_parameters.rig.rig_mode_debug){
2337
						(new ShowDoubleFloatArrays()).showArrays(
2338 2339 2340 2341 2342 2343 2344 2345
								disparity_bimap,
								tilesX,
								disparity_bimap[0].length/tilesX,
								true,
								"DISP_MAP-D"+disparity,
								ImageDtt.BIDISPARITY_TITLES);
					}
				}
2346
				if (disp_step > 0) { // refine non-infinity passes
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
					// first - refine once for the main camera
					double [][] prev_bimap = null;
					double [] scale_bad = null;
					for (int nrefine = 0; nrefine < clt_parameters.rig.num_refine_master; nrefine++) {
						double [][] disparity_bimap_new =  refineRig(
								quadCLT_main,    // QuadCLT                        quadCLT_main,    // tiles should be set
								quadCLT_aux,     // QuadCLT                        quadCLT_aux,
								disparity_bimap, // double [][]                    src_bimap,       // current state of measurements (or null for new measurement)
								prev_bimap,      // double [][]                    prev_bimap, // previous state of measurements or null
								null, // scale_bad,       // double []                      scale_bad,
								2, //0,               // int                            refine_mode,     // 0 - by main, 1 - by aux, 2 - by inter
								true,            // boolean                        keep_inf,        // keep expected disparity 0.0 if it was so
2359
								disparity_correction_main, // double                                   inf_disparity,
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
								clt_parameters.rig.refine_min_strength , // double refine_min_strength, // do not refine weaker tiles
								clt_parameters.rig.refine_tolerance ,    // double refine_tolerance,    // do not refine if absolute disparity below
								null, // tile_list,       // ArrayList<Integer>             tile_list,       // or null
								num_new,         // int     []                                     num_new,
								clt_parameters,  // EyesisCorrectionParameters.CLTParameters clt_parameters,
								false,           //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
								0,                              // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
								// refine mode - no window offset
								true,            // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
								threadsMax,      // final int                      threadsMax,      // maximal number of threads to launch
								updateStatus,    // final boolean                  updateStatus,
								debugLevel);     // final int                      debugLevel);
						prev_bimap = disparity_bimap;
						disparity_bimap = disparity_bimap_new;
						if (disparity_bimap != null){
							if (clt_parameters.show_map &&  (debugLevel > 2) && clt_parameters.rig.rig_mode_debug){
2376
								(new ShowDoubleFloatArrays()).showArrays(
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
										disparity_bimap,
										tilesX,
										disparity_bimap[0].length/tilesX,
										true,
										"DISP_MAP-refine_master-"+nrefine,
										ImageDtt.BIDISPARITY_TITLES);
							}
						}

					}
					// now refine for the inter-camera correlation
					prev_bimap = null;
					for (int nrefine = 0; nrefine < clt_parameters.rig.num_refine_inter; nrefine++) {
						double [][] disparity_bimap_new =  refineRig(
								quadCLT_main,    // QuadCLT                        quadCLT_main,    // tiles should be set
								quadCLT_aux,     // QuadCLT                        quadCLT_aux,
								disparity_bimap, // double [][]                    src_bimap,       // current state of measurements (or null for new measurement)
								prev_bimap,      // double [][]                    prev_bimap, // previous state of measurements or null
								scale_bad,       // double []                      scale_bad,
								2,               // int                            refine_mode,     // 0 - by main, 1 - by aux, 2 - by inter
								true,            // boolean                        keep_inf,        // keep expected disparity 0.0 if it was so
2398
								disparity_correction_main, // double                                   inf_disparity,
2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
								clt_parameters.rig.refine_min_strength , // double refine_min_strength, // do not refine weaker tiles
								clt_parameters.rig.refine_tolerance ,    // double refine_tolerance,    // do not refine if absolute disparity below
								null, // tile_list,       // ArrayList<Integer>             tile_list,       // or null
								num_new,         // int     []                                     num_new,
								clt_parameters,  // EyesisCorrectionParameters.CLTParameters clt_parameters,
								false,             //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
								0,                              // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
								// refine mode - no window offset
								true,            // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
								threadsMax,      // final int                      threadsMax,      // maximal number of threads to launch
								updateStatus,    // final boolean                  updateStatus,
								debugLevel);     // final int                      debugLevel);
						prev_bimap = disparity_bimap;
						disparity_bimap = disparity_bimap_new;
						if (disparity_bimap != null){
							if (clt_parameters.show_map &&  (debugLevel > 2) && clt_parameters.rig.rig_mode_debug){
2415
								(new ShowDoubleFloatArrays()).showArrays(
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
										disparity_bimap,
										tilesX,
										disparity_bimap[0].length/tilesX,
										true,
										"DISP_MAP-refine_inter-"+nrefine,
										ImageDtt.BIDISPARITY_TITLES);
							}
						}

					}
				} // if (disparity > 0.0) { // refine non-infinity passes
				// rebuild tiles list that match requirements, debug-show results
				tile_list = selectRigTiles(
						clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
						true, // boolean select_infinity,
						true, // boolean select_noninfinity,
2432
						disparity_correction_main, // double                                   inf_disparity,
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
						disparity_bimap, // double[][] disparity_bimap,
						tilesX);  // int tilesX,
				if (debugLevel > -1) showListedRigTiles(
						"rig_tiles_D"+disparity, // title
						tile_list, //ArrayList<Integer> tile_list,
						disparity_bimap, // double[][] disparity_bimap,
						tilesX); // int tilesX

			} //  for (int disp_step = 0; disp_step < clt_parameters.rig.rig_num_disp_steps; disp_step++)

			// short cycle (remeasure only for the list). May also break from it if RMS is not improving
			for (int num_short_cycle = 0; num_short_cycle < clt_parameters.rig.rig_adjust_short_cycles;num_short_cycle++) {
2445
				// refine for the existing list - all listed tiles, no thresholds
2446 2447 2448 2449 2450 2451 2452 2453 2454
				disparity_bimap =  refineRig(
						quadCLT_main,    // QuadCLT                        quadCLT_main,    // tiles should be set
						quadCLT_aux,     // QuadCLT                        quadCLT_aux,
						disparity_bimap, // double [][]                    src_bimap,       // current state of measurements (or null for new measurement)
						null,            // double [][]                                    prev_bimap, // previous state of measurements or null
						null,       // double []                           scale_bad,
						2,               // int                            refine_mode,     // 0 - by main, 1 - by aux, 2 - by inter
						// will still re-measure infinity if refine_min_strength == 0.0
						true,            // boolean                        keep_inf,        // keep expected disparity 0.0 if it was so
2455
						disparity_correction_main, // double                                   inf_disparity,
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
						0.0,             // double refine_min_strength, // do not refine weaker tiles
						0.0,             // double refine_tolerance,    // do not refine if absolute disparity below
						tile_list,       // ArrayList<Integer>             tile_list,       // or null
						num_new,         // int     []                                     num_new,
						clt_parameters,  // EyesisCorrectionParameters.CLTParameters clt_parameters,
						false,             //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
						0,                              // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
						// refine mode - disable window offset
						true,            // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
						threadsMax,      // final int                      threadsMax,      // maximal number of threads to launch
						updateStatus,    // final boolean                  updateStatus,
						debugLevel);     // final int                      debugLevel);
				// show updated results for the list
				if (debugLevel > -2) showListedRigTiles(
						"selected_rig_tiles", // title
						tile_list, //ArrayList<Integer> tile_list,
						disparity_bimap, // double[][] disparity_bimap,
						tilesX); // int tilesX

				// do actual adjustment step, update rig parameters
				quadCLT_aux.geometryCorrection.getRigCorrection(
						clt_parameters.rig.inf_weight ,     // double             infinity_importance, // of all measurements
						clt_parameters.rig.inf_weight_disp, // double             dx_max, //  = 0.3;
						clt_parameters.rig.inf_weight_disp_pow,                                // double             dx_pow, //  = 1.0;
						clt_parameters.rig.rig_adjust_orientation,        // boolean            adjust_orientation,
						clt_parameters.rig.rig_adjust_roll,               // boolean            adjust_roll,
						clt_parameters.rig.rig_adjust_zoom,               // boolean            adjust_zoom,
						clt_parameters.rig.rig_adjust_angle,              // boolean            adjust_angle,
						clt_parameters.rig.rig_adjust_distance,           // boolean            adjust_distance,
						clt_parameters.rig.rig_adjust_forward,            // boolean            adjust_forward, // not used
						clt_parameters.rig.rig_correction_scale,          // double             scale_correction,
2487
						disparity_correction_main, // double             infinity_disparity,
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501
						tile_list,                                        // ArrayList<Integer> tile_list,
						quadCLT_main,                                     // QuadCLT            qc_main,
						disparity_bimap[ImageDtt.BI_STR_CROSS_INDEX],     // double []          strength,
						disparity_bimap[ImageDtt.BI_DISP_CROSS_DX_INDEX], // double []          diff_x, // used only with target_disparity == 0
						disparity_bimap[ImageDtt.BI_DISP_CROSS_DY_INDEX], // double []          diff_y,
						disparity_bimap[ImageDtt.BI_TARGET_INDEX],        // double []          target_disparity,
						debugLevel+1);

			} // end of for (int num_short_cycle = 0; num_short_cycle < clt_parameters.rig.rig_adjust_short_cycles;num_short_cycle++) {


		} // end of for (int num_full_cycle = 0; num_full_cycle < clt_parameters.rig.rig_adjust_full_cycles;num_full_cycle++) {
		if (disparity_bimap != null){
			if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){
2502
				(new ShowDoubleFloatArrays()).showArrays(
2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
						disparity_bimap,
						tilesX,
						disparity_bimap[0].length/tilesX,
						true,
						"DISP_MAP",
						ImageDtt.BIDISPARITY_TITLES);
			}
		}

		// loop here with the same tileList

		return true;
	}


2518

2519 2520 2521 2522
	public boolean processPoles(
			QuadCLT            quadCLT_main,  // tiles should be set
			QuadCLT            quadCLT_aux,
			BiCamDSI                                       biCamDSI,
2523
			CLTParameters       clt_parameters,
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 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 2598 2599 2600 2601 2602 2603 2604
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      globalDebugLevel)
	{
		// -1 and above - follow clt_parameters.poles.poles_debug_level, -2 and below - follow global debug level
		final int debugLevel = (globalDebugLevel > -2) ? clt_parameters.poles.poles_debug_level:globalDebugLevel;
		if ((quadCLT_main == null) ||
				(quadCLT_main.tp == null) ||
				(quadCLT_main.tp.clt_3d_passes == null) ||
				(biCamDSI_persistent== null) ||
				(biCamDSI_persistent.biScans== null) ||
				(quadCLT_main.tp.rig_pre_poles_ds == null)
				) {
			String msg = "Data is not available. Please run \"Ground truth\" first";
			IJ.showMessage("Error",msg);
			System.out.println(msg);
			return false;
		}
		int scan_index = biCamDSI_persistent.biScans.size()-1;
		BiScan biScan =  biCamDSI_persistent.biScans.get(scan_index);
		if (debugLevel> -1) {
			biScan.showScan(quadCLT_main.image_name+"LastBiScan-"+scan_index, null);
		}
		//		  if (poleProcessor_persistent == null) {
		poleProcessor_persistent = new PoleProcessor(
				biCamDSI_persistent,
				this, //	TwoQuadCLT twoQuadCLT,
				quadCLT_main.tp.getTilesX(),
				quadCLT_main.tp.getTilesY());
		//		  }
		PoleProcessor pp = poleProcessor_persistent;
		boolean [] selection =  quadCLT_main.tp.rig_pre_poles_sel.clone();
		int num_bugs_corrected= pp.zero_tiles_check(
				"pre-poles",
				quadCLT_main.tp.rig_pre_poles_ds, // double [][] ds,
				true); // boolean debug)
		if (num_bugs_corrected > 0) {
			System.out.println("Corrected "+num_bugs_corrected+" bugs, where disparity is <= 0 with non-zero strength before poles");
		}

		double [][] poles_ds = pp.processPoles(
				quadCLT_main,  // QuadCLT            quadCLT_main,  // tiles should be set
				quadCLT_aux,   //QuadCLT            quadCLT_aux,
				quadCLT_main.tp.rig_pre_poles_ds, //  double [][]                                    src_ds, // source disparity, strength pair
				selection, // boolean []                                     selection, // source tile selection, will be modified
				clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				threadsMax,  // final int                                      threadsMax,  // maximal number of threads to launch
				updateStatus, // final boolean                                  updateStatus,
				debugLevel); // final int                                      globalDebugLevel)

		num_bugs_corrected= pp.zero_tiles_check(
				"post-poles",
				poles_ds, // double [][] ds,
				true); // boolean debug)
		if (num_bugs_corrected > 0) {
			System.out.println("Corrected "+num_bugs_corrected+" bugs, where disparity is <= 0 with non-zero strength after poles");
		}
		quadCLT_main.tp.rig_post_poles_ds =        poles_ds; // Rig disparity and strength before processing poles
		quadCLT_main.tp.rig_post_poles_sel =       selection; // Rig tile selection before processing poles

		CLTPass3d scan_last = quadCLT_main.tp.clt_3d_passes.get( quadCLT_main.tp.clt_3d_passes.size() -1); // get really last one

		quadCLT_main.tp.trimCLTPasses(false); // remove rig composite scan if any
		CLTPass3d rig_scan = quadCLT_main.tp.compositeScan(
				poles_ds[0],  // final double []             disparity,
				poles_ds[1],  // final double []             strength,
				selection,                  // final boolean []            selected,
				debugLevel);                // final int                   debugLevel)
		rig_scan.texture_tiles = scan_last.texture_tiles;
		// scan_last
		quadCLT_main.tp.clt_3d_passes.add(rig_scan);
		quadCLT_main.tp.saveCLTPasses(true);       // rig pass
		return true;
	}

	//  improve DSI acquired for a single camera by use of a pair
	// Run this after "CLT 3D"

	public void groundTruth(
			QuadCLT            quadCLT_main,  // tiles should be set
			QuadCLT            quadCLT_aux,
2605 2606 2607
			CLTParameters       clt_parameters,
			ColorProcParameters                            colorProcParameters, //
			ColorProcParameters                            colorProcParameters_aux, //
2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel)// throws Exception
	{
		if ((quadCLT_main.tp == null) || (quadCLT_main.tp.clt_3d_passes == null)) {
			String msg = "DSI data not available. Please run\"CLT 3D\" first";
			IJ.showMessage("ERROR",msg);
			System.out.println(msg);
			return;
		}

		double [][] rig_disparity_strength =  quadCLT_main.getGroundTruthByRig(); // saved pair

		if (rig_disparity_strength == null) {
			rig_disparity_strength = groundTruthByRigPlanes(
					quadCLT_main,   // QuadCLT            quadCLT_main,  // tiles should be set
					quadCLT_aux,    // QuadCLT            quadCLT_aux,
					clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
2626 2627
					colorProcParameters,          //  ColorProcParameters                       colorProcParameters, //
					colorProcParameters_aux,          //  ColorProcParameters                       colorProcParameters, //
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680
					threadsMax,     // final int                                      threadsMax,  // maximal number of threads to launch
					updateStatus,   // final boolean                                  updateStatus,
					debugLevel);    // final int                                      debugLevel);
			if (rig_disparity_strength != null) {
				quadCLT_main.tp.rig_disparity_strength = rig_disparity_strength;
			}
		}
		CLTPass3d scan_bg =   quadCLT_main.tp.clt_3d_passes.get( 0); // get bg scan
		//		  quadCLT_main.tp.trimCLTPasses(false); // remove rig composite scan if any
		// last but not including any rid data
		CLTPass3d scan_last = quadCLT_main.tp.clt_3d_passes.get( quadCLT_main.tp.clt_3d_passes_size -1); // get last one

		// TODO: combine in a single function to always call after groundTruthByRig. Or before use?
		boolean [] infinity_select = scan_bg.getSelected(); // null;
		boolean [] was_select = scan_last.getSelected(); // null;
		boolean[] selection = null;
		final int tilesX = quadCLT_main.tp.getTilesX();
		final int tilesY = quadCLT_main.tp.getTilesY();
		BiCamDSI biCamDSI = new BiCamDSI( tilesX, tilesY, threadsMax);
		//          boolean [][] dbg_sel = (debugLevel > -4)? new boolean [8][]:null;// was 4
		boolean [][] dbg_sel = (debugLevel > -2)? new boolean [8][]:null;// was 4
		if (dbg_sel!=null) dbg_sel[0] = infinity_select;
		if (dbg_sel!=null) dbg_sel[1] = was_select;
		if (clt_parameters.rig.ltfar_en) {
			double strength_floor = (clt_parameters.rig.ltfar_auto_floor)? Double.NaN: (clt_parameters.rig.lt_trusted_strength*clt_parameters.rig.lt_strength_rfloor);
			double ltfar_min_strength = clt_parameters.rig.ltfar_min_rstrength * clt_parameters.rig.lt_trusted_strength;

			selection = biCamDSI.selectFarObjects(
					strength_floor, //double     strength_floor,
					clt_parameters.rig.ltfar_min_disparity , //	double     min_disparity,
					clt_parameters.rig.ltfar_min_mean , //	double     min_mean,
					clt_parameters.rig.ltfar_max_disparity , //double     max_disparity,
					clt_parameters.rig.ltfar_max_mean , //double     max_mean,
					clt_parameters.rig.ltfar_min_disp_to_rms , //double     min_disp_to_rms,
					ltfar_min_strength , //double     min_strength,
					clt_parameters.rig.ltfar_neib_dist , //int        neib_dist, // >=1
					clt_parameters.rig.ltfar_rsigma , //double     rsigma,
					clt_parameters.rig.ltfar_frac, // double     tile_frac,
					//ltfar_frac
					infinity_select, // null, // TODO: add real	after debug boolean [] infinity_select,
					rig_disparity_strength[0], // 	double []  disparity,
					rig_disparity_strength[1], // 	double []  strength,
					tilesX, // 	int        tilesX, debug only
					debugLevel); // int        debugLevel);
			if (dbg_sel!=null) dbg_sel[2] = selection.clone();
		}

		selection=biCamDSI.selectNearObjects(
				0.0, // double     min_strength,
				infinity_select, // boolean [] infinity_select,
				selection, // boolean [] selection,
				rig_disparity_strength[0], // 	double []  disparity,
				rig_disparity_strength[1]);  // 	double []  strength,
2681 2682 2683



2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
		if (dbg_sel!=null) dbg_sel[3] = selection.clone();

		if (clt_parameters.rig.rf_master_infinity) {
			selection = biCamDSI.combineSelections(
					selection, // boolean [] selection1,
					was_select, // boolean [] selection2,
					infinity_select, // boolean [] enable,
					false); // boolean    invert_enable)
		}
		if (clt_parameters.rig.rf_master_near) {
			selection = biCamDSI.combineSelections(
					selection, // boolean [] selection1,
					was_select, // boolean [] selection2,
					infinity_select, // boolean [] enable,
					true); // boolean    invert_enable)
		}
		if (dbg_sel!=null) dbg_sel[4] = selection.clone(); // far+near+old

		boolean [] selection_lone = biCamDSI.selectLoneFar(
				clt_parameters.rig.ltfar_trusted_s, //  double     min_far_strength,
				clt_parameters.rig.ltfar_trusted_d, // 	double     min_far_disparity,
				infinity_select,                    // boolean [] infinity_select,
				null,                               // boolean [] selection,
				rig_disparity_strength[0],          // double []  disparity,
				rig_disparity_strength[1]);         // double []  strength)
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720

		selection_lone = biCamDSI.selectNearOverInfinity(
				clt_parameters.rig.ltgrp_min_strength,       // double     min_strength,
				clt_parameters.rig.ltgrp_min_neibs,          // int        min_neibs,
				clt_parameters.rig.ltgrp_gr_min_disparity,   // double     min_disparity,
				clt_parameters.rig.ltgrp_gr_disp_atolerance, // double     disp_atolerance,
				clt_parameters.rig.ltgrp_gr_disp_rtolerance, // double     disp_rtolerance,
				infinity_select,                             // boolean [] infinity_select,
				selection,                                   // boolean [] selection,
				rig_disparity_strength[0],                   // double []  disparity,
				rig_disparity_strength[1]);                  // double []  strength,

2721 2722 2723 2724 2725 2726 2727
		// add this selection, but keep it too till after filtering
		selection = biCamDSI.combineSelections(
				selection,                          // boolean [] selection1,
				selection_lone,                     // boolean [] selection2,
				null,                               // boolean [] enable,
				false);                             // boolean    invert_enable)
		if (dbg_sel!=null) dbg_sel[5] = selection.clone(); // far+near+old+lone
2728 2729

		// filter only near objects
2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
		biCamDSI.expandShrinkExpandFilter(
				clt_parameters.rig.rf_pre_expand_near,   // int        pre_expand,
				clt_parameters.rig.rf_shrink_near,       // 	int        shrink,
				clt_parameters.rig.rf_post_expand_near,  // int        post_expand,
				selection,                          // 	boolean [] selection,
				infinity_select); // 	boolean [] prohibit)
		// filter all - infinity and near (less aggressive)

		if (dbg_sel!=null) dbg_sel[6] = selection.clone(); // far+near+old+lone- filtered near

		biCamDSI.expandShrinkExpandFilter(
				clt_parameters.rig.rf_pre_expand,   // int        pre_expand,
				clt_parameters.rig.rf_shrink,       // 	int        shrink,
				clt_parameters.rig.rf_post_expand,  // int        post_expand,
				selection,                          // 	boolean [] selection,
				null); // 	boolean [] prohibit)

		if (dbg_sel!=null) dbg_sel[7] = selection.clone(); // far+near+old+lone- filtered near-filtered far

		// restore lone tile selections (may be removed by filter)
		selection = biCamDSI.combineSelections(
				selection,                          // boolean [] selection1,
				selection_lone,                     // boolean [] selection2,
				null,                               // boolean [] enable,
				false);                             // boolean    invert_enable)
		// restore master camera selections (poles may be removed by a filter
		if (clt_parameters.rig.rf_master_infinity) {
			selection = biCamDSI.combineSelections(
					selection, // boolean [] selection1,
					was_select, // boolean [] selection2,
					infinity_select, // boolean [] enable,
					false); // boolean    invert_enable)
		}
		if (clt_parameters.rig.rf_master_near) {
			selection = biCamDSI.combineSelections(
					selection, // boolean [] selection1,
					was_select, // boolean [] selection2,
					infinity_select, // boolean [] enable,
					true); // boolean    invert_enable)
		}

		if (dbg_sel != null) {
			double [][] dbg_img = new double[7][selection.length];
			for (int nTile = 0; nTile < selection.length;nTile++) {
				dbg_img[0][nTile] = (dbg_sel[0][nTile]? 1.0:0.0) + (dbg_sel[1][nTile]?2.0:0.0);
				dbg_img[1][nTile] = (dbg_sel[2][nTile]? 1.0:0.0) + (dbg_sel[3][nTile]?2.0:0.0);
				dbg_img[2][nTile] = (dbg_sel[4][nTile]? 1.0:0.0) + (dbg_sel[5][nTile]?2.0:0.0);
				dbg_img[3][nTile] = (dbg_sel[6][nTile]? 1.0:0.0);
				dbg_img[4][nTile] = (dbg_sel[7][nTile]? 1.0:0.0);
				dbg_img[5][nTile] = (selection[nTile]? 1.0:0.0);
				dbg_img[6][nTile] = (selection_lone[nTile]? 1.0:0.0);
			}
			String [] titles = {"old_sel","new_sel","combo-lone", "f-near", "f-far","final","lone"};
2783
			(new ShowDoubleFloatArrays()).showArrays(
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
					dbg_img,
					tilesX,
					dbg_img[0].length/tilesX,
					true,
					"Selections",
					titles);
		}
		// set composite scan

		boolean [] cond_sel = (clt_parameters.rig.rf_remove_unselected)? selection:null;
		double [][] f_rig_disparity_strength =  biCamDSI.filterDisparityStrength(
				clt_parameters.rig.rf_min_disp,     // double  min_disparity,
				rig_disparity_strength[0],          // double []  disparity,
				rig_disparity_strength[1],          // double []  strength)
				cond_sel);                          // 	boolean [] selected)
2799
		// CLT ASSIGN needs best texture for each tile. Initially will just copy from the previous master
2800 2801 2802 2803
		// composite scan, later - fill disparity gaps and re-measure

		/*
		 *  TODO: interpolate disparities before measuring to fill gaps?
2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
	  public double [][][][][] getRigTextures(
			  boolean                                  need_master,
			  boolean                                  need_aux,
			  double []                                disparity, // non-nan - measure
			  QuadCLT                                  quadCLT_main,  // tiles should be set
			  QuadCLT                                  quadCLT_aux,
			  EyesisCorrectionParameters.CLTParameters clt_parameters,
			  final int                                threadsMax,  // maximal number of threads to launch
			  final boolean                            updateStatus,
			  final int                                debugLevel) // throws Exception

2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
		 */

		quadCLT_main.tp.trimCLTPasses(false); // remove rig composite scan if any
		//		 quadCLT_main.tp.rig_pre_poles_ds =        f_rig_disparity_strength; // Rig disparity and strength before processing poles
		//		 quadCLT_main.tp.rig_pre_poles_sel =        selection; // Rig tile selection before processing poles
		quadCLT_main.tp.rig_pre_poles_ds =        rig_disparity_strength; // Rig disparity and strength before processing poles
		quadCLT_main.tp.rig_pre_poles_sel =        selection; // Rig tile selection before processing poles
		quadCLT_main.tp.rig_post_poles_ds =        null;
		quadCLT_main.tp.rig_post_poles_sel =       null;

		if (debugLevel > -4) {
			System.out.println("Saved quadCLT_main.tp.rig_pre_poles_ds and quadCLT_main.tp.rig_pre_poles_sel");
		}
		// process poles if enabled
		if (clt_parameters.poles.poles_en) {
			if (debugLevel > -4) {
				System.out.println("Processing poles");
			}

			//			  if (poleProcessor_persistent == null) {
			poleProcessor_persistent = new PoleProcessor(
					biCamDSI_persistent,
					this, //	TwoQuadCLT twoQuadCLT,
					quadCLT_main.tp.getTilesX(),
					quadCLT_main.tp.getTilesY());
			//			  }
			PoleProcessor pp = poleProcessor_persistent;
			selection =  quadCLT_main.tp.rig_pre_poles_sel.clone();

			int num_bugs_corrected= pp.zero_tiles_check(
					"pre-poles",
					quadCLT_main.tp.rig_pre_poles_ds, // double [][] ds,
					true); // boolean debug)
			if (num_bugs_corrected > 0) {
				System.out.println("Corrected "+num_bugs_corrected+" bugs, where disparity is <= 0 with non-zero strength before poles");
			}


			double [][] poles_ds = pp.processPoles(
					quadCLT_main,  // QuadCLT            quadCLT_main,  // tiles should be set
					quadCLT_aux,   //QuadCLT            quadCLT_aux,
					quadCLT_main.tp.rig_pre_poles_ds, //  double [][]                                    src_ds, // source disparity, strength pair
					selection, // boolean []                                     selection, // source tile selection, will be modified
					clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
					threadsMax,  // final int                                      threadsMax,  // maximal number of threads to launch
					updateStatus, // final boolean                                  updateStatus,

					(debugLevel > -2) ? clt_parameters.poles.poles_debug_level:debugLevel);//
			//					 (debugLevel > -4) ? clt_parameters.poles.poles_debug_level:debugLevel);//
			//					 debugLevel); // final int                                      globalDebugLevel)

			num_bugs_corrected= pp.zero_tiles_check(
					"post-poles",
					poles_ds, // double [][] ds,
					true); // boolean debug)
			if (num_bugs_corrected > 0) {
				System.out.println("Corrected "+num_bugs_corrected+" bugs, where disparity is <= 0 with non-zero strength after poles");
			}

			quadCLT_main.tp.rig_post_poles_ds =        poles_ds; // Rig disparity and strength before processing poles
			quadCLT_main.tp.rig_post_poles_sel =       selection; // Rig tile selection before processing poles
			if (debugLevel > -4) {
				System.out.println("Saved quadCLT_main.tp.rig_post_poles_ds and quadCLT_main.tp.rig_post_poles_sel");
			}

			f_rig_disparity_strength = poles_ds;
		} else {
			if (debugLevel > -4) {
				System.out.println("Skipped processing poles");
			}
		}

2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927
		// Add areas from the main camera that correspond do occlusions of the aux (and so missing rig data). No real analysis of the occlusions here,
		// just filling gaps where rig data is 0.0 strengtth

		if (clt_parameters.rig.oc_fill_aux_occl) {
			if (debugLevel > -4) {
				System.out.println("Trying to fill rig gaps with main camera data (assuming aux cam occlusions)");
			}
		//scan_last
			double [][] main_last_scan = quadCLT_main.tp.getShowDS(scan_last,
					false); // boolean force_final);
			double disp_scale_inter = quadCLT_main.geometryCorrection.getDisparityRadius()/quadCLT_aux.geometryCorrection.getBaseline(); // 4.8
			// TODO: Move to parameters
			double      disp_atol = 0.2;
			double      disp_rtol = 0.1;
			double      strength_boost = 1.5;
//			boolean

			boolean [] sel_occl =  selectAuxOcclusions(
					main_last_scan,                // double [][] ds_main,
					f_rig_disparity_strength,      // double [][] ds_rig,
					disp_scale_inter,              // double      disp_rig_scale,
					clt_parameters.rig.oc_min_strength, // double      min_strength,
					clt_parameters.grow_disp_max,                 // double      max_disparity,
					disp_atol,                     // double      disp_atol,
					disp_rtol,                     // double      disp_rtol,
					clt_parameters.transform_size, // int         tileSize,     // 8
					1);                            // int         debugLevel);
			if (sel_occl != null) {
				if (debugLevel > -4) {
					double [][] dbg_img = new double [5][];
					String [] titles = {"disp_main","disp_rig","disp_occl","str_main","str_rig"};
					dbg_img[0] = main_last_scan[0];
					dbg_img[1] = f_rig_disparity_strength[0];
					dbg_img[2] = main_last_scan[0].clone();
					dbg_img[3] = main_last_scan[1];
					dbg_img[4] = f_rig_disparity_strength[1];
					for (int nTile = 0; nTile < sel_occl.length; nTile++) {
						if (!sel_occl[nTile]) {
							dbg_img[2][nTile] = Double.NaN;
						}
					}
2928
					(new ShowDoubleFloatArrays()).showArrays(
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
							dbg_img,
							tilesX,
							dbg_img[0].length/tilesX,
							true,
							quadCLT_main.image_name+"Aux_occlusions",
							titles);
				}
				int num_replaced_occl = 0;
				for (int nTile = 0; nTile <  f_rig_disparity_strength[1].length; nTile++) { // only missing tiles
//					if (nTile== 50582) {
//						System.out.println("Replacing occlusions, nTile="+nTile);
//					}
					if (sel_occl[nTile]) {
						f_rig_disparity_strength[0][nTile] = main_last_scan[0][nTile];
						f_rig_disparity_strength[1][nTile] = strength_boost*  main_last_scan[1][nTile];
						selection[nTile] = true;
						num_replaced_occl ++;
					}
				}
				if (debugLevel > -4) {
					System.out.println("Replaced "+num_replaced_occl+" empty tiles in rig DSI with main camera data");
				}
			} else {
				if (debugLevel > -4) {
					System.out.println("No occluded tiles replaced");
				}

			}

/*
			int num_replaced_occl = 0;
			for (int nTile = 0; nTile <  f_rig_disparity_strength[1].length; nTile++) { // only missing tiles
				if (nTile== 50582) {
					System.out.println("Replacing occlusions, nTile="+nTile);
				}
				if (f_rig_disparity_strength[1][nTile] <= 0.0) { // only missing tiles
					if (    (main_last_scan[0][nTile] >= clt_parameters.rig.oc_min_disparity) && // only near objects
							(main_last_scan[1][nTile] >= clt_parameters.rig.oc_min_strength)) { // only strong tiles
						f_rig_disparity_strength[0][nTile] = main_last_scan[0][nTile];
						f_rig_disparity_strength[1][nTile] = main_last_scan[1][nTile];
						selection[nTile] = true;
						num_replaced_occl ++;
					}
				}
			}
*/
		}

2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987
		CLTPass3d rig_scan = quadCLT_main.tp.compositeScan(
				f_rig_disparity_strength[0],  // final double []             disparity,
				f_rig_disparity_strength[1],  // final double []             strength,
				selection,                  // final boolean []            selected,
				debugLevel);                // final int                   debugLevel)
		rig_scan.texture_tiles = scan_last.texture_tiles;

		// scan_last

		quadCLT_main.tp.clt_3d_passes.add(rig_scan);
		quadCLT_main.tp.saveCLTPasses(true);       // rig pass
2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057
	}

	public boolean [] selectAuxOcclusions(
			double [][] ds_main,
			double [][] ds_rig,
			double      disp_rig_scale,
			double      min_strength,
			double      max_disparity,
			double      disp_atol,
			double      disp_rtol,
			int         tileSize,     // 8
			int         debugLevel)
	{
		TileNeibs         tnImage =  biCamDSI_persistent.tnImage;
		int tilesX=  tnImage.getSizeX();
		int tilesY=  tnImage.getSizeY();
		int numTiles = tilesY*tilesX;
		boolean [] occl_sel = new boolean [numTiles];
		int num_replaced_occl = 0;
		for (int nTile = 0; nTile < numTiles; nTile++) { // only missing tiles
			if (nTile== 47120) {
				System.out.println("Replacing occlusions, nTile="+nTile);
			}
			if ((ds_rig[1][nTile] <= 0.0) && (ds_main[1][nTile] >= min_strength)) { // only missing tiles
				// See if aux camera may be potentially occluded for this tile
				int tileX = nTile % tilesX;
				int tileY = nTile / tilesX;
				double disp = ds_main[0][nTile];
				for (int tx = tileX+1; tx < tilesX; tx++) {
					disp += tileSize*disp_rig_scale; // disparity of the next tile right (here we assume aux is to the right of the main!)
					if (disp > max_disparity) {
						break;
					}
					int nTile1 = tnImage.getIndex(tx, tileY);
					if (nTile1>= 0) {
						double mn = (ds_rig[1][nTile1] > 0.0) ? ds_rig[0][nTile1]: Double.NaN;
						double mx = mn;
						for (int dir = 0; dir < 8; dir++) {
							int nTile2 = tnImage.getNeibIndex(nTile1, dir);
							if (nTile2 >= 0) if ((ds_rig[1][nTile2] > 0.0) && !Double.isNaN(ds_rig[0][nTile2])){
								if (!(ds_rig[0][nTile2] > mn)) mn = ds_rig[0][nTile2]; // mn==NaN - assign
								if (!(ds_rig[0][nTile2] < mx)) mx = ds_rig[0][nTile2]; // mn==NaN - assign
							}
						}
						if (!Double.isNaN(mn)) {
							double disp_avg = 0.5*(mn+mx);
							double disp_tol = disp_atol + disp_avg*disp_rtol;
							if (mx < (disp_avg + disp_tol)) mx =  disp_avg + disp_tol;
							if (mn < (disp_avg - disp_tol)) mn =  disp_avg - disp_tol;
							if ((disp >= mn) && (disp <=mx)) { // that may be occlusion
								occl_sel[nTile] = true;
								num_replaced_occl ++;
								if (debugLevel > 0) {
									System.out.println("Tile ("+tileX+", "+tileY+") may have an occlusion for aux camera by ("+
											(nTile1 % tilesX)+", "+(nTile1 / tilesX)+")");
								}
								break; // for (int nTile = 0; nTile < numTiles; nTile++)
							}
						}
					}
				}
			}
		}
		if (debugLevel > 0) {
			System.out.println("Found "+num_replaced_occl+" potential aux camera occluded tiles");
		}
		if (num_replaced_occl == 0) {
			occl_sel = null; // not caller to bother
		}
		return occl_sel;
3058 3059
	}

3060
	public double [][][][][] getRigTextures( // never used
3061 3062 3063 3064 3065
			boolean                                  need_master,
			boolean                                  need_aux,
			double []                                disparity, // non-nan - measure
			QuadCLT                                  quadCLT_main,  // tiles should be set
			QuadCLT                                  quadCLT_aux,
3066
			CLTParameters clt_parameters,
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090
			final int                                threadsMax,  // maximal number of threads to launch
			final boolean                            updateStatus,
			final int                                debugLevel) // throws Exception
	{
		final int tile_op_all = clt_parameters.tile_task_op; //FIXME Use some constant?
		final int tilesX = quadCLT_main.tp.getTilesX();
		final int tilesY = quadCLT_main.tp.getTilesY();
		final int [][]     tile_op = new int [tilesY][tilesX];
		final double [][]  disparity_array = new double [tilesY][tilesX];
		boolean [] need_textures = {need_master, need_aux};
		final double [][][][][] texture_tiles = new double [need_textures.length][][][][];
		for (int ncam = 0; ncam < need_textures.length; ncam++) if (need_textures[ncam]) {
			texture_tiles[ncam] = new double [tilesY][tilesX][][];
			for (int tileY = 0; tileY < tilesY; tileY++){
				for (int tileX = 0; tileX < tilesX; tileX++){
					texture_tiles[ncam][tileY][tileX] = null;
					int nTile = tileY*tilesX + tileX;
					if (!Double.isNaN(disparity[nTile])) {
						tile_op[tileY][tileX] = tile_op_all;
						disparity_array[tileY][tileX] = disparity[nTile];
					}
				}
			}
		}
3091 3092 3093
		ImageDtt image_dtt = new ImageDtt(
				clt_parameters.transform_size,
				quadCLT_main.isMonochrome(),
3094
				quadCLT_main.isLwir(),
3095
				clt_parameters.getScaleStrength(false));
3096 3097
		image_dtt.clt_bi_quad (
				clt_parameters,                       // final EyesisCorrectionParameters.CLTParameters       clt_parameters,
3098
				clt_parameters.getFatZero(image_dtt.isMonochrome()),              // final double              fatzero,         // May use correlation fat zero from 2 different parameters - fat_zero and rig.ml_fatzero
3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
				false,                                //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				0,                                    // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				// does not matter here
				true,                                 // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				tile_op,                              // final int [][]            tile_op_main,    // [tilesY][tilesX] - what to do - 0 - nothing for this tile
				disparity_array,                      // final double [][]         disparity_array, // [tilesY][tilesX] - individual per-tile expected disparity
				quadCLT_main.image_data,              // final double [][][]       image_data_main, // first index - number of image in a quad
				quadCLT_aux.image_data,               // final double [][][]       image_data_aux,  // first index - number of image in a quad
				quadCLT_main.saturation_imp,          // final boolean [][]        saturation_main, // (near) saturated pixels or null
				quadCLT_aux.saturation_imp,           // final boolean [][]        saturation_aux,  // (near) saturated pixels or null
				// correlation results - combo will be for the correation between two quad cameras
				null,                                 // final double [][][][]     clt_corr_combo,  // [type][tilesY][tilesX][(2*transform_size-1)*(2*transform_size-1)] // if null - will not calculate
				null, // disparity_bimap,             // final double [][]    disparity_bimap, // [23][tilesY][tilesX]
				null, // ml_data,                     // 	final double [][]         ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				texture_tiles[0],                     // final double [][][][]     texture_tiles_main, // [tilesY][tilesX]["RGBA".length()][];  null - will skip images combining
				texture_tiles[1],                     // final double [][][][]     texture_tiles_aux,  // [tilesY][tilesX]["RGBA".length()][];  null - will skip images combining
3115
				quadCLT_main.tp.getTilesX()*image_dtt.transform_size, // final int                 width,
3116 3117 3118 3119 3120 3121 3122

				quadCLT_main.getGeometryCorrection(), // final GeometryCorrection  geometryCorrection_main,
				quadCLT_aux.getGeometryCorrection(),  // final GeometryCorrection  geometryCorrection_aux,
				quadCLT_main.getCLTKernels(),         // final double [][][][][][] clt_kernels_main, // [channel_in_quad][color][tileY][tileX][band][pixel] , size should match image (have 1 tile around)
				quadCLT_aux.getCLTKernels(),          // final double [][][][][][] clt_kernels_aux,  // [channel_in_quad][color][tileY][tileX][band][pixel] , size should match image (have 1 tile around)
				clt_parameters.corr_magic_scale,      // final double              corr_magic_scale, // still not understood coefficient that reduces reported disparity value.  Seems to be around 0.85
				false, // true,                                 // 	final boolean             keep_clt_data,
3123
//				woi_tops,                             // final int [][]            woi_tops,
3124
				null,                                 // final double [][][]       ers_delay,        // if not null - fill with tile center acquisition delay
3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136
				threadsMax,                           // final int                 threadsMax,  // maximal number of threads to launch
				debugLevel-2);                        // final int                 globalDebugLevel);

		return texture_tiles;

	}



	public void copyJP4src(
			QuadCLT                                  quadCLT_main,  // tiles should be set
			QuadCLT                                  quadCLT_aux,
3137
			CLTParameters clt_parameters,
3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170
			final int                                debugLevel) // throws Exception
	{
		//		  quadCLT_main.writeKml(debugLevel);
		//		  quadCLT_main.writeRatingFile(debugLevel);


		String [] sourceFiles_main=quadCLT_main.correctionsParameters.getSourcePaths();
		//



		//		  String [] sourceFiles_aux=quadCLT_main.correctionsParameters.getSourcePaths();
		String set_name = quadCLT_main.image_name;
		if (set_name == null ) {
			QuadCLT.SetChannels [] set_channels=quadCLT_main.setChannels(debugLevel);
			set_name = set_channels[0].set_name;
		}

		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(set_name,debugLevel); // only for specified image timestamp
		QuadCLT.SetChannels [] set_channels_aux =  quadCLT_aux.setChannels(set_name,debugLevel);

		ArrayList<String> path_list = new ArrayList<String>();
		for (int i = 0; i < set_channels_main.length; i++) {
			for (int fn:set_channels_main[i].file_number) {
				path_list.add(sourceFiles_main[fn]);
			}
		}
		for (int i = 0; i < set_channels_aux.length; i++) {
			for (int fn:set_channels_aux[i].file_number) {
				path_list.add(sourceFiles_main[fn]);
			}
		}

3171
		quadCLT_main.writeKml(debugLevel ); // also generated with x3d model
3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197

		String jp4_copy_path= quadCLT_main.correctionsParameters.selectX3dDirectory(
				set_name, // quad timestamp. Will be ignored if correctionsParameters.use_x3d_subdirs is false
				quadCLT_main.correctionsParameters.jp4SubDir,
				true,  // smart,
				true);  //newAllowed, // save
		File dir = (new File(jp4_copy_path)); // .getParentFile();
		if (!dir.exists()){
			dir.mkdirs();
			System.out.println("Created "+dir);
		}
		for (String fname:path_list) {
			if (fname.contains(quadCLT_main.image_name)) { // only files containing set name // TODO:improve
				File file = new File(fname);
				try {
					Files.copy(
							(file).toPath(),
							(new File(jp4_copy_path + Prefs.getFileSeparator()+file.getName())).toPath(),
							StandardCopyOption.REPLACE_EXISTING);
					System.out.println("Copied "+fname+" -> "+dir);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					System.out.println("Failed to copy "+fname+" -> "+dir);
				}
			}
		}
3198
		System.out.println("jp4_copy_path = "+jp4_copy_path);
3199 3200 3201 3202 3203 3204 3205 3206
		//		  System.out.println("Do something useful here");
	}



	public void outputMLData(
			QuadCLT                                  quadCLT_main,  // tiles should be set
			QuadCLT                                  quadCLT_aux,
3207
			CLTParameters clt_parameters,
3208
			String                                   ml_directory,       // full path or null (will use config one)
3209 3210 3211 3212 3213 3214 3215 3216 3217 3218
			final int                                threadsMax,  // maximal number of threads to launch
			final boolean                            updateStatus,
			final int                                debugLevel) // throws Exception
	{
		if ((quadCLT_main.tp == null) || (quadCLT_main.tp.rig_pre_poles_ds == null)) {
			String msg = "DSI data not available. Please run \"Ground truth\" first";
			IJ.showMessage("Error",msg);
			System.out.println(msg);
			return;
		}
3219
		boolean post_poles =  clt_parameters.rig.ml_poles;
3220
		double [][] rig_disparity_strength = clt_parameters.rig.ml_poles?quadCLT_main.tp.rig_post_poles_ds : quadCLT_main.tp.rig_pre_poles_ds;
3221 3222 3223 3224 3225
		if ((quadCLT_main.tp.main_ds_ml == null) && (this.dsi != null) &&  (this.dsi[DSI_DISPARITY_MAIN] != null) &&  (this.dsi[DSI_STRENGTH_MAIN] != null)){
			quadCLT_main.tp.main_ds_ml = new double[2][];
			quadCLT_main.tp.main_ds_ml[0] = this.dsi[DSI_DISPARITY_MAIN];
			quadCLT_main.tp.main_ds_ml[1] = this.dsi[DSI_STRENGTH_MAIN];
		}
3226
		double [][] main_disparity_strength = quadCLT_main.tp.main_ds_ml;
3227 3228
		if (rig_disparity_strength == null) {
			System.out.println("DSI data for the scene after poles extraction is not available. You may enable it and re-run \"Ground truth\" command or run \"Poles GT\"");
Andrey Filippov's avatar
Andrey Filippov committed
3229 3230
			rig_disparity_strength = quadCLT_main.tp.rig_pre_poles_ds;
			System.out.println("Using pre-poles data for ML output");
3231
		}
Andrey Filippov's avatar
Andrey Filippov committed
3232
		if (debugLevel > -6) {
3233
			if (post_poles) {
3234 3235 3236 3237 3238
				System.out.println("==== Generating ML data for the DSI that includes extracted vertical poles ====");
			} else {
				System.out.println("==== Generating ML data for the DSI that DOES NOT include extracted vertical poles ====");
			}
		}
Andrey Filippov's avatar
Andrey Filippov committed
3239
		// Create filtered/expanded min and rig DSI
3240 3241 3242 3243
		// FIXME: Make quadCLT_main.tp.main_ds_ml dusing COMBO_DSI write (too late) or just write earlier?
		double [][] main_dsi = null;
		if (main_disparity_strength != null) {
			main_dsi = enhanceMainDSI(
Andrey Filippov's avatar
Andrey Filippov committed
3244 3245 3246 3247 3248 3249 3250 3251 3252 3253
				main_disparity_strength,              // double [][] main_dsi,
				rig_disparity_strength,               // double [][] rig_dsi,
				clt_parameters.rig.ml_rig_tolerance,  // double      rig_tolerance,
				clt_parameters.rig.ml_rnd_offset,     // double      rnd_offset,
				clt_parameters.rig.ml_main_tolerance, // double      main_tolerance,
				clt_parameters.rig.ml_grow_steps,     // int         grow_steps,
				clt_parameters.rig.ml_grow_mode,      // int         grow_mode,
				clt_parameters.rig.ml_new_strength,   // double      new_strength)
//				debugLevel + 3);                        // int         debugLevel);
				debugLevel + 0);                        // int         debugLevel);
3254
		}
Andrey Filippov's avatar
Andrey Filippov committed
3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265
		double [][] rig_dsi = enhanceMainDSI(
				rig_disparity_strength,              // double [][] main_dsi,
				rig_disparity_strength,               // double [][] rig_dsi,
				clt_parameters.rig.ml_rig_tolerance,  // double      rig_tolerance,
				clt_parameters.rig.ml_rnd_offset,     // double      rnd_offset,
				clt_parameters.rig.ml_main_tolerance, // double      main_tolerance,
				clt_parameters.rig.ml_grow_steps,     // int         grow_steps,
				clt_parameters.rig.ml_grow_mode,      // int         grow_mode,
				clt_parameters.rig.ml_new_strength,   // double      new_strength)
//				debugLevel + 3);                        // int         debugLevel);
				debugLevel + 0);                        // int         debugLevel);
3266

3267
		if (ml_directory == null) ml_directory= quadCLT_main.correctionsParameters.selectMlDirectory(
3268 3269 3270 3271 3272 3273 3274
				quadCLT_main.image_name,
				true,  // smart,
				true);  //newAllowed, // save
		Correlation2d corr2d = new Correlation2d(
				clt_parameters.img_dtt,              // ImageDttParameters  imgdtt_params,
				clt_parameters.transform_size,             // int transform_size,
				2.0,                        //  double wndx_scale, // (wndy scale is always 1.0)
3275
				quadCLT_main.isMonochrome(),
3276
				(debugLevel > -1));   //   boolean debug)
3277

3278
// Create test data that does not rely on the rig measurements
3279
		String img_name_main =quadCLT_main.image_name+"-ML_DATA-";
Andrey Filippov's avatar
Andrey Filippov committed
3280
		// zero random offset:
3281
		if ( clt_parameters.rig.ml_main && (main_dsi != null)) {
Andrey Filippov's avatar
Andrey Filippov committed
3282 3283 3284 3285 3286 3287 3288 3289 3290
			double [][] ml_data_main = remeasureRigML(
					0.0,                     // double               disparity_offset_low,
					Double.NaN, // 0.0,                    // double               disparity_offset_high,
					quadCLT_main,                             // QuadCLT              quadCLT_main,    // tiles should be set
					quadCLT_aux,                              // QuadCLT              quadCLT_aux,
					//	    			  disparity_bimap,                          // double [][]          src_bimap,
					main_dsi[0],               // double []            disparity_main, // main camera disparity to use - if null, calculate from the rig one
					rig_disparity_strength[0],                // double []            disparity,
					rig_disparity_strength[1],                // double []            strength,
3291

Andrey Filippov's avatar
Andrey Filippov committed
3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319
					clt_parameters,                           // EyesisCorrectionParameters.CLTParameters clt_parameters,
					clt_parameters.rig.ml_hwidth,             // int ml_hwidth
					clt_parameters.rig.ml_fatzero,            // double               fatzero,
					//change if needed?
					0, //  int              lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
					threadsMax,                               // final int            threadsMax,  // maximal number of threads to launch
					updateStatus,                             // final boolean        updateStatus,
					debugLevel);                              // final int            debugLevel);
			saveMlFile(
					img_name_main,                                 // String               ml_title,
					ml_directory,                             // String               ml_directory,
					Double.NaN,                               // double               disp_offset_low,
					Double.NaN,                               // double               disp_offset_high,
					quadCLT_main,                             // QuadCLT              quadCLT_main,
					quadCLT_aux,                              // QuadCLT              quadCLT_aux,
					corr2d,                                   //Correlation2d        corr2d, // to access "other" layer
					clt_parameters.rig.ml_8bit,               // boolean              use8bpp,
					clt_parameters.rig.ml_limit_extrim,       // double               limit_extrim,
					clt_parameters.rig.ml_keep_aux,           // boolean              keep_aux,
					clt_parameters.rig.ml_keep_inter,         // boolean              keep_inter,
					clt_parameters.rig.ml_keep_hor_vert,      // boolean              keep_hor_vert,
					clt_parameters.rig.ml_keep_tbrl,          // boolean              ml_keep_tbrl,
					clt_parameters.rig.ml_keep_debug,         // boolean              keep_debug,
					clt_parameters.rig.ml_fatzero,            // double               ml_fatzero,
					clt_parameters.rig.ml_hwidth,             // int                  ml_hwidth,
					ml_data_main,                             // double [][]          ml_data,
					clt_parameters.rig.ml_show_ml,            // boolean              show,
					debugLevel);                              // int                  debugLevel
3320

Andrey Filippov's avatar
Andrey Filippov committed
3321 3322
		}
		// Create images from main cameras, but adding random disparity offset
3323
		if ( clt_parameters.rig.ml_main_rnd && (main_dsi != null)) {
Andrey Filippov's avatar
Andrey Filippov committed
3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
			double [][] ml_data_main = remeasureRigML(
					0.0,                     // double               disparity_offset_low,
					clt_parameters.rig.ml_disparity_sweep, // 0.0,                    // double               disparity_offset_high,
					quadCLT_main,                             // QuadCLT              quadCLT_main,    // tiles should be set
					quadCLT_aux,                              // QuadCLT              quadCLT_aux,
					//	    			  disparity_bimap,                          // double [][]          src_bimap,
					main_dsi[0],               // double []            disparity_main, // main camera disparity to use - if null, calculate from the rig one
					rig_disparity_strength[0],                // double []            disparity,
					rig_disparity_strength[1],                // double []            strength,

					clt_parameters,                           // EyesisCorrectionParameters.CLTParameters clt_parameters,
					clt_parameters.rig.ml_hwidth,             // int ml_hwidth
					clt_parameters.rig.ml_fatzero,            // double               fatzero,
					//change if needed?
					0, //  int              lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
					threadsMax,                               // final int            threadsMax,  // maximal number of threads to launch
					updateStatus,                             // final boolean        updateStatus,
					debugLevel);                              // final int            debugLevel);
			saveMlFile(
					img_name_main,                            // String               ml_title,
					ml_directory,                             // String               ml_directory,
					Double.NaN,                               // double               disp_offset_low,
					clt_parameters.rig.ml_disparity_sweep,    // double               disp_offset_high,
					quadCLT_main,                             // QuadCLT              quadCLT_main,
					quadCLT_aux,                              // QuadCLT              quadCLT_aux,
					corr2d,                                   //Correlation2d        corr2d, // to access "other" layer
					clt_parameters.rig.ml_8bit,               // boolean              use8bpp,
					clt_parameters.rig.ml_limit_extrim,       // double               limit_extrim,
					clt_parameters.rig.ml_keep_aux,           // boolean              keep_aux,
					clt_parameters.rig.ml_keep_inter,         // boolean              keep_inter,
					clt_parameters.rig.ml_keep_hor_vert,      // boolean              keep_hor_vert,
					clt_parameters.rig.ml_keep_tbrl,          // boolean              ml_keep_tbrl,
					clt_parameters.rig.ml_keep_debug,         // boolean              keep_debug,
					clt_parameters.rig.ml_fatzero,            // double               ml_fatzero,
					clt_parameters.rig.ml_hwidth,             // int                  ml_hwidth,
					ml_data_main,                             // double [][]          ml_data,
					clt_parameters.rig.ml_show_ml,            // boolean              show,
					debugLevel);                              // int                  debugLevel
3362

Andrey Filippov's avatar
Andrey Filippov committed
3363 3364 3365
		}

		// Create images from main cameras, but adding random disparity offset
3366
		if ( clt_parameters.rig.ml_rig_rnd && (rig_dsi != null)) {
Andrey Filippov's avatar
Andrey Filippov committed
3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403
			double [][] ml_data_main = remeasureRigML(
					0.0,                     // double               disparity_offset_low,
					clt_parameters.rig.ml_disparity_sweep, // 0.0,                    // double               disparity_offset_high,
					quadCLT_main,                             // QuadCLT              quadCLT_main,    // tiles should be set
					quadCLT_aux,                              // QuadCLT              quadCLT_aux,
					rig_dsi[0],                               // double []            disparity_main, // main camera disparity to use - if null, calculate from the rig one
					rig_disparity_strength[0],                // double []            disparity,
					rig_disparity_strength[1],                // double []            strength,

					clt_parameters,                           // EyesisCorrectionParameters.CLTParameters clt_parameters,
					clt_parameters.rig.ml_hwidth,             // int ml_hwidth
					clt_parameters.rig.ml_fatzero,            // double               fatzero,
					//change if needed?
					0, //  int              lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
					threadsMax,                               // final int            threadsMax,  // maximal number of threads to launch
					updateStatus,                             // final boolean        updateStatus,
					debugLevel);                              // final int            debugLevel);
			saveMlFile(
					img_name_main,                            // String               ml_title,
					ml_directory,                             // String               ml_directory,
					Double.NaN,                               // double               disp_offset_low,
					-clt_parameters.rig.ml_disparity_sweep,   // double               disp_offset_high,
					quadCLT_main,                             // QuadCLT              quadCLT_main,
					quadCLT_aux,                              // QuadCLT              quadCLT_aux,
					corr2d,                                   //Correlation2d        corr2d, // to access "other" layer
					clt_parameters.rig.ml_8bit,               // boolean              use8bpp,
					clt_parameters.rig.ml_limit_extrim,       // double               limit_extrim,
					clt_parameters.rig.ml_keep_aux,           // boolean              keep_aux,
					clt_parameters.rig.ml_keep_inter,         // boolean              keep_inter,
					clt_parameters.rig.ml_keep_hor_vert,      // boolean              keep_hor_vert,
					clt_parameters.rig.ml_keep_tbrl,          // boolean              ml_keep_tbrl,
					clt_parameters.rig.ml_keep_debug,         // boolean              keep_debug,
					clt_parameters.rig.ml_fatzero,            // double               ml_fatzero,
					clt_parameters.rig.ml_hwidth,             // int                  ml_hwidth,
					ml_data_main,                             // double [][]          ml_data,
					clt_parameters.rig.ml_show_ml,            // boolean              show,
					debugLevel);                              // int                  debugLevel
3404

Andrey Filippov's avatar
Andrey Filippov committed
3405 3406 3407 3408
		}
		// Old code:
		// Create images from tig with random offset
		// TODO: add extrapolation, similar to main camera?
3409
		for (int sweep_step = 0; sweep_step < clt_parameters.rig.ml_sweep_steps; sweep_step++){
3410 3411
			double disparity_offset_low = 0;
			double disparity_offset_high = Double.NaN;
3412
			if (clt_parameters.rig.ml_sweep_steps > 1) {
3413 3414 3415 3416
				disparity_offset_low = clt_parameters.rig.ml_disparity_sweep * (2.0 * sweep_step/(clt_parameters.rig.ml_sweep_steps - 1.0) -1.0);
				if (clt_parameters.rig.ml_randomize) {
					disparity_offset_high = clt_parameters.rig.ml_disparity_sweep * (2.0 * (sweep_step + 1)/(clt_parameters.rig.ml_sweep_steps - 1.0) -1.0);
				}
3417
			}
3418

3419
			String img_name = clt_parameters.rig.ml_randomize ? quadCLT_main.image_name+"-ML_DATARND-" : quadCLT_main.image_name+"-ML_DATA-";
3420
			double [][] ml_data = remeasureRigML(
3421 3422
					disparity_offset_low,                     // double               disparity_offset_low,
					disparity_offset_high,                    // double               disparity_offset_high,
3423 3424 3425
					quadCLT_main,                             // QuadCLT              quadCLT_main,    // tiles should be set
					quadCLT_aux,                              // QuadCLT              quadCLT_aux,
					//	    			  disparity_bimap,                          // double [][]          src_bimap,
3426
					null, // double []                                      disparity_main, // main camera disparity to use - if null, calculate from the rig one
3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438
					rig_disparity_strength[0],                // double []            disparity,
					rig_disparity_strength[1],                // double []            strength,

					clt_parameters,                           // EyesisCorrectionParameters.CLTParameters clt_parameters,
					clt_parameters.rig.ml_hwidth,             // int ml_hwidth
					clt_parameters.rig.ml_fatzero,            // double               fatzero,
					//change if needed?
					0, //  int              lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
					threadsMax,                               // final int            threadsMax,  // maximal number of threads to launch
					updateStatus,                             // final boolean        updateStatus,
					debugLevel);                              // final int            debugLevel);
			saveMlFile(
3439
					img_name,                                 // String               ml_title,
3440
					ml_directory,                             // String               ml_directory,
3441 3442
					disparity_offset_low,                     // double               disp_offset_low,
					disparity_offset_high,                    // double               disp_offset_high,
3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457
					quadCLT_main,                             // QuadCLT              quadCLT_main,
					quadCLT_aux,                              // QuadCLT              quadCLT_aux,
					corr2d,                                   //Correlation2d        corr2d, // to access "other" layer
					clt_parameters.rig.ml_8bit,               // boolean              use8bpp,
					clt_parameters.rig.ml_limit_extrim,       // double               limit_extrim,
					clt_parameters.rig.ml_keep_aux,           // boolean              keep_aux,
					clt_parameters.rig.ml_keep_inter,         // boolean              keep_inter,
					clt_parameters.rig.ml_keep_hor_vert,      // boolean              keep_hor_vert,
					clt_parameters.rig.ml_keep_tbrl,          // boolean              ml_keep_tbrl,
					clt_parameters.rig.ml_keep_debug,         // boolean              keep_debug,
					clt_parameters.rig.ml_fatzero,            // double               ml_fatzero,
					clt_parameters.rig.ml_hwidth,             // int                  ml_hwidth,
					ml_data,                                  // double [][]          ml_data,
					clt_parameters.rig.ml_show_ml,            // boolean              show,
					debugLevel);                              // int                  debugLevel
3458
			Runtime.getRuntime().gc();
3459 3460 3461 3462 3463 3464 3465 3466
			if (clt_parameters.rig.ml_randomize) {
				System.out.println("Generated ML data, randomized offset = "+String.format("%8.5f...%8.5f",disparity_offset_low,disparity_offset_high)+", --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");
			} else {
				System.out.println("Generated ML data, offset = "+String.format("%8.5f",disparity_offset_low)+", --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");
			}
			if (clt_parameters.rig.ml_randomize && (sweep_step == (clt_parameters.rig.ml_sweep_steps-2))) { // reduce by 1 for random
				break;
			}
3467 3468 3469
		}
	}

3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642


	public void outputMLDataLwir(
			QuadCLT                                  quadCLT_aux,
			CLTParameters clt_parameters,
			String                                   ml_directory,       // full path or null (will use config one)
			final int                                threadsMax,  // maximal number of threads to launch
			final boolean                            updateStatus,
			final int                                debugLevel) // throws Exception
	{

		if ((quadCLT_aux == null) || (quadCLT_aux.tp == null) || (this.dsi_aux_from_main  == null)) {
			String msg = "DSI data for AUX camera is not available. Please generateload it first";
			IJ.showMessage("Error",msg);
			System.out.println(msg);
			return;
		}
		String img_name =quadCLT_main.image_name+"-ML_DATA-";
		if (ml_directory == null) ml_directory= quadCLT_main.correctionsParameters.selectMlDirectory(
				quadCLT_main.image_name,
				true,  // smart,
				true);  //newAllowed, // save
		Correlation2d corr2d = new Correlation2d(
				clt_parameters.img_dtt,         // ImageDttParameters  imgdtt_params,
				clt_parameters.transform_size,  // int transform_size,
				2.0,                            // double wndx_scale, // (wndy scale is always 1.0)
				quadCLT_aux.isMonochrome(),     // boolean monochrome,
				(debugLevel > -1));             // boolean debug)

		if (clt_parameters.rig.ml_aux_ag) {
			double [][] ml_data =  remeasureAuxML(
					quadCLT_aux,                                    // QuadCLT                                        quadCLT_aux,
					this.dsi_aux_from_main[QuadCLT.FGBG_DISPARITY], // double []                                      disparity,
					this.dsi_aux_from_main,                         // double [][]                                    dsi_aux_from_main, // Main camera DSI converted into the coordinates of the AUX one (see QuadCLT.FGBG_TITLES)-
					clt_parameters,                                 // CLTParameters       clt_parameters,
					clt_parameters.rig.ml_hwidth,                   // int                                            ml_hwidth,
					clt_parameters.rig.ml_fatzero,                  // double                                         fatzero,
					threadsMax,                                     // final int            threadsMax,  // maximal number of threads to launch
					updateStatus,                                   // final boolean        updateStatus,
					debugLevel);                                    // final int            debugLevel);

			saveMlFile(
					img_name,                                 // String               ml_title,
					ml_directory,                             // String               ml_directory,
					Double.NaN,                               // double               disp_offset_low,
					0.0,   // AG                              // double               disp_offset_high,
					null, // quadCLT_main,                    // QuadCLT              quadCLT_main,
					quadCLT_aux,                              // QuadCLT              quadCLT_aux,
					corr2d,                                   // Correlation2d        corr2d, // to access "other" layer
					clt_parameters.rig.ml_8bit,               // boolean              use8bpp, // true
					clt_parameters.rig.ml_limit_extrim,       // double               limit_extrim, 1E-5
					clt_parameters.rig.ml_keep_aux,           // boolean              keep_aux, false
					clt_parameters.rig.ml_keep_inter,         // boolean              keep_inter, // false
					clt_parameters.rig.ml_keep_hor_vert,      // boolean              keep_hor_vert, // true
					clt_parameters.rig.ml_keep_tbrl,          // boolean              ml_keep_tbrl,  // false
					clt_parameters.rig.ml_keep_debug,         // boolean              keep_debug,    // false
					clt_parameters.rig.ml_fatzero,            // double               ml_fatzero,    // 0.05
					clt_parameters.rig.ml_hwidth,             // int                  ml_hwidth,     // 4
					ml_data,                                  // double [][]          ml_data,       //false
					clt_parameters.rig.ml_show_ml,            // boolean              show,
					debugLevel);                              // int                  debugLevel
		}
		if (clt_parameters.rig.ml_aux_fg) {
			double [][] ml_data =  remeasureAuxML(
					quadCLT_aux,                                  // QuadCLT                                        quadCLT_aux,
					this.dsi_aux_from_main[QuadCLT.FGBG_FG_DISP], // double []                                      disparity,
					this.dsi_aux_from_main,                       // double [][]                                    dsi_aux_from_main, // Main camera DSI converted into the coordinates of the AUX one (see QuadCLT.FGBG_TITLES)-
					clt_parameters,                               // CLTParameters       clt_parameters,
					clt_parameters.rig.ml_hwidth,                 // int                                            ml_hwidth,
					clt_parameters.rig.ml_fatzero,                // double                                         fatzero,
					threadsMax,                                   // final int            threadsMax,  // maximal number of threads to launch
					updateStatus,                                 // final boolean        updateStatus,
					debugLevel);                                  // final int            debugLevel);

			saveMlFile(
					img_name,                                 // String               ml_title,
					ml_directory,                             // String               ml_directory,
					Double.NaN,                               // double               disp_offset_low,
					1.0,  // FG                               // double               disp_offset_high,
					null, // quadCLT_main,                    // QuadCLT              quadCLT_main,
					quadCLT_aux,                              // QuadCLT              quadCLT_aux,
					corr2d,                                   // Correlation2d        corr2d, // to access "other" layer
					clt_parameters.rig.ml_8bit,               // boolean              use8bpp, // true
					clt_parameters.rig.ml_limit_extrim,       // double               limit_extrim, 1E-5
					clt_parameters.rig.ml_keep_aux,           // boolean              keep_aux, false
					clt_parameters.rig.ml_keep_inter,         // boolean              keep_inter, // false
					clt_parameters.rig.ml_keep_hor_vert,      // boolean              keep_hor_vert, // true
					clt_parameters.rig.ml_keep_tbrl,          // boolean              ml_keep_tbrl,  // false
					clt_parameters.rig.ml_keep_debug,         // boolean              keep_debug,    // false
					clt_parameters.rig.ml_fatzero,            // double               ml_fatzero,    // 0.05
					clt_parameters.rig.ml_hwidth,             // int                  ml_hwidth,     // 4
					ml_data,                                  // double [][]          ml_data,       //false
					clt_parameters.rig.ml_show_ml,            // boolean              show,
					debugLevel);                              // int                  debugLevel
		}

		if (clt_parameters.rig.ml_aux_bg) {
			double [][] ml_data =  remeasureAuxML(
					quadCLT_aux,                                  // QuadCLT                                        quadCLT_aux,
					this.dsi_aux_from_main[QuadCLT.FGBG_BG_DISP], // double []                                      disparity,
					this.dsi_aux_from_main,                       // double [][]                                    dsi_aux_from_main, // Main camera DSI converted into the coordinates of the AUX one (see QuadCLT.FGBG_TITLES)-
					clt_parameters,                               // CLTParameters       clt_parameters,
					clt_parameters.rig.ml_hwidth,                 // int                                            ml_hwidth,
					clt_parameters.rig.ml_fatzero,                // double                                         fatzero,
					threadsMax,                                   // final int            threadsMax,  // maximal number of threads to launch
					updateStatus,                                 // final boolean        updateStatus,
					debugLevel);                                  // final int            debugLevel);

			saveMlFile(
					img_name,                                 // String               ml_title,
					ml_directory,                             // String               ml_directory,
					Double.NaN,                               // double               disp_offset_low,
					-1.0,  // BG                              // double               disp_offset_high,
					null, // quadCLT_main,                    // QuadCLT              quadCLT_main,
					quadCLT_aux,                              // QuadCLT              quadCLT_aux,
					corr2d,                                   // Correlation2d        corr2d, // to access "other" layer
					clt_parameters.rig.ml_8bit,               // boolean              use8bpp, // true
					clt_parameters.rig.ml_limit_extrim,       // double               limit_extrim, 1E-5
					clt_parameters.rig.ml_keep_aux,           // boolean              keep_aux, false
					clt_parameters.rig.ml_keep_inter,         // boolean              keep_inter, // false
					clt_parameters.rig.ml_keep_hor_vert,      // boolean              keep_hor_vert, // true
					clt_parameters.rig.ml_keep_tbrl,          // boolean              ml_keep_tbrl,  // false
					clt_parameters.rig.ml_keep_debug,         // boolean              keep_debug,    // false
					clt_parameters.rig.ml_fatzero,            // double               ml_fatzero,    // 0.05
					clt_parameters.rig.ml_hwidth,             // int                  ml_hwidth,     // 4
					ml_data,                                  // double [][]          ml_data,       //false
					clt_parameters.rig.ml_show_ml,            // boolean              show,
					debugLevel);                              // int                  debugLevel
		}
		if (clt_parameters.rig.ml_aux_step > 0.0) {
			double [] target_disparity = new double [this.dsi_aux_from_main[QuadCLT.FGBG_DISPARITY].length];
			for (double disparity = clt_parameters.rig.ml_aux_low; disparity <= clt_parameters.rig.ml_aux_high; disparity += clt_parameters.rig.ml_aux_step) {
				for (int nt = 0; nt < target_disparity.length; nt++) {
					target_disparity[nt] = disparity;
				}
				double [][] ml_data =  remeasureAuxML(
						quadCLT_aux,                          // QuadCLT                                        quadCLT_aux,
						target_disparity,                     // double []                                      disparity,
						this.dsi_aux_from_main,               // double [][]                                    dsi_aux_from_main, // Main camera DSI converted into the coordinates of the AUX one (see QuadCLT.FGBG_TITLES)-
						clt_parameters,                       // CLTParameters       clt_parameters,
						clt_parameters.rig.ml_hwidth,         // int                                            ml_hwidth,
						clt_parameters.rig.ml_fatzero,        // double                                         fatzero,
						threadsMax,                           // final int            threadsMax,  // maximal number of threads to launch
						updateStatus,                         // final boolean        updateStatus,
						debugLevel);                          // final int            debugLevel);

				saveMlFile(
						img_name,                                 // String               ml_title,
						ml_directory,                             // String               ml_directory,
						disparity, // absolute disparity          // double               disp_offset_low,
						0.0,  // not used                         // double               disp_offset_high,
						null, // -> aux_mode (LWIR),              // QuadCLT              quadCLT_main,
						quadCLT_aux,                              // QuadCLT              quadCLT_aux,
						corr2d,                                   // Correlation2d        corr2d, // to access "other" layer
						clt_parameters.rig.ml_8bit,               // boolean              use8bpp, // true
						clt_parameters.rig.ml_limit_extrim,       // double               limit_extrim, 1E-5
						clt_parameters.rig.ml_keep_aux,           // boolean              keep_aux, false
						clt_parameters.rig.ml_keep_inter,         // boolean              keep_inter, // false
						clt_parameters.rig.ml_keep_hor_vert,      // boolean              keep_hor_vert, // true
						clt_parameters.rig.ml_keep_tbrl,          // boolean              ml_keep_tbrl,  // false
						clt_parameters.rig.ml_keep_debug,         // boolean              keep_debug,    // false
						clt_parameters.rig.ml_fatzero,            // double               ml_fatzero,    // 0.05
						clt_parameters.rig.ml_hwidth,             // int                  ml_hwidth,     // 4
						ml_data,                                  // double [][]          ml_data,       //false
						clt_parameters.rig.ml_show_ml,            // boolean              show,
						debugLevel);                              // int                  debugLevel
			}
		}
		Runtime.getRuntime().gc();
    	System.out.println("Generated ML data, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");
	}


3643 3644 3645
	public double [][] prepareRefineExistingDSI(
			QuadCLT            quadCLT_main,  // tiles should be set
			QuadCLT            quadCLT_aux,
3646 3647 3648
			CLTParameters       clt_parameters,
			ColorProcParameters                            colorProcParameters, //
			ColorProcParameters                            colorProcParameters_aux, //
3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel) //  throws Exception
	{
		final int refine_inter = 2; // 3; // 3 - dx, 2 - disparity
		final int tilesX = quadCLT_main.tp.getTilesX();
		//		  final int tilesY = quadCLT_main.tp.getTilesY();
		if ((quadCLT_main == null) || (quadCLT_aux == null)) {
			System.out.println("QuadCLT instances are not initilaized");
			return null;
		}
		// verify main camera has measured data
		// Measure with target disparity == 0
		if ((quadCLT_main.tp == null) || (quadCLT_main.tp.clt_3d_passes == null) || (quadCLT_main.tp.clt_3d_passes.size() ==0)){
			System.out.println("No DSI data for the main camera is available. Please run \"CLT 3D\" command");
			return null;
		}
		// See if auxiliary camera has images configured, if not - do it now.
		if (quadCLT_aux.image_name ==null) {
			boolean aux_OK = quadCLT_aux.setupImageData(
					quadCLT_main.image_name,                             // String image_name,
					quadCLT_main.correctionsParameters.getSourcePaths(), // String [] sourceFiles,
					clt_parameters,                                      // EyesisCorrectionParameters.CLTParameters       clt_parameters,
3672
					colorProcParameters,                                 //  ColorProcParameters                       colorProcParameters, //
3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707
					threadsMax,                                          // int threadsMax,
					debugLevel);                                         // int debugLevel);
			if (!aux_OK) {
				return null;
			}
		}
		// Re-measure background
		double [][] disparity_bimap_infinity = measureNewRigDisparity(
				quadCLT_main,      // QuadCLT             quadCLT_main,    // tiles should be set
				quadCLT_aux,       // QuadCLT             quadCLT_aux,
				null,              // double [][]         src_bimap,       // current state of measurements (or null for new measurement)
				0,                 // double              disparity,
				null,              // ArrayList<Integer>  tile_list,       // or null. If non-null - do not remeasure members of the list
				clt_parameters,    // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				false,             //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				0,                 // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				// first measurement - use as set in parameters
				clt_parameters.rig.no_int_x0,           // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,        // final int           threadsMax,      // maximal number of threads to launch
				updateStatus,      // final boolean       updateStatus,
				debugLevel);       // final int           debugLevel);


		int [] num_new = new int[1];
		boolean [] trusted_infinity = 	  getTrustedDisparity(
				quadCLT_main,                            // QuadCLT            quadCLT_main,  // tiles should be set
				quadCLT_aux,                             // QuadCLT            quadCLT_aux,
				true,                                    // boolean            use_individual,
				clt_parameters.rig.min_trusted_strength, // double             min_combo_strength,    // check correlation strength combined for all 3 correlations
				clt_parameters.grow_disp_trust,          // double             max_trusted_disparity, // 4.0 -> change to rig_trust
				clt_parameters.rig.trusted_tolerance,    // double             trusted_tolerance,
				null,                                    // boolean []         was_trusted,
				disparity_bimap_infinity );              // double [][]        bimap // current state of measurements

		if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){
3708
			(new ShowDoubleFloatArrays()).showArrays(
3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731
					disparity_bimap_infinity,
					tilesX,
					disparity_bimap_infinity[0].length/tilesX,
					true,
					quadCLT_main.image_name+"DISP_MAP-INFINITY",
					ImageDtt.BIDISPARITY_TITLES);

		}
		double [][] prev_bimap = null;
		double [] scale_bad = new double [trusted_infinity.length];
		for (int i = 0; i < scale_bad.length; i++) scale_bad[i] = 1.0;
		for (int nref = 0; nref < clt_parameters.rig.num_inf_refine; nref++) {
			// refine infinity using inter correlation
			double refine_tolerance = (nref > 0)?clt_parameters.rig.refine_tolerance:0.0;
			// only for infinity to prevent remaining 0.0?
			double [][] disparity_bimap_new =  refineRigSel(
					quadCLT_main,    // QuadCLT                        quadCLT_main,    // tiles should be set
					quadCLT_aux,     // QuadCLT                        quadCLT_aux,
					disparity_bimap_infinity, // double [][]                    src_bimap,       // current state of measurements (or null for new measurement)
					prev_bimap,      // double [][]                    prev_bimap, // previous state of measurements or null
					scale_bad,       // double []                      scale_bad,
					refine_inter,    // int                            refine_mode,     // 0 - by main, 1 - by aux, 2 - by inter
					false,           // boolean                        keep_inf,        // keep expected disparity 0.0 if it was so
3732
					0.0,             // double                                         inf_disparity,
3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783
					0.0, // clt_parameters.rig.refine_min_strength , // double refine_min_strength, // do not refine weaker tiles
					refine_tolerance ,    // double refine_tolerance,    // do not refine if absolute disparity below
					trusted_infinity, // tile_list,       // ArrayList<Integer>             tile_list,       // or null
					num_new,         // int     []                                     num_new,
					clt_parameters,  // EyesisCorrectionParameters.CLTParameters clt_parameters,
					false,             //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
					0,                 // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
					// refine - no window offset
					true,           // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
					threadsMax,      // final int                      threadsMax,      // maximal number of threads to launch
					updateStatus,    // final boolean                  updateStatus,
					debugLevel);     // final int                      debugLevel);
			prev_bimap = disparity_bimap_infinity;
			disparity_bimap_infinity = disparity_bimap_new;
			trusted_infinity = 	  getTrustedDisparity(
					quadCLT_main,                             // QuadCLT            quadCLT_main,  // tiles should be set
					quadCLT_aux,                              // QuadCLT            quadCLT_aux,
					true,                                     // boolean            use_individual,
					clt_parameters.rig.min_trusted_strength,  // double             min_combo_strength,    // check correlation strength combined for all 3 correlations
					clt_parameters.grow_disp_trust,           // double             max_trusted_disparity, // 4.0 -> change to rig_trust
					clt_parameters.rig.trusted_tolerance,     // double             trusted_tolerance,
					trusted_infinity, // null,                // boolean []         was_trusted,
					disparity_bimap_infinity );               // double [][]        bimap // current state of measurements
			if (debugLevel > -2) {
				System.out.println("enhanceByRig(): refined (infinity) "+num_new[0]+" tiles");
			}

			if (num_new[0] < clt_parameters.rig.min_new) break;
		}



		if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){

			for (int layer = 0; layer < disparity_bimap_infinity.length; layer ++) if (disparity_bimap_infinity[layer] != null){
				for (int nTile = 0; nTile < disparity_bimap_infinity[layer].length; nTile++) {
					if (!trusted_infinity[nTile]) disparity_bimap_infinity[layer][nTile] = Double.NaN;
				}
			}
			if (scale_bad!= null) {
				int num_bad = 0, num_trusted = 0;
				for (int nTile = 0; nTile < scale_bad.length; nTile++) {
					if (!trusted_infinity[nTile]) scale_bad[nTile] = Double.NaN;
					else {
						if (scale_bad[nTile] < 1.0) num_bad++;
						scale_bad[nTile] =  -scale_bad[nTile];
						num_trusted ++;

					}
				}
				System.out.println("num_trusted = "+num_trusted+", num_bad = "+num_bad);
3784
				(new ShowDoubleFloatArrays()).showArrays(
3785 3786 3787 3788 3789 3790
						scale_bad,
						tilesX,
						disparity_bimap_infinity[0].length/tilesX,
						quadCLT_main.image_name+"-INFINITY-SCALE_BAD"+clt_parameters.disparity);

			}
3791
			(new ShowDoubleFloatArrays()).showArrays(
3792 3793 3794 3795 3796 3797 3798 3799 3800 3801
					disparity_bimap_infinity,
					tilesX,
					disparity_bimap_infinity[0].length/tilesX,
					true,
					quadCLT_main.image_name+"-INFINITY-REFINED-TRUSTED"+clt_parameters.disparity,
					ImageDtt.BIDISPARITY_TITLES);
		}

		// Get DSI from the main camera
		quadCLT_main.tp.trimCLTPasses(false); // remove rig composite scan if any
3802
		// last but not including any rig data
3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823
		CLTPass3d scan_last = quadCLT_main.tp.clt_3d_passes.get( quadCLT_main.tp.clt_3d_passes_size -1); // get last one
		double [][] disparity_bimap = setBimapFromCLTPass3d(
				scan_last,      // CLTPass3d                                scan,
				quadCLT_main,   // QuadCLT                                  quadCLT_main,  // tiles should be set
				quadCLT_aux,    // QuadCLT                                  quadCLT_aux,
				clt_parameters, // EyesisCorrectionParameters.CLTParameters clt_parameters,
				threadsMax,     // final int        threadsMax,  // maximal number of threads to launch
				updateStatus,   // final boolean    updateStatus,
				debugLevel);    // final int        debugLevel);

		//		  int [] num_new = new int[1];
		boolean [] trusted_near = 	  getTrustedDisparity(
				quadCLT_main,                                      // QuadCLT            quadCLT_main,  // tiles should be set
				quadCLT_aux,                                       // QuadCLT            quadCLT_aux,
				true,                                              // boolean            use_individual,
				0.5*clt_parameters.rig.min_trusted_strength,       // double             min_combo_strength,    // check correlation strength combined for all 3 correlations
				clt_parameters.grow_disp_trust,                    // double             max_trusted_disparity, // 4.0 -> change to rig_trust
				clt_parameters.rig.trusted_tolerance,              // double             trusted_tolerance,
				null,                                              // boolean []         was_trusted,
				disparity_bimap); // double [][]        bimap // current state of measurements
		if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){
3824
			(new ShowDoubleFloatArrays()).showArrays(
3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845
					disparity_bimap,
					tilesX,
					disparity_bimap[0].length/tilesX,
					true,
					quadCLT_main.image_name+"DISP_MAP-NONINFINITY",
					ImageDtt.BIDISPARITY_TITLES);

		}

		for (int i = 0; i < scale_bad.length; i++) scale_bad[i] = 1.0;
		prev_bimap = null;
		for (int nref = 0; nref < clt_parameters.rig.num_near_refine; nref++) {
			// refine infinity using inter correlation
			double [][] disparity_bimap_new =  refineRigSel(
					quadCLT_main,    // QuadCLT                        quadCLT_main,    // tiles should be set
					quadCLT_aux,     // QuadCLT                        quadCLT_aux,
					disparity_bimap, // double [][]                    src_bimap,       // current state of measurements (or null for new measurement)
					prev_bimap,      // double [][]                    prev_bimap, // previous state of measurements or null
					scale_bad,       // double []                      scale_bad,
					refine_inter,    // int                            refine_mode,     // 0 - by main, 1 - by aux, 2 - by inter
					false,           // boolean                        keep_inf,        // keep expected disparity 0.0 if it was so
3846
					0.0,             // double                                         inf_disparity,
3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894
					0.0, // clt_parameters.rig.refine_min_strength , // double refine_min_strength, // do not refine weaker tiles
					clt_parameters.rig.refine_tolerance ,    // double refine_tolerance,    // do not refine if absolute disparity below
					trusted_near,    // tile_list,       // ArrayList<Integer>             tile_list,       // or null
					num_new,         // int     []                                     num_new,
					clt_parameters,  // EyesisCorrectionParameters.CLTParameters clt_parameters,
					false,           //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
					0,                 // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
					// refine - no window offset
					true,           // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
					threadsMax,      // final int                      threadsMax,      // maximal number of threads to launch
					updateStatus,    // final boolean                  updateStatus,
					debugLevel);     // final int                      debugLevel);
			prev_bimap = disparity_bimap;
			disparity_bimap = disparity_bimap_new;
			trusted_near = 	  getTrustedDisparity(
					quadCLT_main,                            // QuadCLT            quadCLT_main,  // tiles should be set
					quadCLT_aux,                             // QuadCLT            quadCLT_aux,
					true,                                     // boolean            use_individual,
					clt_parameters.rig.min_trusted_strength, // double             min_combo_strength,    // check correlation strength combined for all 3 correlations
					clt_parameters.grow_disp_trust,          // double             max_trusted_disparity, // 4.0 -> change to rig_trust
					clt_parameters.rig.trusted_tolerance,    // double             trusted_tolerance,
					trusted_near, // null,                   // boolean []         was_trusted,
					disparity_bimap );                       // double [][]        bimap // current state of measurements
			if (debugLevel > -2) {
				System.out.println("enhanceByRig(): refined (near) "+num_new[0]+" tiles");
			}
			if (num_new[0] < clt_parameters.rig.min_new) break;
		}

		if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){

			for (int layer = 0; layer < disparity_bimap.length; layer ++) if (disparity_bimap[layer] != null){
				for (int nTile = 0; nTile < disparity_bimap[layer].length; nTile++) {
					if (!trusted_near[nTile]) disparity_bimap[layer][nTile] = Double.NaN;
				}
			}
			if (scale_bad!= null) {
				int num_bad = 0, num_trusted = 0;
				for (int nTile = 0; nTile < scale_bad.length; nTile++) {
					if (!trusted_near[nTile]) scale_bad[nTile] = Double.NaN;
					else {
						if (scale_bad[nTile] < 1.0) num_bad++;
						scale_bad[nTile] =  -scale_bad[nTile];
						num_trusted ++;

					}
				}
				System.out.println("num_trusted = "+num_trusted+", num_bad = "+num_bad);
3895
				(new ShowDoubleFloatArrays()).showArrays(
3896 3897 3898 3899 3900 3901
						scale_bad,
						tilesX,
						disparity_bimap[0].length/tilesX,
						quadCLT_main.image_name+"-NEAR-SCALE_BAD"+clt_parameters.disparity);

			}
3902
			(new ShowDoubleFloatArrays()).showArrays(
3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921
					disparity_bimap,
					tilesX,
					disparity_bimap[0].length/tilesX,
					true,
					quadCLT_main.image_name+"-NEAR-REFINED-TRUSTED"+clt_parameters.disparity,
					ImageDtt.BIDISPARITY_TITLES);
		}
		// Combine infinity and non-infinity
		for (int nTile = 0; nTile < disparity_bimap[0].length; nTile++) {
			if (trusted_infinity[nTile] &&
					(!trusted_near[nTile] ||
							(disparity_bimap_infinity[ImageDtt.BI_STR_ALL_INDEX][nTile] > disparity_bimap[ImageDtt.BI_STR_ALL_INDEX][nTile]))) {
				for (int i = 0; i < disparity_bimap.length; i++) if (disparity_bimap_infinity[i]!=null) {
					disparity_bimap[i][nTile] = disparity_bimap_infinity[i][nTile];
				}
				trusted_near[nTile] = true;
			}
		}

3922
		if (clt_parameters.show_map &&  (debugLevel > -3) && clt_parameters.rig.rig_mode_debug && !clt_parameters.batch_run){
3923
			(new ShowDoubleFloatArrays()).showArrays(
3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939
					disparity_bimap,
					tilesX,
					disparity_bimap[0].length/tilesX,
					true,
					quadCLT_main.image_name+"DSI_ALL",
					ImageDtt.BIDISPARITY_TITLES);
			for (int layer = 0; layer < disparity_bimap.length; layer ++) if (disparity_bimap[layer] != null){
				for (int nTile = 0; nTile < disparity_bimap[layer].length; nTile++) {
					if (!trusted_near[nTile]) disparity_bimap[layer][nTile] = Double.NaN;
				}
			}
			for (int layer:ImageDtt.BIDISPARITY_STRENGTHS) if (disparity_bimap[layer] != null){
				for (int nTile = 0; nTile < disparity_bimap[layer].length; nTile++) {
					if (!trusted_near[nTile]) disparity_bimap[layer][nTile] = 0.0;
				}
			}
3940
			(new ShowDoubleFloatArrays()).showArrays(
3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
					disparity_bimap,
					tilesX,
					disparity_bimap[0].length/tilesX,
					true,
					quadCLT_main.image_name+"-DSI-ALL-TRUSTED",
					ImageDtt.BIDISPARITY_TITLES);
		}

		// just testing - copy and run in pole detection mode (TODO: Remove)
		if (debugLevel > -100) return disparity_bimap;

		// need to re-measure
		double [][] disparity_bimap_poles =  measureNewRigDisparity(
				quadCLT_main,    // QuadCLT                        quadCLT_main,    // tiles should be set
				quadCLT_aux,     // QuadCLT                        quadCLT_aux,
				disparity_bimap[ImageDtt.BI_TARGET_INDEX], // double []                                      disparity, // Double.NaN - skip, ohers - measure
				clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				true, // boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				0,                 // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				// any - in notch mode it is disabled
				clt_parameters.rig.no_int_x0,           // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,      // final int                      threadsMax,      // maximal number of threads to launch
				updateStatus,    // final boolean                  updateStatus,
				debugLevel); // +4);     // final int                      debugLevel);

3966
		(new ShowDoubleFloatArrays()).showArrays(
3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985
				disparity_bimap_poles,
				tilesX,
				disparity_bimap[0].length/tilesX,
				true,
				quadCLT_main.image_name+"-INITIAL-POLES",
				ImageDtt.BIDISPARITY_TITLES);

		for (int i = 0; i < scale_bad.length; i++) scale_bad[i] = 1.0;
		prev_bimap = null;
		for (int nref = 0; nref < clt_parameters.rig.num_near_refine; nref++) {
			// refine infinity using inter correlation
			double [][] disparity_bimap_new =  refineRigSel(
					quadCLT_main,    // QuadCLT                        quadCLT_main,    // tiles should be set
					quadCLT_aux,     // QuadCLT                        quadCLT_aux,
					disparity_bimap_poles, // double [][]                    src_bimap,       // current state of measurements (or null for new measurement)
					prev_bimap,      // double [][]                    prev_bimap, // previous state of measurements or null
					scale_bad,       // double []                      scale_bad,
					refine_inter,    // int                            refine_mode,     // 0 - by main, 1 - by aux, 2 - by inter
					false,           // boolean                        keep_inf,        // keep expected disparity 0.0 if it was so
3986
					0.0,             // double                                         inf_disparity,
3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028
					0.0, // clt_parameters.rig.refine_min_strength , // double refine_min_strength, // do not refine weaker tiles
					clt_parameters.rig.refine_tolerance ,    // double refine_tolerance,    // do not refine if absolute disparity below
					trusted_near,    // tile_list,       // ArrayList<Integer>             tile_list,       // or null
					num_new,         // int     []                                     num_new,
					clt_parameters,  // EyesisCorrectionParameters.CLTParameters clt_parameters,
					true,            //  final boolean                  notch_mode,      // use notch filter for inter-camera correlation to detect poles
					0,               // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
					true,            // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
					threadsMax,      // final int                      threadsMax,      // maximal number of threads to launch
					updateStatus,    // final boolean                  updateStatus,
					debugLevel);     // final int                      debugLevel);
			prev_bimap = disparity_bimap_poles;
			disparity_bimap_poles = disparity_bimap_new;
			trusted_near = 	  getTrustedDisparity(
					quadCLT_main,                            // QuadCLT            quadCLT_main,  // tiles should be set
					quadCLT_aux,                             // QuadCLT            quadCLT_aux,
					true,                                    // boolean            use_individual,
					clt_parameters.rig.min_trusted_strength, // double             min_combo_strength,    // check correlation strength combined for all 3 correlations
					clt_parameters.grow_disp_trust,          // double             max_trusted_disparity, // 4.0 -> change to rig_trust
					clt_parameters.rig.trusted_tolerance,    // double             trusted_tolerance,
					trusted_near, // null,                   // boolean []         was_trusted,
					disparity_bimap_poles );                       // double [][]        bimap // current state of measurements
			if (debugLevel > -2) {
				System.out.println("enhanceByRig(): refined (poles) "+num_new[0]+" tiles");
			}
			if (num_new[0] < clt_parameters.rig.min_new) break;
		}

		if (clt_parameters.show_map &&  (debugLevel > -2) && clt_parameters.rig.rig_mode_debug){

			if (scale_bad!= null) {
				int num_bad = 0, num_trusted = 0;
				for (int nTile = 0; nTile < scale_bad.length; nTile++) {
					if (!trusted_near[nTile]) scale_bad[nTile] = Double.NaN;
					else {
						if (scale_bad[nTile] < 1.0) num_bad++;
						scale_bad[nTile] =  -scale_bad[nTile];
						num_trusted ++;

					}
				}
				System.out.println("num_trusted = "+num_trusted+", num_bad = "+num_bad);
4029
				(new ShowDoubleFloatArrays()).showArrays(
4030 4031 4032 4033 4034 4035
						scale_bad,
						tilesX,
						disparity_bimap_poles[0].length/tilesX,
						quadCLT_main.image_name+"-NEAR-SCALE_BAD_POLES"+clt_parameters.disparity);

			}
4036
			(new ShowDoubleFloatArrays()).showArrays(
4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051
					disparity_bimap_poles,
					tilesX,
					disparity_bimap_poles[0].length/tilesX,
					true,
					quadCLT_main.image_name+"-POLES-REFINED-TRUSTED",
					ImageDtt.BIDISPARITY_TITLES);
		}
		// END OF just testing - copy and run in pole detection mode (TODO: Remove)
		return disparity_bimap;

	}

	public BiScan rigInitialScan(
			QuadCLT            quadCLT_main,  // tiles should be set
			QuadCLT            quadCLT_aux,
4052 4053 4054
			CLTParameters       clt_parameters,
			ColorProcParameters                            colorProcParameters, //
			ColorProcParameters                            colorProcParameters_aux, //
4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel) //  throws Exception
	{
		if (getBiScan(0) != null) {
			return getBiScan(0);
		};

		final int tilesX = quadCLT_main.tp.getTilesX();
		final int tilesY = quadCLT_main.tp.getTilesY();
		BiCamDSI biCamDSI = new BiCamDSI( tilesX, tilesY,threadsMax);
		System.out.println("rigInitialScan()");
		double [][] disparity_bimap = prepareRefineExistingDSI(
				quadCLT_main,  // QuadCLT            quadCLT_main,  // tiles should be set
				quadCLT_aux,   // QuadCLT            quadCLT_aux,
				clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
4071 4072
				colorProcParameters,          //  ColorProcParameters                       colorProcParameters, //
				colorProcParameters_aux,          //  ColorProcParameters                       colorProcParameters, //
4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117
				threadsMax,        // final int           threadsMax,      // maximal number of threads to launch
				updateStatus,      // final boolean       updateStatus,
				debugLevel);       // final int           debugLevel);
		if (disparity_bimap == null) {
			String msg = "Failed to get (and refine) initial rig DSI from the existing data";
			System.out.println(msg);
			IJ.showMessage("ERROR",msg);
			return null;
		}

		biCamDSI.addBiScan(disparity_bimap, BiScan.BISCAN_SINGLECORR);
		biCamDSI.getBiScan(0).calcTrusted(   // finds strong trusted and validates week ones if they fit planes
				clt_parameters.rig.pf_trusted_strength, // final double     trusted_strength, // trusted correlation strength
				clt_parameters.rig.pf_strength_rfloor,  // final double     strength_rfloor,   // strength floor - relative to trusted
				clt_parameters.rig.pf_cond_rtrusted,    // final double     cond_rtrusted,     // minimal strength to consider - fraction of trusted
				clt_parameters.rig.pf_strength_pow,     // final double     strength_pow,      // raise strength-floor to this power
				clt_parameters.rig.pf_smpl_radius,      // final int        smpl_radius,
				clt_parameters.rig.pf_smpl_num,         // final int        smpl_num,   //         = 3;      // Number after removing worst (should be >1)
				clt_parameters.rig.pf_smpl_fract,       // final double     smpl_fract, // Number of friends among all neighbors
				clt_parameters.rig.pf_max_adiff,        // final double     max_adiff,  // Maximal absolute difference betweenthe center tile and friends
				clt_parameters.rig.pf_max_rdiff,        // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
				clt_parameters.rig.pf_max_atilt,        // final double     max_atilt, //  = 2.0; // pix per tile
				clt_parameters.rig.pf_max_rtilt,        // final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
				clt_parameters.rig.pf_smpl_arms,        // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
				clt_parameters.rig.pf_smpl_rrms,        // final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
				clt_parameters.rig.pf_damp_tilt,        // final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
				clt_parameters.rig.pf_rwsigma,          // 						final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma
				clt_parameters.tileX,                   // final int        dbg_x,
				clt_parameters.tileY,                   // final int        dbg_y,
				debugLevel);                            // final int        debugLevel);


		if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){
			biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR).showScan(
					quadCLT_main.image_name+"-BISCAN_initial");
		}
		biCamDSI_persistent = biCamDSI;
		return getBiScan(0);
	}



	public double [][] groundTruthByRigPlanes(
			QuadCLT            quadCLT_main,  // tiles should be set
			QuadCLT            quadCLT_aux,
4118 4119 4120
			CLTParameters       clt_parameters,
			ColorProcParameters                            colorProcParameters, //
			ColorProcParameters                            colorProcParameters_aux, //
4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel) //  throws Exception
	{
		if (getBiScan(0) != null) {
			if (getBiScan(1) != null) {
				System.out.println("Expected just a single BiScan here, got "+(biCamDSI_persistent.biScans.size())+". Trimming");
				while (biCamDSI_persistent.biScans.size()>1) {
					biCamDSI_persistent.biScans.remove(1);
				}
				Runtime.getRuntime().gc();
				System.out.println("--- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");


			}
		} else { // create a new one
			if (rigInitialScan(				quadCLT_main,  // QuadCLT            quadCLT_main,  // tiles should be set
					quadCLT_aux,   // QuadCLT            quadCLT_aux,
					clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
4140 4141 4142
					colorProcParameters,          //  ColorProcParameters                       colorProcParameters, //
					colorProcParameters_aux,          //  ColorProcParameters                       colorProcParameters, //

4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232
					threadsMax,        // final int           threadsMax,      // maximal number of threads to launch
					updateStatus,      // final boolean       updateStatus,
					debugLevel)== null)       // final int           debugLevel);
			{
				return null; // Failed to get
			}
		}

		final int num_tries_strongest_by_fittest = 5;
		final int num_full_cycles =       clt_parameters.rig.pf_en_trim_fg? 3 : 1;  // Number of full low-texture cycles that include growing flat LT and trimmin weak FG over BG
		//		  final int num_cross_gaps_cycles = 12+ (num_simple_expand_cysles * dxy.length); // maximal number of adding new tiles cycles while "crossing the gaps)
		final int min_cross_gaps_new =    20; // minimal number of the new added tiles
		final int refine_inter = 2; // 3; // 3 - dx, 2 - disparity
		final int tilesX = quadCLT_main.tp.getTilesX();
		final int tilesY = quadCLT_main.tp.getTilesY();


		/*
		BiCamDSI biCamDSI = new BiCamDSI( tilesX, tilesY,threadsMax);
		System.out.println("groundTruthByRigPlanes()");


		double [][] disparity_bimap = prepareRefineExistingDSI(
				quadCLT_main,  // QuadCLT            quadCLT_main,  // tiles should be set
				quadCLT_aux,   // QuadCLT            quadCLT_aux,
				clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				threadsMax,        // final int           threadsMax,      // maximal number of threads to launch
				updateStatus,      // final boolean       updateStatus,
				debugLevel);       // final int           debugLevel);
		if (disparity_bimap == null) {
			String msg = "Failed to get (and refine) initial rig DSI from the existing data";
			System.out.println(msg);
			IJ.showMessage("ERROR",msg);
			return null;
		}

		biCamDSI.addBiScan(disparity_bimap, BiScan.BISCAN_SINGLECORR);
		if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){
			biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR).showScan(
					quadCLT_main.image_name+"-BISCAN_initial");
		}
 		*/
		BiCamDSI biCamDSI = biCamDSI_persistent;



		int [][] dxy = {{0, -1},{0,1},{-1,0},{1,0}};
		int num_simple_expand_cysles = 8;
		final int num_cross_gaps_cycles = 12 + (num_simple_expand_cysles * dxy.length); // maximal number of adding new tiles cycles while "crossing the gaps)
		for (int num_fcycle = 0; num_fcycle < num_full_cycles; num_fcycle++) {
			// Grow tiles, cross gaps (do not trim yet
			//
			int [] num_simple_added = new int[dxy.length];
			for (int i = 0; i < num_simple_added.length; i++) {
				num_simple_added[i] = -1;
			}
			for (int num_cycle = 0; num_cycle < num_cross_gaps_cycles; num_cycle++) {
				BiScan last_scan = biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR);
				if (clt_parameters.rig.lonefg_disp_incr > 0.0) {
					int removed_lone = last_scan.trimWeakLoneFG(
							clt_parameters.rig.pf_trusted_strength, // final double    trusted_strength, // trusted correlation strength
							clt_parameters.rig.lonefg_rstrength,  // final double     min_rstrength,   // strength floor - relative to trusted
							clt_parameters.rig.lonefg_disp_incr ,//final double     max_disp_inc,
							clt_parameters.tileX,                   // final int        dbg_x,
							clt_parameters.tileY,                   // final int        dbg_y,
							debugLevel+2);                            // final int        debugLevel);
					System.out.println("trimWeakLoneFG() -> "+removed_lone);
				}
				int [] trusted_stats = last_scan.calcTrusted(   // finds strong trusted and validates week ones if they fit planes
						clt_parameters.rig.pf_trusted_strength, // final double     trusted_strength, // trusted correlation strength
						clt_parameters.rig.pf_strength_rfloor,  // final double     strength_rfloor,   // strength floor - relative to trusted
						clt_parameters.rig.pf_cond_rtrusted,    // final double     cond_rtrusted,     // minimal strength to consider - fraction of trusted
						clt_parameters.rig.pf_strength_pow,     // final double     strength_pow,      // raise strength-floor to this power
						clt_parameters.rig.pf_smpl_radius,      // final int        smpl_radius,
						clt_parameters.rig.pf_smpl_num,         // final int        smpl_num,   //         = 3;      // Number after removing worst (should be >1)
						clt_parameters.rig.pf_smpl_fract,       // final double     smpl_fract, // Number of friends among all neighbors
						clt_parameters.rig.pf_max_adiff,        // final double     max_adiff,  // Maximal absolute difference betweenthe center tile and friends
						clt_parameters.rig.pf_max_rdiff,        // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
						clt_parameters.rig.pf_max_atilt,        // final double     max_atilt, //  = 2.0; // pix per tile
						clt_parameters.rig.pf_max_rtilt,        // final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
						clt_parameters.rig.pf_smpl_arms,        // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
						clt_parameters.rig.pf_smpl_rrms,        // final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
						clt_parameters.rig.pf_damp_tilt,        // final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
						clt_parameters.rig.pf_rwsigma,          // 						final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma
						clt_parameters.tileX,                   // final int        dbg_x,
						clt_parameters.tileY,                   // final int        dbg_y,
						debugLevel);                            // final int        debugLevel);
				if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){
					biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR).showScan(
							quadCLT_main.image_name+"-BISCAN_TRUSTED"+num_fcycle+"-"+num_cycle);
4233
				}
4234

4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259
				/*
				 * @return array of 3 numbers: number of trusted strong tiles, number of additional trusted by plane fitting, and number of all
				 * somewhat strong tiles
				 */
				if (debugLevel > -4) {
					System.out.println("groundTruthByRigPlanes() grow pass "+num_cycle+" of "+ num_cross_gaps_cycles+
							" strong trusted: "+trusted_stats[0]+ " neib trusted: "+trusted_stats[1]+" weak trusted: " + trusted_stats[2]);
				}
				int num_added_tiles =0;
				if ((num_cycle < num_simple_expand_cysles * dxy.length) && (num_cycle >= dxy.length)) {
					boolean all_last_zeros = true;
					for (int i =0 ; i <=dxy.length; i++) {
						if (num_simple_added[(num_cycle-1-i) % dxy.length] != 0) {
							all_last_zeros = false;
							break;
						}
					}
					if (all_last_zeros) {
						if (debugLevel > -4) {
							System.out.println("==== groundTruthByRigPlanes() grow pass "+num_cycle+" of "+ num_cross_gaps_cycles+
									" all "+(num_simple_added.length)+" direction expansions added 0 tiles, proceeding to low texture expansion ====");
						}
						num_cycle = num_simple_expand_cysles * dxy.length;
					}
				}
4260

4261 4262 4263 4264 4265 4266 4267 4268 4269 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 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336
				if (num_cycle < num_simple_expand_cysles * dxy.length) {
					// simple duplicating one step in 4 directions
					num_added_tiles = last_scan.suggestNewScan(
							dxy[num_cycle % dxy.length], // final int []     dxy,               //up,down,right,left
							clt_parameters.rig.pf_discard_cond,     // final boolean    discard_cond,      // consider conditionally trusted tiles (not promoted to trusted) as empty
							clt_parameters.rig.pf_discard_weak,     // final boolean    discard_weak,      // consider conditionally trusted tiles (not promoted to trusted) as empty
							clt_parameters.rig.pf_discard_strong,   // final boolean    discard_strong,      // consider conditionally trusted tiles (not promoted to trusted) as empty
							clt_parameters.rig.pf_new_diff,         // final double     new_diff,            // minimal difference between the new suggested and the already tried/measured one
							true,                                   // final boolean    remove_all_tried,  // remove from suggested - not only disabled, but all tried
							clt_parameters.tileX,                   // final int        dbg_x,
							clt_parameters.tileY,                   // final int        dbg_y,
							debugLevel);                            // final int        debugLevel);
					//TODO: add expanding FG over existing BG. Use "Strong enough" for FG to beat BG. Maybe expand by multiple steps?
					num_simple_added[num_cycle % dxy.length] = num_added_tiles;
				} else {

					// suggest new disparities, using plane surfaces (extending around that may cause false surfaces)
					/*
					 * Suggest disparities to try for the tiles in poorly textured areas by fitting planes in DSI
					 * calcTrusted should be called before to set up trusted/cond_trusted tiles
					 * suggested tiles will be compared against and made sure they differ by more than a specified margin
					 * 1) current measured (refined) disparity value
					 * 2) target disparity that lead to the current measurement after refinement
					 * 3) any other disable measurement
					 * 4) any target disparity that lead to the disabled measurement
					 * @return number of new tiles to measure in the  array of suggested disparities - Double.NaN - nothing suggested
					 *  for the tile. May need additional filtering to avoid suggested already tried disparities
					 */

					num_added_tiles = last_scan.suggestNewScan(
							null,                                   // final boolean [] area_of_interest,
							null,                                   // final double [][] disparityStrength,
							clt_parameters.rig.pf_trusted_strength, // final double     trusted_strength, // trusted correlation strength
							clt_parameters.rig.pf_strength_rfloor,  // final double     strength_rfloor,   // strength floor - relative to trusted
							clt_parameters.rig.pf_discard_cond,     // final boolean    discard_cond,      // consider conditionally trusted tiles (not promoted to trusted) as empty
							clt_parameters.rig.pf_discard_weak,     // final boolean    discard_weak,      // consider conditionally trusted tiles (not promoted to trusted) as empty
							clt_parameters.rig.pf_discard_strong,   // final boolean    discard_strong,      // consider conditionally trusted tiles (not promoted to trusted) as empty
							clt_parameters.rig.pf_strength_pow,     // final double     strength_pow,      // raise strength-floor to this power
							clt_parameters.rig.pf_smpl_radius,      // final int        smpl_radius,
							clt_parameters.rig.pf_smpl_num,         // final int        smpl_num,   //         = 3;      // Number after removing worst (should be >1)
							clt_parameters.rig.pf_smpl_fract,       // final double     smpl_fract, // Number of friends among all neighbors
							clt_parameters.rig.pf_smpl_num_narrow,  // final int        smpl_num_narrow,   //         = 3;      // Number after removing worst (should be >1)
							clt_parameters.rig.pf_max_adiff,        // final double     max_adiff,  // Maximal absolute difference betweenthe center tile and friends
							clt_parameters.rig.pf_max_rdiff,        // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
							clt_parameters.rig.pf_max_atilt,        // final double     max_atilt, //  = 2.0; // pix per tile
							clt_parameters.rig.pf_max_rtilt,        // final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
							clt_parameters.rig.pf_smpl_arms,        // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
							clt_parameters.rig.pf_smpl_rrms,        // final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
							clt_parameters.rig.pf_damp_tilt,        // final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
							clt_parameters.rig.pf_rwsigma,          // final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma
							clt_parameters.rig.pf_rwsigma_narrow,   // final double     rwsigma_narrow,    //  = used to determine initial tilt
							clt_parameters.rig.pf_new_diff,         // final double     new_diff,            // minimal difference between the new suggested and the already tried/measured one
							true,                                   // final boolean    remove_all_tried,  // remove from suggested - not only disabled, but all tried
							0.0,                                    // final double     center_weight,     // use center tile too (0.0 - do not use)
							clt_parameters.rig.pf_use_alt,          // final boolean    use_alt,           // use tiles from other scans if they fit better
							clt_parameters.rig.pf_goal_fraction_rms,// final double     goal_fraction_rms, // Try to make rms to be this fraction of maximal acceptable by removing outliers
							clt_parameters.rig.pf_boost_low_density,// NOT USED HERE, MAY BE 0,                                    // final double     boost_low_density, // 0 - strength is proportional to 1/density, 1.0 - same as remaining tiles
							null,                                   // final double []  smooth_strength,   // optionally fill strength array when used for smoothing DSI
							0,                                      // final int        fourq_min,         // each of the 4 corners should have at least this number of tiles.
							0,                                      // final int        fourq_gap,         // symmetrical vertical and horizontal center areas that do not belong to any corner
							clt_parameters.tileX,                   // final int        dbg_x,
							clt_parameters.tileY,                   // final int        dbg_y,
							debugLevel);                            // final int        debugLevel);
				}
				if (debugLevel > -4) {
					System.out.println("groundTruthByRigPlanes() full cycle = "+num_fcycle+", grow pass "+num_cycle+" of "+ num_cross_gaps_cycles+
							" suggestNewScan() -> "+num_added_tiles);
				}
				//num_cycle < num_cross_gaps_cycles;
				//				  boolean last_cycle = (num_added_tiles < min_cross_gaps_new) || (num_cycle >= (num_cross_gaps_cycles-1));
				boolean last_cycle = ((num_added_tiles < min_cross_gaps_new) && (num_cycle >= num_simple_expand_cysles * dxy.length)) || (num_cycle >= (num_cross_gaps_cycles-1));
				if (clt_parameters.show_map &&  (debugLevel > -2) && clt_parameters.rig.rig_mode_debug){
					if (last_cycle) //  || (num_cycle < 2 * dxy.length))
						biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR).showScan(
								quadCLT_main.image_name+"-BISCAN_SUGGESTED"+num_fcycle+"-"+num_cycle);
				}
4337

4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 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 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468
				if (last_cycle && clt_parameters.rig.pf_en_trim_fg) { // last cycle and trimming enabled
					if (debugLevel > -4) {
						//						  System.out.println("groundTruthByRigPlanes(): num_added_tiles= "+num_added_tiles+" > "+min_cross_gaps_new+", done growing over gaps");
						System.out.println("groundTruthByRigPlanes(): that was the last growing over gaps cycle, performing trimming hanging weak FG over BG");
					}

					/*
					 * Disable low-textured tiles are not between strong tiles, but on one side of it.
					 * This method relies on the assumption that FG edge should have strong correlation, so it tries multiple directions
					 * from the weak (not trusted strong) tiles and trims tiles that either do not have anything in that direction or have
					 * farther tiles.
					 * Trimming(disabling) weak (trusted but not strong_trusted) tiles if on any one side:
					 *   a) there are no same plane or closer tiles
					 *   b) there are no in-plane or closer strong tiles, but there are some (strong or any?) farther tiles
					 * repeat while more are trimmed
					 * maybe, if there are both strong in-plane and far - see which are closer
					 */
					int num_trimmed = last_scan.trimWeakFG(
							clt_parameters.rig.pf_trusted_strength, // final double     trusted_strength, // trusted correlation strength
							clt_parameters.rig.pf_strength_rfloor,  // final double     strength_rfloor,   // strength floor - relative to trusted
							clt_parameters.rig.pf_cond_rtrusted,    // final double     cond_rtrusted,     // minimal strength to consider - fraction of trusted
							clt_parameters.rig.pf_strength_pow,     // final double     strength_pow,      // raise strength-floor to this power
							clt_parameters.rig.pf_smpl_radius,      // final int        smpl_radius,
							clt_parameters.rig.pf_smpl_num,         // final int        smpl_num,   //         = 3;      // Number after removing worst (should be >1)
							clt_parameters.rig.pf_smpl_fract,       // final double     smpl_fract, // Number of friends among all neighbors
							clt_parameters.rig.pf_max_adiff,        // final double     max_adiff,  // Maximal absolute difference betweenthe center tile and friends
							clt_parameters.rig.pf_max_rdiff,        // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
							clt_parameters.rig.pf_max_atilt,        // final double     max_atilt, //  = 2.0; // pix per tile
							clt_parameters.rig.pf_max_rtilt,        // final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
							clt_parameters.rig.pf_smpl_arms,        // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
							clt_parameters.rig.pf_smpl_rrms,        // final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
							clt_parameters.rig.pf_damp_tilt,        // final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
							clt_parameters.rig.pf_rwsigma,          // final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma

							clt_parameters.rig.pf_atolerance,       // final double     atolerance,  // When deciding closer/farther
							clt_parameters.rig.pf_rtolerance,       // final double     rtolerance,  // same, scaled with disparity
							clt_parameters.rig.pf_num_dirs,         // final int        num_dirs,    // number of directions to try
							clt_parameters.rig.pf_blind_dist,       // final double     blind_dist,  // analyze only tiles farther than this in the selected direction
							clt_parameters.rig.pf_strong_only_far,  // final boolean    strong_only_far, // in variant b) only compare with strong far
							clt_parameters.rig.pf_num_strong_far,   // final int        num_strong_far,    // number of directions to try
							clt_parameters.rig.pf_num_weak_far,     // final int        num_weak_far,     // number of directions to try
							clt_parameters.tileX,                   // final int        dbg_x,
							clt_parameters.tileY,                   // final int        dbg_y,
							debugLevel);                            // final int        debugLevel);
					if (debugLevel > -4) {
						System.out.println("groundTruthByRigPlanes(): full cycle="+num_fcycle+" num_trimmed= "+num_trimmed+" tiles");
					}
					if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){
						biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR).showScan(
								quadCLT_main.image_name+"-BISCAN_TRIMMED"+num_fcycle+"-"+num_cycle);
					}

					// suggest again, after trimming
					int num_added_tiles_trimmed = last_scan.suggestNewScan(
							null,                                   // final boolean [] area_of_interest,
							null,                                   // final double [][] disparityStrength,
							clt_parameters.rig.pf_trusted_strength, // final double     trusted_strength, // trusted correlation strength
							clt_parameters.rig.pf_strength_rfloor,  // final double     strength_rfloor,   // strength floor - relative to trusted
							clt_parameters.rig.pf_discard_cond,     // final boolean    discard_cond,      // consider conditionally trusted tiles (not promoted to trusted) as empty
							clt_parameters.rig.pf_discard_weak,     // final boolean    discard_weak,      // consider conditionally trusted tiles (not promoted to trusted) as empty
							clt_parameters.rig.pf_discard_strong,   // final boolean    discard_strong,      // consider conditionally trusted tiles (not promoted to trusted) as empty
							clt_parameters.rig.pf_strength_pow,     // final double     strength_pow,      // raise strength-floor to this power
							clt_parameters.rig.pf_smpl_radius,      // final int        smpl_radius,
							clt_parameters.rig.pf_smpl_num,         // final int        smpl_num,   //         = 3;      // Number after removing worst (should be >1)
							clt_parameters.rig.pf_smpl_fract,       // final double     smpl_fract, // Number of friends among all neighbors
							clt_parameters.rig.pf_smpl_num_narrow,  // final int        smpl_num_narrow,   //         = 3;      // Number after removing worst (should be >1)
							clt_parameters.rig.pf_max_adiff,        // final double     max_adiff,  // Maximal absolute difference betweenthe center tile and friends
							clt_parameters.rig.pf_max_rdiff,        // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
							clt_parameters.rig.pf_max_atilt,        // final double     max_atilt, //  = 2.0; // pix per tile
							clt_parameters.rig.pf_max_rtilt,        // final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
							clt_parameters.rig.pf_smpl_arms,        // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
							clt_parameters.rig.pf_smpl_rrms,        // final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
							clt_parameters.rig.pf_damp_tilt,        // final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
							clt_parameters.rig.pf_rwsigma,          // final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma
							clt_parameters.rig.pf_rwsigma_narrow,   // final double     rwsigma_narrow,    //  = used to determine initial tilt
							clt_parameters.rig.pf_new_diff,         // final double     new_diff,            // minimal difference between the new suggested and the already tried/measured one
							true,                                   // final boolean    remove_all_tried,  // remove from suggested - not only disabled, but all tried
							0.0,                                    // final double     center_weight,     // use center tile too (0.0 - do not use)
							clt_parameters.rig.pf_use_alt,          // final boolean    use_alt,           // use tiles from other scans if they fit better
							clt_parameters.rig.pf_goal_fraction_rms,// final double     goal_fraction_rms, // Try to make rms to be this fraction of maximal acceptable by removing outliers
							clt_parameters.rig.pf_boost_low_density,// NOT USED HERE, MAY BE 0,                                    // final double     boost_low_density, // 0 - strength is proportional to 1/density, 1.0 - same as remaining tiles
							null,                                   // final double []  smooth_strength,   // optionally fill strength array when used for smoothing DSI
							0,                                      // final int        fourq_min,         // each of the 4 corners should have at least this number of tiles.
							0,                                      // final int        fourq_gap,         // symmetrical vertical and horizontal center areas that do not belong to any corner
							clt_parameters.tileX,                   // final int        dbg_x,
							clt_parameters.tileY,                   // final int        dbg_y,
							debugLevel);                            // final int        debugLevel);
					if (debugLevel > -4) {
						System.out.println("groundTruthByRigPlanes() full cycle = "+num_fcycle+", grow pass "+num_cycle+" of "+ num_cross_gaps_cycles+
								" suggestNewScan() -> "+num_added_tiles_trimmed+"( after trimming)");
					}
					if (clt_parameters.show_map &&  (debugLevel > -2) && clt_parameters.rig.rig_mode_debug){
						biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR).showScan(
								quadCLT_main.image_name+"-BISCAN_TRIMMED_SUGGESTED"+num_fcycle+"-"+num_cycle);
					}

					//					  break; // too few added before trimmimng or number of steps exceeded limit
				} // if (last_cycle && clt_parameters.rig.pf_en_trim_fg) { // last cycle and trimming enabled
				// measure and refine
				double [] target_disparity = biCamDSI.getTargetDisparity(-1); // get last

				// Measure provided tiles (break after, if it was the last cycle)

				double [][] disparity_bimap = measureNewRigDisparity(
						quadCLT_main,      // QuadCLT             quadCLT_main,    // tiles should be set
						quadCLT_aux,       // QuadCLT             quadCLT_aux,
						target_disparity,  // double []                                      disparity, // Double.NaN - skip, ohers - measure
						clt_parameters,    // EyesisCorrectionParameters.CLTParameters       clt_parameters,
						false,             //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
						0,                 // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
						// first measurement - use default value:
						clt_parameters.rig.no_int_x0,           // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
						threadsMax,        // final int           threadsMax,      // maximal number of threads to launch
						updateStatus,      // final boolean       updateStatus,
						debugLevel);       // final int           debugLevel);

				// refine measurements
				int [] num_new = new int[1];
				// at least for small separation FG/BG individual cameras may not provide trusted results - ignore them only use rig
				boolean [] trusted_measurements = 	  getTrustedDisparity(
						quadCLT_main,                            // QuadCLT            quadCLT_main,  // tiles should be set
						quadCLT_aux,                             // QuadCLT            quadCLT_aux,
						//						  false,                                   // boolean            use_individual,
						true,                                   // boolean            use_individual,
						0.8*clt_parameters.rig.min_trusted_strength, // double             min_combo_strength,    // check correlation strength combined for all 3 correlations
						clt_parameters.grow_disp_trust,          // double             max_trusted_disparity, // 4.0 -> change to rig_trust
						clt_parameters.rig.trusted_tolerance,    // double             trusted_tolerance,
						null,                                    // boolean []         was_trusted,
						disparity_bimap);              // double [][]        bimap // current state of measurements

				if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){
4469
					(new ShowDoubleFloatArrays()).showArrays(
4470 4471 4472 4473 4474 4475
							disparity_bimap,
							tilesX,
							tilesY,
							true,
							quadCLT_main.image_name+"-gaps_cycle"+num_cycle,
							ImageDtt.BIDISPARITY_TITLES);
4476

4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490
				}
				double [][] prev_bimap = null;
				double [] scale_bad = new double [trusted_measurements.length];
				for (int i = 0; i < scale_bad.length; i++) scale_bad[i] = 1.0;
				for (int nref = 0; nref < clt_parameters.rig.num_inf_refine; nref++) {
					// refine infinity using inter correlation
					double [][] disparity_bimap_new =  refineRigSel(
							quadCLT_main,    // QuadCLT                        quadCLT_main,    // tiles should be set
							quadCLT_aux,     // QuadCLT                        quadCLT_aux,
							disparity_bimap, // double [][]                    src_bimap,       // current state of measurements (or null for new measurement)
							prev_bimap,      // double [][]                    prev_bimap, // previous state of measurements or null
							scale_bad,       // double []                      scale_bad,
							refine_inter,    // int                            refine_mode,     // 0 - by main, 1 - by aux, 2 - by inter
							false,           // boolean                        keep_inf,        // keep expected disparity 0.0 if it was so
4491
							0.0,             // double                                         inf_disparity,
4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518
							0.0, // clt_parameters.rig.refine_min_strength , // double refine_min_strength, // do not refine weaker tiles
							clt_parameters.rig.refine_tolerance ,    // double refine_tolerance,    // do not refine if absolute disparity below
							trusted_measurements, // tile_list,       // ArrayList<Integer>             tile_list,       // or null
							num_new,         // int     []                                     num_new,
							clt_parameters,  // EyesisCorrectionParameters.CLTParameters clt_parameters,
							false,           //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
							0,               // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
							// disable window preset in refine mode
							true,            // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
							threadsMax,      // final int                      threadsMax,      // maximal number of threads to launch
							updateStatus,    // final boolean                  updateStatus,
							debugLevel);     // final int                      debugLevel);
					prev_bimap = disparity_bimap;
					disparity_bimap = disparity_bimap_new;
					trusted_measurements = 	  getTrustedDisparityInter(
							0.0, // clt_parameters.rig.lt_trusted_strength*clt_parameters.rig.lt_need_friends, // double             min_inter_strength,    // check correlation strength combined for all 3 correlations
							clt_parameters.grow_disp_trust,           // double             max_trusted_disparity,
							trusted_measurements,                     // boolean []         was_trusted,
							disparity_bimap );                        // double [][]        bimap // current state of measurements

					if (debugLevel > -2) {
						System.out.println("groundTruthByRigPlanes(): cycle="+num_cycle+", refinement step="+nref+" num_new= "+num_new[0]+" tiles");
					}
					if (num_new[0] < clt_parameters.rig.pf_min_new) {
						break;
					}
				}
4519 4520


4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541
				//FIXME: 	show only for the last_cycle
				if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){
					double [][] dbg_img = new double[disparity_bimap.length][];
					for (int layer = 0; layer < disparity_bimap.length; layer ++) if (disparity_bimap[layer] != null){
						dbg_img [layer]= disparity_bimap[layer].clone();
						for (int nTile = 0; nTile < disparity_bimap[layer].length; nTile++) {
							if (!trusted_measurements[nTile]) dbg_img[layer][nTile] = Double.NaN;
						}
					}
					if ((scale_bad!= null) && (debugLevel > 0)){
						int num_bad = 0, num_trusted = 0;
						for (int nTile = 0; nTile < scale_bad.length; nTile++) {
							if (!trusted_measurements[nTile]) scale_bad[nTile] = Double.NaN;
							else {
								if (scale_bad[nTile] < 1.0) num_bad++;
								scale_bad[nTile] =  -scale_bad[nTile];
								num_trusted ++;

							}
						}
						System.out.println("num_trusted = "+num_trusted+", num_bad = "+num_bad);
4542
						(new ShowDoubleFloatArrays()).showArrays(
4543 4544 4545 4546 4547 4548
								scale_bad,
								tilesX,
								tilesY,
								quadCLT_main.image_name+"-gaps_cycle"+num_cycle+"-scale_bad");

					}
4549
					(new ShowDoubleFloatArrays()).showArrays(
4550 4551 4552 4553 4554 4555 4556
							dbg_img,
							tilesX,
							tilesY,
							true,
							quadCLT_main.image_name+"-gaps_cycle"+num_cycle+"-REFINED_TRUSTED",
							ImageDtt.BIDISPARITY_TITLES);
				}
4557

4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596
				// add refined data
				biCamDSI.addBiScan(disparity_bimap, BiScan.BISCAN_SINGLECORR);
				// find strongest if FG over BG - not the strongest, but either strongest or just strong and nearer
				biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR).copyLastStrongestEnabled(
						clt_parameters.rig.pf_last_priority); // final boolean last_priority)

				double afloor = clt_parameters.rig.pf_trusted_strength * clt_parameters.rig.pf_strength_rfloor;

				// replace strongest by fittest
				for (int nfit = 0; nfit < num_tries_strongest_by_fittest; nfit++) {
					int num_replaced = biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR).copyFittestEnabled(
							afloor,                             // final double  str_floor,      // absolute strength floor
							clt_parameters.rig.pf_disp_afloor,  // final double  pf_disp_afloor, // =            0.1;    // When selecting the best fit from the alternative disparities, divide by difference increased by this
							clt_parameters.rig.pf_disp_rfloor); // 	final double  pf_disp_rfloor) //  =            0.02;   // Increase pf_disp_afloor for large disparities
					if ((debugLevel > -2) && clt_parameters.rig.rig_mode_debug){
						System.out.println("groundTruthByRigPlanes(): Replacing strongest by fittest: ntry = "+nfit+", replaced "+num_replaced+" tiles");
					}
					if (num_replaced == 0) {
						break;
					}
				}
				double  fg_str_good_enough =  clt_parameters.rig.pf_trusted_strength  * 0.6; // 4; // absolute strength floor for good enough
				double  fg_min_FGtoBG =      1.0;    // minimal disparity difference over
				double  fg_disp_atolerance = 0.1;    // Maximal absolute disparity difference to qualifying neighbor
				double  fg_disp_rtolerance = 0.02;   // Maximal relative (to absolute disparity) disparity difference to qualifying neighbor
				int     fg_min_neib =        2;      // minimal number of qualifying neighbors to promote FG tile

				// promote thin FG objects over even stronger BG ones (as thin stick in FG over textured BG)

				int num_replaced_fg = biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR).copyStrongFGEnabled(
						fg_str_good_enough, // final double  str_good_enough, // absolute strength floor for good enough
						fg_min_FGtoBG,      // final double  min_FGtoBG,      // minimal disparity difference over
						fg_disp_atolerance, // final double  disp_atolerance, // =  0.1;    // Maximal absolute disparity difference to qualifying neighbor
						fg_disp_rtolerance, // final double  disp_rtolerance, // =  0.02;   // Maximal relative (to absolute disparity) disparity difference to qualifying neighbor
						fg_min_neib);       // final int     min_neib)        // minimal number of qualifying neighbors to promote FG tile
				//				  if ((debugLevel > -2) && clt_parameters.rig.rig_mode_debug){
				if ((debugLevel > -4)){
					System.out.println("groundTruthByRigPlanes(): Replacing BG with FG tiles,  replaced "+num_replaced_fg+" tiles");
				}
4597

4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655
				if (clt_parameters.show_map &&  (debugLevel > 0) && clt_parameters.rig.rig_mode_debug){
					biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR).showScan(
							quadCLT_main.image_name+"-BISCAN_"+num_fcycle+"-"+num_cycle);
				}
				if (last_cycle) { // last cycle
					if ((debugLevel > -2) && clt_parameters.rig.rig_mode_debug){
						System.out.println("groundTruthByRigPlanes(): that was refinement measurements after the trimming of hanging weak FG over BG");
					}
					break;
				}
				//	public void showScan(String title) {
				if (debugLevel > -2){
					System.out.println("groundTruthByRigPlanes(): num_cycle="+num_cycle);
				}
			} // for (int num_cycle = 0; num_cycle < num_cross_gaps_cycles; num_cycle++) {
			if (debugLevel > -2){
				System.out.println("groundTruthByRigPlanes(): num_fcycle="+num_fcycle);
			}
		}// 		  for (int num_fcycle = 0; num_fcycle < num_full_cycles; num_fcycle++) {



		// Fill in low-textured areas using averaged correlation
		double [][] rig_disparity_strength = null;
		biCamDSI_persistent = biCamDSI; // save for pole detection
		if (clt_parameters.rig.ltavg_en) {
			if (debugLevel > -2) {
				System.out.println("groundTruthByRigPlanes(): Processing low-textured areas with multi-tile correlation averaging");
			}
			// next method adds to the list of BiScans
			//			  double [][] ds_avg =
			//requires biCamDSI_persistent
			measureLowTextureAreas(
					quadCLT_main,   // QuadCLT            quadCLT_main,  // tiles should be set
					quadCLT_aux,    // QuadCLT            quadCLT_aux,  // tiles should be set
					clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
					threadsMax,     // final int     threadsMax,  // maximal number of threads to launch
					updateStatus,   // final boolean updateStatus,
					debugLevel-2);    // final int    debugLevel) //
			// get last that was just added
			rig_disparity_strength = biCamDSI.getLastBiScan(BiScan.BISCAN_ANY).getDisparityStrength(
					false, // boolean only_strong,
					false, // boolean only_trusted,
					true); // boolean only_enabled,

		} else {
			// ignore any added low-texture areas
			rig_disparity_strength = biCamDSI.getLastBiScan(BiScan.BISCAN_SINGLECORR).getDisparityStrength(
					false, // boolean only_strong,
					false, // boolean only_trusted,
					true); // boolean only_enabled,
		}
		return rig_disparity_strength;
	}

	public boolean showBiScan(
			QuadCLT            quadCLT_main,  // tiles should be set
			QuadCLT            quadCLT_aux,  // tiles should be set
4656
			CLTParameters       clt_parameters,
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 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 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 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 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 4786 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 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel) //  throws Exception
	{

		if ((quadCLT_main == null) ||
				(quadCLT_main.tp == null) ||
				(quadCLT_main.tp.clt_3d_passes == null) ||
				(biCamDSI_persistent== null) ||
				(biCamDSI_persistent.biScans== null)) {
			String msg = "Data is not available. Please run \"Ground truth\" first";
			IJ.showMessage("Error",msg);
			System.out.println(msg);
			return false;
		}
		int scan_index = biCamDSI_persistent.biScans.size()-1;
		boolean show_smooth =     false;
		boolean keep_unreliable = false;
		boolean keep_weak =       false;
		boolean keep_strong =     false;
		double  center_weight =   1.0;
		// from clt_parameters.rig
		double trusted_strength = clt_parameters.rig.pf_trusted_strength;
		double cond_rtrusted =    clt_parameters.rig.pf_cond_rtrusted;
		double strength_rfloor =  clt_parameters.rig.pf_strength_rfloor;
		double strength_pow =     clt_parameters.rig.pf_strength_pow;
		int smpl_radius =         clt_parameters.rig.pf_fourq_radius; // clt_parameters.rig.pf_smpl_radius;
		int smpl_num =            clt_parameters.rig.pf_smpl_num;
		int smpl_num_narrow =     clt_parameters.rig.pf_smpl_num_narrow;
		double smpl_fract =       clt_parameters.rig.pf_smpl_fract;
		double max_adiff =        clt_parameters.rig.pf_max_adiff;
		double max_rdiff =        clt_parameters.rig.pf_max_rdiff;
		double max_atilt =        clt_parameters.rig.pf_max_atilt;
		double max_rtilt =        clt_parameters.rig.pf_max_rtilt;
		double smpl_arms =        clt_parameters.rig.pf_smpl_arms;
		double smpl_rrms =        clt_parameters.rig.pf_smpl_rrms;
		double damp_tilt =        clt_parameters.rig.pf_damp_tilt;
		double rwsigma =          clt_parameters.rig.pf_rwsigma;
		double rwsigma_narrow =   clt_parameters.rig.pf_rwsigma_narrow;

		boolean use_alt =         clt_parameters.rig.pf_use_alt;
		double goal_fraction_rms= clt_parameters.rig.pf_goal_fraction_rms;    // Try to make rms to be this fraction of maximal acceptable by removing outliers
		double boost_low_density= clt_parameters.rig.pf_boost_low_density;    // Strength assigned to fake tiles from neighbors (the lower - the higher)

		int        fourq_min =    clt_parameters.rig.pf_fourq_min;
		int        fourq_gap =    clt_parameters.rig.pf_fourq_gap;

		boolean  run_avg =         true; // false; //ltavg_en
		int      lt_radius =       clt_parameters.rig.ltavg_radius;
		boolean  strong_only =     clt_parameters.rig.ltavg_dens_strong;
		int      need_tiles =      clt_parameters.rig.ltavg_dens_tiles;
		int      max_radius =      clt_parameters.rig.ltavg_dens_radius;

		double   min_disparity =   clt_parameters.rig.ltavg_min_disparity;

		double   max_density =     clt_parameters.rig.ltavg_max_density;
		int      gap_hwidth =      clt_parameters.rig.ltavg_gap_hwidth;
		int      clust_hwidth =    clt_parameters.rig.ltavg_clust_hwidth;
		int      extra_grow =      clt_parameters.rig.ltavg_extra_grow;
		// smoothing parameters
		boolean  smooth_strength = clt_parameters.rig.ltavg_smooth_strength;  // provide tile strength when smoothing target disparity
		double   neib_pull =       clt_parameters.rig.ltavg_neib_pull;    // pull to weighted average relative to pull to the original disparity value. If 0.0 - will only update former NaN-s
		int      max_iter =        clt_parameters.rig.ltavg_max_iter;      //
		double   min_change =      clt_parameters.rig.ltavg_min_change;   //


		int ref_smpl_radius =  clt_parameters.rig.ltavg_ref_smpl_radius; // 11;          // final int        smpl_radius,
		int ref_smpl_num =     clt_parameters.rig.ltavg_ref_smpl_num; // 40;          // final int        smpl_num_narrow,   //         = 3;      // Number after removing worst (should be >1)
		double ref_max_adiff = clt_parameters.rig.ltavg_ref_max_adiff; //0.15;        // final double     max_adiff,  // Maximal absolute difference between the center tile and friends
		double ref_max_rdiff = clt_parameters.rig.ltavg_ref_max_rdiff; //0.04;        // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
		double ref_smpl_arms = clt_parameters.rig.ltavg_ref_smpl_arms; //0.1;         // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
		double ref_smpl_rrms = clt_parameters.rig.ltavg_ref_smpl_rrms; //0.01;        // final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
		int num_lt_refine =    clt_parameters.rig.ltavg_num_lt_refine; // 20; // make a parameter
		double strong_tol =    clt_parameters.rig.ltavg_strong_tol ; //
		double weak_tol =      clt_parameters.rig.ltavg_weak_tol ; //

		GenericJTabbedDialog gd = new GenericJTabbedDialog("Set CLT parameters",900,1100);
		gd.addTab("Genearl","Select bi-scan to show and process");

		gd.addNumericField("Scan index (0..."+(biCamDSI_persistent.biScans.size()-1),  scan_index, 0, 2, "",  "Display scan by index");

		gd.addCheckbox    ("Show smooth disparity/strength for the selected scan",  show_smooth, 		"Unchecked - just as is");
		gd.addCheckbox    ("Keep unreliable tiles",                                 keep_unreliable, 	"Unchecked - overwrite with smooth data");
		gd.addCheckbox    ("Keep weak (but trusted) tiles",                         keep_weak,       	"Unchecked - overwrite with smooth data");
		gd.addCheckbox    ("Keep strng trusted tiles",                              keep_strong, 	    "Unchecked - overwrite with smooth data");
		gd.addNumericField("Center weight - relative weight of the existing tile ", center_weight,  4,6,"",
				"0.0 - suggest new disparity over existing tiles without ant regard to the original value, 1.0 - same influence as any other tile");

		gd.addMessage     ("Parameters that are copied from the CLT parameters");
		gd.addNumericField("Strength sufficient without neighbors",                                               trusted_strength,  4,6,"",
				"Unconditionally trusted tile. Other stength values are referenceds as fraction of this value (after strength floor subtraction)");
		gd.addNumericField("Strength sufficient with neighbors support, fraction of the trusted strength",      cond_rtrusted,  4,6,"",
				"Strength that may be valid for the tile if there are neighbors in the same possibly tilted plane of the DSI (floor corrected)");

		gd.addNumericField("Fraction of trusted strength to subtract",                                            strength_rfloor,  4,6,"",
				"Strength floor to subtract from all strength values");
		gd.addNumericField("Raise strength-floor to this power",                                                  strength_pow,  4,6,"",
				"Currently just 1.0 - lenear");
		gd.addNumericField("How far to extend around known tiles (probably should increase this value up to?",    smpl_radius,  0,3,"tiles",
				"Process a aquare centered at the current tile withthe side of twice this value plus 1 (2*pf_smpl_radius + 1)");
		gd.addNumericField("Number after remaining in the sample square after removing worst fitting tiles",      smpl_num,  0,3,"",
				"When fitting planes the outliers are removed until the number of remaining tiles equals this value");
		gd.addNumericField("Number of remaining tiles when using narrow selection",                               smpl_num_narrow,  0,3,"",
				"Number of remaining tiles during initial palne fitting to the center pixels (it is later extended to include farther tiles)");
		gd.addNumericField("Fraction of the reamining tiles of all non-zero tiles?",                              smpl_fract,  4,6,"",
				"This value is combined to the previous one (absilute). Maximal of absolute and relative times number of all non-empty tiles is used");
		gd.addNumericField("Maximal absolute disparity difference between the plane and tiles that fit",          max_adiff,  4,6,"pix",
				"Maximal absolute disparity difference for fitting. Combined with the next one (relative) ");
		gd.addNumericField("Maximal relative (to center disparity) difference between the plane and tiles that fit",max_rdiff,  4,6,"pix/pix",
				"This value is multipled by the tile disparity and added to the maximal absolute difference");
		gd.addNumericField("Maximal absolute tile tilt in DSI space",                                             max_atilt,  4,6,"pix/tile",
				"Maximal disparity difference betweeing neighbor tiles for the tilted plane. Combined with the relative one (next), min of both limits applies");
		gd.addNumericField("Maximal relative (per pixel of disparity) tile tilt in DSI space",                    max_rtilt,  4,6,"1/tile",
				"Maximal relative (to center disparity) tilt. Near tiles (larger disparity may have larger differnce.");
		gd.addNumericField("Maximal absolute RMS of the remaining tiles in a sample",                             smpl_arms,  4,6,"pix",
				"After removing outliers RMS of the remaining tiles must be less than this value");
		gd.addNumericField("Maximal relative (to center disparity) RMS of the remaining tiles in a sample",       smpl_rrms,  4,6,"pix/pix",
				"Relative RMS times disparity is added to the absolute one");
		gd.addNumericField("Tilt cost for damping insufficient plane data",                                       damp_tilt,  4,6,"",
				"Regularisation to handle co-linear and even single-point planes, forcing fronto-parallel for single point, and minimal tilt for co-linear set");
		gd.addNumericField("Influence of far neighbors is reduced as a Gaussian with this sigma",                 rwsigma,  4,6,"",
				"Sigma is relative to selection radius (square half-side)");
		gd.addNumericField("Weight function Gaussian sigma (relative to radius) for initial plane fitting",       rwsigma_narrow,  4,6,"",
				"Weight function Gaussian sigma (relative to selection radius) for initial plane fitting. May be ~=1/radius");
		gd.addCheckbox    ("When fitting planes, look for alternative measure tiles",use_alt, 	        "Unchecked - only use the latest (current) tile");
		gd.addNumericField("Try to make rms to be this fraction of maximal acceptable by removing outliers",      goal_fraction_rms,  4,6,"pix",
				"When removing outliers to fit planes, stop removing when the RMS of the remaining drops below this fraction of the maxium allowed RMS (should be < 1.0");
		gd.addNumericField("Strength assigned to fake tiles from neighbors (the lower - the higher)",             boost_low_density,  4,6,"pix",
				"Returned strength assigned to the tiles increases with this value - seems to be a bug");

		gd.addNumericField("Each of the 4 corners should have at least this number of tiles",                     fourq_min,  0,3,"",
				"Apply (>0) only for filling gaps, not during expansion. It requires that every of the 4 corners of the sample square has this number of tiles for a plane");
		gd.addNumericField("Four corners center gap half-width (1 - 1 tile, 2 - 3 tiles, 3 - 5 tiles, ...",       fourq_gap,  0,3,"",
				"Specifies corners of the sample square that should have tiles remain, after removing centre columns and center rows");

		gd.addTab("LT Avg","Low texture correlatinaveraging");
		gd.addCheckbox    ("Measure with tile averaging",                                                         run_avg, 	        "");
		gd.addNumericField("Averaging radius (1 - 3x3 square, 2  - 5x5, ...",                                     lt_radius,  0,3,"",  "");
		gd.addCheckbox    ("Calculate density of strong trusted only (false include weak trusted)",               strong_only, 	    "");
		gd.addNumericField("Minimal number tiles to calculate density)",                                          need_tiles,  0,3,"",  "");
		gd.addNumericField("Maximal radius for measuruing density)",                                              max_radius,  0,3,"",  "");

		gd.addNumericField("Minimal disparity to apply filter",                                                   min_disparity,  4,6,"pix",
				"Farther objects will not be filtered");

		gd.addNumericField("Maximal density to consider it to be low textured area",                              max_density,  4,6,"",
				"Select areas with lower density");
		gd.addNumericField("Maximal radius of a void in low-texture selection to fill"  ,                         gap_hwidth,  0,3,"",
				"Low textured selection may have gaps that will be filled");
		gd.addNumericField("Minimal radius of a low-textured cluster to process",                                 clust_hwidth,  0,3,"",
				"Remove low-textured areas smaller that twice this size in each orthogonal directions");
		gd.addNumericField("Additionally grow low-textured areas selections",                                     extra_grow,  0,3,"",
				"Low textured areas will be grown by the radius of correlation averaging plus this value");




		gd.addCheckbox    ("Use tile strengths when filling gaps/smoothing",                                      smooth_strength,
				"Unchecked - consider all tiles to have the same strength");
		gd.addNumericField("Relative pull of the nieghbor tiles compared to the original disparity" ,             neib_pull,   4,6,"",
				"If set to 0.0 - only gaps will be filled, defined disparities will not be modified");
		gd.addNumericField("Maximal number of smoothing / gap filling iterations to perform",                     max_iter,    0,3,"",
				"Safety limit for smoothing iterations ");
		gd.addNumericField("Minimal disparity change to continue smoothing",                                      min_change,  4,6,"pix","");

		gd.addNumericField("How far to extend around a tile when refining averaging correlation measuremnts by planes ",    ref_smpl_radius,  0,3,"tiles",
				"Process a aquare centered at the current tile withthe side of twice this value plus 1 (2*pf_smpl_radius + 1)");
		gd.addNumericField("Number after remaining in the sample square after removing worst fitting tiles",      ref_smpl_num,  0,3,"",
				"When fitting planes the outliers are removed until the number of remaining tiles equals this value");
		gd.addNumericField("Maximal absolute disparity difference between the plane and tiles that fit",          ref_max_adiff,  4,6,"pix",
				"Maximal absolute disparity difference for fitting. Combined with the next one (relative) ");
		gd.addNumericField("Maximal relative (to center disparity) difference between the plane and tiles that fit",ref_max_rdiff,  4,6,"pix/pix",
				"This value is multipled by the tile disparity and added to the maximal absolute difference");
		gd.addNumericField("Maximal absolute RMS of the remaining tiles in a sample",                             ref_smpl_arms,  4,6,"pix",
				"After removing outliers RMS of the remaining tiles must be less than this value");
		gd.addNumericField("Maximal relative (to center disparity) RMS of the remaining tiles in a sample",       ref_smpl_rrms,  4,6,"pix/pix",
				"Relative RMS times disparity is added to the absolute one");


		gd.addNumericField("Maximal number of low texture/averaging correlation passes",                          num_lt_refine,  0,3,"",
				"Will also exit when maximal tile disparity change falls below ltavg_min_change (..continue smoothing above)");
		gd.addNumericField("Strong tile difference to averaged to be accepted",                                   strong_tol,  4,6,"pix",
				"When combining normal measurements with low texture/correlation averaging use strong normal if they are close to averaged");
		gd.addNumericField("Weak trusted tile difference to averaged to be accepted",                             weak_tol,  4,6,"pix",
				"When combining normal measurements with low texture/correlation averaging use weak normal if they are close to averaged");



		//		  boolean run_avg = false;
		//		  int     lt_radius = 1;


		gd.showDialog();
		if (gd.wasCanceled()) return false;
		scan_index =      (int) gd.getNextNumber();
		show_smooth =           gd.getNextBoolean();
		keep_unreliable =       gd.getNextBoolean();
		keep_weak =             gd.getNextBoolean();
		keep_strong  =          gd.getNextBoolean();
		center_weight =         gd.getNextNumber();
		// from clt_parameters.rig
		trusted_strength =      gd.getNextNumber();
		cond_rtrusted =         gd.getNextNumber();
		strength_rfloor =       gd.getNextNumber();
		strength_pow =          gd.getNextNumber();
		smpl_radius  =    (int) gd.getNextNumber();
		smpl_num =        (int) gd.getNextNumber();
		smpl_num_narrow = (int) gd.getNextNumber();
		smpl_fract =            gd.getNextNumber();
		max_adiff =             gd.getNextNumber();
		max_rdiff =             gd.getNextNumber();
		max_atilt =             gd.getNextNumber();
		max_rtilt =             gd.getNextNumber();
		smpl_arms =             gd.getNextNumber();
		smpl_rrms =             gd.getNextNumber();
		damp_tilt =             gd.getNextNumber();
		rwsigma =               gd.getNextNumber();
		rwsigma_narrow =        gd.getNextNumber();

		use_alt =               gd.getNextBoolean();
		goal_fraction_rms=      gd.getNextNumber();
		boost_low_density=      gd.getNextNumber();

		fourq_min=        (int) gd.getNextNumber();
		fourq_gap=        (int) gd.getNextNumber();

		//		  gd.addTab("LT Avg","Low texture correlatinaveraging");

		run_avg  =              gd.getNextBoolean();
		lt_radius=        (int) gd.getNextNumber();
		strong_only =           gd.getNextBoolean();
		need_tiles=       (int) gd.getNextNumber();
		max_radius=       (int) gd.getNextNumber();

		min_disparity =         gd.getNextNumber();

		max_density =           gd.getNextNumber();
		gap_hwidth=             (int) gd.getNextNumber();
		clust_hwidth=           (int) gd.getNextNumber();
		extra_grow=             (int) gd.getNextNumber();

		smooth_strength =       gd.getNextBoolean();
		neib_pull =             gd.getNextNumber();
		max_iter=         (int) gd.getNextNumber();
		min_change =            gd.getNextNumber();

		ref_smpl_radius=  (int) gd.getNextNumber();
		ref_smpl_num=     (int) gd.getNextNumber();
		ref_max_adiff=          gd.getNextNumber();
		ref_max_rdiff=          gd.getNextNumber();
		ref_smpl_arms=          gd.getNextNumber();
		ref_smpl_rrms=          gd.getNextNumber();

		num_lt_refine=    (int) gd.getNextNumber();
		strong_tol=             gd.getNextNumber();
		weak_tol=               gd.getNextNumber();

		BiScan biScan =  biCamDSI_persistent.biScans.get(scan_index);
		double [][] ds = null;
		if (show_smooth) {
4917
			@SuppressWarnings("unused")
4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 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 4982 4983 4984 4985
			double [][] final_ds=  measureLowTextureAreas(
					quadCLT_main,      // QuadCLT            quadCLT_main,  // tiles should be set
					quadCLT_aux,       // QuadCLT            quadCLT_aux,  // tiles should be set
					clt_parameters,    // EyesisCorrectionParameters.CLTParameters       clt_parameters,
					// from clt_parameters.rig
					trusted_strength,  // double      trusted_strength,
					cond_rtrusted,     // double      cond_rtrusted,
					strength_rfloor,   // double      strength_rfloor,
					strength_pow,      // double      strength_pow,
					smpl_radius,       // int         smpl_radius,
					smpl_num,          // int         smpl_num,
					smpl_num_narrow,   // int         smpl_num_narrow,
					smpl_fract,        // double      smpl_fract,
					max_adiff,         // double      max_adiff,
					max_rdiff,         // double      max_rdiff,
					max_atilt,         // double      max_atilt,
					max_rtilt,         // double      max_rtilt,
					smpl_arms,         // double      smpl_arms,
					smpl_rrms,         // double      smpl_rrms,
					damp_tilt,         // double      damp_tilt,
					rwsigma,           // double      rwsigma,
					rwsigma_narrow,    // double      rwsigma_narrow,
					use_alt,           // boolean     use_alt,
					goal_fraction_rms, // double      goal_fraction_rms,
					boost_low_density, // double      boost_low_density,
					fourq_min,         // int         fourq_min,
					fourq_gap,         // int         fourq_gap,
					lt_radius,         // int         lt_radius,
					strong_only,       // boolean     strong_only,
					need_tiles,        // int         need_tiles,
					max_radius,        // int         max_radius,
					min_disparity,     // double      min_disparity,
					max_density,       // double      max_density,
					gap_hwidth,        // int         gap_hwidth,
					clust_hwidth,      // int         clust_hwidth,
					extra_grow,        // int         extra_grow,
					// smoothing parameters
					smooth_strength,   // boolean     smooth_strength,
					neib_pull,         // double      neib_pull,
					max_iter,          // int         max_iter,
					min_change,        // double      min_change,
					ref_smpl_radius,   // int         ref_smpl_radius,
					ref_smpl_num,      // int         ref_smpl_num,
					ref_max_adiff,     // double      ref_max_adiff,
					ref_max_rdiff,     // double      ref_max_rdiff,
					ref_smpl_arms,     // double      ref_smpl_arms,
					ref_smpl_rrms,     // double      ref_smpl_rrms,
					num_lt_refine,     // int         num_lt_refine,
					strong_tol,        // double      strong_tol,
					weak_tol,          // double      weak_tol,
					clt_parameters.rig.ltavg_expand_lt,      // boolean    expand_lt, //  =           true;
					clt_parameters.rig.ltavg_expand_dist,    // int        expand_dist, //  =         4;
					clt_parameters.rig.ltavg_expand_tol,     // double     expand_tol, //  =          0.15;   // expand LT right and left if it ends with same or nearer tile
					clt_parameters.rig.ltavg_expand_floor,   // double      expand_floor, //  =      0.5;    // multiply single-tile strength floor for correlation-average
					clt_parameters.rig.ltavg_expand_sample_num,// int         expand_sample_num, //  =   5;      // minimal number of samples in expansion mode
					threadsMax,        // maximal number of threads to launch
					updateStatus,
					debugLevel);
		} else {
			biScan.showScan(quadCLT_main.image_name+"BiScan-"+scan_index,ds);
		}

		return true;
	}

	public double [][] measureLowTextureAreas(
			QuadCLT            quadCLT_main,  // tiles should be set
			QuadCLT            quadCLT_aux,  // tiles should be set
4986
			CLTParameters       clt_parameters,
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 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054
			final int     threadsMax,  // maximal number of threads to launch
			final boolean updateStatus,
			final int    debugLevel) //  throws Exception
	{
		return  measureLowTextureAreas(
				quadCLT_main,      // QuadCLT            quadCLT_main,  // tiles should be set
				quadCLT_aux,       // QuadCLT            quadCLT_aux,  // tiles should be set
				clt_parameters,    // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				// from clt_parameters.rig
				clt_parameters.rig.pf_trusted_strength,  // double      trusted_strength,
				clt_parameters.rig.pf_cond_rtrusted,     // double      cond_rtrusted,
				clt_parameters.rig.pf_strength_rfloor,   // double      strength_rfloor,
				clt_parameters.rig.pf_strength_pow,      // double      strength_pow,
				clt_parameters.rig.pf_fourq_radius,      // clt_parameters.rig.pf_smpl_radius, // smpl_radius,       // int         smpl_radius,
				clt_parameters.rig.pf_smpl_num,          // int         smpl_num,
				clt_parameters.rig.pf_smpl_num_narrow,   // int         smpl_num_narrow,
				clt_parameters.rig.pf_smpl_fract,        // double      smpl_fract,
				clt_parameters.rig.pf_max_adiff,         // double      max_adiff,
				clt_parameters.rig.pf_max_rdiff,         // double      max_rdiff,
				clt_parameters.rig.pf_max_atilt,         // double      max_atilt,
				clt_parameters.rig.pf_max_rtilt,         // double      max_rtilt,
				clt_parameters.rig.pf_smpl_arms,         // double      smpl_arms,
				clt_parameters.rig.pf_smpl_rrms,         // double      smpl_rrms,
				clt_parameters.rig.pf_damp_tilt,         // double      damp_tilt,
				clt_parameters.rig.pf_rwsigma,           // double      rwsigma,
				clt_parameters.rig.pf_rwsigma_narrow,    // double      rwsigma_narrow,
				clt_parameters.rig.pf_use_alt,           // boolean     use_alt,
				clt_parameters.rig.pf_goal_fraction_rms, // double      goal_fraction_rms, // Try to make rms to be this fraction of maximal acceptable by removing outliers
				clt_parameters.rig.pf_boost_low_density, // double      boost_low_density,// Strength assigned to fake tiles from neighbors (the lower - the higher)
				clt_parameters.rig.pf_fourq_min,         // int         fourq_min,
				clt_parameters.rig.pf_fourq_gap,         // int         fourq_gap,
				clt_parameters.rig.ltavg_radius,         // int         lt_radius,
				clt_parameters.rig.ltavg_dens_strong,    // boolean     strong_only,
				clt_parameters.rig.ltavg_dens_tiles,     // int         need_tiles,
				clt_parameters.rig.ltavg_dens_radius,    // int         max_radius,
				clt_parameters.rig.ltavg_min_disparity,  // double      min_disparity,
				clt_parameters.rig.ltavg_max_density,    // double      max_density,
				clt_parameters.rig.ltavg_gap_hwidth,     // int         gap_hwidth,
				clt_parameters.rig.ltavg_clust_hwidth,   // int         clust_hwidth,
				clt_parameters.rig.ltavg_extra_grow,     // int         extra_grow,
				// smoothing parameters
				clt_parameters.rig.ltavg_smooth_strength,// boolean     smooth_strength,
				clt_parameters.rig.ltavg_neib_pull,      // double      neib_pull,
				clt_parameters.rig.ltavg_max_iter,       // int         max_iter,
				clt_parameters.rig.ltavg_min_change,     // double      min_change,
				clt_parameters.rig.ltavg_ref_smpl_radius,// int         ref_smpl_radius,
				clt_parameters.rig.ltavg_ref_smpl_num,   // int         ref_smpl_num,
				clt_parameters.rig.ltavg_ref_max_adiff,  // double      ref_max_adiff,
				clt_parameters.rig.ltavg_ref_max_rdiff,  // double      ref_max_rdiff,
				clt_parameters.rig.ltavg_ref_smpl_arms,  // double      ref_smpl_arms,
				clt_parameters.rig.ltavg_ref_smpl_rrms,  // double      ref_smpl_rrms,
				clt_parameters.rig.ltavg_num_lt_refine,  // int         num_lt_refine,
				clt_parameters.rig.ltavg_strong_tol,     // double      strong_tol,
				clt_parameters.rig.ltavg_weak_tol,       // double      weak_tol,
				clt_parameters.rig.ltavg_expand_lt,      // boolean    expand_lt, //  =           true;
				clt_parameters.rig.ltavg_expand_dist,    // int        expand_dist, //  =         4;
				clt_parameters.rig.ltavg_expand_tol,     // double     expand_tol, //  =          0.15;   // expand LT right and left if it ends with same or nearer tile
				clt_parameters.rig.ltavg_expand_floor,   // double      expand_floor, //  =      0.5;    // multiply single-tile strength floor for correlation-average
				clt_parameters.rig.ltavg_expand_sample_num,// int         expand_sample_num, //  =   5;      // minimal number of samples in expansion mode
				threadsMax,        // maximal number of threads to launch
				updateStatus,
				debugLevel);
	}


	public double [][] measureLowTextureAreas(
			QuadCLT            quadCLT_main,  // tiles should be set
			QuadCLT            quadCLT_aux,  // tiles should be set
5055
			CLTParameters       clt_parameters,
5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 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 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 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 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 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 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 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362
			// from clt_parameters.rig
			double      trusted_strength,
			double      cond_rtrusted,
			double      strength_rfloor,
			double      strength_pow,
			int         smpl_radius,
			int         smpl_num,
			int         smpl_num_narrow,
			double      smpl_fract,
			double      max_adiff,
			double      max_rdiff,
			double      max_atilt,
			double      max_rtilt,
			double      smpl_arms,
			double      smpl_rrms,
			double      damp_tilt,
			double      rwsigma,
			double      rwsigma_narrow,
			boolean     use_alt,
			double      goal_fraction_rms,
			double      boost_low_density,
			int         fourq_min,
			int         fourq_gap,
			//			  boolean     run_avg,
			int         lt_radius,
			boolean     strong_only,
			int         need_tiles,
			int         max_radius,
			double      min_disparity,
			double      max_density,
			int         gap_hwidth,
			int         clust_hwidth,
			int         extra_grow,
			// smoothing parameters
			boolean     smooth_strength,
			double      neib_pull,
			int         max_iter,
			double      min_change,
			int         ref_smpl_radius,
			int         ref_smpl_num,
			double      ref_max_adiff,
			double      ref_max_rdiff,
			double      ref_smpl_arms,
			double      ref_smpl_rrms,
			int         num_lt_refine,
			double      strong_tol,
			double      weak_tol,
			boolean     expand_lt, //  =           true;
			int         expand_dist, //  =         4;
			double      expand_tol, //  =          0.15;   // expand LT right and left if it ends with same or nearer tile
			double      expand_floor, //  =      0.5;    // multiply single-tile strength floor for correlation-average
			int         expand_sample_num, //  =   5;      // minimal number of samples in expansion mode
			final int     threadsMax,  // maximal number of threads to launch
			final boolean updateStatus,
			final int    debugLevel) //  throws Exception
	{
		boolean show_smooth =     true;
		boolean keep_unreliable = false;
		boolean keep_weak =       false;
		boolean keep_strong =     false;
		double  center_weight =   1.0;

		if (debugLevel > -2){
			System.out.println(" === showBiScan( parameters : =====");
			//			  System.out.println("       scan_index= "+scan_index);
			System.out.println("      show_smooth= "+show_smooth);
			System.out.println("  keep_unreliable= "+keep_unreliable);
			System.out.println("        keep_weak= "+keep_weak);
			System.out.println("      keep_strong= "+keep_strong);
			System.out.println("    center_weight= "+center_weight);

			System.out.println(" trusted_strength= "+trusted_strength);
			System.out.println("    cond_rtrusted= "+cond_rtrusted);
			System.out.println("  strength_rfloor= "+strength_rfloor);
			System.out.println("     strength_pow= "+strength_pow);
			System.out.println("      smpl_radius= "+smpl_radius);
			System.out.println("         smpl_num= "+smpl_num);
			System.out.println("  smpl_num_narrow= "+smpl_num_narrow);
			System.out.println("       smpl_fract= "+smpl_fract);
			System.out.println("        max_adiff= "+max_adiff);
			System.out.println("        max_rdiff= "+max_rdiff);
			System.out.println("        max_atilt= "+max_atilt);
			System.out.println("        max_rtilt= "+max_rtilt);
			System.out.println("        smpl_arms= "+smpl_arms);
			System.out.println("        smpl_rrms= "+smpl_rrms);
			System.out.println("        damp_tilt= "+damp_tilt);
			System.out.println("          rwsigma= "+rwsigma);
			System.out.println("   rwsigma_narrow= "+rwsigma_narrow);

			System.out.println("          use_alt= "+use_alt);
			System.out.println("goal_fraction_rms= "+goal_fraction_rms);
			System.out.println("boost_low_density= "+boost_low_density);

			System.out.println("        fourq_min= "+fourq_min);
			System.out.println("        fourq_gap= "+fourq_gap);

			//			  System.out.println("          run_avg= "+run_avg);
			System.out.println("        lt_radius= "+lt_radius);
			System.out.println("      strong_only= "+strong_only);
			System.out.println("       need_tiles= "+need_tiles);
			System.out.println("       max_radius= "+max_radius);

			System.out.println("    min_disparity= "+min_disparity);
			System.out.println("      max_density= "+max_density);
			System.out.println("       gap_hwidth= "+gap_hwidth);
			System.out.println("       extra_grow= "+extra_grow);

			System.out.println("     clust_hwidth= "+clust_hwidth);
			System.out.println("  smooth_strength= "+smooth_strength);
			System.out.println("        neib_pull= "+neib_pull);
			System.out.println("         max_iter= "+max_iter);
			System.out.println("       min_change= "+min_change);

			System.out.println("  ref_smpl_radius= "+ref_smpl_radius);
			System.out.println("     ref_smpl_num= "+ref_smpl_num);
			System.out.println("    ref_max_adiff= "+ref_max_adiff);
			System.out.println("    ref_max_rdiff= "+ref_max_rdiff);
			System.out.println("    ref_smpl_arms= "+ref_smpl_arms);
			System.out.println("    ref_smpl_rrms= "+ref_smpl_rrms);

			System.out.println("    num_lt_refine= "+num_lt_refine);
			System.out.println("       strong_tol= "+strong_tol);
			System.out.println("         weak_tol= "+weak_tol);

			System.out.println("        expand_lt= "+expand_lt);
			System.out.println("      expand_dist= "+expand_dist);
			System.out.println("       expand_tol= "+expand_tol);

			System.out.println("     expand_floor= "+expand_floor);
			System.out.println("expand_sample_num= "+expand_sample_num);
		}
		BiScan biScan =  biCamDSI_persistent.getLastBiScan(BiScan.BISCAN_SINGLECORR); // biScans.get(scan_index);
		biCamDSI_persistent.getLastBiScan(BiScan.BISCAN_SINGLECORR).copyLastStrongestEnabled(
				clt_parameters.rig.pf_last_priority); // final boolean last_priority)
		double afloor = trusted_strength * strength_rfloor;
		int num_tries_strongest_by_fittest = 5;
		// replace strongest by fittest
		for (int nfit = 0; nfit < num_tries_strongest_by_fittest; nfit++) {
			int num_replaced = biCamDSI_persistent.getLastBiScan(BiScan.BISCAN_SINGLECORR).copyFittestEnabled(
					afloor,                             // final double  str_floor,      // absolute strength floor
					clt_parameters.rig.pf_disp_afloor,  // final double  pf_disp_afloor, // =            0.1;    // When selecting the best fit from the alternative disparities, divide by difference increased by this
					clt_parameters.rig.pf_disp_rfloor); // 	final double  pf_disp_rfloor) //  =            0.02;   // Increase pf_disp_afloor for large disparities
			if ((debugLevel > -2) && clt_parameters.rig.rig_mode_debug){
				System.out.println("measureLowTextureAreas(): Replacing strongest by fittest: ntry = "+nfit+", replaced "+num_replaced+" tiles");
			}
			if (num_replaced == 0) {
				break;
			}
		}

		double  fg_str_good_enough = trusted_strength * 0.4; // absolute strength floor for good enough
		double  fg_min_FGtoBG =      1.0;    // minimal disparity difference over
		double  fg_disp_atolerance = 0.1;    // Maximal absolute disparity difference to qualifying neighbor
		double  fg_disp_rtolerance = 0.02;   // Maximal relative (to absolute disparity) disparity difference to qualifying neighbor
		int     fg_min_neib =        2;      // minimal number of qualifying neighbors to promote FG tile

		// promote thin FG objects over even stronger BG ones (as thin stick in FG over textured BG)

		int num_replaced_fg = biCamDSI_persistent.getLastBiScan(BiScan.BISCAN_SINGLECORR).copyStrongFGEnabled(
				fg_str_good_enough, // final double  str_good_enough, // absolute strength floor for good enough
				fg_min_FGtoBG,      // final double  min_FGtoBG,      // minimal disparity difference over
				fg_disp_atolerance, // final double  disp_atolerance, // =  0.1;    // Maximal absolute disparity difference to qualifying neighbor
				fg_disp_rtolerance, // final double  disp_rtolerance, // =  0.02;   // Maximal relative (to absolute disparity) disparity difference to qualifying neighbor
				fg_min_neib);       // final int     min_neib)        // minimal number of qualifying neighbors to promote FG tile
		//		  if ((debugLevel > -2) && clt_parameters.rig.rig_mode_debug){
		if ((debugLevel > -2)){
			System.out.println("measureLowTextureAreas(): Replacing BG with FG tiles,  replaced "+num_replaced_fg+" tiles");
		}



		biScan.calcTrusted(   // finds strong trusted and validates week ones if they fit planes
				trusted_strength, // final double     trusted_strength, // trusted correlation strength
				strength_rfloor,  // final double     strength_rfloor,   // strength floor - relative to trusted
				cond_rtrusted,    // final double     cond_rtrusted,     // minimal strength to consider - fraction of trusted
				strength_pow,     // final double     strength_pow,      // raise strength-floor to this power
				smpl_radius,      // final int        smpl_radius,
				smpl_num,         // final int        smpl_num,   //         = 3;      // Number after removing worst (should be >1)
				smpl_fract,       // final double     smpl_fract, // Number of friends among all neighbors
				max_adiff,        // final double     max_adiff,  // Maximal absolute difference betweenthe center tile and friends
				max_rdiff,        // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
				max_atilt,        // final double     max_atilt, //  = 2.0; // pix per tile
				max_rtilt,        // final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
				smpl_arms,        // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
				smpl_rrms,        // final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
				damp_tilt,        // final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
				rwsigma,          // 						final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma
				clt_parameters.tileX,                   // final int        dbg_x,
				clt_parameters.tileY,                   // final int        dbg_y,
				debugLevel);                            // final int        debugLevel);

		double [] density = 		  biScan.getDensity(
				strong_only, // final boolean strong_only,
				need_tiles, // 20, // 10,    // final int need_tiles,
				max_radius, // 20, // 15,    // final int max_radius,
				clt_parameters.tileX, // final int        dbg_x,
				clt_parameters.tileY, // final int        dbg_y,
				debugLevel+2);        // final int        debugLevel
		boolean [] pre_select = biScan.selectLowTextures(
				min_disparity,        // double    min_disparity,
				max_density,          // double    max_density,
				lt_radius+extra_grow, // int       grow,
				gap_hwidth,           // int       max_gap_radius,
				clust_hwidth,         // int       min_clust_radius,
				density,              // double [] density,
				null);                // double [] src_disparity);
		double []   dbg_presel = new double [pre_select.length];
		for (int i = 0; i < pre_select.length; i++) dbg_presel[i] = pre_select[i]? 1.0:0.0;
		double [][] dbg_dens_str = {density, dbg_presel};
		//		  biScan.showScan(quadCLT_main.image_name+"-density-"+scan_index,dbg_dens_str); //list_index
		if (debugLevel > 0) {
			biScan.showScan(quadCLT_main.image_name+"-density-"+biScan.list_index,dbg_dens_str); //list_index
		}

		double [][] ds = biScan.getFilteredDisparityStrength(
				pre_select,           // final boolean [] area_of_interest,
				null,                 // final double [][] disparityStrength,
				min_disparity,        // final double     min_disparity,    // keep original disparity far tiles
				trusted_strength,     // final double     trusted_strength, // trusted correlation strength
				strength_rfloor,      // final double     strength_rfloor,   // strength floor - relative to trusted
				!keep_unreliable,     // final boolean    discard_unreliable,// replace v
				!keep_weak,           // final boolean    discard_weak,      // consider weak trusted tiles (not promoted to trusted) as empty
				!keep_strong,         // final boolean    discard_strong,    // suggest new disparities even for strong tiles
				strength_pow,         // final double     strength_pow,      // raise strength-floor to this power
				null,                 // final double []  smpl_radius_array, // space-variant radius
				smpl_radius,          // final int        smpl_radius,
				smpl_num,             // final int        smpl_num,   //         = 3;      // Number after removing worst (should be >1)
				smpl_fract,           // final double     smpl_fract, // Number of friends among all neighbors
				smpl_num_narrow,      // final int        smpl_num_narrow,   //         = 3;      // Number after removing worst (should be >1)
				max_adiff,            // final double     max_adiff,  // Maximal absolute difference between the center tile and friends
				max_rdiff,            // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
				max_atilt,            // final double     max_atilt, //  = 2.0; // pix per tile
				max_rtilt,            // final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
				smpl_arms,            // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
				smpl_rrms,            // final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
				damp_tilt,            // final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
				rwsigma,              // final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma
				rwsigma_narrow,       // final double     rwsigma_narrow,    //  = used to determine initial tilt
				center_weight,        // final double     center_weight,     // use center tile too (0.0 - do not use)
				use_alt,              // final boolean    use_alt,           // use tiles from other scans if they fit better
				goal_fraction_rms,    // final double     goal_fraction_rms, // Try to make rms to be this fraction of maximal acceptable by removing outliers
				boost_low_density,    //final double     boost_low_density, // 0 - strength is proportional to 1/density, 1.0 - same as remaining tiles
				fourq_min,            // final int        fourq_min,         // each of the 4 corners should have at least this number of tiles.
				fourq_gap,            // final int        fourq_gap,         // symmetrical vertical and horizontal center areas that do not belong to any corner
				clt_parameters.tileX, // final int        dbg_x,
				clt_parameters.tileY, // final int        dbg_y,
				debugLevel+0);          // final int        debugLevel
		if (debugLevel > 0) {
			biScan.showScan(quadCLT_main.image_name+"-BiScan-"+biScan.list_index,ds);
		}

		boolean [] lt_select = biScan.selectLowTextures(
				min_disparity,        // double    min_disparity,
				max_density,          // double    max_density,
				lt_radius+extra_grow, // 	int       grow,
				gap_hwidth,           // int       max_gap_radius,
				clust_hwidth,         // int       min_clust_radius,
				density,              // double [] density,
				ds[0]);               // double [] src_disparity);

		// compare iterations at lt_compare;
		boolean [] lt_compare = lt_select.clone();
		biCamDSI_persistent.tnImage.shrinkSelection(
				2*(lt_radius), // 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
				lt_compare, // boolean [] tiles,
				null); // boolean [] prohibit)


		double [][] ds1 = {ds[0].clone(), ds[1].clone()} ;
		for (int i = 0; i < lt_select.length; i++) if (!lt_select[i]) {
			ds1[0][i] = Double.NaN;
			ds1[1][i] = 0.0;
		}
		if (debugLevel > 0) {
			biScan.showScan(quadCLT_main.image_name+"-selection-"+biScan.list_index,ds1);
		}
		double [] lt_strength = smooth_strength? ds1[1]:null;

		double [][] ds2 = biScan.fillAndSmooth(
				ds1[0],               // final double [] src_disparity,
				lt_strength,          // final double [] src_strength, // if not null will be used for weighted pull
				lt_select,            // final boolean [] selection,
				neib_pull,            // final double     neib_pull, // pull to weighted average relative to pull to the original disparity value. If 0.0 - will only update former NaN-s
				max_iter,             // final int max_iterations,
				min_change,           // final double min_change,
				clt_parameters.tileX, // final int        dbg_x,
				clt_parameters.tileY, // final int        dbg_y,
				debugLevel+0);        // final int        debugLevel
		if (debugLevel > 0) {
			biScan.showScan(quadCLT_main.image_name+"-smooth-"+biScan.list_index,ds2);
		}

		//		  if (run_avg) {
		int tilesX = quadCLT_main.tp.getTilesX();
		double [][] disparity_bimap = measureNewRigDisparity(
				quadCLT_main,   // QuadCLT                                  quadCLT_main,  // tiles should be set
				quadCLT_aux,    // QuadCLT                                  quadCLT_aux,
				ds2[0],          // double []                                      disparity, // Double.NaN - skip, ohers - measure
				clt_parameters, // EyesisCorrectionParameters.CLTParameters clt_parameters,
				false, // boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_radius,      // int                 lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
				// use set from parameters
				clt_parameters.rig.no_int_x0,    // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,     // final int        threadsMax,  // maximal number of threads to launch
				updateStatus,  // updateStatus,   // final boolean    updateStatus,
				debugLevel);    // final int        debugLevel)
		if (debugLevel > 0) {
5363
			(new ShowDoubleFloatArrays()).showArrays(
5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374
					disparity_bimap,
					tilesX,
					disparity_bimap[0].length/tilesX,
					true,
					quadCLT_main.image_name+"LPF"+lt_radius,
					ImageDtt.BIDISPARITY_TITLES);
		}

		//try to refine
		int [] num_new = new int[1];
		/*
5375 5376 5377 5378 5379 5380 5381 5382
			  boolean [] trusted_measurements = 	  getTrustedDisparity(
					  quadCLT_main,                            // QuadCLT            quadCLT_main,  // tiles should be set
					  quadCLT_aux,                             // QuadCLT            quadCLT_aux,
					  clt_parameters.rig.min_trusted_strength, // double             min_combo_strength,    // check correlation strength combined for all 3 correlations
					  clt_parameters.grow_disp_trust,          // double             max_trusted_disparity, // 4.0 -> change to rig_trust
					  clt_parameters.rig.trusted_tolerance,    // double             trusted_tolerance,
					  null,                                    // boolean []         was_trusted,
					  disparity_bimap);              // double [][]        bimap // current state of measurements
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 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447
		 */
		double [][] prev_bimap = null;
		double [] scale_bad = new double [ds2[0].length];
		for (int i = 0; i < scale_bad.length; i++) scale_bad[i] = 1.0;
		for (int nref = 0; nref < num_lt_refine; nref++) { // clt_parameters.rig.num_inf_refine; nref++) {
			//			  for (int nref = 0; nref < clt_parameters.rig.num_inf_refine; nref++) {

			double [][] disparity_bimap_new =  refineRigAvg(
					quadCLT_main,    // QuadCLT                        quadCLT_main,    // tiles should be set
					quadCLT_aux,     // QuadCLT                        quadCLT_aux,
					disparity_bimap, // double [][]                    src_bimap,       // current state of measurements (or null for new measurement)
					prev_bimap,      // double [][]                    prev_bimap, // previous state of measurements or null
					scale_bad,       // double []                      scale_bad,
					lt_select,       // final boolean []  area_of_interest,
					num_new,         // int     []                               num_new,
					clt_parameters,  // EyesisCorrectionParameters.CLTParameters clt_parameters,
					lt_radius,          // final int                                lt_radius,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
					biScan,          // final BiScan                             biScan,
					min_disparity, // final double     min_disparity,    // keep original disparity far tiles
					trusted_strength, // final double     trusted_strength, // trusted correlation strength
					expand_floor * strength_rfloor,// final double     strength_rfloor,   // strength floor - relative to trusted
					strength_pow,      //final double     strength_pow,      // raise strength-floor to this power
					ref_smpl_radius,   // final int        smpl_radius,
					smpl_fract,     // final double     smpl_fract, // Number of friends among all neighbors
					ref_smpl_num,   // final int        ref_smpl_num,   //         = 3;      // Number after removing worst (should be >1)
					ref_max_adiff,      // final double     max_adiff,  // Maximal absolute difference betweenthe center tile and friends
					ref_max_rdiff,      // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
					max_atilt,      // final double     max_atilt, //  = 2.0; // pix per tile
					max_rtilt,      // final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
					ref_smpl_arms,  // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
					ref_smpl_rrms,  // 							  final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
					damp_tilt,      // final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
					rwsigma,        // final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma
					goal_fraction_rms, //final double     goal_fraction_rms, // Try to make rms to be this fraction of maximal acceptable by removing outliers
					max_iter,       // final int        max_iterations,
					min_change, // final double     min_change,
					clt_parameters.tileX, // final int        dbg_x,
					clt_parameters.tileY, // final int        dbg_y,
					threadsMax,      // final int                      threadsMax,      // maximal number of threads to launch
					updateStatus,    // final boolean                  updateStatus,
					debugLevel);     // final int                      debugLevel);

			prev_bimap = disparity_bimap;
			disparity_bimap = disparity_bimap_new;

			double max_diff =0.0, sw = 0.0, swd = 0.0, swd2 = 0.0;
			for (int nTile = 0; nTile < lt_compare.length; nTile++) if (lt_compare[nTile]){
				double w = disparity_bimap[ImageDtt.BI_STR_CROSS_INDEX][nTile]; // subtract floor?
				double d = disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile]-prev_bimap[ImageDtt.BI_TARGET_INDEX][nTile];
				if (Double.isNaN(d)) {
					System.out.println("showBiScan(): got NaN: disparity_bimap[ImageDtt.BI_TARGET_INDEX]["+nTile+"]="+disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile]+
							", prev_bimap[ImageDtt.BI_TARGET_INDEX]["+nTile+"]="+prev_bimap[ImageDtt.BI_TARGET_INDEX][nTile]);
				} else {
					sw += w;
					swd += w*d;
					swd2 +=w*d*d;
					max_diff = Math.max(max_diff, Math.abs(d));
				}
			}
			double mean = swd / sw;
			double rms = Math.sqrt(swd2 / sw);
			if (debugLevel > 0) {
				System.out.println("showBiScan() iteration "+nref+": mean ="+mean+", rms = "+ rms+", max diff. = "+max_diff );
			}

5448
			if (debugLevel > 10) {(new ShowDoubleFloatArrays()).showArrays(
5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471
					disparity_bimap,
					tilesX,
					disparity_bimap[0].length/tilesX,
					true,
					quadCLT_main.image_name+"RE-MEASURED_R"+lt_radius+"-N"+nref,
					ImageDtt.BIDISPARITY_TITLES);
			}



			if (debugLevel > 0) {
				System.out.println("measureLowTextureAreas():  refinement step="+nref+" num_new= "+num_new[0]+" tiles");
			}
			if (num_new[0] < clt_parameters.rig.pf_min_new) break; // currently will never happen
			if (( max_diff < min_change) || (nref == (num_lt_refine - 1))) {
				if (debugLevel > -2) {
					System.out.println("showBiScan() final iteration "+nref+": mean ="+mean+", rms = "+ rms+", max diff. = "+max_diff );
				}
				break;
			}

		}
		if (debugLevel > 0) {
5472
			(new ShowDoubleFloatArrays()).showArrays(
5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559
					disparity_bimap,
					tilesX,
					disparity_bimap[0].length/tilesX,
					true,
					quadCLT_main.image_name+"CORR-AVG"+lt_radius,
					ImageDtt.BIDISPARITY_TITLES);
		}

		double [][] avg_ds = {disparity_bimap[ImageDtt.BI_TARGET_INDEX],disparity_bimap[ImageDtt.BI_STR_CROSS_INDEX]};
		// maybe trim all previously added to the last BiScan.BISCAN_SINGLECORR?
		// so far just add
		for (int nTile = 0; nTile < lt_select.length; nTile++) if (!lt_select[nTile]){ // keep border tiles
			avg_ds[0][nTile] = Double.NaN;
			avg_ds[1][nTile] = 0.0;
		}

		boolean [] strong = biScan.strong_trusted;
		boolean [] weak =   biScan.trusted;
		double [][] ds_single = biScan.getDisparityStrength(
				false, // only_strong,
				false, // only_trusted,
				true); // only_enabled);
		if (expand_lt) {
			boolean [] expanded_lt = lt_select.clone();
			TileNeibs         tnImage =  biCamDSI_persistent.tnImage;
			tnImage.growSelection(
					2* expand_dist,   // 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
					expanded_lt,      // boolean [] tiles,
					null);            // boolean [] prohibit)
			for (int nTile = 0; nTile < expanded_lt.length; nTile++) {
				expanded_lt[nTile] &= ! lt_select[nTile] && !weak[nTile]; // Or just !Double.isNaN(ds_single[0][nTile]) ???
			}
			if (debugLevel > 0) {
				double [][] dbg_sel = new double [2][expanded_lt.length];
				for (int i = 0; i < expanded_lt.length; i++) {
					dbg_sel[0][i] = (lt_select[i]? 1:0) + (expanded_lt[i]? 2:0);
					dbg_sel[1][i] = (lt_select[i]? 1:0);
				}
				biScan.showScan(quadCLT_main.image_name+"-lt-selections"+biScan.list_index, dbg_sel);
				biScan.showScan(quadCLT_main.image_name+"-avg_ds"+biScan.list_index, avg_ds);

			}

			int expand_radius = 2*expand_dist; // where it looks for valid tiles
			double [][] ds_preexpanded =	biScan.getFilteredDisparityStrength(
					expanded_lt,          // final boolean [] area_of_interest,
					avg_ds,               // final double [][] disparityStrength,
					min_disparity,        // final double     min_disparity,    // keep original disparity far tiles
					trusted_strength,     // final double     trusted_strength, // trusted correlation strength
					expand_floor * strength_rfloor,// final double     strength_rfloor,   // strength floor - relative to trusted
					true,     // final boolean    discard_unreliable,// replace v
					true,           // final boolean    discard_weak,      // consider weak trusted tiles (not promoted to trusted) as empty
					true,         // final boolean    discard_strong,    // suggest new disparities even for strong tiles
					strength_pow,         // final double     strength_pow,      // raise strength-floor to this power
					null,                 // final double []  smpl_radius_array, // space-variant radius
					expand_radius,        // final int        smpl_radius,
					0,                    // final int        smpl_num,   //         = 3;      // Number after removing worst (should be >1)
					//					  0.5 * smpl_fract,        // final double     smpl_fract, // Number of friends among all neighbors
					smpl_fract,           // final double     smpl_fract, // Number of friends among all neighbors
					expand_sample_num,    // ref_smpl_num,         // final int        smpl_num_narrow,   //         = 3;      // Number after removing worst (should be >1)
					ref_max_adiff,        // final double     max_adiff,  // Maximal absolute difference between the center tile and friends
					ref_max_rdiff,        // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
					max_atilt,            // final double     max_atilt, //  = 2.0; // pix per tile
					max_rtilt,            // final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
					ref_smpl_arms,        // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
					ref_smpl_rrms,        // final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
					damp_tilt,            // final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
					0.0,                  // final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma
					rwsigma,              // final double     rwsigma_narrow,    //  = used to determine initial tilt
					1.0,                  // final double     center_weight,     // use center tile too (0.0 - do not use)
					false,                // final boolean    use_alt,           // use tiles from other scans if they fit better
					goal_fraction_rms,    // final double     goal_fraction_rms, // Try to make rms to be this fraction of maximal acceptable by removing outliers
					0.8,                  // boost_low_density,    //final double     boost_low_density, // 0 - strength is proportional to 1/density, 1.0 - same as remaining tiles
					0,                    // final int        fourq_min,         // each of the 4 corners should have at least this number of tiles.
					0,                    // final int        fourq_gap,         // symmetrical vertical and horizontal center areas that do not belong to any corner
					clt_parameters.tileX, // final int        dbg_x,
					clt_parameters.tileY, // final int        dbg_y,
					debugLevel+0);          // final int        debugLevel
			if (debugLevel > -4) {
				biScan.showScan(quadCLT_main.image_name+"-preexpand"+biScan.list_index, ds_preexpanded);
			}

			for (int nTile = 0; nTile < expanded_lt.length; nTile++) {
				if (Double.isNaN(ds_preexpanded[0][nTile]) && !Double.isNaN(avg_ds[0][nTile])){
					ds_preexpanded[0][nTile] = avg_ds[0][nTile];
					ds_preexpanded[1][nTile] = avg_ds[1][nTile];
				}
5560

5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575
			}
			if (debugLevel > -4) {// 0) {
				biScan.showScan(quadCLT_main.image_name+"-combo-expand"+biScan.list_index, ds_preexpanded); // already wrong strength
			}

			//			  double [][] ds_expanded =
			avg_ds = biScan.getLTExpanded(
					expand_tol,       // final double      tolerance, // should be not NaN over lt
					ds_preexpanded,   // final double [][] ds_lt, // should be not NaN over lt
					ds_single[0],     // final double []   d_single,
					lt_select,        // final boolean []  lt_sel,
					expanded_lt,      // final boolean []  exp_sel,
					weak);            // final boolean []  trusted);
			// TODO use fillAndSmooth() to calculate new weights (keeping disparity as it was)
			/*
5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587
			  double [][] avg_ds_strength = biScan.fillAndSmooth(
					  ds_preexpanded[0],    // final double [] src_disparity,
					  ds_preexpanded[1],    // final double [] src_strength, // if not null will be used for weighted pull
					  lt_select,            // final boolean [] selection,
					  0.0,                  // only gaps neib_pull, // final double     neib_pull, // pull to weighted average relative to pull to the original disparity value. If 0.0 - will only update former NaN-s
					  max_iter,             // final int max_iterations,
					  min_change,           // final double min_change,
					  clt_parameters.tileX, // final int        dbg_x,
					  clt_parameters.tileY, // final int        dbg_y,
					  debugLevel+0);        // final int        debugLevel

			  avg_ds[1] = avg_ds_strength[1];
5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 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
			 */
			if (debugLevel > -4) { //-2) {
				biScan.showScan(quadCLT_main.image_name+"-lt-expanded"+biScan.list_index, avg_ds);
			}

		}

		int new_index = biCamDSI_persistent.addBiScan(
				avg_ds[0], // double [] disparity, // this will be "measured"
				avg_ds[1], // double [] strength,
				null, // boolean [] trusted,
				null, // boolean [] disabled,
				BiScan.BISCAN_AVGCORR); //int        scan_type)
		BiScan newScan = biCamDSI_persistent.getBiScan(new_index);
		if (debugLevel > -2) {
			System.out.println("Added scan #new_index");
		}

		for (int nTile = 0; nTile < lt_compare.length; nTile++){
			if (!lt_compare[nTile]) {
				if (!Double.isNaN(ds_single[0][nTile])) { // keep border from low texture if there are no normal measurements for this tile
					newScan.src_index[nTile] = biScan.src_index[nTile]; // will use same disparity/strength
				}
			} else {
				if (
						(strong[nTile] && (Math.abs(ds_single[0][nTile] - avg_ds[0][nTile]) <= strong_tol)) ||
						(weak[nTile] &&   (Math.abs(ds_single[0][nTile] - avg_ds[0][nTile]) <= weak_tol))) {
					newScan.src_index[nTile] = biScan.src_index[nTile]; // will use same disparity/strength
				}
			}
		}

		double [][] merged_ds = newScan.getDisparityStrength(
				false, // only_strong,
				false, // only_trusted,
				true); // only_enabled);



		// TODO: strength floor with averaged
		double avg_rfloor =        0.8 * strength_rfloor;
		double avg_cond_rtrusted = 0.8 * cond_rtrusted;

		int [] trusted_stats = newScan.calcTrusted(   // finds strong trusted and validates week ones if they fit planes
				trusted_strength,       // final double     trusted_strength, // trusted correlation strength
				avg_rfloor,             // final double     strength_rfloor,   // strength floor - relative to trusted
				avg_cond_rtrusted,      // final double     cond_rtrusted,     // minimal strength to consider - fraction of trusted
				strength_pow,           // final double     strength_pow,      // raise strength-floor to this power
				smpl_radius,            // final int        smpl_radius,
				smpl_num,               // final int        smpl_num,   //         = 3;      // Number after removing worst (should be >1)
				smpl_fract,             // final double     smpl_fract, // Number of friends among all neighbors
				max_adiff,              // final double     max_adiff,  // Maximal absolute difference betweenthe center tile and friends
				max_rdiff,              // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
				max_atilt,              // final double     max_atilt, //  = 2.0; // pix per tile
				max_rtilt,              // final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
				smpl_arms,              // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
				smpl_rrms,              // final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
				damp_tilt,              // final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
				rwsigma,                // 						final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma
				clt_parameters.tileX,                   // final int        dbg_x,
				clt_parameters.tileY,                   // final int        dbg_y,
				debugLevel);                            // final int        debugLevel);


		if (debugLevel > -2) {
			System.out.println("measureLowTextureAreas()  strong trusted: "+trusted_stats[0]+
					" neib trusted: "+trusted_stats[1]+" weak trusted: " + trusted_stats[2]);
		}

		if (debugLevel > -2) {
			newScan.showScan(quadCLT_main.image_name+"-smooth-"+newScan.list_index, avg_ds);
		}
		return merged_ds;
	}




	public double [][] refineRigAvg(
			QuadCLT                                  quadCLT_main,  // tiles should be set
			QuadCLT                                  quadCLT_aux,
			double [][]                              src_bimap, // current state of measurements
			double [][]                              prev_bimap, // previous state of measurements or null
			double []                                scale_bad,
			final boolean []  area_of_interest,
			int     []                               num_new,
5674
			CLTParameters clt_parameters,
5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728
			final int                                lt_radius,      // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
			final BiScan                             biScan,
			//			  final double [][] disparityStrength,
			final double     min_disparity,    // keep original disparity far tiles
			final double     trusted_strength, // trusted correlation strength
			final double     avg_strength_rfloor,   // strength floor - relative to trusted
			final double     strength_pow,      // raise strength-floor to this power
			final int        smpl_radius,
			final double     smpl_fract, // Number of friends among all neighbors
			final int        ref_smpl_num,   //         = 3;      // Number after removing worst (should be >1)
			final double     max_adiff,  // Maximal absolute difference betweenthe center tile and friends
			final double     max_rdiff, //  Maximal relative difference between the center tile and friends
			final double     max_atilt, //  = 2.0; // pix per tile
			final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
			final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
			final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
			final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
			final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma
			final double     goal_fraction_rms, // Try to make rms to be this fraction of maximal acceptable by removing outliers
			final int        max_iterations,
			final double     min_change,
			final int        dbg_x,
			final int        dbg_y,
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel)
	{
		int tilesX =quadCLT_main.tp.getTilesX();
		int tilesY =quadCLT_main.tp.getTilesY();
		int [][] tile_op = new int [tilesY][tilesX];
		double [][] disparity_array = new double [tilesY][tilesX];
		double disp_scale_main =  1.0/clt_parameters.corr_magic_scale; // Is it needed?
		double disp_scale_aux =   disp_scale_main * quadCLT_main.geometryCorrection.getDisparityRadius()/quadCLT_aux.geometryCorrection.getDisparityRadius();
		double disp_scale_inter = disp_scale_main * quadCLT_main.geometryCorrection.getDisparityRadius()/quadCLT_aux.geometryCorrection.getBaseline();
		int tile_op_all = clt_parameters.tile_task_op; //FIXME Use some constant?
		int numMeas = 0;
		double [][] ds_ref = new double[2][];
		ds_ref[0] = new double [tilesX*tilesY];

		for (int tileY = 0; tileY<tilesY;tileY++) {
			for (int tileX = 0; tileX<tilesX;tileX++) {
				int nTile = tileY * tilesX + tileX;
				if (((area_of_interest == null) || area_of_interest[nTile]) && !Double.isNaN(src_bimap[ImageDtt.BI_TARGET_INDEX][nTile])) {
					if (prepRefineTile(
							(lt_radius > 0),
							clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
							tile_op_all,    // int                                            tile_op_all,
							src_bimap, // double [][]                                     src_bimap, // current state of measurements
							prev_bimap, // double [][]                                    prev_bimap, // previous state of measurements or null
							scale_bad,  // double []                                      scale_bad,
							tile_op, // int [][]                                          tile_op, // common for both amin and aux
							disparity_array, // double [][]                                    disparity_array,
							2, // int                                            refine_mode, // 0 - by main, 1 - by aux, 2 - by inter
							false,    // boolean                                        keep_inf,    // keep expected disparity 0.0 if it was so
5729
							0.0,             // double                                         inf_disparity,
5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810
							0.0, // double                                         refine_min_strength, // do not refine weaker tiles
							0.0,    // double                                         refine_tolerance,    // do not refine if absolute disparity below
							disp_scale_main,  // double                                         disp_scale_main,  // 1.0
							disp_scale_aux,   //double                                         disp_scale_aux,   // ~0.58
							disp_scale_inter, //double                                         disp_scale_inter, // ~4.86
							//								  scale_step,       // double                                         scale_step,  // scale for "unstable tiles"
							tileX, // int                                            tileX,
							tileY, // int                                            tileY,
							nTile )) {
						numMeas++; //int                                            nTile
						ds_ref[0][nTile] = disparity_array[tileY][tileX];
					}
				}
			}
		}
		ds_ref[1] = src_bimap[ImageDtt.BI_STR_CROSS_INDEX];
		if (debugLevel > 0) {
			System.out.println("refineRigAvg(): prepared "+numMeas+" to measure");
		}

		double [][] ds_planes = biScan.getFilteredDisparityStrength(
				area_of_interest,     // final boolean [] area_of_interest,
				ds_ref,                 // final double [][] disparityStrength,
				min_disparity,        // final double     min_disparity,    // keep original disparity far tiles
				trusted_strength,     // final double     trusted_strength, // trusted correlation strength
				avg_strength_rfloor,// final double     strength_rfloor,   // strength floor - relative to trusted
				true,     // final boolean    discard_unreliable,// replace v
				true,           // final boolean    discard_weak,      // consider weak trusted tiles (not promoted to trusted) as empty
				true,         // final boolean    discard_strong,    // suggest new disparities even for strong tiles
				strength_pow,         // final double     strength_pow,      // raise strength-floor to this power
				null,                 // final double []  smpl_radius_array, // space-variant radius
				smpl_radius,          // final int        smpl_radius,
				0,                    // final int        smpl_num,   //         = 3;      // Number after removing worst (should be >1)
				smpl_fract,           // final double     smpl_fract, // Number of friends among all neighbors
				ref_smpl_num,         // final int        smpl_num_narrow,   //         = 3;      // Number after removing worst (should be >1)
				max_adiff,            // final double     max_adiff,  // Maximal absolute difference between the center tile and friends
				max_rdiff,            // final double     max_rdiff, //  Maximal relative difference between the center tile and friends
				max_atilt,            // final double     max_atilt, //  = 2.0; // pix per tile
				max_rtilt,            // final double     max_rtilt, //  = 0.2; // (pix / disparity) per tile
				smpl_arms,            // final double     smpl_arms, //         = 0.1;    // Maximal RMS of the remaining tiles in a sample
				smpl_rrms,            // final double     smpl_rrms,        //      = 0.005;  // Maximal RMS/disparity in addition to smplRms
				damp_tilt,            // final double     damp_tilt, //   =     0.001; // Tilt cost for damping insufficient plane data
				0.0,                  // final double     rwsigma,           //  = 0.7; // influence of far neighbors diminish as a Gaussian with this sigma
				rwsigma,              // final double     rwsigma_narrow,    //  = used to determine initial tilt
				1.0,                  // final double     center_weight,     // use center tile too (0.0 - do not use)
				false,                // final boolean    use_alt,           // use tiles from other scans if they fit better
				goal_fraction_rms,    // final double     goal_fraction_rms, // Try to make rms to be this fraction of maximal acceptable by removing outliers
				0.8,                  // boost_low_density,    //final double     boost_low_density, // 0 - strength is proportional to 1/density, 1.0 - same as remaining tiles
				0,                    // final int        fourq_min,         // each of the 4 corners should have at least this number of tiles.
				0,                    // final int        fourq_gap,         // symmetrical vertical and horizontal center areas that do not belong to any corner
				clt_parameters.tileX, // final int        dbg_x,
				clt_parameters.tileY, // final int        dbg_y,
				debugLevel+0);          // final int        debugLevel

		// fill NaN gaps:
		double [][] ds_no_gaps = biScan.fillAndSmooth(
				ds_planes[0],         // disparity_bimap[ImageDtt.BI_TARGET_INDEX], // ds1[0], // final double [] src_disparity,
				null,                 // lt_strength, // final double [] src_strength, // if not null will be used for weighted pull
				area_of_interest,     // final boolean [] selection,
				0.0,                  // only gaps neib_pull, // final double     neib_pull, // pull to weighted average relative to pull to the original disparity value. If 0.0 - will only update former NaN-s
				max_iterations,       // final int max_iterations,
				min_change,           // final double min_change,
				clt_parameters.tileX, // final int        dbg_x,
				clt_parameters.tileY, // final int        dbg_y,
				debugLevel+0);        // final int        debugLevel

		// reformat back to disparity_array
		for (int tileY = 0; tileY<tilesY;tileY++) {
			for (int tileX = 0; tileX<tilesX;tileX++) {
				int nTile = tileY * tilesX + tileX;
				disparity_array[tileY][tileX] = ds_no_gaps[0][nTile];
			}
		}

		double [][] disparity_bimap  =  measureRig(
				quadCLT_main,        // QuadCLT                                        quadCLT_main,  // tiles should be set
				quadCLT_aux,         // QuadCLT                                        quadCLT_aux,
				tile_op,             // int [][]                                       tile_op, // common for both amin and aux
				disparity_array,     // double [][]                                    disparity_array,
				null, // double [][]                                    ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				clt_parameters,      // EyesisCorrectionParameters.CLTParameters       clt_parameters,
5811
				clt_parameters.getFatZero(quadCLT_main.isMonochrome()), // double                                         fatzero,
5812 5813 5814 5815 5816 5817 5818 5819 5820 5821
				false,                          //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_radius,                       // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				true,                            // final boolean             no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,          //final int        threadsMax,  // maximal number of threads to launch
				updateStatus,        // final boolean    updateStatus,
				debugLevel);          // final int        debugLevel)

		// combine with old results for tiles that were not re-measured
		// not needed here as so far everything selected is re-measured in the averaging mode)
		/*
5822 5823 5824 5825
		  for (int tileY = 0; tileY<tilesY;tileY++) {
			  for (int tileX = 0; tileX<tilesX;tileX++) {
				  int nTile = tileY * tilesX + tileX;
				  if ((selection == null) || selection[nTile]) {
5826 5827 5828 5829 5830 5831 5832
					  if (Double.isNaN(disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile]) && !Double.isNaN(src_bimap[ImageDtt.BI_TARGET_INDEX][nTile])) {
						  for (int i = 0; i < disparity_bimap.length; i++) {
							  disparity_bimap[i][nTile] = src_bimap[i][nTile];
						  }
					  }
				  }
			  }
5833
		  }
5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846
		 */
		if (num_new != null) {
			num_new[0] = numMeas;
		}
		return disparity_bimap;
	}




	public double [][] fillPoorTextureByInter(
			QuadCLT            quadCLT_main,  // tiles should be set
			QuadCLT            quadCLT_aux,
5847
			CLTParameters       clt_parameters,
5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885
			double [][]                                    disparity_bimap,
			BiCamDSI                                       biCamDSI,
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel)// throws Exception
	{
		final int refine_inter = 2; // use inter-cam disparity for refinement
		final int tilesX = quadCLT_main.tp.getTilesX();
		//		  final int tilesY = quadCLT_main.tp.getTilesY();
		double [] suggestedLTMeasurements =  biCamDSI.suggestLTTiles(
				disparity_bimap,                           // double [][] disparity_bimap,
				null, // boolean []  trusted,       // may be null if disparity is alreasdy NaN-ed
				clt_parameters.rig.lt_min_disparity,       // double      min_disparity, //  =         0.0;    // apply low texture to near objects
				clt_parameters.rig.lt_trusted_strength,    // double      trusted_strength, // =       0.2;    // strength sufficient without neighbors
				clt_parameters.rig.lt_strength_rfloor,     // double      strength_rfloor,  // =       0.28;   // strength floor relative to trusted_strength
				clt_parameters.rig.lt_need_friends,        // double      need_friends, // =           0.4;    // strength sufficient with neighbors support, fraction of lt_trusted_strength
				clt_parameters.rig.lt_extend_dist,         // int         extend_dist, // =            3;      // how far to extend around known tiles (probably should increase this value up to?
				// dealing with neighbors variance
				clt_parameters.rig.lt_wsigma,              // double      wsigma,     //  = 1.0; // influence of far neighbors diminish as a Gaussian with this sigma
				clt_parameters.rig.lt_max_asigma,          // double      max_asigma, // =             .15;     // Maximal acceptable standard deviation of the neighbors (remove, then add)
				clt_parameters.rig.lt_max_rsigma,          // double      max_rsigma, // =             .05;     // Maximal acceptable standard deviation of the neighbors (remove, then add)
				debugLevel);                               // int         debugLevel


		double [][] disparity_bimap_lt = setBimapFromDisparityNaN(
				suggestedLTMeasurements,      // double []                                      disparity,
				quadCLT_main,         // QuadCLT                                  quadCLT_main,  // tiles should be set
				quadCLT_aux,          // QuadCLT                                  quadCLT_aux,
				clt_parameters,       // EyesisCorrectionParameters.CLTParameters clt_parameters,
				false,                //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				0,                 // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				// first measurement - use default value:
				clt_parameters.rig.no_int_x0,           // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,           // final int        threadsMax,  // maximal number of threads to launch
				updateStatus,         // final boolean    updateStatus,
				debugLevel);          // final int        debugLevel);

		if (clt_parameters.show_map &&  (debugLevel > -2) && clt_parameters.rig.rig_mode_debug){
5886
			(new ShowDoubleFloatArrays()).showArrays(
5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911
					disparity_bimap_lt,
					tilesX,
					disparity_bimap[0].length/tilesX,
					true,
					quadCLT_main.image_name+"NEW_LT_MEASURED",
					ImageDtt.BIDISPARITY_TITLES);
		}

		// refine just the new suggested measurements
		double [][] prev_bimap = null;
		int [] num_new =        new int[1];
		double [] scale_bad = new double [suggestedLTMeasurements.length];
		for (int i = 0; i < scale_bad.length; i++) scale_bad[i] = 1.0;
		prev_bimap = null;
		boolean [] trusted_lt = null;
		for (int nref = 0; nref < clt_parameters.rig.num_near_refine; nref++) {
			// refine infinity using inter correlation
			double [][] disparity_bimap_new =  refineRigSel(
					quadCLT_main,    // QuadCLT                        quadCLT_main,    // tiles should be set
					quadCLT_aux,     // QuadCLT                        quadCLT_aux,
					disparity_bimap_lt, // double [][]                    src_bimap,       // current state of measurements (or null for new measurement)
					prev_bimap,      // double [][]                    prev_bimap, // previous state of measurements or null
					scale_bad,       // double []                      scale_bad,
					refine_inter,    // int                            refine_mode,     // 0 - by main, 1 - by aux, 2 - by inter
					false,           // boolean                        keep_inf,        // keep expected disparity 0.0 if it was so
5912
					0.0,             // double                                         inf_disparity,
5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947
					0.0, // clt_parameters.rig.refine_min_strength , // double refine_min_strength, // do not refine weaker tiles
					clt_parameters.rig.refine_tolerance ,    // double refine_tolerance,    // do not refine if absolute disparity below
					trusted_lt,      // null, // trusted_lt,    // tile_list,       // ArrayList<Integer>             tile_list,       // or null
					num_new,         // int     []                                     num_new,
					clt_parameters,  // EyesisCorrectionParameters.CLTParameters clt_parameters,
					false,           //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
					0,                 // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
					// in refine mode disable int preset of the window
					true,             // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide

					threadsMax,      // final int                      threadsMax,      // maximal number of threads to launch
					updateStatus,    // final boolean                  updateStatus,
					debugLevel);     // final int                      debugLevel);
			prev_bimap = disparity_bimap_lt;
			disparity_bimap_lt = disparity_bimap_new;
			//low texture may have very poor individual correlations, do not check them at all
			trusted_lt = 	getTrustedDisparityInter(
					0.0, // clt_parameters.rig.lt_trusted_strength*clt_parameters.rig.lt_need_friends, // double             min_inter_strength,    // check correlation strength combined for all 3 correlations
					clt_parameters.grow_disp_trust,          // double             max_trusted_disparity,
					trusted_lt, // boolean []         was_trusted,
					disparity_bimap_lt );                       // double [][]        bimap // current state of measurements

			if (debugLevel > -2) {
				System.out.println("enhanceByRig(): refined (lt) "+num_new[0]+" tiles");
			}
			if (num_new[0] < clt_parameters.rig.min_new) break;
		}
		trusted_lt = 	getTrustedDisparityInter(
				clt_parameters.rig.lt_trusted_strength*clt_parameters.rig.lt_need_friends, // double             min_inter_strength,    // check correlation strength combined for all 3 correlations
				clt_parameters.grow_disp_trust,          // double             max_trusted_disparity,
				trusted_lt, // boolean []         was_trusted,
				disparity_bimap_lt );                       // double [][]        bimap // current state of measurements


		if (clt_parameters.show_map &&  (debugLevel > -2) && clt_parameters.rig.rig_mode_debug){
5948
			(new ShowDoubleFloatArrays()).showArrays(
5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970
					disparity_bimap_lt,
					tilesX,
					disparity_bimap[0].length/tilesX,
					true,
					quadCLT_main.image_name+"NEW_LT_REFINED",
					ImageDtt.BIDISPARITY_TITLES);
		}

		// combine new measured results with the previously known (new overwrites old
		for (int nTile = 0; nTile < disparity_bimap_lt[0].length; nTile++) {
			//    		  if (trusted_lt[nTile] &&
			//   				  (!trusted_near[nTile] ||
			//    						  (disparity_bimap_infinity[ImageDtt.BI_STR_ALL_INDEX][nTile] > disparity_bimap[ImageDtt.BI_STR_ALL_INDEX][nTile]))) {
			// start with unconditional use of new
			if (trusted_lt[nTile]) {
				for (int i = 0; i < disparity_bimap.length; i++) if (disparity_bimap!=null) {
					disparity_bimap[i][nTile] = disparity_bimap_lt[i][nTile];
				}
				//    			  trusted_near[nTile] = true;
			}
		}
		if (clt_parameters.show_map &&  (debugLevel > -2) && clt_parameters.rig.rig_mode_debug){
5971
			(new ShowDoubleFloatArrays()).showArrays(
5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987
					disparity_bimap_lt,
					tilesX,
					disparity_bimap[0].length/tilesX,
					true,
					quadCLT_main.image_name+"DSI_ADDED",
					ImageDtt.BIDISPARITY_TITLES);
		}
		return disparity_bimap;
	}




	public void saveMlFile(
			String               ml_title,
			String               ml_directory,
5988 5989 5990 5991 5992 5993 5994
			// new meanings in aux mode:
			// disp_offset_low NaN:
			//   disp_offset_high = 0.0 use average GT disparity
			//   disp_offset_high > 0.0 use FG GT disparity
			//   disp_offset_high < 0.0 use BG GT disparity
			// disp_offset_low != NaN: it is absolute disparity

Andrey Filippov's avatar
Andrey Filippov committed
5995 5996
			double               disp_offset_low,  // NaN - Main camera is used
			double               disp_offset_high, // !NaN and  isNaN(disp_offset_low) - random amplitude: positive - from main, negative - from rig
5997
			QuadCLT              quadCLT_main, // use null for aux mode
5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012
			QuadCLT              quadCLT_aux,
			Correlation2d        corr2d, // to access "other" layer
			boolean              use8bpp,
			double               limit_extrim,
			boolean              keep_aux,
			boolean              keep_inter,
			boolean              keep_hor_vert,
			boolean              ml_keep_tbrl,
			boolean              keep_debug,
			double               ml_fatzero,
			int                  ml_hwidth,
			double [][]          ml_data,
			boolean              show,
			int                  debugLevel
			) {
6013 6014 6015 6016
		final boolean has_main = (quadCLT_main != null);
		final boolean aux_mode = !has_main;
		final int tilesX = (has_main) ? quadCLT_main.tp.getTilesX() : quadCLT_aux.tp.getTilesX();
		final int tilesY = (has_main) ? quadCLT_main.tp.getTilesY() : quadCLT_aux.tp.getTilesY();
6017 6018 6019 6020
		int ml_width = 2 * ml_hwidth + 1;
		int width =  tilesX * ml_width;
		int height = tilesY * ml_width;
		String title = ml_title+ (use8bpp?"08":"32")+"B-"+(keep_aux?"A":"")+(keep_inter?"I":"")+(keep_hor_vert?"O":"")+(ml_keep_tbrl?"T":"")+
6021
				(keep_debug?"D":"")+"-FZ"+ml_fatzero;
6022 6023 6024 6025 6026 6027 6028 6029 6030
		if (aux_mode) {
			if (!Double.isNaN(disp_offset_low)) {
				title += "-D" + String.format("%08.5f",disp_offset_low).trim(); // absolute disparity
			} else if (disp_offset_high > 0.0){ // foreground ground truth disparity
				title += "-FG";
			} else if (disp_offset_high < 0.0){ // background ground truth disparity
				title += "-BG";
			} else { // average ground truth disparity
				title += "-AG";
6031
			}
6032
		} else {
6033 6034 6035 6036 6037 6038
			if (!Double.isNaN(disp_offset_low)) {
				title += "-OFFS" + String.format("%08.5f",disp_offset_low).trim();
				if (disp_offset_high > disp_offset_low) {
					title+="_";
					title+=String.format("%08.5f",disp_offset_high).trim();
				}
Andrey Filippov's avatar
Andrey Filippov committed
6039
			} else {
6040 6041
				if (Double.isNaN(disp_offset_high)) {
					title += "-MAIN";
Andrey Filippov's avatar
Andrey Filippov committed
6042
				} else {
6043 6044 6045 6046 6047 6048 6049 6050
					if (disp_offset_high > 0) {
						title += "-MAIN_RND";
						title+=String.format("%08.5f",disp_offset_high).trim();
					} else {
						disp_offset_high = -disp_offset_high;
						title+="-RIG_RND";
						title+=String.format("%08.5f",disp_offset_high).trim();
					}
Andrey Filippov's avatar
Andrey Filippov committed
6051 6052
				}
			}
6053
		}
6054 6055 6056 6057 6058 6059 6060 6061 6062 6063
		int [] main_indices = {
				ImageDtt.ML_TOP_INDEX,    // 8 - top pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_BOTTOM_INDEX, // 9 - bottom pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_LEFT_INDEX,   //10 - left pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_RIGHT_INDEX,  //11 - right pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_DIAGM_INDEX,  //12 - main diagonal (top-left to bottom-right) pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_DIAGO_INDEX,  //13 - other diagonal (bottom-left to top-right) pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_HOR_INDEX,    //14 - horizontal pairs combined 2d correlation center area (auxiliary camera)
				ImageDtt.ML_VERT_INDEX    //15 - vertical pairs combined 2d correlation center area (auxiliary camera)
		};
6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102
		int [] aux_indices = {
				ImageDtt.ML_TOP_AUX_INDEX,    // 8 - top pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_BOTTOM_AUX_INDEX, // 9 - bottom pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_LEFT_AUX_INDEX,   //10 - left pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_RIGHT_AUX_INDEX,  //11 - right pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_DIAGM_AUX_INDEX,  //12 - main diagonal (top-left to bottom-right) pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_DIAGO_AUX_INDEX,  //13 - other diagonal (bottom-left to top-right) pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_HOR_AUX_INDEX,    //14 - horizontal pairs combined 2d correlation center area (auxiliary camera)
				ImageDtt.ML_VERT_AUX_INDEX    //15 - vertical pairs combined 2d correlation center area (auxiliary camera)
		};
		int [] inter_indices = {
				ImageDtt.ML_INTER_INDEX       //16 - inter-camera (between two quad ones) correlation center area
		};
		int [] hor_vert_indices = {
				ImageDtt.ML_HOR_INDEX,        // 6 - horizontal pairs combined 2d correlation center area
				ImageDtt.ML_VERT_INDEX,       // 7 - vertical pairs combined 2d correlation center area
				ImageDtt.ML_HOR_AUX_INDEX,    //14 - horizontal pairs combined 2d correlation center area (auxiliary camera)
				ImageDtt.ML_VERT_AUX_INDEX    //15 - vertical pairs combined 2d correlation center area (auxiliary camera)
		};

		int [] tbrl_indices = {
				ImageDtt.ML_TOP_INDEX,        // 0 - top pair 2d correlation center area
				ImageDtt.ML_BOTTOM_INDEX,     // 1 - bottom pair 2d correlation center area
				ImageDtt.ML_LEFT_INDEX,       // 2 - left pair 2d correlation center area
				ImageDtt.ML_RIGHT_INDEX,      // 3 - right pair 2d correlation center area
				ImageDtt.ML_TOP_AUX_INDEX,    // 8 - top pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_BOTTOM_AUX_INDEX, // 9 - bottom pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_LEFT_AUX_INDEX,   //10 - left pair 2d correlation center area (auxiliary camera)
				ImageDtt.ML_RIGHT_AUX_INDEX   //11 - right pair 2d correlation center area (auxiliary camera)
		};
		int [] dbg_indices = {
				ImageDtt.ML_DBG1_INDEX        //18 - just debug data (first - auto phase correlation)
		};
		int [] non_corr_indices = {
				ImageDtt.ML_OTHER_INDEX,      //17 - other data: 0 (top left tile corner) - preset disparity of the tile, 1: (next element) - ground trouth data, 2:
				ImageDtt.ML_DBG1_INDEX        //18 - just debug data (first - auto phase correlation)
		};

		boolean [] skip_layers = new boolean [ImageDtt.ML_TITLES.length];
6103
		if (!has_main)       for (int nl:main_indices)     skip_layers[nl] = true;
6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166
		if (!keep_aux)       for (int nl:aux_indices)      skip_layers[nl] = true;
		if (!keep_inter)     for (int nl:inter_indices)    skip_layers[nl] = true;
		if (!keep_hor_vert)  for (int nl:hor_vert_indices) skip_layers[nl] = true;
		if (!ml_keep_tbrl)   for (int nl:tbrl_indices)     skip_layers[nl] = true;

		if (!keep_debug)     for (int nl:dbg_indices)      skip_layers[nl] = true;

		ImageStack array_stack=new ImageStack(width,height);
		double soft_mn = Double.NaN,soft_mx = Double.NaN;
		if (use8bpp) {
			int num_bins = 256;
			boolean [] skip_histogram =   skip_layers.clone();
			for (int nl:non_corr_indices) skip_histogram[nl] = true;
			double mn = 0.0, mx = 0.0; // data has both positive and negative values
			for (int nl = 0; nl < ml_data.length; nl++) if (!skip_histogram[nl]) {
				for (int i = 0; i < ml_data[nl].length; i++) if (!Double.isNaN(ml_data[nl][i])){
					if      (ml_data[nl][i] > mx) mx = ml_data[nl][i];
					else if (ml_data[nl][i] < mn) mn = ml_data[nl][i];
				}
			}
			if (debugLevel > -2) {
				System.out.println("saveMlFile(): min="+mn+", max="+mx);
			}
			int [] histogram = new int [num_bins];
			int num_values = 0;
			for (int nl = 0; nl < ml_data.length; nl++) if (!skip_histogram[nl]) {
				for (int i = 0; i < ml_data[nl].length; i++) if (!Double.isNaN(ml_data[nl][i])){
					int bin = (int) Math.round(num_bins*(ml_data[nl][i] - mn)/(mx-mn));
					// rounding errors?
					if (bin < 0) bin = 0;
					else if (bin >= num_bins) bin = num_bins-1;
					histogram[bin]++;
					num_values++;
				}
			}
			double ignore_vals = limit_extrim*num_values;
			soft_mn = mn;
			soft_mx = mx;
			{
				double sl = 0.0;
				int i = 0;
				while (sl < ignore_vals) {
					i++;
					sl+= histogram[i];
					soft_mn += (mx-mn)/num_bins;
				}
				double f = (sl - ignore_vals)/histogram[i];
				soft_mn -= (mx-mn)/num_bins*(1.0 - f);

				sl = 0.0;
				i = num_bins-1;
				while (sl < ignore_vals) {
					i--;
					sl+= histogram[i];
					soft_mx -= (mx-mn)/num_bins;
				}
				f = (sl - ignore_vals)/histogram[i];
				soft_mn += (mx-mn)/num_bins*(1.0 - f);
				if (debugLevel > -2) {
					System.out.println("saveMlFile(): soft min="+soft_mn+", soft max="+soft_mx);
				}
			}
			// convert double data  to byte, so v<=soft_mn -> 1; v>= soft_mx -> 255, NaN -> 0
6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179
			int [] signed_data = {
					ImageDtt.ML_OTHER_TARGET,
					ImageDtt.ML_OTHER_GTRUTH,
					ImageDtt.ML_OTHER_GTRUTH_FG_DISP,
					ImageDtt.ML_OTHER_GTRUTH_BG_DISP,
					ImageDtt.ML_OTHER_AUX_DISP};
			int [] unsigned_data = {
					ImageDtt.ML_OTHER_GTRUTH_STRENGTH,
					ImageDtt.ML_OTHER_GTRUTH_RMS,
					ImageDtt.ML_OTHER_GTRUTH_RMS_SPLIT,
					ImageDtt.ML_OTHER_GTRUTH_FG_STR,
					ImageDtt.ML_OTHER_GTRUTH_BG_STR,
					ImageDtt.ML_OTHER_AUX_STR};
6180 6181 6182 6183 6184 6185 6186
			byte [][] iml_data = new byte [ml_data.length][];
			for (int nl = 0; nl < ml_data.length; nl++) if (!skip_layers[nl]) {
				iml_data[nl] = new byte [ml_data[nl].length];
				if (nl == ImageDtt.ML_OTHER_INDEX) {
					// special treatment - make 2 bytes of one disparity value
					for (int tileY = 0; tileY < tilesY; tileY++) {
						for (int tileX = 0; tileX < tilesX; tileX++) {
6187
							/*
6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233
							double target_disparity = corr2d.restoreMlTilePixel(
									tileX,                            // int         tileX,
									tileY,                            // int         tileY,
									ml_hwidth,                        // int         ml_hwidth,
									ml_data,                          // double [][] ml_data,
									ImageDtt.ML_OTHER_INDEX,          // int         ml_layer,
									ImageDtt.ML_OTHER_TARGET ,        // int         ml_index,
									tilesX);                          // int         tilesX);
							double gtruth_disparity = corr2d.restoreMlTilePixel(
									tileX,                            // int         tileX,
									tileY,                            // int         tileY,
									ml_hwidth,                        // int         ml_hwidth,
									ml_data,                          // double [][] ml_data,
									ImageDtt.ML_OTHER_INDEX,          // int         ml_layer,
									ImageDtt.ML_OTHER_GTRUTH ,        // int         ml_index,
									tilesX);                          // int         tilesX);
							double gtruth_strength = corr2d.restoreMlTilePixel(
									tileX,                            // int         tileX,
									tileY,                            // int         tileY,
									ml_hwidth,                        // int         ml_hwidth,
									ml_data,                          // double [][] ml_data,
									ImageDtt.ML_OTHER_INDEX,          // int         ml_layer,
									ImageDtt.ML_OTHER_GTRUTH_STRENGTH ,     // int         ml_index,
									tilesX);                          // int         tilesX);
							// converting disparity to 9.7 ( 1/128 pixel step, +/-256 pixels disparity range), 0x8000 - zero disparity
							// converting strength to 2 bytes 0.16 fixed point
							int itd = (int) Math.round(128 * target_disparity) + 0x8000;
							int [] itarget_disparity = {itd >> 8, itd & 0xff};
							int igt = (int) Math.round(128 * gtruth_disparity) + 0x8000;
							int [] igtruth_disparity = {igt >> 8, igt & 0xff};
							int igs = (int) Math.round(0x10000 * gtruth_strength);
							int [] igtruth_strength =  {igs >> 8, igs & 0xff};
							for (int nb = 0; nb<2; nb++) {
								if (!Double.isNaN(target_disparity)) {
									int indx =  corr2d.getMlTilePixelIndex(tileX,tileY, ml_hwidth, ImageDtt.ML_OTHER_TARGET + nb, tilesX);
									iml_data[nl][indx] = (byte) itarget_disparity[nb];
								}
								if (!Double.isNaN(gtruth_disparity)) {
									int indx =  corr2d.getMlTilePixelIndex(tileX,tileY, ml_hwidth, ImageDtt.ML_OTHER_GTRUTH + nb, tilesX);
									iml_data[nl][indx] = (byte) igtruth_disparity[nb];
								}
								if (gtruth_strength > 0.0) {
									int indx =  corr2d.getMlTilePixelIndex(tileX,tileY, ml_hwidth, ImageDtt.ML_OTHER_GTRUTH_STRENGTH + nb, tilesX);
									iml_data[nl][indx] = (byte) igtruth_strength[nb];
								}
							}
6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274
							*/
							for (int data:signed_data) if (aux_mode || (data <= ImageDtt.ML_OTHER_GTRUTH_STRENGTH)) {
								double d =  corr2d.restoreMlTilePixel(
										tileX,                            // int         tileX,
										tileY,                            // int         tileY,
										ml_hwidth,                        // int         ml_hwidth,
										ml_data,                          // double [][] ml_data,
										ImageDtt.ML_OTHER_INDEX,          // int         ml_layer,
										data ,                           // int         ml_index,
										tilesX);                          // int         tilesX);
								if (!Double.isNaN(d)) {
									int id = (int) Math.round(128 * d) + 0x8000;
									int [] ida = {id >> 8, id & 0xff};
									for (int nb = 0; nb<2; nb++) {
										int indx =  corr2d.getMlTilePixelIndex(tileX,tileY, ml_hwidth, data + nb, tilesX);
										iml_data[nl][indx] = (byte) ida[nb];
									}
								}
							}
							for (int data:unsigned_data) if (aux_mode || (data <= ImageDtt.ML_OTHER_GTRUTH_STRENGTH)) {
								double d =  corr2d.restoreMlTilePixel(
										tileX,                            // int         tileX,
										tileY,                            // int         tileY,
										ml_hwidth,                        // int         ml_hwidth,
										ml_data,                          // double [][] ml_data,
										ImageDtt.ML_OTHER_INDEX,          // int         ml_layer,
										data ,                           // int         ml_index,
										tilesX);                          // int         tilesX);
								if (!Double.isNaN(d) && (d > 0.0)) {
									int iscale = 0x10000;
									if ((data == ImageDtt.ML_OTHER_GTRUTH_RMS) || (data == ImageDtt.ML_OTHER_GTRUTH_RMS_SPLIT)) {
										iscale = 0x1000;
									}
									int id = (int) Math.round(iscale * d);
									int [] ida = {id >> 8, id & 0xff};
									for (int nb = 0; nb<2; nb++) {
										int indx =  corr2d.getMlTilePixelIndex(tileX,tileY, ml_hwidth, data + nb, tilesX);
										iml_data[nl][indx] = (byte) ida[nb];
									}
								}
							}
6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285
						}
					}
				} else {
					double k = 254.0/(soft_mx-soft_mn);
					for (int i = 0; i < ml_data[nl].length;i++) {
						if (Double.isNaN(ml_data[nl][i])){
							iml_data[nl][i] = 0; // -128;
						} else {
							int iv = (int) Math.round(k*(ml_data[nl][i]-soft_mn));
							if      (iv < 0) iv = 0;
							else if (iv > 254) iv = 254;
6286
							iml_data[nl][i] = (byte) (iv + 1); //  (iv - 127); // NaN will stay 0;
6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302
						}
					}
				}
			}
			for (int nl = 0; nl< ml_data.length; nl++) if (!skip_layers[nl]) {
				array_stack.addSlice(ImageDtt.ML_TITLES[nl], iml_data[nl]);
			}
		} else {
			float [] fpixels;
			for (int nl = 0; nl< ml_data.length; nl++) if (!skip_layers[nl]) {
				fpixels=new float[ml_data[nl].length];
				for (int j=0;j<fpixels.length;j++) fpixels[j]=(float) ml_data[nl][j];
				array_stack.addSlice(ImageDtt.ML_TITLES[nl],    fpixels);
			}
		}

6303
		double disparityRadiusMain =  has_main ? quadCLT_main.geometryCorrection.getDisparityRadius():Double.NaN;
6304
		double disparityRadiusAux =   quadCLT_aux.geometryCorrection.getDisparityRadius();
6305
		double intercameraBaseline =  has_main ? quadCLT_aux.geometryCorrection.getBaseline():Double.NaN;
6306 6307

		ImagePlus imp_ml = new ImagePlus(title, array_stack);
6308
		imp_ml.setProperty("VERSION",  "1.2");
6309
		imp_ml.setProperty("tileWidth",   ""+ml_width);
6310 6311 6312 6313 6314
		imp_ml.setProperty("dispOffset",  ""+disp_offset_low);
		if (disp_offset_high>disp_offset_low) {
			imp_ml.setProperty("dispOffsetLow",  ""+disp_offset_low);
			imp_ml.setProperty("dispOffsetHigh",  ""+disp_offset_high);
		}
6315 6316
		imp_ml.setProperty("ML_OTHER_TARGET",           ""+ImageDtt.ML_OTHER_TARGET);
		imp_ml.setProperty("ML_OTHER_GTRUTH",           ""+ImageDtt.ML_OTHER_GTRUTH);
6317
		imp_ml.setProperty("ML_OTHER_GTRUTH_STRENGTH",  ""+ImageDtt.ML_OTHER_GTRUTH_STRENGTH);
6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331
		if (aux_mode) {
			imp_ml.setProperty("ML_OTHER_GTRUTH_RMS",       ImageDtt.ML_OTHER_GTRUTH_RMS);
			imp_ml.setProperty("ML_OTHER_GTRUTH_RMS_SPLIT", ImageDtt.ML_OTHER_GTRUTH_RMS_SPLIT);
			imp_ml.setProperty("ML_OTHER_GTRUTH_FG_DISP",   ImageDtt.ML_OTHER_GTRUTH_FG_DISP);
			imp_ml.setProperty("ML_OTHER_GTRUTH_FG_STR",    ImageDtt.ML_OTHER_GTRUTH_FG_STR);
			imp_ml.setProperty("ML_OTHER_GTRUTH_BG_DISP",   ImageDtt.ML_OTHER_GTRUTH_BG_DISP);
			imp_ml.setProperty("ML_OTHER_GTRUTH_BG_STR",    ImageDtt.ML_OTHER_GTRUTH_BG_STR);
			imp_ml.setProperty("ML_OTHER_AUX_DISP",         ImageDtt.ML_OTHER_AUX_DISP);
			imp_ml.setProperty("ML_OTHER_AUX_STR",          ImageDtt.ML_OTHER_AUX_STR);
		}
		if (has_main) {
			imp_ml.setProperty("disparityRadiusMain",  ""+disparityRadiusMain);
			imp_ml.setProperty("intercameraBaseline",  ""+intercameraBaseline);
		}
6332
		imp_ml.setProperty("disparityRadiusAux",  ""+disparityRadiusAux);
6333 6334 6335 6336
		if (use8bpp) {
			imp_ml.setProperty("data_min",  ""+soft_mn);
			imp_ml.setProperty("data_max",  ""+soft_mx);
		}
6337 6338

		imp_ml.setProperty("comment_tileWidth",   "Square tile size for each 2d correlation, always odd");
6339 6340 6341 6342 6343
		imp_ml.setProperty("comment_dispOffset",  "Tile target disparity minus ground truth disparity");
		if (disp_offset_high>disp_offset_low) {
			imp_ml.setProperty("comment_dispOffsetLow",  "Tile target disparity minus ground truth disparity, low margin for random distribution");
			imp_ml.setProperty("comment_dispOffsetHigh", "Tile target disparity minus ground truth disparity, high margin for random distribution");
		}
6344 6345 6346
		imp_ml.setProperty("comment_ML_OTHER_TARGET",  "Offset of the target disparity in the \"other\" layer tile");
		imp_ml.setProperty("comment_ML_OTHER_GTRUTH",  "Offset of the ground truth disparity in the \"other\" layer tile");
		imp_ml.setProperty("comment_ML_OTHER_GTRUTH_STRENGTH",  "Offset of the ground truth strength in the \"other\" layer tile");
6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362
		if (aux_mode) {
			imp_ml.setProperty("comment_ML_OTHER_GTRUTH_RMS","Offset of the GT disparity RMS");
			imp_ml.setProperty("comment_ML_OTHER_GTRUTH_RMS_SPLIT", "Offset of the GT disparity RMS combined from FG and BG");
			imp_ml.setProperty("comment_ML_OTHER_GTRUTH_FG_DISP", "Offset of the GT FG disparity");
			imp_ml.setProperty("comment_ML_OTHER_GTRUTH_FG_STR", "Offset of the GT FG strength");
			imp_ml.setProperty("comment_ML_OTHER_GTRUTH_BG_DISP", "Offset of the GT BG disparity");
			imp_ml.setProperty("comment_ML_OTHER_GTRUTH_BG_STR", "Offset of the GT BG strength");
		}
		if (use8bpp) {
			imp_ml.setProperty("comment_data_min",  "Defined only for 8bpp mode - value, corresponding to -127 (-128 is NaN)");
			imp_ml.setProperty("comment_data_max",  "Defined only for 8bpp mode - value, corresponding to +127 (-128 is NaN)");
		}
		if (has_main) {
			imp_ml.setProperty("comment_disparityRadiusMain",  "Side of the square where 4 main camera subcameras are located (mm)");
			imp_ml.setProperty("comment_intercameraBaseline",  "Horizontal distance between the main and the auxiliary camera centers (mm). Disparity is specified for the main camera");
		}
6363
		imp_ml.setProperty("comment_disparityRadiusAux",  "Side of the square where 4 main camera subcameras are located (mm). Disparity is specified for the main camera");
6364

6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401
		(new JP46_Reader_camera(false)).encodeProperiesToInfo(imp_ml);
		imp_ml.getProcessor().resetMinAndMax();
		if (show ) {
			imp_ml.show();
		}
		File dir = new File(ml_directory);
		if (!dir.exists()){
			dir.mkdirs();
			System.out.println("Created "+dir);
		}

		String path = ml_directory+=Prefs.getFileSeparator()+imp_ml.getTitle();
		FileSaver fs=new FileSaver(imp_ml);
		fs.saveAsTiff(path+".tiff");
		if (debugLevel > -4) {
			System.out.println("Saved ML data to "+path+".tiff");
		}
	}



	/**
	 * Get disparity from the DSI data of the main camera and re-measure with the rig
	 * @param scan - main camera DSI scan to get initial disparity and selection from
	 * @param quadCLT_main main camera QuadCLT instance (should have tp initialized)
	 * @param quadCLT_aux auxiliary camera QuadCLT instance (should have tp initialized)
	 * @param clt_parameters various configuration parameters
	 * @param threadsMax maximal number of threads to use
	 * @param updateStatus update IJ status bar
	 * @param debugLevel debug level
	 * @return rig measurement results
	 */

	public double [][] setBimapFromCLTPass3d(
			CLTPass3d                                      scan,
			QuadCLT                                        quadCLT_main,  // tiles should be set
			QuadCLT                                        quadCLT_aux,
6402
			CLTParameters       clt_parameters,
6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel){
		int tile_op_all = clt_parameters.tile_task_op; //FIXME Use some constant?
		final int tilesX = quadCLT_main.tp.getTilesX();
		final int tilesY = quadCLT_main.tp.getTilesY();
		int [][]                                           tile_op = new int[tilesY][tilesX]; // common for both amin and aux
		double [][]                                        disparity_array = new double[tilesY][tilesX];

		double [] disparity =    scan.getDisparity();
		double [] strength =     scan.getOriginalStrength();
		//		  boolean [] selection =   scan.getSelected();
		boolean [] selection =   new boolean [strength.length];
		for (int nTile = 0; nTile < selection.length; nTile++) {
			selection[nTile] = strength[nTile] > 0.0;
		}

		for (int nTile = 0; nTile < disparity.length; nTile++) {
			if (((selection == null) || (selection[nTile]) && !Double.isNaN(disparity[nTile]))) {
				int tileY = nTile / tilesX;
				int tileX = nTile % tilesX;
				tile_op[tileY][tileX] = tile_op_all;
				disparity_array[tileY][tileX] = disparity[nTile];
			}
		}
		double [][] disparity_bimap = measureRig(
				quadCLT_main,    // QuadCLT                                  quadCLT_main,  // tiles should be set
				quadCLT_aux,     //QuadCLT                                   quadCLT_aux,
				tile_op,         // int [][]                                 tile_op, // common for both amin and aux
				disparity_array, // double [][]                              disparity_array,
				null, // double [][]                                    ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				clt_parameters,  // EyesisCorrectionParameters.CLTParameters clt_parameters,
6435
				clt_parameters.getFatZero(quadCLT_main.isMonochrome()), // double                                         fatzero,
6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461
				false,                   //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				0,                          // final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				clt_parameters.rig.no_int_x0, // final boolean             no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very
				threadsMax,      // final int        threadsMax,  // maximal number of threads to launch
				updateStatus,    // final boolean    updateStatus,
				debugLevel);     // final int        debugLevel);

		return disparity_bimap;
	}

	/**
	 * Perform rig measurement from the new predicted disparity values
	 * @param disparity array of predicted disparities, NaN - do not measure
	 * @param quadCLT_main main camera QuadCLT instance (should have tp initialized)
	 * @param quadCLT_aux auxiliary camera QuadCLT instance (should have tp initialized)
	 * @param clt_parameters various configuration parameters
	 * @param threadsMax maximal number of threads to use
	 * @param updateStatus update IJ status bar
	 * @param debugLevel debug level
	 * @return rig measurement results
	 */

	public double [][] setBimapFromDisparityNaN(
			double []                                      disparity,
			QuadCLT                                        quadCLT_main,  // tiles should be set
			QuadCLT                                        quadCLT_aux,
6462
			CLTParameters       clt_parameters,
6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490
			boolean                                        notch_mode,      // use notch filter for inter-camera correlation to detect poles
			int                                            lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
			boolean                                        no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel){
		int tile_op_all = clt_parameters.tile_task_op; //FIXME Use some constant?
		final int tilesX = quadCLT_main.tp.getTilesX();
		final int tilesY = quadCLT_main.tp.getTilesY();
		int [][]                                           tile_op = new int[tilesY][tilesX]; // common for both amin and aux
		double [][]                                        disparity_array = new double[tilesY][tilesX];


		for (int nTile = 0; nTile < disparity.length; nTile++) {
			if (!Double.isNaN(disparity[nTile])) {
				int tileY = nTile / tilesX;
				int tileX = nTile % tilesX;
				tile_op[tileY][tileX] = tile_op_all;
				disparity_array[tileY][tileX] = disparity[nTile];
			}
		}
		double [][] disparity_bimap = measureRig(
				quadCLT_main,    // QuadCLT                                  quadCLT_main,  // tiles should be set
				quadCLT_aux,     //QuadCLT                                   quadCLT_aux,
				tile_op,         // int [][]                                 tile_op, // common for both amin and aux
				disparity_array, // double [][]                              disparity_array,
				null, // double [][]                                    ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				clt_parameters,  // EyesisCorrectionParameters.CLTParameters clt_parameters,
6491
				clt_parameters.getFatZero(quadCLT_main.isMonochrome()), // double                                         fatzero,
6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577
				notch_mode,                          //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_rad,                               // final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				no_int_x0,       // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,      // final int        threadsMax,  // maximal number of threads to launch
				updateStatus,    // final boolean    updateStatus,
				debugLevel);     // final int        debugLevel);

		return disparity_bimap;
	}

	/**
	 * Select tiles that have small enough residual disparity to trust on each of the two cameras and the whole rig.
	 * @param quadCLT_main main camera QuadCLT instance (should have tp initialized)
	 * @param quadCLT_aux auxiliary camera QuadCLT instance (should have tp initialized)
	 * @param min_combo_strength minimal combined correlation strength for each camera and the rig
	 * @param max_trusted_disparity maximal disparity on a rig to trust (currently 4.0 pixels from zero each way)
	 * @param trusted_tolerance allow other cameras with scaled disparity if their disparity is under this value (for small baselines)
	 * @param bimap measured data
	 * @return per-tile array of trusted tiles
	 */
	boolean [] getTrustedDisparity(
			QuadCLT            quadCLT_main,  // tiles should be set
			QuadCLT            quadCLT_aux,
			boolean            use_individual,
			double             min_combo_strength,    // check correlation strength combined for all 3 correlations
			double             max_trusted_disparity,
			double             trusted_tolerance,
			boolean []         was_trusted,
			double [][]        bimap // current state of measurements
			) {
		double trusted_inter =    max_trusted_disparity;
		double trusted_main =     trusted_inter * quadCLT_main.geometryCorrection.getDisparityRadius()/quadCLT_aux.geometryCorrection.getBaseline();
		double trusted_aux =      trusted_inter * quadCLT_aux.geometryCorrection.getDisparityRadius()/quadCLT_aux.geometryCorrection.getBaseline();
		if (trusted_main < trusted_tolerance) trusted_main = trusted_tolerance;
		if (trusted_aux  < trusted_tolerance) trusted_aux =  trusted_tolerance;
		boolean [] trusted = new boolean [bimap[ImageDtt.BI_DISP_CROSS_INDEX].length];
		if (use_individual) {
			for (int i = 0; i < trusted.length; i++) {
				trusted[i] = (Math.abs(bimap[ImageDtt.BI_DISP_CROSS_INDEX][i]) <= trusted_inter) &&
						(Math.abs(bimap[ImageDtt.BI_DISP_FULL_INDEX][i])  <= trusted_main) &&
						(Math.abs(bimap[ImageDtt.BI_ADISP_FULL_INDEX][i]) <= trusted_aux) &&
						(bimap[ImageDtt.BI_STR_ALL_INDEX][i]              >= min_combo_strength) &&
						((was_trusted == null) || was_trusted[i]);
			}
		} else {
			for (int i = 0; i < trusted.length; i++) {
				trusted[i] = (Math.abs(bimap[ImageDtt.BI_DISP_CROSS_INDEX][i]) <= trusted_inter) &&
						(bimap[ImageDtt.BI_STR_CROSS_INDEX][i]                 >= min_combo_strength) &&
						((was_trusted == null) || was_trusted[i]);
			}
		}
		return trusted;
	}
	/**
	 * Select tiles that have small enough residual disparity and sufficient strength to trust for the whole rig only
	 * @param min_inter_strength minimal inter-camera correlation strength
	 * @param max_trusted_disparity maximal disparity on a rig to trust (currently 4.0 pixels from zero each way)
	 * @param bimap measured data
	 * @return per-tile array of trusted tiles
	 */
	boolean [] getTrustedDisparityInter(
			double             min_inter_strength,    // check correlation strength combined for all 3 correlations
			double             max_trusted_disparity,
			boolean []         was_trusted,
			double [][]        bimap // current state of measurements
			) {
		double trusted_inter =    max_trusted_disparity;
		boolean [] trusted = new boolean [bimap[ImageDtt.BI_DISP_CROSS_INDEX].length];
		for (int i = 0; i < trusted.length; i++) {
			trusted[i] = (Math.abs(bimap[ImageDtt.BI_DISP_CROSS_INDEX][i]) <= trusted_inter) &&
					(bimap[ImageDtt.BI_STR_CROSS_INDEX][i]              >= min_inter_strength) &&
					((was_trusted == null) || was_trusted[i]);
		}
		return trusted;
	}

	/**
	 * Refine (re-measure with updated expected disparity) tiles. If refine_min_strength and refine_tolerance are both
	 * set to 0.0, all (or listed) tiles will be re-measured, use camera after extrinsics are changed
	 * With refine_min_strength == 0, will re-measure infinity (have keep_inf == true)
	 * @param quadCLT_main main camera QuadCLT instance (should have tp initialized)
	 * @param quadCLT_aux auxiliary camera QuadCLT instance (should have tp initialized)
	 * @param src_bimap results of the older measurements (now includes expected disparity)
	 * @param prev_bimap results of the even older measurements to interpolate if there was an overshoot
	 * @param refine_mode reference camera data: 0 - main camera, 1 - aux camera, 2 - cross-camera
	 * @param keep_inf do not refine expected disparity for infinity, unless  refine_min_strength == 0
6578
	 * @param inf_sel if not null - selects "infinity" tiles that shoild not be remeasured
6579 6580 6581 6582 6583 6584 6585 6586 6587 6588
	 * @param refine_min_strength do not refine weaker tiles
	 * @param refine_tolerance do not refine if residual disparity (after FD pre-shift by expected disparity) less than this
	 * @param tile_list list of selected tiles or null. If null - try to refine all tiles, otherwise - only listed tiles
	 * @param num_new - otional int [1] to return number of new tiles
	 * @param clt_parameters various configuration parameters
	 * @param threadsMax maximal number of threads to use
	 * @param updateStatus update IJ status bar
	 * @param debugLevel debug level
	 * @return results of the new measurements combined with the old results
	 */
6589

6590 6591 6592 6593 6594 6595 6596 6597
	public double [][] refineRig(
			QuadCLT                                  quadCLT_main,  // tiles should be set
			QuadCLT                                  quadCLT_aux,
			double [][]                              src_bimap, // current state of measurements
			double [][]                              prev_bimap, // previous state of measurements or null
			double []                                scale_bad,
			int                                      refine_mode, // 0 - by main, 1 - by aux, 2 - by inter
			boolean                                  keep_inf,    // keep expected disparity 0.0 if it was so
6598
			double                                   inf_disparity,
6599 6600 6601 6602
			double                                   refine_min_strength, // do not refine weaker tiles
			double                                   refine_tolerance,    // do not refine if absolute disparity below
			ArrayList<Integer>                       tile_list, // or null
			int     []                               num_new,
6603
			CLTParameters clt_parameters,
6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622
			boolean                                  notch_mode,      // use notch filter for inter-camera correlation to detect poles
			int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
			final boolean                            no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
			final int                                threadsMax,  // maximal number of threads to launch
			final boolean                            updateStatus,
			final int                                debugLevel){
		boolean [] selection = null;
		if (tile_list != null) {
			selection = new boolean [quadCLT_main.tp.getTilesX() * quadCLT_main.tp.getTilesY()];
			for (int nTile:tile_list) selection[nTile] = true;
		}
		return refineRigSel(
				quadCLT_main,  // tiles should be set
				quadCLT_aux,
				src_bimap, // current state of measurements
				prev_bimap, // previous state of measurements or null
				scale_bad,  //
				refine_mode, // 0 - by main, 1 - by aux, 2 - by inter
				keep_inf,    // keep expected disparity 0.0 if it was so
6623
				inf_disparity, // double                                   inf_disparity,
6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644
				refine_min_strength, // do not refine weaker tiles
				refine_tolerance,    // do not refine if absolute disparity below
				selection,
				num_new,
				clt_parameters,
				notch_mode,                          //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_rad,                              // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				no_int_x0,           // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,  // maximal number of threads to launch
				updateStatus,
				debugLevel);
	}

	public double [][] refineRigSel(
			QuadCLT                                        quadCLT_main,  // tiles should be set
			QuadCLT                                        quadCLT_aux,
			double [][]                                    src_bimap, // current state of measurements
			double [][]                                    prev_bimap, // previous state of measurements or null
			double []                                      scale_bad,
			int                                            refine_mode, // 0 - by main, 1 - by aux, 2 - by inter
			boolean                                        keep_inf,    // keep expected disparity 0.0 if it was so
6645
			double                                         inf_disparity,
6646 6647 6648 6649
			double                                         refine_min_strength, // do not refine weaker tiles
			double                                         refine_tolerance,    // do not refine if absolute disparity below
			boolean []                                     selection,
			int     []                                     num_new,
6650
			CLTParameters       clt_parameters,
6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680
			final boolean                                  notch_mode,      // use notch filter for inter-camera correlation to detect poles
			final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
			final boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel){
		int tilesX =quadCLT_main.tp.getTilesX();
		int tilesY =quadCLT_main.tp.getTilesY();
		int [][] tile_op = new int [tilesY][tilesX];
		double [][] disparity_array = new double [tilesY][tilesX];
		double disp_scale_main =  1.0/clt_parameters.corr_magic_scale; // Is it needed?
		double disp_scale_aux =   disp_scale_main * quadCLT_main.geometryCorrection.getDisparityRadius()/quadCLT_aux.geometryCorrection.getDisparityRadius();
		double disp_scale_inter = disp_scale_main * quadCLT_main.geometryCorrection.getDisparityRadius()/quadCLT_aux.geometryCorrection.getBaseline();
		int tile_op_all = clt_parameters.tile_task_op; //FIXME Use some constant?
		int numMeas = 0;
		for (int tileY = 0; tileY<tilesY;tileY++) {
			for (int tileX = 0; tileX<tilesX;tileX++) {
				int nTile = tileY * tilesX + tileX;
				if (((selection == null) || selection[nTile]) && !Double.isNaN(src_bimap[ImageDtt.BI_TARGET_INDEX][nTile])) {
					if (prepRefineTile(
							(lt_rad > 0),
							clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
							tile_op_all,    // int                                            tile_op_all,
							src_bimap, // double [][]                                     src_bimap, // current state of measurements
							prev_bimap, // double [][]                                    prev_bimap, // previous state of measurements or null
							scale_bad,  // double []                                      scale_bad,
							tile_op, // int [][]                                          tile_op, // common for both amin and aux
							disparity_array, // double [][]                                    disparity_array,
							refine_mode, // int                                            refine_mode, // 0 - by main, 1 - by aux, 2 - by inter
							keep_inf,    // boolean                                        keep_inf,    // keep expected disparity 0.0 if it was so
6681
							inf_disparity, // double                                         inf_disparity,
6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703
							refine_min_strength, // double                                         refine_min_strength, // do not refine weaker tiles
							refine_tolerance,    // double                                         refine_tolerance,    // do not refine if absolute disparity below
							disp_scale_main,  // double                                         disp_scale_main,  // 1.0
							disp_scale_aux,   //double                                         disp_scale_aux,   // ~0.58
							disp_scale_inter, //double                                         disp_scale_inter, // ~4.86
							//								  scale_step,       // double                                         scale_step,  // scale for "unstable tiles"
							tileX, // int                                            tileX,
							tileY, // int                                            tileY,
							nTile )) numMeas++; //int                                            nTile
				}
			}
		}
		if (debugLevel >0) {
			System.out.println("refineRig() mode="+refine_mode+": Prepared "+numMeas+" to measure");
		}
		double [][] disparity_bimap  =  measureRig(
				quadCLT_main,        // QuadCLT                                        quadCLT_main,  // tiles should be set
				quadCLT_aux,         // QuadCLT                                        quadCLT_aux,
				tile_op,             // int [][]                                       tile_op, // common for both amin and aux
				disparity_array,     // double [][]                                    disparity_array,
				null, // double [][]                                    ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				clt_parameters,      // EyesisCorrectionParameters.CLTParameters       clt_parameters,
6704
				clt_parameters.getFatZero(quadCLT_main.isMonochrome()), // double                                         fatzero,
6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730
				notch_mode,                          //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_rad,                              // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				no_int_x0,                            // final boolean             no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,          //final int        threadsMax,  // maximal number of threads to launch
				updateStatus,        // final boolean    updateStatus,
				debugLevel);          // final int        debugLevel)
		// combine with old results for tiles that were not re-measured

		for (int tileY = 0; tileY<tilesY;tileY++) {
			for (int tileX = 0; tileX<tilesX;tileX++) {
				int nTile = tileY * tilesX + tileX;
				if ((selection == null) || selection[nTile]) {
					if (Double.isNaN(disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile]) && !Double.isNaN(src_bimap[ImageDtt.BI_TARGET_INDEX][nTile])) {
						for (int i = 0; i < disparity_bimap.length; i++) {
							disparity_bimap[i][nTile] = src_bimap[i][nTile];
						}
					}
				}
			}
		}
		if (num_new != null) {
			num_new[0] = numMeas;
		}
		return disparity_bimap;
	}

6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743
	public double [][] refineRig_new(
			QuadCLT                                  quadCLT_main,  // tiles should be set
			QuadCLT                                  quadCLT_aux,
			double [][]                              src_bimap, // current state of measurements
			double [][]                              prev_bimap, // previous state of measurements or null
			double []                                scale_bad,
			int                                      refine_mode, // 0 - by main, 1 - by aux, 2 - by inter
			boolean                                  keep_inf,    // keep expected disparity 0.0 if it was so
			boolean []                               inf_sel,     // infinity selection
			double                                   refine_min_strength, // do not refine weaker tiles
			double                                   refine_tolerance,    // do not refine if absolute disparity below
			ArrayList<Integer>                       tile_list, // or null
			int     []                               num_new,
6744
			CLTParameters clt_parameters,
6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798
			boolean                                  notch_mode,      // use notch filter for inter-camera correlation to detect poles
			int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
			final boolean                            no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
			final int                                threadsMax,  // maximal number of threads to launch
			final boolean                            updateStatus,
			final int                                debugLevel){
		boolean [] selection = null;
		if (tile_list != null) {
			selection = new boolean [quadCLT_main.tp.getTilesX() * quadCLT_main.tp.getTilesY()];
			if (inf_sel == null) {
				for (int nTile:tile_list) selection[nTile] = true;
			} else {
				for (int nTile:tile_list) selection[nTile] = !inf_sel[nTile];
			}
		} else if (inf_sel != null) {
			selection = new boolean [quadCLT_main.tp.getTilesX() * quadCLT_main.tp.getTilesY()];
			for (int nTile = 0; nTile < selection.length; nTile++) {
				selection[nTile] = !inf_sel[nTile];
			}

		}
		return refineRigSel_new(
				quadCLT_main,  // tiles should be set
				quadCLT_aux,
				src_bimap, // current state of measurements
				prev_bimap, // previous state of measurements or null
				scale_bad,  //
				refine_mode, // 0 - by main, 1 - by aux, 2 - by inter
				keep_inf,    // keep expected disparity 0.0 if it was so
				refine_min_strength, // do not refine weaker tiles
				refine_tolerance,    // do not refine if absolute disparity below
				selection,
				num_new,
				clt_parameters,
				notch_mode,                          //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_rad,                              // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				no_int_x0,           // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,  // maximal number of threads to launch
				updateStatus,
				debugLevel);
	}

	public double [][] refineRigSel_new(
			QuadCLT                                        quadCLT_main,  // tiles should be set
			QuadCLT                                        quadCLT_aux,
			double [][]                                    src_bimap, // current state of measurements
			double [][]                                    prev_bimap, // previous state of measurements or null
			double []                                      scale_bad,
			int                                            refine_mode, // 0 - by main, 1 - by aux, 2 - by inter
			boolean                                        keep_inf,    // keep expected disparity 0.0 if it was so
			double                                         refine_min_strength, // do not refine weaker tiles
			double                                         refine_tolerance,    // do not refine if absolute disparity below
			boolean []                                     selection,
			int     []                                     num_new,
6799
			CLTParameters       clt_parameters,
6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852
			final boolean                                  notch_mode,      // use notch filter for inter-camera correlation to detect poles
			final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
			final boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel){
		int tilesX =quadCLT_main.tp.getTilesX();
		int tilesY =quadCLT_main.tp.getTilesY();
		int [][] tile_op = new int [tilesY][tilesX];
		double [][] disparity_array = new double [tilesY][tilesX];
		double disp_scale_main =  1.0/clt_parameters.corr_magic_scale; // Is it needed?
		double disp_scale_aux =   disp_scale_main * quadCLT_main.geometryCorrection.getDisparityRadius()/quadCLT_aux.geometryCorrection.getDisparityRadius();
		double disp_scale_inter = disp_scale_main * quadCLT_main.geometryCorrection.getDisparityRadius()/quadCLT_aux.geometryCorrection.getBaseline();
		int tile_op_all = clt_parameters.tile_task_op; //FIXME Use some constant?
		int numMeas = 0;
		for (int tileY = 0; tileY<tilesY;tileY++) {
			for (int tileX = 0; tileX<tilesX;tileX++) {
				int nTile = tileY * tilesX + tileX;
				if (((selection == null) || selection[nTile]) && !Double.isNaN(src_bimap[ImageDtt.BI_TARGET_INDEX][nTile])) {
					if (prepRefineTile(
							(lt_rad > 0),
							clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
							tile_op_all,    // int                                            tile_op_all,
							src_bimap, // double [][]                                     src_bimap, // current state of measurements
							prev_bimap, // double [][]                                    prev_bimap, // previous state of measurements or null
							scale_bad,  // double []                                      scale_bad,
							tile_op, // int [][]                                          tile_op, // common for both amin and aux
							disparity_array, // double [][]                                    disparity_array,
							refine_mode, // int                                            refine_mode, // 0 - by main, 1 - by aux, 2 - by inter
							keep_inf,    // boolean                                        keep_inf,    // keep expected disparity 0.0 if it was so
							0.0,             // double                                         inf_disparity,
							refine_min_strength, // double                                         refine_min_strength, // do not refine weaker tiles
							refine_tolerance,    // double                                         refine_tolerance,    // do not refine if absolute disparity below
							disp_scale_main,  // double                                         disp_scale_main,  // 1.0
							disp_scale_aux,   //double                                         disp_scale_aux,   // ~0.58
							disp_scale_inter, //double                                         disp_scale_inter, // ~4.86
							//								  scale_step,       // double                                         scale_step,  // scale for "unstable tiles"
							tileX, // int                                            tileX,
							tileY, // int                                            tileY,
							nTile )) numMeas++; //int                                            nTile
				}
			}
		}
		if (debugLevel >0) {
			System.out.println("refineRigSel() mode="+refine_mode+": Prepared "+numMeas+" to measure");
		}
		double [][] disparity_bimap  =  measureRig(
				quadCLT_main,        // QuadCLT                                        quadCLT_main,  // tiles should be set
				quadCLT_aux,         // QuadCLT                                        quadCLT_aux,
				tile_op,             // int [][]                                       tile_op, // common for both amin and aux
				disparity_array,     // double [][]                                    disparity_array,
				null, // double [][]                                    ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				clt_parameters,      // EyesisCorrectionParameters.CLTParameters       clt_parameters,
6853
				clt_parameters.getFatZero(quadCLT_main.isMonochrome()), // double                                         fatzero,
6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884
				notch_mode,                          //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_rad,                              // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				no_int_x0,                            // final boolean             no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,          //final int        threadsMax,  // maximal number of threads to launch
				updateStatus,        // final boolean    updateStatus,
				debugLevel);          // final int        debugLevel)
		// combine with old results for tiles that were not re-measured

		for (int tileY = 0; tileY<tilesY;tileY++) {
			for (int tileX = 0; tileX<tilesX;tileX++) {
				int nTile = tileY * tilesX + tileX;
// FIXME: see if the parameter is needed
//				if ((selection == null) || selection[nTile]) {
					if (Double.isNaN(disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile]) && !Double.isNaN(src_bimap[ImageDtt.BI_TARGET_INDEX][nTile])) {
						if (nTile == 35509) {
							System.out.println("refineRigSel(): nTile="+nTile);
						}

						for (int i = 0; i < disparity_bimap.length; i++) {
							disparity_bimap[i][nTile] = src_bimap[i][nTile];
						}
					}
//				}
			}
		}
		if (num_new != null) {
			num_new[0] = numMeas;
		}
		return disparity_bimap;
	}

6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904
	/**
	 * Add measurements with new specified disparity of the main camera
	 * @param quadCLT_main main camera QuadCLT instance (should have tp initialized)
	 * @param quadCLT_aux auxiliary camera QuadCLT instance (should have tp initialized)
	 * @param src_bimap results of the older measurements (now includes expected disparity) or null (no old results available)
	 * @param disparity new expected disparity value to try
	 * @param tile_list list of selected tiles or null. If not null, will not re-measure listed tiles
	 * @param clt_parameters various configuration parameters
	 * @param threadsMax maximal number of threads to use
	 * @param updateStatus update IJ status bar
	 * @param debugLevel debug level
	 * @return results of the new measurements combined with the old results (if available)
	 */

	public double [][] measureNewRigDisparity(
			QuadCLT                                        quadCLT_main,  // tiles should be set
			QuadCLT                                        quadCLT_aux,
			double [][]                                    src_bimap, // current state of measurements (or null for new measurement)
			double                                         disparity,
			ArrayList<Integer>                             tile_list, // or null. If non-null - do not remeasure members of the list
6905
			CLTParameters       clt_parameters,
6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942
			boolean                                        notch_mode,      // use notch filter for inter-camera correlation to detect poles
			int                                            lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
			boolean                                        no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel){
		if ((debugLevel > 0) && (tile_list != null)) {
			System.out.println("measureNewRigDisparity(), disparity = "+disparity+", tile_list.size()="+tile_list.size());
		}
		int tile_op_all = clt_parameters.tile_task_op; //FIXME Use some constant?
		int tilesX =quadCLT_main.tp.getTilesX();
		int tilesY =quadCLT_main.tp.getTilesY();
		int [][] tile_op = new int [tilesY][tilesX];
		double [][] disparity_array = new double [tilesY][tilesX];

		boolean [] selected = new boolean [tilesX * tilesY];
		if (tile_list != null) {
			for (int nTile:tile_list) {
				selected[nTile] = true;
			}
		}
		for (int tileY = 0; tileY<tilesY;tileY++) {
			for (int tileX = 0; tileX<tilesX;tileX++) {
				int nTile = tileY * tilesX + tileX;
				if ((src_bimap == null) || Double.isNaN(src_bimap[ImageDtt.BI_TARGET_INDEX][nTile]) || !selected[nTile]) {
					tile_op[tileY][tileX] = tile_op_all;
					disparity_array[tileY][tileX] = disparity;
				}
			}
		}
		double [][] disparity_bimap  =  measureRig(
				quadCLT_main,        // QuadCLT                                        quadCLT_main,  // tiles should be set
				quadCLT_aux,         // QuadCLT                                        quadCLT_aux,
				tile_op,             // int [][]                                       tile_op, // common for both amin and aux
				disparity_array,     // double [][]                                    disparity_array,
				null, // double [][]                                    ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				clt_parameters,      // EyesisCorrectionParameters.CLTParameters       clt_parameters,
6943
				clt_parameters.getFatZero(quadCLT_main.isMonochrome()), // double                                         fatzero,
6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955
				notch_mode,                          //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_rad,                              // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				no_int_x0,           // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,          //final int        threadsMax,  // maximal number of threads to launch
				updateStatus,        // final boolean    updateStatus,
				debugLevel);          // final int        debugLevel)

		// combine with old results (if available) for the tiles that were not re-measured
		if (src_bimap != null) {
			for (int tileY = 0; tileY<tilesY;tileY++) {
				for (int tileX = 0; tileX<tilesX;tileX++) {
					int nTile = tileY * tilesX + tileX;
6956 6957 6958
					if (nTile == 35509) {
						System.out.println("measureNewRigDisparity(): nTile="+nTile);
					}
6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000
					boolean use_old = false;
					//				  if (Double.isNaN(disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile]) && !Double.isNaN(src_bimap[ImageDtt.BI_TARGET_INDEX][nTile])) {
					if (Double.isNaN(disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile])) {
						use_old = true;
					} else if (!Double.isNaN(src_bimap[ImageDtt.BI_TARGET_INDEX][nTile])) {
						double comp_strength_old = src_bimap[ImageDtt.BI_STR_FULL_INDEX][nTile] * src_bimap[ImageDtt.BI_ASTR_FULL_INDEX][nTile];
						double comp_strength_new = disparity_bimap[ImageDtt.BI_STR_FULL_INDEX][nTile]* disparity_bimap[ImageDtt.BI_ASTR_FULL_INDEX][nTile];
						if (comp_strength_old > comp_strength_new) {
							use_old = true;
						} else if (!(comp_strength_old < comp_strength_new)) { //one or both are NaN
							// for now - enough,
							if (Double.isNaN (comp_strength_new)) {
								use_old = true;
							}
						}
					}
					if (use_old) {
						for (int i = 0; i < disparity_bimap.length; i++) {
							disparity_bimap[i][nTile] = src_bimap[i][nTile];
						}
					}
				}
			}
		}
		return disparity_bimap;
	}

	/**
	 * Measure with specified disparity array, skip Double.NaN tiles
	 * @param quadCLT_main main camera QuadCLT instance (should have tp initialized)
	 * @param quadCLT_aux auxiliary camera QuadCLT instance (should have tp initialized)
	 * @param disparity expected per-tile disparities. NaN - do not measure
	 * @param clt_parameters various configuration parameters
	 * @param threadsMax maximal number of threads to use
	 * @param updateStatus update IJ status bar
	 * @param debugLevel debug level
	 * @return results of the new measurements combined with the old results (if available)
	 */
	public double [][] measureNewRigDisparity(
			QuadCLT                                        quadCLT_main,  // tiles should be set
			QuadCLT                                        quadCLT_aux,
			double []                                      disparity, // Double.NaN - skip, ohers - measure
7001
			CLTParameters       clt_parameters,
7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029
			boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
			int                 lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
			boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel){
		int tile_op_all = clt_parameters.tile_task_op; //FIXME Use some constant?
		int tilesX =quadCLT_main.tp.getTilesX();
		int tilesY =quadCLT_main.tp.getTilesY();
		int [][] tile_op = new int [tilesY][tilesX];
		double [][] disparity_array = new double [tilesY][tilesX];
		for (int tileY = 0; tileY<tilesY;tileY++) {
			for (int tileX = 0; tileX<tilesX;tileX++) {
				int nTile = tileY * tilesX + tileX;
				disparity_array[tileY][tileX] = disparity[nTile];
				if (!Double.isNaN(disparity[nTile])) {
					tile_op[tileY][tileX] = tile_op_all;
					//disparity_array[tileY][tileX] = disparity[nTile];
				}
			}
		}
		double [][] disparity_bimap  =  measureRig(
				quadCLT_main,        // QuadCLT                                        quadCLT_main,  // tiles should be set
				quadCLT_aux,         // QuadCLT                                        quadCLT_aux,
				tile_op,             // int [][]                                       tile_op, // common for both amin and aux
				disparity_array,     // double [][]                                    disparity_array,
				null, // double [][]                                    ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				clt_parameters,      // EyesisCorrectionParameters.CLTParameters       clt_parameters,
7030
				clt_parameters.getFatZero(quadCLT_main.isMonochrome()), // double                                         fatzero,
7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042
				notch_mode,          //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_rad,                              // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				no_int_x0,           // boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				threadsMax,          //final int        threadsMax,  // maximal number of threads to launch
				updateStatus,        // final boolean    updateStatus,
				debugLevel);         // final int        debugLevel)
		return disparity_bimap;
	}


	private boolean prepRefineTile(
			boolean                                        remeasure_nan, // use old suggestion if result of the measurement was NaN
7043
			CLTParameters       clt_parameters,
7044 7045 7046 7047 7048 7049 7050 7051
			int                                            tile_op_all,
			double [][]                                    src_bimap, // current state of measurements
			double [][]                                    prev_bimap, // previous state of measurements or null
			double []                                      scale_bad,
			int [][]                                       tile_op, // common for both amin and aux
			double [][]                                    disparity_array,
			int                                            refine_mode, // 0 - by main, 1 - by aux, 2 - by inter, 3 - inter-dx
			boolean                                        keep_inf,    // keep expected disparity 0.0 if it was so
7052
			double                                         inf_disparity,
7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066
			double                                         refine_min_strength, // do not refine weaker tiles
			double                                         refine_tolerance,    // do not refine if absolute disparity below
			double                                         disp_scale_main,  // 1.0
			double                                         disp_scale_aux,   // ~0.58
			double                                         disp_scale_inter, // ~4.86
			//			  double                                         scale_step,  // scale for "unstable tiles"
			int                                            tileX,
			int                                            tileY,
			int                                            nTile) {

		boolean debug_this = false; // nTile==40661; // 61924;
		// check if it was measured (skip NAN)
		if (Double.isNaN(src_bimap[ImageDtt.BI_TARGET_INDEX][nTile])) return false;
		// check if it is infinity and change is prohibited
7067
		if (keep_inf && (src_bimap[ImageDtt.BI_TARGET_INDEX][nTile] == inf_disparity)) {
7068 7069
			if ((refine_min_strength == 0.0) || (refine_tolerance == 0.0)) {
				tile_op[tileY][tileX] = tile_op_all;
7070
				disparity_array[tileY][tileX] = inf_disparity;
7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163
				return true;
			}
			return false;
		}
		double diff_disp, strength, disp_scale, diff_prev;
		switch (refine_mode) {
		case 0:
			diff_disp = src_bimap[ImageDtt.BI_DISP_FULL_INDEX][nTile];
			diff_prev= (prev_bimap == null)? Double.NaN:prev_bimap[ImageDtt.BI_DISP_FULL_INDEX][nTile];
			strength = src_bimap[ImageDtt.BI_STR_FULL_INDEX][nTile];
			disp_scale = disp_scale_main;
			break;
		case 1:
			diff_disp = src_bimap[ImageDtt.BI_ADISP_FULL_INDEX][nTile];
			diff_prev= (prev_bimap == null)? Double.NaN:prev_bimap[ImageDtt.BI_ADISP_FULL_INDEX][nTile];
			strength = src_bimap[ImageDtt.BI_ASTR_FULL_INDEX][nTile];
			disp_scale = disp_scale_aux;
			break;
		case 2:
			diff_disp = src_bimap[ImageDtt.BI_DISP_CROSS_INDEX][nTile];
			diff_prev= (prev_bimap == null)? Double.NaN:prev_bimap[ImageDtt.BI_DISP_CROSS_INDEX][nTile];
			strength = src_bimap[ImageDtt.BI_STR_CROSS_INDEX][nTile];
			disp_scale = disp_scale_inter;
			break;
		default: // case 3
		diff_disp = src_bimap[ImageDtt.BI_DISP_CROSS_DX_INDEX][nTile];
		diff_prev= (prev_bimap == null)? Double.NaN:prev_bimap[ImageDtt.BI_DISP_CROSS_DX_INDEX][nTile];
		strength = src_bimap[ImageDtt.BI_STR_CROSS_INDEX][nTile];
		disp_scale = disp_scale_inter;
		}
		if (Double.isNaN(diff_disp)) {
			if (remeasure_nan) {
				tile_op[tileY][tileX] = tile_op_all;
				disparity_array[tileY][tileX] = src_bimap[ImageDtt.BI_TARGET_INDEX][nTile]; // repeat previous - only makes sense with averaging
				return true;

			} else {
				return false;
			}
		}

		// strong enough?
		if (strength < refine_min_strength) return false;
		// residual disparity large enough to bother
		if (Math.abs(diff_disp) < refine_tolerance) return false;
		// or use extrapolate too?
		if (debug_this) {
			//			  System.out.println("disp_scale="+disp_scale);
			if (prev_bimap != null) {
				//				  System.out.println(
				///						  "prepRefineTile(): prev_bimap[ImageDtt.BI_TARGET_INDEX][nTile] = "+prev_bimap[ImageDtt.BI_TARGET_INDEX][nTile]+
				//						  ", src_bimap[ImageDtt.BI_TARGET_INDEX][nTile]="+src_bimap[ImageDtt.BI_TARGET_INDEX][nTile]+", diff_prev="+diff_prev+", diff_disp="+diff_disp);
			} else {
				//				  System.out.println("prepRefineTile():  src_bimap[ImageDtt.BI_TARGET_INDEX][nTile]="+src_bimap[ImageDtt.BI_TARGET_INDEX][nTile]+", diff_prev="+diff_prev+", diff_disp="+diff_disp);
			}
		}
		boolean from_prev = false;
		if ((scale_bad != null) && (Math.abs(diff_disp) > Math.abs(diff_prev))){
			scale_bad[nTile] *= 0.9; // reduce step
			from_prev = true;
		}
		double new_disp;
		if (Double.isNaN(diff_prev) || (diff_prev * diff_disp > 0)) {
			new_disp = src_bimap[ImageDtt.BI_TARGET_INDEX][nTile] + diff_disp*disp_scale;
			//			  if (debug_this) System.out.println(" >> 1 => disparity_array["+tileY+"]["+tileX+"]="+new_disp);
		}  else { // interpolate
			new_disp = (src_bimap[ImageDtt.BI_TARGET_INDEX][nTile]*diff_prev - prev_bimap[ImageDtt.BI_TARGET_INDEX][nTile]*diff_disp)/(diff_prev-diff_disp);
			//			  if (debug_this) System.out.println(" >> 2  => disparity_array["+tileY+"]["+tileX+"]="+new_disp);
		}
		double ref_target = from_prev ? prev_bimap[ImageDtt.BI_TARGET_INDEX][nTile] : src_bimap[ImageDtt.BI_TARGET_INDEX][nTile];
		if ((scale_bad != null) && (scale_bad[nTile] < 1.0)) {
			new_disp = ref_target * (1.0 - scale_bad[nTile]) +  new_disp * scale_bad[nTile];
			//			  if (debug_this) System.out.println(" scale_bad["+nTile+"]= "+scale_bad[nTile]+" , corrected new_disp="+new_disp+" (was "+ src_bimap[ImageDtt.BI_TARGET_INDEX][nTile]+
			//					  ", prev "+prev_bimap[ImageDtt.BI_TARGET_INDEX][nTile]+")");
		} else if (prev_bimap!=null){
			//			  if (debug_this) System.out.println("new_disp="+new_disp+" (was "+ src_bimap[ImageDtt.BI_TARGET_INDEX][nTile]+
			//					  ", prev "+prev_bimap[ImageDtt.BI_TARGET_INDEX][nTile]+")");
		}
		if (debug_this) System.out.println("prepRefineTile():target_diff "+ src_bimap[ImageDtt.BI_TARGET_INDEX][nTile]+","+diff_disp+","+scale_bad[nTile]);

		//		  if (Math.abs((new_disp - ref_target)/new_disp) < refine_tolerance) return false;
		if (Math.abs(new_disp - ref_target) < refine_tolerance) return false;
		disparity_array[tileY][tileX] = new_disp;
		tile_op[tileY][tileX] = tile_op_all;
		return true;
	}

	double [][] measureRig(
			QuadCLT                                  quadCLT_main,  // tiles should be set
			QuadCLT                                  quadCLT_aux,
			int [][]                                 tile_op, // common for both amin and aux
			double [][]                              disparity_array,
			double [][]                              ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
7164
			CLTParameters clt_parameters,
7165 7166 7167 7168 7169 7170 7171
			double                                   fatzero,
			boolean                                  notch_mode, // use pole-detection mode for inter-camera correlation
			int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
			boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
			final int                                threadsMax,  // maximal number of threads to launch
			final boolean                            updateStatus,
			final int                                debugLevel){
7172 7173 7174
		ImageDtt image_dtt = new ImageDtt(
				clt_parameters.transform_size,
				quadCLT_main.isMonochrome(),
7175
				quadCLT_main.isLwir(),
7176
				clt_parameters.getScaleStrength(false));
7177 7178 7179

		double [][] disparity_bimap  = new double [ImageDtt.BIDISPARITY_TITLES.length][]; //[0] -residual disparity, [1] - orthogonal (just for debugging) last 4 - max pixel differences

7180
//		int [][] woi_tops = {quadCLT_main.woi_tops,quadCLT_aux.woi_tops};
7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198
		image_dtt.clt_bi_quad (
				clt_parameters,                       // final EyesisCorrectionParameters.CLTParameters       clt_parameters,
				fatzero,                              // final double              fatzero,         // May use correlation fat zero from 2 different parameters - fat_zero and rig.ml_fatzero
				notch_mode,                           //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_rad,                               // final int                                   lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				no_int_x0,                            // final boolean             no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				tile_op,                              // final int [][]            tile_op_main,    // [tilesY][tilesX] - what to do - 0 - nothing for this tile
				disparity_array,                      // final double [][]         disparity_array, // [tilesY][tilesX] - individual per-tile expected disparity
				quadCLT_main.image_data,              // final double [][][]       image_data_main, // first index - number of image in a quad
				quadCLT_aux.image_data,               // final double [][][]       image_data_aux,  // first index - number of image in a quad
				quadCLT_main.saturation_imp,          // final boolean [][]        saturation_main, // (near) saturated pixels or null
				quadCLT_aux.saturation_imp,           // final boolean [][]        saturation_aux,  // (near) saturated pixels or null
				// correlation results - combo will be for the correation between two quad cameras
				null,                                 // final double [][][][]     clt_corr_combo,  // [type][tilesY][tilesX][(2*transform_size-1)*(2*transform_size-1)] // if null - will not calculate
				disparity_bimap,                      // final double [][]    disparity_bimap, // [23][tilesY][tilesX]
				ml_data,                              // 	final double [][]         ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				null,                                 // final double [][][][]     texture_tiles_main, // [tilesY][tilesX]["RGBA".length()][];  null - will skip images combining
				null,                                 // final double [][][][]     texture_tiles_aux,  // [tilesY][tilesX]["RGBA".length()][];  null - will skip images combining
7199
				quadCLT_main.tp.getTilesX()*image_dtt.transform_size, // final int                 width,
7200 7201 7202 7203 7204 7205 7206

				quadCLT_main.getGeometryCorrection(), // final GeometryCorrection  geometryCorrection_main,
				quadCLT_aux.getGeometryCorrection(),  // final GeometryCorrection  geometryCorrection_aux,
				quadCLT_main.getCLTKernels(),         // final double [][][][][][] clt_kernels_main, // [channel_in_quad][color][tileY][tileX][band][pixel] , size should match image (have 1 tile around)
				quadCLT_aux.getCLTKernels(),          // final double [][][][][][] clt_kernels_aux,  // [channel_in_quad][color][tileY][tileX][band][pixel] , size should match image (have 1 tile around)
				clt_parameters.corr_magic_scale,      // final double              corr_magic_scale, // still not understood coefficient that reduces reported disparity value.  Seems to be around 0.85
				false, // true,                                 // 	final boolean             keep_clt_data,
7207
//				woi_tops,                             // final int [][]            woi_tops,
7208
				null,                                 // final double [][][]       ers_delay,        // if not null - fill with tile center acquisition delay
7209 7210 7211 7212 7213
				threadsMax,                           // final int                 threadsMax,  // maximal number of threads to launch
				debugLevel-2);                        // final int                 globalDebugLevel);
		return disparity_bimap;
	}

7214 7215


7216
	public double [][] remeasureRigML(
7217 7218
			double                                         disparity_offset_low,
			double                                         disparity_offset_high,
7219 7220
			QuadCLT                                        quadCLT_main,  // tiles should be set
			QuadCLT                                        quadCLT_aux,
7221
			double []                                      disparity_main, // main camera disparity to use - if null, calculate from the rig one
7222 7223
			double []                                      disparity,
			double []                                      strength,
7224
			CLTParameters       clt_parameters,
7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246
			int                                            ml_hwidth,
			double                                         fatzero,
			int              lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel){
		int tile_op_all = clt_parameters.tile_task_op; //FIXME Use some constant?
		final int tilesX = quadCLT_main.tp.getTilesX();
		final int tilesY = quadCLT_main.tp.getTilesY();
		//		  int ml_hwidth =      2;
		int ml_width = 2 * ml_hwidth + 1;

		double [][] ml_data  = new double [ImageDtt.ML_TITLES.length][tilesX * tilesY * ml_width * ml_width];
		for (int nLayer=0; nLayer < ml_data.length; nLayer++) {
			for (int nTile=0; nTile <  ml_data[nLayer].length; nTile++) {
				ml_data[nLayer][nTile] = Double.NaN;
			}
		}

		int [][]           tile_op = new int[tilesY][tilesX]; // common for both main and aux
		double [][]        disparity_array = new double[tilesY][tilesX];
		boolean [] selection =   new boolean [strength.length];
Andrey Filippov's avatar
Andrey Filippov committed
7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263
		if (disparity_main != null) {
			for (int nTile = 0; nTile < selection.length; nTile++) {
				//			selection[nTile] = strength[nTile] > 0.0;
				selection[nTile] = (strength[nTile] > 0.0) || !Double.isNaN(disparity_main[nTile]); // measuring correlation for clusters - around defined tiles
				if (selection[nTile] && Double.isNaN(disparity[nTile])) {
					disparity[nTile] = 0.0; // it will not be used
					strength[nTile]  = 0.0; // should already be set
				}
			}
		}
		if (!(disparity_offset_high > disparity_offset_low)) { // otherwise offset to the rig data is used
			for (int nTile = 0; nTile < selection.length; nTile++) {
				if (selection[nTile] && Double.isNaN(disparity[nTile])) {
					disparity[nTile] = 0.0; // it will not be used
					strength[nTile]  = 0.0; // should already be set
				}
			}
7264
		}
7265
		Random rnd = new Random(System.nanoTime());
7266 7267 7268 7269
		Correlation2d corr2d = new Correlation2d(
				clt_parameters.img_dtt,              // ImageDttParameters  imgdtt_params,
				clt_parameters.transform_size,             // int transform_size,
				2.0,                        //  double wndx_scale, // (wndy scale is always 1.0)
7270
				quadCLT_main.isMonochrome(),
7271 7272 7273
				(debugLevel > -1));   //   boolean debug)

		for (int nTile = 0; nTile < disparity.length; nTile++) {
Andrey Filippov's avatar
Andrey Filippov committed
7274
			if ((selection == null) || selection[nTile]) {
7275 7276 7277
				int tileY = nTile / tilesX;
				int tileX = nTile % tilesX;
				tile_op[tileY][tileX] = tile_op_all;
7278 7279 7280 7281
				double disparity_offset = disparity_offset_low;
				if (disparity_offset_high > disparity_offset) { // will not happen if disparity_offset_high is NaN
					disparity_offset = disparity_offset_low + (disparity_offset_high-disparity_offset_low)*rnd.nextDouble();
				}
7282 7283 7284
				if ((disparity_main != null) && !Double.isNaN(disparity_main[nTile])) {
					// Use actuall disparity from the main camera
					disparity_offset = disparity_main[nTile] - disparity[nTile];
Andrey Filippov's avatar
Andrey Filippov committed
7285 7286 7287
					if (!Double.isNaN(disparity_offset_high) && (disparity_offset_high > 0.0)) {
						disparity_offset += disparity_offset_high* (2 * rnd.nextDouble() - 1.0);
					}
7288
				}
7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326
				disparity_array[tileY][tileX] = disparity[nTile]+disparity_offset;
				corr2d.saveMlTilePixel(
						tileX,                         // int         tileX,
						tileY,                         // int         tileY,
						ml_hwidth,                     // int         ml_hwidth,
						ml_data,                       // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,       // int         ml_layer,
						ImageDtt.ML_OTHER_GTRUTH ,     // int         ml_index,
						disparity[nTile],              // target disparitydouble      ml_value,
						tilesX);                       // int         tilesX);
				corr2d.saveMlTilePixel(
						tileX,                         // int         tileX,
						tileY,                         // int         tileY,
						ml_hwidth,                     // int         ml_hwidth,
						ml_data,                       // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,       // int         ml_layer,
						ImageDtt.ML_OTHER_GTRUTH_STRENGTH, // int         ml_index,
						strength[nTile],               // target disparitydouble      ml_value,
						tilesX);                       // int         tilesX);
			}
		}
		measureRig(
				quadCLT_main, // QuadCLT                                        quadCLT_main,  // tiles should be set
				quadCLT_aux, // QuadCLT                                        quadCLT_aux,
				tile_op, // int [][]                                       tile_op, // common for both amin and aux
				disparity_array, // double [][]                                    disparity_array,
				ml_data, // double [][]                                    ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				clt_parameters,   // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				fatzero,          // double                                         fatzero,
				false,            //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_rad,                              // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				true,             // whatever here. final boolean             no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very
				threadsMax,       // maximal number of threads to launch // final int        threadsMax,  // maximal number of threads to launch
				updateStatus,     // final boolean    updateStatus,
				debugLevel);      // final int        debugLevel)
		return ml_data;
	}

7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340
	double [][] measureAux(
//			QuadCLT                                  quadCLT_main,  // tiles should be set
			QuadCLT                                  quadCLT_aux,
			int [][]                                 tile_op, // common for both amin and aux
			double [][]                              disparity_array,
			double [][]                              ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
			CLTParameters clt_parameters,
			double                                   fatzero,
			boolean                                  notch_mode, // use pole-detection mode for inter-camera correlation
			int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using (2*notch_mode+1)^2 square
			boolean                                  no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
			final int                                threadsMax,  // maximal number of threads to launch
			final boolean                            updateStatus,
			final int                                debugLevel){
7341 7342 7343
		ImageDtt image_dtt = new ImageDtt(
				clt_parameters.transform_size,
				quadCLT_aux.isMonochrome(),
7344
				quadCLT_aux.isLwir(),
7345
				clt_parameters.getScaleStrength(true));
7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364
		double [][] disparity_bimap  = new double [ImageDtt.BIDISPARITY_TITLES.length][]; //[0] -residual disparity, [1] - orthogonal (just for debugging) last 4 - max pixel differences
		image_dtt.clt_bi_quad (
				clt_parameters,                       // final EyesisCorrectionParameters.CLTParameters       clt_parameters,
				fatzero,                              // final double              fatzero,         // May use correlation fat zero from 2 different parameters - fat_zero and rig.ml_fatzero
				notch_mode,                           //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				lt_rad,                               // final int                                   lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				no_int_x0,                            // final boolean             no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very wide
				tile_op,                              // final int [][]            tile_op_main,    // [tilesY][tilesX] - what to do - 0 - nothing for this tile
				disparity_array,                      // final double [][]         disparity_array, // [tilesY][tilesX] - individual per-tile expected disparity
				null, // quadCLT_main.image_data,              // final double [][][]       image_data_main, // first index - number of image in a quad
				quadCLT_aux.image_data,               // final double [][][]       image_data_aux,  // first index - number of image in a quad
				null, // quadCLT_main.saturation_imp,          // final boolean [][]        saturation_main, // (near) saturated pixels or null
				quadCLT_aux.saturation_imp,           // final boolean [][]        saturation_aux,  // (near) saturated pixels or null
				// correlation results - combo will be for the correation between two quad cameras
				null,                                 // final double [][][][]     clt_corr_combo,  // [type][tilesY][tilesX][(2*transform_size-1)*(2*transform_size-1)] // if null - will not calculate
				disparity_bimap,                      // final double [][]    disparity_bimap, // [23][tilesY][tilesX]
				ml_data,                              // 	final double [][]         ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				null,                                 // final double [][][][]     texture_tiles_main, // [tilesY][tilesX]["RGBA".length()][];  null - will skip images combining
				null,                                 // final double [][][][]     texture_tiles_aux,  // [tilesY][tilesX]["RGBA".length()][];  null - will skip images combining
7365 7366
//				quadCLT_main.tp.getTilesX()*image_dtt.transform_size, // final int                 width,
				quadCLT_aux.tp.getTilesX()*image_dtt.transform_size, // final int                 width,
7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537

				null, // quadCLT_main.getGeometryCorrection(), // final GeometryCorrection  geometryCorrection_main,
				quadCLT_aux.getGeometryCorrection(),  // final GeometryCorrection  geometryCorrection_aux,
				null, // quadCLT_main.getCLTKernels(),         // final double [][][][][][] clt_kernels_main, // [channel_in_quad][color][tileY][tileX][band][pixel] , size should match image (have 1 tile around)
				quadCLT_aux.getCLTKernels(),          // final double [][][][][][] clt_kernels_aux,  // [channel_in_quad][color][tileY][tileX][band][pixel] , size should match image (have 1 tile around)
				clt_parameters.corr_magic_scale,      // final double              corr_magic_scale, // still not understood coefficient that reduces reported disparity value.  Seems to be around 0.85
				false, // true,                                 // 	final boolean             keep_clt_data,
				null,                                 // final double [][][]       ers_delay,        // if not null - fill with tile center acquisition delay
				threadsMax,                           // final int                 threadsMax,  // maximal number of threads to launch
				debugLevel-2);                        // final int                 globalDebugLevel);
		return disparity_bimap;
	}

	public double [][] remeasureAuxML(
			QuadCLT                                        quadCLT_aux,
			double []                                      disparity, // Double.NaN - do not measure
			double [][]                                    dsi_aux_from_main, // Main camera DSI converted into the coordinates of the AUX one (see QuadCLT.FGBG_TITLES)-
			CLTParameters       clt_parameters,
			int                                            ml_hwidth,
			double                                         fatzero,
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel){
		int tile_op_all = clt_parameters.tile_task_op; //FIXME Use some constant?
		final int tilesX = quadCLT_aux.tp.getTilesX();
		final int tilesY = quadCLT_aux.tp.getTilesY();
		//		  int ml_hwidth =      2;
		int ml_width = 2 * ml_hwidth + 1;

		double [][] ml_data  = new double [ImageDtt.ML_TITLES.length][tilesX * tilesY * ml_width * ml_width];
		for (int nLayer=0; nLayer < ml_data.length; nLayer++) {
			for (int nTile=0; nTile <  ml_data[nLayer].length; nTile++) {
				ml_data[nLayer][nTile] = Double.NaN;
			}
		}

		int [][]           tile_op = new int[tilesY][tilesX]; // common for both main and aux
		double [][]        disparity_array = new double[tilesY][tilesX];
		Correlation2d corr2d = new Correlation2d(
				clt_parameters.img_dtt,              // ImageDttParameters  imgdtt_params,
				clt_parameters.transform_size,             // int transform_size,
				2.0,                        //  double wndx_scale, // (wndy scale is always 1.0)
				quadCLT_aux.isMonochrome(),
				(debugLevel > -1));   //   boolean debug)

		for (int nTile = 0; nTile < disparity.length; nTile++) if (!Double.isNaN(disparity[nTile])) {
				int tileY = nTile / tilesX;
				int tileX = nTile % tilesX;
				tile_op[tileY][tileX] = tile_op_all;
				disparity_array[tileY][tileX] = disparity[nTile];
				corr2d.saveMlTilePixel(
						tileX,                                            // int         tileX,
						tileY,                                            // int         tileY,
						ml_hwidth,                                        // int         ml_hwidth,
						ml_data,                                          // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,                          // int         ml_layer,
						ImageDtt.ML_OTHER_GTRUTH ,                        // int         ml_index,
						dsi_aux_from_main[QuadCLT.FGBG_DISPARITY][nTile], // double      ml_value,
						tilesX);                                          // int         tilesX);
				corr2d.saveMlTilePixel(
						tileX,                                            // int         tileX,
						tileY,                                            // int         tileY,
						ml_hwidth,                                        // int         ml_hwidth,
						ml_data,                                          // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,                          // int         ml_layer,
						ImageDtt.ML_OTHER_GTRUTH_STRENGTH,                // int         ml_index,
						dsi_aux_from_main[QuadCLT.FGBG_STRENGTH][nTile],  // double      ml_value,
						tilesX);                                          // int         tilesX);
				if (dsi_aux_from_main.length < (QuadCLT.FGBG_RMS -1)) continue;
				corr2d.saveMlTilePixel(
						tileX,                                            // int         tileX,
						tileY,                                            // int         tileY,
						ml_hwidth,                                        // int         ml_hwidth,
						ml_data,                                          // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,                          // int         ml_layer,
						ImageDtt.ML_OTHER_GTRUTH_RMS,                     // int         ml_index,
						dsi_aux_from_main[QuadCLT.FGBG_RMS][nTile],       // double      ml_value,
						tilesX);                                          // int         tilesX);
				if (dsi_aux_from_main.length < (QuadCLT.FGBG_RMS_SPLIT -1)) continue;
				corr2d.saveMlTilePixel(
						tileX,                                            // int         tileX,
						tileY,                                            // int         tileY,
						ml_hwidth,                                        // int         ml_hwidth,
						ml_data,                                          // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,                          // int         ml_layer,
						ImageDtt.ML_OTHER_GTRUTH_RMS_SPLIT,               // int         ml_index,
						dsi_aux_from_main[QuadCLT.FGBG_RMS_SPLIT][nTile], // double      ml_value,
						tilesX);                                          // int         tilesX);
				if (dsi_aux_from_main.length < (QuadCLT.FGBG_FG_DISP -1)) continue;
				corr2d.saveMlTilePixel(
						tileX,                                            // int         tileX,
						tileY,                                            // int         tileY,
						ml_hwidth,                                        // int         ml_hwidth,
						ml_data,                                          // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,                          // int         ml_layer,
						ImageDtt.ML_OTHER_GTRUTH_FG_DISP,                 // int         ml_index,
						dsi_aux_from_main[QuadCLT.FGBG_FG_DISP][nTile],   // double      ml_value,
						tilesX);                                          // int         tilesX);
				if (dsi_aux_from_main.length < (QuadCLT.FGBG_FG_STR -1)) continue;
				corr2d.saveMlTilePixel(
						tileX,                                            // int         tileX,
						tileY,                                            // int         tileY,
						ml_hwidth,                                        // int         ml_hwidth,
						ml_data,                                          // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,                          // int         ml_layer,
						ImageDtt.ML_OTHER_GTRUTH_FG_STR,                  // int         ml_index,
						dsi_aux_from_main[QuadCLT.FGBG_FG_STR][nTile],    // double      ml_value,
						tilesX);                                          // int         tilesX);
				if (dsi_aux_from_main.length < (QuadCLT.FGBG_BG_DISP -1)) continue;
				corr2d.saveMlTilePixel(
						tileX,                                            // int         tileX,
						tileY,                                            // int         tileY,
						ml_hwidth,                                        // int         ml_hwidth,
						ml_data,                                          // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,                          // int         ml_layer,
						ImageDtt.ML_OTHER_GTRUTH_BG_DISP,                 // int         ml_index,
						dsi_aux_from_main[QuadCLT.FGBG_BG_DISP][nTile],   // double      ml_value,
						tilesX);                                          // int         tilesX);
				if (dsi_aux_from_main.length < (QuadCLT.FGBG_BG_STR -1)) continue;
				corr2d.saveMlTilePixel(
						tileX,                                            // int         tileX,
						tileY,                                            // int         tileY,
						ml_hwidth,                                        // int         ml_hwidth,
						ml_data,                                          // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,                          // int         ml_layer,
						ImageDtt.ML_OTHER_GTRUTH_BG_STR,                  // int         ml_index,
						dsi_aux_from_main[QuadCLT.FGBG_BG_STR][nTile],    // double      ml_value,
						tilesX);                                          // int         tilesX);

				if (dsi_aux_from_main.length < (QuadCLT.FGBG_AUX_DISP -1)) continue;
				corr2d.saveMlTilePixel(
						tileX,                                            // int         tileX,
						tileY,                                            // int         tileY,
						ml_hwidth,                                        // int         ml_hwidth,
						ml_data,                                          // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,                          // int         ml_layer,
						ImageDtt.ML_OTHER_AUX_DISP,                 // int         ml_index,
						dsi_aux_from_main[QuadCLT.FGBG_AUX_DISP][nTile],   // double      ml_value,
						tilesX);                                          // int         tilesX);
				if (dsi_aux_from_main.length < (QuadCLT.FGBG_AUX_STR -1)) continue;
				corr2d.saveMlTilePixel(
						tileX,                                            // int         tileX,
						tileY,                                            // int         tileY,
						ml_hwidth,                                        // int         ml_hwidth,
						ml_data,                                          // double [][] ml_data,
						ImageDtt.ML_OTHER_INDEX,                          // int         ml_layer,
						ImageDtt.ML_OTHER_AUX_STR,                  // int         ml_index,
						dsi_aux_from_main[QuadCLT.FGBG_AUX_STR][nTile],    // double      ml_value,
						tilesX);                                          // int         tilesX);
		}

		measureAux(
				quadCLT_aux, // QuadCLT                                        quadCLT_aux,
				tile_op, // int [][]                                       tile_op, // common for both amin and aux
				disparity_array, // double [][]                                    disparity_array,
				ml_data, // double [][]                                    ml_data,         // data for ML - 10 layers - 4 center areas (3x3, 5x5,..) per camera-per direction, 1 - composite, and 1 with just 1 data (target disparity)
				clt_parameters,   // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				fatzero,          // double                                         fatzero,
				false,            //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
				0,                // lt_rad,    // final int  // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
				true,             // whatever here. final boolean             no_int_x0,       // do not offset window to integer maximum - used when averaging low textures to avoid "jumps" for very
				threadsMax,       // maximal number of threads to launch // final int        threadsMax,  // maximal number of threads to launch
				updateStatus,     // final boolean    updateStatus,
				debugLevel);      // final int        debugLevel)
		return ml_data;
	}





7538
	ArrayList<Integer> selectRigTiles(
7539
			CLTParameters       clt_parameters,
7540 7541
			boolean select_infinity,
			boolean select_noninfinity,
7542
			double                                   inf_disparity,
7543 7544 7545 7546 7547 7548 7549
			double[][] disparity_bimap,
			int tilesX)
	{
		ArrayList<Integer> tilesList = new ArrayList<Integer>();
		int numTiles = disparity_bimap[ImageDtt.BI_STR_FULL_INDEX].length;
		if (select_infinity) {
			for (int nTile = 0; nTile < numTiles; nTile++) {
7550
				if (    (disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile] == inf_disparity) && // expected disparity was 0.0 (infinity)
7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567
						(disparity_bimap[ImageDtt.BI_STR_FULL_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_main) &&
						(disparity_bimap[ImageDtt.BI_ASTR_FULL_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_aux) &&
						(disparity_bimap[ImageDtt.BI_STR_CROSS_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_rig) &&

						(disparity_bimap[ImageDtt.BI_DISP_FULL_INDEX][nTile] <= clt_parameters.rig.inf_max_disp_main) &&
						(disparity_bimap[ImageDtt.BI_ADISP_FULL_INDEX][nTile] <= clt_parameters.rig.inf_max_disp_aux) &&
						(disparity_bimap[ImageDtt.BI_DISP_CROSS_INDEX][nTile] <= clt_parameters.rig.inf_max_disp_rig) &&

						(disparity_bimap[ImageDtt.BI_DISP_FULL_INDEX][nTile] >= -clt_parameters.rig.inf_max_disp_main) &&
						(disparity_bimap[ImageDtt.BI_ADISP_FULL_INDEX][nTile] >= -clt_parameters.rig.inf_max_disp_aux) &&
						(disparity_bimap[ImageDtt.BI_DISP_CROSS_INDEX][nTile] >= -clt_parameters.rig.inf_max_disp_rig * clt_parameters.rig.inf_neg_tolerance)) {
					tilesList.add(nTile);
				}
			}
		}
		if (select_noninfinity) {
			for (int nTile = 0; nTile < numTiles; nTile++) {
7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582
				if (    (disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile] > inf_disparity ) && // expected disparity was > 0.0 (not infinity)
						(disparity_bimap[ImageDtt.BI_STR_FULL_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_main)&&
						(disparity_bimap[ImageDtt.BI_ASTR_FULL_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_aux)&&
						(disparity_bimap[ImageDtt.BI_STR_CROSS_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_rig)&&
						(Math.abs(disparity_bimap[ImageDtt.BI_DISP_FULL_INDEX][nTile]) <= clt_parameters.rig.near_max_disp_main)&&
						(Math.abs(disparity_bimap[ImageDtt.BI_ADISP_FULL_INDEX][nTile]) <= clt_parameters.rig.near_max_disp_aux)&&
						(Math.abs(disparity_bimap[ImageDtt.BI_DISP_CROSS_INDEX][nTile]) <= clt_parameters.rig.near_max_disp_rig)) {
					tilesList.add(nTile);
				}
			}
		}
		return tilesList;
	}

	ArrayList<Integer> selectRigTiles_new(
7583
			CLTParameters       clt_parameters,
7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619
			boolean ignore_target,    // to select non-zero "infinity"
			boolean []  disabled,
			boolean select_infinity,
			boolean select_noninfinity,
			double[][] disparity_bimap,
			int tilesX)
	{
		ArrayList<Integer> tilesList = new ArrayList<Integer>();
		int numTiles = disparity_bimap[ImageDtt.BI_STR_FULL_INDEX].length;
		if (select_infinity) {
			for (int nTile = 0; nTile < numTiles; nTile++) {
				if (    ((disabled == null)  || !disabled[nTile]) &&
						!Double.isNaN(disparity_bimap[ImageDtt.BI_DISP_CROSS_DX_INDEX][nTile]) &&
						!Double.isNaN(disparity_bimap[ImageDtt.BI_DISP_CROSS_DY_INDEX][nTile]) &&
						((disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile] == 0.0 ) || ignore_target)&& // expected disparity was 0.0 (infinity)
						(disparity_bimap[ImageDtt.BI_STR_FULL_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_main) &&
						(disparity_bimap[ImageDtt.BI_ASTR_FULL_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_aux) &&
						(disparity_bimap[ImageDtt.BI_STR_CROSS_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_rig) &&

						(disparity_bimap[ImageDtt.BI_DISP_FULL_INDEX][nTile] <= clt_parameters.rig.inf_max_disp_main) &&
						(disparity_bimap[ImageDtt.BI_ADISP_FULL_INDEX][nTile] <= clt_parameters.rig.inf_max_disp_aux) &&
						(disparity_bimap[ImageDtt.BI_DISP_CROSS_INDEX][nTile] <= clt_parameters.rig.inf_max_disp_rig) &&

						(disparity_bimap[ImageDtt.BI_DISP_FULL_INDEX][nTile] >= -clt_parameters.rig.inf_max_disp_main) &&
						(disparity_bimap[ImageDtt.BI_ADISP_FULL_INDEX][nTile] >= -clt_parameters.rig.inf_max_disp_aux) &&
						(disparity_bimap[ImageDtt.BI_DISP_CROSS_INDEX][nTile] >= -clt_parameters.rig.inf_max_disp_rig * clt_parameters.rig.inf_neg_tolerance)) {
					tilesList.add(nTile);
				}
			}
		}
		if (select_noninfinity) {
			for (int nTile = 0; nTile < numTiles; nTile++) {
				if (    ((disabled == null)  || !disabled[nTile]) &&
						!Double.isNaN(disparity_bimap[ImageDtt.BI_DISP_CROSS_DX_INDEX][nTile]) &&
						!Double.isNaN(disparity_bimap[ImageDtt.BI_DISP_CROSS_DY_INDEX][nTile]) &&
						(disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile] > 0.0 ) && // expected disparity was > 0.0 (not infinity)
7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656
						(disparity_bimap[ImageDtt.BI_STR_FULL_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_main)&&
						(disparity_bimap[ImageDtt.BI_ASTR_FULL_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_aux)&&
						(disparity_bimap[ImageDtt.BI_STR_CROSS_INDEX][nTile] >= clt_parameters.rig.inf_min_strength_rig)&&
						(Math.abs(disparity_bimap[ImageDtt.BI_DISP_FULL_INDEX][nTile]) <= clt_parameters.rig.near_max_disp_main)&&
						(Math.abs(disparity_bimap[ImageDtt.BI_ADISP_FULL_INDEX][nTile]) <= clt_parameters.rig.near_max_disp_aux)&&
						(Math.abs(disparity_bimap[ImageDtt.BI_DISP_CROSS_INDEX][nTile]) <= clt_parameters.rig.near_max_disp_rig)) {
					tilesList.add(nTile);
				}
			}
		}
		return tilesList;
	}



	public void showListedRigTiles(
			String title,
			ArrayList<Integer> tile_list,
			double[][] disparity_bimap,
			int tilesX ){
		int numTiles = disparity_bimap[ImageDtt.BI_STR_FULL_INDEX].length;
		String [] titles = {"disparity", "dx","dy","strength","target"};
		double [][] dbg_inf = new double [5][numTiles];
		for (int nTile = 0; nTile < numTiles; nTile++){
			dbg_inf[0][nTile] = Double.NaN;
			dbg_inf[1][nTile] = Double.NaN;
			dbg_inf[2][nTile] = Double.NaN;
			dbg_inf[3][nTile] = Double.NaN; // 0.0;
			dbg_inf[4][nTile] = Double.NaN; // 0.0;
		}
		for (int nTile:tile_list) {
			dbg_inf[0][nTile] = disparity_bimap[ImageDtt.BI_DISP_CROSS_INDEX][nTile];
			dbg_inf[1][nTile] = disparity_bimap[ImageDtt.BI_DISP_CROSS_DX_INDEX][nTile];
			dbg_inf[2][nTile] = disparity_bimap[ImageDtt.BI_DISP_CROSS_DY_INDEX][nTile];
			dbg_inf[3][nTile] = disparity_bimap[ImageDtt.BI_STR_CROSS_INDEX][nTile];
			dbg_inf[4][nTile] = disparity_bimap[ImageDtt.BI_TARGET_INDEX][nTile];
		}
7657
		(new ShowDoubleFloatArrays()).showArrays(
7658 7659 7660 7661 7662 7663 7664 7665 7666
				dbg_inf,
				tilesX,
				numTiles/tilesX,
				true,
				title,
				titles );
	}

	public void batchRig(
7667 7668
			QuadCLT                                              quadCLT_main,  // tiles should be set
			QuadCLT                                              quadCLT_aux,
7669
			CLTParameters             clt_parameters,
7670
			EyesisCorrectionParameters.DebayerParameters         debayerParameters,
7671 7672
			ColorProcParameters                                  colorProcParameters,
			ColorProcParameters                                  colorProcParameters_aux,
7673 7674
			CorrectionColorProc.ColorGainsParameters             channelGainParameters,
			EyesisCorrectionParameters.RGBParameters             rgbParameters,
7675
			EyesisCorrectionParameters.EquirectangularParameters equirectangularParameters,
7676
			Properties                                           properties,
7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel)  throws Exception
	{
		//		  final boolean    batch_mode = clt_parameters.batch_run;
		final int        debugLevelInner=clt_parameters.batch_run? -2: debugLevel;
		this.startTime=System.nanoTime();
		String [] sourceFiles=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		QuadCLT.SetChannels [] set_channels_aux =  quadCLT_aux.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0) || (set_channels_aux == null) || (set_channels_aux.length==0)) {
			System.out.println("No files to process (of "+sourceFiles.length+")");
			return;
		}
		double [] referenceExposures_main = quadCLT_main.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		double [] referenceExposures_aux =  quadCLT_aux.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		for (int nSet = 0; nSet < set_channels_main.length; nSet++){
			// check it is the same set for both cameras
			if (set_channels_aux.length <= nSet ) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: nothing");
			}
			if (!set_channels_main[nSet].name().equals(set_channels_aux[nSet].name())) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: '"+set_channels_main[nSet].name()+"'");
			}

			int [] channelFiles_main = set_channels_main[nSet].fileNumber();
			int [] channelFiles_aux =  set_channels_aux[nSet].fileNumber();
			boolean [][] saturation_imp_main = (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			boolean [][] saturation_imp_aux =  (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			double [] scaleExposures_main = new double[channelFiles_main.length];
			double [] scaleExposures_aux =  new double[channelFiles_main.length];
7708
			if (updateStatus) IJ.showStatus("Conditioning main camera image set for "+quadCLT_main.image_name);
7709 7710
			ImagePlus [] imp_srcs_main = quadCLT_main.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
7711
					colorProcParameters,            //  ColorProcParameters                       colorProcParameters, //
7712 7713 7714 7715 7716 7717
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_main[nSet].name(), // String                                    set_name,
					referenceExposures_main,        // double []                                 referenceExposures,
					channelFiles_main,              // int []                                    channelFiles,
					scaleExposures_main,            //output  // double [] scaleExposures
					saturation_imp_main,            //output  // boolean [][]                              saturation_imp,
7718
					threadsMax,                 // int                                       threadsMax,
7719
					debugLevelInner); // int                                       debugLevel);
7720
			if (updateStatus) IJ.showStatus("Conditioning aux camera image set for "+quadCLT_main.image_name);
7721 7722
			ImagePlus [] imp_srcs_aux = quadCLT_aux.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
7723
					colorProcParameters_aux,        //  ColorProcParameters                       colorProcParameters, //
7724 7725 7726 7727 7728 7729
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_aux[nSet].name(), // String                                    set_name,
					referenceExposures_aux,        // double []                                 referenceExposures,
					channelFiles_aux,              // int []                                    channelFiles,
					scaleExposures_aux,            //output  // double [] scaleExposures
					saturation_imp_aux,            //output  // boolean [][]                              saturation_imp,
7730
					threadsMax,                 // int                                       threadsMax,
7731 7732 7733
					debugLevelInner); // int                                       debugLevel);

			// optionally adjust main, aux, rig here
7734
			// Early main camera adjustment, rig data is not available
7735
			for (int num_adjust_main = 0; num_adjust_main < quadCLT_main.correctionsParameters.rig_batch_adjust_main; num_adjust_main++) {
7736 7737 7738 7739 7740 7741
				if (updateStatus) IJ.showStatus("Building basic  DSI for the main camera image set "+quadCLT_main.image_name+
						" (w/o rig), pass "+(num_adjust_main+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_main);
				if (debugLevel > -5) {
					System.out.println("Building basic  DSI for the main camera image set "+quadCLT_main.image_name+
							" (w/o rig), pass "+(num_adjust_main+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_main);
				}
7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754

				quadCLT_main.preExpandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						imp_srcs_main, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
						saturation_imp_main, // boolean [][] saturation_imp, // (near) saturated pixels or null
						clt_parameters,
						debayerParameters,
						colorProcParameters,
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevelInner);
				// adjust extrinsics here
				System.out.println("Adjust main extrinsics here");
7755 7756 7757 7758 7759 7760
				if (updateStatus) IJ.showStatus("Adjusting main camera image set for "+quadCLT_main.image_name+
						" (w/o rig), pass "+(num_adjust_main+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_main);
				if (debugLevel > -5) {
					System.out.println("Adjusting main camera image set for "+quadCLT_main.image_name+
							" (w/o rig), pass "+(num_adjust_main+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_main);
				}
7761
				boolean ok = quadCLT_main.extrinsicsCLT(
7762 7763
						clt_parameters, // EyesisCorrectionParameters.CLTParameters           clt_parameters,
						false, // adjust_poly,
7764 7765
						  -1.0, // double inf_min,
						  1.0,  // double inf_max,
7766 7767 7768
						threadsMax,  //final int        threadsMax,  // maximal number of threads to launch
						updateStatus,// final boolean    updateStatus,
						debugLevelInner); // final int        debugLevel)
7769 7770
// clear memory for main
				quadCLT_main.tp.resetCLTPasses();
7771
				if (!ok) break;
7772 7773

			}
7774
			// Early aux camera adjustment, rig data is not available
7775
			for (int num_adjust_aux = 0; num_adjust_aux < quadCLT_main.correctionsParameters.rig_batch_adjust_aux; num_adjust_aux++) {
7776 7777 7778 7779 7780 7781
				if (updateStatus) IJ.showStatus("Building basic DSI for the aux camera image set "+quadCLT_main.image_name+
						" (w/o rig), pass "+(num_adjust_aux+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_aux);
				if (debugLevel > -5) {
					System.out.println("Building basic DSI for the aux camera image set "+quadCLT_main.image_name+
							" (w/o rig), pass "+(num_adjust_aux+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_aux);
				}
7782 7783 7784 7785 7786
				quadCLT_aux.preExpandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						imp_srcs_aux, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
						saturation_imp_aux, // boolean [][] saturation_imp, // (near) saturated pixels or null
						clt_parameters,
						debayerParameters,
7787
						colorProcParameters_aux,
7788 7789 7790 7791 7792
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevelInner);
				// adjust extrinsics here
7793 7794 7795 7796 7797 7798
				if (updateStatus) IJ.showStatus("Adjusting aux camera image set for "+quadCLT_main.image_name+
						" (w/o rig), pass "+(num_adjust_aux+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_aux);
				if (debugLevel > -5) {
					System.out.println("Adjusting aux camera image set for "+quadCLT_main.image_name+
							" (w/o rig), pass "+(num_adjust_aux+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_aux);
				}
7799 7800 7801 7802 7803 7804 7805
			    double inf_min = -1.0;
			    double inf_max =  1.0;
			    if (num_adjust_aux >= (quadCLT_main.correctionsParameters.rig_batch_adjust_aux/2)) {
			        inf_min = -0.2;
			        inf_max = 0.05;
			    }
				
7806
				boolean ok = quadCLT_aux.extrinsicsCLT(
7807 7808
						clt_parameters, // EyesisCorrectionParameters.CLTParameters           clt_parameters,
						false,          // adjust_poly,
7809 7810
			            inf_min, // double inf_min,
			            inf_max,  // double inf_max,
7811 7812 7813
						threadsMax,     //final int        threadsMax,  // maximal number of threads to launch
						updateStatus,   // final boolean    updateStatus,
						debugLevelInner);    // final int        debugLevel)
7814 7815
				// clear memory for aux
				quadCLT_aux.tp.resetCLTPasses();
7816
				if (!ok) break;
7817
			}
7818
			// Early rig adjustment, main/aux are not adjusted with rig data
7819
			for (int num_adjust_rig = 0; num_adjust_rig < quadCLT_main.correctionsParameters.rig_batch_adjust_rig; num_adjust_rig++) {
7820 7821 7822 7823 7824 7825 7826
				if (updateStatus) IJ.showStatus("Adjusting dual camera rig infinity (early) for "+quadCLT_main.image_name+
						", pass "+(num_adjust_rig+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_rig);
				if (debugLevel > -5) {
					System.out.println("Adjusting dual camera rig infinity (early) for "+quadCLT_main.image_name+
							", pass "+(num_adjust_rig+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_rig);
				}

7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838
				processInfinityRig(
						quadCLT_main,               // QuadCLT                                        quadCLT_main,
						quadCLT_aux,                // QuadCLT                                        quadCLT_aux,
						imp_srcs_main,              // ImagePlus []                                   imp_quad_main,
						imp_srcs_aux,               // ImagePlus []                                   imp_quad_aux,
						saturation_imp_main,        // boolean [][]                                   saturation_main, // (near) saturated pixels or null
						saturation_imp_aux,         // boolean [][]                                   saturation_aux, // (near) saturated pixels or null
						clt_parameters,             // EyesisCorrectionParameters.CLTParameters       clt_parameters,
						threadsMax,                 // final int        threadsMax,  // maximal number of threads to launch
						updateStatus,               // final boolean    updateStatus,
						debugLevelInner-2);                // final int        debugLevel);
			}
7839
			// Delete previous results if any camera adjustments were made
7840 7841 7842 7843
			if (    (quadCLT_main.correctionsParameters.rig_batch_adjust_main > 0) ||
					(quadCLT_main.correctionsParameters.rig_batch_adjust_aux > 0) ||
					(quadCLT_main.correctionsParameters.rig_batch_adjust_rig > 0)) {

7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885
				if (debugLevel > -5) {
					System.out.println("\n---- Field adjustments after the first round ----");
					quadCLT_main.showExtrinsicCorr("main");  // show_fine_corr("main");
					quadCLT_aux.showExtrinsicCorr("aux");    // show_fine_corr("aux");
					quadCLT_aux.geometryCorrection.showRig();// show_fine_corr("aux");
				}
				biCamDSI_persistent = null;
				quadCLT_main.tp.resetCLTPasses();
				quadCLT_aux.tp.resetCLTPasses();

			}

			if ((quadCLT_main.correctionsParameters.rig_batch_adjust_main_gt > 0) ||
					(quadCLT_main.correctionsParameters.rig_batch_adjust_main_gt > 0)){
				{
					if (updateStatus) IJ.showStatus("Building basic DSI for the main camera image set "+quadCLT_main.image_name+ " (post rig adjustment)");
					quadCLT_main.preExpandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
							imp_srcs_main, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
							saturation_imp_main, // boolean [][] saturation_imp, // (near) saturated pixels or null
							clt_parameters,
							debayerParameters,
							colorProcParameters,
							rgbParameters,
							threadsMax,  // maximal number of threads to launch
							updateStatus,
							debugLevelInner);
					if (updateStatus) IJ.showStatus("Expanding DSI for the main camera image set "+quadCLT_main.image_name+ " (post rig adjustment)");
					quadCLT_main.expandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
							clt_parameters,
							debayerParameters,
							colorProcParameters,
							channelGainParameters,
							rgbParameters,
							threadsMax,  // maximal number of threads to launch
							updateStatus,
							debugLevel);
					if (updateStatus) IJ.showStatus("Refining main camera DSI with the rig for "+quadCLT_main.image_name);
					// Prepare DSI from the main camera, then refine it with the rig to get the "GT" data for the main/aux
					BiScan scan = rigInitialScan(
							quadCLT_main,  // QuadCLT            quadCLT_main,  // tiles should be set
							quadCLT_aux,  // QuadCLT            quadCLT_aux,
							clt_parameters, // EyesisCorrectionParameters.CLTParameters       clt_parameters,
7886 7887
							colorProcParameters,           //  ColorProcParameters                       colorProcParameters, //
							colorProcParameters_aux,          //  ColorProcParameters                       colorProcParameters, //
7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905
							threadsMax,  // final int                                      threadsMax,  // maximal number of threads to launch
							updateStatus, // final boolean                                  updateStatus,
							debugLevel); // final int                                      debugLevel)
					if (scan == null) {
						System.out.println("***** Failed to get main camera DSI and refine it with the rig, aborting this image set *****");
						continue;
					}

				}
			}

			for (int num_adjust_main = 0; num_adjust_main < quadCLT_main.correctionsParameters.rig_batch_adjust_main_gt; num_adjust_main++) {
				if (updateStatus) IJ.showStatus("Adjusting main camera image set for "+quadCLT_main.image_name+
						" (with rig DSI), pass "+(num_adjust_main+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_main_gt);
				if (debugLevel > -5) {
					System.out.println("Adjusting main camera image set for "+quadCLT_main.image_name+
							" (with rig DSI), pass "+(num_adjust_main+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_main_gt);
				}
7906 7907 7908 7909 7910 7911 7912 7913 7914
				double [][] gt_disp_strength = quadCLT_main.getRigDSFromTwoQuadCL(
						this, //maybe null in no-rig mode, otherwise may contain rig measurements to be used as infinity ground truth
						clt_parameters,
						debugLevelInner); // final int        debugLevel)

//				  GeometryCorrection geometryCorrection_main = null;
//				  if (geometryCorrection.getRotMatrix(true) != null) {
//					  geometryCorrection_main = twoQuadCLT.quadCLT_main.getGeometryCorrection();
//				  }
7915

7916
				boolean ok = quadCLT_main.extrinsicsCLTfromGT(
7917 7918 7919 7920 7921 7922 7923 7924
						//						  this,   // TwoQuadCLT       twoQuadCLT, //maybe null in no-rig mode, otherwise may contain rig measurements to be used as infinity ground truth
						null,
						gt_disp_strength,
						clt_parameters, // EyesisCorrectionParameters.CLTParameters           clt_parameters,
						false,
						threadsMax,  //final int        threadsMax,  // maximal number of threads to launch
						updateStatus,// final boolean    updateStatus,
						debugLevelInner); // final int        debugLevel)
7925
				if (!ok) break;
7926
			}
7927

7928 7929 7930 7931 7932 7933 7934
			for (int num_adjust_aux = 0; num_adjust_aux < quadCLT_main.correctionsParameters.rig_batch_adjust_aux_gt; num_adjust_aux++) {
				if (updateStatus) IJ.showStatus("Adjusting aux camera image set for "+quadCLT_main.image_name+
						" (with rig DSI), pass "+(num_adjust_aux+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_aux_gt);
				if (debugLevel > -5) {
					System.out.println("Adjusting aux camera image set for "+quadCLT_main.image_name+
							" (with rig DSI), pass "+(num_adjust_aux+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_aux_gt);
				}
7935 7936 7937 7938
				double [][] gt_disp_strength = quadCLT_aux.getRigDSFromTwoQuadCL(
						this, //maybe null in no-rig mode, otherwise may contain rig measurements to be used as infinity ground truth
						clt_parameters,
						debugLevelInner); // final int        debugLevel)
7939

7940
				boolean ok = quadCLT_aux.extrinsicsCLTfromGT(
7941 7942 7943
//						  this,   // TwoQuadCLT       twoQuadCLT, //maybe null in no-rig mode, otherwise may contain rig measurements to be used as infinity ground truth
						  quadCLT_main.getGeometryCorrection(),
						  gt_disp_strength,
7944 7945 7946 7947 7948
						  clt_parameters, // EyesisCorrectionParameters.CLTParameters           clt_parameters,
						  false,
						  threadsMax,  //final int        threadsMax,  // maximal number of threads to launch
						  updateStatus,// final boolean    updateStatus,
						  debugLevelInner); // final int        debugLevel)
7949
				if (!ok) break;
7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984
			}
			// Late rig adjustment, after main/aux are adjusted with rig data as ground truth
			// keeping the same DSI, required measurements will be performed anyway
			for (int num_adjust_rig = 0; num_adjust_rig < quadCLT_main.correctionsParameters.rig_batch_adjust_rig_gt; num_adjust_rig++) {
				if (updateStatus) IJ.showStatus("Adjusting dual camera rig infinity (late, after re-adjustment of the main/aux) for "+quadCLT_main.image_name+
						", pass "+(num_adjust_rig+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_rig_gt);
				if (debugLevel > -5) {
					System.out.println("Adjusting dual camera rig infinity (late, after re-adjustment of the main/aux) for "+quadCLT_main.image_name+
							", pass "+(num_adjust_rig+1)+" of "+quadCLT_main.correctionsParameters.rig_batch_adjust_rig_gt);
				}

				processInfinityRig(
						quadCLT_main,               // QuadCLT                                        quadCLT_main,
						quadCLT_aux,                // QuadCLT                                        quadCLT_aux,
						imp_srcs_main,              // ImagePlus []                                   imp_quad_main,
						imp_srcs_aux,               // ImagePlus []                                   imp_quad_aux,
						saturation_imp_main,        // boolean [][]                                   saturation_main, // (near) saturated pixels or null
						saturation_imp_aux,         // boolean [][]                                   saturation_aux, // (near) saturated pixels or null
						clt_parameters,             // EyesisCorrectionParameters.CLTParameters       clt_parameters,
						threadsMax,                 // final int        threadsMax,  // maximal number of threads to launch
						updateStatus,               // final boolean    updateStatus,
						debugLevelInner-2);                // final int        debugLevel);
			}
			// Delete previous results if any of the late adjustments were performed
			if (    (quadCLT_main.correctionsParameters.rig_batch_adjust_main_gt > 0) ||
					(quadCLT_main.correctionsParameters.rig_batch_adjust_aux_gt > 0) ||
					(quadCLT_main.correctionsParameters.rig_batch_adjust_rig_gt > 0)) {

				if (debugLevel > -5) {
					System.out.println("\n---- Field adjustments after the second round ----");
					quadCLT_main.showExtrinsicCorr("main");  // show_fine_corr("main");
					quadCLT_aux.showExtrinsicCorr("aux");    // show_fine_corr("aux");
					quadCLT_aux.geometryCorrection.showRig();// show_fine_corr("aux");
				}
				biCamDSI_persistent = null;
7985 7986 7987 7988 7989 7990 7991
				quadCLT_main.tp.resetCLTPasses();
				quadCLT_aux.tp.resetCLTPasses();

			}

			// Generate 8 images and thumbnails
			if (quadCLT_main.correctionsParameters.clt_batch_4img){
7992
				if (updateStatus) IJ.showStatus("Rendering 8 image set (disparity = 0) for "+quadCLT_main.image_name);
7993 7994 7995 7996 7997 7998 7999 8000 8001 8002
				processCLTQuadCorrPair(
						quadCLT_main,               // QuadCLT                                        quadCLT_main,
						quadCLT_aux,                // QuadCLT                                        quadCLT_aux,
						imp_srcs_main,              // ImagePlus []                                   imp_quad_main,
						imp_srcs_aux,               // ImagePlus []                                   imp_quad_aux,
						saturation_imp_main,        // boolean [][]                                   saturation_main, // (near) saturated pixels or null
						saturation_imp_aux,         // boolean [][]                                   saturation_aux, // (near) saturated pixels or null
						clt_parameters,             // EyesisCorrectionParameters.CLTParameters       clt_parameters,
						debayerParameters,          // EyesisCorrectionParameters.DebayerParameters   debayerParameters,
						colorProcParameters,        // EyesisCorrectionParameters.ColorProcParameters colorProcParameters,
8003
						colorProcParameters_aux,    // EyesisCorrectionParameters.ColorProcParameters colorProcParameters_aux,
8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017
						rgbParameters,              // EyesisCorrectionParameters.RGBParameters       rgbParameters,
						scaleExposures_main,        // double []	                                     scaleExposures_main, // probably not needed here - restores brightness of the final image
						scaleExposures_aux,         // double []	                                     scaleExposures_aux, // probably not needed here - restores brightness of the final image
						false,                      //  final boolean             notch_mode,      // use notch filter for inter-camera correlation to detect poles
						// averages measurements
						clt_parameters.rig.lt_avg_radius,// final int                                      lt_rad,          // low texture mode - inter-correlation is averaged between the neighbors before argmax-ing, using
						threadsMax,                 // final int        threadsMax,  // maximal number of threads to launch
						updateStatus,               // final boolean    updateStatus,
						debugLevelInner);                // final int        debugLevel);
			}
			// ground truth and then all the rest

			quadCLT_main.tp.resetCLTPasses();
			quadCLT_aux.tp.resetCLTPasses();
8018 8019 8020 8021 8022 8023 8024
			if (quadCLT_main.correctionsParameters.clt_batch_dsi_aux) {
				if (updateStatus) IJ.showStatus("Building basic DSI for the aux camera image set "+quadCLT_main.image_name+" (for DSI export)");
				quadCLT_aux.preExpandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						imp_srcs_aux, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
						saturation_imp_aux, // boolean [][] saturation_imp, // (near) saturated pixels or null
						clt_parameters,
						debayerParameters,
8025
						colorProcParameters_aux,
8026 8027 8028 8029 8030 8031 8032 8033
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevelInner);
				if (updateStatus) IJ.showStatus("Expanding DSI for the aux camera image set "+quadCLT_main.image_name+" (for DSI export)");
				quadCLT_aux.expandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						clt_parameters,
						debayerParameters,
8034
						colorProcParameters_aux,
8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048
						channelGainParameters,
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevel);
				double [][] aux_last_scan = quadCLT_aux.tp.getShowDS(
						quadCLT_aux.tp.clt_3d_passes.get( quadCLT_aux.tp.clt_3d_passes.size() -1),
						false); // boolean force_final);

				dsi[DSI_DISPARITY_AUX] = aux_last_scan[0];
				dsi[DSI_STRENGTH_AUX] =  aux_last_scan[1];
				quadCLT_aux.tp.resetCLTPasses();
			}

8049
			if (quadCLT_main.correctionsParameters.clt_batch_explore) {
8050
				if (updateStatus) IJ.showStatus("Building basic DSI for the main camera image set "+quadCLT_main.image_name+" (after all adjustments)");
8051 8052 8053 8054 8055 8056 8057 8058 8059 8060
				quadCLT_main.preExpandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						imp_srcs_main, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
						saturation_imp_main, // boolean [][] saturation_imp, // (near) saturated pixels or null
						clt_parameters,
						debayerParameters,
						colorProcParameters,
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevelInner);
8061
				if (updateStatus) IJ.showStatus("Expanding DSI for the main camera image set "+quadCLT_main.image_name+" (after all adjustments)");
8062 8063 8064 8065 8066 8067 8068 8069 8070
				quadCLT_main.expandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						clt_parameters,
						debayerParameters,
						colorProcParameters,
						channelGainParameters,
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevel);
8071 8072 8073 8074 8075 8076 8077 8078 8079
				double [][] main_last_scan = quadCLT_main.tp.getShowDS(
						quadCLT_main.tp.clt_3d_passes.get( quadCLT_main.tp.clt_3d_passes.size() -1),
						false); // boolean force_final);

				dsi[DSI_DISPARITY_MAIN] = main_last_scan[0];
				dsi[DSI_STRENGTH_MAIN] =  main_last_scan[1];

//				CLTPass3d scan_last = quadCLT_main.tp.clt_3d_passes.get( quadCLT_main.tp.clt_3d_passes.size() -1);

8080
				if (updateStatus) IJ.showStatus("Creating \"ground truth\" DSI using dual-camera rig "+quadCLT_main.image_name);
8081 8082 8083 8084
				groundTruth(                        // actually there is no sense to process multiple image sets. Combine with other processing?
						quadCLT_main,               // QuadCLT quadCLT_main,
						quadCLT_aux,                // QuadCLT quadCLT_aux,
						clt_parameters,             // EyesisCorrectionParameters.CLTParameters       clt_parameters,
8085 8086
						colorProcParameters,          //  ColorProcParameters                       colorProcParameters, //
						colorProcParameters_aux,          //  ColorProcParameters                       colorProcParameters, //
8087 8088 8089
						threadsMax,                 // final int        threadsMax,  // maximal number of threads to launch
						updateStatus,               // final boolean    updateStatus,
						debugLevelInner-2);                // final int        debugLevel);
8090 8091 8092 8093 8094 8095
				double [][] rig_last_scan = quadCLT_main.tp.getShowDS(
						quadCLT_main.tp.clt_3d_passes.get( quadCLT_main.tp.clt_3d_passes.size() -1),
						false); // boolean force_final);

				dsi[DSI_DISPARITY_RIG] = rig_last_scan[0];
				dsi[DSI_STRENGTH_RIG] =  rig_last_scan[1];
8096

8097 8098 8099
			} else {
				continue;
			}
8100
			resetRig   (false); // includes biCamDSI_persistent = null
8101 8102 8103 8104
			Runtime.getRuntime().gc();
			System.out.println("--- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

			if (quadCLT_main.correctionsParameters.clt_batch_surf) {
8105 8106
				if (updateStatus) IJ.showStatus("Creating and filtering supertile plane surfaces from the DSI "+quadCLT_main.image_name);

8107 8108 8109 8110 8111 8112 8113 8114 8115 8116
				quadCLT_main.tp.showPlanes(
						clt_parameters,
						quadCLT_main.geometryCorrection,
						threadsMax,
						updateStatus,
						debugLevelInner);

			} else continue; // if (correctionsParameters.clt_batch_surf)

			if (quadCLT_main.correctionsParameters.clt_batch_assign) {
8117
				if (updateStatus) IJ.showStatus("Assigning tiles to candidate surfaces "+quadCLT_main.image_name);
8118 8119 8120 8121 8122 8123 8124
				// prepare average RGBA for the last scan
				quadCLT_main.setPassAvgRBGA(                      // get image from a single pass, return relative path for x3d // USED in lwir
						clt_parameters,                           // CLTParameters           clt_parameters,
						quadCLT_main.tp.clt_3d_passes.size() - 1, // int        scanIndex,
						threadsMax,                               // int        threadsMax,  // maximal number of threads to launch
						updateStatus,                             // boolean    updateStatus,
						debugLevelInner);                         // int        debugLevel)
8125
				double [][] assignments_dbg = quadCLT_main.tp.assignTilesToSurfaces(
8126 8127 8128 8129 8130
						clt_parameters,
						quadCLT_main.geometryCorrection,
						threadsMax,
						updateStatus,
						debugLevelInner);
8131 8132 8133 8134 8135
				if (assignments_dbg == null) continue;
				dsi[DSI_DISPARITY_X3D] = assignments_dbg[TileSurface.ASGN_A_DISP];

// TODO use assignments_dbg

8136
			} else continue; // if (correctionsParameters.clt_batch_assign)
8137 8138 8139 8140 8141 8142
			// generate ML data if enabled
			if (quadCLT_main.correctionsParameters.clt_batch_genMl) { // rig.ml_generate) { //clt_batch_genMl
				outputMLData(
						quadCLT_main,   // QuadCLT                                  quadCLT_main,  // tiles should be set
						quadCLT_aux,    // QuadCLT                                  quadCLT_aux,
						clt_parameters, // EyesisCorrectionParameters.CLTParameters clt_parameters,
8143
	    				null,           //String                                   ml_directory,       // full path or null (will use config one)
8144 8145 8146
						threadsMax,     // final int                                threadsMax,  // maximal number of threads to launch
						updateStatus,   // final boolean                            updateStatus,
						debugLevel);    // final int                                debugLevel)
8147
				/*
8148 8149 8150 8151 8152 8153
				if (clt_parameters.rig.ml_copyJP4) {
					copyJP4src(
							quadCLT_main,   // QuadCLT                                  quadCLT_main,  // tiles should be set
							quadCLT_aux,    // QuadCLT                                  quadCLT_aux,
							clt_parameters, // EyesisCorrectionParameters.CLTParameters clt_parameters,
							debugLevel);    // final int                                debugLevel)
8154 8155 8156 8157 8158 8159 8160 8161 8162
				}*/
			}
			// copy regardless of ML generation
			if (clt_parameters.rig.ml_copyJP4) {
				copyJP4src(
						quadCLT_main,   // QuadCLT                                  quadCLT_main,  // tiles should be set
						quadCLT_aux,    // QuadCLT                                  quadCLT_aux,
						clt_parameters, // EyesisCorrectionParameters.CLTParameters clt_parameters,
						debugLevel);    // final int                                debugLevel)
8163
			}
8164 8165

			if (quadCLT_main.correctionsParameters.clt_batch_gen3d) {
8166
				if (updateStatus) IJ.showStatus("Generating and exporting 3D scene model "+quadCLT_main.image_name);
8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177
				boolean ok = quadCLT_main.output3d(
						clt_parameters,      // EyesisCorrectionParameters.CLTParameters           clt_parameters,
						colorProcParameters, // EyesisCorrectionParameters.ColorProcParameters colorProcParameters,
						rgbParameters,       // EyesisCorrectionParameters.RGBParameters             rgbParameters,
						threadsMax,          // final int        threadsMax,  // maximal number of threads to launch
						updateStatus,        // final boolean    updateStatus,
						debugLevelInner);         // final int        debugLevel)
				if (!ok) continue;
			} else continue; // if (correctionsParameters.clt_batch_gen3d)


8178
			if (quadCLT_main.correctionsParameters.clt_batch_dsi) {
Andrey Filippov's avatar
Andrey Filippov committed
8179 8180
				quadCLT_main.saveDSI (
						dsi);
8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194
			}

			if (quadCLT_main.correctionsParameters.clt_batch_save_extrinsics) {
				 saveProperties(
							null,        // String path,                // full name with extension or w/o path to use x3d directory
							null,        // Properties properties,    // if null - will only save extrinsics)
							debugLevel);
			}
			if (quadCLT_main.correctionsParameters.clt_batch_save_all) {
				 saveProperties(
							null,        // String path,                // full name with extension or w/o path to use x3d directory
							properties,  // Properties properties,    // if null - will only save extrinsics)
							debugLevel);
			}
8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205
			Runtime.getRuntime().gc();
			if (debugLevel >-1) System.out.println("Processing set "+(nSet+1)+" (of "+set_channels_aux.length+") finished at "+
					IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

			if (quadCLT_aux.eyesisCorrections.stopRequested.get()>0) {
				System.out.println("User requested stop");
				System.out.println("Processing "+(nSet + 1)+" file sets (of "+set_channels_main.length+") finished at "+
						IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");
				return;
			}
		}
8206
		System.out.println("batchRig(): processing "+(quadCLT_main.getTotalFiles(set_channels_main)+quadCLT_aux.getTotalFiles(set_channels_aux))+" files ("+set_channels_main.length+" file sets) finished at "+
8207 8208 8209
				IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

	}
8210

Andrey Filippov's avatar
Andrey Filippov committed
8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260
	public void TestInterScene(
			QuadCLT                                              quadCLT_main, // tiles should be set
//			QuadCLT                                              quadCLT_aux,
			CLTParameters             clt_parameters,
			EyesisCorrectionParameters.DebayerParameters         debayerParameters,
			ColorProcParameters                                  colorProcParameters,
			ColorProcParameters                                  colorProcParameters_aux,
			CorrectionColorProc.ColorGainsParameters             channelGainParameters,
			EyesisCorrectionParameters.RGBParameters             rgbParameters,
			EyesisCorrectionParameters.EquirectangularParameters equirectangularParameters,
			Properties                                           properties,
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel)  throws Exception
	{
		if ((quadCLT_main != null) && (quadCLT_main.getGPU() != null)) {
			quadCLT_main.getGPU().resetGeometryCorrection();
			quadCLT_main.gpuResetCorrVector(); // .getGPU().resetGeometryCorrectionVector();
		}
		// final boolean    batch_mode = clt_parameters.batch_run;
		this.startTime=System.nanoTime();
		String [] sourceFiles0=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0)) {
			System.out.println("No files to process (of "+sourceFiles0.length+")");
			return;
		}
		QuadCLT.SetChannels [] set_channels=quadCLT_main.setChannels(debugLevel);
//		String set_name = set_channels[0].set_name;
		
		QuadCLT [] quadCLTs = new QuadCLT [set_channels.length]; 
		for (int i = 0; i < quadCLTs.length; i++) {
			quadCLTs[i] = quadCLT_main.spawnQuadCLT(
					set_channels[i].set_name,
					clt_parameters,
					colorProcParameters, //
					threadsMax,
					debugLevel);
			// temporarily fix wrong sign:
			ErsCorrection ers = (ErsCorrection) (quadCLTs[i].getGeometryCorrection());
			ers.setupERSfromExtrinsics();			
			quadCLTs[i].setDSRBG(
					clt_parameters, // CLTParameters  clt_parameters,
					threadsMax,     // int            threadsMax,  // maximal number of threads to launch
					updateStatus,   // boolean        updateStatus,
					debugLevel);    // int            debugLevel)
///			quadCLTs[i].showDSIMain();
		}
		
		
8261 8262
///		double k_prev = 0.75;
///		double corr_scale = 0.75;
8263 8264 8265 8266
		OpticalFlow opticalFlow = new OpticalFlow(
				threadsMax, // int            threadsMax,  // maximal number of threads to launch
				updateStatus); // boolean        updateStatus);
		
8267
		for (int i = 1; i < quadCLTs.length; i++) {
Andrey Filippov's avatar
Andrey Filippov committed
8268
			QuadCLT qPrev = (i > 0) ? quadCLTs[i - 1] : null;
8269 8270 8271 8272 8273 8274 8275 8276 8277 8278


			//			double [][][] pair_sets =
			opticalFlow.get_pair(
					clt_parameters, // CLTParameters  clt_parameters,
					clt_parameters.ofp.k_prev, // k_prev,
					quadCLTs[i],
					qPrev,
					clt_parameters.ofp.ers_to_pose_scale, // corr_scale,
					clt_parameters.ofp.debug_level_optical); // 1); // -1); // int debug_level);
Andrey Filippov's avatar
Andrey Filippov committed
8279 8280 8281 8282 8283 8284
		}


		System.out.println("End of test");


8285
	}
8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396
	
	public void interPairsLMA(
			QuadCLT                                              quadCLT_main, // tiles should be set
			CLTParameters             clt_parameters,
			EyesisCorrectionParameters.DebayerParameters         debayerParameters,
			ColorProcParameters                                  colorProcParameters,
			ColorProcParameters                                  colorProcParameters_aux,
			CorrectionColorProc.ColorGainsParameters             channelGainParameters,
			EyesisCorrectionParameters.RGBParameters             rgbParameters,
			EyesisCorrectionParameters.EquirectangularParameters equirectangularParameters,
			Properties                                           properties,
			boolean                                              reset_from_extrinsics,
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel)  throws Exception
	{
		if ((quadCLT_main != null) && (quadCLT_main.getGPU() != null)) {
			quadCLT_main.getGPU().resetGeometryCorrection();
			quadCLT_main.gpuResetCorrVector(); // .getGPU().resetGeometryCorrectionVector();
		}
		// final boolean    batch_mode = clt_parameters.batch_run;
		this.startTime=System.nanoTime();
		String [] sourceFiles0=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0)) {
			System.out.println("No files to process (of "+sourceFiles0.length+")");
			return;
		}
		QuadCLT.SetChannels [] set_channels=quadCLT_main.setChannels(debugLevel);
//		String set_name = set_channels[0].set_name;
		
		QuadCLT [] quadCLTs = new QuadCLT [set_channels.length]; 
		for (int i = 0; i < quadCLTs.length; i++) {
			quadCLTs[i] = quadCLT_main.spawnQuadCLT(
					set_channels[i].set_name,
					clt_parameters,
					colorProcParameters, //
					threadsMax,
					debugLevel);
			// temporarily fix wrong sign:
//			ErsCorrection ers = (ErsCorrection) (quadCLTs[i].getGeometryCorrection());
			ErsCorrection ers = quadCLTs[i].getErsCorrection();
			if (reset_from_extrinsics) {
				System.out.println("Reset ERS parameters from intraframe extrinsics");
				ers.setupERSfromExtrinsics();
			}
			quadCLTs[i].setDSRBG(
					clt_parameters, // CLTParameters  clt_parameters,
					threadsMax,     // int            threadsMax,  // maximal number of threads to launch
					updateStatus,   // boolean        updateStatus,
					debugLevel);    // int            debugLevel)
///			quadCLTs[i].showDSIMain();
		}
		
		
		OpticalFlow opticalFlow = new OpticalFlow(
				threadsMax, // int            threadsMax,  // maximal number of threads to launch
				updateStatus); // boolean        updateStatus);
		
		for (int i = 1; i < quadCLTs.length; i++) {
			QuadCLT qPrev = (i > 0) ? quadCLTs[i - 1] : null;
			//			double [][][] pair_sets =
			double [][] pose = 	opticalFlow.getPoseFromErs(
					clt_parameters.ofp.k_prev, // k_prev,
					quadCLTs[i],
					qPrev,
					clt_parameters.ofp.debug_level_optical); // 1); // -1); // int debug_level);
			// how was it working before? qPrev.getErsCorrection() shoud remain what was set in the previous adjustment 
			quadCLTs[i].getErsCorrection().setupERSfromExtrinsics();
			qPrev.getErsCorrection().setupERSfromExtrinsics();
			
			opticalFlow.adjustPairsLMA(
					clt_parameters, // CLTParameters  clt_parameters,
//					clt_parameters.ofp.k_prev, // k_prev,
					quadCLTs[i],
					qPrev,
					pose[0], // xyz
					pose[1], // atr
					clt_parameters.ilp.ilma_lma_select,             // final boolean[]   param_select,
					clt_parameters.ilp.ilma_regularization_weights, //  final double []   param_regweights,
//					clt_parameters.ofp.ers_to_pose_scale, // corr_scale,
					clt_parameters.ofp.debug_level_optical); // 1); // -1); // int debug_level);
			/*
			scenes_xyzatr[i] = adjustPairsLMA(
					clt_parameters,     // CLTParameters  clt_parameters,			
					reference_QuadClt, // QuadCLT reference_QuadCLT,
					scene_QuadClt, // QuadCLT scene_QuadCLT,
					pose[0], // xyz
					pose[1], // atr
					clt_parameters.ilp.ilma_lma_select,             // final boolean[]   param_select,
					clt_parameters.ilp.ilma_regularization_weights, //  final double []   param_regweights,
					debug_level); // int debug_level)
			 * 
			 *  
			 *  reversed
			opticalFlow.test_LMA(
					clt_parameters, // CLTParameters  clt_parameters,
					clt_parameters.ofp.k_prev, // k_prev,
					qPrev,
					quadCLTs[i],
					clt_parameters.ofp.ers_to_pose_scale, // corr_scale,
					clt_parameters.ofp.debug_level_optical); // 1); // -1); // int debug_level);
			 */
		}


		System.out.println("End of test");


	}
	
8397 8398 8399 8400 8401 8402 8403 8404 8405 8406
	public void TestInterLMA(
			QuadCLT                                              quadCLT_main, // tiles should be set
			CLTParameters             clt_parameters,
			EyesisCorrectionParameters.DebayerParameters         debayerParameters,
			ColorProcParameters                                  colorProcParameters,
			ColorProcParameters                                  colorProcParameters_aux,
			CorrectionColorProc.ColorGainsParameters             channelGainParameters,
			EyesisCorrectionParameters.RGBParameters             rgbParameters,
			EyesisCorrectionParameters.EquirectangularParameters equirectangularParameters,
			Properties                                           properties,
8407
			boolean                                              reset_from_extrinsics,
8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel)  throws Exception
	{
		if ((quadCLT_main != null) && (quadCLT_main.getGPU() != null)) {
			quadCLT_main.getGPU().resetGeometryCorrection();
			quadCLT_main.gpuResetCorrVector(); // .getGPU().resetGeometryCorrectionVector();
		}
		// final boolean    batch_mode = clt_parameters.batch_run;
		this.startTime=System.nanoTime();
		String [] sourceFiles0=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0)) {
			System.out.println("No files to process (of "+sourceFiles0.length+")");
			return;
		}
		QuadCLT.SetChannels [] set_channels=quadCLT_main.setChannels(debugLevel);
//		String set_name = set_channels[0].set_name;
		
		QuadCLT [] quadCLTs = new QuadCLT [set_channels.length]; 
		for (int i = 0; i < quadCLTs.length; i++) {
			quadCLTs[i] = quadCLT_main.spawnQuadCLT(
					set_channels[i].set_name,
					clt_parameters,
					colorProcParameters, //
					threadsMax,
					debugLevel);
			// temporarily fix wrong sign:
			ErsCorrection ers = (ErsCorrection) (quadCLTs[i].getGeometryCorrection());
8437 8438 8439 8440
			if (reset_from_extrinsics) {
				System.out.println("Reset ERS parameters from intraframe extrinsics");
				ers.setupERSfromExtrinsics();
			}
8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453
			quadCLTs[i].setDSRBG(
					clt_parameters, // CLTParameters  clt_parameters,
					threadsMax,     // int            threadsMax,  // maximal number of threads to launch
					updateStatus,   // boolean        updateStatus,
					debugLevel);    // int            debugLevel)
///			quadCLTs[i].showDSIMain();
		}
		
		
		OpticalFlow opticalFlow = new OpticalFlow(
				threadsMax, // int            threadsMax,  // maximal number of threads to launch
				updateStatus); // boolean        updateStatus);
		
8454 8455 8456 8457 8458 8459 8460 8461
		opticalFlow.adjustPairsDualPass(
				clt_parameters, // CLTParameters  clt_parameters,			
				clt_parameters.ofp.k_prev, // k_prev,
				quadCLTs, // QuadCLT [] scenes, // ordered by increasing timestamps
				clt_parameters.ofp.debug_level_optical); // 1); // -1); // int debug_level);
		
		/*
		
8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472
		for (int i = 1; i < quadCLTs.length; i++) {
			QuadCLT qPrev = (i > 0) ? quadCLTs[i - 1] : null;
			//			double [][][] pair_sets =
			opticalFlow.test_LMA(
					clt_parameters, // CLTParameters  clt_parameters,
					clt_parameters.ofp.k_prev, // k_prev,
					quadCLTs[i],
					qPrev,
					clt_parameters.ofp.ers_to_pose_scale, // corr_scale,
					clt_parameters.ofp.debug_level_optical); // 1); // -1); // int debug_level);
					*/
8473
			/* reversed
8474 8475 8476 8477 8478 8479 8480
			opticalFlow.test_LMA(
					clt_parameters, // CLTParameters  clt_parameters,
					clt_parameters.ofp.k_prev, // k_prev,
					qPrev,
					quadCLTs[i],
					clt_parameters.ofp.ers_to_pose_scale, // corr_scale,
					clt_parameters.ofp.debug_level_optical); // 1); // -1); // int debug_level);
8481 8482
			 */
		/*
8483
		}
8484
       */
8485 8486 8487 8488

		System.out.println("End of test");


Andrey Filippov's avatar
Andrey Filippov committed
8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528
	}

	public void interSeriesLMA(
			QuadCLT                                              quadCLT_main, // tiles should be set
			CLTParameters             clt_parameters,
			EyesisCorrectionParameters.DebayerParameters         debayerParameters,
			ColorProcParameters                                  colorProcParameters,
			ColorProcParameters                                  colorProcParameters_aux,
			CorrectionColorProc.ColorGainsParameters             channelGainParameters,
			EyesisCorrectionParameters.RGBParameters             rgbParameters,
			EyesisCorrectionParameters.EquirectangularParameters equirectangularParameters,
			Properties                                           properties,
			boolean                                              reset_from_extrinsics,
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel)  throws Exception
	{
		if ((quadCLT_main != null) && (quadCLT_main.getGPU() != null)) {
			quadCLT_main.getGPU().resetGeometryCorrection();
			quadCLT_main.gpuResetCorrVector(); // .getGPU().resetGeometryCorrectionVector();
		}
		// final boolean    batch_mode = clt_parameters.batch_run;
		this.startTime=System.nanoTime();
		String [] sourceFiles0=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0)) {
			System.out.println("No files to process (of "+sourceFiles0.length+")");
			return;
		}
		QuadCLT.SetChannels [] set_channels=quadCLT_main.setChannels(debugLevel);
		
		QuadCLT [] quadCLTs = new QuadCLT [set_channels.length]; 
		for (int i = 0; i < quadCLTs.length; i++) {
			quadCLTs[i] = quadCLT_main.spawnQuadCLT(
					set_channels[i].set_name,
					clt_parameters,
					colorProcParameters, //
					threadsMax,
					debugLevel);
			// temporarily fix wrong sign:
8529
//			ErsCorrection ers = (ErsCorrection) (quadCLTs[i].getGeometryCorrection());
Andrey Filippov's avatar
Andrey Filippov committed
8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547
			quadCLTs[i].setDSRBG(
					clt_parameters, // CLTParameters  clt_parameters,
					threadsMax,     // int            threadsMax,  // maximal number of threads to launch
					updateStatus,   // boolean        updateStatus,
					debugLevel);    // int            debugLevel)
		}
		
		
		OpticalFlow opticalFlow = new OpticalFlow(
				threadsMax, // int            threadsMax,  // maximal number of threads to launch
				updateStatus); // boolean        updateStatus);
		
		opticalFlow.adjustSeries(
				clt_parameters, // CLTParameters  clt_parameters,			
				clt_parameters.ofp.k_prev, // k_prev,
				quadCLTs, // QuadCLT [] scenes, // ordered by increasing timestamps
				clt_parameters.ofp.debug_level_optical); // 1); // -1); // int debug_level);
		System.out.println("End of interSeriesLMA()");
8548 8549 8550 8551 8552
	}
	
	
	public void intersceneAccumulate(
			QuadCLT                                              quadCLT_main, // tiles should be set
8553
			CLTParameters                                        clt_parameters,
8554 8555 8556 8557 8558 8559 8560 8561 8562 8563
			EyesisCorrectionParameters.DebayerParameters         debayerParameters,
			ColorProcParameters                                  colorProcParameters,
			CorrectionColorProc.ColorGainsParameters             channelGainParameters,
			EyesisCorrectionParameters.RGBParameters             rgbParameters,
			EyesisCorrectionParameters.EquirectangularParameters equirectangularParameters,
			Properties                                           properties,
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel)  throws Exception
	{
8564
//	double []            noise_sigma_level = {0.01, 1.5};
8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578
		if ((quadCLT_main != null) && (quadCLT_main.getGPU() != null)) {
			quadCLT_main.getGPU().resetGeometryCorrection();
			quadCLT_main.gpuResetCorrVector(); // .getGPU().resetGeometryCorrectionVector();
		}
		// final boolean    batch_mode = clt_parameters.batch_run;
		this.startTime=System.nanoTime();
		String [] sourceFiles0=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0)) {
			System.out.println("No files to process (of "+sourceFiles0.length+")");
			return;
		}
		QuadCLT.SetChannels [] set_channels=quadCLT_main.setChannels(debugLevel); // TODO: use just the last one (to need this is no time)
		
8579
		QuadCLT ref_quadCLT = quadCLT_main.spawnQuadCLTWithNoise( // spawnQuadCLT(
8580 8581 8582
				set_channels[set_channels.length-1].set_name,
				clt_parameters,
				colorProcParameters, //
8583
				null, // noise_sigma_level,   // double []            noise_sigma_level,
8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601
				threadsMax,
				debugLevel);
		// temporarily fix wrong sign:
//		ErsCorrection ers = (ErsCorrection) (ref_quadCLT.getGeometryCorrection());
		ref_quadCLT.setDSRBG( // runs GPU to calculate average R,B,G
				clt_parameters, // CLTParameters  clt_parameters,
				threadsMax,     // int            threadsMax,  // maximal number of threads to launch
				updateStatus,   // boolean        updateStatus,
				debugLevel);    // int            debugLevel)
		
		OpticalFlow opticalFlow = new OpticalFlow(
				threadsMax, // int            threadsMax,  // maximal number of threads to launch
				updateStatus); // boolean        updateStatus);
		
		opticalFlow.IntersceneAccumulate(
				clt_parameters,            // CLTParameters       clt_parameters,
				colorProcParameters,       // ColorProcParameters colorProcParameters,
				ref_quadCLT,               // QuadCLT [] scenes, // ordered by increasing timestamps
8602
				null, // noise_sigma_level,         // double []            noise_sigma_level,
8603 8604 8605
				clt_parameters.ofp.debug_level_optical); // 1); // -1); // int debug_level);
		System.out.println("End of intersceneAccumulate()");
		
Andrey Filippov's avatar
Andrey Filippov committed
8606
	}
8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673

	public void intersceneNoiseStats(
			QuadCLT                                              quadCLT_main, // tiles should be set
			CLTParameters                                        clt_parameters,
			EyesisCorrectionParameters.DebayerParameters         debayerParameters,
			ColorProcParameters                                  colorProcParameters,
			CorrectionColorProc.ColorGainsParameters             channelGainParameters,
			EyesisCorrectionParameters.RGBParameters             rgbParameters,
			EyesisCorrectionParameters.EquirectangularParameters equirectangularParameters,
			Properties                                           properties,
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel)  throws Exception
	{
//		double []            noise_sigma_level = {0.01, 1.5, 1.0}; // amount, sigma, offset
//		double []            noise_sigma_level = {0.1, 1.5, 1.0};  // amount, sigma, offset
//		double []            noise_sigma_level = {1.0, 1.5, 1.0};  // amount, sigma, offset
//		double []            noise_sigma_level = {3.0, 1.5, 1.0};  // amount, sigma, offset
//		double []            noise_sigma_level = {5.0, 1.5, 1.0};  // amount, sigma, offset
		double []            noise_sigma_level = null;
		if (clt_parameters.inp.noise_scale > 0.0) {
			noise_sigma_level = new double[] {
					clt_parameters.inp.noise_scale,
					clt_parameters.inp.noise_sigma,
					clt_parameters.inp.initial_offset};  // amount, sigma, offset
		}
		
		boolean ref_only =  clt_parameters.inp.ref_only; //  true; // process only reference frame (false - inter-scene)
		if ((quadCLT_main != null) && (quadCLT_main.getGPU() != null)) {
			quadCLT_main.getGPU().resetGeometryCorrection();
			quadCLT_main.gpuResetCorrVector(); // .getGPU().resetGeometryCorrectionVector();
		}
		// final boolean    batch_mode = clt_parameters.batch_run;
		this.startTime=System.nanoTime();
		String [] sourceFiles0=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0)) {
			System.out.println("No files to process (of "+sourceFiles0.length+")");
			return;
		}
		QuadCLT.SetChannels [] set_channels=quadCLT_main.setChannels(debugLevel); // TODO: use just the last one (to need this is no time)
		
		QuadCLT ref_quadCLT = quadCLT_main.spawnQuadCLTWithNoise( // spawnQuadCLT(
				set_channels[set_channels.length-1].set_name,
				clt_parameters,
				colorProcParameters, //
				noise_sigma_level,   // double []            noise_sigma_level,
				threadsMax,
				clt_parameters.inp.noise_debug_level); // debugLevel);
		/**/
		getNoiseStats(
				clt_parameters, // CLTParameters        clt_parameters,
				ref_quadCLT, //QuadCLT              ref_scene, // ordered by increasing timestamps
				debugLevel); // int                  debug_level);
		/**/
	}	
	
	
	public void intersceneNoise(
			QuadCLT                                              quadCLT_main, // tiles should be set
			CLTParameters                                        clt_parameters,
			EyesisCorrectionParameters.DebayerParameters         debayerParameters,
			ColorProcParameters                                  colorProcParameters,
			CorrectionColorProc.ColorGainsParameters             channelGainParameters,
			EyesisCorrectionParameters.RGBParameters             rgbParameters,
			EyesisCorrectionParameters.EquirectangularParameters equirectangularParameters,
			Properties                                           properties,
8674
			boolean                                              bayer_artifacts_debug,
8675 8676 8677 8678 8679 8680 8681 8682 8683 8684
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel)  throws Exception
	{
//		double []            noise_sigma_level = {0.01, 1.5, 1.0}; // amount, sigma, offset
//		double []            noise_sigma_level = {0.1, 1.5, 1.0};  // amount, sigma, offset
//		double []            noise_sigma_level = {1.0, 1.5, 1.0};  // amount, sigma, offset
//		double []            noise_sigma_level = {3.0, 1.5, 1.0};  // amount, sigma, offset
//		double []            noise_sigma_level = {5.0, 1.5, 1.0};  // amount, sigma, offset
		double []            noise_sigma_level = null;
8685
		if (clt_parameters.inp.noise_scale >= 0.0) {// <0 - will generate no-noise data
8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746
			noise_sigma_level = new double[] {
					clt_parameters.inp.noise_scale,
					clt_parameters.inp.noise_sigma,
					clt_parameters.inp.initial_offset};  // amount, sigma, offset
		}
		
		boolean ref_only =  clt_parameters.inp.ref_only; //  true; // process only reference frame (false - inter-scene)
		if ((quadCLT_main != null) && (quadCLT_main.getGPU() != null)) {
			quadCLT_main.getGPU().resetGeometryCorrection();
			quadCLT_main.gpuResetCorrVector(); // .getGPU().resetGeometryCorrectionVector();
		}
		// final boolean    batch_mode = clt_parameters.batch_run;
		this.startTime=System.nanoTime();
		String [] sourceFiles0=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0)) {
			System.out.println("No files to process (of "+sourceFiles0.length+")");
			return;
		}
		QuadCLT.SetChannels [] set_channels=quadCLT_main.setChannels(debugLevel); // TODO: use just the last one (to need this is no time)
		
		QuadCLT ref_quadCLT = quadCLT_main.spawnQuadCLTWithNoise( // spawnQuadCLT(
				set_channels[set_channels.length-1].set_name,
				clt_parameters,
				colorProcParameters, //
				noise_sigma_level,   // double []            noise_sigma_level,
				threadsMax,
				clt_parameters.inp.noise_debug_level); // debugLevel);
		/*
		getNoiseStats(
				clt_parameters, // CLTParameters        clt_parameters,
				ref_quadCLT, //QuadCLT              ref_scene, // ordered by increasing timestamps
				debugLevel); // int                  debug_level);
		*/
		// Create 4-slice image with noise from the current data
		if (noise_sigma_level != null) {
			String noisy_4slice_suffix = "-noise-level_"+ noise_sigma_level[0]+"-sigma_"+noise_sigma_level[1];
			ref_quadCLT.genSave4sliceImage(
					clt_parameters,        // CLTParameters                                   clt_parameters,
					noisy_4slice_suffix,   // String                                          suffix,
					debayerParameters,     // EyesisCorrectionParameters.DebayerParameters    debayerParameters,
					colorProcParameters,   // ColorProcParameters                             colorProcParameters,
					channelGainParameters, // CorrectionColorProc.ColorGainsParameters        channelGainParameters,
					rgbParameters,         // EyesisCorrectionParameters.RGBParameters        rgbParameters,
					threadsMax,            // final int                                       threadsMax,  // maximal number of threads to launch
					clt_parameters.inp.noise_debug_level); // debugLevel);           // final int                                       debugLevel);
		}
		// temporarily fix wrong sign:
//		ErsCorrection ers = (ErsCorrection) (ref_quadCLT.getGeometryCorrection());
		ref_quadCLT.setDSRBG( // runs GPU to calculate average R,B,G
				clt_parameters, // CLTParameters  clt_parameters,
				threadsMax,     // int            threadsMax,  // maximal number of threads to launch
				updateStatus,   // boolean        updateStatus,
				clt_parameters.inp.noise_debug_level); // debugLevel);    // int            debugLevel)
	
//		if (debugLevel > -1000) return; // TODO: Remove
		
		
		OpticalFlow opticalFlow = new OpticalFlow(
				threadsMax, // int            threadsMax,  // maximal number of threads to launch
				updateStatus); // boolean        updateStatus);
8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763
		if (bayer_artifacts_debug) {
			opticalFlow.intersceneNoiseDebug(
					clt_parameters,            // CLTParameters       clt_parameters,
					ref_only,                  // boolean              ref_only, // process only reference frame (false - inter-scene)
					colorProcParameters,       // ColorProcParameters colorProcParameters,
					ref_quadCLT,               // QuadCLT [] scenes, // ordered by increasing timestamps
					noise_sigma_level,         // double []            noise_sigma_level,
					clt_parameters.inp.noise_debug_level); // clt_parameters.ofp.debug_level_optical - 1); // 1); // -1); // int debug_level);
		} else {
			opticalFlow.intersceneNoise(
					clt_parameters,            // CLTParameters       clt_parameters,
					ref_only,                  // boolean              ref_only, // process only reference frame (false - inter-scene)
					colorProcParameters,       // ColorProcParameters colorProcParameters,
					ref_quadCLT,               // QuadCLT [] scenes, // ordered by increasing timestamps
					noise_sigma_level,         // double []            noise_sigma_level,
					clt_parameters.inp.noise_debug_level); // clt_parameters.ofp.debug_level_optical - 1); // 1); // -1); // int debug_level);
		}
8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046
		System.out.println("End of intersceneNoise()");
	}

	public void getNoiseStats(
			CLTParameters        clt_parameters,
			QuadCLT              ref_scene, // ordered by increasing timestamps
			int                  debug_level)
	{
		String []            noise_files = {
				"-results-lev_1.0E-6-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_1.0E-6-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_1.0E-6-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_0.01-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_0.01-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_0.01-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_0.1-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_0.1-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_0.1-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_0.2-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_0.2-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_0.2-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_0.3-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_0.3-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_0.3-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_0.4-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_0.4-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_0.4-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_0.5-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_0.5-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_0.5-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_0.6-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_0.6-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_0.6-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_0.7-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_0.7-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_0.7-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_0.8-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_0.8-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_0.8-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_0.9-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_0.9-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_0.9-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_1.0-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_1.0-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_1.0-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_1.2-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_1.2-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_1.2-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_1.4-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_1.4-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_1.4-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_1.6-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_1.6-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_1.6-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_1.8-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_1.8-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_1.8-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_2.0-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_2.0-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_2.0-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_2.2-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_2.2-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_2.2-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_2.4-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_2.4-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_2.4-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_2.6-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_2.6-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_2.6-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_2.8-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_2.8-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_2.8-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_3.0-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_3.0-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_3.0-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_3.3-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_3.3-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_3.3-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_3.6-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_3.6-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_3.6-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_4.0-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_4.0-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_4.0-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_4.5-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_4.5-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_4.5-sigma_1.5-offset1.0-nointer-mask1",

				"-results-lev_5.0-sigma_1.5-offset1.0-inter-mask63",
				"-results-lev_5.0-sigma_1.5-offset1.0-nointer-mask63",
				"-results-lev_5.0-sigma_1.5-offset1.0-nointer-mask1"};
		
		getNoiseStats(
				clt_parameters,
				ref_scene, // ordered by increasing timestamps
				noise_files,
				debug_level);		
	}

	
	
	
	public void getNoiseStats(
			CLTParameters        clt_parameters,
			QuadCLT              ref_scene, // ordered by increasing timestamps
			String []            noise_files,
			int                  debug_level)
	{
		/*
		"disp-last",
		"str_last",
		"num vlaid" <= 1.0
		*/
		double max_diff = 0.01; // last diff >
		double max_err = 2.0; // 1.0; // 0.5; // pix
		double max_err1 =0.25; // pix
		double min_strength = 0.0; // minimal strength to calculate rmse (ignore weaker)
		int indx_used = 2;
		int indx_last = 0;
		int indx_initial = 3;
		int indx_strength = 1;
		double max_disparity = 200.0; // for max_err1
		
		final double[][] sky_map = ref_scene. readDoubleArrayFromModelDirectory(
		"-sky_mask", // String      suffix,
		0, // int         num_slices, // (0 - all)
		null); // int []      wh);
		
		double [][] ref_dsn = ref_scene.readDoubleArrayFromModelDirectory(
				"-results-nonoise", // String      suffix,
				0, // int         num_slices, // (0 - all)
				null); // int []      wh);
		int indx_last_diff =  ref_dsn.length - 1;
		boolean [] good_tiles = new boolean [ref_dsn[0].length];
		int num_good_init = 0;
		for (int i = 0; i < good_tiles.length; i++) {
			good_tiles[i] = (ref_dsn[indx_used][i] > 0.999) && (Math.abs(ref_dsn[indx_last_diff][i]) < max_diff);
			if (good_tiles[i] && (sky_map != null) && (sky_map[0][i] > 0.0)) {
				good_tiles[i] = false;
			}
			if (good_tiles[i]){
				num_good_init++;
			}
		}
//		double  [] noise_level = new double  [noise_files.length];
//		boolean [] intra =       new boolean [noise_files.length];
//		boolean [] inter =       new boolean [noise_files.length];
		class DisparityResults{
			double [][] results;
		}
		HashMap <Double, DisparityResults> results_map = new HashMap <Double, DisparityResults> (); 
		for (int nf = 0; nf < noise_files.length; nf++) {
			String fn = noise_files[nf];
			String [] tokens = fn.replace("E-","E_minus").split("-");
			double noise_level = Double.parseDouble(tokens[2].replace("E_minus","E-").substring("lev_".length()));
			boolean inter = !fn.contains("nointer");
			boolean intra = !fn.contains("mask1");
//			System.out.println("level="+noise_level+", inter="+inter+", intra="+intra);
			
			double [][] noise_dsn = ref_scene.readDoubleArrayFromModelDirectory(
					fn, // noise_files[nf], // String      suffix,
					0, // int         num_slices, // (0 - all)
					null); // int []      wh);
			boolean [] converged_tiles_this = good_tiles.clone();
			boolean [] good_tiles_this = good_tiles.clone();
			boolean [] good_tiles_this1 = good_tiles.clone();
			int num_converged = 0;
			int num_good = 0;
			int num_good1 = 0;
			int num_near = 0;
			int num_converged_near = 0;
			
			
			double s0 = 0.0;
			double s2 = 0.0;
			for (int i = 0; i < good_tiles.length; i++) if (good_tiles[i]) {
				converged_tiles_this[i] = (Math.abs(noise_dsn[indx_last_diff][i]) < max_diff);
				if (converged_tiles_this[i]){
					num_converged++;
					good_tiles_this[i] = (Math.abs(noise_dsn[indx_last][i] - noise_dsn[indx_initial][i]) < max_err);
					if (good_tiles_this[i]) {
						num_good++;
						double w = (noise_dsn[indx_strength][i] < min_strength)? 0.0 : 1.0;
						s0 += w;
						double d = noise_dsn[indx_last][i] - noise_dsn[indx_initial][i];
						s2 += w * d * d;
					}
					/*
					good_tiles_this1[i] = (Math.abs(noise_dsn[indx_last][i] - noise_dsn[indx_initial][i]) < max_err1);
					if (good_tiles_this1[i]) {
						num_good1++;
					}
					*/
				}
				if (noise_dsn[indx_initial][i] <= max_disparity) { // only for near tiles
					num_near++;
					if (converged_tiles_this[i]){
						num_converged_near++;
						good_tiles_this1[i] = (Math.abs(noise_dsn[indx_last][i] - noise_dsn[indx_initial][i]) < max_err1);
						if (good_tiles_this1[i]) {
							num_good1++;
						}
					}					
				}
			}
			double rmse = Math.sqrt(s2/s0);
			/*
			 * 		int indx_strength = 1;

			double perc_good =      100.0* num_good/num_good_init;
			double perc_good1 =     100.0* num_good1/num_good_init;
			double perc_good_conf = 100.0* num_good/num_converged;
			*/
			double [] results = {
					1.0* num_good/num_good_init,
//					1.0* num_good1/num_good_init,
					1.0* num_good1/num_near,
					1.0* num_good/num_converged,
					1.0* num_good1/num_converged_near,
					rmse
			};
			if (!results_map.containsKey(noise_level)) {
				DisparityResults dr = new DisparityResults();
				dr.results = new double [3][];
				results_map.put(noise_level, dr);
			}
			int results_index = inter ? 0 : (intra? 1 : 2);
			DisparityResults dr = results_map.get(noise_level);
			dr.results[results_index] = results;
			System.out.println("getNoiseStats(): "+noise_files[nf]+": good_ref= " + num_good_init+
//					", converged= "+num_converged+", good= "+num_good+", good(0.5)= "+perc_good+"%, good(0.1)= "+perc_good1+"%, perc_good_conf= "+perc_good_conf+"%");
					", converged= "+num_converged+", good= "+num_good+" good(0.1)= "+num_good1+", num_near="+num_near);
		}
		List<Double> noise_levels_list = new ArrayList<Double>(results_map.keySet());
		Collections.sort(noise_levels_list);
		System.out.println("\n");
		System.out.print("noise_level, ");
		System.out.print("inter("+max_err+"), inter("+max_err1+"), inter_conf("+max_err+"), inter_conf("+max_err1+"), inter_rmse("+max_err+"),");
		System.out.print("intra("+max_err+"), intra("+max_err1+"), intra_conf("+max_err+"), intra_conf("+max_err1+"), intra_rmse("+max_err+"),");
		System.out.print("binocular("+max_err+"), binocular("+max_err1+"), binocular_conf("+max_err+"), binocular_conf("+max_err1+"), binocular_rmse("+max_err+")");
		System.out.println();
		for (Double nl:noise_levels_list) {
			System.out.print(nl+", ");
			double [][] results = results_map.get(nl).results;
			for (int n = 0; n < results.length; n++) {
				for (int i = 0; i < results[n].length; i++) {
					System.out.print(results[n][i]);
					if ((n < (results.length -1)) ||(i< (results[n].length - 1))) {
						System.out.print(", ");
					}
				}
			}
			System.out.println();
		}
		System.out.println();
	}
	
	
Andrey Filippov's avatar
Andrey Filippov committed
9047
	
9048
	public void batchLwirRig(
9049
			QuadCLT                                              quadCLT_main, // tiles should be set
9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062
			QuadCLT                                              quadCLT_aux,
			CLTParameters             clt_parameters,
			EyesisCorrectionParameters.DebayerParameters         debayerParameters,
			ColorProcParameters                                  colorProcParameters,
			ColorProcParameters                                  colorProcParameters_aux,
			CorrectionColorProc.ColorGainsParameters             channelGainParameters,
			EyesisCorrectionParameters.RGBParameters             rgbParameters,
			EyesisCorrectionParameters.EquirectangularParameters equirectangularParameters,
			Properties                                           properties,
			final int        threadsMax,  // maximal number of threads to launch
			final boolean    updateStatus,
			final int        debugLevel)  throws Exception
	{
9063 9064
		if ((quadCLT_main != null) && (quadCLT_main.getGPU() != null)) {
			quadCLT_main.getGPU().resetGeometryCorrection();
9065
			quadCLT_main.gpuResetCorrVector(); // .getGPU().resetGeometryCorrectionVector();
9066 9067 9068
		}
		if ((quadCLT_aux != null) && (quadCLT_aux.getGPU() != null)) {
			quadCLT_aux.getGPU().resetGeometryCorrection();
9069
			quadCLT_aux.gpuResetCorrVector(); // .getGPU().resetGeometryCorrectionVector();
9070 9071
		}

9072
		// final boolean    batch_mode = clt_parameters.batch_run;
9073 9074
		// Reset dsi data (only 2 slices will be used)
		this.dsi =           new double [DSI_SLICES.length][];
9075 9076
		this.dsi_aux_from_main =   null; // full data, including rms, fg and bg data
		quadCLT_aux.ds_from_main = null; // this is for adjust6ment only (short)
9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115

		final int        debugLevelInner=clt_parameters.batch_run? -2: debugLevel;
		this.startTime=System.nanoTime();
		String [] sourceFiles=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		QuadCLT.SetChannels [] set_channels_aux =  quadCLT_aux.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0) || (set_channels_aux == null) || (set_channels_aux.length==0)) {
			System.out.println("No files to process (of "+sourceFiles.length+")");
			return;
		}
		double [] referenceExposures_main = null;
		double [] referenceExposures_aux =  null;
		if (!colorProcParameters.lwir_islwir)      referenceExposures_main = quadCLT_main.eyesisCorrections.calcReferenceExposures(debugLevel);
		if (!colorProcParameters_aux.lwir_islwir)  referenceExposures_aux =  quadCLT_aux.eyesisCorrections.calcReferenceExposures(debugLevel);
		for (int nSet = 0; nSet < set_channels_main.length; nSet++){
			// check it is the same set for both cameras
			if (set_channels_aux.length <= nSet ) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: nothing");
			}
			if (!set_channels_main[nSet].name().equals(set_channels_aux[nSet].name())) {
				throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: '"+set_channels_main[nSet].name()+"'");
			}

			int [] channelFiles_main = set_channels_main[nSet].fileNumber();
			int [] channelFiles_aux =  set_channels_aux[nSet].fileNumber();
			boolean [][] saturation_imp_main = (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			boolean [][] saturation_imp_aux =  (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
			double [] scaleExposures_main = new double[channelFiles_main.length];
			double [] scaleExposures_aux =  new double[channelFiles_main.length];
			if (updateStatus) IJ.showStatus("Conditioning main camera image set for "+quadCLT_main.image_name);
			ImagePlus [] imp_srcs_main = quadCLT_main.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
					colorProcParameters,            //  ColorProcParameters                       colorProcParameters, //
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_main[nSet].name(), // String                                    set_name,
					referenceExposures_main,        // double []                                 referenceExposures,
					channelFiles_main,              // int []                                    channelFiles,
					scaleExposures_main,            //output  // double [] scaleExposures
					saturation_imp_main,            //output  // boolean [][]                              saturation_imp,
9116
					threadsMax,                 // int                                       threadsMax,
9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134
					debugLevelInner); // int                                       debugLevel);
			if (updateStatus) IJ.showStatus("Conditioning aux camera image set for "+quadCLT_main.image_name);

			// optionally adjust main, aux (aux always will use main - calculate if needed
			// Early main camera adjustment, rig data is not available
			// with LWIR only 1 type of adjustments is possibkle - pre for main, post for aux. Combine configuration fields made for the 8-rig
			int adjust_main = (quadCLT_main.correctionsParameters.rig_batch_adjust_main > quadCLT_main.correctionsParameters.rig_batch_adjust_main_gt)?
					quadCLT_main.correctionsParameters.rig_batch_adjust_main : quadCLT_main.correctionsParameters.rig_batch_adjust_main_gt;
			int adjust_aux = (quadCLT_main.correctionsParameters.rig_batch_adjust_aux > quadCLT_main.correctionsParameters.rig_batch_adjust_aux_gt)?
					quadCLT_main.correctionsParameters.rig_batch_adjust_aux : quadCLT_main.correctionsParameters.rig_batch_adjust_aux_gt;

			for (int num_adjust_main = 0; num_adjust_main < adjust_main; num_adjust_main++) {
				if (updateStatus) IJ.showStatus("Building basic  DSI for the main camera image set "+quadCLT_main.image_name+
						", pass "+(num_adjust_main+1)+" of "+adjust_main);
				if (debugLevel > -5) {
					System.out.println("Building basic  DSI for the main camera image set "+quadCLT_main.image_name+
							", pass "+(num_adjust_main+1)+" of "+adjust_main);
				}
Andrey Filippov's avatar
Andrey Filippov committed
9135
//Generates background image in model tree - should be done later, after adjustment (It is overwritten later, so OK)
9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153
				quadCLT_main.preExpandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						imp_srcs_main, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
						saturation_imp_main, // boolean [][] saturation_imp, // (near) saturated pixels or null
						clt_parameters,
						debayerParameters,
						colorProcParameters,
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevelInner);
				// adjust extrinsics here
				System.out.println("Adjust main extrinsics here");
				if (updateStatus) IJ.showStatus("Adjusting main camera image set for "+quadCLT_main.image_name+
						", pass "+(num_adjust_main+1)+" of "+adjust_main);
				if (debugLevel > -5) {
					System.out.println("Adjusting main camera image set for "+quadCLT_main.image_name+
							", pass "+(num_adjust_main+1)+" of "+adjust_main);
				}
9154
				if (debugLevel > -1){
9155 9156 9157 9158 9159 9160 9161 9162 9163 9164
					int scan_index =  quadCLT_main.tp.clt_3d_passes.size() -1;
					quadCLT_main.tp.showScan(
							quadCLT_main.tp.clt_3d_passes.get(scan_index),   // CLTPass3d   scan,
							"pre-adjust-extrinsic-scan-"+scan_index); //String title)
					for (int s = 0; (s < 5) && (s < scan_index); s++) {
						quadCLT_main.tp.showScan(
								quadCLT_main.tp.clt_3d_passes.get(s),   // CLTPass3d   scan,
								"pre-adjust-extrinsic-scan-"+s); //String title)
					}
				}
9165 9166 9167 9168 9169 9170 9171 9172
			    double inf_min = clt_parameters.ly_inf_min_broad; // -0.5;
			    double inf_max = clt_parameters.ly_inf_max_broad; // 0.5;
			    if (clt_parameters.ly_inf_force_fine || (num_adjust_main >= (adjust_main/2))) {
			        inf_min = clt_parameters.ly_inf_min_narrow; // -0.2;
			        inf_max = clt_parameters.ly_inf_max_narrow; // 0.05;
			        System.out.println("Late adjustment, using narrow band infinity detection, inf_min="+inf_min+", inf_max="+inf_max);
			    } else {
			        System.out.println("Early adjustment, using wide band infinity detection, inf_min="+inf_min+", inf_max="+inf_max);
9173
			    }
9174 9175 9176
				boolean ok = quadCLT_main.extrinsicsCLT(
						clt_parameters, // EyesisCorrectionParameters.CLTParameters           clt_parameters,
						false, // adjust_poly,
9177 9178
						inf_min, // double inf_min,
						inf_max,  // double inf_max,
9179 9180 9181 9182 9183 9184 9185
						threadsMax,  //final int        threadsMax,  // maximal number of threads to launch
						updateStatus,// final boolean    updateStatus,
						debugLevelInner); // final int        debugLevel)
// clear memory for main
				quadCLT_main.tp.resetCLTPasses();
				if (!ok) break;
			}
9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208
			if (quadCLT_main.correctionsParameters.clt_batch_dsi1){
		        System.out.println("Trying experimental features DSI/ERS");
				quadCLT_main.preExpandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						imp_srcs_main, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
						saturation_imp_main, // boolean [][] saturation_imp, // (near) saturated pixels or null
						clt_parameters,
						debayerParameters,
						colorProcParameters,
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevelInner);
				
				double [][] dsi_ly = quadCLT_main.filterByLY(
						clt_parameters, // EyesisCorrectionParameters.CLTParameters           clt_parameters,
				        clt_parameters.ly_inf_min_narrow, // double inf_min,
				        clt_parameters.ly_inf_max_narrow,  // double inf_max,
						threadsMax,  //final int        threadsMax,  // maximal number of threads to launch
						updateStatus,// final boolean    updateStatus,
						debugLevelInner); // final int        debugLevel)				
				dsi[DSI_DISPARITY_MAIN] = dsi_ly[0];
				dsi[DSI_STRENGTH_MAIN] =  dsi_ly[1];
//				if (quadCLT_main.correctionsParameters.clt_batch_dsi) { // Should be always enabled ?
Andrey Filippov's avatar
Andrey Filippov committed
9209
				quadCLT_main.saveDSIMain (dsi);
9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225
//				}
				// clear memory for main
				quadCLT_main.tp.resetCLTPasses();
				// copy regardless of ML generation
				// See if it will copy all files, not just the main camera ones

				if (clt_parameters.rig.ml_copyJP4) {
					copyJP4src(
							quadCLT_main,   // QuadCLT                                  quadCLT_main,  // tiles should be set
							quadCLT_aux,    // QuadCLT                                  quadCLT_aux,
							clt_parameters, // EyesisCorrectionParameters.CLTParameters clt_parameters,
							debugLevel);    // final int                                debugLevel)
				}
			}			
			
			
9226 9227
			// Generate 4 main camera images and thumbnail
			if (quadCLT_main.correctionsParameters.clt_batch_4img){
9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238
				if (clt_parameters.gpu_use_main) {
					if (updateStatus) IJ.showStatus("GPU: Rendering 4 image set (disparity = 0) for "+quadCLT_main.image_name+ "and a thumb nail");
					quadCLT_main.processCLTQuadCorrGPU(
							imp_srcs_main,       // ImagePlus []                                    imp_quad,
							saturation_imp_main, // boolean [][] saturation_imp, // (near) saturated pixels or null
							clt_parameters,      // CLTParameters                                   clt_parameters,
							debayerParameters,   // EyesisCorrectionParameters.DebayerParameters    debayerParameters,
							colorProcParameters, // ColorProcParameters                             colorProcParameters,
							channelGainParameters,
							rgbParameters,       // EyesisCorrectionParameters.RGBParameters        rgbParameters,
							scaleExposures_main, // double []	                                    scaleExposures, // probably not needed here - restores brightness of the final image
9239
							false,               // boolean                                         only4slice,
9240 9241
							threadsMax,          // final int        threadsMax,  // maximal number of threads to launch
							updateStatus,        // final boolean    updateStatus,
9242
							debugLevel);         // final int        debugLevel);
9243 9244
				} else {
					if (updateStatus) IJ.showStatus("CPU: Rendering 4 image set (disparity = 0) for "+quadCLT_main.image_name+ "and a thumb nail");
9245

9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260
					quadCLT_main.processCLTQuadCorrCPU( // returns ImagePlus, but it already should be saved/shown
							imp_srcs_main, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
							saturation_imp_main, // boolean [][] saturation_imp, // (near) saturated pixels or null
							clt_parameters,
							debayerParameters,
							colorProcParameters,
							channelGainParameters,
							rgbParameters,
							scaleExposures_main,
							false, // calculate and apply additional fine geometry correction
							false, // calculate and apply geometry correction at infinity
							threadsMax,  // maximal number of threads to launch
							updateStatus,
							debugLevel);
				}
9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290
				quadCLT_main.tp.resetCLTPasses();
			}


			if (quadCLT_main.correctionsParameters.clt_batch_explore) {
				if (updateStatus) IJ.showStatus("Building basic DSI for the main camera image set "+quadCLT_main.image_name+" (after all adjustments)");
				quadCLT_main.preExpandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						imp_srcs_main, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
						saturation_imp_main, // boolean [][] saturation_imp, // (near) saturated pixels or null
						clt_parameters,
						debayerParameters,
						colorProcParameters,
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevelInner);
				if (updateStatus) IJ.showStatus("Expanding DSI for the main camera image set "+quadCLT_main.image_name+" (after all adjustments)");
				quadCLT_main.expandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						clt_parameters,
						debayerParameters,
						colorProcParameters,
						channelGainParameters,
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevel);
				double [][] main_last_scan = quadCLT_main.tp.getShowDS(
						quadCLT_main.tp.clt_3d_passes.get( quadCLT_main.tp.clt_3d_passes.size() -1),
						false); // boolean force_final);

Andrey Filippov's avatar
Andrey Filippov committed
9291 9292 9293 9294 9295 9296 9297 9298
				if (debugLevel > -1) { //-5){
					int scan_index =  quadCLT_main.tp.clt_3d_passes.size() -1;
					quadCLT_main.tp.showScan(
							quadCLT_main.tp.clt_3d_passes.get(scan_index),   // CLTPass3d   scan,
							"test_pre-after-"+scan_index); //String title)
				}


9299

9300 9301 9302
				dsi[DSI_DISPARITY_MAIN] = main_last_scan[0];
				dsi[DSI_STRENGTH_MAIN] =  main_last_scan[1];
				if (quadCLT_main.correctionsParameters.clt_batch_dsi) { // Should be always enabled ?
Andrey Filippov's avatar
Andrey Filippov committed
9303 9304
					quadCLT_main.saveDSIMain (
							dsi);
9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321
				}


				Runtime.getRuntime().gc();
				System.out.println("--- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

				if (quadCLT_main.correctionsParameters.clt_batch_surf) {
					if (updateStatus) IJ.showStatus("Creating and filtering supertile plane surfaces from the DSI "+quadCLT_main.image_name);
					quadCLT_main.tp.showPlanes(
							clt_parameters,
							quadCLT_main.geometryCorrection,
							threadsMax,
							updateStatus,
							debugLevelInner);

					if (quadCLT_main.correctionsParameters.clt_batch_assign) {
						if (updateStatus) IJ.showStatus("Assigning tiles to candidate surfaces "+quadCLT_main.image_name);
9322 9323 9324 9325 9326 9327 9328
						// prepare average RGBA for the last scan
						quadCLT_main.setPassAvgRBGA(                      // get image from a single pass, return relative path for x3d // USED in lwir
								clt_parameters,                           // CLTParameters           clt_parameters,
								quadCLT_main.tp.clt_3d_passes.size() - 1, // int        scanIndex,
								threadsMax,                               // int        threadsMax,  // maximal number of threads to launch
								updateStatus,                             // boolean    updateStatus,
								debugLevelInner);                         // int        debugLevel)
9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351
						double [][] assignments_dbg = quadCLT_main.tp.assignTilesToSurfaces(
								clt_parameters,
								quadCLT_main.geometryCorrection,
								threadsMax,
								updateStatus,
								debugLevelInner);
						if (assignments_dbg == null) continue;
						dsi[DSI_DISPARITY_X3D] = assignments_dbg[TileSurface.ASGN_A_DISP];

						// TODO use assignments_dbg

						// generate ML data if enabled
						/*
						if (quadCLT_main.correctionsParameters.clt_batch_genMl) { // rig.ml_generate) { //clt_batch_genMl
							outputMLData(
									quadCLT_main,   // QuadCLT                                  quadCLT_main,  // tiles should be set
									quadCLT_aux,    // QuadCLT                                  quadCLT_aux,
									clt_parameters, // EyesisCorrectionParameters.CLTParameters clt_parameters,
									null,           //String                                   ml_directory,       // full path or null (will use config one)
									threadsMax,     // final int                                threadsMax,  // maximal number of threads to launch
									updateStatus,   // final boolean                            updateStatus,
									debugLevel);    // final int                                debugLevel)
						}
Andrey Filippov's avatar
Andrey Filippov committed
9352
						 */
9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374
						// copy regardless of ML generation
						// See if it will copy all files, not just the main camera ones

						if (clt_parameters.rig.ml_copyJP4) {
							copyJP4src(
									quadCLT_main,   // QuadCLT                                  quadCLT_main,  // tiles should be set
									quadCLT_aux,    // QuadCLT                                  quadCLT_aux,
									clt_parameters, // EyesisCorrectionParameters.CLTParameters clt_parameters,
									debugLevel);    // final int                                debugLevel)
						}

						if (quadCLT_main.correctionsParameters.clt_batch_gen3d) {
							if (updateStatus) IJ.showStatus("Generating and exporting 3D scene model "+quadCLT_main.image_name);
							boolean ok = quadCLT_main.output3d(
									clt_parameters,      // EyesisCorrectionParameters.CLTParameters           clt_parameters,
									colorProcParameters, // EyesisCorrectionParameters.ColorProcParameters colorProcParameters,
									rgbParameters,       // EyesisCorrectionParameters.RGBParameters             rgbParameters,
									threadsMax,          // final int        threadsMax,  // maximal number of threads to launch
									updateStatus,        // final boolean    updateStatus,
									debugLevelInner);         // final int        debugLevel)
							if (!ok) continue;
						}
9375 9376
						// save assigned disparity also? - with "-DSI_COMBO" suffix
						if (quadCLT_main.correctionsParameters.clt_batch_dsi) {
Andrey Filippov's avatar
Andrey Filippov committed
9377 9378
							quadCLT_main.saveDSI (
									dsi);
9379 9380
						}

9381 9382 9383
					}
				}
			} else { // if (quadCLT_main.correctionsParameters.clt_batch_explore) {
9384 9385
				int num_restored =  0;
				try {
Andrey Filippov's avatar
Andrey Filippov committed
9386 9387 9388
					num_restored =  quadCLT_main.restoreDSI(DSI_MAIN_SUFFIX, // "-DSI_COMBO", "-DSI_MAIN"
							dsi);
							
9389 9390 9391
				} catch (Exception e) {

				}
9392
				if (num_restored < 2) {
9393
					System.out.println("No DSI from the main camera is available. Please re-run with 'clt_batch_explore' enabled to generate it");
9394 9395 9396 9397 9398
					if (quadCLT_main.correctionsParameters.clt_batch_save_extrinsics) {
						saveProperties(
								null,        // String path,                // full name with extension or w/o path to use x3d directory
								null,        // Properties properties,      // if null - will only save extrinsics)
								debugLevel);
Andrey Filippov's avatar
Andrey Filippov committed
9399 9400 9401 9402 9403
						
						quadCLT_main.saveInterProperties( // save properties for interscene processing (extrinsics, ers, ...)
								null, // String path,             // full name with extension or w/o path to use x3d directory
//								null, // Properties properties,   // if null - will only save extrinsics)
								debugLevel);
9404
					}
Andrey Filippov's avatar
Andrey Filippov committed
9405 9406 9407
					
					
					
9408 9409 9410 9411 9412 9413
					if (quadCLT_main.correctionsParameters.clt_batch_save_all) {
						saveProperties(
								null,        // String path,                // full name with extension or w/o path to use x3d directory
								properties,  // Properties properties,    // if null - will only save extrinsics)
								debugLevel);
					}
9414
					continue; // skipping to the next file
9415 9416 9417 9418 9419 9420 9421 9422
				}
			}

			// Process AUX (LWIR) camera data
			// 1) Prepare DS for adjustments (just d/s, with ambiguous disparity tiles removed)
			// 2) Prepare full D/S and FG/BG data to be embedded within the ML files
			double [][] main_ds = {dsi[DSI_DISPARITY_MAIN], dsi[DSI_STRENGTH_MAIN]};

9423 9424 9425 9426 9427 9428 9429 9430 9431 9432
			if ((adjust_aux == 0) &&
					!quadCLT_main.correctionsParameters.clt_batch_4img_aux &&
					!quadCLT_main.correctionsParameters.clt_batch_dsi_aux &&
					!quadCLT_main.correctionsParameters.clt_batch_genMl &&
					!quadCLT_main.correctionsParameters.clt_batch_save_extrinsics &&
					!quadCLT_main.correctionsParameters.clt_batch_save_all) {
				continue; 
			}
			
			
9433
			quadCLT_aux.ds_from_main = quadCLT_aux.depthMapMainToAux( // only 2 layers for adjustments
9434 9435 9436 9437 9438 9439 9440 9441
					main_ds, // double [][] ds,
					quadCLT_main.getGeometryCorrection(), //  GeometryCorrection geometryCorrection_main,
					quadCLT_aux.getGeometryCorrection(), //  GeometryCorrection geometryCorrection_aux,
					clt_parameters,
					false,             // split_fg_bg,
					true,              // for_adjust,
					debugLevel);       // DEBUG_LEVEL); // int debug_level

9442
			this.dsi_aux_from_main = quadCLT_aux.depthMapMainToAux( // 8 layers for ML generation/exporting + 2 zero layers
9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459
					main_ds, // double [][] ds,
					quadCLT_main.getGeometryCorrection(), //  GeometryCorrection geometryCorrection_main,
					quadCLT_aux.getGeometryCorrection(),  //  GeometryCorrection geometryCorrection_aux,
					clt_parameters,
					true,                                 // split_fg_bg,
					false,                                // for_adjust,
					debugLevel);                          // int debug_level

			ImagePlus [] imp_srcs_aux = quadCLT_aux.conditionImageSet(
					clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
					colorProcParameters_aux,        //  ColorProcParameters                       colorProcParameters, //
					sourceFiles,                    // String []                                 sourceFiles,
					set_channels_aux[nSet].name(), // String                                    set_name,
					referenceExposures_aux,        // double []                                 referenceExposures,
					channelFiles_aux,              // int []                                    channelFiles,
					scaleExposures_aux,            //output  // double [] scaleExposures
					saturation_imp_aux,            //output  // boolean [][]                              saturation_imp,
9460
					threadsMax,                 // int                                       threadsMax,
9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490
					debugLevelInner); // int                                       debugLevel);

			// optionally adjust AUX extrinsics (using quadCLT_aux.ds_from_main )
			for (int num_adjust_aux = 0; num_adjust_aux < adjust_aux; num_adjust_aux++) {
				if (updateStatus) IJ.showStatus("Building basic  DSI for the AUX camera image set "+quadCLT_main.image_name+
						" using main camera DSI, pass "+(num_adjust_aux+1)+" of "+num_adjust_aux);
				if (debugLevel > -5) {
					System.out.println("Building basic  DSI for the AUX camera image set "+quadCLT_main.image_name+
							" using main camera DSI, pass "+(num_adjust_aux+1)+" of "+num_adjust_aux);
				}
				quadCLT_aux.preExpandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						imp_srcs_aux, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
						saturation_imp_aux, // boolean [][] saturation_imp, // (near) saturated pixels or null
						clt_parameters,
						debayerParameters,
						colorProcParameters_aux,
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevelInner);
				// adjust extrinsics here
				System.out.println("Adjust AUX extrinsics here");
				if (updateStatus) IJ.showStatus("Adjusting AUX camera image set for "+quadCLT_aux.image_name+
						", pass "+(num_adjust_aux+1)+" of "+adjust_aux);
				if (debugLevel > -5) {
					System.out.println("Adjusting AUX camera image set for "+quadCLT_aux.image_name+
							", pass "+(num_adjust_aux+1)+" of "+adjust_aux);
				}
				if (quadCLT_aux.ds_from_main == null) {
					System.out.println("BUG: quadCLT_aux.ds_from_main should be not null here!");
9491 9492 9493 9494 9495 9496
				    double inf_min = -1.0;
				    double inf_max =  1.0;
				    if (num_adjust_aux >= (adjust_aux/2)) {
				        inf_min = -0.2;
				        inf_max = 0.05;
				    }
9497 9498 9499 9500
					// adjust w/o main camera - maybe will be used in the future
					boolean ok = quadCLT_aux.extrinsicsCLT(
							clt_parameters, // EyesisCorrectionParameters.CLTParameters           clt_parameters,
							false, // adjust_poly,
9501 9502
				            inf_min, // double inf_min,
				            inf_max,  // double inf_max,
9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520
							threadsMax,  //final int        threadsMax,  // maximal number of threads to launch
							updateStatus,// final boolean    updateStatus,
							debugLevelInner); // final int        debugLevel)
					if (!ok) break;
				}
				boolean ok = quadCLT_aux.extrinsicsCLTfromGT(
						  null,
						  quadCLT_aux.ds_from_main, // gt_disp_strength,
						  clt_parameters,           // EyesisCorrectionParameters.CLTParameters           clt_parameters,
						  false,                    // adjust_poly,
						  threadsMax,               // final int        threadsMax,  // maximal number of threads to launch
						  updateStatus,             // final boolean    updateStatus,
						  debugLevel + 2);          // final int        debugLevel)
// clear memory for AUX
				quadCLT_aux.tp.resetCLTPasses();
				if (!ok) break;
			}
			// Generate 4 AUX camera images and thumbnail
9521
			if (quadCLT_main.correctionsParameters.clt_batch_4img_aux){
9522 9523
				if (updateStatus) IJ.showStatus("Rendering 4 AUX image set (disparity = 0) for "+quadCLT_aux.image_name);

9524
				quadCLT_aux.processCLTQuadCorrCPU( // returns ImagePlus, but it already should be saved/shown
9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540
						imp_srcs_aux, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
						saturation_imp_aux, // boolean [][] saturation_imp, // (near) saturated pixels or null
						  clt_parameters,
						  debayerParameters,
						  colorProcParameters_aux,
						  channelGainParameters,
						  rgbParameters,
						  scaleExposures_aux,
						  false, // calculate and apply additional fine geometry correction
						  false, // calculate and apply geometry correction at infinity
						  threadsMax,  // maximal number of threads to launch
						  updateStatus,
						  debugLevel);
				quadCLT_aux.tp.resetCLTPasses();
			}
			// Currently - no LWIR 3D model generation, maybe it will be added later
9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566
			// Generate AUX DS
			if (quadCLT_main.correctionsParameters.clt_batch_dsi_aux) {
				if (updateStatus) IJ.showStatus("Building basic DSI for the aux camera image set "+quadCLT_main.image_name+" (for DSI export)");
				quadCLT_aux.preExpandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						imp_srcs_aux, // [srcChannel], // should have properties "name"(base for saving results), "channel","path"
						saturation_imp_aux, // boolean [][] saturation_imp, // (near) saturated pixels or null
						clt_parameters,
						debayerParameters,
						colorProcParameters_aux,
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevelInner);
				if (updateStatus) IJ.showStatus("Expanding DSI for the aux camera image set "+quadCLT_main.image_name+" (for DSI export)");
				quadCLT_aux.expandCLTQuad3d( // returns ImagePlus, but it already should be saved/shown
						clt_parameters,
						debayerParameters,
						colorProcParameters_aux,
						channelGainParameters,
						rgbParameters,
						threadsMax,  // maximal number of threads to launch
						updateStatus,
						debugLevel);
				double [][] aux_last_scan = quadCLT_aux.tp.getShowDS(
						quadCLT_aux.tp.clt_3d_passes.get( quadCLT_aux.tp.clt_3d_passes.size() -1),
						false); // boolean force_final);
9567

9568 9569 9570 9571
//				dsi[DSI_DISPARITY_AUX] = aux_last_scan[0]; // incompatible dimensions
//				dsi[DSI_STRENGTH_AUX] =  aux_last_scan[1]; // incompatible dimensions
				dsi_aux_from_main[QuadCLT.FGBG_AUX_DISP] = aux_last_scan[0];
				dsi_aux_from_main[QuadCLT.FGBG_AUX_STR] =  aux_last_scan[1];
Andrey Filippov's avatar
Andrey Filippov committed
9572 9573 9574
				quadCLT_main.saveDSIGTAux( // GT from main and AUX DS
						quadCLT_aux,
						dsi_aux_from_main);
9575 9576 9577
				quadCLT_aux.tp.resetCLTPasses();
			}
			//
9578

9579 9580 9581 9582 9583 9584 9585 9586 9587 9588
			// TODO: Add new ML generation here
			if (quadCLT_main.correctionsParameters.clt_batch_genMl) { // rig.ml_generate) { //clt_batch_genMl
				outputMLDataLwir(
						quadCLT_aux,    // QuadCLT                                  quadCLT_aux,
						clt_parameters, // EyesisCorrectionParameters.CLTParameters clt_parameters,
						null,           //String                                   ml_directory,       // full path or null (will use config one)
						threadsMax,     // final int                                threadsMax,  // maximal number of threads to launch
						updateStatus,   // final boolean                            updateStatus,
						debugLevel);    // final int                                debugLevel)
			}
9589 9590
			
			
9591 9592

			if (quadCLT_main.correctionsParameters.clt_batch_save_extrinsics) {
Andrey Filippov's avatar
Andrey Filippov committed
9593
				saveProperties( // uses global quadCLT_main
9594 9595 9596
						null,        // String path,                // full name with extension or w/o path to use x3d directory
						null,        // Properties properties,      // if null - will only save extrinsics)
						debugLevel);
Andrey Filippov's avatar
Andrey Filippov committed
9597 9598 9599 9600 9601
				quadCLT_main.saveInterProperties( // save properties for interscene processing (extrinsics, ers, ...)
						null, // String path,             // full name with extension or w/o path to use x3d directory
//						null, // Properties properties,   // if null - will only save extrinsics)
						debugLevel);
				
9602 9603 9604 9605 9606 9607 9608
			}
			if (quadCLT_main.correctionsParameters.clt_batch_save_all) {
				saveProperties(
						null,        // String path,                // full name with extension or w/o path to use x3d directory
						properties,  // Properties properties,    // if null - will only save extrinsics)
						debugLevel);
			}
9609

9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620
			Runtime.getRuntime().gc();
			if (debugLevel >-1) System.out.println("Processing set "+(nSet+1)+" (of "+set_channels_aux.length+") finished at "+
					IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");

			if (quadCLT_aux.eyesisCorrections.stopRequested.get()>0) {
				System.out.println("User requested stop");
				System.out.println("Processing "+(nSet + 1)+" file sets (of "+set_channels_main.length+") finished at "+
						IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");
				return;
			}
		}
9621
		System.out.println("batchLwirRig(): processing "+(quadCLT_main.getTotalFiles(set_channels_main)+quadCLT_aux.getTotalFiles(set_channels_aux))+" files ("+set_channels_main.length+" file sets) finished at "+
9622 9623 9624
				IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec, --- Free memory="+Runtime.getRuntime().freeMemory()+" (of "+Runtime.getRuntime().totalMemory()+")");
	}

9625 9626
	public void showDSI()
	{
Andrey Filippov's avatar
Andrey Filippov committed
9627
		  quadCLT_main.showDSI(dsi);
9628 9629
	}

Andrey Filippov's avatar
Andrey Filippov committed
9630
/*
9631
	public void saveDSIMain(
Andrey Filippov's avatar
Andrey Filippov committed
9632 9633
			QuadCLT quadCLT,
			double [][] dsi) // DSI_SLICES.length
9634
	{
Andrey Filippov's avatar
Andrey Filippov committed
9635 9636 9637
		String x3d_path= quadCLT.correctionsParameters.selectX3dDirectory( // for x3d and obj
				quadCLT.correctionsParameters.getModelName(quadCLT.image_name), // quad timestamp. Will be ignored if correctionsParameters.use_x3d_subdirs is false
				quadCLT.correctionsParameters.x3dModelVersion,
9638 9639
				true,  // smart,
				true);  //newAllowed, // save
Andrey Filippov's avatar
Andrey Filippov committed
9640
		String title = quadCLT.image_name+"-DSI_MAIN";
9641 9642 9643
		String []   titles =   {DSI_SLICES[DSI_DISPARITY_MAIN], DSI_SLICES[DSI_STRENGTH_MAIN]};
		double [][] dsi_main = {dsi[DSI_DISPARITY_MAIN],        dsi[DSI_STRENGTH_MAIN]};

Andrey Filippov's avatar
Andrey Filippov committed
9644 9645
		ImagePlus imp = (new ShowDoubleFloatArrays()).makeArrays(dsi_main,quadCLT.tp.getTilesX(), quadCLT.tp.getTilesY(),  title, titles);
		quadCLT.eyesisCorrections.saveAndShow(
9646 9647 9648 9649 9650 9651 9652
				imp,      // ImagePlus             imp,
				x3d_path, // String                path,
				false,    // boolean               png,
				false,    // boolean               show,
				0);       // int                   jpegQuality)
	}

Andrey Filippov's avatar
Andrey Filippov committed
9653

9654
	// Save GT from main and AUX calculated DS
Andrey Filippov's avatar
Andrey Filippov committed
9655 9656 9657 9658
	public void saveDSIGTAux(
			QuadCLT quadCLT_main,
			QuadCLT quadCLT_aux,
			double [][] dsi_aux_from_main)
9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669
	{
		String x3d_path= quadCLT_main.correctionsParameters.selectX3dDirectory( // for x3d and obj
				quadCLT_main.correctionsParameters.getModelName(quadCLT_main.image_name), // quad timestamp. Will be ignored if correctionsParameters.use_x3d_subdirs is false
				quadCLT_main.correctionsParameters.x3dModelVersion,
				true,  // smart,
				true);  //newAllowed, // save
		String title = quadCLT_aux.image_name+"-DSI_GT-AUX";
//		String []   titles =   {DSI_SLICES[DSI_DISPARITY_MAIN], DSI_SLICES[DSI_STRENGTH_MAIN]};
//		double [][] dsi_main = {dsi[DSI_DISPARITY_MAIN],        dsi[DSI_STRENGTH_MAIN]};

		ImagePlus imp = (new ShowDoubleFloatArrays()).makeArrays(
Andrey Filippov's avatar
Andrey Filippov committed
9670
				dsi_aux_from_main, // dsi_main,
9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682
				quadCLT_aux.tp.getTilesX(),
				quadCLT_aux.tp.getTilesY(),
				title,
				QuadCLT.FGBG_TITLES_AUX); // titles);
		quadCLT_main.eyesisCorrections.saveAndShow(
				imp,      // ImagePlus             imp,
				x3d_path, // String                path,
				false,    // boolean               png,
				false,    // boolean               show,
				0);       // int                   jpegQuality)
	}

Andrey Filippov's avatar
Andrey Filippov committed
9683 9684 9685
	public void showDSIMain(
			QuadCLT quadCLT_main,
			double [][] dsi)
9686 9687 9688 9689 9690 9691 9692
	{
		  String title = quadCLT_main.image_name+"-DSI_MAIN";
		  String []   titles =   {DSI_SLICES[DSI_DISPARITY_MAIN], DSI_SLICES[DSI_STRENGTH_MAIN]};
		  double [][] dsi_main = {dsi[DSI_DISPARITY_MAIN],        dsi[DSI_STRENGTH_MAIN]};

		  (new ShowDoubleFloatArrays()).showArrays(dsi_main,quadCLT_main.tp.getTilesX(), quadCLT_main.tp.getTilesY(), true, title, titles);
	}
Andrey Filippov's avatar
Andrey Filippov committed
9693
*/
9694 9695


9696
	public double [][] getRigDSI(
9697 9698
			String                                         path_DSI,   // Combo DSI path
			boolean                                        main) // false - rig
9699
	{
9700 9701 9702
		int [] slices_rig =  {TwoQuadCLT.DSI_DISPARITY_RIG,  TwoQuadCLT.DSI_STRENGTH_RIG};
		int [] slices_main = {TwoQuadCLT.DSI_DISPARITY_MAIN, TwoQuadCLT.DSI_STRENGTH_MAIN};
		int [] slices = main? slices_main:slices_rig;
9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719
		double[][] dsi = new double [slices.length][];
		ImagePlus imp_dsi=new ImagePlus(path_DSI);
		ImageStack dsi_stack=  imp_dsi.getStack();
		int nLayers = dsi_stack.getSize();
		for (int nl = 0; nl < nLayers; nl++){
			for (int i = 0; i < slices.length; i++) {
				if (TwoQuadCLT.DSI_SLICES[slices[i]].equals(dsi_stack.getSliceLabel(nl + 1))) {
					dsi[i] = new double [((float[]) dsi_stack.getPixels(nl + 1)).length];
					for (int j = 0; j < dsi[i].length; j++) {
						dsi[i][j] = ((float[]) dsi_stack.getPixels(nl + 1))[j];
					}
					break;
				}
			}
		}
		return dsi;
	}
Andrey Filippov's avatar
Andrey Filippov committed
9720 9721 9722 9723
	/**
	 * Enhance main DSI data to prepare ML files:
	 * 1. remove tiles that are too different from the rig (> rig_tolerance) - that may me different object
	 * 2. replace undefined tiles that have rig data with average of 8 neighbors within
9724
	 *    rig_tolerance from rig disparity. If there are no suitable neighbors, use
Andrey Filippov's avatar
Andrey Filippov committed
9725
	 *    random offset from rig disparity within +/- rnd_offset
9726
	 * 3. grow defined data, each layer using min/max/average from the known neighbors
Andrey Filippov's avatar
Andrey Filippov committed
9727 9728 9729 9730 9731 9732 9733 9734 9735
	 * 4. assign new_strength to previously undefined tiles
	 * @param main_dsi
	 * @param rig_dsi
	 * @param rig_tolerance
	 * @param rnd_offset
	 * @param main_tolerance
	 * @param grow_steps
	 * @param grow_mode : -1 - min, 0 - average, +1 - max
	 * @param new_strength
9736
	 * @return 'enhanced' disparity/strength for the main camera
Andrey Filippov's avatar
Andrey Filippov committed
9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768
	 */

	public double [][] enhanceMainDSI(
			double [][] main_dsi,
			double [][] rig_dsi,
			double      rig_tolerance,
			double      rnd_offset,
			double      main_tolerance,
			int         grow_steps,
			int         grow_mode,
			double      inher_strength,
			int         debugLevel)
	{
		double [][] dbg_img = null;
		int num_dbg = 0;
		String [] dbg_titles = null;
		if (debugLevel > 1) {
			num_dbg = grow_steps + 4;
			dbg_img = new double [2 * num_dbg][];
			dbg_titles = new String [2 * num_dbg];
			dbg_img[0]           = main_dsi[0].clone();
			dbg_img[0 + num_dbg] = main_dsi[1].clone();
			dbg_titles[0] =           "main_d";
			dbg_titles[0 + num_dbg] = "main_s";
			dbg_img[1]           = rig_dsi [0].clone();
			dbg_img[1 + num_dbg] = rig_dsi [1].clone();
			dbg_titles[1] =           "rig_d";
			dbg_titles[1 + num_dbg] = "rig_s";
		}
		final int tilesX = this.quadCLT_main.tp.getTilesX();
		final int tilesY = this.quadCLT_main.tp.getTilesY();
		TileNeibs         tnImage =  new TileNeibs(tilesX, tilesY); // biCamDSI_persistent.tnImage;
9769

Andrey Filippov's avatar
Andrey Filippov committed
9770 9771 9772 9773 9774
		double [][]       enh_dsi = {main_dsi[0].clone(),main_dsi[1].clone()};
		int num_too_far =      0;
		int num_by_neib =      0;
		int num_rnd =          0;
		int num_extrapolated = 0;
9775

Andrey Filippov's avatar
Andrey Filippov committed
9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812
		for (int nTile = 0; nTile < enh_dsi[0].length;nTile++) {
			// Remove from main camera measurements those that do not have rig data or differ from rig by more than rig_tolerance
			if (Double.isNaN(rig_dsi[0][nTile]) || (Math.abs(rig_dsi[0][nTile] - enh_dsi[0][nTile]) > rig_tolerance)) {
				enh_dsi[1][nTile] = 0.0;
				enh_dsi[0][nTile] = Double.NaN;
				if (!Double.isNaN(rig_dsi[0][nTile])) {
					num_too_far++; // count only too far, not NaN-s
				}
			}
		}
		double [] new_disp = enh_dsi[0].clone();
		double [] new_str =  enh_dsi[1].clone();
		Random rnd = new Random(System.nanoTime());
		for (int nTile = 0; nTile < enh_dsi[0].length;nTile++) if (Double.isNaN(enh_dsi[0][nTile]) && !Double.isNaN(rig_dsi[0][nTile])){
			double sw = 0.0;
			double sdw = 0.0;
			int nneibs = 0;
			for (int dir = 0; dir < 8; dir++) {
				int nTile1 = tnImage.getNeibIndex(nTile, dir);
				if (    (nTile1 >= 0) &&
						!Double.isNaN(enh_dsi[0][nTile1]) &&
						(Math.abs(enh_dsi[0][nTile1] - rig_dsi[0][nTile]) <= main_tolerance)) {
					double w = enh_dsi[1][nTile1];
					sw +=  w;
					sdw += w * enh_dsi[0][nTile1];
					nneibs++;
				}
			}
			if (sw > 0) {
				new_disp[nTile] = sdw/sw;
				new_str[nTile] = inher_strength * sw/nneibs;
				num_by_neib++;
			} else {
				new_disp[nTile] = rig_dsi[0][nTile] + rnd_offset*(2 * rnd.nextDouble() - 1.0);
				new_str[nTile] = inher_strength * rig_dsi[1][nTile];
				num_rnd++;
			}
9813 9814

		}
Andrey Filippov's avatar
Andrey Filippov committed
9815 9816 9817 9818 9819 9820 9821 9822 9823 9824
		for (int nTile = 0; nTile < enh_dsi[0].length;nTile++) if (Double.isNaN(enh_dsi[0][nTile]) && !Double.isNaN(rig_dsi[0][nTile])){
			enh_dsi[0][nTile] = new_disp[nTile];
			enh_dsi[1][nTile] = new_str[nTile];
		}
		if (dbg_img != null) {
			dbg_img[2]           = enh_dsi[0].clone();
			dbg_img[2 + num_dbg] = enh_dsi[1].clone();
			dbg_titles[2] =           "enh_preexp_d";
			dbg_titles[2 + num_dbg] = "enh_preexp_s";
		}
9825
		//		double inher_strength = 0.5;
Andrey Filippov's avatar
Andrey Filippov committed
9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840
		boolean [] exp_full = null;
		if (grow_steps > 0) for (int n_expand = 0; n_expand < (grow_steps+1); n_expand++) {
			boolean [] selection = new boolean[enh_dsi[0].length];
			for (int nTile = 0; nTile < enh_dsi[0].length;nTile++) {
				selection[nTile] = !Double.isNaN(enh_dsi[0][nTile]);
			}
			if (n_expand == (grow_steps-1)) {
				exp_full = selection.clone();
				tnImage.growSelection(2, exp_full, null); // hor, vert and diagonal
				tnImage.growSelection(1, selection, null); // only hor/vert
			} else if ((n_expand == grow_steps) && (exp_full != null)) {
				selection = exp_full;
			} else {
				tnImage.growSelection(1, selection, null); // only hor/vert
			}
9841

Andrey Filippov's avatar
Andrey Filippov committed
9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886
//			tnImage.growSelection(2, selection, null);
			for (int nTile = 0; nTile < enh_dsi[0].length;nTile++) if (selection[nTile] && Double.isNaN((enh_dsi[0][nTile]))){
				double sw = 0.0;
				double sdw = 0.0;
				int ntiles = 0;
				double d_min = Double.POSITIVE_INFINITY;
				double d_max = Double.NEGATIVE_INFINITY;
				for (int dir = 0; dir < 8; dir++) {
					int nTile1 = tnImage.getNeibIndex(nTile, dir);
					if ((nTile1 >= 0) && !Double.isNaN(enh_dsi[0][nTile1])){
						double d = enh_dsi[0][nTile1];
						if (d < d_min) {
							d_min = d;
						}
						if (d > d_max) {
							d_max = d;
						}
						double w = enh_dsi[1][nTile1];
						sw +=  w;
						sdw += w * enh_dsi[0][nTile1];
						ntiles++;
					}
				}
				if (sw > 0.0) {
					double d_avg = sdw/sw;
					switch (grow_mode) {
					case -1: new_disp[nTile] = d_min; break;
					case  1: new_disp[nTile] = d_max; break;
					case  0: new_disp[nTile] = d_avg;   break;
					default: {
						// find - which of the min,max, avg is closer to rig (if available, if not - use avg)
						if (!Double.isNaN(rig_dsi[0][nTile])) {
							double [] diffs = {Math.abs(d_min - rig_dsi[0][nTile]), Math.abs(d_max - rig_dsi[0][nTile]),Math.abs(d_avg - rig_dsi[0][nTile])};
							if ((diffs[0] < diffs[1]) && (diffs[0] < diffs[2])){
								new_disp[nTile] = d_min;
							} else if (diffs[1] < diffs[2]) {
								new_disp[nTile] = d_max;
							} else {
								new_disp[nTile] = d_avg;
							}
						} else {
							new_disp[nTile] = d_avg;
						}
					}
					}
9887
					new_str[nTile] = inher_strength * sw/ntiles;
Andrey Filippov's avatar
Andrey Filippov committed
9888 9889
					num_extrapolated++;
				} else {
9890 9891
					new_disp[nTile] = Double.NaN;
					new_str[nTile] = 0.0;
Andrey Filippov's avatar
Andrey Filippov committed
9892
				}
9893

Andrey Filippov's avatar
Andrey Filippov committed
9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904
			}
			for (int nTile = 0; nTile < enh_dsi[0].length;nTile++) if (selection[nTile] && Double.isNaN(enh_dsi[0][nTile]) && !Double.isNaN(new_disp[nTile]) ){
				enh_dsi[0][nTile] = new_disp[nTile];
				enh_dsi[1][nTile] = new_str[nTile]; // new_strength;
			}
			if (dbg_img != null) {
				dbg_img[3+n_expand]           = enh_dsi[0].clone();
				dbg_img[3+n_expand + num_dbg] = enh_dsi[1].clone();
				dbg_titles[3+n_expand] =           "enh_exp"+n_expand+"_d";
				dbg_titles[3+n_expand + num_dbg] = "enh_exp"+n_expand+"_s";
			}
9905

Andrey Filippov's avatar
Andrey Filippov committed
9906 9907 9908 9909 9910
		}
		if (debugLevel > 0) {
			System.out.println("enhanceMainDSI(): num_too_far="+num_too_far+", num_by_neib="+num_by_neib+", num_rnd="+num_rnd+", num_extrapolated="+num_extrapolated);
		}
		if (dbg_img != null) {
9911
			(new ShowDoubleFloatArrays()).showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
9912 9913 9914 9915 9916 9917
					dbg_img,
					tilesX,
					tilesY,
					true,
					"enhanced_dsi_dbg",
					dbg_titles);
9918

Andrey Filippov's avatar
Andrey Filippov committed
9919 9920 9921
		}
		return enh_dsi;
	}
9922 9923


9924 9925 9926 9927 9928 9929
	public void regenerateML(
			String                                         path_DSI,   // Combo DSI path
			String                                         model_dir,  // model/version directory
			String                                         ml_subdir,  // new ML subdir (or null to use configuartion one)
			QuadCLT                                        quadCLT_main,
			QuadCLT                                        quadCLT_aux,
9930
			CLTParameters       clt_parameters,
9931
			EyesisCorrectionParameters.DebayerParameters   debayerParameters,
9932 9933
			ColorProcParameters                            colorProcParameters,
			ColorProcParameters                            colorProcParameters_aux,
9934 9935 9936 9937 9938 9939
			EyesisCorrectionParameters.RGBParameters       rgbParameters,
			final int                                      threadsMax,  // maximal number of threads to launch
			final boolean                                  updateStatus,
			final int                                      debugLevel) throws Exception
	{
		this.startTime=System.nanoTime();
Andrey Filippov's avatar
Andrey Filippov committed
9940 9941 9942 9943 9944 9945 9946 9947 9948
		boolean new_dir_only = true;
		String ml_dir = (ml_subdir == null)? null: (model_dir+Prefs.getFileSeparator()+ml_subdir);
		if (new_dir_only) {
			File dir = new File(ml_dir);
			if (dir.exists()){
				System.out.println("Directory already exists: "+dir+", and new_dir_only=true -> skipping generation");
				return;
			}
		}
9949

9950 9951
		double [][] rig_dsi =  getRigDSI(path_DSI, false);
		double [][] main_dsi = getRigDSI(path_DSI, true);
9952

9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981
		String [] sourceFiles=quadCLT_main.correctionsParameters.getSourcePaths();
		QuadCLT.SetChannels [] set_channels_main = quadCLT_main.setChannels(debugLevel);
		QuadCLT.SetChannels [] set_channels_aux =  quadCLT_aux.setChannels(debugLevel);
		if ((set_channels_main == null) || (set_channels_main.length==0) || (set_channels_aux == null) || (set_channels_aux.length==0)) {
			System.out.println("No files to process (of "+sourceFiles.length+")");
			return;
		}
		double [] referenceExposures_main = quadCLT_main.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		double [] referenceExposures_aux =  quadCLT_aux.eyesisCorrections.calcReferenceExposures(debugLevel); // multiply each image by this and divide by individual (if not NaN)
		if ((set_channels_main.length != 1) || (set_channels_aux.length != 1)) {
			System.out.println("Wrong number of source file sets, expecting 1, got "+set_channels_main.length+", "+set_channels_aux.length);
		}
		int nSet = 0;
		if (set_channels_aux.length <= nSet ) {
			throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: nothing");
		}
		if (!set_channels_main[nSet].name().equals(set_channels_aux[nSet].name())) {
			throw new Exception ("Set names for cameras do not match: main camera: '"+set_channels_main[nSet].name()+"', aux. camera: '"+set_channels_main[nSet].name()+"'");
		}

		int [] channelFiles_main = set_channels_main[nSet].fileNumber();
		int [] channelFiles_aux =  set_channels_aux[nSet].fileNumber();
		boolean [][] saturation_main = (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
		boolean [][] saturation_aux =  (clt_parameters.sat_level > 0.0)? new boolean[channelFiles_main.length][] : null;
		double [] scaleExposures_main = new double[channelFiles_main.length];
		double [] scaleExposures_aux =  new double[channelFiles_main.length];

		ImagePlus [] imp_quad_main = quadCLT_main.conditionImageSet(
				clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
9982
				colorProcParameters,            //  ColorProcParameters                       colorProcParameters, //
9983 9984 9985 9986 9987 9988
				sourceFiles,                    // String []                                 sourceFiles,
				set_channels_main[nSet].name(), // String                                    set_name,
				referenceExposures_main,        // double []                                 referenceExposures,
				channelFiles_main,              // int []                                    channelFiles,
				scaleExposures_main,            //output  // double [] scaleExposures
				saturation_main,                //output  // boolean [][]                              saturation_imp,
9989
				threadsMax,                 // int                                       threadsMax,
9990 9991 9992 9993
				debugLevel);                   // int                                       debugLevel);

		ImagePlus [] imp_quad_aux = quadCLT_aux.conditionImageSet(
				clt_parameters,                 // EyesisCorrectionParameters.CLTParameters  clt_parameters,
9994
				colorProcParameters_aux,        //  ColorProcParameters                       colorProcParameters, //
9995 9996 9997 9998 9999 10000
				sourceFiles,                    // String []                                 sourceFiles,
				set_channels_aux[nSet].name(),  // String                                    set_name,
				referenceExposures_aux,         // double []                                 referenceExposures,
				channelFiles_aux,               // int []                                    channelFiles,
				scaleExposures_aux,             //output  // double [] scaleExposures
				saturation_aux,                 //output  // boolean [][]                              saturation_imp,
10001
				threadsMax,                 // int                                       threadsMax,
10002
				debugLevel);                    // int                                       debugLevel);
10003
/*		// 08/12/2020 Moved to conditionImageSet
10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014
		getRigImageStacks(
				clt_parameters,  // EyesisCorrectionParameters.CLTParameters       clt_parameters,
				quadCLT_main,    // QuadCLT                                         quadCLT_main,
				quadCLT_aux,     // QuadCLT                                          quadCLT_aux,
				imp_quad_main,   // ImagePlus []                                   imp_quad_main,
				imp_quad_aux,    // ImagePlus []                                    imp_quad_aux,
				saturation_main, // boolean [][]        saturation_main, // (near) saturated pixels or null
				saturation_aux, // boolean [][]        saturation_aux, // (near) saturated pixels or null
				threadsMax,      // maximal number of threads to launch
				debugLevel);     // final int        debugLevel);
		// now tp is defined
10015 10016
*/ 

10017
/*
Andrey Filippov's avatar
Andrey Filippov committed
10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029
		main_dsi = enhanceMainDSI(
				main_dsi,                             // double [][] main_dsi,
				rig_dsi,                              // double [][] rig_dsi,
				clt_parameters.rig.ml_rig_tolerance,  // double      rig_tolerance,
				clt_parameters.rig.ml_rnd_offset,     // double      rnd_offset,
				clt_parameters.rig.ml_main_tolerance, // double      main_tolerance,
				clt_parameters.rig.ml_grow_steps,     // int         grow_steps,
				clt_parameters.rig.ml_grow_mode,      // int         grow_mode,
				clt_parameters.rig.ml_new_strength,   // double      new_strength)
//				debugLevel + 3);                        // int         debugLevel);
				debugLevel + 0);                        // int         debugLevel);
*/
10030 10031
		quadCLT_main.tp.rig_pre_poles_ds = rig_dsi;  // use rig data from the COMBO-DSI file
		quadCLT_main.tp.main_ds_ml =       main_dsi; // use rig data from the COMBO-DSI file
10032 10033 10034

//		quadCLT_main.tp.resetCLTPasses();
//		quadCLT_aux.tp.resetCLTPasses();
Andrey Filippov's avatar
Andrey Filippov committed
10035
//		String ml_dir = (ml_subdir == null)? null: (model_dir+Prefs.getFileSeparator()+ml_subdir);
10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047
		outputMLData(
				quadCLT_main,   // QuadCLT                                  quadCLT_main,  // tiles should be set
				quadCLT_aux,    // QuadCLT                                  quadCLT_aux,
				clt_parameters, // EyesisCorrectionParameters.CLTParameters clt_parameters,
				ml_dir,         // String                                   ml_directory,       // full path or null (will use config one)
				threadsMax,     // final int                                threadsMax,  // maximal number of threads to launch
				updateStatus,   // final boolean                            updateStatus,
				debugLevel);    // final int                                debugLevel)
		System.out.println();
	}


10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107
	public void saveProperties(
			String path,                // full name with extension or w/o path to use x3d directory
			Properties properties,    // if null - will only save extrinsics)
			int debugLevel)
	{
		// update properties from potentially modified parameters (others should be updated
		if (path == null) {
			path = quadCLT_main.image_name + ((properties == null) ? "-EXTRINSICS":"")+".corr-xml";

		}
		if (!path.contains(Prefs.getFileSeparator())) {
			  String x3d_path= quadCLT_main.correctionsParameters.selectX3dDirectory( // for x3d and obj
					  quadCLT_main.correctionsParameters.getModelName(quadCLT_main.image_name), // quad timestamp. Will be ignored if correctionsParameters.use_x3d_subdirs is false
					  quadCLT_main.correctionsParameters.x3dModelVersion,
						  true,  // smart,
						  true);  //newAllowed, // save
			  path = x3d_path+Prefs.getFileSeparator()+path;
		}
		if (properties == null) {
			properties = new Properties();
		}
		quadCLT_main.setProperties(QuadCLT.PREFIX,properties);
		quadCLT_aux.setProperties(QuadCLT.PREFIX_AUX,properties);
		OutputStream os;
		try {
			os = new FileOutputStream(path);
		} catch (FileNotFoundException e1) {
			// missing config directory
			File dir = (new File(path)).getParentFile();
			if (!dir.exists()){
				dir.mkdirs();
				try {
					os = new FileOutputStream(path);
				} catch (FileNotFoundException e2) {
					IJ.showMessage("Error","Failed to create directory "+dir.getName()+" to save configuration file: "+path);
					return;
				}
			} else {
				IJ.showMessage("Error","Failed to open configuration file: "+path);
				return;
			}
		}
		try {
			properties.storeToXML(os,
					"last updated " + new java.util.Date(), "UTF8");

		} catch (IOException e) {
			IJ.showMessage("Error","Failed to write XML configuration file: "+path);
			return;
		}
		try {
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (debugLevel> -3) {
			System.out.println("Configuration parameters are saved to "+path);
		}
	}
10108
}