From 0d75893f89b90bb01c4a3681005ba0aa743369b3 Mon Sep 17 00:00:00 2001 From: Pierre POUCHIN Date: Wed, 24 Feb 2021 16:24:31 +0100 Subject: [PATCH] Added dynamic version (in code), fixed typos and fixed previously broken code. --- .gitlab-ci.yml | 2 +- pom.xml | 1 + .../analyseTest/OutputFileVerification.java | 67 +- .../java/gred/nucleus/autocrop/AutoCrop.java | 397 ++++---- .../nucleus/autocrop/AutoCropCalling.java | 30 +- .../nucleus/autocrop/AutocropParameters.java | 204 +++-- src/main/java/gred/nucleus/autocrop/Box.java | 24 +- .../nucleus/autocrop/CropFromCoordinates.java | 27 +- .../nucleus/autocrop/GenerateOverlay.java | 11 +- .../gred/nucleus/autocrop/annotAutoCrop.java | 107 +-- .../generateProjectionFromCoordinates.java | 70 +- .../autocrop/rectangleIntersection.java | 143 ++- .../nucleus/cli/CLIActionOptionCmdLine.java | 14 +- .../nucleus/cli/CLIActionOptionOMERO.java | 23 +- .../gred/nucleus/cli/CLIActionOptions.java | 23 +- src/main/java/gred/nucleus/cli/CLIHelper.java | 53 +- .../java/gred/nucleus/cli/CLIRunAction.java | 24 +- .../gred/nucleus/cli/CLIRunActionOMERO.java | 34 +- .../ComponentRemovalBoundary.java | 1 - .../ComponentRemovalLinear.java | 32 +- .../ComponentRemovalLinearComplement.java | 34 +- .../ComponentRemovalNone.java | 1 - .../ComponentRemovalThresholdVolume.java | 4 +- .../connectedComponent/ComponentInfo.java | 16 +- .../ConnectedComponent.java | 327 ++++--- .../ConnectedComponent2D.java | 24 +- .../ConnectedComponent3D.java | 32 +- .../nucleus/core/ChromocenterAnalysis.java | 6 +- .../core/ChromocentersEnhancement.java | 28 +- .../nucleus/core/ComputeNucleiParameters.java | 20 +- .../nucleus/core/ConvexHullSegmentation.java | 1 + .../java/gred/nucleus/core/Measure3D.java | 240 ++--- .../core/NucleusChromocentersAnalysis.java | 7 +- .../nucleus/core/NucleusSegmentation.java | 76 +- .../gred/nucleus/core/RadialDistance.java | 13 +- .../nucleus/dialogs/AutocropConfigDialog.java | 196 ++-- .../gred/nucleus/dialogs/AutocropDialog.java | 387 +++++--- ...centerSegmentationPipelineBatchDialog.java | 511 ++++++----- ...omocentersAnalysisPipelineBatchDialog.java | 729 ++++++++------- .../dialogs/CropFromCoodinateDialog.java | 12 +- ...eusSegmentationAndAnalysisBatchDialog.java | 849 +++++++++--------- .../NucleusSegmentationAndAnalysisDialog.java | 240 ++--- .../NucleusSegmentationBatchDialog.java | 715 ++++++++------- .../dialogs/NucleusSegmentationDialog.java | 70 +- .../dialogs/SegmentationConfigDialog.java | 120 +-- .../nucleus/dialogs/SegmentationDialog.java | 15 +- .../dialogs/computeParametersDialog.java | 491 +++++----- .../gred/nucleus/exceptions/fileInOut.java | 2 - .../nucleus/filesInputOutput/Directory.java | 69 +- .../nucleus/filesInputOutput/FilesNames.java | 17 +- .../filesInputOutput/OutputTextFile.java | 6 +- .../filesInputOutput/OutputTexteFile.java | 6 +- .../nucleus/filesInputOutput/OutputTiff.java | 1 + .../nucleus/imageProcess/Thresholding.java | 9 +- .../ComputeNucleiParametersML.java | 225 ++--- .../machineLeaningUtils/SliceToStack.java | 15 +- .../mains/ChromocenterTransformation.java | 5 +- .../gred/nucleus/mains/MulticropFilter.java | 9 +- .../java/gred/nucleus/mains/TestAutoCrop.java | 13 +- .../mains/TestSegmentationMethods.java | 27 +- src/main/java/gred/nucleus/mains/Version.java | 21 + .../java/gred/nucleus/mains/bitsConvert.java | 1 + .../mains/computeSegmentationParameters.java | 49 +- .../computeSegmentationParametersDL.java | 44 +- src/main/java/gred/nucleus/mains/main.java | 115 ++- .../gred/nucleus/mains/noiseComputing.java | 31 +- src/main/java/gred/nucleus/myGradient/FJ.java | 296 +++--- .../gred/nucleus/myGradient/FJ_About.java | 38 +- .../nucleus/myGradient/FJ_Derivatives.java | 263 +++--- .../gred/nucleus/myGradient/FJ_Edges.java | 419 ++++----- .../gred/nucleus/myGradient/FJ_Hessian.java | 297 +++--- .../gred/nucleus/myGradient/FJ_Laplacian.java | 303 ++++--- .../gred/nucleus/myGradient/FJ_Options.java | 234 ++--- .../gred/nucleus/myGradient/FJ_Panel.java | 238 ++--- .../nucleus/myGradient/FJ_Statistics.java | 782 ++++++++-------- .../gred/nucleus/myGradient/FJ_Structure.java | 301 ++++--- .../gred/nucleus/myGradient/FJ_Website.java | 33 +- .../java/gred/nucleus/myGradient/MyEdges.java | 186 ++-- .../gred/nucleus/myGradient/MyGradient.java | 63 +- .../NucleusAnalysis.java | 53 +- .../java/gred/nucleus/plugins/Autocrop_.java | 66 +- .../ChromocenterSegmentationBatchPlugin_.java | 17 +- .../ChromocenterSegmentationPlugin_.java | 16 +- .../plugins/ChromocentersAnalysisPlugin_.java | 20 +- .../nucleus/plugins/CropFromCoordinate_.java | 6 +- .../nucleus/plugins/NucleusAnalysis_.java | 16 +- ...usSegmentationAndAnalysisBatchPlugin_.java | 44 +- ...NucleusSegmentationAndAnalysisPlugin_.java | 2 +- .../NucleusSegmentationBatchPlugin_.java | 28 +- .../nucleus/plugins/PluginParameters.java | 63 +- .../gred/nucleus/plugins/Segmentation_.java | 42 +- .../plugins/computeParametersPlugin_.java | 3 - .../segmentation/SegmentationCalling.java | 61 +- .../segmentation/SegmentationParameters.java | 23 +- .../test/AutocropImageIntegration.java | 20 +- .../nucleus/test/ImagesIntegrationTest.java | 2 +- .../SegmentationImageIntegrationCheck.java | 21 +- .../test/SegmentationImagesIntegration.java | 17 +- .../gred/nucleus/utils/ComponentConnexe.java | 169 ++-- .../nucleus/utils/ConvexeHullDetection.java | 80 +- .../nucleus/utils/ConvexeHullImageMaker.java | 85 +- .../java/gred/nucleus/utils/Distance_Map.java | 14 +- .../java/gred/nucleus/utils/FileList.java | 467 +++++----- .../java/gred/nucleus/utils/FillingHoles.java | 39 +- .../java/gred/nucleus/utils/Gradient.java | 25 +- .../java/gred/nucleus/utils/Histogram.java | 16 +- .../nucleus/utils/RegionalExtremaFilter.java | 33 +- src/main/java/gred/nucleus/utils/Voxel.java | 34 +- .../java/gred/nucleus/utils/VoxelRecord.java | 30 +- src/main/resources/nucleusj.properties | 1 + src/main/resources/plugins.config | 4 +- 111 files changed, 6334 insertions(+), 5752 deletions(-) create mode 100644 src/main/java/gred/nucleus/mains/Version.java create mode 100644 src/main/resources/nucleusj.properties diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 02d41a96..03febdb5 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -25,7 +25,7 @@ compile: - target # ------------------------- Deploy ---------------------------------------- -# Deploy the Maven artifacts generated by "Compile" stage to Gitlab's Maven repository. +# Deploy the Maven artifacts generated by "Compile" stage to Gitlab Maven repository. deploy: stage: deploy diff --git a/pom.xml b/pom.xml index b5a1ea64..697f69c2 100644 --- a/pom.xml +++ b/pom.xml @@ -71,6 +71,7 @@ ${basedir}/src/main/resources + true ${project.build.sourceDirectory} diff --git a/src/main/java/gred/nucleus/analyseTest/OutputFileVerification.java b/src/main/java/gred/nucleus/analyseTest/OutputFileVerification.java index 7f66eb15..ba8faea4 100644 --- a/src/main/java/gred/nucleus/analyseTest/OutputFileVerification.java +++ b/src/main/java/gred/nucleus/analyseTest/OutputFileVerification.java @@ -50,67 +50,73 @@ public OutputFileVerification(String PathExpectedResult, String PathOutPut) { this._rawPathOutPut = PathOutPut; } + /** * List files expected and compute md5sum stored in hashMap (read recursively folders) * * @param path : path of folder which contains files expected */ - public void GetFileResultExpected(String path) throws IOException { + public void GetFileResultExpected(String path) { File root = new File(path); File[] list = root.listFiles(); - for (File f : list) { - if (f.isDirectory()) { - GetFileResultExpected(f.getAbsolutePath()); - } else { - String temps = f.getPath().replace( - this._rawPathExpectedResult, ""); - this._myMapInitialFilesInputFolder.put(temps, md5(f.getPath())); + if(list != null) { + for (File f : list) { + if (f.isDirectory()) { + GetFileResultExpected(f.getAbsolutePath()); + } else { + String temps = f.getPath().replace( + this._rawPathExpectedResult, ""); + this._myMapInitialFilesInputFolder.put(temps, md5(f.getPath())); + } } } - } + /** * List files already inside the output folder and compute md5sum stored in hashMap (read recursively folders) * * @param path : path of folder which contains files expected */ - public void GetFilesOutputFolder(String path) throws IOException { + public void GetFilesOutputFolder(String path) { File root = new File(path); File[] list = root.listFiles(); - for (File f : list) { - if (f.isDirectory()) { - GetFilesOutputFolder(f.getAbsolutePath()); - } else { - String temps = f.getPath().replace(this._rawPathOutPut, - ""); - this._myMapInitialFileOutputFolder.put(temps, md5(f.getPath())); + if(list != null) { + for (File f : list) { + if (f.isDirectory()) { + GetFilesOutputFolder(f.getAbsolutePath()); + } else { + String temps = f.getPath().replace(this._rawPathOutPut, ""); + this._myMapInitialFileOutputFolder.put(temps, md5(f.getPath())); + } } } - } + /** * List files output folder produce by the analyse and compute md5sum stored in hashMap (read recursively folders) * * @param path : path of folder which contains files expected */ - public void GetFilesResultingOfAnalysis(String path) throws IOException { + public void GetFilesResultingOfAnalysis(String path) { File root = new File(path); File[] list = root.listFiles(); - for (File f : list) { - if (f.isDirectory()) { - GetFilesResultingOfAnalysis(f.getAbsolutePath()); - } else { - String temps = f.getPath().replace(this._rawPathOutPut - , ""); - System.out.println(temps); - this._myMapFilesProduceByAnalysis.put(temps, md5(f.getPath())); + if(list != null) { + for (File f : list) { + if (f.isDirectory()) { + GetFilesResultingOfAnalysis(f.getAbsolutePath()); + } else { + String temps = f.getPath().replace(this._rawPathOutPut + , ""); + System.out.println(temps); + this._myMapFilesProduceByAnalysis.put(temps, md5(f.getPath())); + } } } - } + /** Method to compare md5sum of files from output analysis with expected results */ public void CompareAnalysisResult() { for (Map.Entry entry : @@ -126,10 +132,10 @@ public void CompareAnalysisResult() { + hashCode + "\n" + this._myMapFilesProduceByAnalysis.get(fileName) + "\n"); } - } } + /** * Method to compute md5sum of file * @@ -137,9 +143,8 @@ public void CompareAnalysisResult() { * * @return hash md5 of file * - * @throws IOException */ - public String md5(String path) throws IOException { + public String md5(String path) { String checksumMD5 = "Na"; try { checksumMD5 = DigestUtils.md5Hex(new FileInputStream(path)); diff --git a/src/main/java/gred/nucleus/autocrop/AutoCrop.java b/src/main/java/gred/nucleus/autocrop/AutoCrop.java index 25980ba7..a1d4161b 100644 --- a/src/main/java/gred/nucleus/autocrop/AutoCrop.java +++ b/src/main/java/gred/nucleus/autocrop/AutoCrop.java @@ -8,7 +8,6 @@ import gred.nucleus.filesInputOutput.OutputTextFile; import gred.nucleus.filesInputOutput.OutputTexteFile; import gred.nucleus.filesInputOutput.OutputTiff; -import gred.nucleus.exceptions.fileInOut; import gred.nucleus.imageProcess.Thresholding; import gred.nucleus.utils.Histogram; import ij.ImagePlus; @@ -20,7 +19,6 @@ import inra.ijpb.binary.BinaryImages; import inra.ijpb.label.LabelImages; import loci.common.DebugTools; -import loci.formats.FormatException; import loci.plugins.BF; import loci.plugins.in.ImporterOptions; import omero.ServerError; @@ -78,7 +76,7 @@ public class AutoCrop { /** Parameters crop analyse */ private AutocropParameters m_autocropParameters; /** OTSU threshold used to compute segmented image */ - private int OTSUthreshold; + private int OTSUThreshold; /** Slice start to compute OTSU */ private String sliceUsedForOTSU; /** Default threshold */ @@ -94,7 +92,7 @@ public class AutoCrop { * @param autocropParametersAnalyse : list of analyse parameter */ public AutoCrop(File imageFile, String outputFilesPrefix, AutocropParameters autocropParametersAnalyse) - throws IOException, FormatException, fileInOut, Exception { + throws Exception { this.m_autocropParameters = autocropParametersAnalyse; this.m_currentFile = imageFile; this.m_imageFilePath = imageFile.getAbsolutePath(); @@ -111,8 +109,9 @@ public AutoCrop(File imageFile, String outputFilesPrefix, AutocropParameters aut this.m_infoImageAnalyse = autocropParametersAnalyse.getAnalyseParameters(); } + public AutoCrop(ImageContainer image, AutocropParameters autocropParametersAnalyse, Client client) - throws IOException, FormatException, fileInOut, Exception { + throws Exception { this.m_currentFile = new File(image.getName()); this.m_autocropParameters = autocropParametersAnalyse; this.m_outputDirPath = this.m_autocropParameters.getOutputFolder(); @@ -130,10 +129,11 @@ public AutoCrop(ImageContainer image, AutocropParameters autocropParametersAnaly this.m_infoImageAnalyse = autocropParametersAnalyse.getAnalyseParameters(); } + public AutoCrop(File imageFile, String outputFilesPrefix, AutocropParameters autocropParametersAnalyse, - HashMap _boxes) throws IOException, FormatException, fileInOut, Exception { + HashMap _boxes) throws Exception { this.m_autocropParameters = autocropParametersAnalyse; this.m_currentFile = imageFile; this.m_imageFilePath = imageFile.getAbsolutePath(); @@ -146,6 +146,7 @@ public AutoCrop(File imageFile, m_boxes = _boxes; } + /** * Method to get specific channel to compute OTSU threshold * @@ -155,17 +156,18 @@ public AutoCrop(File imageFile, */ public ImagePlus getImageChannel(int channelNumber) throws Exception { DebugTools.enableLogging("OFF"); /* DEBUG INFO BIO-FORMATS OFF*/ - ImagePlus[] currentImage = BF.openImagePlus(this.m_imageFilePath); - ChannelSplitter splitter = new ChannelSplitter(); - currentImage = splitter.split(currentImage[0]); + ImagePlus[] currentImage = BF.openImagePlus(this.m_imageFilePath); + currentImage = ChannelSplitter.split(currentImage[0]); return currentImage[channelNumber]; } + public ImagePlus getImageChannelOmero(int channelNumber, ImageContainer image, Client client) throws Exception { int[] cBound = {channelNumber, channelNumber}; return image.toImagePlus(client, null, null, cBound, null, null); } + /** * Method to check multichannel and initialising channelNumbers variable * @@ -173,15 +175,15 @@ public ImagePlus getImageChannelOmero(int channelNumber, ImageContainer image, C */ public void setChannelNumbers() throws Exception { DebugTools.enableLogging("OFF"); /* DEBUG INFO BIO-FORMATS OFF*/ - ImagePlus[] currentImage = BF.openImagePlus(this.m_imageFilePath); - ChannelSplitter channelSplitter = new ChannelSplitter(); - currentImage = channelSplitter.split(currentImage[0]); + ImagePlus[] currentImage = BF.openImagePlus(this.m_imageFilePath); + currentImage = ChannelSplitter.split(currentImage[0]); this.m_rawImg = currentImage[0]; if (currentImage.length > 1) { this.m_channelNumbers = currentImage.length; } } + public void setChannelNumbersOmero(ImageContainer image, Client client) throws Exception { DebugTools.enableLogging("OFF"); /* DEBUG INFO BIO-FORMATS OFF*/ int[] cBound = {this.m_autocropParameters.getChannelToComputeThreshold(), @@ -190,12 +192,12 @@ public void setChannelNumbersOmero(ImageContainer image, Client client) throws E this.m_channelNumbers = image.getPixels().getSizeC(); } + /** * Method computing OTSU threshold and creating segmented image from this threshold. Before OTSU threshold a - * Gaussian Blur is applied (case of anisotropic voxels) - * TODO add case where voxel are not anisotropic for Gaussian Blur Case where OTSU threshold is under 20 computation - * using only half of last slice (useful in case of top slice with lot of noise) If OTSU threshold is still - * under 20 threshold default threshold value is 20. + * Gaussian Blur is applied (case of anisotropic voxels) TODO add case where voxel are not anisotropic for Gaussian + * Blur Case where OTSU threshold is under 20 computation using only half of last slice (useful in case of top slice + * with lot of noise) If OTSU threshold is still under 20 threshold default threshold value is 20. */ public void thresholdKernels() { if (this.m_imageSeg == null) { @@ -205,9 +207,9 @@ public void thresholdKernels() { GaussianBlur3D.blur(this.m_imageSeg, 0.5, 0.5, 1); Thresholding thresholding = new Thresholding(); int thresh = thresholding.computeOtsuThreshold(this.m_imageSeg); - if (thresh < this.m_autocropParameters.getThresholdOTSUcomputing()) { + if (thresh < this.m_autocropParameters.getThresholdOTSUComputing()) { ImagePlus imp2; - if (m_autocropParameters.getSlicesOTSUcomputing() == 0) { + if (m_autocropParameters.getSlicesOTSUComputing() == 0) { this.sliceUsedForOTSU = "Start:" + this.m_imageSeg.getStackSize() / 2 + "-" + this.m_imageSeg.getStackSize(); imp2 = new Duplicator().run(this.m_imageSeg, @@ -215,61 +217,64 @@ public void thresholdKernels() { this.m_imageSeg.getStackSize()); } else { this.sliceUsedForOTSU = "Start:" + - this.m_autocropParameters.getSlicesOTSUcomputing() + + this.m_autocropParameters.getSlicesOTSUComputing() + "-" + this.m_imageSeg.getStackSize(); imp2 = new Duplicator().run(this.m_imageSeg, - this.m_autocropParameters.getSlicesOTSUcomputing(), + this.m_autocropParameters.getSlicesOTSUComputing(), this.m_imageSeg.getStackSize()); } int thresh2 = thresholding.computeOtsuThreshold(imp2); - if (thresh2 < this.m_autocropParameters.getThresholdOTSUcomputing()) { - thresh = this.m_autocropParameters.getThresholdOTSUcomputing(); + if (thresh2 < this.m_autocropParameters.getThresholdOTSUComputing()) { + thresh = this.m_autocropParameters.getThresholdOTSUComputing(); this.m_defaultThreshold = true; } else { thresh = thresh2; } } - this.OTSUthreshold = thresh; + this.OTSUThreshold = thresh; this.m_imageSeg = this.generateSegmentedImage(this.m_imageSeg, thresh); } - /** MorpholibJ Method computing connect component using OTSU segmented image */ - public void computeConnectcomponent() { + + /** MorpholibJ Method computing connected components using OTSU segmented image */ + public void computeConnectedComponent() { this.m_imageSeg_labelled = BinaryImages.componentsLabeling(this.m_imageSeg, 26, 32); } + /** - * Initialize hashMap m_boxes containing component connect pixel value associate to number of voxels composing it. - * Filter connect component based on minimum volume (default 1 ) and maximum volume (default 2147483647) + * Initializes hashMap m_boxes containing connected components pixel value associate to number of voxels composing + * it. Filter connected components based on minimum volume (default 1 ) and maximum volume (default 2147483647) */ public void componentSizeFilter() { Histogram histogram = new Histogram(); histogram.run(this.m_imageSeg_labelled); - histogram.getHistogram(); - HashMap parcour = histogram.getHistogram(); - for (Map.Entry entry : parcour.entrySet()) { - Double cle = entry.getKey(); - Integer valeur = entry.getValue(); - if (!((valeur * getVoxelVolume() < this.m_autocropParameters.getM_minVolumeNucleus()) || - (valeur * getVoxelVolume() > this.m_autocropParameters.getM_maxVolumeNucleus())) && valeur > 1) { - Box initializeBox = new Box(Short.MAX_VALUE, + HashMap histogramData = histogram.getHistogram(); + for (Map.Entry entry : histogramData.entrySet()) { + Double key = entry.getKey(); + Integer value = entry.getValue(); + if (!((value * getVoxelVolume() < this.m_autocropParameters.getM_minVolumeNucleus()) || + (value * getVoxelVolume() > this.m_autocropParameters.getM_maxVolumeNucleus())) && value > 1) { + Box initializedBox = new Box(Short.MAX_VALUE, Short.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE); - this.m_boxes.put(cle, initializeBox); + this.m_boxes.put(key, initializedBox); } } getNumberOfBox(); } + /** MorpholibJ Method filtering border connect component */ public void componentBorderFilter() { LabelImages.removeBorderLabels(this.m_imageSeg_labelled); } + /** * Detection of the of the bounding box for each object of the image. A Connected component detection is do on the * m_imageThresholding and all the object on the border and under or upper threshold volume are removed. The @@ -311,54 +316,56 @@ public void computeBoxes2() { } } + /** - * Method to add X voxels in x y z arround the connected component. X by default is 20 in x y z. Parameter can be + * Method to add X voxels in x y z around the connected component. X by default is 20 in x y z. Parameter can be * modified in autocrop parameters : -m_xCropBoxSize -m_yCropBoxSize -m_zCropBoxSize */ public void addCROP_parameter() { for (int y = 0; y < this.m_channelNumbers; y++) { int i = 0; for (Map.Entry entry : this.m_boxes.entrySet()) { - Box box = entry.getValue(); - int xmin = box.getXMin() - this.m_autocropParameters.getxCropBoxSize(); - int ymin = box.getYMin() - this.m_autocropParameters.getxCropBoxSize(); - int zmin = box.getZMin() - this.m_autocropParameters.getzCropBoxSize(); - String coord = box.getXMin() + "_" + box.getYMin() + "_" + box.getZMin(); - if (xmin <= 0) { - xmin = 1; + Box box = entry.getValue(); + int xMin = box.getXMin() - this.m_autocropParameters.getXCropBoxSize(); + int yMin = box.getYMin() - this.m_autocropParameters.getXCropBoxSize(); + int zMin = box.getZMin() - this.m_autocropParameters.getZCropBoxSize(); + String coordinates = box.getXMin() + "_" + box.getYMin() + "_" + box.getZMin(); + if (xMin <= 0) { + xMin = 1; } - if (ymin <= 0) { - ymin = 1; + if (yMin <= 0) { + yMin = 1; } - if (zmin <= 0) { - zmin = 1; + if (zMin <= 0) { + zMin = 1; } - int width = box.getXMax() + (2 * this.m_autocropParameters.getxCropBoxSize()) - box.getXMin(); + int width = box.getXMax() + (2 * this.m_autocropParameters.getXCropBoxSize()) - box.getXMin(); if (width > m_imageSeg.getWidth()) { width = m_imageSeg.getWidth() - 1; } - int height = box.getYMax() + (2 * this.m_autocropParameters.getxCropBoxSize()) - box.getYMin(); - int depth = box.getZMax() + (2 * this.m_autocropParameters.getzCropBoxSize()) - box.getZMin(); - if (width + xmin >= this.m_imageSeg.getWidth() || width < 0) { - width = this.m_imageSeg.getWidth() - xmin; + int height = box.getYMax() + (2 * this.m_autocropParameters.getXCropBoxSize()) - box.getYMin(); + int depth = box.getZMax() + (2 * this.m_autocropParameters.getZCropBoxSize()) - box.getZMin(); + if (width + xMin >= this.m_imageSeg.getWidth() || width < 0) { + width = this.m_imageSeg.getWidth() - xMin; } - if ((height + ymin) >= this.m_imageSeg.getHeight() || (height < 0)) { - height = this.m_imageSeg.getHeight() - ymin; + if ((height + yMin) >= this.m_imageSeg.getHeight() || (height < 0)) { + height = this.m_imageSeg.getHeight() - yMin; } - if (depth + zmin >= this.m_imageSeg.getNSlices() || depth < 0) { - depth = this.m_imageSeg.getNSlices() - zmin; + if (depth + zMin >= this.m_imageSeg.getNSlices() || depth < 0) { + depth = this.m_imageSeg.getNSlices() - zMin; } - /*System.out.println(ymin+" " +height +" "+this.m_imageSeg.getHeight());*/ - box.setXMin((short) xmin); - box.setXMax((short) (xmin + width)); - box.setYMin((short) ymin); - box.setYMax((short) (ymin + height)); - box.setZMin((short) zmin); - box.setZMax((short) (zmin + depth)); + /*System.out.println(yMin+" " +height +" "+this.m_imageSeg.getHeight());*/ + box.setXMin((short) xMin); + box.setXMax((short) (xMin + width)); + box.setYMin((short) yMin); + box.setYMax((short) (yMin + height)); + box.setZMin((short) zMin); + box.setZMax((short) (zMin + depth)); } } } + /** * Method crops a box of interest, create and save a new small image. This process allow the crop of all the * bounding box contained in the input ArrayList and the crop is did on the ImageCore put in input in this method @@ -368,26 +375,26 @@ public void addCROP_parameter() { public void cropKernels2() throws Exception { Directory dirOutput = new Directory(this.m_outputDirPath + "nuclei"); dirOutput.CheckAndCreateDir(); - this.m_infoImageAnalyse += getSpecificImageInfo() + getColumnName(); + this.m_infoImageAnalyse += getSpecificImageInfo() + getColumnNames(); for (int c = 0; c < this.m_channelNumbers; c++) { for (Map.Entry entry : this.m_boxes.entrySet()) { - int i = entry.getKey().intValue(); - Box box = entry.getValue(); - int xmin = box.getXMin(); - int ymin = box.getYMin(); - int zmin = box.getZMin(); - String coord = box.getXMin() + "_" + box.getYMin() + "_" + box.getZMin(); - int width = box.getXMax() - box.getXMin(); - int height = box.getYMax() - box.getYMin(); - int depth = box.getZMax() - box.getZMin(); - ImagePlus imgResu; + int i = entry.getKey().intValue(); + Box box = entry.getValue(); + int xMin = box.getXMin(); + int yMin = box.getYMin(); + int zMin = box.getZMin(); + int width = box.getXMax() - box.getXMin(); + int height = box.getYMax() - box.getYMin(); + int depth = box.getZMax() - box.getZMin(); + String coordinates = box.getXMin() + "_" + box.getYMin() + "_" + box.getZMin(); + ImagePlus croppedImage; if (this.m_rawImg.getNSlices() > 1) { - imgResu = cropImage(xmin, ymin, zmin, width, height, depth, c); + croppedImage = cropImage(xMin, yMin, zMin, width, height, depth, c); } else { - imgResu = cropImage2D(xmin, ymin, width, height, c); + croppedImage = cropImage2D(xMin, yMin, width, height, c); } Calibration cal = this.m_rawImg.getCalibration(); - imgResu.setCalibration(cal); + croppedImage.setCalibration(cal); OutputTiff fileOutput = new OutputTiff(dirOutput.get_dirPath() + File.separator + this.m_outputFilesPrefix + @@ -407,13 +414,13 @@ public void cropKernels2() throws Exception { ".tif\t" + c + "\t" + i + "\t" + - xmin + "\t" + - ymin + "\t" + - zmin + "\t" + + xMin + "\t" + + yMin + "\t" + + zMin + "\t" + width + "\t" + height + "\t" + depth + "\n"; - fileOutput.SaveImage(imgResu); + fileOutput.SaveImage(croppedImage); this.m_outputFile.add(this.m_outputDirPath + File.separator + this.m_outputFilesPrefix + @@ -423,48 +430,49 @@ public void cropKernels2() throws Exception { i + ".tif"); if (c == 0) { - int xmax = xmin + width; - int ymax = ymin + height; - int zmax = zmin + depth; + int xMax = xMin + width; + int yMax = yMin + height; + int zMax = zMin + depth; this.m_boxCoordinates.add(this.m_outputDirPath + File.separator + this.m_outputFilesPrefix + "_" + i + "_C0" + "\t" + - xmin + "\t" + - xmax + "\t" + - ymin + "\t" + - ymax + "\t" + - zmin + "\t" + - zmax); - //xmin, ymin,zmin, width,height, depth,y + xMin + "\t" + + xMax + "\t" + + yMin + "\t" + + yMax + "\t" + + zMin + "\t" + + zMax); + //xMin, yMin,zMin, width,height, depth,y } } } } + public void cropKernelsOmero(ImageContainer image, Long[] outputsDat, Client client) throws Exception { - this.m_infoImageAnalyse += getSpecificImageInfo() + getColumnName(); + this.m_infoImageAnalyse += getSpecificImageInfo() + getColumnNames(); for (int c = 0; c < this.m_channelNumbers; c++) { for (Map.Entry entry : this.m_boxes.entrySet()) { - DatasetContainer dataset = client.getDataset(outputsDat[c]); - int i = entry.getKey().intValue(); - Box box = entry.getValue(); - int xmin = box.getXMin(); - int ymin = box.getYMin(); - int zmin = box.getZMin(); - String coord = box.getXMin() + "_" + box.getYMin() + "_" + box.getZMin(); - int width = box.getXMax() - box.getXMin(); - int height = box.getYMax() - box.getYMin(); - int depth = box.getZMax() - box.getZMin(); - int[] xBound = {box.getXMin(), box.getXMax() - 1}; - int[] yBound = {box.getYMin(), box.getYMax() - 1}; - int[] zBound = {box.getZMin(), box.getZMax() - 1}; - int[] cBound = {c, c}; - List shapes = new ArrayList<>(); + DatasetContainer dataset = client.getDataset(outputsDat[c]); + int i = entry.getKey().intValue(); + Box box = entry.getValue(); + int xMin = box.getXMin(); + int yMin = box.getYMin(); + int zMin = box.getZMin(); + int width = box.getXMax() - box.getXMin(); + int height = box.getYMax() - box.getYMin(); + int depth = box.getZMax() - box.getZMin(); + String coordinates = box.getXMin() + "_" + box.getYMin() + "_" + box.getZMin(); + int[] xBound = {box.getXMin(), box.getXMax() - 1}; + int[] yBound = {box.getYMin(), box.getYMax() - 1}; + int[] zBound = {box.getZMin(), box.getZMax() - 1}; + int[] cBound = {c, c}; + List shapes = new ArrayList<>(); for (int z = box.getZMin(); z < box.getZMax(); z++) { - RectangleData rectangle = new RectangleData(xmin, ymin, width, height); + RectangleData rectangle = new RectangleData(xMin, yMin, width, height); rectangle.setC(c); rectangle.setZ(z); rectangle.setT(0); @@ -475,11 +483,11 @@ public void cropKernelsOmero(ImageContainer image, Long[] outputsDat, Client cli } ROIContainer roi = new ROIContainer(shapes); image.saveROI(client, roi); - ImagePlus imgResu = image.toImagePlus(client, xBound, yBound, cBound, zBound, null); - Calibration cal = this.m_rawImg.getCalibration(); - imgResu.setCalibration(cal); - String path = - new java.io.File(".").getCanonicalPath() + "/" + this.m_outputFilesPrefix + "_" + i + ".tif"; + ImagePlus croppedImage = image.toImagePlus(client, xBound, yBound, cBound, zBound, null); + Calibration cal = this.m_rawImg.getCalibration(); + croppedImage.setCalibration(cal); + String path = new java.io.File(".").getCanonicalPath() + File.separator + + this.m_outputFilesPrefix + "_" + i + ".tif"; OutputTiff fileOutput = new OutputTiff(path); this.m_infoImageAnalyse = this.m_infoImageAnalyse + m_outputDirPath + @@ -491,63 +499,64 @@ public void cropKernelsOmero(ImageContainer image, Long[] outputsDat, Client cli ".tif\t" + c + "\t" + i + "\t" + - xmin + "\t" + - ymin + "\t" + - zmin + "\t" + + xMin + "\t" + + yMin + "\t" + + zMin + "\t" + width + "\t" + height + "\t" + depth + "\n"; - fileOutput.SaveImage(imgResu); + fileOutput.SaveImage(croppedImage); this.m_outputFile.add(this.m_outputFilesPrefix + "_" + i + ".tif"); dataset.importImages(client, path); File file = new File(path); file.delete(); if (c == 0) { - int xmax = xmin + width; - int ymax = ymin + height; - int zmax = zmin + depth; + int xMax = xMin + width; + int yMax = yMin + height; + int zMax = zMin + depth; this.m_boxCoordinates.add(this.m_outputDirPath + File.separator + this.m_outputFilesPrefix + "_" + - coord + + coordinates + i + "\t" + - xmin + "\t" + - xmax + "\t" + - ymin + "\t" + - ymax + "\t" + - zmin + "\t" + - zmax); - //xmin, ymin,zmin, width,height, depth,y + xMin + "\t" + + xMax + "\t" + + yMin + "\t" + + yMax + "\t" + + zMin + "\t" + + zMax); + //xMin, yMin,zMin, width,height, depth,y } } } } + /** Method crops a box of interest, from coordinate files. */ public void cropKernels3() throws Exception { Directory dirOutput = new Directory(this.m_outputDirPath + File.separator + "Nuclei"); dirOutput.CheckAndCreateDir(); - this.m_infoImageAnalyse += getSpecificImageInfo() + getColumnName(); + this.m_infoImageAnalyse += getSpecificImageInfo() + getColumnNames(); for (int c = 0; c < this.m_channelNumbers; c++) { for (Map.Entry entry : this.m_boxes.entrySet()) { - int i = entry.getKey().intValue(); - Box box = entry.getValue(); - int xmin = box.getXMin(); - int ymin = box.getYMin(); - int zmin = box.getZMin(); - String coord = box.getXMin() + "_" + box.getYMin() + "_" + box.getZMin(); - int width = box.getXMax() - box.getXMin(); - int height = box.getYMax() - box.getYMin(); - int depth = box.getZMax() - box.getZMin(); - ImagePlus imgResu; + int i = entry.getKey().intValue(); + Box box = entry.getValue(); + int xMin = box.getXMin(); + int yMin = box.getYMin(); + int zMin = box.getZMin(); + int width = box.getXMax() - box.getXMin(); + int height = box.getYMax() - box.getYMin(); + int depth = box.getZMax() - box.getZMin(); + String coordinates = box.getXMin() + "_" + box.getYMin() + "_" + box.getZMin(); + ImagePlus croppedImage; if (this.m_rawImg.getNSlices() > 1) { - imgResu = cropImage(xmin, ymin, zmin, width, height, depth, c); + croppedImage = cropImage(xMin, yMin, zMin, width, height, depth, c); } else { - imgResu = cropImage2D(xmin, ymin, width, height, c); + croppedImage = cropImage2D(xMin, yMin, width, height, c); } Calibration cal = this.m_rawImg.getCalibration(); - imgResu.setCalibration(cal); + croppedImage.setCalibration(cal); OutputTiff fileOutput = new OutputTiff(dirOutput.get_dirPath() + File.separator + this.m_outputFilesPrefix + @@ -567,13 +576,13 @@ public void cropKernels3() throws Exception { ".tif\t" + c + "\t" + i + "\t" + - xmin + "\t" + - ymin + "\t" + - zmin + "\t" + + xMin + "\t" + + yMin + "\t" + + zMin + "\t" + width + "\t" + height + "\t" + depth + "\n"; - fileOutput.SaveImage(imgResu); + fileOutput.SaveImage(croppedImage); this.m_outputFile.add(this.m_outputDirPath + File.separator + this.m_outputFilesPrefix + @@ -583,28 +592,29 @@ public void cropKernels3() throws Exception { i + ".tif"); if (c == 0) { - int xmax = xmin + width; - int ymax = ymin + height; - int zmax = zmin + depth; + int xMax = xMin + width; + int yMax = yMin + height; + int zMax = zMin + depth; this.m_boxCoordinates.add(this.m_outputDirPath + File.separator + this.m_outputFilesPrefix + "_" + i + "\t" + - xmin + "\t" + - xmax + "\t" + - ymin + "\t" + - ymax + "\t" + - zmin + "\t" + - zmax); - //xmin, ymin,zmin, width,height, depth,y + xMin + "\t" + + xMax + "\t" + + yMin + "\t" + + yMax + "\t" + + zMin + "\t" + + zMax); + //xMin, yMin,zMin, width,height, depth,y } } } } + /** - * Getter for the m_outputFiel ArrayList + * Getter for the m_outputFile ArrayList * * @return m_outputFile: ArrayList of String for the path of the output files created. */ @@ -612,6 +622,7 @@ public ArrayList getOutputFileArrayList() { return this.m_outputFile; } + /** * Getter for the m_boxCoordinates * @@ -621,6 +632,7 @@ public ArrayList getFileCoordinates() { return this.m_boxCoordinates; } + /** * Create binary image with the threshold value gave in input * @@ -648,12 +660,13 @@ private ImagePlus generateSegmentedImage(ImagePlus imagePlusInput, int threshold return imagePlusSegmented; } + /** * Crop of the bounding box on 3D image. The coordinates are inputs of this methods * - * @param xmin: coordinate x min of the crop - * @param ymin: coordinate y min of the crop - * @param zmin: coordinate z min of the crop + * @param xMin: coordinate x min of the crop + * @param yMin: coordinate y min of the crop + * @param zMin: coordinate z min of the crop * @param width: coordinate x max of the crop * @param height: coordinate y max of the crop * @param depth: coordinate z max of the crop @@ -661,43 +674,44 @@ private ImagePlus generateSegmentedImage(ImagePlus imagePlusInput, int threshold * * @return : ImageCoreIJ of the cropped image. */ - public ImagePlus cropImage(int xmin, int ymin, int zmin, int width, int height, int depth, int channelNumber) + public ImagePlus cropImage(int xMin, int yMin, int zMin, int width, int height, int depth, int channelNumber) throws Exception { ImporterOptions options = new ImporterOptions(); options.setId(this.m_imageFilePath); options.setAutoscale(true); options.setCrop(true); - ImagePlus[] imps = BF.openImagePlus(options); - ImagePlus sort = new ImagePlus(); - ChannelSplitter channelSplitter = new ChannelSplitter(); - imps = channelSplitter.split(imps[0]); - sort.setStack(imps[channelNumber].getStack().crop(xmin, ymin, zmin, width, height, depth)); + ImagePlus[] imps = BF.openImagePlus(options); + ImagePlus sort = new ImagePlus(); + imps = ChannelSplitter.split(imps[0]); + sort.setStack(imps[channelNumber].getStack().crop(xMin, yMin, zMin, width, height, depth)); return sort; } + /** * Crop of the bounding box on 2D image. The coordinates are inputs of this methods. * - * @param xmin: coordinate x min of the crop - * @param ymin: coordinate y min of the crop + * @param xMin: coordinate x min of the crop + * @param yMin: coordinate y min of the crop * @param width: coordinate x max of the crop * @param height: coordinate y max of the crop * @param channelNumber: channel to crop * * @return : ImageCoreIJ of the cropped image. */ - public ImagePlus cropImage2D(int xmin, int ymin, int width, int height, int channelNumber) throws Exception { + public ImagePlus cropImage2D(int xMin, int yMin, int width, int height, int channelNumber) throws Exception { ImporterOptions options = new ImporterOptions(); options.setId(this.m_imageFilePath); options.setAutoscale(true); options.setCrop(true); ImagePlus[] imps = BF.openImagePlus(options); ImagePlus sort = imps[channelNumber]; - sort.setRoi(xmin, ymin, width, height); + sort.setRoi(xMin, yMin, width, height); sort.crop(); return sort; } + /** * Getter of the number of nuclei contained in the input image * @@ -707,34 +721,34 @@ public int getNbOfNuc() { return this.m_boxes.size(); } + /** @return Header current image info analyse */ public String getSpecificImageInfo() { Calibration cal = this.m_rawImg.getCalibration(); return "#Image: " + this.m_imageFilePath + "\n#OTSU threshold: " + - this.OTSUthreshold + - "\n#Slice used for OTSU threshol: " + + this.OTSUThreshold + + "\n#Slice used for OTSU threshold: " + this.sliceUsedForOTSU + "\n"; } + /** * Getter column name for the tab delimited file * * @return columns name for output text file */ - public String getColumnName() { - String columnName = "FileName\tChannelNumber\tCropNumber\tXStart\tYStart\tZStart\twidth\theight\tdepth\n"; - return columnName; + public String getColumnNames() { + return "FileName\tChannelNumber\tCropNumber\tXStart\tYStart\tZStart\twidth\theight\tdepth\n"; } + /** - * Write analyse info in output texte file - * - * @throws IOException + * Write analysis info in output text file */ - public void writeAnalyseInfo() throws Exception { + public void writeAnalyseInfo() { Directory dirOutput = new Directory(this.m_outputDirPath + "coordinates"); dirOutput.CheckAndCreateDir(); OutputTextFile resultFileOutput = new OutputTextFile(this.m_outputDirPath + @@ -745,22 +759,25 @@ public void writeAnalyseInfo() throws Exception { resultFileOutput.SaveTextFile(this.m_infoImageAnalyse); } + /** - * Write analyse info in output texte file + * Write analyse info in output text file * * @throws IOException */ public void writeAnalyseInfoOmero(Long id, Client client) throws DSOutOfServiceException, IOException, DSAccessException, ExecutionException, ServerError { - String path = new java.io.File(".").getCanonicalPath() + this.m_outputFilesPrefix + ".txt"; - OutputTexteFile resultFileOutput = new OutputTexteFile(path); - resultFileOutput.SaveTexteFile(this.m_infoImageAnalyse); - DatasetContainer dataset = client.getDataset(id); - File file = new File(path); + String path = + new java.io.File(".").getCanonicalPath() + this.m_outputFilesPrefix + ".txt"; + File file = new File(path); + OutputTexteFile resultFileOutput = new OutputTexteFile(path); + DatasetContainer dataset = client.getDataset(id); + resultFileOutput.saveTextFile(this.m_infoImageAnalyse); dataset.addFile(client, file); file.delete(); } + /** * Getter number of crop * @@ -771,16 +788,18 @@ public String getImageCropInfo() { "\t" + getNbOfNuc() + "\t" + - this.OTSUthreshold + + this.OTSUThreshold + "\t" + this.m_defaultThreshold + "\n"; } + public void getNumberOfBox() { System.out.println("Number of box :" + this.m_boxes.size()); } + /** * Compute volume voxel of current image analysed * @@ -797,15 +816,17 @@ public double getVoxelVolume() { return calibration; } + /** Compute boxes merging if intersecting */ public void boxIntersection() { - if (this.m_autocropParameters.getboxesRegroupement()) { + if (this.m_autocropParameters.getBoxesRegrouping()) { rectangleIntersection recompute = new rectangleIntersection(this.m_boxes, this.m_autocropParameters); recompute.runRectangleRecompilation(); this.m_boxes = recompute.getNewBoxes(); } } + /** * Set a list of boxes * diff --git a/src/main/java/gred/nucleus/autocrop/AutoCropCalling.java b/src/main/java/gred/nucleus/autocrop/AutoCropCalling.java index ed2df8f7..a4af6552 100644 --- a/src/main/java/gred/nucleus/autocrop/AutoCropCalling.java +++ b/src/main/java/gred/nucleus/autocrop/AutoCropCalling.java @@ -6,10 +6,8 @@ import gred.nucleus.filesInputOutput.FilesNames; import gred.nucleus.filesInputOutput.OutputTextFile; import ij.IJ; -import loci.formats.FormatException; import java.io.File; -import java.io.IOException; import java.util.List; @@ -33,20 +31,20 @@ public class AutoCropCalling { public AutoCropCalling() { } + public AutoCropCalling(AutocropParameters autocropParameters) { this.m_autocropParameters = autocropParameters; - this.m_outputCropGeneralInfo = autocropParameters.getAnalyseParameters() + getColnameResult(); + this.m_outputCropGeneralInfo = autocropParameters.getAnalyseParameters() + getResultsColumnNames(); } + /** * Run auto crop on image's folder: -If input is a file: open the image with bio-formats plugin to obtain the metadata * then run the auto crop. -If input is directory, listed the file, foreach tif file loaded file with bio-formats, run * the auto crop. * - * @throws IOException if file problem - * @throws FormatException Bio-formats exception */ - public void runFolder() throws Exception { + public void runFolder() { Directory directoryInput = new Directory(this.m_autocropParameters.getInputFolder()); directoryInput.listImageFiles(this.m_autocropParameters.getInputFolder()); directoryInput.checkIfEmpty(); @@ -56,11 +54,11 @@ public void runFolder() throws Exception { System.out.println("Current file " + currentFile.getAbsolutePath()); String fileImg = currentFile.toString(); FilesNames outPutFilesNames = new FilesNames(fileImg); - this._prefix = outPutFilesNames.PrefixeNameFile(); + this._prefix = outPutFilesNames.prefixNameFile(); try { AutoCrop autoCrop = new AutoCrop(currentFile, this._prefix, this.m_autocropParameters); autoCrop.thresholdKernels(); - autoCrop.computeConnectcomponent(); + autoCrop.computeConnectedComponent(); autoCrop.componentBorderFilter(); autoCrop.componentSizeFilter(); autoCrop.computeBoxes2(); @@ -100,10 +98,10 @@ public void runFile(String file) throws Exception { File currentFile = new File(file); String fileImg = currentFile.toString(); FilesNames outPutFilesNames = new FilesNames(fileImg); - this._prefix = outPutFilesNames.PrefixeNameFile(); + this._prefix = outPutFilesNames.prefixNameFile(); AutoCrop autoCrop = new AutoCrop(currentFile, this._prefix, this.m_autocropParameters); autoCrop.thresholdKernels(); - autoCrop.computeConnectcomponent(); + autoCrop.computeConnectedComponent(); autoCrop.componentBorderFilter(); autoCrop.componentSizeFilter(); autoCrop.computeBoxes2(); @@ -113,21 +111,22 @@ public void runFile(String file) throws Exception { autoCrop.writeAnalyseInfo(); annotAutoCrop test = new annotAutoCrop(autoCrop.getFileCoordinates(), currentFile, - this.m_autocropParameters.getOutputFolder() + currentFile.separator, + this.m_autocropParameters.getOutputFolder() + File.separator, this._prefix, this.m_autocropParameters); test.run(); this.m_outputCropGeneralInfo = this.m_outputCropGeneralInfo + autoCrop.getImageCropInfo(); } + public void runImageOmero(ImageContainer image, Long[] outputsDatImages, Client client) throws Exception { String fileImg = image.getName(); System.out.println("Current file : " + fileImg); FilesNames outPutFilesNames = new FilesNames(fileImg); - this._prefix = outPutFilesNames.PrefixeNameFile(); + this._prefix = outPutFilesNames.prefixNameFile(); AutoCrop autoCrop = new AutoCrop(image, this.m_autocropParameters, client); autoCrop.thresholdKernels(); - autoCrop.computeConnectcomponent(); + autoCrop.computeConnectedComponent(); autoCrop.componentBorderFilter(); autoCrop.componentSizeFilter(); autoCrop.computeBoxes2(); @@ -139,6 +138,7 @@ public void runImageOmero(ImageContainer image, Long[] outputsDatImages, Client this.m_outputCropGeneralInfo = this.m_outputCropGeneralInfo + autoCrop.getImageCropInfo(); } + public void runSeveralImageOmero(List images, Long[] outputsDatImages, Client client) throws Exception { for (ImageContainer image : images) runImageOmero(image, outputsDatImages, client); @@ -146,11 +146,11 @@ public void runSeveralImageOmero(List images, Long[] outputsDatI /** - * List of columns name in csv coordinates output file. + * List of columns names in csv coordinates output file. * * @return columns name */ - public String getColnameResult() { + public String getResultsColumnNames() { return "FileName\tNumberOfCrop\tOTSUThreshold\tDefaultOTSUThreshold\n"; } } diff --git a/src/main/java/gred/nucleus/autocrop/AutocropParameters.java b/src/main/java/gred/nucleus/autocrop/AutocropParameters.java index 63575850..556631d7 100644 --- a/src/main/java/gred/nucleus/autocrop/AutocropParameters.java +++ b/src/main/java/gred/nucleus/autocrop/AutocropParameters.java @@ -15,26 +15,27 @@ public class AutocropParameters extends PluginParameters { /** Maximal object volume to crop */ int m_maxVolumeNucleus = 2147483647; /** Number of pixels take plus object size in x */ - private int m_xCropBoxSize = 40; + private int m_xCropBoxSize = 40; /** Number of pixels take plus object size in y */ - private int m_yCropBoxSize = 40; + private int m_yCropBoxSize = 40; /** Number of slice take plus object in y */ - private int m_zCropBoxSize = 20; + private int m_zCropBoxSize = 20; /** Minimal default OTSU threshold */ - private int m_thresholdOTSUcomputing = 20; + private int m_thresholdOTSUComputing = 20; /** Channel to compute OTSU threshold */ private int m_channelToComputeThreshold = 0; /** Slice start to compute OTSU threshold */ - private int m_slicesOTSUcomputing = 0; + private int m_slicesOTSUComputing = 0; /** Surface percent of boxes to groups them */ private int m_boxesPercentSurfaceToFilter = 50; - /** Activation of boxes regroupement */ - private boolean m_boxesRegroupement = true; + /** Activation of boxes regrouping */ + private boolean m_boxesRegrouping = true; public AutocropParameters() { } + /** * Constructor with default parameter * @@ -46,6 +47,7 @@ public AutocropParameters(String inputFolder, String outputFolder) { } + /** * Constructor with box size modifications * @@ -59,16 +61,17 @@ public AutocropParameters(String inputFolder, String outputFolder, int xCropBoxSize, int yCropBoxSize, int zCropBoxSize, - int thresholdOTSUcomputing, + int thresholdOTSUComputing, int channelToComputeThreshold) { super(inputFolder, outputFolder); this.m_xCropBoxSize = xCropBoxSize; this.m_yCropBoxSize = yCropBoxSize; this.m_zCropBoxSize = zCropBoxSize; - this.m_thresholdOTSUcomputing = thresholdOTSUcomputing; + this.m_thresholdOTSUComputing = thresholdOTSUComputing; this.m_channelToComputeThreshold = channelToComputeThreshold; } + /** * Constructor with all manual parameters * @@ -78,8 +81,8 @@ public AutocropParameters(String inputFolder, String outputFolder, * @param yCropBoxSize : number of voxels add in z axis around object * @param zCropBoxSize : number of stack add in z axis around object * @param channelToComputeThreshold : channel number to compute OTSU - * @param slicesOTSUcomputing : slice start to compute OTSU - * @param thresholdOTSUcomputing : minimum OTSU threshold used + * @param slicesOTSUComputing : slice start to compute OTSU + * @param thresholdOTSUComputing : minimum OTSU threshold used * @param maxVolumeNucleus : volume maximum of objects detected * @param minVolumeNucleus : volume minimum of objects detected */ @@ -87,8 +90,8 @@ public AutocropParameters(String inputFolder, String outputFolder, int xCropBoxSize, int yCropBoxSize, int zCropBoxSize, - int slicesOTSUcomputing, - int thresholdOTSUcomputing, + int slicesOTSUComputing, + int thresholdOTSUComputing, int channelToComputeThreshold, int minVolumeNucleus, int maxVolumeNucleus) { @@ -97,14 +100,15 @@ public AutocropParameters(String inputFolder, String outputFolder, this.m_xCropBoxSize = xCropBoxSize; this.m_yCropBoxSize = yCropBoxSize; this.m_zCropBoxSize = zCropBoxSize; - this.m_thresholdOTSUcomputing = thresholdOTSUcomputing; - this.m_slicesOTSUcomputing = slicesOTSUcomputing; + this.m_thresholdOTSUComputing = thresholdOTSUComputing; + this.m_slicesOTSUComputing = slicesOTSUComputing; this.m_channelToComputeThreshold = channelToComputeThreshold; this.m_maxVolumeNucleus = maxVolumeNucleus; this.m_minVolumeNucleus = minVolumeNucleus; } + /** * Constructor with all manual parameters 2 * @@ -114,39 +118,39 @@ public AutocropParameters(String inputFolder, String outputFolder, * @param yCropBoxSize : number of voxels add in z axis around object * @param zCropBoxSize : number of stack add in z axis around object * @param channelToComputeThreshold : channel number to compute OTSU - * @param slicesOTSUcomputing : slice start to compute OTSU - * @param thresholdOTSUcomputing : minimum OTSU threshold used + * @param slicesOTSUComputing : slice start to compute OTSU + * @param thresholdOTSUComputing : minimum OTSU threshold used * @param maxVolumeNucleus : volume maximum of objects detected * @param minVolumeNucleus : volume minimum of objects detected * @param boxesPercentSurfaceToFilter : surface percent of boxes to groups them - * @param boxesRegroupement : activation of boxes regroupement + * @param boxesRegrouping : activation of boxes regrouping */ public AutocropParameters(String inputFolder, String outputFolder, int xCropBoxSize, int yCropBoxSize, int zCropBoxSize, - int slicesOTSUcomputing, - int thresholdOTSUcomputing, + int slicesOTSUComputing, + int thresholdOTSUComputing, int channelToComputeThreshold, int minVolumeNucleus, int maxVolumeNucleus, int boxesPercentSurfaceToFilter, - boolean boxesRegroupement) { + boolean boxesRegrouping) { super(inputFolder, outputFolder); this.m_xCropBoxSize = xCropBoxSize; this.m_yCropBoxSize = yCropBoxSize; this.m_zCropBoxSize = zCropBoxSize; - this.m_thresholdOTSUcomputing = thresholdOTSUcomputing; - this.m_slicesOTSUcomputing = slicesOTSUcomputing; + this.m_thresholdOTSUComputing = thresholdOTSUComputing; + this.m_slicesOTSUComputing = slicesOTSUComputing; this.m_channelToComputeThreshold = channelToComputeThreshold; this.m_maxVolumeNucleus = maxVolumeNucleus; this.m_minVolumeNucleus = minVolumeNucleus; - this.m_boxesRegroupement = boxesRegroupement; + this.m_boxesRegrouping = boxesRegrouping; this.m_boxesPercentSurfaceToFilter = boxesPercentSurfaceToFilter; - } + /** * Constructor with box size modification and slice number used to start OTSU threshold calculation to last slice * @@ -156,8 +160,8 @@ public AutocropParameters(String inputFolder, String outputFolder, * @param yCropBoxSize : number of voxels add in z axis around object * @param zCropBoxSize : number of stack add in z axis around object * @param channelToComputeThreshold : channel number to compute OTSU - * @param slicesOTSUcomputing : slice start to compute OTSU - * @param thresholdOTSUcomputing : minimum OTSU threshold used + * @param slicesOTSUComputing : slice start to compute OTSU + * @param thresholdOTSUComputing : minimum OTSU threshold used * @param maxVolumeNucleus : volume maximum of objects detected * @param minVolumeNucleus : volume minimum of objects detected */ @@ -168,8 +172,8 @@ public AutocropParameters(String inputFolder, String outputFolder, int xCropBoxSize, int yCropBoxSize, int zCropBoxSize, - int slicesOTSUcomputing, - int thresholdOTSUcomputing, + int slicesOTSUComputing, + int thresholdOTSUComputing, int channelToComputeThreshold, int minVolumeNucleus, int maxVolumeNucleus) { @@ -178,14 +182,15 @@ public AutocropParameters(String inputFolder, String outputFolder, this.m_xCropBoxSize = xCropBoxSize; this.m_yCropBoxSize = yCropBoxSize; this.m_zCropBoxSize = zCropBoxSize; - this.m_thresholdOTSUcomputing = thresholdOTSUcomputing; - this.m_slicesOTSUcomputing = slicesOTSUcomputing; + this.m_thresholdOTSUComputing = thresholdOTSUComputing; + this.m_slicesOTSUComputing = slicesOTSUComputing; this.m_channelToComputeThreshold = channelToComputeThreshold; this.m_maxVolumeNucleus = maxVolumeNucleus; this.m_minVolumeNucleus = minVolumeNucleus; } + /** * Constructor with box size modification and slice number used to start OTSU threshold calculation to last slice * @@ -198,12 +203,12 @@ public AutocropParameters(String inputFolder, String outputFolder, * @param yCropBoxSize : number of voxels add in z axis around object * @param zCropBoxSize : number of stack add in z axis around object * @param channelToComputeThreshold : channel number to compute OTSU - * @param slicesOTSUcomputing : slice start to compute OTSU - * @param thresholdOTSUcomputing : minimum OTSU threshold used + * @param slicesOTSUComputing : slice start to compute OTSU + * @param thresholdOTSUComputing : minimum OTSU threshold used * @param maxVolumeNucleus : volume maximum of objects detected * @param minVolumeNucleus : volume minimum of objects detected * @param boxesPercentSurfaceToFilter : surface percent of boxes to groups them - * @param boxesRegroupement : activation of boxes regroupement + * @param regroupBoxes : activation of boxes regrouping */ public AutocropParameters(String inputFolder, String outputFolder, double xCal, @@ -212,28 +217,29 @@ public AutocropParameters(String inputFolder, String outputFolder, int xCropBoxSize, int yCropBoxSize, int zCropBoxSize, - int slicesOTSUcomputing, - int thresholdOTSUcomputing, + int slicesOTSUComputing, + int thresholdOTSUComputing, int channelToComputeThreshold, int minVolumeNucleus, int maxVolumeNucleus, int boxesPercentSurfaceToFilter, - boolean boxesRegroupement) { + boolean regroupBoxes) { super(inputFolder, outputFolder, xCal, yCal, zCal); this.m_xCropBoxSize = xCropBoxSize; this.m_yCropBoxSize = yCropBoxSize; this.m_zCropBoxSize = zCropBoxSize; - this.m_thresholdOTSUcomputing = thresholdOTSUcomputing; - this.m_slicesOTSUcomputing = slicesOTSUcomputing; + this.m_thresholdOTSUComputing = thresholdOTSUComputing; + this.m_slicesOTSUComputing = slicesOTSUComputing; this.m_channelToComputeThreshold = channelToComputeThreshold; this.m_maxVolumeNucleus = maxVolumeNucleus; this.m_minVolumeNucleus = minVolumeNucleus; this.m_boxesPercentSurfaceToFilter = boxesPercentSurfaceToFilter; - this.m_boxesRegroupement = boxesRegroupement; + this.m_boxesRegrouping = regroupBoxes; } + /** * Constructor using input , output folders and config file (for command line execution) * @@ -248,12 +254,12 @@ public AutocropParameters(String inputFolder, String outputFolder, } + public void addProperties(String pathToConfigFile) { - Properties prop = new Properties(); - String fileName = pathToConfigFile; - InputStream is = null; + Properties prop = new Properties(); + InputStream is = null; try { - is = new FileInputStream(fileName); + is = new FileInputStream(pathToConfigFile); } catch (FileNotFoundException ex) { System.err.println(pathToConfigFile + " : can't find the config file !"); System.exit(-1); @@ -265,50 +271,42 @@ public void addProperties(String pathToConfigFile) { System.exit(-1); } for (String idProp : prop.stringPropertyNames()) { - if (idProp.equals("xCropBoxSize")) { - this.m_xCropBoxSize = - Integer.parseInt(prop.getProperty("xCropBoxSize")); - } - if (idProp.equals("yCropBoxSize")) { - this.m_yCropBoxSize = - Integer.parseInt(prop.getProperty("yCropBoxSize")); - } - if (idProp.equals("zCropBoxSize")) { - this.m_zCropBoxSize = - Integer.parseInt(prop.getProperty("zCropBoxSize")); - } - if (idProp.equals("thresholdOTSUcomputing")) { - this.m_thresholdOTSUcomputing = - Integer.parseInt(prop.getProperty("thresholdOTSUcomputing")); - } - if (idProp.equals("slicesOTSUcomputing")) { - this.m_slicesOTSUcomputing = - Integer.parseInt(prop.getProperty("slicesOTSUcomputing")); - } - if (idProp.equals("channelToComputeThreshold")) { - this.m_channelToComputeThreshold = - Integer.parseInt(prop.getProperty("channelToComputeThreshold")); - } - if (idProp.equals("maxVolumeNucleus")) { - this.m_maxVolumeNucleus = - Integer.parseInt(prop.getProperty("maxVolumeNucleus")); + switch (idProp) { + case "xCropBoxSize": + this.m_xCropBoxSize = Integer.parseInt(prop.getProperty("xCropBoxSize")); + break; + case "yCropBoxSize": + this.m_yCropBoxSize = Integer.parseInt(prop.getProperty("yCropBoxSize")); + break; + case "zCropBoxSize": + this.m_zCropBoxSize = Integer.parseInt(prop.getProperty("zCropBoxSize")); + break; + case "thresholdOTSUComputing": + this.m_thresholdOTSUComputing = Integer.parseInt(prop.getProperty("thresholdOTSUComputing")); + break; + case "slicesOTSUComputing": + this.m_slicesOTSUComputing = Integer.parseInt(prop.getProperty("slicesOTSUComputing")); + break; + case "channelToComputeThreshold": + this.m_channelToComputeThreshold = Integer.parseInt(prop.getProperty("channelToComputeThreshold")); + break; + case "maxVolumeNucleus": + this.m_maxVolumeNucleus = Integer.parseInt(prop.getProperty("maxVolumeNucleus")); + break; + case "minVolumeNucleus": + this.m_minVolumeNucleus = Integer.parseInt(prop.getProperty("minVolumeNucleus")); + break; + case "boxesPercentSurfaceToFilter": + this.m_boxesPercentSurfaceToFilter = Integer.parseInt(prop.getProperty("boxesPercentSurfaceToFilter")); + break; + case "boxesRegrouping": + this.m_boxesRegrouping = Boolean.parseBoolean(prop.getProperty("boxesRegrouping")); + break; } - if (idProp.equals("minVolumeNucleus")) { - this.m_minVolumeNucleus = - Integer.parseInt(prop.getProperty("minVolumeNucleus")); - } - if (idProp.equals("boxesPercentSurfaceToFilter")) { - this.m_boxesPercentSurfaceToFilter = - Integer.parseInt(prop.getProperty("boxesPercentSurfaceToFilter")); - } - if (idProp.equals("boxesRegroupement")) { - this.m_boxesRegroupement = - Boolean.parseBoolean(prop.getProperty("boxesRegroupement")); - } - } } + /** * Method to get parameters of the analyse * @@ -316,53 +314,58 @@ public void addProperties(String pathToConfigFile) { */ public String getAnalyseParameters() { super.getAnalyseParameters(); - this.m_headerInfo += "#X box size: " + getxCropBoxSize() + "\n" - + "#Y box size: " + getyCropBoxSize() + "\n" - + "#Z box size: " + getzCropBoxSize() + "\n" - + "#thresholdOTSUcomputing: " + getThresholdOTSUcomputing() + "\n" - + "#slicesOTSUcomputing: " + getSlicesOTSUcomputing() + "\n" + this.m_headerInfo += "#X box size: " + getXCropBoxSize() + "\n" + + "#Y box size: " + getYCropBoxSize() + "\n" + + "#Z box size: " + getZCropBoxSize() + "\n" + + "#thresholdOTSUComputing: " + getThresholdOTSUComputing() + "\n" + + "#slicesOTSUComputing: " + getSlicesOTSUComputing() + "\n" + "#channelToComputeThreshold: " + getChannelToComputeThreshold() + "\n" + "#maxVolumeNucleus:" + getM_maxVolumeNucleus() + "\n" + "#minVolumeNucleus: " + getM_minVolumeNucleus() + "\n"; return this.m_headerInfo; } + /** * Getter for x box size in pixel * * @return x box size in pixel */ - public int getxCropBoxSize() { + public int getXCropBoxSize() { return this.m_xCropBoxSize; } + /** * Getter for y box size in pixel * * @return y box size in pixel */ - public int getyCropBoxSize() { + public int getYCropBoxSize() { return this.m_yCropBoxSize; } + /** * Getter for z box size in pixel * * @return z box size in pixel */ - public int getzCropBoxSize() { + public int getZCropBoxSize() { return this.m_zCropBoxSize; } + /** * Getter for OTSU threshold used to compute segmented image * * @return OTSU threshold used */ - public int getThresholdOTSUcomputing() { - return this.m_thresholdOTSUcomputing; + public int getThresholdOTSUComputing() { + return this.m_thresholdOTSUComputing; } + /** * Getter for channel number used to segmented image (OTSU computing) * @@ -372,6 +375,7 @@ public int getChannelToComputeThreshold() { return this.m_channelToComputeThreshold; } + /** * Getter for minimum volume object segmented * @@ -381,6 +385,7 @@ public int getM_minVolumeNucleus() { return this.m_minVolumeNucleus; } + /** * Getter for maximum volume object segmented * @@ -390,24 +395,27 @@ public int getM_maxVolumeNucleus() { return this.m_maxVolumeNucleus; } + /** * Getter for start slice used to compute OTSU * * @return start slice */ - public int getSlicesOTSUcomputing() { - return this.m_slicesOTSUcomputing; + public int getSlicesOTSUComputing() { + return this.m_slicesOTSUComputing; } + /** * Getter boxes merging activation * * @return status */ - public boolean getboxesRegroupement() { - return this.m_boxesRegroupement; + public boolean getBoxesRegrouping() { + return this.m_boxesRegrouping; } + /** * Getter percent of surface intersection to merge 2 rectangles. * diff --git a/src/main/java/gred/nucleus/autocrop/Box.java b/src/main/java/gred/nucleus/autocrop/Box.java index 9ebef1d2..a94cfb1d 100644 --- a/src/main/java/gred/nucleus/autocrop/Box.java +++ b/src/main/java/gred/nucleus/autocrop/Box.java @@ -2,24 +2,24 @@ /** * Represents the information relative to a Box in the image space (e.g. a bounding box for an object in an image). A - * box is represented by the minimal values (xmin, ymin, zmin) and the maximal values (xmax, ymax, zmax) for each + * box is represented by the minimal values (xMin, yMin, zMin) and the maximal values (xMax, yMax, zMax) for each * coordinate. * * @author Tristan Dubos and Axel Poulet */ public class Box { /** The coordinate x min of the Box */ - private short m_xMin = 0; + private short m_xMin; /** The coordinate x max of the Box */ - private short m_xMax = 0; + private short m_xMax; /** The coordinate y min of the Box */ - private short m_yMin = 0; + private short m_yMin; /** The coordinate y max of the Box */ - private short m_yMax = 0; + private short m_yMax; /** The coordinate z min of the Box */ private short m_zMin; /** The coordinate z max of the Box */ - private short m_zMax = 0; + private short m_zMax; /** * Constructor @@ -41,6 +41,7 @@ public Box(short xMin, short xMax, short yMin, short yMax, short zMin, this.m_zMax = zMax; } + /** * Returns minimal value of the x coordinate in the box * @@ -50,11 +51,13 @@ public short getXMin() { return this.m_xMin; } + /** @param xMin the m_xMin to set */ public void setXMin(short xMin) { this.m_xMin = xMin; } + /** * Returns maximal value of the x coordinate in the box * @@ -64,11 +67,13 @@ public short getXMax() { return this.m_xMax; } + /** @param xMax the m_xMax to set */ public void setXMax(short xMax) { this.m_xMax = xMax; } + /** * Returns minimal value of the y coordinate in the box * @@ -78,11 +83,13 @@ public short getYMin() { return this.m_yMin; } + /** @param yMin the m_yMin to set */ public void setYMin(short yMin) { this.m_yMin = yMin; } + /** * Returns maximal value of the y coordinate in the box * @@ -92,11 +99,13 @@ public short getYMax() { return this.m_yMax; } + /** @param yMax the m_yMax to set */ public void setYMax(short yMax) { this.m_yMax = yMax; } + /** * returns minimal value of the z coordinate in the box * @@ -106,11 +115,13 @@ public short getZMin() { return this.m_zMin; } + /** @param zMin the m_zMin to set */ public void setZMin(short zMin) { this.m_zMin = zMin; } + /** * Returns maximal value of the z coordinate in the box * @@ -120,6 +131,7 @@ public short getZMax() { return this.m_zMax; } + /** @param zMax the m_zMax to set */ public void setZMax(short zMax) { this.m_zMax = zMax; diff --git a/src/main/java/gred/nucleus/autocrop/CropFromCoordinates.java b/src/main/java/gred/nucleus/autocrop/CropFromCoordinates.java index c62edb4c..788a6193 100644 --- a/src/main/java/gred/nucleus/autocrop/CropFromCoordinates.java +++ b/src/main/java/gred/nucleus/autocrop/CropFromCoordinates.java @@ -1,12 +1,9 @@ package gred.nucleus.autocrop; import gred.nucleus.filesInputOutput.FilesNames; -import gred.nucleus.exceptions.fileInOut; -import loci.formats.FormatException; import java.io.File; import java.io.FileNotFoundException; -import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; @@ -21,7 +18,7 @@ public class CropFromCoordinates { * @param linkCoordinateToRawImage tabulate file */ public CropFromCoordinates(String linkCoordinateToRawImage) - throws IOException, Exception { + throws Exception { File coordinateFile = new File(linkCoordinateToRawImage); Scanner scanner = new Scanner(coordinateFile); while (scanner.hasNextLine()) { @@ -35,27 +32,29 @@ public CropFromCoordinates(String linkCoordinateToRawImage) } } - public void runCropFromCoordinate() throws IOException, FormatException, fileInOut, Exception { + + public void runCropFromCoordinate() throws Exception { for (Map.Entry listOfFile : coordinateToRawImage.entrySet()) { - File coordinateFile = new File(listOfFile.getKey()); - File rawImage = new File(listOfFile.getValue()); - AutocropParameters autocropParameters = + File coordinateFile = new File(listOfFile.getKey()); + File rawImage = new File(listOfFile.getValue()); + AutocropParameters autocropParameters = new AutocropParameters(rawImage.getParent(), rawImage.getParent()); - HashMap m_boxes = readCoordinatesTXT(coordinateFile); - FilesNames outPutFilesNames = new FilesNames(listOfFile.getValue()); - String _prefix = outPutFilesNames.PrefixeNameFile(); - AutoCrop autoCrop = new AutoCrop(rawImage, _prefix, autocropParameters, m_boxes); + HashMap m_boxes = readCoordinatesTXT(coordinateFile); + FilesNames outPutFilesNames = new FilesNames(listOfFile.getValue()); + String _prefix = outPutFilesNames.prefixNameFile(); + AutoCrop autoCrop = new AutoCrop(rawImage, _prefix, autocropParameters, m_boxes); autoCrop.cropKernels3(); } } - public HashMap readCoordinatesTXT(File boxeFile) { + + public HashMap readCoordinatesTXT(File boxesFile) { HashMap boxLists = new HashMap<>(); double count = 0; try { - Scanner scanner = new Scanner(boxeFile); + Scanner scanner = new Scanner(boxesFile); while (scanner.hasNextLine()) { String line = scanner.nextLine(); diff --git a/src/main/java/gred/nucleus/autocrop/GenerateOverlay.java b/src/main/java/gred/nucleus/autocrop/GenerateOverlay.java index ade1727c..b402740f 100644 --- a/src/main/java/gred/nucleus/autocrop/GenerateOverlay.java +++ b/src/main/java/gred/nucleus/autocrop/GenerateOverlay.java @@ -6,7 +6,6 @@ import ij.io.FileSaver; import java.io.File; -import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; @@ -15,7 +14,7 @@ public class GenerateOverlay { HashMap linkOverlayProjection = new HashMap<>(); - public GenerateOverlay(String linkOverlayProjection) throws IOException, Exception { + public GenerateOverlay(String linkOverlayProjection) throws Exception { File overlayProjection = new File(linkOverlayProjection); Scanner scanner = new Scanner(overlayProjection); while (scanner.hasNextLine()) { @@ -29,6 +28,7 @@ public GenerateOverlay(String linkOverlayProjection) throws IOException, Excepti } } + /** * Save output file in png format for OMERO * @@ -40,11 +40,11 @@ public static void saveFile(ImagePlus imagePlusInput, String pathFile) { fileSaver.saveAsPng(pathFile); } + public void run() { for (Map.Entry listOfFile : this.linkOverlayProjection.entrySet()) { File zprojectionFile = new File(listOfFile.getValue()); - Directory output = new Directory(zprojectionFile.getParent() + - zprojectionFile.separator + + Directory output = new Directory(zprojectionFile.getParent() + File.separator + "Overlay_Projection_MERGED"); output.CheckAndCreateDir(); ImagePlus overlay = IJ.openImage(listOfFile.getKey()); @@ -55,8 +55,7 @@ public void run() { overlay.show(); Zprojection.show(); IJ.run("Add Image...", overlay + " x=0 y=0 opacity=50"); - saveFile(Zprojection, output.m_dirPath + - zprojectionFile.separator + + saveFile(Zprojection, output.m_dirPath + File.separator + zprojectionFile.getName().substring(0, zprojectionFile.getName().lastIndexOf('.')) + "_MERGED.tiff"); overlay.close(); diff --git a/src/main/java/gred/nucleus/autocrop/annotAutoCrop.java b/src/main/java/gred/nucleus/autocrop/annotAutoCrop.java index bb3062dc..a5197ad5 100644 --- a/src/main/java/gred/nucleus/autocrop/annotAutoCrop.java +++ b/src/main/java/gred/nucleus/autocrop/annotAutoCrop.java @@ -13,10 +13,12 @@ import java.io.File; import java.io.IOException; import java.util.ArrayList; +import java.util.regex.Pattern; /** - * This class create Z projection file of 3D stack (wide field image) and report boxes for each nucleus cropped by the - * Autocrop class. It takes the raw images imput crop and the list of boxes coordinate generate by the Autocrop class. + * This class creates Z projection file of 3D stack (wide field image) and report boxes for each nucleus cropped by the + * Autocrop class. It takes the raw images input crop and the list of boxes coordinates generated by the Autocrop + * class. * * @author Tristan Dubos and Axel Poulet */ @@ -38,16 +40,16 @@ public class annotAutoCrop { /** * Constructor for autocrop * - * @param ListBox : ArrayList of coordinate (coordinate of nuclei cropped) + * @param boxesCoordinates : ArrayList of coordinates (coordinates of nuclei cropped) * @param imageFile : File of current image analysed * @param outputDirPath : path to the output folder * @param autocropParameters : autocrop parameters used to crop nuclei * @param prefix : name of raw image (use for z projection) * - * @throws IOException - * @throws FormatException + * @throws IOException : if imageFile cannot be opened + * @throws FormatException : if something goes wrong performing a file format operation */ - public annotAutoCrop(ArrayList ListBox, + public annotAutoCrop(ArrayList boxesCoordinates, File imageFile, String outputDirPath, String prefix, @@ -55,46 +57,38 @@ public annotAutoCrop(ArrayList ListBox, throws IOException, FormatException { this.m_autocropParameters = autocropParameters; this.m_currentFile = imageFile; - this.m_zProjection = BF.openImagePlus( - imageFile.getAbsolutePath())[ - this.m_autocropParameters.getSlicesOTSUcomputing()]; - this.m_boxCoordinates = ListBox; + this.m_zProjection = + BF.openImagePlus(imageFile.getAbsolutePath())[this.m_autocropParameters.getSlicesOTSUComputing()]; + this.m_boxCoordinates = boxesCoordinates; this.m_outputFilesPrefix = prefix; this.m_outputDirPath = outputDirPath; - Directory dirOutput = new Directory( - this.m_outputDirPath + "zprojection"); + Directory dirOutput = new Directory(this.m_outputDirPath + "zprojection"); dirOutput.CheckAndCreateDir(); - - } + /** - * Constructor for re-generate projection after segmentatio + * Constructor for re-generate projection after segmentation * - * @param ListBox : ArrayList of coordinate (coordinate of nuclei cropped) + * @param boxesCoordinates : ArrayList of coordinates (coordinates of nuclei cropped) * @param imageFile : File of current image analysed * @param outputDirPath : path to the output folder * @param autocropParameters : autocrop parameters used to crop nuclei * - * @throws IOException - * @throws FormatException + * @throws IOException : if imageFile cannot be opened + * @throws FormatException : if something goes wrong performing a file format operation */ - public annotAutoCrop(ArrayList ListBox, + public annotAutoCrop(ArrayList boxesCoordinates, File imageFile, String outputDirPath, AutocropParameters autocropParameters) throws IOException, FormatException { this.m_autocropParameters = autocropParameters; this.m_currentFile = imageFile; - this.m_zProjection = BF.openImagePlus( - imageFile.getAbsolutePath())[ - this.m_autocropParameters.getSlicesOTSUcomputing()]; - this.m_boxCoordinates = ListBox; - - + this.m_zProjection = + BF.openImagePlus(imageFile.getAbsolutePath())[this.m_autocropParameters.getSlicesOTSUComputing()]; + this.m_boxCoordinates = boxesCoordinates; this.m_outputDirPath = outputDirPath; - - } @@ -109,14 +103,12 @@ public void runAddBadCrop(ArrayList _box) { for (String m_boxCoordinate : this.m_boxCoordinates) { String[] splitLine = m_boxCoordinate.split("\\t"); - String[] fileName = splitLine[0].split("\\/"); + String[] fileName = splitLine[0].split(Pattern.quote(File.separator)); String[] Name = fileName[fileName.length - 1].split("_"); addBadCropBoxToZProjection(m_boxCoordinate, Integer.parseInt(Name[Name.length - 2])); } - String outFileZbox = this.m_outputDirPath + "_BAD_CROP_LESS.tif"; - saveFile(this.m_zProjection, outFileZbox); - - + String outFileZBox = this.m_outputDirPath + "_BAD_CROP_LESS.tif"; + saveFile(this.m_zProjection, outFileZBox); } @@ -130,31 +122,24 @@ public void run() { adjustContrast(0.3); for (String m_boxCoordinate : this.m_boxCoordinates) { String[] splitLine = m_boxCoordinate.split("\\t"); - String[] fileName = splitLine[0].split("\\/"); + String[] fileName = splitLine[0].split(Pattern.quote(File.separator)); String[] Name = fileName[fileName.length - 1].split("_"); System.out.println("le truc qui merde " + - m_boxCoordinate + - "\n" + - splitLine[0] + - "\n" + + m_boxCoordinate + "\n" + + splitLine[0] + "\n" + Integer.parseInt(Name[Name.length - 2])); addBoxCropToZProjection(m_boxCoordinate, Integer.parseInt(Name[Name.length - 2])); } - String outFileZbox = this.m_outputDirPath + - this.m_currentFile.separator + - "zprojection" + - this.m_currentFile.separator + - m_outputFilesPrefix + - "_Zprojection.tif"; - System.out.println("outFileZbox " + outFileZbox); - - saveFile(this.m_zProjection, outFileZbox); - - + String outFileZBox = this.m_outputDirPath + File.separator + + "zprojection" + File.separator + + m_outputFilesPrefix + "_Zprojection.tif"; + System.out.println("outFileZBox " + outFileZBox); + saveFile(this.m_zProjection, outFileZBox); } + /** - * Save the ImagePlus Zprojection image + * Save the ImagePlus Z-projection image * * @param imagePlusInput image to save * @param pathFile path to save the image @@ -164,6 +149,7 @@ public void saveFile(ImagePlus imagePlusInput, String pathFile) { fileSaver.saveAsTiff(pathFile); } + /** * Method to project 3D stack to 2D images using Max method projection. * @@ -177,6 +163,7 @@ private ImagePlus projectionMax(ZProjector project) { return project.getProjection(); } + /** * Draw box from coordinate in the Z projection image and add the crop number. * @@ -202,11 +189,10 @@ private void addBoxCropToZProjection(String coordinateList, int boxNumber) { /* Calculation of the coordinate to add nuclei Number */ int xBorder = Integer.parseInt(currentBox[1]) - 100; - int yBorder = Integer.parseInt(currentBox[3]) + (( - Integer.parseInt(currentBox[4]) - - Integer.parseInt(currentBox[3])) / 2) - - 20; - if (xBorder <= 40) { // When the box is in left border the number need + int yBorder = Integer.parseInt(currentBox[3]) + + ((Integer.parseInt(currentBox[4]) - Integer.parseInt(currentBox[3])) / 2) - 20; + // When the box is in left border the number need + if (xBorder <= 40) { // to be write on the right of the box xBorder = Integer.parseInt(currentBox[2]) + 60; } @@ -218,7 +204,6 @@ private void addBoxCropToZProjection(String coordinateList, int boxNumber) { this.m_zProjection.setRoi(left); /* Draw the nucleus number aside the box */ IJ.run(this.m_zProjection, "Draw", "stack"); - } @@ -247,7 +232,8 @@ private void addBadCropBoxToZProjection(String coordinateList, int boxNumber) { int xBorder = Integer.parseInt(currentBox[1]) - 100; int yBorder = Integer.parseInt(currentBox[3]) + ((Integer.parseInt(currentBox[4]) - Integer.parseInt(currentBox[3])) / 2) - 20; - if (xBorder <= 40) { // When the box is in left border the number need + // When the box is in left border the number need + if (xBorder <= 40) { // to be write on the right of the box xBorder = Integer.parseInt(currentBox[2]) + 60; } @@ -261,19 +247,16 @@ private void addBadCropBoxToZProjection(String coordinateList, int boxNumber) { this.m_zProjection.setRoi(left); /* Draw the nucleus number aside the box */ IJ.run(this.m_zProjection, "Draw", "stack"); - } + /** * Method to Contrast the images values and invert the LUT. * * @param contrast : double number for contrast */ private void adjustContrast(double contrast) { - IJ.run(this.m_zProjection, - "Enhance Contrast...", - "saturated=" + contrast); - IJ.run(this.m_zProjection, - "Invert LUT", ""); + IJ.run(this.m_zProjection, "Enhance Contrast...", "saturated=" + contrast); + IJ.run(this.m_zProjection, "Invert LUT", ""); } } diff --git a/src/main/java/gred/nucleus/autocrop/generateProjectionFromCoordinates.java b/src/main/java/gred/nucleus/autocrop/generateProjectionFromCoordinates.java index 640445c6..6a7aabd6 100644 --- a/src/main/java/gred/nucleus/autocrop/generateProjectionFromCoordinates.java +++ b/src/main/java/gred/nucleus/autocrop/generateProjectionFromCoordinates.java @@ -6,6 +6,7 @@ import java.io.File; import java.io.FileNotFoundException; import java.util.*; +import java.util.regex.Pattern; public class generateProjectionFromCoordinates { @@ -28,6 +29,7 @@ public generateProjectionFromCoordinates(String pathToCoordinates, String pathTo this.m_pathToCoordinates = pathToCoordinates; } + /** * Constructor * @@ -40,42 +42,44 @@ public generateProjectionFromCoordinates(String pathToCoordinates, String pathTo this.m_pathToRaw = pathToRaw; } + /** * Compute list of boxes from coordinates file. * - * @param boxeFile coordinate file + * @param boxFile coordinates file * * @return list of boxes file to draw in red */ - public static HashMap readCoordinnateTXT(File boxeFile) { + public static HashMap readCoordinatesTXT(File boxFile) { HashMap boxLists = new HashMap<>(); try { - Scanner scanner = new Scanner(boxeFile); + Scanner scanner = new Scanner(boxFile); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if ((!(line.matches("^#.*"))) && (!(line.matches("^FileName.*")))) { String[] splitLine = line.split("\\t"); - String[] fileName = splitLine[0].split("\\/"); + String[] fileName = splitLine[0].split(Pattern.quote(File.separator)); int xMax = Integer.parseInt(splitLine[3]) + Integer.parseInt(splitLine[6]); int yMax = Integer.parseInt(splitLine[4]) + Integer.parseInt(splitLine[7]); int zMax = Integer.parseInt(splitLine[5]) + Integer.parseInt(splitLine[8]); - boxLists.put(fileName[fileName.length - 1], splitLine[0] - + "\t" + splitLine[3] - + "\t" + xMax - + "\t" + splitLine[4] - + "\t" + yMax - + "\t" + splitLine[5] - + "\t" + zMax); - System.out.println("EUUU" + fileName[fileName.length - 1] + "value" + splitLine[0] - + "\t" + splitLine[3] - + "\t" + xMax - + "\t" + splitLine[4] - + "\t" + yMax - + "\t" + splitLine[5] - + "\t" + zMax); + boxLists.put(fileName[fileName.length - 1], splitLine[0] + "\t" + + splitLine[3] + "\t" + + xMax + "\t" + + splitLine[4] + "\t" + + yMax + "\t" + + splitLine[5] + "\t" + + zMax); + System.out.println("EUUU" + fileName[fileName.length - 1] + "value" + + splitLine[0] + "\t" + + splitLine[3] + "\t" + + xMax +"\t" + + splitLine[4] + "\t" + + yMax + "\t" + + splitLine[5] + "\t" + + zMax); } } } catch (FileNotFoundException e) { @@ -84,6 +88,7 @@ public static HashMap readCoordinnateTXT(File boxeFile) { return boxLists; } + /** * Run new annotation of Zprojection, color in red nuclei which were filtered (in case of GIFT wrapping color in red * nuclei which not pass the segmentation most of case Z truncated ) @@ -91,9 +96,9 @@ public static HashMap readCoordinnateTXT(File boxeFile) { * @throws Exception */ public void generateCoordinateFiltered() throws Exception { - Directory GIFTsegImages = new Directory(this.m_pathToGIFTSeg); - GIFTsegImages.listImageFiles(this.m_pathToGIFTSeg); - GIFTsegImages.checkIfEmpty(); + Directory GIFTSegImages = new Directory(this.m_pathToGIFTSeg); + GIFTSegImages.listImageFiles(this.m_pathToGIFTSeg); + GIFTSegImages.checkIfEmpty(); Directory Zprojection = new Directory(this.m_pathToZprojection); Zprojection.listImageFiles(this.m_pathToZprojection); Zprojection.checkIfEmpty(); @@ -102,12 +107,12 @@ public void generateCoordinateFiltered() throws Exception { Coordinates.checkIfEmpty(); for (short i = 0; i < Coordinates.getNumberFiles(); ++i) { File coordinateFile = Coordinates.getFile(i); - HashMap listOfBoxes = readCoordinnateTXT(coordinateFile); + HashMap listOfBoxes = readCoordinatesTXT(coordinateFile); ArrayList boxNumber = new ArrayList<>(); ArrayList boxListsNucleiNotPass = new ArrayList<>(); Map sortedMap = new TreeMap<>(listOfBoxes); for (HashMap.Entry entry : sortedMap.entrySet()) { - if (!(GIFTsegImages.checkIfFileExists(entry.getKey()))) { + if (!(GIFTSegImages.checkIfFileExists(entry.getKey()))) { boxListsNucleiNotPass.add(entry.getValue()); System.out.println("add " + entry.getValue()); } @@ -134,9 +139,9 @@ public void generateCoordinateFiltered() throws Exception { autocropParameters); annotAutoCrop.runAddBadCrop(boxNumber); } - } + public void generateCoordinate() throws Exception { Directory RawImage = new Directory(this.m_pathToRaw); RawImage.listImageFiles(this.m_pathToRaw); @@ -147,23 +152,21 @@ public void generateCoordinate() throws Exception { for (short i = 0; i < Coordinates.getNumberFiles(); ++i) { File coordinateFile = Coordinates.getFile(i); - HashMap listOfBoxes = readCoordinnateTXT(coordinateFile); + HashMap listOfBoxes = readCoordinatesTXT(coordinateFile); ArrayList boxNumber = new ArrayList<>(); ArrayList boxListsNucleiNotPass = new ArrayList<>(); - Map sortedMap = new TreeMap<>(listOfBoxes); for (HashMap.Entry entry : listOfBoxes.entrySet()) { boxListsNucleiNotPass.add(entry.getValue()); } System.out.println(coordinateFile.getName()); - File CurrentRaw = RawImage.searchFileNameWithoutExtension(coordinateFile.getName() - .substring(0, - coordinateFile - .getName() - .lastIndexOf( - '.'))); + File CurrentRaw = RawImage.searchFileNameWithoutExtension(coordinateFile.getName() + .substring(0, + coordinateFile.getName() + .lastIndexOf( + '.'))); FilesNames outPutFilesNames = new FilesNames(CurrentRaw.toString()); - String prefix = outPutFilesNames.PrefixeNameFile(); + String prefix = outPutFilesNames.prefixNameFile(); System.out.println("current raw " + CurrentRaw.getName()); AutocropParameters autocropParameters = new AutocropParameters(CurrentRaw.getParent(), CurrentRaw.getParent() + @@ -175,7 +178,6 @@ public void generateCoordinate() throws Exception { autocropParameters); annotAutoCrop.run(); } - } } diff --git a/src/main/java/gred/nucleus/autocrop/rectangleIntersection.java b/src/main/java/gred/nucleus/autocrop/rectangleIntersection.java index ac3eec0d..41fa5b2c 100644 --- a/src/main/java/gred/nucleus/autocrop/rectangleIntersection.java +++ b/src/main/java/gred/nucleus/autocrop/rectangleIntersection.java @@ -6,28 +6,23 @@ import java.util.HashMap; import java.util.Map; -/* - * This class is use to filter autocrop boxes intersecting in 2D. - * This process is a default option used in autocrop : - * - * Parameter : boolean boxesRegroupement - * - * Here we regroup boxes with a certain percentage of surface - * intersection : - * if SurfaceA intersect SurfaceB >50% && SurfaceB intersect SurfaceA >50% - * You can defined the percent of surface intersection parameter - * in Aurocrop parameters : - * - * Parameter : int boxesPercentSurfaceToFilter - * - * - * */ +/** + * This class is use to filter autocrop boxes intersecting in 2D. This process is a default option used in autocrop : + *

+ * Parameter : boolean boxesRegrouping + *

+ * Here we regroup boxes with a certain percentage of surface intersection : if SurfaceA intersect SurfaceB >50% && + * SurfaceB intersect SurfaceA >50% You can defined the percent of surface intersection parameter in Autocrop parameters + * : + *

+ * Parameter : int boxesPercentSurfaceToFilter + **/ public class rectangleIntersection { - /** List of boxes Rectangle : xmin , ymin , width , height */ + /** List of boxes Rectangle : xMin , yMin , width , height */ ArrayList listRectangle = new ArrayList<>(); /** Slice coordinate associated to the rectangles(boxes) */ ArrayList zSlices = new ArrayList<>(); @@ -36,7 +31,7 @@ public class rectangleIntersection { /** Number of intersections per rectangles */ HashMap countIntersect = new HashMap<>(); /** Final list of rectangles after re rectangle computations */ - ArrayList finalListRectange = new ArrayList<>(); + ArrayList finalListRectangle = new ArrayList<>(); /** Boolean to check if new rectangles are computed */ boolean newBoxesAdded = false; /** Autocrop parameter */ @@ -44,7 +39,7 @@ public class rectangleIntersection { /** * Constructor getting list of boxes computed in autocrop class. Initialisation of a list of 2D rectangles and a - * list of Z stack associated (Zmin-Zmax). + * list of Z stack associated (zMin-zMax). * * @param _boxes : list of boxes * @param m_autocropParameters : autocrop parameters @@ -62,6 +57,7 @@ public rectangleIntersection(HashMap _boxes, AutocropParameters m_a } } + /** * Compute the percentage of surface intersecting between r1 and r2. * @@ -70,7 +66,7 @@ public rectangleIntersection(HashMap _boxes, AutocropParameters m_a * * @return percent of overlap of r1 */ - public static double perceOf2Rect(Rectangle2D r1, Rectangle2D r2) { + public static double percentOf2Rectangles(Rectangle2D r1, Rectangle2D r2) { Rectangle2D r = new Rectangle2D.Double(); Rectangle2D.intersect(r1, r2, r); double fr1 = r1.getWidth() * r1.getHeight(); // area of "r1" @@ -78,6 +74,7 @@ public static double perceOf2Rect(Rectangle2D r1, Rectangle2D r2) { return (fr1 == 0 || f <= 0) ? 0 : (f / fr1) * 100; // overlap percentage } + /** * Class to run the boxes merge process : Step 1 : detecting boxes intersections Step 2 : group rectangle * intersecting Step 3 : compile new rectangle @@ -88,12 +85,12 @@ public void runRectangleRecompilation() { while (this.newBoxesAdded) { tours++; computeIntersection(); - rectangleRegroupement(); + rectangleRegroup(); recompileRectangle(); } - } + /** Regroup list of rectangles intersecting */ public void computeIntersection() { this.rectangleIntersect.clear(); @@ -107,9 +104,9 @@ public void computeIntersection() { if (listRectangle.get(i).intersects(this.listRectangle.get(y))) { - if (perceOf2Rect(this.listRectangle.get(i), this.listRectangle.get(y)) > + if (percentOf2Rectangles(this.listRectangle.get(i), this.listRectangle.get(y)) > autocropParameters.getBoxesPercentSurfaceToFilter() || - perceOf2Rect(this.listRectangle.get(y), this.listRectangle.get(i)) > + percentOf2Rectangles(this.listRectangle.get(y), this.listRectangle.get(i)) > autocropParameters.getBoxesPercentSurfaceToFilter()) { this.rectangleIntersect.add(i + "-" + y); @@ -126,85 +123,71 @@ public void computeIntersection() { } } + /** Regroup of rectangle intersecting recursively */ - public void rectangleRegroupement() { - this.finalListRectange.clear(); + public void rectangleRegroup() { + this.finalListRectangle.clear(); for (Map.Entry entry : this.countIntersect.entrySet()) { - String listRectangleConnected = "" + entry.getKey(); - String listRectangleConnectedStartTurn = "" + entry.getKey(); + StringBuilder listRectangleConnected = new StringBuilder("" + entry.getKey()); + String listRectangleConnectedStartTurn = "" + entry.getKey(); for (int i = 0; i < this.rectangleIntersect.size(); i++) { String[] splitIntersect = this.rectangleIntersect.get(i).split("-"); if (splitIntersect[0].equals(Integer.toString(entry.getKey()))) { - String[] splitlist = this.rectangleIntersect.get(i).split("-"); - listRectangleConnected = listRectangleConnected + "-" + splitlist[splitlist.length - 1]; + String[] splitList = this.rectangleIntersect.get(i).split("-"); + listRectangleConnected.append("-").append(splitList[splitList.length - 1]); this.rectangleIntersect.remove(i); - this.rectangleIntersect.remove(this.rectangleIntersect.indexOf(splitlist[splitlist.length - 1] + - "-" + - entry.getKey())); - ArrayList listAParcourir = new ArrayList<>(); - listAParcourir.add(splitlist[splitlist.length - 1]); - while (listAParcourir.size() > 0) { + this.rectangleIntersect.remove(splitList[splitList.length - 1] + "-" + entry.getKey()); + ArrayList listToIterateThrough = new ArrayList<>(); + listToIterateThrough.add(splitList[splitList.length - 1]); + while (listToIterateThrough.size() > 0) { for (int y = 0; y < this.rectangleIntersect.size(); y++) { String[] splitIntersect2 = this.rectangleIntersect.get(y).split("-"); - if (splitIntersect2[0].equals(listAParcourir.get(0))) { - String[] splitlist2 = this.rectangleIntersect.get(y).split("-"); - listAParcourir.add(splitlist2[splitlist.length - 1]); - listRectangleConnected = - listRectangleConnected + "-" + splitlist2[splitlist.length - 1]; - String[] splitCurrentRectangleConnected = listRectangleConnected.split("-"); + if (splitIntersect2[0].equals(listToIterateThrough.get(0))) { + String[] splitList2 = this.rectangleIntersect.get(y).split("-"); + listToIterateThrough.add(splitList2[splitList.length - 1]); + listRectangleConnected.append("-").append(splitList2[splitList.length - 1]); + String[] splitCurrentRectangleConnected = listRectangleConnected.toString().split("-"); this.rectangleIntersect.remove(y); - this.rectangleIntersect.remove(this.rectangleIntersect.indexOf(splitlist2[splitlist.length - - 1] + - "-" + - listAParcourir.get(0))); + this.rectangleIntersect.remove(splitList2[splitList.length - 1] + + "-" + + listToIterateThrough.get(0)); for (String s : splitCurrentRectangleConnected) { - if (this.rectangleIntersect.contains(splitlist2[splitlist.length - 1] + "-" + s)) { - this.rectangleIntersect.remove(this.rectangleIntersect.indexOf(splitlist2[ - splitlist.length - - 1] + - "-" + - s)); - } - if (this.rectangleIntersect.contains(s + "-" + splitlist2[splitlist.length - 1])) { - this.rectangleIntersect.remove(this.rectangleIntersect.indexOf(s + - "-" + - splitlist2[ - splitlist.length - - 1])); - } + this.rectangleIntersect.remove(splitList2[splitList.length - 1] + "-" + s); + this.rectangleIntersect.remove(s + "-" + splitList2[splitList.length - 1]); } y = 0; } } - listAParcourir.remove(0); + listToIterateThrough.remove(0); } } - if (!(listRectangleConnected.equals(listRectangleConnectedStartTurn))) { + if (!(listRectangleConnected.toString().equals(listRectangleConnectedStartTurn))) { i--; - listRectangleConnectedStartTurn = listRectangleConnected; + listRectangleConnectedStartTurn = listRectangleConnected.toString(); } } - this.finalListRectange.add(listRectangleConnected); + this.finalListRectangle.add(listRectangleConnected.toString()); } } + /** Compile of new rectangle by getting extreme coordinate of a group of rectangles. */ public void recompileRectangle() { this.newBoxesAdded = false; ArrayList listOfRectangleToAdd = new ArrayList<>(); ArrayList listOfRectangleZSliceToAdd = new ArrayList<>(); ArrayList listOfRectangleToRemove = new ArrayList<>(); - for (String value : this.finalListRectange) { - String[] splitlist2 = value.split("-"); + for (String value : this.finalListRectangle) { + String[] splitList2 = value.split("-"); double xMixNewRectangle = 0; double yMinNewRectangle = 0; double maxWidth = 0; double maxHeight = 0; int minZSlice = 0; int maxZSlice = 0; - if (splitlist2.length > 1) { - for (String s : splitlist2) { + if (splitList2.length > 1) { + for (String s : splitList2) { int tmp = Integer.parseInt(s); if ((this.listRectangle.get(tmp).getX() < xMixNewRectangle) || (xMixNewRectangle == 0)) { xMixNewRectangle = this.listRectangle.get(tmp).getX(); @@ -235,8 +218,8 @@ public void recompileRectangle() { (int) this.listRectangle.get(tmp).getHeight())); } - maxZSlice = (int) maxZSlice - (int) minZSlice; - listOfRectangleZSliceToAdd.add((int) minZSlice + "-" + (int) maxZSlice); + maxZSlice = maxZSlice - minZSlice; + listOfRectangleZSliceToAdd.add(minZSlice + "-" + maxZSlice); maxWidth = (int) maxWidth - (int) xMixNewRectangle; maxHeight = (int) maxHeight - (int) yMinNewRectangle; listOfRectangleToAdd.add(new Rectangle((int) xMixNewRectangle, @@ -257,9 +240,9 @@ public void recompileRectangle() { listRectangle.remove(indexRectangleRemove); zSlices.remove(indexRectangleRemove); } - } + /** * Computing the list of the new rectangles using boxes coordinates format. * @@ -271,22 +254,20 @@ public HashMap getNewBoxes() { for (int i = 0; i < listRectangle.size(); i++) { String[] zSliceTMP = this.zSlices.get(i).split("-"); - Integer.valueOf(zSliceTMP[0]); - short tmpXmax = (short) (this.listRectangle.get(i).getX() + this.listRectangle.get(i).getWidth()); - short tmpYmax = (short) (this.listRectangle.get(i).getY() + this.listRectangle.get(i).getHeight()); - short tmpZmax = (short) (Short.parseShort(zSliceTMP[0]) + Short.parseShort(zSliceTMP[1])); - if (tmpZmax == 0) { - tmpZmax = 1; + short tmpXMax = (short) (this.listRectangle.get(i).getX() + this.listRectangle.get(i).getWidth()); + short tmpYMax = (short) (this.listRectangle.get(i).getY() + this.listRectangle.get(i).getHeight()); + short tmpZMax = (short) (Short.parseShort(zSliceTMP[0]) + Short.parseShort(zSliceTMP[1])); + if (tmpZMax == 0) { + tmpZMax = 1; } Box box = new Box((short) (this.listRectangle.get(i).getX()), - tmpXmax, + tmpXMax, (short) (this.listRectangle.get(i).getY()), - tmpYmax, + tmpYMax, Short.parseShort(zSliceTMP[0]), - tmpZmax); + tmpZMax); boxes.put((double) i, box); } return boxes; } - } diff --git a/src/main/java/gred/nucleus/cli/CLIActionOptionCmdLine.java b/src/main/java/gred/nucleus/cli/CLIActionOptionCmdLine.java index d8e6cab4..0c391b51 100644 --- a/src/main/java/gred/nucleus/cli/CLIActionOptionCmdLine.java +++ b/src/main/java/gred/nucleus/cli/CLIActionOptionCmdLine.java @@ -35,14 +35,13 @@ public class CLIActionOptionCmdLine extends CLIActionOptions { /** * @param args command line argument * - * @throws Exception ParseException */ - public CLIActionOptionCmdLine(String[] args) throws Exception { + public CLIActionOptionCmdLine(String[] args) { super(args); this.m_action.setDescription(this.m_action.getDescription() + "\n" + - "computeParameters : compute paramaters \n" + + "computeParameters : compute parameters \n" + "computeParametersDL : compute parameters for machine leaning\n" + - "generateProjection : generate projection from coodinates\n" + + "generateProjection : generate projection from coordinates\n" + "CropFromCoordinate : crop wide-field image from coordinate\n" + "GenerateOverlay : generate overlay from images \n"); @@ -53,15 +52,16 @@ public CLIActionOptionCmdLine(String[] args) throws Exception { } catch (ParseException exp) { System.out.println(exp.getMessage() + "\n"); - System.out.println(getHelperInfos()); + System.out.println(getHelperInfo()); System.exit(1); } catch (Exception exp) { System.out.println("Action option \"" + this.m_cmd.getOptionValue("action") + "\" not available" + "\n"); - System.out.println(getHelperInfos()); + System.out.println(getHelperInfo()); System.exit(1); } } + /** * Method to check action parameter * @@ -82,6 +82,7 @@ private static boolean CMDAvailableAction(String action) { return actionAvailableInOmero.contains(action); } + /** Method to check specific action parameters */ private void checkSpecificOptions() { switch (this.m_cmd.getOptionValue("action")) { @@ -135,5 +136,4 @@ private void checkSpecificOptions() { break; } } - } \ No newline at end of file diff --git a/src/main/java/gred/nucleus/cli/CLIActionOptionOMERO.java b/src/main/java/gred/nucleus/cli/CLIActionOptionOMERO.java index 0224e63b..08ae4f39 100644 --- a/src/main/java/gred/nucleus/cli/CLIActionOptionOMERO.java +++ b/src/main/java/gred/nucleus/cli/CLIActionOptionOMERO.java @@ -9,14 +9,14 @@ import static org.apache.commons.lang.Validate.isTrue; -/** Herited class to handle OMERO command line option */ +/** Inherited class to handle OMERO command line option */ public class CLIActionOptionOMERO extends CLIActionOptions { /** Host name server */ private final Option m_hostname = Option.builder("ho") .longOpt("hostname") .required() .type(String.class) - .desc("Hostname of the OMERO serveur") + .desc("Hostname of the OMERO server") .numberOfArgs(1) .build(); /** Server port connexion */ @@ -62,9 +62,8 @@ public class CLIActionOptionOMERO extends CLIActionOptions { * * @param argument : list of command line argument * - * @throws Exception ParseException */ - public CLIActionOptionOMERO(String[] argument) throws Exception { + public CLIActionOptionOMERO(String[] argument) { super(argument); this.m_options.addOption(this.m_action); this.m_options.addOption(this.m_outputFolder); @@ -77,7 +76,7 @@ public CLIActionOptionOMERO(String[] argument) throws Exception { "OMERO inputs 2 information separated with slash separator : " + "Type input: dataset, project, image, tag " + "Input id number" + "\n" + - "Exemple : " + "\n" + + "Example : " + "\n" + " dataset/1622"); try { this.m_cmd = this.m_parser.parse(this.m_options, argument); @@ -85,19 +84,18 @@ public CLIActionOptionOMERO(String[] argument) throws Exception { } catch (ParseException exp) { System.out.println(exp.getMessage() + "\n"); - System.out.println(getHelperInfos()); + System.out.println(getHelperInfo()); System.exit(1); } catch (Exception exp) { System.out.println("Action option \"" + this.m_cmd.getOptionValue("action") + "\" not available" + "\n"); - System.out.println(getHelperInfos()); + System.out.println(getHelperInfo()); System.exit(1); } - - } + /** * Method to check action parameter * @@ -112,30 +110,35 @@ private static boolean OMEROAvailableAction(String action) { return actionAvailableInOmero.contains(action); } + private Option getGroup() { return this.m_group; } + private Option getHostname() { return this.m_hostname; } + private Option getPort() { return this.m_port; } + private Option getUsername() { return this.m_username; } + private Option getPassword() { return this.m_password; } + private Option getOutputFolder() { return this.m_outputFolder; } - } // if(cmd.getOptionValue("action").equals("autocrop")) { diff --git a/src/main/java/gred/nucleus/cli/CLIActionOptions.java b/src/main/java/gred/nucleus/cli/CLIActionOptions.java index 34c7cad8..5e17164b 100644 --- a/src/main/java/gred/nucleus/cli/CLIActionOptions.java +++ b/src/main/java/gred/nucleus/cli/CLIActionOptions.java @@ -1,12 +1,13 @@ package gred.nucleus.cli; +import gred.nucleus.mains.Version; import org.apache.commons.cli.*; /** Generic class to handle command line option */ public class CLIActionOptions { /** NucleusJ version */ - private static final String NJversion = "1.2.2"; + private static final String NJ_version = Version.get(); /** Path to input folder */ public Option m_inputFolder = Option.builder("in") .longOpt("input") @@ -21,7 +22,7 @@ public class CLIActionOptions { .desc("Path to config file\n" + "To generate config file example in current folder:\n" + "java -jar NucleusJ_2-" + - NJversion + + NJ_version + ".jar -h configFileExample") .numberOfArgs(1) .build(); @@ -39,7 +40,7 @@ public class CLIActionOptions { public Option m_omero = Option.builder("ome") .longOpt("omero") .type(boolean.class) - .desc("Use of NucleuJ2.0 in OMERO\n") + .desc("Use of NucleusJ2.0 in OMERO\n") .build(); /** List of options */ Options m_options = new Options(); @@ -64,28 +65,30 @@ public CLIActionOptions(String[] argument) { this.m_cmd = this.m_parser.parse(this.m_options, argument, true); } catch (ParseException exp) { System.out.println(exp.getMessage() + "\n"); - System.out.println(getHelperInfos()); + System.out.println(getHelperInfo()); System.exit(1); } } + /** @return : helper info */ - public String getHelperInfos() { + public String getHelperInfo() { return "More details for available actions:\n" + - "java -jar NucleusJ_2-" + NJversion + ".jar -h \n" + - "java -jar NucleusJ_2-" + NJversion + ".jar -help \n\n" + + "java -jar NucleusJ_2-" + NJ_version + ".jar -h \n" + + "java -jar NucleusJ_2-" + NJ_version + ".jar -help \n\n" + "More details for a specific action:\n" + - "java -jar NucleusJ_2-" + NJversion + ".jar -h \n" + - "java -jar NucleusJ_2-" + NJversion + ".jar -help "; + "java -jar NucleusJ_2-" + NJ_version + ".jar -h \n" + + "java -jar NucleusJ_2-" + NJ_version + ".jar -help "; } + /** @return list of options */ public Options getM_options() { return this.m_options; } + public CommandLine getCmd() { return this.m_cmd; } - } \ No newline at end of file diff --git a/src/main/java/gred/nucleus/cli/CLIHelper.java b/src/main/java/gred/nucleus/cli/CLIHelper.java index 975278d2..22008725 100644 --- a/src/main/java/gred/nucleus/cli/CLIHelper.java +++ b/src/main/java/gred/nucleus/cli/CLIHelper.java @@ -2,21 +2,20 @@ import gred.nucleus.filesInputOutput.Directory; import gred.nucleus.filesInputOutput.OutputTextFile; +import gred.nucleus.mains.Version; import org.apache.commons.cli.HelpFormatter; /** Class to generate helper */ public class CLIHelper { - private static final String NJversion = "1.1.0"; /** * Constructor * - * @param args command line arguement + * @param args command line arguments * - * @throws Exception format helper */ - public CLIHelper(String[] args) throws Exception { + public CLIHelper(String[] args) { if (args.length == 2) { specificAction(args[1]); } else { @@ -24,13 +23,13 @@ public CLIHelper(String[] args) throws Exception { } } + /** * Method get help for command line with example command line * - * @throws Exception format helper */ - private static void CmdHelpFull() throws Exception { - String example_command = "java -jar NucleusJ_2-" + NJversion + ".jar "; + private static void CmdHelpFull() { + String example_command = "java -jar NucleusJ_2-" + Version.get() + ".jar "; String example_argument = "-action segmentation " + "-input path/to/input/folder/ " + "-output path/to/output/folder/ "; @@ -45,7 +44,7 @@ private static void CmdHelpFull() throws Exception { "-action segmentation " + "-input path/to/input/folder/ " + "-output path/to/output/folder/ " + - "-hostname omero-server-adress " + + "-hostname omero-server-address " + "-port 0 " + "-group 000"; String[] example_OMEROCmd = example_argument_OMERO.split(" "); @@ -57,15 +56,15 @@ private static void CmdHelpFull() throws Exception { System.exit(1); } + /** * Helper for specific action. * * @param action action * - * @throws Exception format helper */ - private static void specificAction(String action) throws Exception { - String example_command = "java -jar NucleusJ_2-" + NJversion + ".jar "; + private static void specificAction(String action) { + String example_command = "java -jar NucleusJ_2-" + Version.get() + ".jar "; String example_argument; String[] example_Cmd; HelpFormatter formatter; @@ -86,7 +85,7 @@ private static void specificAction(String action) throws Exception { "-action segmentation " + "-input path/to/input/folder/ " + "-output path/to/output/folder/ " + - "-hostname omero-server-adress " + + "-hostname omero-server-address " + "-port 0 " + "-group 000"; @@ -113,7 +112,7 @@ private static void specificAction(String action) throws Exception { "-action autocrop " + "-input path/to/input/folder/ " + "-output path/to/output/folder/ " + - "-hostname omero-server-adress " + + "-hostname omero-server-address " + "-port 0 " + "-group 000"; example_OMEROCmd = example_argument_OMERO.split(" "); @@ -163,7 +162,7 @@ private static void specificAction(String action) throws Exception { example_argument = "-action generateProjectionFiltered " + "-input path/to/coordinate/file/folder/ " + "-input2 path/to/segmented/image/folder/ " + - "-input3 path/to/Zprojection/folder/"; + "-input3 path/to/ZProjection/folder/"; example_Cmd = example_argument.split(" "); command = new CLIActionOptionCmdLine(example_Cmd); formatter = new HelpFormatter(); @@ -201,21 +200,21 @@ private static void specificAction(String action) throws Exception { "zCropBoxSize:20\n" + "minVolumeNucleus:1\n" + "maxVolumeNucleus:2147483647\n" + - "thresholdOSTUcomputing:20\n" + + "thresholdOTSUComputing:20\n" + "channelToComputeThreshold:0\n" + - "slicesOTSUcomputing:0\n" + + "slicesOTSUComputing:0\n" + "boxesPercentSurfaceToFilter:50\n" + - "boxesRegroupement:10\n" + - "xcal:1\n" + - "ycal:1\n" + - "zcal:1"; + "boxesRegrouping:10\n" + + "xCal:1\n" + + "yCal:1\n" + + "zCal:1"; String segConfigOption = - "thresholdOSTUcomputing:20\n" + + "thresholdOTSUComputing:20\n" + "GiftWrapping:true\n" + - "xcal:1\n" + - "ycal:1\n" + - "zcal:1"; + "xCal:1\n" + + "yCal:1\n" + + "zCal:1"; System.out.println("Two config file with default parameters generate: \n"); saveFile(autocropConfigOption, "autocropConfigListParameters"); @@ -233,20 +232,20 @@ private static void specificAction(String action) throws Exception { example_Cmd = example_argument.split(" "); CLIActionOptions wrongAction = new CLIActionOptions(example_Cmd); System.out.println("Invalid action \"" + action + "\" :\n"); - System.out.println(wrongAction.getHelperInfos()); + System.out.println(wrongAction.getHelperInfo()); break; } } + /** * Save information use to save config file parameter example. * * @param text text to save * @param fileName file name * - * @throws Exception file exception */ - public static void saveFile(String text, String fileName) throws Exception { + public static void saveFile(String text, String fileName) { Directory dirOutput = new Directory(System.getProperty("user.dir")); OutputTextFile resultFileOutputOTSU = new OutputTextFile( dirOutput.get_dirPath() diff --git a/src/main/java/gred/nucleus/cli/CLIRunAction.java b/src/main/java/gred/nucleus/cli/CLIRunAction.java index f47ba700..fbca8ae9 100644 --- a/src/main/java/gred/nucleus/cli/CLIRunAction.java +++ b/src/main/java/gred/nucleus/cli/CLIRunAction.java @@ -1,8 +1,8 @@ package gred.nucleus.cli; -import gred.nucleus.machineLeaningUtils.ComputeNucleiParametersML; import gred.nucleus.autocrop.*; import gred.nucleus.core.ComputeNucleiParameters; +import gred.nucleus.machineLeaningUtils.ComputeNucleiParametersML; import gred.nucleus.segmentation.SegmentationCalling; import gred.nucleus.segmentation.SegmentationParameters; import org.apache.commons.cli.CommandLine; @@ -35,21 +35,24 @@ public CLIRunAction(CommandLine cmd) throws Exception { runCropFromCoordinates(); break; case "GenerateOverlay": - runGenereOV(); + runGenerateOV(); break; } } - private void runGenereOV() throws Exception { + + private void runGenerateOV() throws Exception { GenerateOverlay ov = new GenerateOverlay(this.m_cmd.getOptionValue("input")); ov.run(); } + private void runCropFromCoordinates() throws Exception { CropFromCoordinates test = new CropFromCoordinates(this.m_cmd.getOptionValue("input")); test.runCropFromCoordinate(); } + private void runProjectionFromCoordinates() throws Exception { if (this.m_cmd.hasOption("coordinateFiltered")) { generateProjectionFromCoordinates projection = @@ -65,6 +68,7 @@ private void runProjectionFromCoordinates() throws Exception { } } + private void runAutocrop() throws Exception { AutocropParameters autocropParameters = new AutocropParameters( this.m_cmd.getOptionValue("input") @@ -82,6 +86,7 @@ private void runAutocrop() throws Exception { } } + private void runSegmentation() throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(this.m_cmd.getOptionValue("input"), this.m_cmd.getOptionValue("output")); @@ -90,17 +95,17 @@ private void runSegmentation() throws Exception { segmentationParameters.addProperties(this.m_cmd.getOptionValue("config")); } if (this.m_cmd.hasOption("file")) { - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { - String log = otsuModif.runOneImage(this.m_cmd.getOptionValue("input")); + String log = otsuModified.runOneImage(this.m_cmd.getOptionValue("input")); if (!(log.equals(""))) System.out.println("Nuclei which didn't pass the segmentation\n" + log); } catch (IOException e) { e.printStackTrace(); } } else { - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { - String log = otsuModif.runSeveralImages2(); + String log = otsuModified.runSeveralImages2(); if (!(log.equals(""))) System.out.println("Nuclei which didn't pass the segmentation\n" + log); } catch (IOException e) { e.printStackTrace(); @@ -108,17 +113,18 @@ private void runSegmentation() throws Exception { } } - private void runComputeNucleiParameters() throws Exception { + + private void runComputeNucleiParameters() { ComputeNucleiParameters generateParameters = new ComputeNucleiParameters(this.m_cmd.getOptionValue("input"), this.m_cmd.getOptionValue("input2")); if (this.m_cmd.hasOption("config")) generateParameters.addConfigParameters(this.m_cmd.getOptionValue("config")); generateParameters.run(); } + private void runComputeNucleiParametersDL() throws Exception { ComputeNucleiParametersML computeParameters = new ComputeNucleiParametersML(this.m_cmd.getOptionValue("input"), this.m_cmd.getOptionValue("input2")); computeParameters.run(); } - } diff --git a/src/main/java/gred/nucleus/cli/CLIRunActionOMERO.java b/src/main/java/gred/nucleus/cli/CLIRunActionOMERO.java index c03771e5..6c756f78 100644 --- a/src/main/java/gred/nucleus/cli/CLIRunActionOMERO.java +++ b/src/main/java/gred/nucleus/cli/CLIRunActionOMERO.java @@ -12,8 +12,10 @@ import org.apache.commons.cli.Options; import java.io.Console; +import java.io.File; import java.io.IOException; import java.util.List; +import java.util.regex.Pattern; public class CLIRunActionOMERO { /** List of options */ @@ -45,11 +47,12 @@ public CLIRunActionOMERO(CommandLine cmd) throws Exception { this.m_client.disconnect(); } + public static void autoCropOmero(String inputDirectory, String outputDirectory, Client client, AutoCropCalling autoCrop) throws Exception { - String[] param = inputDirectory.split("/"); + String[] param = inputDirectory.split(Pattern.quote(File.separator)); if (param.length >= 2) { Long id = Long.parseLong(param[1]); @@ -68,7 +71,7 @@ public static void autoCropOmero(String inputDirectory, autoCrop.runImageOmero(image, outputsDat, client); } else { - List images = null; + List images; String name = ""; @@ -103,11 +106,12 @@ public static void autoCropOmero(String inputDirectory, } else { throw new IllegalArgumentException("Wrong input parameter : " + inputDirectory + "\n\n\n" - + "Exemple format expected:\n" + + "Example format expected:\n" + "dataset/OMERO_ID \n"); } } + public void getOMEROPassword() { if (this.m_cmd.hasOption("password")) { this.m_mdp = this.m_cmd.getOptionValue("password"); @@ -116,9 +120,9 @@ public void getOMEROPassword() { Console con = System.console(); this.m_mdp = String.valueOf(con.readPassword()); } - } + public void checkOMEROConnexion() { try { m_client.connect(this.m_cmd.getOptionValue("hostname"), @@ -133,6 +137,7 @@ public void checkOMEROConnexion() { } } + public void runAutoCropOmero() throws Exception { AutocropParameters autocropParameters = new AutocropParameters(".", "."); if (this.m_cmd.hasOption("config")) { @@ -151,24 +156,26 @@ public void runAutoCropOmero() throws Exception { } } + public void runSegmentationOmero() throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(".", "."); if (this.m_cmd.hasOption("config")) { segmentationParameters.addGeneralProperties(this.m_cmd.getOptionValue("config")); segmentationParameters.addProperties(this.m_cmd.getOptionValue("config")); } - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); segmentationOmero(this.m_cmd.getOptionValue("input"), this.m_cmd.getOptionValue("output"), this.m_client, - otsuModif); + otsuModified); } + public void segmentationOmero(String inputDirectory, String outputDirectory, Client client, - SegmentationCalling otsuModif) throws Exception { - String[] param = inputDirectory.split("/"); + SegmentationCalling otsuModified) throws Exception { + String[] param = inputDirectory.split(Pattern.quote(File.separator)); if (param.length >= 2) { Long id = Long.parseLong(param[1]); @@ -178,9 +185,9 @@ public void segmentationOmero(String inputDirectory, try { String log; if (param.length == 3 && param[2].equals("ROI")) { - log = otsuModif.runOneImageOmeroROI(image, Long.parseLong(outputDirectory), client); + log = otsuModified.runOneImageOmeroROI(image, Long.parseLong(outputDirectory), client); } else { - log = otsuModif.runOneImageOmero(image, Long.parseLong(outputDirectory), client); + log = otsuModified.runOneImageOmero(image, Long.parseLong(outputDirectory), client); } if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); @@ -189,7 +196,7 @@ public void segmentationOmero(String inputDirectory, e.printStackTrace(); } } else { - List images = null; + List images; switch (param[0]) { case "dataset": @@ -220,9 +227,9 @@ public void segmentationOmero(String inputDirectory, String log; if ((param.length == 3 && param[2].equals("ROI")) || (param.length == 5 && param[4].equals("ROI"))) { - log = otsuModif.runSeveralImageOmeroROI(images, Long.parseLong(outputDirectory), client); + log = otsuModified.runSeveralImageOmeroROI(images, Long.parseLong(outputDirectory), client); } else { - log = otsuModif.runSeveralImageOmero(images, Long.parseLong(outputDirectory), client); + log = otsuModified.runSeveralImageOmero(images, Long.parseLong(outputDirectory), client); } if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); @@ -235,5 +242,4 @@ public void segmentationOmero(String inputDirectory, throw new IllegalArgumentException(); } } - } diff --git a/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalBoundary.java b/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalBoundary.java index ad9a0a75..d612f4f4 100644 --- a/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalBoundary.java +++ b/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalBoundary.java @@ -27,5 +27,4 @@ public class ComponentRemovalBoundary implements ComponentRemovalPredicate { public boolean keepVoxelComponent(Voxel voxel, ComponentInfo componentInfo) { return !componentInfo.isOnTheBorder(); } - } diff --git a/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalLinear.java b/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalLinear.java index 2978c754..6a3e496d 100644 --- a/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalLinear.java +++ b/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalLinear.java @@ -14,30 +14,34 @@ /** * This class is intended to implement the predicate on voxels and connected components to keep all components which are - * within a thick plane. The thick plane's equation is: z >= m_x Coeff*x + m_yCoeff*y + m_constantCoeff > z-m_thickness + * within a thick plane. The thick plane's equation is: z >= m_x Coefficient*x + m_yCoefficient*y + m_constantCoefficient > z-m_thickness * * @author Remy Malgouyres, Tristan Dubos and Axel Poulet */ public class ComponentRemovalLinear implements ComponentRemovalPredicate { - private double m_xCoeff; - private double m_yCoeff; - private double m_constantCoeff; + private double m_xCoefficient; + private double m_yCoefficient; + private double m_constantCoefficient; private double m_thickness; /** - * @param xCoeff first coefficient of the plane's equation - * @param yCoeff second coefficient of the plane's equation - * @param constantCoeff third coefficient of the plane's equation - * @param thickness thickness of the plane + * @param xCoefficient first coefficient of the plane's equation + * @param yCoefficient second coefficient of the plane's equation + * @param constantCoefficient third coefficient of the plane's equation + * @param thickness thickness of the plane */ - public ComponentRemovalLinear(double xCoeff, double yCoeff, double constantCoeff, double thickness) { - this.m_xCoeff = xCoeff; - this.m_yCoeff = yCoeff; - this.m_constantCoeff = constantCoeff; + public ComponentRemovalLinear(double xCoefficient, + double yCoefficient, + double constantCoefficient, + double thickness) { + this.m_xCoefficient = xCoefficient; + this.m_yCoefficient = yCoefficient; + this.m_constantCoefficient = constantCoefficient; this.m_thickness = thickness; } + /** * @return true if the voxel is in the thick plane, false otherwise * @@ -45,8 +49,8 @@ public ComponentRemovalLinear(double xCoeff, double yCoeff, double constantCoeff */ @Override public boolean keepVoxelComponent(Voxel voxel, ComponentInfo componentInfo) { - double zValue = this.m_xCoeff * voxel.getX() + this.m_yCoeff * voxel.getY() + this.m_constantCoeff; + double zValue = + this.m_xCoefficient * voxel.getX() + this.m_yCoefficient * voxel.getY() + this.m_constantCoefficient; return ((voxel.getZ() >= zValue) && (voxel.getZ() < zValue + this.m_thickness)); } - } diff --git a/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalLinearComplement.java b/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalLinearComplement.java index feb3e1de..11bdb732 100644 --- a/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalLinearComplement.java +++ b/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalLinearComplement.java @@ -14,37 +14,41 @@ /** * This class is intended to implement the predicate on voxels and connected components to keep all components which are - * outside a thick plane. The thick plane's equation is: z <= m_x Coeff*x + m_yCoeff*y + m_constantCoeff or z > - * m_thickness + m_x Coeff*x + m_yCoeff*y + m_constantCoeff + * outside a thick plane. The thick plane's equation is: z <= m_x Coefficient*x + m_yCoefficient*y + m_constantCoefficient or z > + * m_thickness + m_x Coefficient*x + m_yCoefficient*y + m_constantCoefficient * * @author Remy Malgouyres, Tristan Dubos and Axel Poulet */ public class ComponentRemovalLinearComplement implements ComponentRemovalPredicate { - private double m_xCoeff; - private double m_yCoeff; - private double m_constantCoeff; + private double m_xCoefficient; + private double m_yCoefficient; + private double m_constantCoefficient; private double m_thickness; /** - * @param xCoeff first coefficient of the plane's equation - * @param yCoeff second coefficient of the plane's equation - * @param constantCoeff third coefficient of the plane's equation - * @param thickness thickness of the plane + * @param xCoefficient first coefficient of the plane's equation + * @param yCoefficient second coefficient of the plane's equation + * @param constantCoefficient third coefficient of the plane's equation + * @param thickness thickness of the plane */ - public ComponentRemovalLinearComplement(double xCoeff, double yCoeff, double constantCoeff, double thickness) { - this.m_xCoeff = xCoeff; - this.m_yCoeff = yCoeff; - this.m_constantCoeff = constantCoeff; + public ComponentRemovalLinearComplement(double xCoefficient, + double yCoefficient, + double constantCoefficient, + double thickness) { + this.m_xCoefficient = xCoefficient; + this.m_yCoefficient = yCoefficient; + this.m_constantCoefficient = constantCoefficient; this.m_thickness = thickness; } + /** * */ @Override public boolean keepVoxelComponent(Voxel voxel, ComponentInfo componentInfo) { - double zValue = this.m_xCoeff * voxel.getX() + this.m_yCoeff * voxel.getY() + this.m_constantCoeff; + double zValue = + this.m_xCoefficient * voxel.getX() + this.m_yCoefficient * voxel.getY() + this.m_constantCoefficient; return ((voxel.getZ() < zValue) || (voxel.getZ() >= zValue + this.m_thickness)); } - } diff --git a/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalNone.java b/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalNone.java index 4aa14656..93650dd3 100644 --- a/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalNone.java +++ b/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalNone.java @@ -25,5 +25,4 @@ public class ComponentRemovalNone implements ComponentRemovalPredicate { public boolean keepVoxelComponent(Voxel voxel, ComponentInfo componentInfo) { return true; } - } diff --git a/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalThresholdVolume.java b/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalThresholdVolume.java index 2b11aed6..f0b446e6 100644 --- a/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalThresholdVolume.java +++ b/src/main/java/gred/nucleus/componentRemoval/ComponentRemovalThresholdVolume.java @@ -31,10 +31,10 @@ public ComponentRemovalThresholdVolume(double thresholdComponentVolume, double u this.m_thresholdCardinality = (int) (thresholdComponentVolume / unitVoxelVolume); } + /** @see */ @Override public boolean keepVoxelComponent(Voxel voxel, ComponentInfo componentInfo) { - return (componentInfo.getnumberOfPoints() >= this.m_thresholdCardinality); + return (componentInfo.getNumberOfPoints() >= this.m_thresholdCardinality); } - } diff --git a/src/main/java/gred/nucleus/connectedComponent/ComponentInfo.java b/src/main/java/gred/nucleus/connectedComponent/ComponentInfo.java index 8b0af25a..7bae50cc 100644 --- a/src/main/java/gred/nucleus/connectedComponent/ComponentInfo.java +++ b/src/main/java/gred/nucleus/connectedComponent/ComponentInfo.java @@ -12,7 +12,7 @@ import gred.nucleus.utils.Voxel; /** - * Represents the informations relative to a connected component in a binary image. + * Represents the information relative to a connected component in a binary image. * * @author Remy Malgouyres, Tristan Dubos and Axel Poulet */ @@ -29,7 +29,8 @@ public class ComponentInfo { /** * Voxel representative of the component (one voxel in the component) Currently, this representative has minimal - * depth Z TODO extend usage using a comparison predicate possibly other that comparing depth. + * depth Z + * TODO extend usage using a comparison predicate possibly other that comparing depth. */ private Voxel m_voxelRepresentant; @@ -55,6 +56,7 @@ public ComponentInfo(int label, int numberOfPoints, Voxel voxelRepresentant, boo this.m_componentOnTheBorder = componentOnTheBorder; } + /** * Getter. * @@ -64,6 +66,7 @@ public int getLabel() { return this.m_label; } + /** * Setter for the label of the component * @@ -73,20 +76,23 @@ public void setLabel(int label) { this.m_label = label; } + /** * Getter * * @return the cardinality of the component */ - public int getnumberOfPoints() { + public int getNumberOfPoints() { return this.m_numberOfPoints; } + /** Increments the cardinality */ public void incrementNumberOfPoints() { this.m_numberOfPoints++; } + /** * Setter * @@ -96,6 +102,7 @@ public void setNumberOfPoints(int numberOfPoints) { this.m_numberOfPoints = numberOfPoints; } + /** * Getter * @@ -105,6 +112,7 @@ public boolean isOnTheBorder() { return this.m_componentOnTheBorder; } + /** * Getter * @@ -114,6 +122,7 @@ public Voxel getRepresentant() { return this.m_voxelRepresentant; } + /** Sets to true the flag indicating whether the component is on the border. */ public void setOnTheeBorder() { this.m_componentOnTheBorder = true; @@ -129,6 +138,5 @@ public void setOnTheeBorder() { public String toString() { return "Component label : " + this.m_label + ", Number of points : " + this.m_numberOfPoints; } - } // end of class ComponentInfo diff --git a/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent.java b/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent.java index 8f68eb49..48101caa 100644 --- a/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent.java +++ b/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent.java @@ -9,40 +9,36 @@ package gred.nucleus.connectedComponent; +import gred.nucleus.componentRemoval.ComponentRemovalNone; +import gred.nucleus.componentRemoval.ComponentRemovalPredicate; import gred.nucleus.utils.Voxel; - -import java.util.ArrayList; - import ij.ImagePlus; import ij.ImageStack; import ij.measure.Calibration; -import gred.nucleus.componentRemoval.ComponentRemovalNone; -import gred.nucleus.componentRemoval.ComponentRemovalPredicate; + +import java.util.ArrayList; /** - * - * Allows connected components labeling in a binary image. - * This abstract class has derived classes to label components in 2D or 3D images. - * Some filtering criteria for filtering the connected components are supported : + * Allows connected components labeling in a binary image. This abstract class has derived classes to label components + * in 2D or 3D images. Some filtering criteria for filtering the connected components are supported : *

    *
  • Minimal volume for the components (taking into account the calibration)
  • *
  • Remove connected components that touch the boundary of the image.
  • *
* An option in the filtering method allows to modify the input image to set random grey levels on each component. - + * * @author Remy Malgouyres, Tristan Dubos and Axel Poulet */ public abstract class ConnectedComponent { /** - * Input Image. - * The image can be modified by the filtering in the filterComponents() method + * Input Image. The image can be modified by the filtering in the filterComponents() method */ protected ImagePlus m_inputImage; - + /** Color of the foreground in the input binary image */ protected int m_foregroundColor; - + /** Components Information (cardinality, label, voxel representative, etc.) */ protected ArrayList m_compInfo; @@ -51,171 +47,222 @@ public abstract class ConnectedComponent { /** Volume of a voxel (used for component size thresholding) */ protected double m_voxelVolume; - + /** * Initializes the fields of this instance (to be called in derived classes constructors) - * @param inputImage : input (probably binary) image, the components of which to compute. + * + * @param inputImage : input (probably binary) image, the components of which to compute. * @param foregroundColor label of the 1's in the input image ip */ protected ConnectedComponent(ImagePlus inputImage, int foregroundColor) { this.m_inputImage = inputImage; Calibration cal = m_inputImage.getCalibration(); - this.m_voxelVolume = cal.pixelDepth*cal.pixelWidth*cal.pixelHeight; - + this.m_voxelVolume = cal.pixelDepth * cal.pixelWidth * cal.pixelHeight; + //System.out.println("vol vx"+m_voxelVolume); this.m_foregroundColor = foregroundColor; - this.m_labels = new int[this.m_inputImage.getWidth()][this.m_inputImage.getHeight()][this.m_inputImage.getNSlices()]; - for (int i=0 ; i(); } - + + /** - * Constructs a ConnectedComponent derived class instance with relevant dimension (2D or 3D). - * the connected components are not labeled. Please call doConnectedComponent(). - * @param inputImage : input (probably binary) image, the components of which to compute. + * Constructs a ConnectedComponent derived class instance with relevant dimension (2D or 3D). the connected + * components are not labeled. Please call doConnectedComponent(). + * + * @param inputImage : input (probably binary) image, the components of which to compute. * @param foregroundColor label of the 1's in the input image inputImage + * * @return an instance of a concrete derived class for ConnectedComponent */ public static ConnectedComponent getConnectedComponent(ImagePlus inputImage, int foregroundColor) { - if (inputImage.getNSlices() <= 1) + if (inputImage.getNSlices() <= 1) { return new ConnectedComponent2D(inputImage, foregroundColor); - + } + return new ConnectedComponent3D(inputImage, foregroundColor); } /** - * Constructs a ConnectedComponent derived class instance with relevant dimension (2D or 3D) and labels the components. - * Filters the image components according to two criteria: + * Constructs a ConnectedComponent derived class instance with relevant dimension (2D or 3D) and labels the + * components. Filters the image components according to two criteria: *
    *
  • Possibly remove the components which are on the edge of the image
  • *
  • Possibly remove the components with size bellow some threshold
  • *
- * @param inputImage : input (probably binary) image, the components of which to compute. - * @param foregroundColor label of the 1's in the input image inputImage - * @param removeBorderComponent true if the components which are on the edge of the image should be removed by filtering - * @param thresholdVoxelVolume minimal volume for filtering (taking into account the calibration) for the components. 0 if no minimal volume is required - * @param setRandomColors true if the colors of the original image should be set according to the components labels. + * + * @param inputImage : input (probably binary) image, the components of which to compute. + * @param foregroundColor label of the 1's in the input image inputImage + * @param removeBorderComponent true if the components which are on the edge of the image should be removed by + * filtering + * @param thresholdVoxelVolume minimal volume for filtering (taking into account the calibration) for the + * components. 0 if no minimal volume is required + * @param setRandomColors true if the colors of the original image should be set according to the components + * labels. + * * @return an instance of a concrete derived class for ConnectedComponent + * * @throws Exception in case the number of connected components exceeds the Short.MAX_VALUE (32767) */ - public static ConnectedComponent getLabelledConnectedComponent( ImagePlus inputImage, int foregroundColor, - boolean removeBorderComponent, double thresholdVoxelVolume, boolean setRandomColors) throws Exception { + public static ConnectedComponent getLabelledConnectedComponent(ImagePlus inputImage, + int foregroundColor, + boolean removeBorderComponent, + double thresholdVoxelVolume, + boolean setRandomColors) throws Exception { ConnectedComponent cc; - if (inputImage.getNSlices() <= 1) + if (inputImage.getNSlices() <= 1) { cc = new ConnectedComponent2D(inputImage, foregroundColor); - else + } else { cc = new ConnectedComponent3D(inputImage, foregroundColor); + } cc.doLabelConnectedComponent(); cc.filterComponents(removeBorderComponent, thresholdVoxelVolume, setRandomColors); return cc; } + /** - * Constructs a ConnectedComponent derived class instance with relevant dimension (2D or 3D) and labels the components. - * Filters the image components according to two criteria: + * Constructs a ConnectedComponent derived class instance with relevant dimension (2D or 3D) and labels the + * components. Filters the image components according to two criteria: *
    *
  • Possibly remove the components which are on the edge of the image
  • *
  • Possibly remove the components with size bellow some threshold
  • *
- * @param inputImage : input (probably binary) image, the components of which to compute. - * @param foregroundColor label of the 1's in the input image inputImage - * @param removeBorderComponent true if the components which are on the edge of the image should be removed by filtering - * @param thresholdVoxelVolume minimal volume for filtering (taking into account the calibration) for the components. 0 if no minimal volume is required - * @param removalPredicate a predicate according to which components should be filtered out - * @param keepPredicate true if we should keep the components with a voxel satisfying removalPredicate, and false if we should remove the components with a voxel satisfying removalPredicate - * @param setRandomColors true if the colors of the original image should be set according to the components labels. + * + * @param inputImage : input (probably binary) image, the components of which to compute. + * @param foregroundColor label of the 1's in the input image inputImage + * @param removeBorderComponent true if the components which are on the edge of the image should be removed by + * filtering + * @param thresholdVoxelVolume minimal volume for filtering (taking into account the calibration) for the + * components. 0 if no minimal volume is required + * @param removalPredicate a predicate according to which components should be filtered out + * @param keepPredicate true if we should keep the components with a voxel satisfying removalPredicate, and + * false if we should remove the components with a voxel satisfying removalPredicate + * @param setRandomColors true if the colors of the original image should be set according to the components + * labels. + * * @return an instance of a concrete derived class for ConnectedComponent - * @throws Exception in case the number of connected components exceeds the Short.MAX_VALUE (32767) + * + * @throws Exception in case the number of connected components exceeds the Short.MAX_VALUE (32767) */ - public static ConnectedComponent getLabelledConnectedComponent(ImagePlus inputImage, int foregroundColor, - boolean removeBorderComponent, double thresholdVoxelVolume, ComponentRemovalPredicate removalPredicate, - boolean keepPredicate, boolean setRandomColors ) throws Exception { + public static ConnectedComponent getLabelledConnectedComponent(ImagePlus inputImage, + int foregroundColor, + boolean removeBorderComponent, + double thresholdVoxelVolume, + ComponentRemovalPredicate removalPredicate, + boolean keepPredicate, + boolean setRandomColors) throws Exception { ConnectedComponent cc; - if (inputImage.getNSlices() <= 1) + if (inputImage.getNSlices() <= 1) { cc = new ConnectedComponent2D(inputImage, foregroundColor); - else + } else { cc = new ConnectedComponent3D(inputImage, foregroundColor); + } cc.doLabelConnectedComponent(); - cc.filterComponents(removeBorderComponent, thresholdVoxelVolume, removalPredicate, keepPredicate, setRandomColors); + cc.filterComponents(removeBorderComponent, + thresholdVoxelVolume, + removalPredicate, + keepPredicate, + setRandomColors); return cc; } - + + /** * retrieves the label of a voxel (after calling doComponents) + * * @param x first coordinate of the pixel * @param y second coordinate of the pixel + * * @return the label of the input voxel (0 if not in any connected component) */ public int getLabel(int x, int y) { return this.m_labels[x][y][0]; } - + + /** * retrieves the label of a voxel (after calling doComponents) + * * @param x first coordinate of the voxel * @param y second coordinate of the voxel * @param z third coordinate of the voxel + * * @return the label of the input voxel (0 if not in any connected component) */ public int getLabel(int x, int y, int z) { return this.m_labels[x][y][z]; } - + + /** * retrieves the label of a voxel (after calling doComponents) - * @param x first coordinate of the voxel - * @param y second coordinate of the voxel - * @param z third coordinate of the voxel + * + * @param x first coordinate of the voxel + * @param y second coordinate of the voxel + * @param z third coordinate of the voxel * @param label the label of the input voxel (0 if not in any connected component) */ protected void setLabel(int x, int y, int z, int label) { this.m_labels[x][y][z] = label; } - + + /** - * Retrieves the informations about a component for its label - * may return null if the component does not exist or has been erased because below volume threshold or on the border. + * Retrieves the information about a component for its label may return null if the component does not exist or has + * been erased because below volume threshold or on the border. + * * @param label the component label - * @return the ComponentInfo instance of the component with the considered label. returns null if the component info is undefined + * + * @return the ComponentInfo instance of the component with the considered label. returns null if the component info + * is undefined */ public ComponentInfo getComponentInfo(short label) { try { - ComponentInfo ci = this.m_compInfo.get(label-1); - if (ci.getnumberOfPoints() ==0) + ComponentInfo ci = this.m_compInfo.get(label - 1); + if (ci.getNumberOfPoints() == 0) { return null; + } return ci; - }catch (Exception e){ + } catch (Exception e) { return null; } } - + + /** * Retrieve a collection of voxels, with one voxel in each (possibly filtered) connected component. + * * @return the array of voxel representatives of components */ public ArrayList getVoxelRepresentants() { ArrayList tabVoxels = new ArrayList<>(); for (ComponentInfo ci : this.m_compInfo) { - if (ci.getnumberOfPoints() > 0) + if (ci.getNumberOfPoints() > 0) { tabVoxels.add(ci.getRepresentant()); + } } return tabVoxels; } - + + /** * labels the connected components of the input image (attribute this.m_ip) + * * @throws Exception in case the number of connected components exceeds the Short.MAX_VALUE (32767) - */ + */ abstract void doLabelConnectedComponent() throws Exception; - - + + /** * Filters the image components according to two criteria: *
    @@ -223,14 +270,25 @@ public ArrayList getVoxelRepresentants() { *
  • Possibly remove the components with size bellow some threshold
  • *
  • Possibly keep (or remove) the components with a voxel satisfying a predicate
  • *
- * @param removeBorderComponent true if the components which are on the edge of the image should be removed by filtering - * @param thresholdComponentVolume minimal volume for filtering (taking into account the calibration) for the components. 0 if no minimal volume is required - * @param setRandomColors true if the colors of the original image should be set according to the components labels. + * + * @param removeBorderComponent true if the components which are on the edge of the image should be removed by + * filtering + * @param thresholdComponentVolume minimal volume for filtering (taking into account the calibration) for the + * components. 0 if no minimal volume is required + * @param setRandomColors true if the colors of the original image should be set according to the + * components labels. */ - protected void filterComponents( boolean removeBorderComponent, double thresholdComponentVolume, boolean setRandomColors) { - filterComponents( removeBorderComponent, thresholdComponentVolume, new ComponentRemovalNone(), true, setRandomColors); + protected void filterComponents(boolean removeBorderComponent, + double thresholdComponentVolume, + boolean setRandomColors) { + filterComponents(removeBorderComponent, + thresholdComponentVolume, + new ComponentRemovalNone(), + true, + setRandomColors); } - + + /** * Filters the image components according to two criteria: *
    @@ -238,32 +296,49 @@ protected void filterComponents( boolean removeBorderComponent, double threshold *
  • Possibly remove the components with size bellow some threshold
  • *
  • Possibly keep (or remove) the components with a voxel satisfying a predicate
  • *
- * @param removeBorderComponent true if the components which are on the edge of the image should be removed by filtering - * @param thresholdComponentVolume minimal volume for filtering (taking into account the calibration) for the components. 0 if no minimal volume is required - * @param removalPredicate a predicate according to which components should be filtered out - * @param keepPredicate true if we should keep only the components with at least one voxel satisfying removalPredicate, and false if we should remove the components with at least one voxel satisfying removalPredicate - * @param setRandomColors true if the colors of the original image should be set according to the components labels. + * + * @param removeBorderComponent true if the components which are on the edge of the image should be removed by + * filtering + * @param thresholdComponentVolume minimal volume for filtering (taking into account the calibration) for the + * components. 0 if no minimal volume is required + * @param removalPredicate a predicate according to which components should be filtered out + * @param keepPredicate true if we should keep only the components with at least one voxel satisfying + * removalPredicate, and false if we should remove the components with at least one + * voxel satisfying removalPredicate + * @param setRandomColors true if the colors of the original image should be set according to the + * components labels. */ - protected void filterComponents( boolean removeBorderComponent, double thresholdComponentVolume, - ComponentRemovalPredicate removalPredicate, boolean keepPredicate, boolean setRandomColors) { - System.out.println("La on des compO : "+this.m_voxelVolume ); - + protected void filterComponents(boolean removeBorderComponent, + double thresholdComponentVolume, + ComponentRemovalPredicate removalPredicate, + boolean keepPredicate, + boolean setRandomColors) { + System.out.println("La on des compO : " + this.m_voxelVolume); + ArrayList existsVoxelSatisfyingPredicate = new ArrayList<>(); - for (int i = 0 ; i < this.m_compInfo.size() ; ++i) + for (int i = 0; i < this.m_compInfo.size(); ++i) { existsVoxelSatisfyingPredicate.add(Boolean.FALSE); - - // Check the predicate + } + + // Check the predicate Voxel voxelToTest = new Voxel(); - for (voxelToTest.setX((short)0); voxelToTest.getX() < this.m_inputImage.getWidth(); voxelToTest.incrementCoord(0)) { - for (voxelToTest.setY((short)0); voxelToTest.getY() < this.m_inputImage.getHeight(); voxelToTest.incrementCoord(1)) { - for (voxelToTest.setZ((short)0); voxelToTest.getZ() < this.m_inputImage.getNSlices(); voxelToTest.incrementCoord(2)) { + for (voxelToTest.setX((short) 0); + voxelToTest.getX() < this.m_inputImage.getWidth(); + voxelToTest.incrementCoordinate(0)) { + for (voxelToTest.setY((short) 0); + voxelToTest.getY() < this.m_inputImage.getHeight(); + voxelToTest.incrementCoordinate(1)) { + for (voxelToTest.setZ((short) 0); + voxelToTest.getZ() < this.m_inputImage.getNSlices(); + voxelToTest.incrementCoordinate(2)) { // get the voxel's label int label = getLabel(voxelToTest.getX(), voxelToTest.getY(), voxelToTest.getZ()); if (label > 0) { // if not a background voxel - ComponentInfo ci = this.m_compInfo.get(label-1); + ComponentInfo ci = this.m_compInfo.get(label - 1); // test the predicate - if(removalPredicate.keepVoxelComponent(voxelToTest, ci)) - existsVoxelSatisfyingPredicate.set(label-1, Boolean.TRUE); + if (removalPredicate.keepVoxelComponent(voxelToTest, ci)) { + existsVoxelSatisfyingPredicate.set(label - 1, Boolean.TRUE); + } } } } @@ -276,51 +351,57 @@ protected void filterComponents( boolean removeBorderComponent, double threshold // if the keep predicate is false for all the voxels // and we should keep only // the components with a voxel satisfying removalPredicate - for (int i = 0 ; i < this.m_compInfo.size() ; ++i) { - if (((!existsVoxelSatisfyingPredicate.get(i)) && keepPredicate) || (existsVoxelSatisfyingPredicate.get(i) && !keepPredicate)) - // remove the component + for (int i = 0; i < this.m_compInfo.size(); ++i) { + if (((!existsVoxelSatisfyingPredicate.get(i)) && keepPredicate) || + (existsVoxelSatisfyingPredicate.get(i) && !keepPredicate)) + // remove the component + { this.m_compInfo.get(i).setNumberOfPoints(0); + } } - - int thresholdNVoxel = (int)(thresholdComponentVolume/this.m_voxelVolume); - ArrayList newLabels = new ArrayList<>(this.m_compInfo.size()); + + int thresholdNVoxel = (int) (thresholdComponentVolume / this.m_voxelVolume); + ArrayList newLabels = new ArrayList<>(this.m_compInfo.size()); ArrayList newTabComponents = new ArrayList<>(); - short componentsCount = 0; + short componentsCount = 0; // For each label - for (int label=1 ; label<=this.m_compInfo.size() ; label++) { - ComponentInfo ci = this.m_compInfo.get(label-1); + for (int label = 1; label <= this.m_compInfo.size(); label++) { + ComponentInfo ci = this.m_compInfo.get(label - 1); // If the component survives the filtering criteria - if (ci != null && ci.getnumberOfPoints() > 0 && ci.getnumberOfPoints() >= thresholdNVoxel && ((!removeBorderComponent) || !ci.isOnTheBorder())) { + if (ci != null && + ci.getNumberOfPoints() > 0 && + ci.getNumberOfPoints() >= thresholdNVoxel && + ((!removeBorderComponent) || !ci.isOnTheBorder())) { componentsCount++; // old label/new label correspondence newLabels.add((int) componentsCount); // register the component in the final array newTabComponents.add(ci); - } - else{ + } else if (ci != null) { ci.setNumberOfPoints(0); newLabels.add(0); } } ArrayList componentsColors = new ArrayList<>(newTabComponents.size()); - for (int i=0 ; i 0 && newLabels.get(label-1) > 0){ - int newLabel = newLabels.get(label-1); // get new label from old label - ComponentInfo ci = newTabComponents.get(newLabel-1); + if (label > 0 && newLabels.get(label - 1) > 0) { + int newLabel = newLabels.get(label - 1); // get new label from old label + ComponentInfo ci = newTabComponents.get(newLabel - 1); ci.setLabel(newLabel); // Set new label for the component setLabel(i, j, k, newLabel); // Set new label for the voxel // Possibly change the color on the whole component - if (setRandomColors) - imgP.setVoxel(i, j, k, componentsColors.get(newLabel-1).intValue()); - } - else{ + if (setRandomColors) { + imgP.setVoxel(i, j, k, componentsColors.get(newLabel - 1).intValue()); + } + } else { setLabel(i, j, k, 0); // Set label to 0 (remove the voxel) imgP.setVoxel(i, j, k, 0); } @@ -329,23 +410,27 @@ protected void filterComponents( boolean removeBorderComponent, double threshold } this.m_compInfo = newTabComponents; } - + /** * @return a human readable string representation of this instance + * * @see Object#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Connected components of the image ").append(this.m_inputImage.getTitle()).append("\n"); - for (ComponentInfo compInfo : this.m_compInfo) + for (ComponentInfo compInfo : this.m_compInfo) { builder.append(compInfo).append("\n"); + } return builder.toString(); } + /** * retrieves the number of components (after calling doComponents) + * * @return the number of components detected. */ public int getNumberOfComponents() { diff --git a/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent2D.java b/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent2D.java index 914d582e..a42171d8 100644 --- a/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent2D.java +++ b/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent2D.java @@ -65,39 +65,39 @@ protected void breadthFirstSearch( Voxel voxelShort, short currentLabel, Compone // freeVoxel(); // Determine the neighborhood taking into account the image's boundaries - short imin, imax, jmin, jmax; + short iMin, iMax, jMin, jMax; if (iV-1 >= 0) - imin = (short)(iV-1); + iMin = (short)(iV-1); else{ - imin = 0; + iMin = 0; componentInfo.setOnTheeBorder(); } if (jV-1 >= 0) - jmin = (short)(jV-1); + jMin = (short)(jV-1); else{ - jmin = 0; + jMin = 0; componentInfo.setOnTheeBorder(); } if (iV+1 < this.m_inputImage.getWidth()) - imax = (short)(iV+1); + iMax = (short)(iV+1); else{ - imax = (short)(this.m_inputImage.getWidth()-1); + iMax = (short)(this.m_inputImage.getWidth()-1); componentInfo.setOnTheeBorder(); } if (jV+1 < this.m_inputImage.getHeight()) - jmax = (short)(jV+1); + jMax = (short)(jV+1); else{ - jmax = (short)(this.m_inputImage.getHeight()-1); + jMax = (short)(this.m_inputImage.getHeight()-1); componentInfo.setOnTheeBorder(); } ImageProcessor imgProc = m_inputImage.getProcessor(); // For each neighbor : - for (short ii = imin ; ii <= imax ; ii++) { - for (short jj = jmin ; jj <= jmax; jj++) { + for (short ii = iMin ; ii <= iMax ; ii++) { + for (short jj = jMin ; jj <= jMax; jj++) { // If the neighbor (different from VoxelRecordShort) is a 1 and not labeled if ((getLabel(ii, jj, 0) == 0) && (imgProc.get(ii, jj) == this.m_foregroundColor)) { // Set the voxel's label @@ -112,6 +112,7 @@ protected void breadthFirstSearch( Voxel voxelShort, short currentLabel, Compone } } + /** labels the connected components of the input image (attribute m_ip) */ @Override public void doLabelConnectedComponent() { @@ -134,6 +135,5 @@ public void doLabelConnectedComponent() { } } } - } // end of class diff --git a/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent3D.java b/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent3D.java index 2e6ba85f..f9f50430 100644 --- a/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent3D.java +++ b/src/main/java/gred/nucleus/connectedComponent/ConnectedComponent3D.java @@ -57,50 +57,50 @@ protected void breadthFirstSearch( Voxel voxelShort, short currentLabel, Compone short jV = polledVoxelShort.getY(); short kV = polledVoxelShort.getZ(); // Determine the neighborhood taking into account the image's boundaries - short imin, imax, jmin, jmax, kmin, kmax; + short iMin, iMax, jMin, jMax, kMin, kMax; if (iV-1 >= 0) - imin = (short)(iV-1); + iMin = (short)(iV-1); else{ - imin = 0; + iMin = 0; componentInfo.setOnTheeBorder(); } if (jV-1 >= 0) - jmin = (short)(jV-1); + jMin = (short)(jV-1); else{ - jmin = 0; + jMin = 0; componentInfo.setOnTheeBorder(); } if (kV-1 >= 0) - kmin = (short)(kV-1); + kMin = (short)(kV-1); else{ - kmin = 0; + kMin = 0; componentInfo.setOnTheeBorder(); } if (iV+1 < this.m_inputImage.getWidth()) - imax = (short)(iV+1); + iMax = (short)(iV+1); else{ - imax = (short)(this.m_inputImage.getWidth()-1); + iMax = (short)(this.m_inputImage.getWidth()-1); componentInfo.setOnTheeBorder(); } if (jV+1 < this.m_inputImage.getHeight()) - jmax = (short)(jV+1); + jMax = (short)(jV+1); else{ - jmax = (short)(this.m_inputImage.getHeight()-1); + jMax = (short)(this.m_inputImage.getHeight()-1); componentInfo.setOnTheeBorder(); } if (kV+1 < this.m_inputImage.getNSlices()) - kmax = (short)(kV+1); + kMax = (short)(kV+1); else{ - kmax = (short)(this.m_inputImage.getNSlices()-1); + kMax = (short)(this.m_inputImage.getNSlices()-1); componentInfo.setOnTheeBorder(); } ImageStack imageStack = m_inputImage.getStack(); // For each neighbor : - for (short kk = kmin ; kk <= kmax; kk++) { + for (short kk = kMin ; kk <= kMax; kk++) { //this.m_inputImage.setCurrentSlice(kk); - for (short ii = imin ; ii <= imax ; ii++) { - for (short jj = jmin ; jj <= jmax; jj++) { + for (short ii = iMin ; ii <= iMax ; ii++) { + for (short jj = jMin ; jj <= jMax; jj++) { // If the neighbor (different from VoxelRecordShort) is a 1 and not labeled if ((getLabel(ii, jj, kk) == 0) && (imageStack.getVoxel(ii,jj,kk) == this.m_foregroundColor)) { // Set the voxel's label diff --git a/src/main/java/gred/nucleus/core/ChromocenterAnalysis.java b/src/main/java/gred/nucleus/core/ChromocenterAnalysis.java index 7bb0e8f4..463da7c5 100644 --- a/src/main/java/gred/nucleus/core/ChromocenterAnalysis.java +++ b/src/main/java/gred/nucleus/core/ChromocenterAnalysis.java @@ -18,6 +18,7 @@ public class ChromocenterAnalysis { public ChromocenterAnalysis() { } + /** * Compute the several parameters to characterize the chromocenter of one image, and return the results on the IJ * log windows @@ -29,7 +30,7 @@ public void computeParametersChromocenter(ImagePlus imagePlusSegmented, ImagePlu Histogram histogram = new Histogram(); histogram.run(imagePlusChromocenter); Measure3D measure3D = new Measure3D(); - double[] tVolume = measure3D.computeVolumeofAllObjects(imagePlusChromocenter); + double[] tVolume = measure3D.computeVolumeOfAllObjects(imagePlusChromocenter); RadialDistance radialDistance = new RadialDistance(); IJ.log("CHROMOCENTER PARAMETERS"); IJ.log("Titre Volume BorderToBorderDistance BarycenterToBorderDistance BarycenterToBorderDistanceNucleus "); @@ -52,6 +53,7 @@ public void computeParametersChromocenter(ImagePlus imagePlusSegmented, ImagePlu } } + /** * Compute the several parameters to characterize the chromocenter of several images, and create one output file for * the results @@ -77,7 +79,7 @@ public void computeParametersChromocenter(String pathResultsFile, imagePlusChromocenter.getCalibration().pixelHeight, imagePlusChromocenter.getCalibration().pixelDepth); double[] tVolume = - measure3D.computeVolumeofAllObjects(imagePlusChromocenter); + measure3D.computeVolumeOfAllObjects(imagePlusChromocenter); RadialDistance radialDistance = new RadialDistance(); double[] tBorderToBorderDistanceTable = radialDistance.computeBorderToBorderDistances(imagePlusSegmented, imagePlusChromocenter); diff --git a/src/main/java/gred/nucleus/core/ChromocentersEnhancement.java b/src/main/java/gred/nucleus/core/ChromocentersEnhancement.java index e36bc903..4cd01add 100644 --- a/src/main/java/gred/nucleus/core/ChromocentersEnhancement.java +++ b/src/main/java/gred/nucleus/core/ChromocentersEnhancement.java @@ -26,6 +26,7 @@ public class ChromocentersEnhancement { public ChromocentersEnhancement() { } + public static void saveFile(ImagePlus imagePlus, String pathFile) { FileSaver fileSaver = new FileSaver(imagePlus); File file = new File(pathFile); @@ -37,13 +38,14 @@ public static void saveFile(ImagePlus imagePlus, String pathFile) { } } + /** * compute and create the image contrast with the raw image and the segmented image * * @param imagePlusRaw raw image * @param imagePlusSegmented segmented image of the nucleus * - * @return image of the cotrasted region + * @return image of the contrasted region */ public ImagePlus applyEnhanceChromocenters(ImagePlus imagePlusRaw, ImagePlus imagePlusSegmented) { MyGradient myGradient = new MyGradient(imagePlusRaw, imagePlusSegmented); @@ -61,6 +63,7 @@ public ImagePlus applyEnhanceChromocenters(ImagePlus imagePlusRaw, ImagePlus ima return computeImage(imagePlusWatershed, contrast); } + /** * Compute the region adjacency graph. The aim is to detect the neighboring region. * @@ -107,11 +110,12 @@ private double[][] getRegionAdjacencyGraph(ImagePlus imagePlusWatershed) { return tRegionAdjacencyGraph; } + /** * Compute the contrasts between neighboring region. * * @param imagePlusRaw raw image - * @param imagePlusRegions imag of the contrasted regions + * @param imagePlusRegions image of the contrasted regions * * @return table of contrast */ @@ -171,6 +175,7 @@ private double[] computeMeanIntensity(ImagePlus imagePlusInput, ImagePlus imageP return tIntensityMean; } + /** * Creation of the image of contrasted regions * @@ -181,14 +186,14 @@ private double[] computeMeanIntensity(ImagePlus imagePlusInput, ImagePlus imageP */ private ImagePlus computeImage(ImagePlus imagePlusInput, double[] tVoxelValue) { double voxelValue; - ImagePlus imagePlusContrast = imagePlusInput.duplicate(); - ImageStack imageStackConstrast = imagePlusContrast.getStack(); + ImagePlus imagePlusContrast = imagePlusInput.duplicate(); + ImageStack imageStackContrast = imagePlusContrast.getStack(); for (int k = 0; k < imagePlusContrast.getNSlices(); ++k) { for (int i = 0; i < imagePlusContrast.getWidth(); ++i) { for (int j = 0; j < imagePlusContrast.getHeight(); ++j) { - voxelValue = imageStackConstrast.getVoxel(i, j, k); + voxelValue = imageStackContrast.getVoxel(i, j, k); if (voxelValue > 0) { - imageStackConstrast.setVoxel(i, j, k, tVoxelValue[(int) voxelValue]); + imageStackContrast.setVoxel(i, j, k, tVoxelValue[(int) voxelValue]); } } } @@ -196,8 +201,9 @@ private ImagePlus computeImage(ImagePlus imagePlusInput, double[] tVoxelValue) { return imagePlusContrast; } + /** - * Passe les valeurs de -1 a 0 suite Ă  la nouvelle version de MorpholibJ + * Converts values from -1 to 0 following the release of a new MorpholibJ version * * @param imagePlusInput * @@ -205,13 +211,13 @@ private ImagePlus computeImage(ImagePlus imagePlusInput, double[] tVoxelValue) { */ private ImagePlus convertNegativeValue(ImagePlus imagePlusInput) { double voxelValue; - ImagePlus imagePlusContrast = imagePlusInput.duplicate(); - ImageStack imageStackConstrast = imagePlusContrast.getStack(); + ImagePlus imagePlusContrast = imagePlusInput.duplicate(); + ImageStack imageStackContrast = imagePlusContrast.getStack(); for (int k = 0; k < imagePlusContrast.getNSlices(); ++k) { for (int i = 0; i < imagePlusContrast.getWidth(); ++i) { for (int j = 0; j < imagePlusContrast.getHeight(); ++j) { - if (imageStackConstrast.getVoxel(i, j, k) == -1.0) { - imageStackConstrast.setVoxel(i, j, k, 0.0); + if (imageStackContrast.getVoxel(i, j, k) == -1.0) { + imageStackContrast.setVoxel(i, j, k, 0.0); } } } diff --git a/src/main/java/gred/nucleus/core/ComputeNucleiParameters.java b/src/main/java/gred/nucleus/core/ComputeNucleiParameters.java index cd3eb27b..7d985536 100644 --- a/src/main/java/gred/nucleus/core/ComputeNucleiParameters.java +++ b/src/main/java/gred/nucleus/core/ComputeNucleiParameters.java @@ -29,6 +29,7 @@ public ComputeNucleiParameters(String rawImagesInputDirectory, } + /** * Constructor with input and output files * @@ -41,6 +42,7 @@ public ComputeNucleiParameters(String rawImagesInputDirectory, String segmentedI } + /** * Constructor with input, output files and calibration from dialog. * @@ -60,16 +62,15 @@ public ComputeNucleiParameters(String rawImagesInputDirectory, String segmentedI * Compute nuclei parameters generate from segmentation ( OTSU / GIFT) Useful if parallel segmentation was use to * get results parameter in the same folder. * - * @throws Exception : file exceptions */ - public void run() throws Exception { + public void run() { Directory directoryRawInput = new Directory(this.m_pluginParameters.getInputFolder()); directoryRawInput.listImageFiles(this.m_pluginParameters.getInputFolder()); directoryRawInput.checkIfEmpty(); Directory directorySegmentedInput = new Directory(this.m_pluginParameters.getOutputFolder()); directorySegmentedInput.listImageFiles(this.m_pluginParameters.getOutputFolder()); directorySegmentedInput.checkIfEmpty(); - ArrayList segmentedImages = directorySegmentedInput.m_listeOfFiles; + ArrayList segmentedImages = directorySegmentedInput.m_fileList; StringBuilder outputCropGeneralInfoOTSU = new StringBuilder(); outputCropGeneralInfoOTSU.append(this.m_pluginParameters.getAnalyseParameters()).append(getColNameResult()); @@ -81,9 +82,9 @@ public void run() throws Exception { Measure3D measure3D = new Measure3D(Segmented, Raw, - this.m_pluginParameters.getXcalibration(Raw), - this.m_pluginParameters.getYcalibration(Raw), - this.m_pluginParameters.getZcalibration(Raw)); + this.m_pluginParameters.getXCalibration(Raw), + this.m_pluginParameters.getYCalibration(Raw), + this.m_pluginParameters.getZCalibration(Raw)); outputCropGeneralInfoOTSU.append(measure3D.nucleusParameter3D()).append("\n"); } catch (Exception e) { e.printStackTrace(); @@ -99,11 +100,13 @@ public void run() throws Exception { } - public void addConfigParameters(String pathToconfig) { - this.m_pluginParameters.addGeneralProperties(pathToconfig); + + public void addConfigParameters(String pathToConfig) { + this.m_pluginParameters.addGeneralProperties(pathToConfig); } + /** @return columns names for results */ private String getColNameResult() { return "NucleusFileName\t" + @@ -123,5 +126,4 @@ private String getColNameResult() { "MedianIntensityBackground\t" + "ImageSize\n"; } - } diff --git a/src/main/java/gred/nucleus/core/ConvexHullSegmentation.java b/src/main/java/gred/nucleus/core/ConvexHullSegmentation.java index f73ad895..9500d505 100644 --- a/src/main/java/gred/nucleus/core/ConvexHullSegmentation.java +++ b/src/main/java/gred/nucleus/core/ConvexHullSegmentation.java @@ -35,6 +35,7 @@ public ImagePlus runGIFTWrapping(ImagePlus imagePlusInput, SegmentationParameter return imageMakingUnion(imagePlusInput, imagePlusXY, imagePlusXZ, imagePlusYZ); } + /** * Make an union of segmented images from the different plans * diff --git a/src/main/java/gred/nucleus/core/Measure3D.java b/src/main/java/gred/nucleus/core/Measure3D.java index 4b4b6cf3..c34c4db8 100644 --- a/src/main/java/gred/nucleus/core/Measure3D.java +++ b/src/main/java/gred/nucleus/core/Measure3D.java @@ -24,7 +24,7 @@ *

*

*

- * //TODO reercrire cette classe ya des choses que je fais 5 fois c'est inutil + * //TODO reecrire cette classe ya des choses que je fais 5 fois c'est inutil * * @author Tristan Dubos and Axel Poulet */ @@ -38,29 +38,31 @@ public class Measure3D { double _yCal; double _zCal; - HashMap _segmentedNucleusHisto = new HashMap<>(); - HashMap _backgroundHisto = new HashMap<>(); + HashMap _segmentedNucleusHistogram = new HashMap<>(); + HashMap _backgroundHistogram = new HashMap<>(); public Measure3D() { } - public Measure3D(double xCal, double ycal, double zCal) { + public Measure3D(double xCal, double yCal, double zCal) { this._xCal = xCal; - this._yCal = ycal; + this._yCal = yCal; this._zCal = zCal; } - public Measure3D(ImagePlus[] imageSeg, ImagePlus rawImage, double xCal, double ycal, double zCal) { + + public Measure3D(ImagePlus[] imageSeg, ImagePlus rawImage, double xCal, double yCal, double zCal) { this._rawImage = rawImage; this._imageSeg = imageSeg; this._xCal = xCal; - this._yCal = ycal; + this._yCal = yCal; this._zCal = zCal; } + /** * Scan of image and if the voxel belong to the object of interest, looking, if in his neighborhood there are voxel * value == 0 then it is a boundary voxel. Adding the surface of the face of the voxel frontier, which are in @@ -111,7 +113,7 @@ public double computeSurfaceObject(double label) { * * @return double table which contain the volume of each image object */ - public double[] computeVolumeofAllObjects(ImagePlus imagePlusInput) { + public double[] computeVolumeOfAllObjects(ImagePlus imagePlusInput) { Histogram histogram = new Histogram(); histogram.run(imagePlusInput); @@ -125,6 +127,7 @@ public double[] computeVolumeofAllObjects(ImagePlus imagePlusInput) { return tObjectVolume; } + /** * Compute the volume of one object with this label * @@ -135,15 +138,16 @@ public double[] computeVolumeofAllObjects(ImagePlus imagePlusInput) { public double computeVolumeObject2(double label) { Histogram histogram = new Histogram(); histogram.run(this._imageSeg[0]); - HashMap hashMapHisto = histogram.getHistogram(); + HashMap hashMapHistogram = histogram.getHistogram(); - return hashMapHisto.get(label) * this._xCal * this._yCal * this._zCal; + return hashMapHistogram.get(label) * this._xCal * this._yCal * this._zCal; } + private double computeVolumeObjectML() { - Double volumeTMP = 0.0; - for (Map.Entry toto : this._segmentedNucleusHisto.entrySet()) { + double volumeTMP = 0.0; + for (Map.Entry toto : this._segmentedNucleusHistogram.entrySet()) { if (toto.getValue() > 0) { volumeTMP += toto.getValue(); } @@ -151,6 +155,7 @@ private double computeVolumeObjectML() { return volumeTMP * this._xCal * this._yCal * this._zCal; } + /** * Compute the volume of one object with this label * @@ -162,10 +167,11 @@ private double computeVolumeObjectML() { public double computeVolumeObject(ImagePlus imagePlusInput, double label) { Histogram histogram = new Histogram(); histogram.run(imagePlusInput); - HashMap hashMapHisto = histogram.getHistogram(); - return hashMapHisto.get(label) * this._xCal * this._yCal * this._zCal; + HashMap hashMapHistogram = histogram.getHistogram(); + return hashMapHistogram.get(label) * this._xCal * this._yCal * this._zCal; } + /** * compute the equivalent spherical radius * @@ -179,6 +185,7 @@ public double equivalentSphericalRadius(double volume) { return radius; } + /** * compute the equivalent spherical radius with ImagePlus in input * @@ -207,6 +214,7 @@ public double computeSphericity(double volume, double surface) { / (surface * surface * surface)); } + /** * Method which compute the eigen value of the matrix (differences between the coordinates of all points and the * barycenter. Obtaining a symmetric matrix : xx xy xz xy yy yz xz yz zz Compute the eigen value with the pakage @@ -220,13 +228,13 @@ public double[] computeEigenValue3D(double label) { ImageStack imageStackInput = this._imageSeg[0].getImageStack(); VoxelRecord barycenter = computeBarycenter3D(true, this._imageSeg[0], label); - double xx = 0; - double xy = 0; - double xz = 0; - double yy = 0; - double yz = 0; - double zz = 0; - int compteur = 0; + double xx = 0; + double xy = 0; + double xz = 0; + double yy = 0; + double yz = 0; + double zz = 0; + int counter = 0; double voxelValue; for (int k = 0; k < this._imageSeg[0].getStackSize(); ++k) { double dz = ((this._zCal * (double) k) - barycenter.getK()); @@ -242,14 +250,14 @@ public double[] computeEigenValue3D(double label) { xy += dx * dy; xz += dx * dz; yz += dy * dz; - compteur++; + counter++; } } } } - double[][] tValues = {{xx / compteur, xy / compteur, xz / compteur}, - {xy / compteur, yy / compteur, yz / compteur}, - {xz / compteur, yz / compteur, zz / compteur}}; + double[][] tValues = {{xx / counter, xy / counter, xz / counter}, + {xy / counter, yy / counter, yz / counter}, + {xz / counter, yz / counter, zz / counter}}; Matrix matrix = new Matrix(tValues); EigenvalueDecomposition eigenValueDecomposition = matrix.eig(); return eigenValueDecomposition.getRealEigenvalues(); @@ -271,6 +279,7 @@ public double[] computeFlatnessAndElongation(double label) { return shapeParameters; } + /** * Method which determines object barycenter * @@ -313,6 +322,7 @@ public VoxelRecord computeBarycenter3D(boolean unit, return voxelRecordBarycenter; } + /** * Method which compute the barycenter of each objects and return the result in a table of VoxelRecord * @@ -325,14 +335,15 @@ public VoxelRecord[] computeObjectBarycenter(ImagePlus imagePlusInput, boolean unit) { Histogram histogram = new Histogram(); histogram.run(imagePlusInput); - double[] tlabel = histogram.getLabels(); - VoxelRecord[] tVoxelRecord = new VoxelRecord[tlabel.length]; - for (int i = 0; i < tlabel.length; ++i) { - tVoxelRecord[i] = computeBarycenter3D(unit, imagePlusInput, tlabel[i]); + double[] tLabel = histogram.getLabels(); + VoxelRecord[] tVoxelRecord = new VoxelRecord[tLabel.length]; + for (int i = 0; i < tLabel.length; ++i) { + tVoxelRecord[i] = computeBarycenter3D(unit, imagePlusInput, tLabel[i]); } return tVoxelRecord; } + /** * Intensity of chromocenters/ intensity of the nucleus * @@ -372,27 +383,26 @@ public double computeIntensityRHF(ImagePlus imagePlusInput return chromocenterIntensity / nucleusIntensity; } + /** * Method which compute the RHF (total chromocenters volume/nucleus volume) * - * @param imagePlusSegmented binary ImagePlus - * @param imagePlusChomocenters ImagePLus of the chromocenters + * @param imagePlusSegmented binary ImagePlus + * @param imagePlusChromocenters ImagePLus of the chromocenters * * @return double Relative Heterochromatin Fraction compute on the Volume ratio */ - public double computeVolumeRHF(ImagePlus imagePlusSegmented - , ImagePlus imagePlusChomocenters) { - double volumeCc = 0; - double[] tVolumeChromocenter = - computeVolumeofAllObjects(imagePlusChomocenters); + public double computeVolumeRHF(ImagePlus imagePlusSegmented, ImagePlus imagePlusChromocenters) { + double volumeCc = 0; + double[] tVolumeChromocenter = computeVolumeOfAllObjects(imagePlusChromocenters); for (double v : tVolumeChromocenter) { volumeCc += v; } - double[] tVolumeSegmented = - computeVolumeofAllObjects(imagePlusSegmented); + double[] tVolumeSegmented = computeVolumeOfAllObjects(imagePlusSegmented); return volumeCc / tVolumeSegmented[0]; } + /** * Detect the number of object on segmented image. * @@ -414,7 +424,7 @@ public int getNumberOfObject(ImagePlus imagePlusInput) { */ public double computeComplexSurface() { Gradient gradient = new Gradient(this._rawImage); - ArrayList[][][] tableUnitaire = gradient.getUnitaire(); + ArrayList[][][] tableUnitary = gradient.getUnitary(); ImageStack imageStackSegmented = this._imageSeg[0].getStack(); double surfaceArea = 0, voxelValue, neighborVoxelValue; VoxelRecord voxelRecordIn = new VoxelRecord(); @@ -439,8 +449,8 @@ public double computeComplexSurface() { kk); surfaceArea = surfaceArea + computeSurfelContribution( - tableUnitaire[i][j][k], - tableUnitaire[i][j][kk], + tableUnitary[i][j][k], + tableUnitary[i][j][kk], voxelRecordIn, voxelRecordOut, ((this._xCal) * (this._yCal))); @@ -459,8 +469,8 @@ public double computeComplexSurface() { j, k); surfaceArea = surfaceArea + computeSurfelContribution( - tableUnitaire[i][j][k], - tableUnitaire[ii][j][k], + tableUnitary[i][j][k], + tableUnitary[ii][j][k], voxelRecordIn, voxelRecordOut, ((this._yCal) * (this._zCal))); } @@ -479,8 +489,8 @@ public double computeComplexSurface() { k); surfaceArea = surfaceArea + computeSurfelContribution( - tableUnitaire[i][j][k], - tableUnitaire[i][jj][k], + tableUnitary[i][j][k], + tableUnitary[i][jj][k], voxelRecordIn, voxelRecordOut, ((this._xCal) * (this._zCal))); @@ -503,7 +513,7 @@ public double computeComplexSurface() { * @return */ public double computeComplexSurface(ImagePlus imagePlusSegmented, Gradient gradient) { - ArrayList[][][] tableUnitaire = gradient.getUnitaire(); + ArrayList[][][] tableUnitary = gradient.getUnitary(); ImageStack imageStackSegmented = imagePlusSegmented.getStack(); double surfaceArea = 0, voxelValue, neighborVoxelValue; VoxelRecord voxelRecordIn = new VoxelRecord(); @@ -523,8 +533,8 @@ public double computeComplexSurface(ImagePlus imagePlusSegmented, Gradient gradi voxelRecordIn.setLocation(i, j, k); voxelRecordOut.setLocation(i, j, kk); surfaceArea = surfaceArea + - computeSurfelContribution(tableUnitaire[i][j][k], - tableUnitaire[i][j][kk], + computeSurfelContribution(tableUnitary[i][j][k], + tableUnitary[i][j][kk], voxelRecordIn, voxelRecordOut, ((xCalibration) * (yCalibration))); @@ -536,8 +546,8 @@ public double computeComplexSurface(ImagePlus imagePlusSegmented, Gradient gradi voxelRecordIn.setLocation(i, j, k); voxelRecordOut.setLocation(ii, j, k); surfaceArea = surfaceArea + - computeSurfelContribution(tableUnitaire[i][j][k], - tableUnitaire[ii][j][k], + computeSurfelContribution(tableUnitary[i][j][k], + tableUnitary[ii][j][k], voxelRecordIn, voxelRecordOut, ((yCalibration) * (zCalibration))); @@ -549,8 +559,8 @@ public double computeComplexSurface(ImagePlus imagePlusSegmented, Gradient gradi voxelRecordIn.setLocation(i, j, k); voxelRecordOut.setLocation(i, jj, k); surfaceArea = surfaceArea + - computeSurfelContribution(tableUnitaire[i][j][k], - tableUnitaire[i][jj][k], + computeSurfelContribution(tableUnitary[i][j][k], + tableUnitary[i][jj][k], voxelRecordIn, voxelRecordOut, ((xCalibration) * (zCalibration))); @@ -567,28 +577,29 @@ public double computeComplexSurface(ImagePlus imagePlusSegmented, Gradient gradi /** * Compute surface contribution of each voxels from gradients. * - * @param listUnitaireIn - * @param listUnitaireOut + * @param listUnitaryIn + * @param listUnitaryOut * @param voxelRecordIn * @param voxelRecordOut * @param as * * @return */ - private double computeSurfelContribution(ArrayList listUnitaireIn, - ArrayList listUnitaireOut, + private double computeSurfelContribution(ArrayList listUnitaryIn, + ArrayList listUnitaryOut, VoxelRecord voxelRecordIn, VoxelRecord voxelRecordOut, double as) { double dx = voxelRecordIn._i - voxelRecordOut._i; double dy = voxelRecordIn._j - voxelRecordOut._j; double dz = voxelRecordIn._k - voxelRecordOut._k; - double nx = (listUnitaireIn.get(0) + listUnitaireOut.get(0)) / 2; - double ny = (listUnitaireIn.get(1) + listUnitaireOut.get(1)) / 2; - double nz = (listUnitaireIn.get(2) + listUnitaireOut.get(2)) / 2; + double nx = (listUnitaryIn.get(0) + listUnitaryOut.get(0)) / 2; + double ny = (listUnitaryIn.get(1) + listUnitaryOut.get(1)) / 2; + double nz = (listUnitaryIn.get(2) + listUnitaryOut.get(2)) / 2; return Math.abs((dx * nx + dy * ny + dz * nz) * as); } + /** * Compute an Hashmap describing the segmented object (from raw data). Key = Voxels intensity value = Number of * voxels @@ -605,21 +616,24 @@ private void histogramSegmentedNucleus() { for (int j = 0; j < this._rawImage.getHeight(); ++j) { double voxelValue = imageStackSeg.getVoxel(i, j, k); if (voxelValue == 255) { - if (!this._segmentedNucleusHisto.containsKey(imageStackRaw.getVoxel(i, j, k))) { - this._segmentedNucleusHisto.put(imageStackRaw.getVoxel(i, j, k), 1); + if (!this._segmentedNucleusHistogram.containsKey(imageStackRaw.getVoxel(i, j, k))) { + this._segmentedNucleusHistogram.put(imageStackRaw.getVoxel(i, j, k), 1); } else { - this._segmentedNucleusHisto.put(imageStackRaw.getVoxel(i, j, k), - this._segmentedNucleusHisto.get(imageStackRaw.getVoxel(i, - j, - k)) + - 1); + this._segmentedNucleusHistogram.put(imageStackRaw.getVoxel(i, j, k), + this._segmentedNucleusHistogram.get(imageStackRaw.getVoxel( + i, + j, + k)) + + 1); } } else { - if (!this._backgroundHisto.containsKey(imageStackRaw.getVoxel(i, j, k))) { - this._backgroundHisto.put(imageStackRaw.getVoxel(i, j, k), 1); + if (!this._backgroundHistogram.containsKey(imageStackRaw.getVoxel(i, j, k))) { + this._backgroundHistogram.put(imageStackRaw.getVoxel(i, j, k), 1); } else { - this._backgroundHisto.put(imageStackRaw.getVoxel(i, j, k), - this._backgroundHisto.get(imageStackRaw.getVoxel(i, j, k)) + 1); + this._backgroundHistogram.put(imageStackRaw.getVoxel(i, j, k), + this._backgroundHistogram.get(imageStackRaw.getVoxel(i, + j, + k)) + 1); } } } @@ -637,15 +651,14 @@ private void histogramSegmentedNucleus() { private double meanIntensity() { int numberOfVoxel = 0; double mean = 0; - for (Map.Entry histo2 : - this._segmentedNucleusHisto.entrySet()) { - numberOfVoxel += histo2.getValue(); - mean += histo2.getKey() * histo2.getValue(); - + for (Map.Entry histogram : this._segmentedNucleusHistogram.entrySet()) { + numberOfVoxel += histogram.getValue(); + mean += histogram.getKey() * histogram.getValue(); } return mean / numberOfVoxel; } + /** * Compute mean intensity of background * @@ -663,13 +676,11 @@ private double meanIntensityBackground() { meanIntensity += imageStackRaw.getVoxel(i, j, k); voxelCounted++; } - } } } meanIntensity = meanIntensity / voxelCounted; return meanIntensity; - } @@ -683,12 +694,9 @@ private double meanIntensityBackground() { private double standardDeviationIntensity(Double mean) { int numberOfVoxel = 0; double std = 0; - for (Map.Entry histo2 : - this._segmentedNucleusHisto.entrySet()) { - numberOfVoxel += histo2.getValue(); - std = Math.abs((histo2.getKey() * histo2.getValue()) - - (histo2.getValue() * mean)); - + for (Map.Entry histogram : this._segmentedNucleusHistogram.entrySet()) { + numberOfVoxel += histogram.getValue(); + std = Math.abs((histogram.getKey() * histogram.getValue()) - (histogram.getValue() * mean)); } return std / (numberOfVoxel - 1); @@ -704,7 +712,7 @@ private double standardDeviationIntensity(Double mean) { private double maxIntensity() { double maxIntensity = 0; for (Map.Entry entry : - this._segmentedNucleusHisto.entrySet()) { + this._segmentedNucleusHistogram.entrySet()) { if (maxIntensity == 0 || entry.getKey().compareTo(maxIntensity) > 0) { maxIntensity = entry.getKey(); } @@ -713,6 +721,7 @@ private double maxIntensity() { } + /** * Find the minimum intensity voxel of segmented object * @@ -721,7 +730,7 @@ private double maxIntensity() { private double minIntensity() { double minIntensity = 0; for (Map.Entry entry : - this._segmentedNucleusHisto.entrySet()) { + this._segmentedNucleusHistogram.entrySet()) { if (minIntensity == 0 || entry.getKey().compareTo(minIntensity) < 0) { minIntensity = entry.getKey(); } @@ -730,6 +739,7 @@ private double minIntensity() { } + /** * Compute the median intensity value of raw image voxel * @@ -739,60 +749,56 @@ public double medianComputingImage() { double voxelMedianValue = 0; Histogram histogram = new Histogram(); histogram.run(this._rawImage); - HashMap _segmentedNucleusHisto = histogram.getHistogram(); + HashMap _segmentedNucleusHistogram = histogram.getHistogram(); int medianElementStop = (this._rawImage.getHeight() * this._rawImage.getWidth() * this._rawImage.getNSlices()) / 2; int increment = 0; - for (HashMap.Entry entry : _segmentedNucleusHisto.entrySet()) { + for (HashMap.Entry entry : _segmentedNucleusHistogram.entrySet()) { increment += entry.getValue(); if (increment > medianElementStop) { voxelMedianValue = entry.getKey(); break; } - - } return voxelMedianValue; } + private double medianIntensityNucleus() { double voxelMedianValue = 0; int numberOfVoxelNucleus = 0; - for (int f : this._segmentedNucleusHisto.values()) { + for (int f : this._segmentedNucleusHistogram.values()) { numberOfVoxelNucleus += f; } int medianElementStop = (numberOfVoxelNucleus) / 2; int increment = 0; for (Map.Entry entry : - this._segmentedNucleusHisto.entrySet()) { + this._segmentedNucleusHistogram.entrySet()) { increment += entry.getValue(); if (increment > medianElementStop) { voxelMedianValue = entry.getKey(); break; } - - } return voxelMedianValue; } + private double medianIntensityBackground() { double voxelMedianValue = 0; int numberOfVoxelBackground = 0; - for (int f : this._segmentedNucleusHisto.values()) { + for (int f : this._segmentedNucleusHistogram.values()) { numberOfVoxelBackground += f; } int medianElementStop = (numberOfVoxelBackground) / 2; int increment = 0; for (Map.Entry entry : - this._backgroundHisto.entrySet()) { + this._backgroundHistogram.entrySet()) { increment += entry.getValue(); if (increment > medianElementStop) { voxelMedianValue = entry.getKey(); break; } - - } return voxelMedianValue; } @@ -804,7 +810,7 @@ private double medianIntensityBackground() { * @return list of parameters compute in this method returned in tabulated format */ public String nucleusParameter3D() { - String resu = ""; + String results; histogramSegmentedNucleus(); // double volume = computeVolumeObject2(255); @@ -812,25 +818,23 @@ public String nucleusParameter3D() { double surfaceArea = computeSurfaceObject(255); double surfaceAreaNew = computeComplexSurface(); double[] tEigenValues = computeEigenValue3D(255); - resu = this._rawImage.getTitle() + "\t" - // + computeVolumeObject2(255) + "\t" - + computeVolumeObjectML() + "\t" - + computeFlatnessAndElongation(255)[0] + "\t" - + computeFlatnessAndElongation(255)[1] + "\t" - + equivalentSphericalRadius(volume) + "\t" - + surfaceAreaNew + "\t" - + computeSphericity(volume, surfaceAreaNew) + "\t" - + meanIntensity() + "\t" - + meanIntensityBackground() + "\t" - + standardDeviationIntensity(meanIntensity()) + "\t" - + minIntensity() + "\t" - + maxIntensity() + "\t" - + medianComputingImage() + "\t" - + medianIntensityNucleus() + "\t" - + medianIntensityBackground() + "\t" - + this._rawImage.getHeight() * this._rawImage.getWidth() * this._rawImage.getNSlices() - ; - return resu; + results = this._rawImage.getTitle() + "\t" + // + computeVolumeObject2(255) + "\t" + + computeVolumeObjectML() + "\t" + + computeFlatnessAndElongation(255)[0] + "\t" + + computeFlatnessAndElongation(255)[1] + "\t" + + equivalentSphericalRadius(volume) + "\t" + + surfaceAreaNew + "\t" + + computeSphericity(volume, surfaceAreaNew) + "\t" + + meanIntensity() + "\t" + + meanIntensityBackground() + "\t" + + standardDeviationIntensity(meanIntensity()) + "\t" + + minIntensity() + "\t" + + maxIntensity() + "\t" + + medianComputingImage() + "\t" + + medianIntensityNucleus() + "\t" + + medianIntensityBackground() + "\t" + + this._rawImage.getHeight() * this._rawImage.getWidth() * this._rawImage.getNSlices(); + return results; } - } \ No newline at end of file diff --git a/src/main/java/gred/nucleus/core/NucleusChromocentersAnalysis.java b/src/main/java/gred/nucleus/core/NucleusChromocentersAnalysis.java index a75f3ff6..14619950 100644 --- a/src/main/java/gred/nucleus/core/NucleusChromocentersAnalysis.java +++ b/src/main/java/gred/nucleus/core/NucleusChromocentersAnalysis.java @@ -66,7 +66,7 @@ public void computeParameters(String rhfChoice, } if (histogram.getNbLabels() > 0) { - double[] tVolumesObjects = measure3D.computeVolumeofAllObjects(imagePlusChromocenter); + double[] tVolumesObjects = measure3D.computeVolumeOfAllObjects(imagePlusChromocenter); RadialDistance radialDistance = new RadialDistance(); double[] tBorderToBorderDistance = radialDistance.computeBorderToBorderDistances(imagePlusSegmented, imagePlusChromocenter); @@ -149,7 +149,7 @@ public void computeParameters(String pathResultsFile, text += measure3D.computeVolumeRHF(imagePlusSegmented, imagePlusChromocenter) + "\t"; } if (histogram.getNbLabels() > 0) { - double[] tVolumesObjects = measure3D.computeVolumeofAllObjects(imagePlusChromocenter); + double[] tVolumesObjects = measure3D.computeVolumeOfAllObjects(imagePlusChromocenter); double volumeCcMean = computeMeanOfTable(tVolumesObjects); int nbCc = measure3D.getNumberOfObject(imagePlusChromocenter); RadialDistance radialDistance = new RadialDistance(); @@ -172,8 +172,9 @@ public void computeParameters(String pathResultsFile, bufferedWriterOutput.close(); } + /** - * Method wich compute the mean of the value in the table + * Computes the mean of the value in the table * * @param tInput Table of value * diff --git a/src/main/java/gred/nucleus/core/NucleusSegmentation.java b/src/main/java/gred/nucleus/core/NucleusSegmentation.java index 3acf5b98..867157af 100644 --- a/src/main/java/gred/nucleus/core/NucleusSegmentation.java +++ b/src/main/java/gred/nucleus/core/NucleusSegmentation.java @@ -49,9 +49,9 @@ public class NucleusSegmentation { /** Segmentation parameters for the analyse */ private final SegmentationParameters m_segmentationParameters; /** List of the 3D parameters computed associated to the segmented image */ - public Measure3D _mesure3D; + public Measure3D _measure3D; /** Threshold detected by the Otsu modified method */ - private int _bestThreshold = -1; + private int _bestThreshold = -1; /* String stocking the file name if any nucleus is detected*/ /** volume min of the detected object */ private int _vMin; @@ -60,9 +60,9 @@ public class NucleusSegmentation { /** ImagePlus input to process */ private ImagePlus _imgRaw; /** ImagePlus input to process */ - private ImagePlus _imgRawTransformed = null; + private ImagePlus _imgRawTransformed; /** Check if the segmentation is not in border */ - private boolean _badCrop = false; + private boolean _badCrop = false; /** Current image analysed */ private File m_currentFile; /** String containing the output prefix */ @@ -93,6 +93,7 @@ public NucleusSegmentation(ImagePlus imgRaw, this._imgRawTransformed = this._imgRaw; } + /** * Constructor for the segmentation analyse for a folder containing images. * @@ -121,6 +122,7 @@ public NucleusSegmentation(File imageFile, } } + public NucleusSegmentation(ImageContainer image, SegmentationParameters segmentationParameters, Client client) throws Exception { this.m_segmentationParameters = segmentationParameters; @@ -134,6 +136,7 @@ public NucleusSegmentation(ImageContainer image, SegmentationParameters segmenta this._imgRawTransformed.setTitle(image.getName()); } + public NucleusSegmentation(ImageContainer image, ROIContainer roi, int i, @@ -162,6 +165,7 @@ public NucleusSegmentation(ImageContainer image, this._imgRawTransformed.setTitle(this._imgRaw.getTitle()); } + /** * Method to set a specific channel image * @@ -179,31 +183,35 @@ public ImagePlus getImageChannel(int channelNumber) throws Exception { return currentImage[0]; } + /** * Method to save 3D parameters computed * * @return list of 3D parameter computed */ public String saveImageResult() { - return this._mesure3D.nucleusParameter3D(); + return this._measure3D.nucleusParameter3D(); } + /** * Method to save 3D parameters computed * - * @param imageseg segmented image + * @param segmentedImage segmented image * * @return */ - public String saveImageResult(ImagePlus[] imageseg) { + public String saveImageResult(ImagePlus[] segmentedImage) { - this._mesure3D = new Measure3D(imageseg, this._imgRaw, getXcalibration(), getYcalibration(), getZcalibration()); - return this._mesure3D.nucleusParameter3D(); + this._measure3D = + new Measure3D(segmentedImage, this._imgRaw, getXcalibration(), getYcalibration(), getZcalibration()); + return this._measure3D.nucleusParameter3D(); } + /** * Method to save segmented image * @@ -215,13 +223,14 @@ private void saveFile(ImagePlus imagePlusInput, String pathFile) { fileSaver.saveAsTiffStack(pathFile); } + /** * Compute of the first threshold of input image with the method of Otsu. From this initial value we will seek the * better segmentation possible: for this we will take the voxels value superior at the threshold value of method of * Otsu : Then we compute the standard deviation of this values voxel > threshold value determines which allows - * range of value we will search the better threshold value : thresholdOtsu - ecartType et thresholdOtsu + - * ecartType. For each threshold test; we do an opening and a closing, then run the holesFilling methods. To finish - * we compute the sphericity. + * range of value we will search the better threshold value : thresholdOtsu - stdDev and thresholdOtsu + stdDev. For + * each threshold test; we do an opening and a closing, then run the holesFilling methods. To finish we compute the + * sphericity. *

* The aim of this method is to maximize the sphericity to obtain the segmented object nearest of the biological * object. @@ -230,7 +239,7 @@ private void saveFile(ImagePlus imagePlusInput, String pathFile) { * * @return ImagePlus Segmented image */ - public void findOTSUmaximisingSephericity() { + public void findOTSUMaximisingSphericity() { double imageVolume = getVoxelVolume() * this._imgRaw.getWidth() * this._imgRaw.getHeight() * this._imgRaw.getStackSize(); @@ -245,7 +254,7 @@ public void findOTSUmaximisingSephericity() { tempSeg = BinaryImages.componentsLabeling(tempSeg, 26, 32); Calibration cal = this._imgRaw.getCalibration(); if (this.m_segmentationParameters.getManualParameter()) { - //TODO AJOUTER LES UNITES + //TODO ADD UNITS cal.setXUnit("µm"); cal.pixelWidth = this.m_segmentationParameters.getXCal(); cal.setYUnit("µm"); @@ -287,17 +296,16 @@ public void findOTSUmaximisingSephericity() { this.m_imageSeg[0].setTitle(this._imgRawTransformed.getTitle()); } } - measure3D = null; } if (this._bestThreshold != -1) { morphologicalCorrection(this.m_imageSeg[0]); checkBorder(this.m_imageSeg[0]); } - } - /** Pre process ot the raw image : - Gaussian blur - LUT application TODO object fonction image transformation */ + + /** Pre process ot the raw image : - Gaussian blur - LUT application TODO object function image transformation */ public void preProcessImage() { GaussianBlur3D.blur(this._imgRawTransformed, 0.1, 0.1, 1); @@ -320,6 +328,7 @@ public void preProcessImage() { } } + /** * @param imagePlusInput * @@ -408,6 +417,7 @@ public ImagePlus generateSegmentedImage(ImagePlus imagePlusInput, int threshold) return imagePlusSegmented; } + /** * Method to check if the final segmented image got pixel on border of the image (filter of partial nucleus). * @@ -446,6 +456,7 @@ private void checkBorder(ImagePlus imagePlusInput) { } } + /** * Method to check if the nucleus is truncated (last slice or border). * @@ -455,6 +466,7 @@ public boolean isBadCrop() { return this._badCrop; } + /** * Determine of the minimum and the maximum value o find the better threshold value. * @@ -479,6 +491,7 @@ private ArrayList computeMinMaxThreshold(ImagePlus imagePlusInput) { return arrayListMinMaxThreshold; } + /** * Determines the number of pixel on the stack index in input return true if the number of pixel>=10. * @@ -507,6 +520,7 @@ private boolean isVoxelThresholded(ImagePlus imagePlusSegmented, return voxelThresolded; } + /** * method to realise morphological correction (filling holes and top hat) * @@ -517,9 +531,11 @@ private void morphologicalCorrection(ImagePlus imagePlusSegmented) { int temps = imagePlusSegmented.getBitDepth(); computeOpening(imagePlusSegmented); computeClosing(imagePlusSegmented); + // TODO FIX? imagePlusSegmented = holesFilling.apply2D(imagePlusSegmented); } + /** * Compute closing with the segmented image. * @@ -540,6 +556,7 @@ private void computeClosing(ImagePlus imagePlusInput) { imagePlusInput.setStack(imageStackInput); } + /** * Compute opening with the segmented image * @@ -560,6 +577,7 @@ private void computeOpening(ImagePlus imagePlusInput) { imagePlusInput.setStack(imageStackInput); } + /** * getter: return the threshold value computed * @@ -569,6 +587,7 @@ public int getBestThreshold() { return _bestThreshold; } + /** * Method to detected if the object is superior or equal at 70% of the image return false. * @@ -581,6 +600,7 @@ private boolean testRelativeObjectVolume(double objectVolume, double imageVolume return !(ratio >= 70); } + /** * Keep the bigger object in the image at 255 put the other at 0. * @@ -604,6 +624,7 @@ private void deleteArtefact(ImagePlus imgSeg) { } } + /** * Detection of the label of the biggest object segmented in the image * @@ -627,6 +648,7 @@ private double getLabelOfLargestObject(ImagePlus imgSeg) { return labelMax; } + /** * Method to get X calibration if it's present in parameters of analyse or get the metadata of the image. TODO * verifier cette methode si elle est au bonne endroit @@ -643,6 +665,7 @@ public double getXcalibration() { return xCal; } + /** * Method to get Y calibration if it's present in parameters of analyse or get the metadata of the image. TODO * verifier cette methode si elle est au bonne endroit @@ -659,6 +682,7 @@ public double getYcalibration() { return yCal; } + /** * Method to get Y calibration if it's present in parameters of analyse or get the metadata of the image. TODO * verifier cette methode si elle est à ca place @@ -675,6 +699,7 @@ public double getZcalibration() { return zCal; } + /** * Method to compute the voxel volume : if it's present in parameters of analyse or get the metadata of the image. * TODO verifier cette methode si elle est à ca place @@ -682,7 +707,7 @@ public double getZcalibration() { * @return Z calibration */ public double getVoxelVolume() { - double calibration = 0; + double calibration; if (this.m_segmentationParameters.m_manualParameter) { calibration = m_segmentationParameters.getVoxelVolume(); } else { @@ -693,6 +718,7 @@ public double getVoxelVolume() { return calibration; } + /** * Method to move bad crop (truncated nucleus) to badcrop folder. * @@ -701,7 +727,7 @@ public double getVoxelVolume() { */ public void checkBadCrop(String inputPathDir) { if ((this._badCrop) || (this.getBestThreshold() == -1)) { - File file = new File(inputPathDir); + File file = new File(inputPathDir); File BadCropFolder = new File(inputPathDir + File.separator + "BadCrop"); System.out.println("et du coup on est dedans ou quoi ...........\n" + BadCropFolder + @@ -715,6 +741,7 @@ public void checkBadCrop(String inputPathDir) { } } + public void checkBadCrop(ImageContainer image, Client client) throws ServerError, DSOutOfServiceException, ExecutionException, DSAccessException { if ((this._badCrop) || (this.getBestThreshold() == -1)) { @@ -736,6 +763,7 @@ public void checkBadCrop(ImageContainer image, Client client) } } + public void checkBadCrop(ROIContainer roi, Client client) throws ServerError, DSOutOfServiceException { @@ -747,6 +775,7 @@ public void checkBadCrop(ROIContainer roi, roi.saveROI(client); } + /** Method to save the OTSU segmented image. TODO verifier cette methode si elle est à ca place */ public void saveOTSUSegmented() { if (!isBadCrop() && getBestThreshold() != -1) { @@ -759,11 +788,12 @@ public void saveOTSUSegmented() { } } + /** Method to save the OTSU segmented image. TODO verifier cette methode si elle est à ca place */ public void saveOTSUSegmentedOmero(Client client, Long id) throws Exception { if (!isBadCrop() && getBestThreshold() != -1) { - String path = new java.io.File(".").getCanonicalPath() + "/" + this.m_imageSeg[0].getTitle(); + String path = new java.io.File(".").getCanonicalPath() + File.separator + this.m_imageSeg[0].getTitle(); saveFile(this.m_imageSeg[0], path); ProjectContainer project = client.getProject(id); @@ -785,6 +815,7 @@ public void saveOTSUSegmentedOmero(Client client, Long id) } } + /** Method to save the OTSU segmented image. TODO verifier cette methode si elle est à ca place */ public void saveGiftWrappingSeg() { @@ -799,6 +830,7 @@ public void saveGiftWrappingSeg() { } } + /** Method to save the OTSU segmented image. TODO verifier cette methode si elle est à ca place */ public void saveGiftWrappingSegOmero(Client client, Long id) throws Exception { @@ -808,7 +840,7 @@ public void saveGiftWrappingSegOmero(Client client, Long id) this.m_imageSeg[0] = nuc.runGIFTWrapping(this.m_imageSeg[0], this.m_segmentationParameters); - String path = new java.io.File(".").getCanonicalPath() + "/" + this.m_imageSeg[0].getTitle(); + String path = new java.io.File(".").getCanonicalPath() + File.separator + this.m_imageSeg[0].getTitle(); saveFile(this.m_imageSeg[0], path); ProjectContainer project = client.getProject(id); @@ -830,6 +862,7 @@ public void saveGiftWrappingSegOmero(Client client, Long id) } } + /** * Method to get the parameter of the 3D parameters for OTSU segmented image if the object can't be segmented return * -1 for parameters. TODO verifier cette methode si elle est à ca place @@ -844,6 +877,7 @@ public String getImageCropInfoOTSU() { } } + /** * Method to get the parameter of the 3D parameters for Gift wrapping segmented image if the object can't be * segmented return -1 for parameters. TODO verifier DUPLICATION DE getImageCropInfoOTSU TODO a ca place ? diff --git a/src/main/java/gred/nucleus/core/RadialDistance.java b/src/main/java/gred/nucleus/core/RadialDistance.java index b3adf04d..402bd130 100644 --- a/src/main/java/gred/nucleus/core/RadialDistance.java +++ b/src/main/java/gred/nucleus/core/RadialDistance.java @@ -33,6 +33,7 @@ public ImagePlus computeDistanceMap(ImagePlus imagePlusSegmentedRescaled) { return imagePlusSegmentedRescaled; } + /** * Compute the shortest distance between the chromocenter periphery and the nuclear envelope * @@ -74,9 +75,10 @@ public double[] computeBorderToBorderDistances(ImagePlus imagePlusSegmented, return tDistanceRadial; } + /** - * Determine the radial distance of all chromocenter in the image of nucleus We realise the distance map on the - * bianary nucleus. This method measure the radial distance between the barycenter of chromocenter and the nuclear + * Determines the radial distance of all chromocenter in the image of nucleus We realise the distance map on the + * binary nucleus. This method measure the radial distance between the barycenter of chromocenter and the nuclear * envelope. * * @param imagePlusSegmented @@ -84,9 +86,7 @@ public double[] computeBorderToBorderDistances(ImagePlus imagePlusSegmented, * * @return */ - public double[] computeBarycenterToBorderDistances( - ImagePlus imagePlusSegmented, - ImagePlus imagePlusChromocenter) { + public double[] computeBarycenterToBorderDistances(ImagePlus imagePlusSegmented, ImagePlus imagePlusChromocenter) { Calibration calibration = imagePlusSegmented.getCalibration(); double xCalibration = calibration.pixelWidth; ImagePlus imagePlusChromocenterRescale = @@ -99,7 +99,7 @@ public double[] computeBarycenterToBorderDistances( VoxelRecord[] tVoxelRecord = measure3D.computeObjectBarycenter( imagePlusChromocenterRescale, false); double[] tRadialDistance = new double[tVoxelRecord.length]; - double distance = -50; + double distance; for (int i = 0; i < tVoxelRecord.length; ++i) { VoxelRecord voxelRecord = tVoxelRecord[i]; distance = imageStackDistanceMap.getVoxel( @@ -111,6 +111,7 @@ public double[] computeBarycenterToBorderDistances( return tRadialDistance; } + /** * Resize the input image to obtain isotropic voxel * diff --git a/src/main/java/gred/nucleus/dialogs/AutocropConfigDialog.java b/src/main/java/gred/nucleus/dialogs/AutocropConfigDialog.java index ba6238f4..25f57c9e 100644 --- a/src/main/java/gred/nucleus/dialogs/AutocropConfigDialog.java +++ b/src/main/java/gred/nucleus/dialogs/AutocropConfigDialog.java @@ -18,25 +18,21 @@ public class AutocropConfigDialog extends JFrame implements ItemListener { private final JTextField maxVolume = new JTextField(); private final JTextField thresholdOTSUComputing = new JTextField(); private final JTextField channelToComputeThreshold = new JTextField(); - private final JTextField slicesOTSUcomputing = new JTextField(); + private final JTextField slicesOTSUComputing = new JTextField(); private final JTextField boxesPercentSurfaceToFilter = new JTextField(); - private final JCheckBox boxesRegroupement = new JCheckBox(); - private final JCheckBox addCalibBox = new JCheckBox(); - private final Container _container; - private final JButton buttonOK = new JButton("Done"); + private final JCheckBox regroupBoxes = new JCheckBox(); + private final JCheckBox addCalibrationBox = new JCheckBox(); private final JPanel cropBoxPane; - private final AutocropDialog caller; - private Boolean isBoxesRegroupementSelected = true; - private JPanel XCalib; - private JPanel YCalib; - private JPanel ZCalib; + private Boolean isRegroupBoxesSelected = true; + private JPanel XCalibration; + private JPanel YCalibration; + private JPanel ZCalibration; public AutocropConfigDialog(AutocropDialog caller) { - this.caller = caller; this.setTitle("Autocrop NucleusJ2"); this.setSize(500, 350); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); - _container = getContentPane(); + Container _container = getContentPane(); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.rowWeights = new double[]{1.0}; gridBagLayout.rowHeights = new int[]{300}; @@ -44,6 +40,7 @@ public AutocropConfigDialog(AutocropDialog caller) { gridBagLayout.columnWidths = new int[]{180, 500}; _container.setLayout(gridBagLayout); + JButton buttonOK = new JButton("Done"); getRootPane().setDefaultButton(buttonOK); @@ -101,15 +98,15 @@ public AutocropConfigDialog(AutocropDialog caller) { \*\/*/ - JPanel calibPanel = new JPanel(); - JLabel calibLabel = new JLabel("Calibration:"); - calibLabel.setAlignmentX(0); - calibPanel.add(calibLabel); - addCalibBox.setSelected(false); - addCalibBox.setMinimumSize(new Dimension(100, 10)); - addCalibBox.addItemListener(this); - calibPanel.add(addCalibBox); - cropBoxPane.add(calibPanel); + JPanel calibrationPanel = new JPanel(); + JLabel calibrationLabel = new JLabel("Calibration:"); + calibrationLabel.setAlignmentX(0); + calibrationPanel.add(calibrationLabel); + addCalibrationBox.setSelected(false); + addCalibrationBox.setMinimumSize(new Dimension(100, 10)); + addCalibrationBox.addItemListener(this); + calibrationPanel.add(addCalibrationBox); + cropBoxPane.add(calibrationPanel); _container.add(cropBoxPane, new GridBagConstraints(0, 0, @@ -168,15 +165,15 @@ public AutocropConfigDialog(AutocropDialog caller) { \*\/*/ - JPanel thresholdOSTUcomputingPanel = new JPanel(); - thresholdOSTUcomputingPanel.setLayout(new BoxLayout(thresholdOSTUcomputingPanel, BoxLayout.X_AXIS)); - thresholdOSTUcomputingPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); - JLabel tOTSUValue = new JLabel("Threshold OSTU computing:"); - thresholdOSTUcomputingPanel.add(tOTSUValue); - thresholdOSTUcomputingPanel.add(Box.createRigidArea(new Dimension(10, 0))); + JPanel thresholdOTSUComputingPanel = new JPanel(); + thresholdOTSUComputingPanel.setLayout(new BoxLayout(thresholdOTSUComputingPanel, BoxLayout.X_AXIS)); + thresholdOTSUComputingPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); + JLabel tOTSUValue = new JLabel("Threshold OTSU computing:"); + thresholdOTSUComputingPanel.add(tOTSUValue); + thresholdOTSUComputingPanel.add(Box.createRigidArea(new Dimension(10, 0))); thresholdOTSUComputing.setText("20"); thresholdOTSUComputing.setMinimumSize(new Dimension(100, 10)); - thresholdOSTUcomputingPanel.add(thresholdOTSUComputing); + thresholdOTSUComputingPanel.add(thresholdOTSUComputing); JPanel channelToComputeThresholdPanel = new JPanel(); channelToComputeThresholdPanel.setLayout(new BoxLayout(channelToComputeThresholdPanel, BoxLayout.X_AXIS)); @@ -188,15 +185,15 @@ public AutocropConfigDialog(AutocropDialog caller) { channelToComputeThreshold.setMinimumSize(new Dimension(100, 10)); channelToComputeThresholdPanel.add(channelToComputeThreshold); - JPanel slicesOTSUcomputingPanel = new JPanel(); - slicesOTSUcomputingPanel.setLayout(new BoxLayout(slicesOTSUcomputingPanel, BoxLayout.X_AXIS)); - slicesOTSUcomputingPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); + JPanel slicesOTSUComputingPanel = new JPanel(); + slicesOTSUComputingPanel.setLayout(new BoxLayout(slicesOTSUComputingPanel, BoxLayout.X_AXIS)); + slicesOTSUComputingPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); JLabel slicesOTSUValue = new JLabel("Slices OTSU computing:"); - slicesOTSUcomputingPanel.add(slicesOTSUValue); - slicesOTSUcomputingPanel.add(Box.createRigidArea(new Dimension(10, 0))); - slicesOTSUcomputing.setText("0"); - slicesOTSUcomputing.setMinimumSize(new Dimension(100, 10)); - slicesOTSUcomputingPanel.add(slicesOTSUcomputing); + slicesOTSUComputingPanel.add(slicesOTSUValue); + slicesOTSUComputingPanel.add(Box.createRigidArea(new Dimension(10, 0))); + slicesOTSUComputing.setText("0"); + slicesOTSUComputing.setMinimumSize(new Dimension(100, 10)); + slicesOTSUComputingPanel.add(slicesOTSUComputing); JPanel boxesPercentSurfacePanel = new JPanel(); boxesPercentSurfacePanel.setLayout(new BoxLayout(boxesPercentSurfacePanel, BoxLayout.X_AXIS)); @@ -208,22 +205,22 @@ public AutocropConfigDialog(AutocropDialog caller) { boxesPercentSurfaceToFilter.setMinimumSize(new Dimension(100, 10)); boxesPercentSurfacePanel.add(boxesPercentSurfaceToFilter); - JPanel boxesRegroupementPanel = new JPanel(); - boxesRegroupementPanel.setLayout(new BoxLayout(boxesRegroupementPanel, BoxLayout.X_AXIS)); - boxesRegroupementPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); - JLabel boxesRegroupementValue = new JLabel("Boxes regroupement:"); - boxesRegroupementPanel.add(boxesRegroupementValue); - boxesRegroupementPanel.add(Box.createRigidArea(new Dimension(10, 0))); - boxesRegroupement.setSelected(true); - boxesRegroupement.setMinimumSize(new Dimension(100, 10)); - boxesRegroupement.addItemListener(this); - boxesRegroupementPanel.add(boxesRegroupement); + JPanel regroupBoxesPanel = new JPanel(); + regroupBoxesPanel.setLayout(new BoxLayout(regroupBoxesPanel, BoxLayout.X_AXIS)); + regroupBoxesPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); + JLabel regroupBoxesValue = new JLabel("Boxes regrouping:"); + regroupBoxesPanel.add(regroupBoxesValue); + regroupBoxesPanel.add(Box.createRigidArea(new Dimension(10, 0))); + regroupBoxes.setSelected(true); + regroupBoxes.setMinimumSize(new Dimension(100, 10)); + regroupBoxes.addItemListener(this); + regroupBoxesPanel.add(regroupBoxes); - volumeNucleus.add(thresholdOSTUcomputingPanel); + volumeNucleus.add(thresholdOTSUComputingPanel); volumeNucleus.add(channelToComputeThresholdPanel); - volumeNucleus.add(slicesOTSUcomputingPanel); + volumeNucleus.add(slicesOTSUComputingPanel); volumeNucleus.add(boxesPercentSurfacePanel); - volumeNucleus.add(boxesRegroupementPanel); + volumeNucleus.add(regroupBoxesPanel); @@ -251,112 +248,126 @@ public AutocropConfigDialog(AutocropDialog caller) { this.setVisible(false); - AutocropConfigDialog.StartListener startListener = new AutocropConfigDialog.StartListener(this); + AutocropConfigDialog.StartListener startListener = new StartListener(this); buttonOK.addActionListener(startListener); } - public String getxCropBoxSize() { + + public String getXCropBoxSize() { return xCropBoxSize.getText(); } - public String getyCropBoxSize() { + + public String getYCropBoxSize() { return yCropBoxSize.getText(); } - public String getzCropBoxSize() { + + public String getZCropBoxSize() { return zCropBoxSize.getText(); } - public String getxCalibration() { + + public String getXCalibration() { return xCalibration.getText(); } - public String getyCalibration() { + + public String getYCalibration() { return yCalibration.getText(); } - public String getzCalibration() { + + public String getZCalibration() { return zCalibration.getText(); } + public String getMinVolume() { return minVolume.getText(); } + public String getMaxVolume() { return maxVolume.getText(); } + public String getThresholdOTSUComputing() { return thresholdOTSUComputing.getText(); } + public String getChannelToComputeThreshold() { return channelToComputeThreshold.getText(); } - public String getSlicesOTSUcomputing() { - return slicesOTSUcomputing.getText(); + + public String getSlicesOTSUComputing() { + return slicesOTSUComputing.getText(); } + public String getBoxesPercentSurfaceToFilter() { return boxesPercentSurfaceToFilter.getText(); } - public boolean getBoxesRegroupementSelected() { - return isBoxesRegroupementSelected; + + public boolean isRegroupBoxesSelected() { + return isRegroupBoxesSelected; } - public boolean isCalibSelected() { - return addCalibBox.isSelected(); + + public boolean isCalibrationSelected() { + return addCalibrationBox.isSelected(); } @Override public void itemStateChanged(ItemEvent e) { - if (e.getSource() == boxesRegroupement) { - isBoxesRegroupementSelected = boxesRegroupement.isSelected(); - } else if (e.getSource() == addCalibBox) { - if (addCalibBox.isSelected()) { + if (e.getSource() == regroupBoxes) { + isRegroupBoxesSelected = regroupBoxes.isSelected(); + } else if (e.getSource() == addCalibrationBox) { + if (addCalibrationBox.isSelected()) { - XCalib = new JPanel(); - XCalib.setLayout(new BoxLayout(XCalib, BoxLayout.X_AXIS)); - XCalib.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); + XCalibration = new JPanel(); + XCalibration.setLayout(new BoxLayout(XCalibration, BoxLayout.X_AXIS)); + XCalibration.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); JLabel xBox2 = new JLabel("X:"); - XCalib.add(xBox2); - XCalib.add(Box.createRigidArea(new Dimension(10, 0))); + XCalibration.add(xBox2); + XCalibration.add(Box.createRigidArea(new Dimension(10, 0))); xCalibration.setText("1"); xCalibration.setMinimumSize(new Dimension(60, 10)); - XCalib.add(xCalibration); + XCalibration.add(xCalibration); - YCalib = new JPanel(); - YCalib.setLayout(new BoxLayout(YCalib, BoxLayout.X_AXIS)); - YCalib.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); + YCalibration = new JPanel(); + YCalibration.setLayout(new BoxLayout(YCalibration, BoxLayout.X_AXIS)); + YCalibration.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); JLabel yBox2 = new JLabel("Y:"); - YCalib.add(yBox2); - YCalib.add(Box.createRigidArea(new Dimension(10, 0))); + YCalibration.add(yBox2); + YCalibration.add(Box.createRigidArea(new Dimension(10, 0))); yCalibration.setText("1"); yCalibration.setMinimumSize(new Dimension(60, 10)); - YCalib.add(yCalibration); + YCalibration.add(yCalibration); - ZCalib = new JPanel(); - ZCalib.setLayout(new BoxLayout(ZCalib, BoxLayout.X_AXIS)); - ZCalib.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); + ZCalibration = new JPanel(); + ZCalibration.setLayout(new BoxLayout(ZCalibration, BoxLayout.X_AXIS)); + ZCalibration.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); JLabel zBox2 = new JLabel("Z:"); - ZCalib.add(zBox2); - ZCalib.add(Box.createRigidArea(new Dimension(10, 0))); + ZCalibration.add(zBox2); + ZCalibration.add(Box.createRigidArea(new Dimension(10, 0))); zCalibration.setText("1"); zCalibration.setMinimumSize(new Dimension(60, 10)); - ZCalib.add(zCalibration); + ZCalibration.add(zCalibration); - cropBoxPane.add(XCalib); - cropBoxPane.add(YCalib); - cropBoxPane.add(ZCalib); + cropBoxPane.add(XCalibration); + cropBoxPane.add(YCalibration); + cropBoxPane.add(ZCalibration); } else { try { - cropBoxPane.remove(XCalib); - cropBoxPane.remove(YCalib); - cropBoxPane.remove(ZCalib); + cropBoxPane.remove(XCalibration); + cropBoxPane.remove(YCalibration); + cropBoxPane.remove(ZCalibration); } catch (NullPointerException nullPointerException) { // Do nothing } @@ -367,14 +378,15 @@ public void itemStateChanged(ItemEvent e) { } - class StartListener implements ActionListener { + static class StartListener implements ActionListener { AutocropConfigDialog _autocropDialog; - /** @param autocropDialog */ + /** @param autocropDialog */ public StartListener(AutocropConfigDialog autocropDialog) { _autocropDialog = autocropDialog; } + public void actionPerformed(ActionEvent actionEvent) { _autocropDialog.setVisible(false); } diff --git a/src/main/java/gred/nucleus/dialogs/AutocropDialog.java b/src/main/java/gred/nucleus/dialogs/AutocropDialog.java index a87ab6ed..30c569c7 100644 --- a/src/main/java/gred/nucleus/dialogs/AutocropDialog.java +++ b/src/main/java/gred/nucleus/dialogs/AutocropDialog.java @@ -10,42 +10,30 @@ public class AutocropDialog extends JFrame implements ActionListener, ItemListener { - private static final long serialVersionUID = 1L; - static private final String newline = "\n"; - private final JButton _jButtonStart = new JButton("Start"); - private final JButton _jButtonQuit = new JButton("Quit"); - private final JButton _jButtonConfig = new JButton("Config"); - private final Container _container; - private final JLabel _jLabelOutput; - private final JLabel _jLabelConfig; - private final JLabel _jLabelInput; - private final JTextField _jInputFileChooser = new JTextField(); - private final JTextField _jOutputFileChooser = new JTextField(); - private final JTextField _jConfigFileChooser = new JTextField(); - private final JFileChooser fc = new JFileChooser(); - private final JCheckBox addConfigBox = new JCheckBox(); - private final JButton sourceButton; - private final JButton destButton; - private final JLabel defConf = new JLabel("Default configuration"); - private final AutocropConfigDialog autocropConfigFileDialog; - private final ButtonGroup buttonGroup = new ButtonGroup(); - private final JRadioButton rdoDefault = new JRadioButton(); - private final JRadioButton rdoAddConfigFile = new JRadioButton(); - private final JRadioButton rdoAddConfigDialog = new JRadioButton(); - private final String inputChooserName = "inputChooser"; - private final String outputChooserName = "outputChooser"; - private final String configChooserName = "configChooser"; - private boolean _start = false; - private JButton confButton; - private int configMode = 0; - private boolean manualConfig = false; - private File selectedInput; - private File selectedOutput; - private File selectedConfig; + private static final long serialVersionUID = 1L; + private final JButton _jButtonConfig = new JButton("Config"); + private final Container _container; + private final JTextField _jInputFileChooser = new JTextField(); + private final JTextField _jOutputFileChooser = new JTextField(); + private final JTextField _jConfigFileChooser = new JTextField(); + private final JFileChooser fc = new JFileChooser(); + private final JLabel defConf = new JLabel("Default configuration"); + private final AutocropConfigDialog autocropConfigFileDialog; + private final JRadioButton rdoDefault = new JRadioButton(); + private final JRadioButton rdoAddConfigFile = new JRadioButton(); + private final JRadioButton rdoAddConfigDialog = new JRadioButton(); + private final String inputChooserName = "inputChooser"; + private final String outputChooserName = "outputChooser"; + private final String configChooserName = "configChooser"; + private boolean _start = false; + private JButton confButton; + private int configMode = 0; /** Architecture of the graphical windows */ public AutocropDialog() { + JButton jButtonStart = new JButton("Start"); + JButton jButtonQuit = new JButton("Quit"); this.setTitle("Autocrop NucleusJ2"); this.setSize(500, 300); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); @@ -58,111 +46,207 @@ public AutocropDialog() { gridBagLayout.columnWeights = new double[]{0.0, 0.0}; gridBagLayout.columnWidths = new int[]{250, 250}; _container.setLayout(gridBagLayout); - - _jLabelInput = new JLabel(); - _container.add(_jLabelInput, new GridBagConstraints(0, 0, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(10, 10, 0, 0), 0, 0)); - _jLabelInput.setText("Input directory:"); - - _container.add(_jInputFileChooser, new GridBagConstraints(0, 0, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(30, 10, 0, 0), 0, 0)); + JLabel jLabelInput = new JLabel(); + _container.add(jLabelInput, + new GridBagConstraints(0, + 0, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(10, 10, 0, 0), + 0, + 0)); + jLabelInput.setText("Input directory:"); + _container.add(_jInputFileChooser, + new GridBagConstraints(0, + 0, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(30, 10, 0, 0), + 0, + 0)); _jInputFileChooser.setPreferredSize(new java.awt.Dimension(300, 20)); _jInputFileChooser.setMinimumSize(new java.awt.Dimension(300, 20)); - - sourceButton = new JButton("..."); - _container.add(sourceButton, new GridBagConstraints(0, 0, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(30, 330, 0, 0), 0, 0)); + JButton sourceButton = new JButton("..."); + _container.add(sourceButton, + new GridBagConstraints(0, + 0, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(30, 330, 0, 0), + 0, + 0)); sourceButton.addActionListener(this); sourceButton.setName(inputChooserName); - - _jLabelOutput = new JLabel(); - _container.add(_jLabelOutput, new GridBagConstraints(0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(10, 10, 0, 0), 0, 0)); - _jLabelOutput.setText("Output directory:"); - _container.add(_jOutputFileChooser, new GridBagConstraints(0, - 1, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(30, 10, 0, 0), - 0, - 0)); + JLabel jLabelOutput = new JLabel(); + _container.add(jLabelOutput, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(10, 10, 0, 0), + 0, + 0)); + jLabelOutput.setText("Output directory:"); + _container.add(_jOutputFileChooser, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(30, 10, 0, 0), + 0, + 0)); _jOutputFileChooser.setPreferredSize(new java.awt.Dimension(300, 20)); _jOutputFileChooser.setMinimumSize(new java.awt.Dimension(300, 20)); - - destButton = new JButton("..."); - _container.add(destButton, new GridBagConstraints(0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(30, 330, 0, 0), 0, 0)); + JButton destButton = new JButton("..."); + _container.add(destButton, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(30, 330, 0, 0), + 0, + 0)); destButton.addActionListener(this); destButton.setName(outputChooserName); - - _jLabelConfig = new JLabel(); - _container.add(_jLabelConfig, new GridBagConstraints(0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(10, 10, 0, 0), 0, 0)); - _jLabelConfig.setText("Config file (optional):"); + JLabel jLabelConfig = new JLabel(); + _container.add(jLabelConfig, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(10, 10, 0, 0), + 0, + 0)); + jLabelConfig.setText("Config file (optional):"); // _container.add(addConfigBox, new GridBagConstraints(0, 2, 0, 0, 0.0, 0.0, // GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, // new Insets(10, 200, 0, 0), 0, 0)); // addConfigBox.addItemListener(this); + ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(rdoDefault); rdoDefault.setSelected(true); rdoDefault.addItemListener(this); itemStateChanged(new ItemEvent(rdoDefault, 0, rdoDefault, ItemEvent.SELECTED)); - _container.add(rdoDefault, new GridBagConstraints(0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(10, 200, 0, 0), 0, 0)); + _container.add(rdoDefault, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(10, 200, 0, 0), + 0, + 0)); buttonGroup.add(rdoAddConfigDialog); rdoAddConfigDialog.addItemListener(this); - _container.add(rdoAddConfigDialog, new GridBagConstraints(0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(10, 230, 0, 0), 0, 0)); + _container.add(rdoAddConfigDialog, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(10, 230, 0, 0), + 0, + 0)); buttonGroup.add(rdoAddConfigFile); rdoAddConfigFile.addItemListener(this); - _container.add(rdoAddConfigFile, new GridBagConstraints(0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(10, 260, 0, 0), 0, 0)); - - - _container.add(_jButtonStart, new GridBagConstraints(0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(40, 80, 0, 0), 0, 0)); - _jButtonStart.setPreferredSize(new java.awt.Dimension(60, 21)); - _container.add(_jButtonQuit, new GridBagConstraints(0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(40, 10, 0, 0), 0, 0)); - _jButtonQuit.setPreferredSize(new java.awt.Dimension(60, 21)); + _container.add(rdoAddConfigFile, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(10, 260, 0, 0), + 0, + 0)); + _container.add(jButtonStart, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 80, 0, 0), + 0, + 0)); + jButtonStart.setPreferredSize(new java.awt.Dimension(60, 21)); + _container.add(jButtonQuit, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 10, 0, 0), + 0, + 0)); + jButtonQuit.setPreferredSize(new java.awt.Dimension(60, 21)); this.setVisible(true); - AutocropDialog.QuitListener quitListener = new AutocropDialog.QuitListener(this); - _jButtonQuit.addActionListener(quitListener); + jButtonQuit.addActionListener(quitListener); AutocropDialog.StartListener startListener = new AutocropDialog.StartListener(this); - _jButtonStart.addActionListener(startListener); + jButtonStart.addActionListener(startListener); AutocropDialog.ConfigListener configListener = new AutocropDialog.ConfigListener(this); _jButtonConfig.addActionListener(configListener); } + public boolean isStart() { return _start; } + public String getInput() { return _jInputFileChooser.getText(); } + public String getOutput() { return _jOutputFileChooser.getText(); } + public String getConfig() { return _jConfigFileChooser.getText(); } @@ -172,10 +256,12 @@ public int getConfigMode() { return configMode; } + public AutocropConfigDialog getAutocropConfigFileDialog() { return autocropConfigFileDialog; } + public void actionPerformed(ActionEvent e) { switch (((JButton) e.getSource()).getName()) { case inputChooserName: @@ -193,15 +279,15 @@ public void actionPerformed(ActionEvent e) { if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { switch (((JButton) e.getSource()).getName()) { case inputChooserName: - selectedInput = fc.getSelectedFile(); + File selectedInput = fc.getSelectedFile(); _jInputFileChooser.setText(selectedInput.getPath()); break; case outputChooserName: - selectedOutput = fc.getSelectedFile(); + File selectedOutput = fc.getSelectedFile(); _jOutputFileChooser.setText(selectedOutput.getPath()); break; case configChooserName: - selectedConfig = fc.getSelectedFile(); + File selectedConfig = fc.getSelectedFile(); _jConfigFileChooser.setText(selectedConfig.getPath()); break; } @@ -215,50 +301,71 @@ public void itemStateChanged(ItemEvent e) { _container.remove(defConf); } else if (configMode == 1) { _container.remove(_jButtonConfig); - if (autocropConfigFileDialog.isVisible()) { - autocropConfigFileDialog.setVisible(false); - } + if (autocropConfigFileDialog.isVisible()) autocropConfigFileDialog.setVisible(false); } else if (configMode == 2) { _container.remove(_jConfigFileChooser); _container.remove(confButton); } - - Object source = e.getSource(); + Object source = e.getSource(); if (source == rdoDefault) { - _container.add(defConf, new GridBagConstraints(0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(40, 10, 0, 0), 0, 0)); + _container.add(defConf, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 10, 0, 0), + 0, + 0)); configMode = 0; - manualConfig = false; } else if (source == rdoAddConfigDialog) { - _container.add(_jButtonConfig, new GridBagConstraints(0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(40, 10, 0, 0), 0, 0)); - manualConfig = true; + _container.add(_jButtonConfig, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 10, 0, 0), + 0, + 0)); configMode = 1; } else if (source == rdoAddConfigFile) { - _container.add(_jConfigFileChooser, new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(40, 10, 0, 0), - 0, - 0)); + _container.add(_jConfigFileChooser, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 10, 0, 0), + 0, + 0)); _jConfigFileChooser.setPreferredSize(new java.awt.Dimension(300, 20)); _jConfigFileChooser.setMinimumSize(new java.awt.Dimension(300, 20)); - confButton = new JButton("..."); - _container.add(confButton, new GridBagConstraints(0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, - new Insets(40, 330, 0, 0), 0, 0)); + _container.add(confButton, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 330, 0, 0), + 0, + 0)); confButton.addActionListener(this); confButton.setName(configChooserName); configMode = 2; - manualConfig = false; } /*if(addConfigBox.isSelected()){ @@ -282,16 +389,18 @@ public void itemStateChanged(ItemEvent e) { repaint(); } + /** Classes listener to interact with the several elements of the window */ class StartListener implements ActionListener { - AutocropDialog _autocropDialog; + final AutocropDialog _autocropDialog; - /** @param autocropDialog */ + /** @param autocropDialog */ public StartListener(AutocropDialog autocropDialog) { - _autocropDialog = autocropDialog; + this._autocropDialog = autocropDialog; } + public void actionPerformed(ActionEvent actionEvent) { _start = true; _autocropDialog.dispose(); @@ -300,13 +409,14 @@ public void actionPerformed(ActionEvent actionEvent) { } class QuitListener implements ActionListener { - AutocropDialog _autocropDialog; + final AutocropDialog _autocropDialog; - /** @param autocropDialog */ + /** @param autocropDialog */ public QuitListener(AutocropDialog autocropDialog) { - _autocropDialog = autocropDialog; + this._autocropDialog = autocropDialog; } + public void actionPerformed(ActionEvent actionEvent) { _autocropDialog.dispose(); autocropConfigFileDialog.dispose(); @@ -314,13 +424,14 @@ public void actionPerformed(ActionEvent actionEvent) { } class ConfigListener implements ActionListener { - AutocropDialog _autocropDialog; + final AutocropDialog _autocropDialog; - /** @param autocropDialog */ + /** @param autocropDialog */ public ConfigListener(AutocropDialog autocropDialog) { - _autocropDialog = autocropDialog; + this._autocropDialog = autocropDialog; } + public void actionPerformed(ActionEvent actionEvent) { autocropConfigFileDialog.setVisible(true); } diff --git a/src/main/java/gred/nucleus/dialogs/ChromocenterSegmentationPipelineBatchDialog.java b/src/main/java/gred/nucleus/dialogs/ChromocenterSegmentationPipelineBatchDialog.java index 33638069..6846cdcc 100644 --- a/src/main/java/gred/nucleus/dialogs/ChromocenterSegmentationPipelineBatchDialog.java +++ b/src/main/java/gred/nucleus/dialogs/ChromocenterSegmentationPipelineBatchDialog.java @@ -14,73 +14,58 @@ */ public class ChromocenterSegmentationPipelineBatchDialog extends JFrame implements ItemListener { private static final long serialVersionUID = 1L; - private JButton _jButtonWorkDirectory = new JButton("Output Directory"); - private JButton _jButtonStart = new JButton("Start"); - private JButton _jButtonQuit = new JButton("Quit"); - private JButton _JButtonRawData = new JButton("Raw Data"); - private Container _container; - private JFormattedTextField _jTextFieldXCalibration = new JFormattedTextField(Number.class); - private JFormattedTextField _jTextFieldYCalibration = new JFormattedTextField(Number.class); - private JFormattedTextField _jTextFieldZCalibration = new JFormattedTextField(Number.class); - private JTextField _jTextFieldUnit = new JTextField(); - private JTextField _jTextFieldWorkDirectory = new JTextField(); - private JTextField _jTextFieldRawData = new JTextField(); - private JLabel _jLabelXcalibration; - private JLabel _jLabelYcalibration; - private JLabel _jLabelZcalibration; - private JLabel _jLabelUnit; - private JLabel _jLabelWorkDirectory; - private JLabel _jLabelCalibration; - private String _workDirectory; - private String _rawDataDirectory; + private final JTextField _jTextFieldWorkDirectory = new JTextField(); + private final JTextField _jTextFieldRawData = new JTextField(); + private final JLabel _jLabelUnit = new JLabel(); + private final JLabel _jLabelXCalibration = new JLabel(); + private final JLabel _jLabelYCalibration = new JLabel(); + private final JLabel _jLabelZCalibration = new JLabel(); + private final JTextPane _readUnit = new JTextPane(); + private final JTextPane _readXCalibration = new JTextPane(); + private final JTextPane _readYCalibration = new JTextPane(); + private final JTextPane _readZCalibration = new JTextPane(); + private final JCheckBox _addCalibrationBox = new JCheckBox(); + private final JPanel _calibration; + private final JFormattedTextField _jTextFieldXCalibration = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldYCalibration = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldZCalibration = new JFormattedTextField(Number.class); + private final JTextField _jTextFieldUnit = new JTextField(); private boolean _start = false; - private JTextField xCalibration = new JTextField(); - private JTextField yCalibration = new JTextField(); - private JTextField zCalibration = new JTextField(); - - - private JPanel Calib; - - private JTextPane unitRead = new JTextPane(); - private JLabel unit = new JLabel(); - - private JLabel calibx = new JLabel(); - private JLabel caliby = new JLabel(); - private JLabel calibz = new JLabel(); - private JTextPane calibXRead = new JTextPane(); - private JTextPane calibYRead = new JTextPane(); - private JTextPane calibZRead = new JTextPane(); - - - private JCheckBox addCalibBox = new JCheckBox(); - /** Architecture of the graphical windows */ public ChromocenterSegmentationPipelineBatchDialog() { + final Container container; + final JLabel jLabelWorkDirectory; + final JLabel jLabelCalibration; + final JButton jButtonWorkDirectory = new JButton("Output Directory"); + final JButton jButtonStart = new JButton("Start"); + final JButton jButtonQuit = new JButton("Quit"); + final JButton jButtonRawData = new JButton("Raw Data"); this.setTitle("Chromocenters segmentation pipeline (Batch)"); this.setSize(500, 500); this.setLocationRelativeTo(null); - _container = getContentPane(); + container = getContentPane(); GridBagLayout gridBagLayout = new GridBagLayout(); // gridBagLayout.rowWeights = new double[] {0.0, 0.0, 0.0, 0.0}; gridBagLayout.rowHeights = new int[]{17, 200, 124, 7, 10}; // gridBagLayout.columnWeights = new double[] {0.0, 20.0, 0.0, 0.1}; gridBagLayout.columnWidths = new int[]{236, 120, 72, 20}; - _container.setLayout(gridBagLayout); + container.setLayout(gridBagLayout); - _jLabelWorkDirectory = new JLabel(); - _container.add - ( - _jLabelWorkDirectory, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(0, 10, 0, 0), 0, 0 - ) - ); - _jLabelWorkDirectory.setText("Work directory and Raw data choice : "); + jLabelWorkDirectory = new JLabel(); + container.add(jLabelWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0, 10, 0, 0), + 0, + 0)); + jLabelWorkDirectory.setText("Work directory and Raw data choice : "); JTextPane jTextPane = new JTextPane(); jTextPane.setText("The Raw Data directory must contain 2 subdirectories:" @@ -88,293 +73,321 @@ public ChromocenterSegmentationPipelineBatchDialog() { + "\n2.for segmented nuclei images, named SegmentedDataNucleus." + "\nPlease keep the same file name during the image processing."); jTextPane.setEditable(false); - _container.add - ( - jTextPane, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(20, 20, 0, 0), 0, 0 - ) - ); + container.add(jTextPane, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(20, 20, 0, 0), + 0, + 0)); - _container.add - ( - _JButtonRawData, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(100, 10, 0, 0), 0, 0 - ) - ); - _JButtonRawData.setPreferredSize(new java.awt.Dimension(120, 21)); - _JButtonRawData.setFont(new java.awt.Font("Albertus", 2, 10)); + container.add(jButtonRawData, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(100, 10, 0, 0), + 0, + 0)); + jButtonRawData.setPreferredSize(new java.awt.Dimension(120, 21)); + jButtonRawData.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); - _container.add - ( - _jTextFieldRawData, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(100, 160, 0, 0), 0, 0 - ) - ); + container.add(_jTextFieldRawData, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(100, 160, 0, 0), + 0, + 0)); _jTextFieldRawData.setPreferredSize(new java.awt.Dimension(280, 21)); - _jTextFieldRawData.setFont(new java.awt.Font("Albertus", 2, 10)); + _jTextFieldRawData.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); - _container.add - ( - _jButtonWorkDirectory, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(140, 10, 0, 0), 0, 0 - ) - ); - _jButtonWorkDirectory.setPreferredSize(new java.awt.Dimension(120, 21)); - _jButtonWorkDirectory.setFont(new java.awt.Font("Albertus", 2, 10)); + container.add(jButtonWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(140, 10, 0, 0), + 0, + 0)); + jButtonWorkDirectory.setPreferredSize(new java.awt.Dimension(120, 21)); + jButtonWorkDirectory.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); - _container.add - ( - _jTextFieldWorkDirectory, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(140, 160, 0, 0), 0, 0 - ) - ); + container.add(_jTextFieldWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(140, 160, 0, 0), + 0, + 0)); _jTextFieldWorkDirectory.setPreferredSize(new java.awt.Dimension(280, 21)); - _jTextFieldWorkDirectory.setFont(new java.awt.Font("Albertus", 2, 10)); + _jTextFieldWorkDirectory.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); - _jLabelCalibration = new JLabel(); - _container.add - ( - _jLabelCalibration, - new GridBagConstraints - ( - 0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(20, 10, 0, 0), 0, 0 - ) - ); + jLabelCalibration = new JLabel(); + container.add(jLabelCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(20, 10, 0, 0), + 0, + 0)); - //_jLabelCalibration.setText("Voxel Calibration:"); - Calib = new JPanel(); - Calib.setLayout(new GridBagLayout()); + //jLabelCalibration.setText("Voxel Calibration:"); + _calibration = new JPanel(); + _calibration.setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.weightx = 2; gc.weighty = 5; gc.ipady = gc.anchor = GridBagConstraints.NORTHWEST; - JLabel calibLabel = new JLabel("Calibration:"); + JLabel calibrationLabel = new JLabel("Calibration:"); gc.gridx = 0; gc.gridy = 0; - calibLabel.setAlignmentX(0); - Calib.add(calibLabel); + calibrationLabel.setAlignmentX(0); + _calibration.add(calibrationLabel); gc.gridx = 1; gc.gridy = 0; - addCalibBox.setSelected(false); - addCalibBox.addItemListener(this); - Calib.add(addCalibBox, gc); - + _addCalibrationBox.setSelected(false); + _addCalibrationBox.addItemListener(this); + _calibration.add(_addCalibrationBox, gc); - _container.add(Calib, - new GridBagConstraints(0, - 2, - 2, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(0, 0, 0, 0), - 0, - 0)); + container.add(_calibration, + new GridBagConstraints(0, + 2, + 2, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), + 0, + 0)); - - _container.add - ( - _jButtonStart, - new GridBagConstraints - ( - 0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(190, 140, 0, 0), 0, 0 - ) - ); - _jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); - _container.add - ( - _jButtonQuit, - new GridBagConstraints - ( - 0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(190, 10, 0, 0), 0, 0 - ) - ); - _jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); + container.add(jButtonStart, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(190, 140, 0, 0), + 0, + 0)); + jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); + container.add(jButtonQuit, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(190, 10, 0, 0), + 0, + 0)); + jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); this.setVisible(true); WorkDirectoryListener wdListener = new WorkDirectoryListener(); - _jButtonWorkDirectory.addActionListener(wdListener); + jButtonWorkDirectory.addActionListener(wdListener); RawDataDirectoryListener ddListener = new RawDataDirectoryListener(); - _JButtonRawData.addActionListener(ddListener); + jButtonRawData.addActionListener(ddListener); QuitListener quitListener = new QuitListener(this); - _jButtonQuit.addActionListener(quitListener); + jButtonQuit.addActionListener(quitListener); StartListener startListener = new StartListener(this); - _jButtonStart.addActionListener(startListener); + jButtonStart.addActionListener(startListener); } - /** @param args */ + + /** @param args arguments */ public static void main(String[] args) { ChromocenterSegmentationPipelineBatchDialog chromocenterSegmentationPipelineBatchDialog = new ChromocenterSegmentationPipelineBatchDialog(); chromocenterSegmentationPipelineBatchDialog.setLocationRelativeTo(null); } + public double getXCalibration() { - String xCal = calibXRead.getText(); + String xCal = _readXCalibration.getText(); return Double.parseDouble(xCal.replaceAll(",", ".")); } + public double getYCalibration() { - String yCal = calibYRead.getText(); + String yCal = _readYCalibration.getText(); return Double.parseDouble(yCal.replaceAll(",", ".")); } + public double getZCalibration() { - String zCal = calibZRead.getText(); + String zCal = _readZCalibration.getText(); return Double.parseDouble(zCal.replaceAll(",", ".")); } + public boolean getCalibrationStatus() { - return addCalibBox.isSelected(); + return _addCalibrationBox.isSelected(); } + public String getUnit() { - return unitRead.getText(); + return _readUnit.getText(); } + public String getWorkDirectory() { return _jTextFieldWorkDirectory.getText(); } + public String getRawDataDirectory() { return _jTextFieldRawData.getText(); } + public boolean isStart() { return _start; } - public String getxCalibration2() { - return xCalibration.getText(); - } - public void itemStateChanged(ItemEvent e) { - if (e.getSource() == addCalibBox) { - if ((addCalibBox.isSelected())) { + if (e.getSource() == _addCalibrationBox) { + if (_addCalibrationBox.isSelected()) { GridBagConstraints gc = new GridBagConstraints(); gc.insets = new Insets(0, 0, 5, 0); - unit.setText("Unit :"); + _jLabelUnit.setText("Unit :"); gc.gridx = 0; gc.gridy = 1; - Calib.add(unit, gc); - unitRead.setPreferredSize(new Dimension(100, 20)); - unitRead.setText("µm"); + _calibration.add(_jLabelUnit, gc); + _readUnit.setPreferredSize(new Dimension(100, 20)); + _readUnit.setText("µm"); gc.gridx = 1; gc.gridy = 1; - Calib.add(unitRead, gc); - unit.setVisible(true); - unitRead.setVisible(true); + _calibration.add(_readUnit, gc); + _jLabelUnit.setVisible(true); + _readUnit.setVisible(true); - calibx.setText("X :"); + _jLabelXCalibration.setText("X :"); gc.gridx = 0; gc.gridy = 2; - Calib.add(calibx, gc); - calibXRead.setPreferredSize(new Dimension(100, 20)); - calibXRead.setText("1"); + _calibration.add(_jLabelXCalibration, gc); + _readXCalibration.setPreferredSize(new Dimension(100, 20)); + _readXCalibration.setText("1"); gc.gridx = 1; gc.gridy = 2; - Calib.add(calibXRead, gc); - calibx.setVisible(true); - calibXRead.setVisible(true); + _calibration.add(_readXCalibration, gc); + _jLabelXCalibration.setVisible(true); + _readXCalibration.setVisible(true); - caliby.setText("Y :"); + _jLabelYCalibration.setText("Y :"); gc.gridx = 0; gc.gridy = 3; - Calib.add(caliby, gc); - calibYRead.setPreferredSize(new Dimension(100, 20)); - calibYRead.setText("1"); + _calibration.add(_jLabelYCalibration, gc); + _readYCalibration.setPreferredSize(new Dimension(100, 20)); + _readYCalibration.setText("1"); gc.gridx = 1; gc.gridy = 3; - Calib.add(calibYRead, gc); - caliby.setVisible(true); - calibYRead.setVisible(true); + _calibration.add(_readYCalibration, gc); + _jLabelYCalibration.setVisible(true); + _readYCalibration.setVisible(true); - calibz.setText("Z :"); + _jLabelZCalibration.setText("Z :"); gc.gridx = 0; gc.gridy = 4; - Calib.add(calibz, gc); - calibZRead.setPreferredSize(new Dimension(100, 20)); - calibZRead.setText("1"); + _calibration.add(_jLabelZCalibration, gc); + _readZCalibration.setPreferredSize(new Dimension(100, 20)); + _readZCalibration.setText("1"); gc.gridx = 1; gc.gridy = 4; - Calib.add(calibZRead, gc); - calibz.setVisible(true); - calibZRead.setVisible(true); + _calibration.add(_readZCalibration, gc); + _jLabelZCalibration.setVisible(true); + _readZCalibration.setVisible(true); - validate(); //pack(); - repaint(); } else { - calibx.setVisible(false); - caliby.setVisible(false); - calibz.setVisible(false); - unit.setVisible(false); - - calibXRead.setVisible(false); - calibYRead.setVisible(false); - calibZRead.setVisible(false); - unitRead.setVisible(false); + _jLabelXCalibration.setVisible(false); + _jLabelYCalibration.setVisible(false); + _jLabelZCalibration.setVisible(false); + _jLabelUnit.setVisible(false); - validate(); - repaint(); + _readXCalibration.setVisible(false); + _readYCalibration.setVisible(false); + _readZCalibration.setVisible(false); + _readUnit.setVisible(false); } + validate(); + repaint(); } } + /** + * + */ + static class QuitListener implements ActionListener { + final ChromocenterSegmentationPipelineBatchDialog _chromocenterSegmentationPipelineBatchDialog; + + /** @param chromocenterSegmentationPipelineBatchDialog chromocenterSegmentationPipelineBatchDialog GUI */ + public QuitListener(ChromocenterSegmentationPipelineBatchDialog chromocenterSegmentationPipelineBatchDialog) { + _chromocenterSegmentationPipelineBatchDialog = chromocenterSegmentationPipelineBatchDialog; + } + + + /** + * + */ + public void actionPerformed(ActionEvent actionEvent) { + _chromocenterSegmentationPipelineBatchDialog.dispose(); + } + } /** Classes listener to interact with the several elements of the window */ class StartListener implements ActionListener { - ChromocenterSegmentationPipelineBatchDialog _chromocenterSegmentationPipelineBatchDialog; + final ChromocenterSegmentationPipelineBatchDialog _chromocenterSegmentationPipelineBatchDialog; - /** @param chromocenterSegmentationPipelineBatchDialog */ + /** @param chromocenterSegmentationPipelineBatchDialog chromocenterSegmentationPipelineBatchDialog GUI */ public StartListener(ChromocenterSegmentationPipelineBatchDialog chromocenterSegmentationPipelineBatchDialog) { _chromocenterSegmentationPipelineBatchDialog = chromocenterSegmentationPipelineBatchDialog; } + /** * */ @@ -394,25 +407,6 @@ public void actionPerformed(ActionEvent actionEvent) { } } - /** - * - */ - class QuitListener implements ActionListener { - ChromocenterSegmentationPipelineBatchDialog _chromocenterSegmentationPipelineBatchDialog; - - /** @param chromocenterSegmentationPipelineBatchDialog */ - public QuitListener(ChromocenterSegmentationPipelineBatchDialog chromocenterSegmentationPipelineBatchDialog) { - _chromocenterSegmentationPipelineBatchDialog = chromocenterSegmentationPipelineBatchDialog; - } - - /** - * - */ - public void actionPerformed(ActionEvent actionEvent) { - _chromocenterSegmentationPipelineBatchDialog.dispose(); - } - } - /** * */ @@ -428,13 +422,14 @@ public void actionPerformed(ActionEvent actionEvent) { if (returnValue == JFileChooser.APPROVE_OPTION) { @SuppressWarnings("unused") String run = jFileChooser.getSelectedFile().getName(); - _workDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); - _jTextFieldWorkDirectory.setText(_workDirectory); + String workDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); + _jTextFieldWorkDirectory.setText(workDirectory); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } + /** * */ @@ -450,12 +445,10 @@ public void actionPerformed(ActionEvent actionEvent) { if (returnValue == JFileChooser.APPROVE_OPTION) { @SuppressWarnings("unused") String run = jFileChooser.getSelectedFile().getName(); - _rawDataDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); - _jTextFieldRawData.setText(_rawDataDirectory); + String rawDataDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); + _jTextFieldRawData.setText(rawDataDirectory); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } - - -} \ No newline at end of file +} \ No newline at end of file diff --git a/src/main/java/gred/nucleus/dialogs/ChromocentersAnalysisPipelineBatchDialog.java b/src/main/java/gred/nucleus/dialogs/ChromocentersAnalysisPipelineBatchDialog.java index 151d8b49..23d73b65 100644 --- a/src/main/java/gred/nucleus/dialogs/ChromocentersAnalysisPipelineBatchDialog.java +++ b/src/main/java/gred/nucleus/dialogs/ChromocentersAnalysisPipelineBatchDialog.java @@ -14,488 +14,501 @@ * @author pouletaxel */ public class ChromocentersAnalysisPipelineBatchDialog extends JFrame implements ItemListener { - private static final long serialVersionUID = 1L; - private final JButton _jButtonWorkDirectory = new JButton("Output Directory"); - private final JButton _jButtonStart = new JButton("Start"); - private final JButton _jButtonQuit = new JButton("Quit"); - private final JButton _jButtonRawData = new JButton("Raw Data"); - - private final Container _container; - - private final JFormattedTextField _jTextFieldXCalibration = new JFormattedTextField(Number.class); - private final JFormattedTextField _jTextFieldYCalibration = new JFormattedTextField(Number.class); - private final JFormattedTextField _jTextFieldZCalibration = new JFormattedTextField(Number.class); - - private final JTextField _jTextFieldUnit = new JTextField(); - private final JTextField _jTextFieldWorkDirectory = new JTextField(); - private final JTextField _jTextFieldRawData = new JTextField(); - private final JLabel _jLabelWorkDirectory; - private final ButtonGroup _buttonGroupChoiceRhf = new ButtonGroup(); - private final JRadioButton _jRadioButtonRhfV = new JRadioButton("VolumeRHF"); - private final JRadioButton _jRadioButtonRhfI = new JRadioButton("IntensityRHF"); - private final JRadioButton _jRadioButtonRhfIV = new JRadioButton("VolumeRHF and IntensityRHF"); - private final ButtonGroup buttonGroupChoiceAnalysis = new ButtonGroup(); - private final JRadioButton _jRadioButtonNucCc = new JRadioButton("Nucleus and chromocenter"); - private final JRadioButton _jRadioButtonCc = new JRadioButton("Chromocenter"); - private final JRadioButton _jRadioButtonNuc = new JRadioButton("Nucleus"); - private final JPanel Calib; - private final JTextPane unitRead = new JTextPane(); - private final JLabel unit = new JLabel(); - private final JLabel calibx = new JLabel(); - private final JLabel caliby = new JLabel(); - private final JLabel calibz = new JLabel(); - private final JTextPane calibXRead = new JTextPane(); - private final JTextPane calibYRead = new JTextPane(); - private final JTextPane calibZRead = new JTextPane(); - private final JCheckBox addCalibBox = new JCheckBox(); - private JLabel _jLabelXcalibration; - private JLabel _jLabelYcalibration; - private JLabel _jLabelZcalibration; - private JLabel _jLabelUnit; - private JLabel _jLabelAnalysis; - private JLabel _jLabelCalibration; - private String _workDirectory; - private String _rawDataDirectory; - private boolean _start = false; + private static final long serialVersionUID = 1L; + private final JTextField _jTextFieldWorkDirectory = new JTextField(); + private final JTextField _jTextFieldRawData = new JTextField(); + private final JRadioButton _jRadioButtonRhfV = new JRadioButton("VolumeRHF"); + private final JRadioButton _jRadioButtonRhfI = new JRadioButton("IntensityRHF"); + private final JRadioButton _jRadioButtonRhfIV = new JRadioButton("VolumeRHF and IntensityRHF"); + private final JRadioButton _jRadioButtonNucCc = new JRadioButton("Nucleus and chromocenter"); + private final JRadioButton _jRadioButtonCc = new JRadioButton("Chromocenter"); + private final JRadioButton _jRadioButtonNuc = new JRadioButton("Nucleus"); + private final JLabel _jLabelUnit = new JLabel(); + private final JLabel _jLabelXCalibration = new JLabel(); + private final JLabel _jLabelYCalibration = new JLabel(); + private final JLabel _jLabelZCalibration = new JLabel(); + private final JTextPane _readUnit = new JTextPane(); + private final JTextPane _readXCalibration = new JTextPane(); + private final JTextPane _readYCalibration = new JTextPane(); + private final JTextPane _readZCalibration = new JTextPane(); + private final JCheckBox _addCalibrationBox = new JCheckBox(); + private final JPanel _calibration; + private final JFormattedTextField _jTextFieldXCalibration = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldYCalibration = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldZCalibration = new JFormattedTextField(Number.class); + private boolean _start = false; + /** Architecture of the graphical windows */ public ChromocentersAnalysisPipelineBatchDialog() { + final Container container = getContentPane(); + final JLabel jLabelWorkDirectory = new JLabel(); + final JButton jButtonWorkDirectory = new JButton("Output Directory"); + final JButton jButtonStart = new JButton("Start"); + final JButton jButtonQuit = new JButton("Quit"); + final JButton jButtonRawData = new JButton("Raw Data"); + final ButtonGroup buttonGroupChoiceAnalysis = new ButtonGroup(); + final ButtonGroup buttonGroupChoiceRhf = new ButtonGroup(); + JLabel jLabelAnalysis; this.setTitle("Chromocenters Analysis Pipeline (Batch)"); this.setSize(500, 600); this.setLocationRelativeTo(null); - _container = getContentPane(); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.1}; gridBagLayout.rowHeights = new int[]{17, 200, 124, 7}; gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.1}; gridBagLayout.columnWidths = new int[]{236, 120, 72, 20}; - _container.setLayout(gridBagLayout); - - _jLabelWorkDirectory = new JLabel(); - _container.add - ( - _jLabelWorkDirectory, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(0, 10, 0, 0), 0, 0 - ) - ); - _jLabelWorkDirectory.setText("Work directory and data directory choice : "); - + container.setLayout(gridBagLayout); + container.add(jLabelWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0, 10, 0, 0), + 0, + 0)); + jLabelWorkDirectory.setText("Work directory and data directory choice : "); JTextPane jTextPane = new JTextPane(); - jTextPane.setText("The Raw Data directory must contain 3 subdirectories:" - + "\n1. for raw nuclei images, named RawDataNucleus. " - + "\n2. for segmented nuclei images, named SegmentedDataNucleus." - + "\n3. for segmented images of chromocenters, named SegmentedDataCc." - + "\nPlease keep the same file name during the image processing."); + jTextPane.setText( + "The Raw Data directory must contain 3 subdirectories:\n1. for raw nuclei images, named RawDataNucleus. \n2. for segmented nuclei images, named SegmentedDataNucleus.\n3. for segmented images of chromocenters, named SegmentedDataCc.\nPlease keep the same file name during the image processing."); jTextPane.setEditable(false); - _container.add - ( - jTextPane, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(20, 20, 0, 0), 0, 0 - ) - ); - - _container.add - ( - _jButtonRawData, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(110, 10, 0, 0), 0, 0 - ) - ); - _jButtonRawData.setPreferredSize(new java.awt.Dimension(120, 21)); - _jButtonRawData.setFont(new java.awt.Font("Albertus", 2, 10)); - - _container.add - ( - _jTextFieldRawData, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(110, 160, 0, 0), 0, 0 - ) - ); + container.add(jTextPane, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(20, 20, 0, 0), + 0, + 0)); + container.add(jButtonRawData, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(110, 10, 0, 0), + 0, + 0)); + jButtonRawData.setPreferredSize(new java.awt.Dimension(120, 21)); + jButtonRawData.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + container.add(_jTextFieldRawData, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(110, 160, 0, 0), + 0, + 0)); _jTextFieldRawData.setPreferredSize(new java.awt.Dimension(280, 21)); - _jTextFieldRawData.setFont(new java.awt.Font("Albertus", 2, 10)); - - _container.add - ( - _jButtonWorkDirectory, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(150, 10, 0, 0), 0, 0 - ) - ); - _jButtonWorkDirectory.setPreferredSize(new java.awt.Dimension(120, 21)); - _jButtonWorkDirectory.setFont(new java.awt.Font("Albertus", 2, 10)); - - _container.add - ( - _jTextFieldWorkDirectory, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(150, 160, 0, 0), 0, 0 - ) - ); + _jTextFieldRawData.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + container.add(jButtonWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(150, 10, 0, 0), + 0, + 0)); + jButtonWorkDirectory.setPreferredSize(new java.awt.Dimension(120, 21)); + jButtonWorkDirectory.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + container.add(_jTextFieldWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(150, 160, 0, 0), + 0, + 0)); _jTextFieldWorkDirectory.setPreferredSize(new java.awt.Dimension(280, 21)); - _jTextFieldWorkDirectory.setFont(new java.awt.Font("Albertus", 2, 10)); - - - Calib = new JPanel(); - Calib.setLayout(new GridBagLayout()); - + _jTextFieldWorkDirectory.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + _calibration = new JPanel(); + _calibration.setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.weightx = 2; gc.weighty = 5; gc.ipady = gc.anchor = GridBagConstraints.NORTHWEST; - - JLabel calibLabel = new JLabel("Calibration:"); + JLabel calibrationLabel = new JLabel("Calibration:"); gc.gridx = 0; gc.gridy = 0; - calibLabel.setAlignmentX(0); - Calib.add(calibLabel); - + calibrationLabel.setAlignmentX(0); + _calibration.add(calibrationLabel); gc.gridx = 1; gc.gridy = 0; - - addCalibBox.setSelected(false); - addCalibBox.addItemListener(this); - Calib.add(addCalibBox, gc); - _container.add(Calib, - new GridBagConstraints(0, - 2, - 2, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(0, 0, 0, 0), - 0, - 0)); - - - _jLabelAnalysis = new JLabel(); - _container.add - ( - _jLabelAnalysis, - new GridBagConstraints - ( - 0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(30, 10, 0, 0), 0, 0 - ) - ); - _jLabelAnalysis.setText("Type of Relative Heterochromatin Fraction:"); - - _buttonGroupChoiceRhf.add(_jRadioButtonRhfV); - _buttonGroupChoiceRhf.add(_jRadioButtonRhfI); - _buttonGroupChoiceRhf.add(_jRadioButtonRhfIV); - _jRadioButtonRhfV.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _jRadioButtonRhfI.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _jRadioButtonRhfIV.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add - ( - _jRadioButtonRhfV, - new GridBagConstraints - ( - 0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(60, 370, 0, 0), 0, 0 - ) - ); - _container.add - ( - _jRadioButtonRhfI, - new GridBagConstraints - ( - 0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(60, 250, 0, 0), 0, 0 - ) - ); - _container.add - ( - _jRadioButtonRhfIV, - new GridBagConstraints - ( - 0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(60, 20, 0, 0), 0, 0 - ) - ); + _addCalibrationBox.setSelected(false); + _addCalibrationBox.addItemListener(this); + _calibration.add(_addCalibrationBox, gc); + container.add(_calibration, + new GridBagConstraints(0, + 2, + 2, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), + 0, + 0)); + jLabelAnalysis = new JLabel(); + container.add(jLabelAnalysis, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(30, 10, 0, 0), + 0, + 0)); + jLabelAnalysis.setText("Type of Relative Heterochromatin Fraction:"); + buttonGroupChoiceRhf.add(_jRadioButtonRhfV); + buttonGroupChoiceRhf.add(_jRadioButtonRhfI); + buttonGroupChoiceRhf.add(_jRadioButtonRhfIV); + _jRadioButtonRhfV.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + _jRadioButtonRhfI.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + _jRadioButtonRhfIV.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jRadioButtonRhfV, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(60, 370, 0, 0), + 0, + 0)); + container.add(_jRadioButtonRhfI, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(60, 250, 0, 0), + 0, + 0)); + container.add(_jRadioButtonRhfIV, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(60, 20, 0, 0), + 0, + 0)); _jRadioButtonRhfIV.setSelected(true); - - _jLabelAnalysis = new JLabel(); - _container.add - ( - _jLabelAnalysis, - new GridBagConstraints - ( - 0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(95, 10, 0, 0), 0, 0 - ) - ); - _jLabelAnalysis.setText("Results file of interest: "); - + jLabelAnalysis = new JLabel(); + container.add(jLabelAnalysis, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(95, 10, 0, 0), + 0, + 0)); + jLabelAnalysis.setText("Results file of interest: "); buttonGroupChoiceAnalysis.add(_jRadioButtonNucCc); buttonGroupChoiceAnalysis.add(_jRadioButtonCc); buttonGroupChoiceAnalysis.add(_jRadioButtonNuc); - _jRadioButtonNuc.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _jRadioButtonCc.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _jRadioButtonNucCc.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add - ( - _jRadioButtonNuc, - new GridBagConstraints - ( - 0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(120, 370, 0, 0), 0, 0 - ) - ); - _container.add - ( - _jRadioButtonCc, - new GridBagConstraints - ( - 0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(120, 250, 0, 0), 0, 0 - ) - ); - _container.add - ( - _jRadioButtonNucCc, - new GridBagConstraints - ( - 0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(120, 20, 0, 0), 0, 0 - ) - ); + _jRadioButtonNuc.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + _jRadioButtonCc.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + _jRadioButtonNucCc.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jRadioButtonNuc, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(120, 370, 0, 0), + 0, + 0)); + container.add(_jRadioButtonCc, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(120, 250, 0, 0), + 0, + 0)); + container.add(_jRadioButtonNucCc, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(120, 20, 0, 0), + 0, + 0)); _jRadioButtonNucCc.setSelected(true); - - _container.add - ( - _jButtonStart, - new GridBagConstraints - ( - 0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(190, 140, 0, 0), 0, 0 - ) - ); - _jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); - _container.add - ( - _jButtonQuit, - new GridBagConstraints - ( - 0, 3, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(190, 10, 0, 0), 0, 0 - ) - ); - _jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); - - + container.add(jButtonStart, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(190, 140, 0, 0), + 0, + 0)); + jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); + container.add(jButtonQuit, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(190, 10, 0, 0), + 0, + 0)); + jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); WorkDirectoryListener wdListener = new WorkDirectoryListener(); - _jButtonWorkDirectory.addActionListener(wdListener); + jButtonWorkDirectory.addActionListener(wdListener); RawDataDirectoryListener ddListener = new RawDataDirectoryListener(); - _jButtonRawData.addActionListener(ddListener); + jButtonRawData.addActionListener(ddListener); QuitListener quitListener = new QuitListener(this); - _jButtonQuit.addActionListener(quitListener); + jButtonQuit.addActionListener(quitListener); StartListener startListener = new StartListener(this); - _jButtonStart.addActionListener(startListener); + jButtonStart.addActionListener(startListener); this.setVisible(true); } - /** @param args */ + + /** @param args arguments */ public static void main(String[] args) { ChromocentersAnalysisPipelineBatchDialog chromocentersAnalysisPipelineBatchDialog = new ChromocentersAnalysisPipelineBatchDialog(); chromocentersAnalysisPipelineBatchDialog.setLocationRelativeTo(null); } + public double getXCalibration() { - String xCal = calibXRead.getText(); + String xCal = _readXCalibration.getText(); return Double.parseDouble(xCal.replaceAll(",", ".")); } + public double getYCalibration() { - String yCal = calibYRead.getText(); + String yCal = _readYCalibration.getText(); return Double.parseDouble(yCal.replaceAll(",", ".")); } + public double getZCalibration() { - String zCal = calibZRead.getText(); + String zCal = _readZCalibration.getText(); return Double.parseDouble(zCal.replaceAll(",", ".")); } + public boolean getCalibrationStatus() { - return addCalibBox.isSelected(); + return _addCalibrationBox.isSelected(); } + public String getUnit() { - return _jTextFieldUnit.getText(); + return _readUnit.getText(); } + public String getWorkDirectory() { return _jTextFieldWorkDirectory.getText(); } + public String getRawDataDirectory() { return _jTextFieldRawData.getText(); } + public boolean isStart() { return _start; } + public boolean isNucAndCcAnalysis() { return _jRadioButtonNucCc.isSelected(); } + public boolean isNucAnalysis() { return _jRadioButtonNuc.isSelected(); } + public boolean isCcAnalysis() { return _jRadioButtonCc.isSelected(); } + public boolean isRHFVolumeAndIntensity() { return _jRadioButtonRhfIV.isSelected(); } + public boolean isRhfVolume() { return _jRadioButtonRhfV.isSelected(); } + public boolean isRhfIntensity() { return _jRadioButtonRhfI.isSelected(); } public void itemStateChanged(ItemEvent e) { - if (e.getSource() == addCalibBox) { - if ((addCalibBox.isSelected())) { + if (e.getSource() == _addCalibrationBox) { + if (_addCalibrationBox.isSelected()) { GridBagConstraints gc = new GridBagConstraints(); gc.insets = new Insets(0, 0, 5, 0); - unit.setText("Unit :"); + _jLabelUnit.setText("Unit :"); gc.gridx = 0; gc.gridy = 1; - Calib.add(unit, gc); - unitRead.setPreferredSize(new Dimension(100, 20)); - unitRead.setText("µm"); + _calibration.add(_jLabelUnit, gc); + _readUnit.setPreferredSize(new Dimension(100, 20)); + _readUnit.setText("µm"); gc.gridx = 1; gc.gridy = 1; - Calib.add(unitRead, gc); - unit.setVisible(true); - unitRead.setVisible(true); + _calibration.add(_readUnit, gc); + _jLabelUnit.setVisible(true); + _readUnit.setVisible(true); - calibx.setText("X :"); + _jLabelXCalibration.setText("X :"); gc.gridx = 0; gc.gridy = 2; - Calib.add(calibx, gc); - calibXRead.setPreferredSize(new Dimension(100, 20)); - calibXRead.setText("1"); + _calibration.add(_jLabelXCalibration, gc); + _readXCalibration.setPreferredSize(new Dimension(100, 20)); + _readXCalibration.setText("1"); gc.gridx = 1; gc.gridy = 2; - Calib.add(calibXRead, gc); - calibx.setVisible(true); - calibXRead.setVisible(true); + _calibration.add(_readXCalibration, gc); + _jLabelXCalibration.setVisible(true); + _readXCalibration.setVisible(true); - caliby.setText("Y :"); + _jLabelYCalibration.setText("Y :"); gc.gridx = 0; gc.gridy = 3; - Calib.add(caliby, gc); - calibYRead.setPreferredSize(new Dimension(100, 20)); - calibYRead.setText("1"); + _calibration.add(_jLabelYCalibration, gc); + _readYCalibration.setPreferredSize(new Dimension(100, 20)); + _readYCalibration.setText("1"); gc.gridx = 1; gc.gridy = 3; - Calib.add(calibYRead, gc); - caliby.setVisible(true); - calibYRead.setVisible(true); + _calibration.add(_readYCalibration, gc); + _jLabelYCalibration.setVisible(true); + _readYCalibration.setVisible(true); - calibz.setText("Z :"); + _jLabelZCalibration.setText("Z :"); gc.gridx = 0; gc.gridy = 4; - Calib.add(calibz, gc); - calibZRead.setPreferredSize(new Dimension(100, 20)); - calibZRead.setText("1"); + _calibration.add(_jLabelZCalibration, gc); + _readZCalibration.setPreferredSize(new Dimension(100, 20)); + _readZCalibration.setText("1"); gc.gridx = 1; gc.gridy = 4; - Calib.add(calibZRead, gc); - calibz.setVisible(true); - calibZRead.setVisible(true); + _calibration.add(_readZCalibration, gc); + _jLabelZCalibration.setVisible(true); + _readZCalibration.setVisible(true); - validate(); //pack(); - repaint(); } else { - calibx.setVisible(false); - caliby.setVisible(false); - calibz.setVisible(false); - unit.setVisible(false); + _jLabelXCalibration.setVisible(false); + _jLabelYCalibration.setVisible(false); + _jLabelZCalibration.setVisible(false); + _jLabelUnit.setVisible(false); - calibXRead.setVisible(false); - calibYRead.setVisible(false); - calibZRead.setVisible(false); - unitRead.setVisible(false); - - validate(); - repaint(); + _readXCalibration.setVisible(false); + _readYCalibration.setVisible(false); + _readZCalibration.setVisible(false); + _readUnit.setVisible(false); } + validate(); + repaint(); } } + /** + * + */ + static class QuitListener implements ActionListener { + final ChromocentersAnalysisPipelineBatchDialog _chromocentersAnalysisPipelineBatchDialog; + + /** @param chromocentersAnalysisPipelineBatchDialog chromocentersAnalysisPipelineBatchDialog GUI */ + public QuitListener(ChromocentersAnalysisPipelineBatchDialog chromocentersAnalysisPipelineBatchDialog) { + _chromocentersAnalysisPipelineBatchDialog = chromocentersAnalysisPipelineBatchDialog; + } + + + /** + * + */ + public void actionPerformed(ActionEvent actionEvent) { + _chromocentersAnalysisPipelineBatchDialog.dispose(); + } + } /** Classes listener to interact with the several elements of the window */ class StartListener implements ActionListener { - ChromocentersAnalysisPipelineBatchDialog _chromocentersAnalysisPipelineBatchDialog; + final ChromocentersAnalysisPipelineBatchDialog _chromocentersAnalysisPipelineBatchDialog; - /** @param chromocentersAnalysisPipelineBatchDialog */ + /** @param chromocentersAnalysisPipelineBatchDialog chromocentersAnalysisPipelineBatchDialog GUI */ public StartListener(ChromocentersAnalysisPipelineBatchDialog chromocentersAnalysisPipelineBatchDialog) { _chromocentersAnalysisPipelineBatchDialog = chromocentersAnalysisPipelineBatchDialog; } + /** * */ @@ -515,25 +528,6 @@ public void actionPerformed(ActionEvent actionEvent) { } } - /** - * - */ - class QuitListener implements ActionListener { - ChromocentersAnalysisPipelineBatchDialog _chromocentersAnalysisPipelineBatchDialog; - - /** @param chromocentersAnalysisPipelineBatchDialog */ - public QuitListener(ChromocentersAnalysisPipelineBatchDialog chromocentersAnalysisPipelineBatchDialog) { - _chromocentersAnalysisPipelineBatchDialog = chromocentersAnalysisPipelineBatchDialog; - } - - /** - * - */ - public void actionPerformed(ActionEvent actionEvent) { - _chromocentersAnalysisPipelineBatchDialog.dispose(); - } - } - /** * */ @@ -549,13 +543,14 @@ public void actionPerformed(ActionEvent actionEvent) { if (returnValue == JFileChooser.APPROVE_OPTION) { @SuppressWarnings("unused") String run = jFileChooser.getSelectedFile().getName(); - _workDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); - _jTextFieldWorkDirectory.setText(_workDirectory); + String workDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); + _jTextFieldWorkDirectory.setText(workDirectory); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } + /** * */ @@ -571,8 +566,8 @@ public void actionPerformed(ActionEvent actionEvent) { if (returnValue == JFileChooser.APPROVE_OPTION) { @SuppressWarnings("unused") String run = jFileChooser.getSelectedFile().getName(); - _rawDataDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); - _jTextFieldRawData.setText(_rawDataDirectory); + String rawDataDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); + _jTextFieldRawData.setText(rawDataDirectory); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } diff --git a/src/main/java/gred/nucleus/dialogs/CropFromCoodinateDialog.java b/src/main/java/gred/nucleus/dialogs/CropFromCoodinateDialog.java index 95bf6e24..48417276 100644 --- a/src/main/java/gred/nucleus/dialogs/CropFromCoodinateDialog.java +++ b/src/main/java/gred/nucleus/dialogs/CropFromCoodinateDialog.java @@ -127,28 +127,33 @@ public CropFromCoodinateDialog() { _jButtonQuit.setPreferredSize(new java.awt.Dimension(60, 21)); this.setVisible(true); - CropFromCoodinateDialog.QuitListener quitListener = new CropFromCoodinateDialog.QuitListener(this); + CropFromCoodinateDialog.QuitListener quitListener = new QuitListener(this); _jButtonQuit.addActionListener(quitListener); CropFromCoodinateDialog.StartListener startListener = new CropFromCoodinateDialog.StartListener(this); _jButtonStart.addActionListener(startListener); } + public boolean isStart() { return _start; } + public String getLink() { return _jLinkFileChooser.getText(); } + public String getImage() { return _jImageChooser.getText(); } + public String getCoord() { return _jCoordFileChooser.getText(); } + public void actionPerformed(ActionEvent e) { if (((JButton) e.getSource()).getName().equals(linkChooserName)) { fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); @@ -174,13 +179,14 @@ public StartListener(CropFromCoodinateDialog autocropDialog) { _autocropDialog = autocropDialog; } + public void actionPerformed(ActionEvent actionEvent) { _start = true; _autocropDialog.dispose(); } } - class QuitListener implements ActionListener { + static class QuitListener implements ActionListener { CropFromCoodinateDialog _autocropDialog; /** @param autocropDialog */ @@ -188,9 +194,9 @@ public QuitListener(CropFromCoodinateDialog autocropDialog) { _autocropDialog = autocropDialog; } + public void actionPerformed(ActionEvent actionEvent) { _autocropDialog.dispose(); } } - } diff --git a/src/main/java/gred/nucleus/dialogs/NucleusSegmentationAndAnalysisBatchDialog.java b/src/main/java/gred/nucleus/dialogs/NucleusSegmentationAndAnalysisBatchDialog.java index ba118cda..0bc05c52 100644 --- a/src/main/java/gred/nucleus/dialogs/NucleusSegmentationAndAnalysisBatchDialog.java +++ b/src/main/java/gred/nucleus/dialogs/NucleusSegmentationAndAnalysisBatchDialog.java @@ -11,543 +11,538 @@ /** - * Class to construct graphical interface for the Nucleus Segentation analysis in batch + * Class to construct graphical interface for the Nucleus Segmentation analysis in batch * * @author Poulet Axel */ public class NucleusSegmentationAndAnalysisBatchDialog extends JFrame { - private static final long serialVersionUID = 1L; - private final JButton _jButtonWorkDirectory = new JButton("Output Directory"); - private final JButton _jButtonStart = new JButton("Start"); - private final JButton _jButtonQuit = new JButton("Quit"); - private final JButton _jButtonRawData = new JButton("Raw Data"); - - private final Container _container; - private final JComboBox _comboBoxCpu = new JComboBox<>(); - - private final JFormattedTextField _jTextFieldXCalibration = new JFormattedTextField(Number.class); - private final JFormattedTextField _jTextFieldYCalibration = new JFormattedTextField(Number.class); - private final JFormattedTextField _jTextFieldZCalibration = new JFormattedTextField(Number.class); - private final JFormattedTextField _jTextFieldMax = new JFormattedTextField(Number.class); - private final JFormattedTextField _jTextFieldMin = new JFormattedTextField(Number.class); - - private final JTextField _jTextFieldUnit = new JTextField(); - private final JTextField _jTextFieldWorkDirectory = new JTextField(); - private final JTextField _jTextFieldRawData = new JTextField(); - - private final JLabel _jLabelXcalibration; - private final JLabel _jLabelYcalibration; - private final JLabel _jLabelZcalibration; - private final JLabel _jLabelUnit; - private final JLabel _jLabelSegmentation; - private final JLabel _jLabelVolumeMin; - private final JLabel _jLabelVolumeMax; - private final JLabel _jLabelAnalysis; - private final JLabel _jLabelWorkDirectory; - private final JLabel _jLabelCalibration; - private final JLabel _jLabelNbCpu; - - private final ButtonGroup buttonGroupChoiceAnalysis = new ButtonGroup(); - private final JRadioButton _jRadioButton2DAnalysis = new JRadioButton("2D"); - private final JRadioButton _jRadioButton3DAnalysis = new JRadioButton("3D"); - private final JRadioButton _jRadioButton2D3DAnalysis = new JRadioButton("2D and 3D"); - - private String _workDirectory; - private String _rawDataDirectory; - private boolean _start = false; - private int _nbCpuChosen = 1; + private static final long serialVersionUID = 1L; + private final JFormattedTextField _jTextFieldXCalibration = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldYCalibration = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldZCalibration = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldMax = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldMin = new JFormattedTextField(Number.class); + private final JTextField _jTextFieldUnit = new JTextField(); + private final JTextField _jTextFieldWorkDirectory = new JTextField(); + private final JTextField _jTextFieldRawData = new JTextField(); + private final JRadioButton _jRadioButton2DAnalysis = new JRadioButton("2D"); + private final JRadioButton _jRadioButton3DAnalysis = new JRadioButton("3D"); + private final JRadioButton _jRadioButton2D3DAnalysis = new JRadioButton("2D and 3D"); + private boolean _start = false; + private int _nbCpuChosen = 1; /** Architecture of the graphical windows */ public NucleusSegmentationAndAnalysisBatchDialog() { + final Container container = getContentPane(); + final JButton jButtonWorkDirectory = new JButton("Output Directory"); + final JButton jButtonStart = new JButton("Start"); + final JButton jButtonQuit = new JButton("Quit"); + final JButton jButtonRawData = new JButton("Raw Data"); + final ButtonGroup buttonGroupChoiceAnalysis = new ButtonGroup(); + final JComboBox comboBoxCpu = new JComboBox<>(); + final JLabel jLabelXCalibration = new JLabel(); + final JLabel jLabelYCalibration = new JLabel(); + final JLabel jLabelZCalibration = new JLabel(); + final JLabel jLabelUnit = new JLabel(); + final JLabel jLabelSegmentation = new JLabel(); + final JLabel jLabelVolumeMin = new JLabel(); + final JLabel jLabelVolumeMax = new JLabel(); + final JLabel jLabelAnalysis = new JLabel(); + final JLabel jLabelWorkDirectory = new JLabel(); + final JLabel jLabelCalibration = new JLabel(); + final JLabel jLabelNbCpu = new JLabel(); + this.setTitle("Nucleus segmentation & analysis (batch)"); this.setSize(500, 500); this.setLocationRelativeTo(null); - _container = getContentPane(); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.1}; gridBagLayout.rowHeights = new int[]{17, 71, 124, 7}; gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.1}; gridBagLayout.columnWidths = new int[]{236, 109, 72, 20}; - _container.setLayout(gridBagLayout); + container.setLayout(gridBagLayout); - _jLabelWorkDirectory = new JLabel(); - _container.add(_jLabelWorkDirectory, - new GridBagConstraints(0, - 1, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(0, 10, 0, 0), - 0, - 0)); - _jLabelWorkDirectory.setText("Work directory and Raw data choice : "); + container.add(jLabelWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0, 10, 0, 0), + 0, + 0)); + jLabelWorkDirectory.setText("Work directory and Raw data choice : "); - _container.add(_jButtonRawData, - new GridBagConstraints(0, - 1, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(30, 10, 0, 0), - 0, - 0)); - _jButtonRawData.setPreferredSize(new java.awt.Dimension(120, 21)); - _jButtonRawData.setFont(new java.awt.Font("Albertus", 2, 10)); + container.add(jButtonRawData, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(30, 10, 0, 0), + 0, + 0)); + jButtonRawData.setPreferredSize(new java.awt.Dimension(120, 21)); + jButtonRawData.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); - _container.add(_jTextFieldRawData, - new GridBagConstraints(0, - 1, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(30, 160, 0, 0), - 0, - 0)); + container.add(_jTextFieldRawData, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(30, 160, 0, 0), + 0, + 0)); _jTextFieldRawData.setPreferredSize(new java.awt.Dimension(280, 21)); - _jTextFieldRawData.setFont(new java.awt.Font("Albertus", 2, 10)); + _jTextFieldRawData.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); - _container.add(_jButtonWorkDirectory, - new GridBagConstraints(0, - 1, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(60, 10, 0, 0), - 0, - 0)); - _jButtonWorkDirectory.setPreferredSize(new java.awt.Dimension(120, 21)); - _jButtonWorkDirectory.setFont(new java.awt.Font("Albertus", 2, 10)); + container.add(jButtonWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(60, 10, 0, 0), + 0, + 0)); + jButtonWorkDirectory.setPreferredSize(new java.awt.Dimension(120, 21)); + jButtonWorkDirectory.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); - _container.add(_jTextFieldWorkDirectory, - new GridBagConstraints(0, - 1, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(60, 160, 0, 0), - 0, - 0)); + container.add(_jTextFieldWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(60, 160, 0, 0), + 0, + 0)); _jTextFieldWorkDirectory.setPreferredSize(new java.awt.Dimension(280, 21)); - _jTextFieldWorkDirectory.setFont(new java.awt.Font("Albertus", 2, 10)); + _jTextFieldWorkDirectory.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); - _jLabelCalibration = new JLabel(); - _container.add(_jLabelCalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(20, 10, 0, 0), - 0, - 0)); - _jLabelCalibration.setText("Voxel Calibration:"); + container.add(jLabelCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(20, 10, 0, 0), + 0, + 0)); + jLabelCalibration.setText("Voxel Calibration:"); - _container.setLayout(gridBagLayout); - _jLabelXcalibration = new JLabel(); - _container.add(_jLabelXcalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(40, 20, 0, 0), - 0, - 0)); - _jLabelXcalibration.setText("x :"); - _jLabelXcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldXCalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(40, 60, 0, 0), - 0, - 0)); + container.setLayout(gridBagLayout); + container.add(jLabelXCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 20, 0, 0), + 0, + 0)); + jLabelXCalibration.setText("x :"); + jLabelXCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldXCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 60, 0, 0), + 0, + 0)); _jTextFieldXCalibration.setText("1"); _jTextFieldXCalibration.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelYcalibration = new JLabel(); - _container.add(_jLabelYcalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(65, 20, 0, 0), - 0, - 0)); - _jLabelYcalibration.setText("y :"); - _jLabelYcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldYCalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(65, 60, 0, 0), - 0, - 0)); + container.add(jLabelYCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(65, 20, 0, 0), + 0, + 0)); + jLabelYCalibration.setText("y :"); + jLabelYCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldYCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(65, 60, 0, 0), + 0, + 0)); _jTextFieldYCalibration.setText("1"); _jTextFieldYCalibration.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelZcalibration = new JLabel(); - _container.add(_jLabelZcalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(90, 20, 0, 0), - 0, - 0)); - _jLabelZcalibration.setText("z :"); - _jLabelZcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldZCalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(90, 60, 0, 0), - 0, - 0)); + container.add(jLabelZCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(90, 20, 0, 0), + 0, + 0)); + jLabelZCalibration.setText("z :"); + jLabelZCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldZCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(90, 60, 0, 0), + 0, + 0)); _jTextFieldZCalibration.setText("1"); _jTextFieldZCalibration.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelUnit = new JLabel(); - _container.add(_jLabelUnit, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(115, 20, 0, 0), - 0, - 0)); - _jLabelUnit.setText("unit :"); - _jLabelUnit.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldUnit, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(115, 60, 0, 0), - 0, - 0)); + container.add(jLabelUnit, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(115, 20, 0, 0), + 0, + 0)); + jLabelUnit.setText("unit :"); + jLabelUnit.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldUnit, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(115, 60, 0, 0), + 0, + 0)); _jTextFieldUnit.setText("pixel"); _jTextFieldUnit.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelSegmentation = new JLabel(); - _container.add(_jLabelSegmentation, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(20, 10, 0, 0), - 0, - 0)); - _jLabelSegmentation.setText("Choose the min and max volumes of the nucleus:"); + container.add(jLabelSegmentation, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(20, 10, 0, 0), + 0, + 0)); + jLabelSegmentation.setText("Choose the min and max volumes of the nucleus:"); - _jLabelVolumeMin = new JLabel(); - _container.add(_jLabelVolumeMin, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(40, 20, 0, 0), - 0, - 0)); - _jLabelVolumeMin.setText("Minimun volume of the segmented nucleus :"); - _jLabelVolumeMin.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldMin, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(40, 320, 0, 0), - 0, - 0)); + container.add(jLabelVolumeMin, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 20, 0, 0), + 0, + 0)); + jLabelVolumeMin.setText("Minimum volume of the segmented nucleus :"); + jLabelVolumeMin.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldMin, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 320, 0, 0), + 0, + 0)); _jTextFieldMin.setText("15"); _jTextFieldMin.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelVolumeMax = new JLabel(); - _container.add(_jLabelVolumeMax, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(70, 20, 0, 0), - 0, - 0)); - _jLabelVolumeMax.setText("Maximum volume of the segmented nucleus :"); - _jLabelVolumeMax.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldMax, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(70, 320, 0, 0), - 0, - 0)); + container.add(jLabelVolumeMax, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(70, 20, 0, 0), + 0, + 0)); + jLabelVolumeMax.setText("Maximum volume of the segmented nucleus :"); + jLabelVolumeMax.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldMax, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(70, 320, 0, 0), + 0, + 0)); _jTextFieldMax.setText("2000"); _jTextFieldMax.setPreferredSize(new java.awt.Dimension(60, 21)); - - _jLabelAnalysis = new JLabel(); - _container.add(_jLabelAnalysis, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(100, 10, 0, 0), - 0, - 0)); - _jLabelAnalysis.setText("Type of analysis:"); + container.add(jLabelAnalysis, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(100, 10, 0, 0), + 0, + 0)); + jLabelAnalysis.setText("Type of analysis:"); buttonGroupChoiceAnalysis.add(_jRadioButton2DAnalysis); buttonGroupChoiceAnalysis.add(_jRadioButton3DAnalysis); buttonGroupChoiceAnalysis.add(_jRadioButton2D3DAnalysis); - _jRadioButton2DAnalysis.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _jRadioButton3DAnalysis.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _jRadioButton2D3DAnalysis.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jRadioButton2DAnalysis, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(130, 170, 0, 0), - 0, - 0)); - _container.add(_jRadioButton3DAnalysis, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(130, 120, 0, 0), - 0, - 0)); - _container.add(_jRadioButton2D3DAnalysis, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(130, 10, 0, 0), - 0, - 0)); + _jRadioButton2DAnalysis.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + _jRadioButton3DAnalysis.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + _jRadioButton2D3DAnalysis.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jRadioButton2DAnalysis, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(130, 170, 0, 0), + 0, + 0)); + container.add(_jRadioButton3DAnalysis, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(130, 120, 0, 0), + 0, + 0)); + container.add(_jRadioButton2D3DAnalysis, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(130, 10, 0, 0), + 0, + 0)); _jRadioButton2D3DAnalysis.setSelected(true); OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean(); int nbProc = bean.getAvailableProcessors(); - for (int i = 1; i <= nbProc; ++i) _comboBoxCpu.addItem(i); - _jLabelNbCpu = new JLabel(); - _jLabelNbCpu.setText("How many CPU(s) :"); - _container.add(_jLabelNbCpu, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(175, 10, 0, 0), - 0, - 0)); - _container.add(_comboBoxCpu, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(170, 200, 0, 0), - 0, - 0)); - _comboBoxCpu.addItemListener(new ItemState()); + for (int i = 1; i <= nbProc; ++i) comboBoxCpu.addItem(i); + jLabelNbCpu.setText("How many CPU(s) :"); + container.add(jLabelNbCpu, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(175, 10, 0, 0), + 0, + 0)); + container.add(comboBoxCpu, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(170, 200, 0, 0), + 0, + 0)); + comboBoxCpu.addItemListener(new ItemState()); - _container.add(_jButtonStart, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(210, 140, 0, 0), - 0, - 0)); - _jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); - _container.add(_jButtonQuit, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(210, 10, 0, 0), - 0, - 0)); - _jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); + container.add(jButtonStart, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(210, 140, 0, 0), + 0, + 0)); + jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); + container.add(jButtonQuit, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(210, 10, 0, 0), + 0, + 0)); + jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); this.setVisible(true); WorkDirectoryListener wdListener = new WorkDirectoryListener(); - _jButtonWorkDirectory.addActionListener(wdListener); - RawDataDirectroryListener ddListener = new RawDataDirectroryListener(); - _jButtonRawData.addActionListener(ddListener); + jButtonWorkDirectory.addActionListener(wdListener); + RawDataDirectoryListener ddListener = new RawDataDirectoryListener(); + jButtonRawData.addActionListener(ddListener); QuitListener quitListener = new QuitListener(this); - _jButtonQuit.addActionListener(quitListener); + jButtonQuit.addActionListener(quitListener); StartListener startListener = new StartListener(this); - _jButtonStart.addActionListener(startListener); + jButtonStart.addActionListener(startListener); } - /** @param args */ + + /** @param args arguments */ public static void main(String[] args) { NucleusSegmentationAndAnalysisBatchDialog nucleusSegmentationAndAnalysisBatchDialog = new NucleusSegmentationAndAnalysisBatchDialog(); nucleusSegmentationAndAnalysisBatchDialog.setLocationRelativeTo(null); } + public int getNbCpu() { return _nbCpuChosen; } + public void setNbCpu(int nb) { _nbCpuChosen = nb; } + public double getXCalibration() { String xCal = _jTextFieldXCalibration.getText(); return Double.parseDouble(xCal.replaceAll(",", ".")); } + public double getYCalibration() { String yCal = _jTextFieldYCalibration.getText(); return Double.parseDouble(yCal.replaceAll(",", ".")); } + public double getZCalibration() { String zCal = _jTextFieldZCalibration.getText(); return Double.parseDouble(zCal.replaceAll(",", ".")); } + public String getUnit() { return _jTextFieldUnit.getText(); } + public double getMinVolume() { return Double.parseDouble(_jTextFieldMin.getText()); } + public double getMaxVolume() { return Double.parseDouble(_jTextFieldMax.getText()); } + public String getWorkDirectory() { return _jTextFieldWorkDirectory.getText(); } + public String getRawDataDirectory() { return _jTextFieldRawData.getText(); } + public boolean isStart() { return _start; } + public boolean is2D3DAnalysis() { return _jRadioButton2D3DAnalysis.isSelected(); } + public boolean is2D() { return _jRadioButton2DAnalysis.isSelected(); } + public boolean is3D() { return _jRadioButton3DAnalysis.isSelected(); } @@ -563,6 +558,7 @@ public void itemStateChanged(ItemEvent e) { } } + /** * */ @@ -570,11 +566,12 @@ class StartListener implements ActionListener { NucleusSegmentationAndAnalysisBatchDialog _nucleusSegmentationAndAnalysisBatchDialog; - /** @param nucleusSegmentationAndAnalysisBatchDialog */ + /** @param nucleusSegmentationAndAnalysisBatchDialog nucleusSegmentationAndAnalysisBatchDialog GUI */ public StartListener(NucleusSegmentationAndAnalysisBatchDialog nucleusSegmentationAndAnalysisBatchDialog) { _nucleusSegmentationAndAnalysisBatchDialog = nucleusSegmentationAndAnalysisBatchDialog; } + /** * */ @@ -591,17 +588,19 @@ public void actionPerformed(ActionEvent actionEvent) { } } + /** * */ - class QuitListener implements ActionListener { + static class QuitListener implements ActionListener { NucleusSegmentationAndAnalysisBatchDialog _nucleusSegmentationAndAnalysisBatchDialog; - /** @param nucleusSegmentationAndAnalysisBatchDialog */ + /** @param nucleusSegmentationAndAnalysisBatchDialog nucleusSegmentationAndAnalysisBatchDialog GUI */ public QuitListener(NucleusSegmentationAndAnalysisBatchDialog nucleusSegmentationAndAnalysisBatchDialog) { _nucleusSegmentationAndAnalysisBatchDialog = nucleusSegmentationAndAnalysisBatchDialog; } + /** * */ @@ -610,6 +609,7 @@ public void actionPerformed(ActionEvent actionEvent) { } } + /** * */ @@ -625,17 +625,18 @@ public void actionPerformed(ActionEvent actionEvent) { if (returnValue == JFileChooser.APPROVE_OPTION) { @SuppressWarnings("unused") String run = jFileChooser.getSelectedFile().getName(); - _workDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); - _jTextFieldWorkDirectory.setText(_workDirectory); + String workDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); + _jTextFieldWorkDirectory.setText(workDirectory); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } + /** * */ - class RawDataDirectroryListener implements ActionListener { + class RawDataDirectoryListener implements ActionListener { /** * */ @@ -647,8 +648,8 @@ public void actionPerformed(ActionEvent actionEvent) { if (returnValue == JFileChooser.APPROVE_OPTION) { @SuppressWarnings("unused") String run = jFileChooser.getSelectedFile().getName(); - _rawDataDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); - _jTextFieldRawData.setText(_rawDataDirectory); + String rawDataDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); + _jTextFieldRawData.setText(rawDataDirectory); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } diff --git a/src/main/java/gred/nucleus/dialogs/NucleusSegmentationAndAnalysisDialog.java b/src/main/java/gred/nucleus/dialogs/NucleusSegmentationAndAnalysisDialog.java index 507dcb9e..92c3ea89 100644 --- a/src/main/java/gred/nucleus/dialogs/NucleusSegmentationAndAnalysisDialog.java +++ b/src/main/java/gred/nucleus/dialogs/NucleusSegmentationAndAnalysisDialog.java @@ -14,50 +14,50 @@ */ public class NucleusSegmentationAndAnalysisDialog extends JFrame { - private static final long serialVersionUID = 1L; - private final JButton _jButtonStart = new JButton("Start"); - private final JButton _jButtonQuit = new JButton("Quit"); - private final Container _container; - private final JFormattedTextField _jTextFieldXCalibration = new JFormattedTextField(Number.class); - private final JFormattedTextField _jTextFieldYCalibration = new JFormattedTextField(Number.class); - private final JFormattedTextField _jTextFieldZCalibration = new JFormattedTextField(Number.class); - private final JFormattedTextField _jTextFieldMax = new JFormattedTextField(Number.class); - private final JFormattedTextField _jTextFieldMin = new JFormattedTextField(Number.class); - private final JTextField _jTextFieldUnit = new JTextField(); - private final JLabel _jLabelXcalibration; - private final JLabel _jLabelYcalibration; - private final JLabel _jLabelZcalibration; - private final JLabel _jLabelUnit; - private final JLabel _jLabelSegmentation; - private final JLabel _jLabelVolumeMin; - private final JLabel _jLabelVolumeMax; - private final JLabel _jLabelAnalysis; - private final JLabel _JLabelCalibration; - private final ButtonGroup buttonGroupChoiceAnalysis = new ButtonGroup(); - private final JRadioButton _jRadioButton2D = new JRadioButton("2D"); - private final JRadioButton _jRadioButton3D = new JRadioButton("3D"); - private final JRadioButton _jRadioButton2D3D = new JRadioButton("2D and 3D"); - private JLabel _jLabelUnitTexte; - private boolean _start = false; + private static final long serialVersionUID = 1L; + private final JFormattedTextField _jTextFieldXCalibration = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldYCalibration = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldZCalibration = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldMax = new JFormattedTextField(Number.class); + private final JFormattedTextField _jTextFieldMin = new JFormattedTextField(Number.class); + private final JTextField _jTextFieldUnit = new JTextField(); + private final JRadioButton _jRadioButton2D = new JRadioButton("2D"); + private final JRadioButton _jRadioButton3D = new JRadioButton("3D"); + private final JRadioButton _jRadioButton2D3D = new JRadioButton("2D and 3D"); + private boolean _start = false; /** Architecture of the graphical windows */ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { + final JButton jButtonStart = new JButton("Start"); + final JButton jButtonQuit = new JButton("Quit"); + final Container container; + final JLabel jLabelXCalibration; + final JLabel jLabelYCalibration; + final JLabel jLabelZCalibration; + final JLabel jLabelUnit; + final JLabel jLabelSegmentation; + final JLabel jLabelVolumeMin; + final JLabel jLabelVolumeMax; + final JLabel jLabelAnalysis; + final JLabel jLabelCalibration; + JLabel jLabelUnitText; + final ButtonGroup buttonGroupChoiceAnalysis = new ButtonGroup(); this.setTitle("Nucleus segmentation & analysis"); this.setSize(500, 350); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); - _container = getContentPane(); + container = getContentPane(); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.1}; gridBagLayout.rowHeights = new int[]{17, 100, 124, 7}; gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.1}; gridBagLayout.columnWidths = new int[]{236, 109, 72, 20}; - _container.setLayout(gridBagLayout); + container.setLayout(gridBagLayout); - _JLabelCalibration = new JLabel(); - _container.add + jLabelCalibration = new JLabel(); + container.add ( - _JLabelCalibration, + jLabelCalibration, new GridBagConstraints ( 0, 1, 0, 0, 0.0, 0.0, @@ -66,13 +66,13 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(0, 10, 0, 0), 0, 0 ) ); - _JLabelCalibration.setText("Voxel Calibration:"); + jLabelCalibration.setText("Voxel Calibration:"); - _container.setLayout(gridBagLayout); - _jLabelXcalibration = new JLabel(); - _container.add + container.setLayout(gridBagLayout); + jLabelXCalibration = new JLabel(); + container.add ( - _jLabelXcalibration, + jLabelXCalibration, new GridBagConstraints ( 0, 1, 0, 0, 0.0, 0.0, @@ -81,9 +81,9 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(20, 20, 0, 0), 0, 0 ) ); - _jLabelXcalibration.setText("x :"); - _jLabelXcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add + jLabelXCalibration.setText("x :"); + jLabelXCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add ( _jTextFieldXCalibration, new GridBagConstraints @@ -97,10 +97,10 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { _jTextFieldXCalibration.setText("" + cal.pixelWidth); _jTextFieldXCalibration.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelYcalibration = new JLabel(); - _container.add + jLabelYCalibration = new JLabel(); + container.add ( - _jLabelYcalibration, + jLabelYCalibration, new GridBagConstraints ( 0, 1, 0, 0, 0.0, 0.0, @@ -109,9 +109,9 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(45, 20, 0, 0), 0, 0 ) ); - _jLabelYcalibration.setText("y :"); - _jLabelYcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add + jLabelYCalibration.setText("y :"); + jLabelYCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add ( _jTextFieldYCalibration, new GridBagConstraints @@ -125,10 +125,10 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { _jTextFieldYCalibration.setText("" + cal.pixelWidth); _jTextFieldYCalibration.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelZcalibration = new JLabel(); - _container.add + jLabelZCalibration = new JLabel(); + container.add ( - _jLabelZcalibration, + jLabelZCalibration, new GridBagConstraints ( 0, 1, 0, 0, 0.0, 0.0, @@ -137,9 +137,9 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(70, 20, 0, 0), 0, 0 ) ); - _jLabelZcalibration.setText("z :"); - _jLabelZcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add + jLabelZCalibration.setText("z :"); + jLabelZCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add ( _jTextFieldZCalibration, new GridBagConstraints @@ -153,10 +153,10 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { _jTextFieldZCalibration.setText("" + cal.pixelDepth); _jTextFieldZCalibration.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelUnit = new JLabel(); - _container.add + jLabelUnit = new JLabel(); + container.add ( - _jLabelUnit, + jLabelUnit, new GridBagConstraints ( 0, 1, 0, 0, 0.0, 0.0, @@ -165,9 +165,9 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(95, 20, 0, 0), 0, 0 ) ); - _jLabelUnit.setText("unit :"); - _jLabelUnit.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add + jLabelUnit.setText("unit :"); + jLabelUnit.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add ( _jTextFieldUnit, new GridBagConstraints @@ -182,10 +182,10 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { _jTextFieldUnit.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelSegmentation = new JLabel(); - _container.add + jLabelSegmentation = new JLabel(); + container.add ( - _jLabelSegmentation, + jLabelSegmentation, new GridBagConstraints ( 0, 2, 0, 0, 0.0, 0.0, @@ -194,12 +194,12 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(20, 10, 0, 0), 0, 0 ) ); - _jLabelSegmentation.setText("Choose the min and max volumes of the nucleus:"); + jLabelSegmentation.setText("Choose the min and max volumes of the nucleus:"); - _jLabelVolumeMin = new JLabel(); - _container.add + jLabelVolumeMin = new JLabel(); + container.add ( - _jLabelVolumeMin, + jLabelVolumeMin, new GridBagConstraints ( 0, 2, 0, 0, 0.0, 0.0, @@ -208,9 +208,9 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(40, 20, 0, 0), 0, 0 ) ); - _jLabelVolumeMin.setText("Minimun volume of the segmented nucleus :"); - _jLabelVolumeMin.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add + jLabelVolumeMin.setText("Minimum volume of the segmented nucleus :"); + jLabelVolumeMin.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add ( _jTextFieldMin, new GridBagConstraints @@ -224,10 +224,10 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { _jTextFieldMin.setText("15"); _jTextFieldMin.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelUnitTexte = new JLabel(); - _container.add + jLabelUnitText = new JLabel(); + container.add ( - _jLabelUnitTexte, + jLabelUnitText, new GridBagConstraints ( 0, 2, 0, 0, 0.0, 0.0, @@ -236,13 +236,13 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(40, 410, 0, 0), 0, 0 ) ); - _jLabelUnitTexte.setText("unit^3"); - _jLabelUnitTexte.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); + jLabelUnitText.setText("unit^3"); + jLabelUnitText.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); - _jLabelVolumeMax = new JLabel(); - _container.add + jLabelVolumeMax = new JLabel(); + container.add ( - _jLabelVolumeMax, + jLabelVolumeMax, new GridBagConstraints ( 0, 2, 0, 0, 0.0, 0.0, @@ -251,9 +251,9 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(70, 20, 0, 0), 0, 0 ) ); - _jLabelVolumeMax.setText("Maximum volume of the segmented nucleus :"); - _jLabelVolumeMax.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add + jLabelVolumeMax.setText("Maximum volume of the segmented nucleus :"); + jLabelVolumeMax.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add ( _jTextFieldMax, new GridBagConstraints @@ -266,10 +266,10 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { ); _jTextFieldMax.setText("2000"); _jTextFieldMax.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelUnitTexte = new JLabel(); - _container.add + jLabelUnitText = new JLabel(); + container.add ( - _jLabelUnitTexte, + jLabelUnitText, new GridBagConstraints ( 0, 2, 0, 0, 0.0, 0.0, @@ -278,13 +278,13 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(70, 410, 0, 0), 0, 0 ) ); - _jLabelUnitTexte.setText("unit^3"); - _jLabelUnitTexte.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); + jLabelUnitText.setText("unit^3"); + jLabelUnitText.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); - _jLabelAnalysis = new JLabel(); - _container.add + jLabelAnalysis = new JLabel(); + container.add ( - _jLabelAnalysis, + jLabelAnalysis, new GridBagConstraints ( 0, 2, 0, 0, 0.0, 0.0, @@ -293,15 +293,15 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(100, 10, 0, 0), 0, 0 ) ); - _jLabelAnalysis.setText("Type of analysis:"); + jLabelAnalysis.setText("Type of analysis:"); buttonGroupChoiceAnalysis.add(_jRadioButton2D); buttonGroupChoiceAnalysis.add(_jRadioButton3D); buttonGroupChoiceAnalysis.add(_jRadioButton2D3D); - _jRadioButton2D.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _jRadioButton3D.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _jRadioButton2D3D.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add + _jRadioButton2D.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + _jRadioButton3D.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + _jRadioButton2D3D.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add ( _jRadioButton2D, new GridBagConstraints @@ -312,7 +312,7 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(130, 170, 0, 0), 0, 0 ) ); - _container.add + container.add ( _jRadioButton3D, new GridBagConstraints @@ -323,7 +323,7 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(130, 120, 0, 0), 0, 0 ) ); - _container.add + container.add ( _jRadioButton2D3D, new GridBagConstraints @@ -336,9 +336,9 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { ); _jRadioButton2D3D.setSelected(true); - _container.add + container.add ( - _jButtonStart, + jButtonStart, new GridBagConstraints ( 0, 2, 0, 0, 0.0, 0.0, @@ -347,10 +347,10 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(160, 140, 0, 0), 0, 0 ) ); - _jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); - _container.add + jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); + container.add ( - _jButtonQuit, + jButtonQuit, new GridBagConstraints ( 0, 2, 0, 0, 0.0, 0.0, @@ -359,92 +359,104 @@ public NucleusSegmentationAndAnalysisDialog(Calibration cal) { new Insets(160, 10, 0, 0), 0, 0 ) ); - _jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); + jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); this.setVisible(true); QuitListener quitListener = new QuitListener(this); - _jButtonQuit.addActionListener(quitListener); + jButtonQuit.addActionListener(quitListener); StartListener startListener = new StartListener(this); - _jButtonStart.addActionListener(startListener); + jButtonStart.addActionListener(startListener); } + public double getXCalibration() { String xCal = _jTextFieldXCalibration.getText(); return Double.parseDouble(xCal.replaceAll(",", ".")); } + public double getYCalibration() { String yCal = _jTextFieldYCalibration.getText(); return Double.parseDouble(yCal.replaceAll(",", ".")); } + public double getZCalibration() { String zCal = _jTextFieldZCalibration.getText(); return Double.parseDouble(zCal.replaceAll(",", ".")); } + public String getUnit() { return _jTextFieldUnit.getText(); } + public double getMinVolume() { return Double.parseDouble(_jTextFieldMin.getText()); } + public double getMaxVolume() { return Double.parseDouble(_jTextFieldMax.getText()); } + public boolean isStart() { return _start; } + public boolean is2D3DAnalysis() { return _jRadioButton2D3D.isSelected(); } + public boolean is2D() { return _jRadioButton2D.isSelected(); } + public boolean is3D() { return _jRadioButton3D.isSelected(); } - /** Classes listener to interact with the several elements of the window */ - class StartListener implements ActionListener { - - NucleusSegmentationAndAnalysisDialog _nucleusSegmentationAndAnalysisDialog; + /** + * + */ + static class QuitListener implements ActionListener { + final NucleusSegmentationAndAnalysisDialog _nucleusSegmentationAndAnalysisDialog; - /** @param nucleusSegmentationAndAnalysisDialog */ - public StartListener(NucleusSegmentationAndAnalysisDialog nucleusSegmentationAndAnalysisDialog) { + /** @param nucleusSegmentationAndAnalysisDialog nucleusSegmentationAndAnalysisDialog GUI */ + public QuitListener(NucleusSegmentationAndAnalysisDialog nucleusSegmentationAndAnalysisDialog) { _nucleusSegmentationAndAnalysisDialog = nucleusSegmentationAndAnalysisDialog; } + /** * */ public void actionPerformed(ActionEvent actionEvent) { - _start = true; _nucleusSegmentationAndAnalysisDialog.dispose(); } } - /** - * - */ - class QuitListener implements ActionListener { - NucleusSegmentationAndAnalysisDialog _nucleusSegmentationAndAnalysisDialog; + /** Classes listener to interact with the several elements of the window */ + class StartListener implements ActionListener { - /** @param nucleusSegmentationAndAnalysisDialog */ - public QuitListener(NucleusSegmentationAndAnalysisDialog nucleusSegmentationAndAnalysisDialog) { + final NucleusSegmentationAndAnalysisDialog _nucleusSegmentationAndAnalysisDialog; + + /** @param nucleusSegmentationAndAnalysisDialog nucleusSegmentationAndAnalysisDialog GUI */ + public StartListener(NucleusSegmentationAndAnalysisDialog nucleusSegmentationAndAnalysisDialog) { _nucleusSegmentationAndAnalysisDialog = nucleusSegmentationAndAnalysisDialog; } + /** * */ public void actionPerformed(ActionEvent actionEvent) { + _start = true; _nucleusSegmentationAndAnalysisDialog.dispose(); } } diff --git a/src/main/java/gred/nucleus/dialogs/NucleusSegmentationBatchDialog.java b/src/main/java/gred/nucleus/dialogs/NucleusSegmentationBatchDialog.java index ebf8ce13..5d25cf31 100644 --- a/src/main/java/gred/nucleus/dialogs/NucleusSegmentationBatchDialog.java +++ b/src/main/java/gred/nucleus/dialogs/NucleusSegmentationBatchDialog.java @@ -16,12 +16,6 @@ */ public class NucleusSegmentationBatchDialog extends JFrame { private static final long serialVersionUID = 1L; - private final JButton _jButtonWorkDirectory = new JButton("Output Directory"); - private final JButton _jButtonStart = new JButton("Start"); - private final JButton _jButtonQuit = new JButton("Quit"); - private final JButton _jButtonRawData = new JButton("Raw Data"); - private final Container _container; - private final JComboBox _comboBoxCpu = new JComboBox<>(); private final JFormattedTextField _jTextFieldXCalibration = new JFormattedTextField(Number.class); private final JFormattedTextField _jTextFieldYCalibration = new JFormattedTextField(Number.class); private final JFormattedTextField _jTextFieldZCalibration = new JFormattedTextField(Number.class); @@ -30,426 +24,443 @@ public class NucleusSegmentationBatchDialog extends JFrame { private final JTextField _jTextFieldUnit = new JTextField(); private final JTextField _jTextFieldWorkDirectory = new JTextField(); private final JTextField _jTextFieldRawData = new JTextField(); - private final JLabel _jLabelXcalibration; - private final JLabel _jLabelYcalibration; - private final JLabel _jLabelZcalibration; - private final JLabel _jLabelUnit; - private final JLabel _jLabelSegmentation; - private final JLabel _jLabelVolumeMin; - private final JLabel _jLabelVolumeMax; - private final JLabel _jLabelWorkDirectory; - private final JLabel _jLabelCalibration; - private final JLabel _jLabelNbCpu; - private String _workDirectory; - private String _rawDataDirectory; private boolean _start = false; private int _nbCpuChosen = 1; /** Architecture of the graphical windows */ public NucleusSegmentationBatchDialog() { + final JButton jButtonWorkDirectory = new JButton("Output Directory"); + final JButton jButtonStart = new JButton("Start"); + final JButton jButtonQuit = new JButton("Quit"); + final JButton jButtonRawData = new JButton("Raw Data"); + final JComboBox comboBoxCpu = new JComboBox<>(); + final Container container; + final JLabel jLabelXCalibration; + final JLabel jLabelYCalibration; + final JLabel jLabelZCalibration; + final JLabel jLabelUnit; + final JLabel jLabelSegmentation; + final JLabel jLabelVolumeMin; + final JLabel jLabelVolumeMax; + final JLabel jLabelWorkDirectory; + final JLabel jLabelCalibration; + final JLabel jLabelNbCpu; this.setTitle("Nucleus segmentation (batch)"); this.setSize(500, 450); this.setLocationRelativeTo(null); - _container = getContentPane(); + container = getContentPane(); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.1}; gridBagLayout.rowHeights = new int[]{17, 71, 124, 7}; gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.1}; gridBagLayout.columnWidths = new int[]{236, 109, 72, 20}; - _container.setLayout(gridBagLayout); - _jLabelWorkDirectory = new JLabel(); - _container.add(_jLabelWorkDirectory, - new GridBagConstraints(0, - 1, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(0, 10, 0, 0), - 0, - 0)); - _jLabelWorkDirectory.setText("Work directory and Raw data choice : "); - _container.add(_jButtonRawData, - new GridBagConstraints(0, - 1, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(30, 10, 0, 0), - 0, - 0)); - _jButtonRawData.setPreferredSize(new java.awt.Dimension(120, 21)); - _jButtonRawData.setFont(new java.awt.Font("Albertus", 2, 10)); - _container.add(_jTextFieldRawData, - new GridBagConstraints(0, - 1, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(30, 160, 0, 0), - 0, - 0)); + container.setLayout(gridBagLayout); + jLabelWorkDirectory = new JLabel(); + container.add(jLabelWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0, 10, 0, 0), + 0, + 0)); + jLabelWorkDirectory.setText("Work directory and Raw data choice : "); + container.add(jButtonRawData, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(30, 10, 0, 0), + 0, + 0)); + jButtonRawData.setPreferredSize(new java.awt.Dimension(120, 21)); + jButtonRawData.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + container.add(_jTextFieldRawData, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(30, 160, 0, 0), + 0, + 0)); _jTextFieldRawData.setPreferredSize(new java.awt.Dimension(280, 21)); - _jTextFieldRawData.setFont(new java.awt.Font("Albertus", 2, 10)); - _container.add(_jButtonWorkDirectory, - new GridBagConstraints(0, - 1, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(60, 10, 0, 0), - 0, - 0)); - _jButtonWorkDirectory.setPreferredSize(new java.awt.Dimension(120, 21)); - _jButtonWorkDirectory.setFont(new java.awt.Font("Albertus", 2, 10)); - _container.add(_jTextFieldWorkDirectory, - new GridBagConstraints(0, - 1, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(60, 160, 0, 0), - 0, - 0)); + _jTextFieldRawData.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + container.add(jButtonWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(60, 10, 0, 0), + 0, + 0)); + jButtonWorkDirectory.setPreferredSize(new java.awt.Dimension(120, 21)); + jButtonWorkDirectory.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + container.add(_jTextFieldWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(60, 160, 0, 0), + 0, + 0)); _jTextFieldWorkDirectory.setPreferredSize(new java.awt.Dimension(280, 21)); - _jTextFieldWorkDirectory.setFont(new java.awt.Font("Albertus", 2, 10)); - _jLabelCalibration = new JLabel(); - _container.add(_jLabelCalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(20, 10, 0, 0), - 0, - 0)); - _jLabelCalibration.setText("Voxel Calibration:"); - _container.setLayout(gridBagLayout); - _jLabelXcalibration = new JLabel(); - _container.add(_jLabelXcalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(40, 20, 0, 0), - 0, - 0)); - _jLabelXcalibration.setText("x :"); - _jLabelXcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldXCalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(40, 60, 0, 0), - 0, - 0)); + _jTextFieldWorkDirectory.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + jLabelCalibration = new JLabel(); + container.add(jLabelCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(20, 10, 0, 0), + 0, + 0)); + jLabelCalibration.setText("Voxel Calibration:"); + container.setLayout(gridBagLayout); + jLabelXCalibration = new JLabel(); + container.add(jLabelXCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 20, 0, 0), + 0, + 0)); + jLabelXCalibration.setText("x :"); + jLabelXCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldXCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 60, 0, 0), + 0, + 0)); _jTextFieldXCalibration.setText("1"); _jTextFieldXCalibration.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelYcalibration = new JLabel(); - _container.add(_jLabelYcalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(65, 20, 0, 0), - 0, - 0)); - _jLabelYcalibration.setText("y :"); - _jLabelYcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldYCalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(65, 60, 0, 0), - 0, - 0)); + jLabelYCalibration = new JLabel(); + container.add(jLabelYCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(65, 20, 0, 0), + 0, + 0)); + jLabelYCalibration.setText("y :"); + jLabelYCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldYCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(65, 60, 0, 0), + 0, + 0)); _jTextFieldYCalibration.setText("1"); _jTextFieldYCalibration.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelZcalibration = new JLabel(); - _container.add(_jLabelZcalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(90, 20, 0, 0), - 0, - 0)); - _jLabelZcalibration.setText("z :"); - _jLabelZcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldZCalibration, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(90, 60, 0, 0), - 0, - 0)); + jLabelZCalibration = new JLabel(); + container.add(jLabelZCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(90, 20, 0, 0), + 0, + 0)); + jLabelZCalibration.setText("z :"); + jLabelZCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldZCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(90, 60, 0, 0), + 0, + 0)); _jTextFieldZCalibration.setText("1"); _jTextFieldZCalibration.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelUnit = new JLabel(); - _container.add(_jLabelUnit, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(115, 20, 0, 0), - 0, - 0)); - _jLabelUnit.setText("unit :"); - _jLabelUnit.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldUnit, - new GridBagConstraints(0, - 2, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(115, 60, 0, 0), - 0, - 0)); + jLabelUnit = new JLabel(); + container.add(jLabelUnit, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(115, 20, 0, 0), + 0, + 0)); + jLabelUnit.setText("unit :"); + jLabelUnit.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldUnit, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(115, 60, 0, 0), + 0, + 0)); _jTextFieldUnit.setText("pixel"); _jTextFieldUnit.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelSegmentation = new JLabel(); - _container.add(_jLabelSegmentation, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(20, 10, 0, 0), - 0, - 0)); - _jLabelSegmentation.setText("Choose the min and max volumes of the nucleus:"); - _jLabelVolumeMin = new JLabel(); - _container.add(_jLabelVolumeMin, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(40, 20, 0, 0), - 0, - 0)); - _jLabelVolumeMin.setText("Minimun volume of the segmented nucleus :"); - _jLabelVolumeMin.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldMin, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(40, 320, 0, 0), - 0, - 0)); + jLabelSegmentation = new JLabel(); + container.add(jLabelSegmentation, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(20, 10, 0, 0), + 0, + 0)); + jLabelSegmentation.setText("Choose the min and max volumes of the nucleus:"); + jLabelVolumeMin = new JLabel(); + container.add(jLabelVolumeMin, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 20, 0, 0), + 0, + 0)); + jLabelVolumeMin.setText("Minimum volume of the segmented nucleus :"); + jLabelVolumeMin.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldMin, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(40, 320, 0, 0), + 0, + 0)); _jTextFieldMin.setText("15"); _jTextFieldMin.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelVolumeMax = new JLabel(); - _container.add(_jLabelVolumeMax, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(70, 20, 0, 0), - 0, - 0)); - _jLabelVolumeMax.setText("Maximum volume of the segmented nucleus :"); - _jLabelVolumeMax.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); - _container.add(_jTextFieldMax, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(70, 320, 0, 0), - 0, - 0)); + jLabelVolumeMax = new JLabel(); + container.add(jLabelVolumeMax, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(70, 20, 0, 0), + 0, + 0)); + jLabelVolumeMax.setText("Maximum volume of the segmented nucleus :"); + jLabelVolumeMax.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); + container.add(_jTextFieldMax, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(70, 320, 0, 0), + 0, + 0)); _jTextFieldMax.setText("2000"); _jTextFieldMax.setPreferredSize(new java.awt.Dimension(60, 21)); OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean(); int nbCpu = bean.getAvailableProcessors(); - for (int i = 1; i <= nbCpu; ++i) _comboBoxCpu.addItem(i); - _jLabelNbCpu = new JLabel(); - _jLabelNbCpu.setText("How many CPU :"); - _container.add(_jLabelNbCpu, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(95, 10, 0, 0), - 0, - 0)); - _container.add(_comboBoxCpu, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(90, 200, 0, 0), - 0, - 0)); - _comboBoxCpu.addItemListener(new ItemState()); - _container.add(_jButtonStart, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(130, 140, 0, 0), - 0, - 0)); - _jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); - _container.add(_jButtonQuit, - new GridBagConstraints(0, - 3, - 0, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(130, 10, 0, 0), - 0, - 0)); - _jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); + for (int i = 1; i <= nbCpu; ++i) comboBoxCpu.addItem(i); + jLabelNbCpu = new JLabel(); + jLabelNbCpu.setText("How many CPU :"); + container.add(jLabelNbCpu, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(95, 10, 0, 0), + 0, + 0)); + container.add(comboBoxCpu, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(90, 200, 0, 0), + 0, + 0)); + comboBoxCpu.addItemListener(new ItemState()); + container.add(jButtonStart, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(130, 140, 0, 0), + 0, + 0)); + jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); + container.add(jButtonQuit, + new GridBagConstraints(0, + 3, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(130, 10, 0, 0), + 0, + 0)); + jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); this.setVisible(true); WorkDirectoryListener wdListener = new WorkDirectoryListener(); - _jButtonWorkDirectory.addActionListener(wdListener); + jButtonWorkDirectory.addActionListener(wdListener); RAwDataDirectoryListener ddListener = new RAwDataDirectoryListener(); - _jButtonRawData.addActionListener(ddListener); + jButtonRawData.addActionListener(ddListener); QuitListener quitListener = new QuitListener(this); - _jButtonQuit.addActionListener(quitListener); + jButtonQuit.addActionListener(quitListener); StartListener startListener = new StartListener(this); - _jButtonStart.addActionListener(startListener); + jButtonStart.addActionListener(startListener); } - /** @param args */ + + /** @param args arguments */ public static void main(String[] args) { NucleusSegmentationBatchDialog nucleusSegmentationBatchDialog = new NucleusSegmentationBatchDialog(); nucleusSegmentationBatchDialog.setLocationRelativeTo(null); } + public int getNbCpu() { return _nbCpuChosen; } + public void setNbCpu(int nb) { _nbCpuChosen = nb; } + public double getXCalibration() { String xCal = _jTextFieldXCalibration.getText(); return Double.parseDouble(xCal.replaceAll(",", ".")); } + public double getYCalibration() { String yCal = _jTextFieldYCalibration.getText(); return Double.parseDouble(yCal.replaceAll(",", ".")); } + public double getZCalibration() { String zCal = _jTextFieldZCalibration.getText(); return Double.parseDouble(zCal.replaceAll(",", ".")); } + public String getUnit() { return _jTextFieldUnit.getText(); } + public double getMinVolume() { return Double.parseDouble(_jTextFieldMin.getText()); } + public double getMaxVolume() { return Double.parseDouble(_jTextFieldMax.getText()); } + public String getWorkDirectory() { return _jTextFieldWorkDirectory.getText(); } + public String getRawDataDirectory() { return _jTextFieldRawData.getText(); } + public boolean isStart() { return _start; } + /** Classes listener to interact with the several elements of the window */ class ItemState implements ItemListener { /** @@ -460,17 +471,19 @@ public void itemStateChanged(ItemEvent e) { } } + /** * */ class StartListener implements ActionListener { - NucleusSegmentationBatchDialog _nucleusSegmentationBatchDialog; + final NucleusSegmentationBatchDialog _nucleusSegmentationBatchDialog; - /** @param nucleusSegmeentationBatchDialog */ - public StartListener(NucleusSegmentationBatchDialog nucleusSegmeentationBatchDialog) { - _nucleusSegmentationBatchDialog = nucleusSegmeentationBatchDialog; + /** @param nucleusSegmentationBatchDialog nucleusSegmentationBatchDialog GUI */ + public StartListener(NucleusSegmentationBatchDialog nucleusSegmentationBatchDialog) { + _nucleusSegmentationBatchDialog = nucleusSegmentationBatchDialog; } + /** * */ @@ -487,17 +500,19 @@ public void actionPerformed(ActionEvent actionEvent) { } } + /** * */ - class QuitListener implements ActionListener { - NucleusSegmentationBatchDialog _nucleusSegmentationBatchDialog; + static class QuitListener implements ActionListener { + final NucleusSegmentationBatchDialog _nucleusSegmentationBatchDialog; - /** @param nucleusSegmentationBatchDialog */ + /** @param nucleusSegmentationBatchDialog nucleusSegmentationBatchDialog GUI */ public QuitListener(NucleusSegmentationBatchDialog nucleusSegmentationBatchDialog) { _nucleusSegmentationBatchDialog = nucleusSegmentationBatchDialog; } + /** * */ @@ -506,6 +521,7 @@ public void actionPerformed(ActionEvent actionEvent) { } } + /** * */ @@ -520,13 +536,14 @@ public void actionPerformed(ActionEvent actionEvent) { int returnValue = jFileChooser.showOpenDialog(getParent()); if (returnValue == JFileChooser.APPROVE_OPTION) { @SuppressWarnings("unused") String run = jFileChooser.getSelectedFile().getName(); - _workDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); - _jTextFieldWorkDirectory.setText(_workDirectory); + String workDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); + _jTextFieldWorkDirectory.setText(workDirectory); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } + /** * */ @@ -541,8 +558,8 @@ public void actionPerformed(ActionEvent actionEvent) { int returnValue = jFileChooser.showOpenDialog(getParent()); if (returnValue == JFileChooser.APPROVE_OPTION) { @SuppressWarnings("unused") String run = jFileChooser.getSelectedFile().getName(); - _rawDataDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); - _jTextFieldRawData.setText(_rawDataDirectory); + String rawDataDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); + _jTextFieldRawData.setText(rawDataDirectory); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } diff --git a/src/main/java/gred/nucleus/dialogs/NucleusSegmentationDialog.java b/src/main/java/gred/nucleus/dialogs/NucleusSegmentationDialog.java index 4383225c..b8004df2 100644 --- a/src/main/java/gred/nucleus/dialogs/NucleusSegmentationDialog.java +++ b/src/main/java/gred/nucleus/dialogs/NucleusSegmentationDialog.java @@ -24,15 +24,15 @@ public class NucleusSegmentationDialog extends JFrame { private final JFormattedTextField _jTextFieldMax = new JFormattedTextField(Number.class); private final JFormattedTextField _jTextFieldMin = new JFormattedTextField(Number.class); private final JTextField _jTextFieldUnit = new JTextField(); - private final JLabel _jLabelXcalibration; - private final JLabel _jLabelYcalibration; - private final JLabel _jLabelZcalibration; + private final JLabel _jLabelXCalibration; + private final JLabel _jLabelYCalibration; + private final JLabel _jLabelZCalibration; private final JLabel _jLabelUnit; private final JLabel _jLabelSegmentation; private final JLabel _jLabelVolumeMin; private final JLabel _jLabelVolumeMax; private final JLabel _JLabelCalibration; - private JLabel _jLabelUnitTexte; + private JLabel _jLabelUnitText; private boolean _start = false; @@ -63,10 +63,10 @@ public NucleusSegmentationDialog(Calibration cal) { _JLabelCalibration.setText("Voxel Calibration:"); _container.setLayout(gridBagLayout); - _jLabelXcalibration = new JLabel(); + _jLabelXCalibration = new JLabel(); _container.add ( - _jLabelXcalibration, + _jLabelXCalibration, new GridBagConstraints ( 0, 1, 0, 0, 0.0, 0.0, @@ -75,8 +75,8 @@ public NucleusSegmentationDialog(Calibration cal) { new Insets(20, 20, 0, 0), 0, 0 ) ); - _jLabelXcalibration.setText("x :"); - _jLabelXcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); + _jLabelXCalibration.setText("x :"); + _jLabelXCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); _container.add ( _jTextFieldXCalibration, @@ -91,10 +91,10 @@ public NucleusSegmentationDialog(Calibration cal) { _jTextFieldXCalibration.setText("" + cal.pixelWidth); _jTextFieldXCalibration.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelYcalibration = new JLabel(); + _jLabelYCalibration = new JLabel(); _container.add ( - _jLabelYcalibration, + _jLabelYCalibration, new GridBagConstraints ( 0, 1, 0, 0, 0.0, 0.0, @@ -103,8 +103,8 @@ public NucleusSegmentationDialog(Calibration cal) { new Insets(45, 20, 0, 0), 0, 0 ) ); - _jLabelYcalibration.setText("y :"); - _jLabelYcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); + _jLabelYCalibration.setText("y :"); + _jLabelYCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); _container.add ( _jTextFieldYCalibration, @@ -119,10 +119,10 @@ public NucleusSegmentationDialog(Calibration cal) { _jTextFieldYCalibration.setText("" + cal.pixelHeight); _jTextFieldYCalibration.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelZcalibration = new JLabel(); + _jLabelZCalibration = new JLabel(); _container.add ( - _jLabelZcalibration, + _jLabelZCalibration, new GridBagConstraints ( 0, 1, 0, 0, 0.0, 0.0, @@ -131,8 +131,8 @@ public NucleusSegmentationDialog(Calibration cal) { new Insets(70, 20, 0, 0), 0, 0 ) ); - _jLabelZcalibration.setText("z :"); - _jLabelZcalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); + _jLabelZCalibration.setText("z :"); + _jLabelZCalibration.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); _container.add ( _jTextFieldZCalibration, @@ -160,7 +160,7 @@ public NucleusSegmentationDialog(Calibration cal) { ) ); _jLabelUnit.setText("unit :"); - _jLabelUnit.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); + _jLabelUnit.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); _container.add ( _jTextFieldUnit, @@ -201,8 +201,8 @@ public NucleusSegmentationDialog(Calibration cal) { new Insets(40, 20, 0, 0), 0, 0 ) ); - _jLabelVolumeMin.setText("Minimun volume of the segmented nucleus :"); - _jLabelVolumeMin.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); + _jLabelVolumeMin.setText("Minimum volume of the segmented nucleus :"); + _jLabelVolumeMin.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); _container.add ( _jTextFieldMin, @@ -217,10 +217,10 @@ public NucleusSegmentationDialog(Calibration cal) { _jTextFieldMin.setText("1"); _jTextFieldMin.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelUnitTexte = new JLabel(); + _jLabelUnitText = new JLabel(); _container.add ( - _jLabelUnitTexte, + _jLabelUnitText, new GridBagConstraints ( 0, 2, 0, 0, 0.0, 0.0, @@ -229,8 +229,8 @@ public NucleusSegmentationDialog(Calibration cal) { new Insets(40, 410, 0, 0), 0, 0 ) ); - _jLabelUnitTexte.setText("unit^3"); - _jLabelUnitTexte.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); + _jLabelUnitText.setText("unit^3"); + _jLabelUnitText.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); _jLabelVolumeMax = new JLabel(); _container.add @@ -245,7 +245,7 @@ public NucleusSegmentationDialog(Calibration cal) { ) ); _jLabelVolumeMax.setText("Maximum volume of the segmented nucleus :"); - _jLabelVolumeMax.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); + _jLabelVolumeMax.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); _container.add ( _jTextFieldMax, @@ -259,10 +259,10 @@ public NucleusSegmentationDialog(Calibration cal) { ); _jTextFieldMax.setText("2000"); _jTextFieldMax.setPreferredSize(new java.awt.Dimension(60, 21)); - _jLabelUnitTexte = new JLabel(); + _jLabelUnitText = new JLabel(); _container.add ( - _jLabelUnitTexte, + _jLabelUnitText, new GridBagConstraints ( 0, 2, 0, 0, 0.0, 0.0, @@ -271,8 +271,8 @@ public NucleusSegmentationDialog(Calibration cal) { new Insets(70, 410, 0, 0), 0, 0 ) ); - _jLabelUnitTexte.setText("unit^3"); - _jLabelUnitTexte.setFont(new java.awt.Font("Albertus Extra Bold (W1)", 2, 12)); + _jLabelUnitText.setText("unit^3"); + _jLabelUnitText.setFont(new java.awt.Font("Albertus Extra Bold (W1)", Font.ITALIC, 12)); _container.add ( @@ -306,42 +306,51 @@ public NucleusSegmentationDialog(Calibration cal) { _jButtonStart.addActionListener(startListener); } + public double getXCalibration() { String xCal = _jTextFieldXCalibration.getText(); return Double.parseDouble(xCal.replaceAll(",", ".")); } + public double getYCalibration() { String yCal = _jTextFieldYCalibration.getText(); return Double.parseDouble(yCal.replaceAll(",", ".")); } + public double getZCalibration() { String zCal = _jTextFieldZCalibration.getText(); return Double.parseDouble(zCal.replaceAll(",", ".")); } + public String getUnit() { return _jTextFieldUnit.getText(); } + public double getMinVolume() { return Double.parseDouble(_jTextFieldMin.getText()); } + public double getMaxVolume() { return Double.parseDouble(_jTextFieldMax.getText()); } + public boolean isStart() { return _start; } + public void action() { StartListener startListener = new StartListener(this); _jButtonStart.addActionListener(startListener); } + /** Classes listener to interact with the several elements of the window */ class StartListener implements ActionListener { NucleusSegmentationDialog _nucleusSegmentationDialog; @@ -351,6 +360,7 @@ public StartListener(NucleusSegmentationDialog nucleusSegmentationDialog) { _nucleusSegmentationDialog = nucleusSegmentationDialog; } + /** * */ @@ -360,16 +370,18 @@ public void actionPerformed(ActionEvent actionEvent) { } } + /** * */ - class QuitListener implements ActionListener { + static class QuitListener implements ActionListener { NucleusSegmentationDialog _nucleusSegmentationDialog; public QuitListener(NucleusSegmentationDialog nucleusSegmentationDialog) { _nucleusSegmentationDialog = nucleusSegmentationDialog; } + /** * */ diff --git a/src/main/java/gred/nucleus/dialogs/SegmentationConfigDialog.java b/src/main/java/gred/nucleus/dialogs/SegmentationConfigDialog.java index 9b78d5bb..df0cecbc 100644 --- a/src/main/java/gred/nucleus/dialogs/SegmentationConfigDialog.java +++ b/src/main/java/gred/nucleus/dialogs/SegmentationConfigDialog.java @@ -8,21 +8,21 @@ import java.awt.event.ItemListener; public class SegmentationConfigDialog extends JFrame implements ItemListener { - private final JTextField minVolume = new JTextField(); - private final JTextField maxVolume = new JTextField(); - private final JCheckBox giftWrapping = new JCheckBox(); - private final JTextField xCalibration = new JTextField(); - private final JTextField yCalibration = new JTextField(); - private final JTextField zCalibration = new JTextField(); - private final JCheckBox addCalibBox = new JCheckBox(); - private final Container _container; - private final JButton buttonOK = new JButton("Done"); - private final JPanel volumePane; + private final JTextField minVolume = new JTextField(); + private final JTextField maxVolume = new JTextField(); + private final JCheckBox giftWrapping = new JCheckBox(); + private final JTextField xCalibration = new JTextField(); + private final JTextField yCalibration = new JTextField(); + private final JTextField zCalibration = new JTextField(); + private final JCheckBox addCalibrationBox = new JCheckBox(); + private final JButton buttonOK = new JButton("Done"); + private final JPanel volumePane; + private final Container _container; private final SegmentationDialog caller; - private Boolean isGiftWrapping = true; - private JPanel XCalib; - private JPanel YCalib; - private JPanel ZCalib; + private Boolean isGiftWrapping = true; + private JPanel XCalibration; + private JPanel YCalibration; + private JPanel ZCalibration; public SegmentationConfigDialog(SegmentationDialog caller) { this.caller = caller; @@ -95,15 +95,15 @@ public SegmentationConfigDialog(SegmentationDialog caller) { \*\/*/ - JPanel calibPanel = new JPanel(); - JLabel calibLabel = new JLabel("Calibration:"); - calibLabel.setAlignmentX(0); - calibPanel.add(calibLabel); - addCalibBox.setSelected(false); - addCalibBox.setMinimumSize(new Dimension(100, 10)); - addCalibBox.addItemListener(this); - calibPanel.add(addCalibBox); - volumePane.add(calibPanel); + JPanel calibrationPanel = new JPanel(); + JLabel calibrationLabel = new JLabel("Calibration:"); + calibrationLabel.setAlignmentX(0); + calibrationPanel.add(calibrationLabel); + addCalibrationBox.setSelected(false); + addCalibrationBox.setMinimumSize(new Dimension(100, 10)); + addCalibrationBox.addItemListener(this); + calibrationPanel.add(addCalibrationBox); + volumePane.add(calibrationPanel); /*/\*\ @@ -129,36 +129,43 @@ public SegmentationConfigDialog(SegmentationDialog caller) { this.setVisible(false); - SegmentationConfigDialog.StartListener startListener = new SegmentationConfigDialog.StartListener(this); + SegmentationConfigDialog.StartListener startListener = new StartListener(this); buttonOK.addActionListener(startListener); } + public String getMinVolume() { return minVolume.getText(); } + public String getMaxVolume() { return maxVolume.getText(); } + public boolean getGiftWrapping() { return giftWrapping.isSelected(); } - public String getxCalibration() { + + public String getXCalibration() { return xCalibration.getText(); } - public String getyCalibration() { + + public String getYCalibration() { return yCalibration.getText(); } - public String getzCalibration() { + + public String getZCalibration() { return zCalibration.getText(); } - public boolean isCalibSelected() { - return addCalibBox.isSelected(); + + public boolean isCalibrationSelected() { + return addCalibrationBox.isSelected(); } @@ -166,50 +173,50 @@ public boolean isCalibSelected() { public void itemStateChanged(ItemEvent e) { if (e.getSource() == giftWrapping) { isGiftWrapping = giftWrapping.isSelected(); - } else if (e.getSource() == addCalibBox) { - if (addCalibBox.isSelected()) { + } else if (e.getSource() == addCalibrationBox) { + if (addCalibrationBox.isSelected()) { - XCalib = new JPanel(); - XCalib.setLayout(new BoxLayout(XCalib, BoxLayout.X_AXIS)); - XCalib.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); + XCalibration = new JPanel(); + XCalibration.setLayout(new BoxLayout(XCalibration, BoxLayout.X_AXIS)); + XCalibration.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); JLabel xBox2 = new JLabel("X:"); - XCalib.add(xBox2); - XCalib.add(Box.createRigidArea(new Dimension(10, 0))); + XCalibration.add(xBox2); + XCalibration.add(Box.createRigidArea(new Dimension(10, 0))); xCalibration.setText("1"); xCalibration.setMinimumSize(new Dimension(60, 10)); - XCalib.add(xCalibration); + XCalibration.add(xCalibration); - YCalib = new JPanel(); - YCalib.setLayout(new BoxLayout(YCalib, BoxLayout.X_AXIS)); - YCalib.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); + YCalibration = new JPanel(); + YCalibration.setLayout(new BoxLayout(YCalibration, BoxLayout.X_AXIS)); + YCalibration.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); JLabel yBox2 = new JLabel("Y:"); - YCalib.add(yBox2); - YCalib.add(Box.createRigidArea(new Dimension(10, 0))); + YCalibration.add(yBox2); + YCalibration.add(Box.createRigidArea(new Dimension(10, 0))); yCalibration.setText("1"); yCalibration.setMinimumSize(new Dimension(60, 10)); - YCalib.add(yCalibration); + YCalibration.add(yCalibration); - ZCalib = new JPanel(); - ZCalib.setLayout(new BoxLayout(ZCalib, BoxLayout.X_AXIS)); - ZCalib.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); + ZCalibration = new JPanel(); + ZCalibration.setLayout(new BoxLayout(ZCalibration, BoxLayout.X_AXIS)); + ZCalibration.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); JLabel zBox2 = new JLabel("Z:"); - ZCalib.add(zBox2); - ZCalib.add(Box.createRigidArea(new Dimension(10, 0))); + ZCalibration.add(zBox2); + ZCalibration.add(Box.createRigidArea(new Dimension(10, 0))); zCalibration.setText("1"); zCalibration.setMinimumSize(new Dimension(60, 10)); - ZCalib.add(zCalibration); + ZCalibration.add(zCalibration); volumePane.remove(buttonOK); - volumePane.add(XCalib); - volumePane.add(YCalib); - volumePane.add(ZCalib); + volumePane.add(XCalibration); + volumePane.add(YCalibration); + volumePane.add(ZCalibration); volumePane.add(buttonOK); } else { try { volumePane.remove(buttonOK); - volumePane.remove(XCalib); - volumePane.remove(YCalib); - volumePane.remove(ZCalib); + volumePane.remove(XCalibration); + volumePane.remove(YCalibration); + volumePane.remove(ZCalibration); volumePane.add(buttonOK); } catch (NullPointerException nullPointerException) { // Do nothing @@ -221,7 +228,7 @@ public void itemStateChanged(ItemEvent e) { } - class StartListener implements ActionListener { + static class StartListener implements ActionListener { SegmentationConfigDialog _segmentationDialog; /** @param segmentationDialog */ @@ -229,6 +236,7 @@ public StartListener(SegmentationConfigDialog segmentationDialog) { _segmentationDialog = segmentationDialog; } + public void actionPerformed(ActionEvent actionEvent) { _segmentationDialog.setVisible(false); } diff --git a/src/main/java/gred/nucleus/dialogs/SegmentationDialog.java b/src/main/java/gred/nucleus/dialogs/SegmentationDialog.java index 081ce906..3bbe940c 100644 --- a/src/main/java/gred/nucleus/dialogs/SegmentationDialog.java +++ b/src/main/java/gred/nucleus/dialogs/SegmentationDialog.java @@ -144,7 +144,7 @@ public SegmentationDialog() { _jButtonQuit.setPreferredSize(new java.awt.Dimension(60, 21)); this.setVisible(true); - SegmentationDialog.QuitListener quitListener = new SegmentationDialog.QuitListener(this); + SegmentationDialog.QuitListener quitListener = new QuitListener(this); _jButtonQuit.addActionListener(quitListener); SegmentationDialog.StartListener startListener = new SegmentationDialog.StartListener(this); _jButtonStart.addActionListener(startListener); @@ -152,30 +152,37 @@ public SegmentationDialog() { _jButtonConfig.addActionListener(configListener); } + public boolean isStart() { return _start; } + public String getInput() { return _jInputFileChooser.getText(); } + public String getOutput() { return _jOutputFileChooser.getText(); } + public String getConfig() { return _jConfigFileChooser.getText(); } + public int getConfigMode() { return configMode; } + public SegmentationConfigDialog getSegmentationConfigFileDialog() { return segmentationConfigFileDialog; } + public void actionPerformed(ActionEvent e) { switch (((JButton) e.getSource()).getName()) { case inputChooserName: @@ -274,16 +281,18 @@ public StartListener(SegmentationDialog autocropDialog) { _segmentationDialog = autocropDialog; } + public void actionPerformed(ActionEvent actionEvent) { _start = true; _segmentationDialog.dispose(); } } + /** * */ - class QuitListener implements ActionListener { + static class QuitListener implements ActionListener { SegmentationDialog _segmentationDialog; /** @param segmentationDialog */ @@ -291,6 +300,7 @@ public QuitListener(SegmentationDialog segmentationDialog) { _segmentationDialog = segmentationDialog; } + public void actionPerformed(ActionEvent actionEvent) { _segmentationDialog.dispose(); } @@ -304,6 +314,7 @@ public ConfigListener(SegmentationDialog segmentationDialog) { _segmentationDialog = segmentationDialog; } + public void actionPerformed(ActionEvent actionEvent) { segmentationConfigFileDialog.setVisible(true); } diff --git a/src/main/java/gred/nucleus/dialogs/computeParametersDialog.java b/src/main/java/gred/nucleus/dialogs/computeParametersDialog.java index 3326b7af..701eb949 100644 --- a/src/main/java/gred/nucleus/dialogs/computeParametersDialog.java +++ b/src/main/java/gred/nucleus/dialogs/computeParametersDialog.java @@ -10,212 +10,200 @@ public class computeParametersDialog extends JFrame implements ItemListener { private static final long serialVersionUID = 1L; private static final JButton _jButtonWorkDirectory = new JButton("Seg Data folder"); - private final JButton _jButtonStart = new JButton("Start"); - private final JButton _jButtonQuit = new JButton("Quit"); - private final JButton _JButtonRawData = new JButton("Raw Data folder"); - private final Container _container; private final JTextField _jTextFieldWorkDirectory = new JTextField(); private final JTextField _jTextFieldRawData = new JTextField(); - private final JLabel _jLabelWorkDirectory; - private final JLabel _jLabelCalibration; - private final JPanel Calib; - private final JTextPane unitRead = new JTextPane(); - private final JLabel unit = new JLabel(); - private final JLabel calibx = new JLabel(); - private final JLabel caliby = new JLabel(); - private final JLabel calibz = new JLabel(); - private final JTextPane calibXRead = new JTextPane(); - private final JTextPane calibYRead = new JTextPane(); - private final JTextPane calibZRead = new JTextPane(); - private final JCheckBox addCalibBox = new JCheckBox(); - private String _workDirectory; - private String _rawDataDirectory; + private final JTextPane _readUnit = new JTextPane(); + private final JLabel _jLabelUnit = new JLabel(); + private final JLabel _jLabelXCalibration = new JLabel(); + private final JLabel _jLabelYCalibration = new JLabel(); + private final JLabel _jLabelZCalibration = new JLabel(); + private final JTextPane _readXCalibration = new JTextPane(); + private final JTextPane _readYCalibration = new JTextPane(); + private final JTextPane _readZCalibration = new JTextPane(); + private final JCheckBox _addCalibrationBox = new JCheckBox(); + private final JPanel _calibration; private boolean _start = false; /** Architecture of the graphical windows */ public computeParametersDialog() { + final Container container = getContentPane(); + final JLabel jLabelWorkDirectory = new JLabel(); + final JLabel jLabelCalibration = new JLabel(); + final JButton jButtonStart = new JButton("Start"); + final JButton jButtonQuit = new JButton("Quit"); + final JButton JButtonRawData = new JButton("Raw Data folder"); this.setTitle("Compute morphological parameters"); this.setSize(500, 500); this.setLocationRelativeTo(null); - _container = getContentPane(); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.rowHeights = new int[]{17, 200, 124, 7, 10}; gridBagLayout.columnWidths = new int[]{236, 120, 72, 20}; - _container.setLayout(gridBagLayout); - - _jLabelWorkDirectory = new JLabel(); - _container.add - ( - _jLabelWorkDirectory, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(0, 10, 0, 0), 0, 0 - ) - ); - _jLabelWorkDirectory.setText("Work directory and Raw data choice : "); - + container.setLayout(gridBagLayout); + container.add(jLabelWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0, 10, 0, 0), + 0, + 0)); + jLabelWorkDirectory.setText("Work directory and Raw data choice : "); JTextPane jTextPane = new JTextPane(); - jTextPane.setText("You must select 2 directories:" - + "\n1 containing raw nuclei images. " - + "\n2 containing segmented nuclei images." - + "\nImages must have same file name."); + jTextPane.setText("You must select 2 directories:\n" + + "1 containing raw nuclei images. \n" + + "2 containing segmented nuclei images.\n" + + "Images must have same file name."); jTextPane.setEditable(false); - _container.add - ( - jTextPane, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(20, 20, 0, 0), 0, 0 - ) - ); - - _container.add - ( - _JButtonRawData, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(100, 10, 0, 0), 0, 0 - ) - ); - _JButtonRawData.setPreferredSize(new java.awt.Dimension(120, 21)); - _JButtonRawData.setFont(new java.awt.Font("Albertus", 2, 10)); - - _container.add - ( - _jTextFieldRawData, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(100, 160, 0, 0), 0, 0 - ) - ); + container.add(jTextPane, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(20, 20, 0, 0), + 0, + 0)); + container.add(JButtonRawData, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(100, 10, 0, 0), + 0, + 0)); + JButtonRawData.setPreferredSize(new java.awt.Dimension(120, 21)); + JButtonRawData.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + container.add(_jTextFieldRawData, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(100, 160, 0, 0), + 0, + 0)); _jTextFieldRawData.setPreferredSize(new java.awt.Dimension(280, 21)); - _jTextFieldRawData.setFont(new java.awt.Font("Albertus", 2, 10)); - - _container.add - ( - _jButtonWorkDirectory, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(140, 10, 0, 0), 0, 0 - ) - ); + _jTextFieldRawData.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + container.add(_jButtonWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(140, 10, 0, 0), + 0, + 0)); _jButtonWorkDirectory.setPreferredSize(new java.awt.Dimension(120, 21)); - _jButtonWorkDirectory.setFont(new java.awt.Font("Albertus", 2, 10)); - - _container.add - ( - _jTextFieldWorkDirectory, - new GridBagConstraints - ( - 0, 1, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(140, 160, 0, 0), 0, 0 - ) - ); + _jButtonWorkDirectory.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + container.add(_jTextFieldWorkDirectory, + new GridBagConstraints(0, + 1, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(140, 160, 0, 0), + 0, + 0)); _jTextFieldWorkDirectory.setPreferredSize(new java.awt.Dimension(280, 21)); - _jTextFieldWorkDirectory.setFont(new java.awt.Font("Albertus", 2, 10)); - - _jLabelCalibration = new JLabel(); - _container.add - ( - _jLabelCalibration, - new GridBagConstraints - ( - 0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(20, 10, 0, 0), 0, 0 - ) - ); - - Calib = new JPanel(); - Calib.setLayout(new GridBagLayout()); - + _jTextFieldWorkDirectory.setFont(new java.awt.Font("Albertus", Font.ITALIC, 10)); + container.add(jLabelCalibration, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(20, 10, 0, 0), + 0, + 0)); + _calibration = new JPanel(); + _calibration.setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.weightx = 2; gc.weighty = 5; gc.ipady = gc.anchor = GridBagConstraints.NORTHWEST; - - JLabel calibLabel = new JLabel("Calibration:"); + JLabel calibrationLabel = new JLabel("Calibration:"); gc.gridx = 0; gc.gridy = 0; - calibLabel.setAlignmentX(0); - Calib.add(calibLabel); - + calibrationLabel.setAlignmentX(0); + _calibration.add(calibrationLabel); gc.gridx = 1; - - addCalibBox.setSelected(false); - addCalibBox.addItemListener(this); - Calib.add(addCalibBox, gc); - - - _container.add(Calib, - new GridBagConstraints(0, - 2, - 2, - 0, - 0.0, - 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(0, 0, 0, 0), - 0, - 0)); - - - _container.add - ( - _jButtonStart, - new GridBagConstraints - ( - 0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(190, 140, 0, 0), 0, 0 - ) - ); - _jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); - _container.add - ( - _jButtonQuit, - new GridBagConstraints - ( - 0, 2, 0, 0, 0.0, 0.0, - GridBagConstraints.NORTHWEST, - GridBagConstraints.NONE, - new Insets(190, 10, 0, 0), 0, 0 - ) - ); - _jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); + _addCalibrationBox.setSelected(false); + _addCalibrationBox.addItemListener(this); + _calibration.add(_addCalibrationBox, gc); + container.add(_calibration, + new GridBagConstraints(0, + 2, + 2, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), + 0, + 0)); + container.add(jButtonStart, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(190, 140, 0, 0), + 0, + 0)); + jButtonStart.setPreferredSize(new java.awt.Dimension(120, 21)); + container.add(jButtonQuit, + new GridBagConstraints(0, + 2, + 0, + 0, + 0.0, + 0.0, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(190, 10, 0, 0), + 0, + 0)); + jButtonQuit.setPreferredSize(new java.awt.Dimension(120, 21)); this.setVisible(true); - computeParametersDialog.WorkDirectoryListener wdListener = new computeParametersDialog.WorkDirectoryListener(); _jButtonWorkDirectory.addActionListener(wdListener); computeParametersDialog.RawDataDirectoryListener ddListener = new computeParametersDialog.RawDataDirectoryListener(); - _JButtonRawData.addActionListener(ddListener); - computeParametersDialog.QuitListener quitListener = new computeParametersDialog.QuitListener(this); - _jButtonQuit.addActionListener(quitListener); + JButtonRawData.addActionListener(ddListener); + computeParametersDialog.QuitListener quitListener = new QuitListener(this); + jButtonQuit.addActionListener(quitListener); computeParametersDialog.StartListener startListener = new computeParametersDialog.StartListener(this); - _jButtonStart.addActionListener(startListener); + jButtonStart.addActionListener(startListener); } + /** * Constructor for segmentation dialog * @@ -227,124 +215,151 @@ public static void main(String[] args) { chromocenterSegmentationPipelineBatchDialog.setLocationRelativeTo(null); } + public double getXCalibration() { - String xCal = calibXRead.getText(); + String xCal = _readXCalibration.getText(); return Double.parseDouble(xCal.replaceAll(",", ".")); } + public double getYCalibration() { - String yCal = calibYRead.getText(); + String yCal = _readYCalibration.getText(); return Double.parseDouble(yCal.replaceAll(",", ".")); } + public double getZCalibration() { - String zCal = calibZRead.getText(); + String zCal = _readZCalibration.getText(); return Double.parseDouble(zCal.replaceAll(",", ".")); } + public boolean getCalibrationStatus() { - return addCalibBox.isSelected(); + return _addCalibrationBox.isSelected(); } + public String getUnit() { - return unitRead.getText(); + return _readUnit.getText(); } + public String getWorkDirectory() { return _jTextFieldWorkDirectory.getText(); } + public String getRawDataDirectory() { return _jTextFieldRawData.getText(); } + public boolean isStart() { return _start; } + public void itemStateChanged(ItemEvent e) { - if (e.getSource() == addCalibBox) { - if ((addCalibBox.isSelected())) { + if (e.getSource() == _addCalibrationBox) { + if (_addCalibrationBox.isSelected()) { GridBagConstraints gc = new GridBagConstraints(); gc.insets = new Insets(0, 0, 5, 0); - unit.setText("Unit :"); + _jLabelUnit.setText("Unit :"); gc.gridx = 0; gc.gridy = 1; - Calib.add(unit, gc); - unitRead.setPreferredSize(new Dimension(100, 20)); - unitRead.setText("µm"); + _calibration.add(_jLabelUnit, gc); + _readUnit.setPreferredSize(new Dimension(100, 20)); + _readUnit.setText("µm"); gc.gridx = 1; gc.gridy = 1; - Calib.add(unitRead, gc); - unit.setVisible(true); - unitRead.setVisible(true); + _calibration.add(_readUnit, gc); + _jLabelUnit.setVisible(true); + _readUnit.setVisible(true); - calibx.setText("X :"); + _jLabelXCalibration.setText("X :"); gc.gridx = 0; gc.gridy = 2; - Calib.add(calibx, gc); - calibXRead.setPreferredSize(new Dimension(100, 20)); - calibXRead.setText("1"); + _calibration.add(_jLabelXCalibration, gc); + _readXCalibration.setPreferredSize(new Dimension(100, 20)); + _readXCalibration.setText("1"); gc.gridx = 1; gc.gridy = 2; - Calib.add(calibXRead, gc); - calibx.setVisible(true); - calibXRead.setVisible(true); + _calibration.add(_readXCalibration, gc); + _jLabelXCalibration.setVisible(true); + _readXCalibration.setVisible(true); - caliby.setText("Y :"); + _jLabelYCalibration.setText("Y :"); gc.gridx = 0; gc.gridy = 3; - Calib.add(caliby, gc); - calibYRead.setPreferredSize(new Dimension(100, 20)); - calibYRead.setText("1"); + _calibration.add(_jLabelYCalibration, gc); + _readYCalibration.setPreferredSize(new Dimension(100, 20)); + _readYCalibration.setText("1"); gc.gridx = 1; gc.gridy = 3; - Calib.add(calibYRead, gc); - caliby.setVisible(true); - calibYRead.setVisible(true); + _calibration.add(_readYCalibration, gc); + _jLabelYCalibration.setVisible(true); + _readYCalibration.setVisible(true); - calibz.setText("Z :"); + _jLabelZCalibration.setText("Z :"); gc.gridx = 0; gc.gridy = 4; - Calib.add(calibz, gc); - calibZRead.setPreferredSize(new Dimension(100, 20)); - calibZRead.setText("1"); + _calibration.add(_jLabelZCalibration, gc); + _readZCalibration.setPreferredSize(new Dimension(100, 20)); + _readZCalibration.setText("1"); gc.gridx = 1; gc.gridy = 4; - Calib.add(calibZRead, gc); - calibz.setVisible(true); - calibZRead.setVisible(true); + _calibration.add(_readZCalibration, gc); + _jLabelZCalibration.setVisible(true); + _readZCalibration.setVisible(true); - validate(); - repaint(); } else { - calibx.setVisible(false); - caliby.setVisible(false); - calibz.setVisible(false); - unit.setVisible(false); - - calibXRead.setVisible(false); - calibYRead.setVisible(false); - calibZRead.setVisible(false); - unitRead.setVisible(false); + _jLabelXCalibration.setVisible(false); + _jLabelYCalibration.setVisible(false); + _jLabelZCalibration.setVisible(false); + _jLabelUnit.setVisible(false); - validate(); - repaint(); + _readXCalibration.setVisible(false); + _readYCalibration.setVisible(false); + _readZCalibration.setVisible(false); + _readUnit.setVisible(false); } + validate(); + repaint(); + } + } + + /** + * + */ + static class QuitListener implements ActionListener { + final computeParametersDialog _computeParametersDialog; + + /** @param computeParametersDialog Dialog parameters */ + public QuitListener(computeParametersDialog computeParametersDialog) { + _computeParametersDialog = computeParametersDialog; + } + + + /** + * + */ + public void actionPerformed(ActionEvent actionEvent) { + _computeParametersDialog.dispose(); } } class StartListener implements ActionListener { - computeParametersDialog _computeParametersDialog; + final computeParametersDialog _computeParametersDialog; /** @param computeParametersDialog Dialog parameters */ public StartListener(computeParametersDialog computeParametersDialog) { _computeParametersDialog = computeParametersDialog; } + /** * */ @@ -364,25 +379,6 @@ public void actionPerformed(ActionEvent actionEvent) { } } - /** - * - */ - class QuitListener implements ActionListener { - computeParametersDialog _computeParametersDialog; - - /** @param computeParametersDialog Dialog parameters */ - public QuitListener(computeParametersDialog computeParametersDialog) { - _computeParametersDialog = computeParametersDialog; - } - - /** - * - */ - public void actionPerformed(ActionEvent actionEvent) { - _computeParametersDialog.dispose(); - } - } - /** * */ @@ -398,13 +394,14 @@ public void actionPerformed(ActionEvent actionEvent) { if (returnValue == JFileChooser.APPROVE_OPTION) { @SuppressWarnings("unused") String run = jFileChooser.getSelectedFile().getName(); - _workDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); - _jTextFieldWorkDirectory.setText(_workDirectory); + String workDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); + _jTextFieldWorkDirectory.setText(workDirectory); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } + /** * */ @@ -420,12 +417,10 @@ public void actionPerformed(ActionEvent actionEvent) { if (returnValue == JFileChooser.APPROVE_OPTION) { @SuppressWarnings("unused") String run = jFileChooser.getSelectedFile().getName(); - _rawDataDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); - _jTextFieldRawData.setText(_rawDataDirectory); + String rawDataDirectory = jFileChooser.getSelectedFile().getAbsolutePath(); + _jTextFieldRawData.setText(rawDataDirectory); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } - - } diff --git a/src/main/java/gred/nucleus/exceptions/fileInOut.java b/src/main/java/gred/nucleus/exceptions/fileInOut.java index 7022b4a7..26f23a60 100644 --- a/src/main/java/gred/nucleus/exceptions/fileInOut.java +++ b/src/main/java/gred/nucleus/exceptions/fileInOut.java @@ -6,8 +6,6 @@ public fileInOut(String fileName) { System.err.println("File " + fileName + " already exist "); } - - } diff --git a/src/main/java/gred/nucleus/filesInputOutput/Directory.java b/src/main/java/gred/nucleus/filesInputOutput/Directory.java index 272b4806..fb5c30fd 100644 --- a/src/main/java/gred/nucleus/filesInputOutput/Directory.java +++ b/src/main/java/gred/nucleus/filesInputOutput/Directory.java @@ -14,13 +14,13 @@ public class Directory { /** Directory path */ public File m_directory; /** Directory path */ - public String m_dirPath = ""; - /** List of files in current forlder + recursive folder */ - public ArrayList m_listeOfFiles = new ArrayList<>(); + public String m_dirPath = ""; + /** List of files in current folder + recursive folder */ + public ArrayList m_fileList = new ArrayList<>(); /** Check if directory contain nd files */ - public Boolean m_containNdFile = false; + public Boolean m_containNdFile = false; /** List of nd files */ - public ArrayList m_listeOfFilesND = new ArrayList<>(); + public ArrayList m_fileListND = new ArrayList<>(); /** * */ @@ -35,13 +35,14 @@ public Directory(String Path) { try { this.m_dirPath = Path; this.m_directory = new File(this.m_dirPath); - this.m_separator = this.m_directory.separator; + this.m_separator = File.separator; } catch (Exception exp) { System.out.println(exp.getMessage()); System.exit(1); } } + /** Method to check if directory and create if doesn't */ public void CheckAndCreateDir() { ChekSeparatorEndPath(); @@ -49,14 +50,15 @@ public void CheckAndCreateDir() { } + /** Check if separator exist */ private void ChekSeparatorEndPath() { - if (!(this.m_dirPath.endsWith("/"))) { - this.m_dirPath = this.m_dirPath + this.m_directory.separator; + if (!(this.m_dirPath.endsWith(File.separator))) { + this.m_dirPath = this.m_dirPath + File.separator; } - } + /** Method creating folder if doesn't exist. */ private void CreateDire() { File dir = new File(this.m_dirPath); @@ -71,11 +73,13 @@ private void CreateDire() { } } + /** @return path current directory */ public String get_dirPath() { return this.m_dirPath; } + /** * Method to recursively list files contains in folder and sub folder. (Argument needed because of recursive way) * @@ -94,68 +98,75 @@ public void listImageFiles(String Path) { listImageFiles(f.getAbsolutePath()); } else { if (!(FilenameUtils.getExtension(f.getName()).equals("txt"))) { - this.m_listeOfFiles.add(f); + this.m_fileList.add(f); if (FilenameUtils.getExtension(f.getName()).equals("nd")) { this.m_containNdFile = true; - this.m_listeOfFilesND.add(f); + this.m_fileListND.add(f); } } } } } + public void listAllFiles(String Path) { File root = new File(Path); File[] list = root.listFiles(); - for (File f : list) { - this.m_listeOfFiles.add(f); - if (f.isDirectory()) { - listAllFiles(f.getAbsolutePath()); - + if (list != null) { + for (File f : list) { + this.m_fileList.add(f); + if (f.isDirectory()) { + listAllFiles(f.getAbsolutePath()); + } } - } } + /** Replace list files if ND files have been listed. */ public void checkAndActualiseNDFiles() { if (this.m_containNdFile) { - this.m_listeOfFiles = this.m_listeOfFilesND; + this.m_fileList = this.m_fileListND; } } + /** check if input directory is empty */ public void checkIfEmpty() { - if (this.m_listeOfFiles.isEmpty()) { + if (this.m_fileList.isEmpty()) { System.err.println("Folder " + this.m_dirPath + " is empty"); } - } + /** @return list of files */ public ArrayList ListFiles() { - return this.m_listeOfFiles; + return this.m_fileList; } + /** - * @param indice of file in list array + * @param index of file in list array * * @return File */ - public File getFile(int indice) { - return this.m_listeOfFiles.get(indice); + public File getFile(int index) { + return this.m_fileList.get(index); } + /** @return number of file listed */ public int getNumberFiles() { - return this.m_listeOfFiles.size(); + return this.m_fileList.size(); } - public String getdirPath() { + + public String getDirPath() { return this.m_directory.getPath() + File.separator; } + public String getSeparator() { return this.m_separator; } @@ -167,7 +178,7 @@ public String getSeparator() { public File searchFileNameWithoutExtension(String fileName) { File fileToReturn = null; - for (File f : this.m_listeOfFiles) { + for (File f : this.m_fileList) { if (f.getName().substring(0, f.getName().lastIndexOf('.')).equals(fileName)) { fileToReturn = f; } @@ -175,10 +186,11 @@ public File searchFileNameWithoutExtension(String fileName) { return fileToReturn; } + public boolean checkIfFileExists(String fileName) { boolean fileExists = false; - for (File f : this.m_listeOfFiles) { + for (File f : this.m_fileList) { if ((f.getName().substring(0, f.getName().lastIndexOf('.')).equals(fileName)) || (f.getName().equals(fileName))) { fileExists = true; @@ -186,5 +198,4 @@ public boolean checkIfFileExists(String fileName) { } return fileExists; } - } diff --git a/src/main/java/gred/nucleus/filesInputOutput/FilesNames.java b/src/main/java/gred/nucleus/filesInputOutput/FilesNames.java index 6412b2cd..2ca5fc7b 100644 --- a/src/main/java/gred/nucleus/filesInputOutput/FilesNames.java +++ b/src/main/java/gred/nucleus/filesInputOutput/FilesNames.java @@ -7,49 +7,54 @@ public class FilesNames { /** Path file input */ - String _pathFile = new String(); + String _pathFile = ""; /** File name */ - String _fileName = new String(); + String _fileName = ""; /** Complete pathFile */ - String _fullPathFile = new String(); + String _fullPathFile = ""; boolean _fileExist = true; public FilesNames() { } + /** Constructor to create file object */ public FilesNames(String filePath) { this._fullPathFile = filePath; File file = new File(filePath); - this._pathFile = file.getParent() + file.separator; + this._pathFile = file.getParent() + File.separator; this._fileName = file.getName(); CheckExistFile(); } - public String PrefixeNameFile() { + + public String prefixNameFile() { return FilenameUtils.removeExtension(this._fileName); } + /** Method to check if file exists */ public void CheckExistFile() { File file = new File(this._fullPathFile); if (!file.exists()) { this._fileExist = false; } - } + /** return boolean true for existing file */ public boolean is_fileExist() { return _fileExist; } + /** return path to file */ public String get_pathFile() { return this._pathFile; } + public void set_fullPathFile(String fileName) { this._fullPathFile = _pathFile + fileName; } diff --git a/src/main/java/gred/nucleus/filesInputOutput/OutputTextFile.java b/src/main/java/gred/nucleus/filesInputOutput/OutputTextFile.java index e913b15a..c41efec3 100644 --- a/src/main/java/gred/nucleus/filesInputOutput/OutputTextFile.java +++ b/src/main/java/gred/nucleus/filesInputOutput/OutputTextFile.java @@ -4,7 +4,6 @@ import org.apache.commons.io.FilenameUtils; import java.io.BufferedWriter; -import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -14,17 +13,18 @@ public OutputTextFile(String filePath) { super(filePath); } + /** Method to save file with verification if file already exists TODO(@DesTristus) ADD ERROR IN LOG FILE */ public void SaveTextFile(String text) { try { int i = 0; while (is_fileExist()) { - set_fullPathFile(PrefixeNameFile() + "-" + i + "." + FilenameUtils.getExtension(_fileName)); + set_fullPathFile(prefixNameFile() + "-" + i + "." + FilenameUtils.getExtension(_fileName)); CheckExistFile(); i++; } BufferedWriter writer; - writer = new BufferedWriter(new FileWriter(new File(this._fullPathFile))); + writer = new BufferedWriter(new FileWriter(this._fullPathFile)); writer.write(text); writer.close(); diff --git a/src/main/java/gred/nucleus/filesInputOutput/OutputTexteFile.java b/src/main/java/gred/nucleus/filesInputOutput/OutputTexteFile.java index 1498b11a..3869c841 100644 --- a/src/main/java/gred/nucleus/filesInputOutput/OutputTexteFile.java +++ b/src/main/java/gred/nucleus/filesInputOutput/OutputTexteFile.java @@ -3,7 +3,6 @@ import ij.IJ; import java.io.BufferedWriter; -import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -13,11 +12,12 @@ public OutputTexteFile(String filePath) { super(filePath); } + /** Method to save file with verification if file already exists TODO(@DesTristus) ADD ERROR IN LOG FILE */ - public void SaveTexteFile(String text) { + public void saveTextFile(String text) { try { BufferedWriter writer; - writer = new BufferedWriter(new FileWriter(new File(this._fullPathFile))); + writer = new BufferedWriter(new FileWriter(this._fullPathFile)); writer.write(text); writer.close(); diff --git a/src/main/java/gred/nucleus/filesInputOutput/OutputTiff.java b/src/main/java/gred/nucleus/filesInputOutput/OutputTiff.java index 050d0a0a..1d5d8417 100644 --- a/src/main/java/gred/nucleus/filesInputOutput/OutputTiff.java +++ b/src/main/java/gred/nucleus/filesInputOutput/OutputTiff.java @@ -13,6 +13,7 @@ public OutputTiff(String filePath) { super(filePath); } + /** Method to save file with verification if file already exists TODO ADD ERROR IN LOG FILE */ public void SaveImage(ImagePlus imageToSave) { try { diff --git a/src/main/java/gred/nucleus/imageProcess/Thresholding.java b/src/main/java/gred/nucleus/imageProcess/Thresholding.java index 31032b2e..5bf7c848 100644 --- a/src/main/java/gred/nucleus/imageProcess/Thresholding.java +++ b/src/main/java/gred/nucleus/imageProcess/Thresholding.java @@ -10,6 +10,7 @@ public class Thresholding { public Thresholding() { } + /** * Compute the initial threshold value from OTSU method * @@ -20,12 +21,13 @@ public Thresholding() { public int computeOtsuThreshold(ImagePlus imagePlusInput) { AutoThresholder autoThresholder = new AutoThresholder(); ImageStatistics imageStatistics = new StackStatistics(imagePlusInput); - int[] tHisto = imageStatistics.histogram; - return autoThresholder.getThreshold(AutoThresholder.Method.Otsu, tHisto); + int[] tHistogram = imageStatistics.histogram; + return autoThresholder.getThreshold(AutoThresholder.Method.Otsu, tHistogram); } + /** - * TODO COMMENTAIRE !!!! 2D 3D + * TODO COMMENT !!!! 2D 3D * * @param imagePlusInput * @@ -47,6 +49,5 @@ public ImagePlus contrastAnd8bits(ImagePlus imagePlusInput) { return imagePlusInput; } - } diff --git a/src/main/java/gred/nucleus/machineLeaningUtils/ComputeNucleiParametersML.java b/src/main/java/gred/nucleus/machineLeaningUtils/ComputeNucleiParametersML.java index 40a41b13..560e7405 100644 --- a/src/main/java/gred/nucleus/machineLeaningUtils/ComputeNucleiParametersML.java +++ b/src/main/java/gred/nucleus/machineLeaningUtils/ComputeNucleiParametersML.java @@ -1,8 +1,8 @@ package gred.nucleus.machineLeaningUtils; +import gred.nucleus.core.Measure3D; import gred.nucleus.filesInputOutput.Directory; import gred.nucleus.filesInputOutput.OutputTextFile; -import gred.nucleus.core.Measure3D; import gred.nucleus.plugins.PluginParameters; import gred.nucleus.utils.Histogram; import ij.ImagePlus; @@ -15,114 +15,117 @@ import java.util.ArrayList; public class ComputeNucleiParametersML { - String m_rawImagesInputDirectory; - String m_segmentedImagesDirectory; - - /** - * Constructor - * @param rawImagesInputDirectory path to raw images - * @param segmentedImagesDirectory path to list of segmented images from machine learning associated to raw - */ - public ComputeNucleiParametersML(String rawImagesInputDirectory, String segmentedImagesDirectory) { - this.m_rawImagesInputDirectory=rawImagesInputDirectory; - this.m_segmentedImagesDirectory=segmentedImagesDirectory; - } - - /** - * Run parameters computation parameters see Measure3D - * @throws Exception - */ - public void run() throws Exception{ - PluginParameters pluginParameters= new PluginParameters(this.m_rawImagesInputDirectory,this.m_segmentedImagesDirectory); - Directory directoryInput = new Directory(pluginParameters.getOutputFolder()); - directoryInput.listImageFiles(pluginParameters.getOutputFolder()); - directoryInput.checkIfEmpty(); - ArrayList segImages =directoryInput.m_listeOfFiles; - String outputCropGeneralInfoOTSU=pluginParameters.getAnalyseParameters()+getColnameResult(); - for (File currentFile : segImages) { - System.out.println("current File " + currentFile.getName()); - ImagePlus Raw = new ImagePlus(pluginParameters.getInputFolder() + - directoryInput.getSeparator() + - currentFile.getName()); - ImagePlus[] Segmented = BF.openImagePlus(pluginParameters.getOutputFolder() + currentFile.getName()); - // TODO TRANSFORMATION FACTORISABLE AVEC METHODE DU DESSUS !!!!! - Segmented[0] = generateSegmentedImage(Segmented[0], 1); - Segmented[0] = BinaryImages.componentsLabeling(Segmented[0], 26, 32); - LabelImages.removeBorderLabels(Segmented[0]); - Segmented[0] = generateSegmentedImage(Segmented[0], 1); - Histogram histogram = new Histogram(); - histogram.run(Segmented[0]); - if (histogram.getNbLabels() > 0) { - Measure3D mesure3D = new Measure3D(Segmented, - Raw, - pluginParameters.getXcalibration(Raw), - pluginParameters.getYcalibration(Raw), - pluginParameters.getZcalibration(Raw)); - outputCropGeneralInfoOTSU += mesure3D.nucleusParameter3D() + "\n"; - } - } - - OutputTextFile resultFileOutputOTSU=new OutputTextFile(pluginParameters.getOutputFolder() - +directoryInput.getSeparator() - +"result_Segmentation_Analyse.csv"); - resultFileOutputOTSU.SaveTextFile( outputCropGeneralInfoOTSU); - - } - - /** - * - * @return columns names for results - */ - public String getColnameResult(){ - return "NucleusFileName\t" + - "Volume\t" + - "Flatness\t" + - "Elongation\t" + - "Sphericity\t" + - "Esr\t" + - "SurfaceArea\t" + - "SurfaceAreaCorrected\t" + - "SphericityCorrected\t" + - "MeanIntensityNucleus\t" + - "MeanIntensityBackground\t" + - "StandardDeviation\t" + - "MinIntensity\t" + - "MaxIntensity\t" + - "MedianIntensityImage\t" + - "MedianIntensityNucleus\t" + - "MedianIntensityBackground\t" + - "ImageSize\t" + - "OTSUThreshold\n"; - } - - /** - * Filter connected connected component if more then 1 nuclei - * @param imagePlusInput - * @param threshold - * @return - */ - public static ImagePlus generateSegmentedImage (ImagePlus imagePlusInput, - int threshold) { - ImageStack imageStackInput = imagePlusInput.getStack(); - ImagePlus imagePlusSegmented = imagePlusInput.duplicate(); - - imagePlusSegmented.setTitle(imagePlusInput.getTitle()); - ImageStack imageStackSegmented = imagePlusSegmented.getStack(); - for(int k = 0; k < imagePlusInput.getStackSize(); ++k) { - for (int i = 0; i < imagePlusInput.getWidth(); ++i) { - for (int j = 0; j < imagePlusInput.getHeight(); ++j) { - double voxelValue = imageStackInput.getVoxel(i, j, k); - if (voxelValue >= 1) { - imageStackSegmented.setVoxel(i, j, k, 255); - imageStackInput.getVoxel(i, j, k); - } - else { - imageStackSegmented.setVoxel(i, j, k, 0); - } - } - } - } - return imagePlusSegmented; - - } + String m_rawImagesInputDirectory; + String m_segmentedImagesDirectory; + + /** + * Constructor + * + * @param rawImagesInputDirectory path to raw images + * @param segmentedImagesDirectory path to list of segmented images from machine learning associated to raw + */ + public ComputeNucleiParametersML(String rawImagesInputDirectory, String segmentedImagesDirectory) { + this.m_rawImagesInputDirectory = rawImagesInputDirectory; + this.m_segmentedImagesDirectory = segmentedImagesDirectory; + } + + /** + * Filter connected connected component if more then 1 nuclei + * + * @param imagePlusInput + * @param threshold + * + * @return + */ + public static ImagePlus generateSegmentedImage(ImagePlus imagePlusInput, + int threshold) { + ImageStack imageStackInput = imagePlusInput.getStack(); + ImagePlus imagePlusSegmented = imagePlusInput.duplicate(); + + imagePlusSegmented.setTitle(imagePlusInput.getTitle()); + ImageStack imageStackSegmented = imagePlusSegmented.getStack(); + for (int k = 0; k < imagePlusInput.getStackSize(); ++k) { + for (int i = 0; i < imagePlusInput.getWidth(); ++i) { + for (int j = 0; j < imagePlusInput.getHeight(); ++j) { + double voxelValue = imageStackInput.getVoxel(i, j, k); + if (voxelValue >= 1) { + imageStackSegmented.setVoxel(i, j, k, 255); + } else { + imageStackSegmented.setVoxel(i, j, k, 0); + } + } + } + } + return imagePlusSegmented; + + } + + /** + * Run parameters computation parameters see Measure3D + * + * @throws Exception + */ + public void run() throws Exception { + PluginParameters pluginParameters = + new PluginParameters(this.m_rawImagesInputDirectory, this.m_segmentedImagesDirectory); + Directory directoryInput = new Directory(pluginParameters.getOutputFolder()); + directoryInput.listImageFiles(pluginParameters.getOutputFolder()); + directoryInput.checkIfEmpty(); + ArrayList segImages = directoryInput.m_fileList; + StringBuilder outputCropGeneralInfoOTSU = + new StringBuilder(pluginParameters.getAnalyseParameters() + getResultsColumnNames()); + for (File currentFile : segImages) { + System.out.println("current File " + currentFile.getName()); + ImagePlus Raw = new ImagePlus(pluginParameters.getInputFolder() + + directoryInput.getSeparator() + + currentFile.getName()); + ImagePlus[] Segmented = BF.openImagePlus(pluginParameters.getOutputFolder() + currentFile.getName()); + // TODO TRANSFORMATION FACTORISABLE AVEC METHODE DU DESSUS !!!!! + Segmented[0] = generateSegmentedImage(Segmented[0], 1); + Segmented[0] = BinaryImages.componentsLabeling(Segmented[0], 26, 32); + LabelImages.removeBorderLabels(Segmented[0]); + Segmented[0] = generateSegmentedImage(Segmented[0], 1); + Histogram histogram = new Histogram(); + histogram.run(Segmented[0]); + if (histogram.getNbLabels() > 0) { + Measure3D measure3D = new Measure3D(Segmented, + Raw, + pluginParameters.getXCalibration(Raw), + pluginParameters.getYCalibration(Raw), + pluginParameters.getZCalibration(Raw)); + outputCropGeneralInfoOTSU.append(measure3D.nucleusParameter3D()).append("\n"); + } + } + + OutputTextFile resultFileOutputOTSU = new OutputTextFile(pluginParameters.getOutputFolder() + + directoryInput.getSeparator() + + "result_Segmentation_Analyse.csv"); + resultFileOutputOTSU.SaveTextFile(outputCropGeneralInfoOTSU.toString()); + + } + + /** + * @return columns names for results + */ + public String getResultsColumnNames() { + return "NucleusFileName\t" + + "Volume\t" + + "Flatness\t" + + "Elongation\t" + + "Sphericity\t" + + "Esr\t" + + "SurfaceArea\t" + + "SurfaceAreaCorrected\t" + + "SphericityCorrected\t" + + "MeanIntensityNucleus\t" + + "MeanIntensityBackground\t" + + "StandardDeviation\t" + + "MinIntensity\t" + + "MaxIntensity\t" + + "MedianIntensityImage\t" + + "MedianIntensityNucleus\t" + + "MedianIntensityBackground\t" + + "ImageSize\t" + + "OTSUThreshold\n"; + } } diff --git a/src/main/java/gred/nucleus/machineLeaningUtils/SliceToStack.java b/src/main/java/gred/nucleus/machineLeaningUtils/SliceToStack.java index 671c9e51..e0d3037c 100644 --- a/src/main/java/gred/nucleus/machineLeaningUtils/SliceToStack.java +++ b/src/main/java/gred/nucleus/machineLeaningUtils/SliceToStack.java @@ -5,6 +5,8 @@ import ij.ImagePlus; import ij.io.FileSaver; import ij.plugin.Concatenator; + +import java.io.File; import java.util.HashMap; import java.util.Map; @@ -33,7 +35,7 @@ public void run() { Directory directoryOutput = new Directory(this.m_pathToOutputDir); Directory directoryInput = new Directory(this.m_pathToSliceDir); directoryInput.listImageFiles(this.m_pathToSliceDir); - //Parcour de l'ensemble des images du dossier + // Iterate over images from directory for (short i = 0; i < directoryInput.getNumberFiles(); ++i) { String tm = directoryInput.getFile(i).getName(); tm = tm.substring(0, tm.lastIndexOf("_")); @@ -50,11 +52,12 @@ public void run() { System.out.println("image :" + entry.getKey()); for (short i = 0; i < image.length; ++i) { //image= BF.openImagePlus((directoryInput.m_dirPath - image[i] = IJ.openImage((directoryInput.m_dirPath - + "/" - + entry.getKey() - + "_" - + i + "_MLprediction.tif")); + image[i] = IJ.openImage((directoryInput.m_dirPath + + File.separator + + entry.getKey() + + "_" + + i + + "_MLprediction.tif")); IJ.run(image[i], "8-bit", ""); // } diff --git a/src/main/java/gred/nucleus/mains/ChromocenterTransformation.java b/src/main/java/gred/nucleus/mains/ChromocenterTransformation.java index 241991a8..0b60085d 100644 --- a/src/main/java/gred/nucleus/mains/ChromocenterTransformation.java +++ b/src/main/java/gred/nucleus/mains/ChromocenterTransformation.java @@ -28,7 +28,7 @@ public static void main(String[] args) throws Exception { File currentFile = directoryInput.getFile(i); String fileImg = currentFile.toString(); FilesNames outPutFilesNames = new FilesNames(fileImg); - String prefix = outPutFilesNames.PrefixeNameFile(); + String prefix = outPutFilesNames.prefixNameFile(); NucleusSegmentation nucleusSegmentation = new NucleusSegmentation(currentFile, prefix, segmentationParameters); ImagePlus[] currentImage = BF.openImagePlus(currentFile.getAbsolutePath()); @@ -40,10 +40,9 @@ public static void main(String[] args) throws Exception { } - - } + public static void saveFile(ImagePlus imagePlusInput, String pathFile) { FileSaver fileSaver = new FileSaver(imagePlusInput); fileSaver.saveAsTiffStack(pathFile); diff --git a/src/main/java/gred/nucleus/mains/MulticropFilter.java b/src/main/java/gred/nucleus/mains/MulticropFilter.java index 69c0c2d5..43407b8a 100644 --- a/src/main/java/gred/nucleus/mains/MulticropFilter.java +++ b/src/main/java/gred/nucleus/mains/MulticropFilter.java @@ -24,7 +24,7 @@ public static void main(String[] args) throws Exception { // TODO FAIRE UNE FONCTION POUR CHOPER LE FICHIER IMAGE DANS LE DIR PEUT IMPORTE L EXTENSION ! File tifFile = directoryTIF.searchFileNameWithoutExtension(coordinateFile.getName().split("\\.")[0]); if (tifFile != null) { - System.out.println("Dedand"); + System.out.println("Inside"); AutocropParameters autocropParameters = new AutocropParameters(tifFile.getParent(), tifFile.getParent()); @@ -35,14 +35,14 @@ public static void main(String[] args) throws Exception { annotAutoCrop.run(); } } - } - public static ArrayList readCoordinatesTXT(File boxeFile) { + + public static ArrayList readCoordinatesTXT(File boxFile) { ArrayList boxLists = new ArrayList<>(); try { - Scanner scanner = new Scanner(boxeFile); + Scanner scanner = new Scanner(boxFile); while (scanner.hasNextLine()) { String line = scanner.nextLine(); @@ -66,6 +66,5 @@ public static ArrayList readCoordinatesTXT(File boxeFile) { } return boxLists; } - } diff --git a/src/main/java/gred/nucleus/mains/TestAutoCrop.java b/src/main/java/gred/nucleus/mains/TestAutoCrop.java index 93a84da8..c5cb187f 100644 --- a/src/main/java/gred/nucleus/mains/TestAutoCrop.java +++ b/src/main/java/gred/nucleus/mains/TestAutoCrop.java @@ -27,22 +27,21 @@ public class TestAutoCrop { static ArrayList m_test; - public static void runAutoCropFolder(String imageSourceFile, String output, String pathToConfig) - throws Exception { + public static void runAutoCropFolder(String imageSourceFile, String output, String pathToConfig) { AutocropParameters autocropParameters = new AutocropParameters(imageSourceFile, output, pathToConfig); AutoCropCalling autoCrop = new AutoCropCalling(autocropParameters); autoCrop.runFolder(); } - public static void runAutoCropFolder(String imageSourceFile, String output) - throws Exception { + public static void runAutoCropFolder(String imageSourceFile, String output) { //AutocropParameters autocropParameters= new AutocropParameters(imageSourceFile,output); AutocropParameters autocropParameters = new AutocropParameters(imageSourceFile, output); AutoCropCalling autoCrop = new AutoCropCalling(autocropParameters); autoCrop.runFolder(); } + public static void runAutoCropFile(String imageSourceFile, String output) throws Exception { //AutocropParameters autocropParameters= new AutocropParameters(imageSourceFile,output); AutocropParameters autocropParameters = new AutocropParameters(imageSourceFile, output); @@ -50,12 +49,14 @@ public static void runAutoCropFile(String imageSourceFile, String output) throws autoCrop.runFile(imageSourceFile); } + public static void runCropFromCoordinates(String coordinateDir) throws Exception { CropFromCoordinates test = new CropFromCoordinates(coordinateDir); test.runCropFromCoordinate(); } + /** * Main function of the package's tests. * @@ -63,7 +64,7 @@ public static void runCropFromCoordinates(String coordinateDir) throws Exception */ public static void main(String[] args) throws Exception { - System.err.println("start prog"); + System.err.println("start program"); long maxMemory = Runtime.getRuntime().maxMemory(); /* Maximum amount of memory the JVM will attempt to use */ System.out.println("Maximum memory (bytes): " + @@ -77,6 +78,4 @@ public static void main(String[] args) throws Exception { System.out.println("Total memory (bytes): " + Runtime.getRuntime().totalMemory() * 1e-9); } - - } diff --git a/src/main/java/gred/nucleus/mains/TestSegmentationMethods.java b/src/main/java/gred/nucleus/mains/TestSegmentationMethods.java index daa80885..264d4d54 100644 --- a/src/main/java/gred/nucleus/mains/TestSegmentationMethods.java +++ b/src/main/java/gred/nucleus/mains/TestSegmentationMethods.java @@ -18,19 +18,20 @@ public class TestSegmentationMethods { /* public static void testStupid(ImagePlus img, short vMin, int vMax, String outputImgString ) throws FormatException { SegmentationParameters segmentationParameters = new SegmentationParameters(); - SegmentationCalling otsuModif = new SegmentationCalling(img, vMin, vMax, outputImgString); + SegmentationCalling otsuModified = new SegmentationCalling(img, vMin, vMax, outputImgString); otsuModif.runSeveralImages2(); } */ + /** * @param input * @param output */ public static void testStupidSeveralImages(String input, String output) throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(input, output); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { - String log = otsuModif.runSeveralImages2(); + String log = otsuModified.runSeveralImages2(); if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); } @@ -39,11 +40,12 @@ public static void testStupidSeveralImages(String input, String output) throws E } } + public static void testStupidSeveralImages(String input, String output, String config) throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(input, output, config); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { - String log = otsuModif.runSeveralImages2(); + String log = otsuModified.runSeveralImages2(); if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); } @@ -52,13 +54,14 @@ public static void testStupidSeveralImages(String input, String output, String c } } + /** * Main function of the package's tests. * * @param args */ public static void main(String[] args) throws Exception { - ///home/titus/Bureau/data/Test_Image_Reproductibilite/IMAGE_TEST_NJ/AUTOCROP_RAW/RAW_BIOFORMATS + ///home/titus/Bureau/data/Test_Image_Reproducibility/IMAGE_TEST_NJ/AUTOCROP_RAW/RAW_BIOFORMATS String timeStampStart = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss").format(Calendar.getInstance().getTime()); @@ -68,14 +71,14 @@ public static void main(String[] args) throws Exception { "/home/tridubos/Bureau/TEST_SEG/Results_checked/Z_Col_cot21&17&22__w11 DAPI SIM_s3/OTSU/"; String inputTristan = - "/media/tridubos/DATA1/SPERMATO/Manipe_1_57_images_input/Segmentation/Analyse_Segmentation/NucleusPB"; + "/media/tridubos/DATA1/SPERMATO/Manip_1_57_images_input/Segmentation/Analyse_Segmentation/NucleusPB"; String outputTristanGift = "/home/tridubos/Bureau/TEST_SEG/Test_analysis/Z_Col_cot21&17&22__w11 DAPI SIM_s3/GIFT/"; String outputTristanOtsu = "/media/tridubos/DATA1/SPERMATO/Manipe_1_57_images_input/Segmentation/Analyse_Segmentation/Segmented"; /* OutputFileVerification fw = new OutputFileVerification(ExpectedResult,inputTristan); - fw.GetFileResultExpeted(ExpectedResult); + fw.GetFileResultExpected(ExpectedResult); fw.GetFilesOutputFolder(inputTristan); */ String pathToTest = "/home/tridubos/Bureau/IMAGES_TEST/AUTOCROP"; @@ -127,18 +130,16 @@ public static void main(String[] args) throws Exception { /*fw.GetFilesResultingOfAnalysis(inputTristan); fw.CompareAnalysisResult(); OutputFileVerification fw = new OutputFileVerification(); - fw.GetFileResultExpeted(ExpectedResult); + fw.GetFileResultExpected(ExpectedResult); fw.GetFilesOutputFolder(outputTristan); fw.GetFilesResultingOfAnalysis(outputTristan); fw.CompareAnalysisResult(); */ System.err.println("The program ended normally."); - String timeStampend = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss").format(Calendar.getInstance().getTime()); + String timestampEnd = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss").format(Calendar.getInstance().getTime()); System.out.println("START :" + timeStampStart); - System.out.println("END :" + timeStampend); + System.out.println("END :" + timestampEnd); } - - } diff --git a/src/main/java/gred/nucleus/mains/Version.java b/src/main/java/gred/nucleus/mains/Version.java new file mode 100644 index 00000000..77a2449c --- /dev/null +++ b/src/main/java/gred/nucleus/mains/Version.java @@ -0,0 +1,21 @@ +package gred.nucleus.mains; + +import java.io.IOException; +import java.util.Properties; + +public class Version { + + public static String get() { + + final Properties properties = new Properties(); + String version = "undefined"; + try { + properties.load(Version.class.getClassLoader().getResourceAsStream("nucleusj.properties")); + version = properties.getProperty("version"); + } catch (IOException e) { + e.printStackTrace(); + } + + return version; + } +} diff --git a/src/main/java/gred/nucleus/mains/bitsConvert.java b/src/main/java/gred/nucleus/mains/bitsConvert.java index dcd78c88..ba2eda26 100644 --- a/src/main/java/gred/nucleus/mains/bitsConvert.java +++ b/src/main/java/gred/nucleus/mains/bitsConvert.java @@ -21,6 +21,7 @@ public static void main(String[] args) { } } + private static void saveFile(ImagePlus imagePlusInput, String pathFile) { FileSaver fileSaver = new FileSaver(imagePlusInput); fileSaver.saveAsTiffStack(pathFile); diff --git a/src/main/java/gred/nucleus/mains/computeSegmentationParameters.java b/src/main/java/gred/nucleus/mains/computeSegmentationParameters.java index 9491bf9d..e8af5e7c 100644 --- a/src/main/java/gred/nucleus/mains/computeSegmentationParameters.java +++ b/src/main/java/gred/nucleus/mains/computeSegmentationParameters.java @@ -1,8 +1,8 @@ package gred.nucleus.mains; +import gred.nucleus.core.Measure3D; import gred.nucleus.filesInputOutput.Directory; import gred.nucleus.filesInputOutput.OutputTextFile; -import gred.nucleus.core.Measure3D; import gred.nucleus.plugins.PluginParameters; import ij.ImagePlus; import ij.ImageStack; @@ -23,24 +23,25 @@ public static void computeNucleusParameters(String RawImageSourceFile, Directory directoryInput = new Directory(pluginParameters.getInputFolder()); directoryInput.listImageFiles(pluginParameters.getInputFolder()); directoryInput.checkIfEmpty(); - ArrayList rawImages = directoryInput.m_listeOfFiles; - String outputCropGeneralInfoOTSU = pluginParameters.getAnalyseParameters() + getColnameResult(); + ArrayList rawImages = directoryInput.m_fileList; + StringBuilder outputCropGeneralInfoOTSU = + new StringBuilder(pluginParameters.getAnalyseParameters() + getColnameResult()); for (File currentFile : rawImages) { ImagePlus Raw = new ImagePlus(currentFile.getAbsolutePath()); ImagePlus[] Segmented = BF.openImagePlus(pluginParameters.getOutputFolder() + currentFile.getName()); - Measure3D mesure3D = new Measure3D(Segmented, + Measure3D measure3D = new Measure3D(Segmented, Raw, - pluginParameters.getXcalibration(Raw), - pluginParameters.getYcalibration(Raw), - pluginParameters.getZcalibration(Raw)); - outputCropGeneralInfoOTSU += mesure3D.nucleusParameter3D() + "\n"; + pluginParameters.getXCalibration(Raw), + pluginParameters.getYCalibration(Raw), + pluginParameters.getZCalibration(Raw)); + outputCropGeneralInfoOTSU.append(measure3D.nucleusParameter3D()).append("\n"); } OutputTextFile resultFileOutputOTSU = new OutputTextFile(pluginParameters.getOutputFolder() + directoryInput.getSeparator() + "result_Segmentation_Analyse.csv"); - resultFileOutputOTSU.SaveTextFile(outputCropGeneralInfoOTSU); + resultFileOutputOTSU.SaveTextFile(outputCropGeneralInfoOTSU.toString()); } @@ -51,29 +52,31 @@ public static void computeNucleusParameters(String RawImageSourceFile, String Se Directory directoryInput = new Directory(pluginParameters.getInputFolder()); directoryInput.listImageFiles(pluginParameters.getInputFolder()); directoryInput.checkIfEmpty(); - ArrayList rawImages = directoryInput.m_listeOfFiles; - String outputCropGeneralInfoOTSU = pluginParameters.getAnalyseParameters() + getColnameResult(); + ArrayList rawImages = directoryInput.m_fileList; + StringBuilder outputCropGeneralInfoOTSU = + new StringBuilder(pluginParameters.getAnalyseParameters() + getColnameResult()); for (File currentFile : rawImages) { System.out.println("current File " + currentFile.getName()); ImagePlus Raw = new ImagePlus(currentFile.getAbsolutePath()); ImagePlus[] Segmented = BF.openImagePlus(pluginParameters.getOutputFolder() + currentFile.getName()); - Measure3D mesure3D = new Measure3D(Segmented, + Measure3D measure3D = new Measure3D(Segmented, Raw, - pluginParameters.getXcalibration(Raw), - pluginParameters.getYcalibration(Raw), - pluginParameters.getZcalibration(Raw)); + pluginParameters.getXCalibration(Raw), + pluginParameters.getYCalibration(Raw), + pluginParameters.getZCalibration(Raw)); - outputCropGeneralInfoOTSU += mesure3D.nucleusParameter3D() + "\tNA" + "\n"; + outputCropGeneralInfoOTSU.append(measure3D.nucleusParameter3D()).append("\tNA").append("\n"); } OutputTextFile resultFileOutputOTSU = new OutputTextFile(pluginParameters.getOutputFolder() + directoryInput.getSeparator() + "result_Segmentation_Analyse.csv"); - resultFileOutputOTSU.SaveTextFile(outputCropGeneralInfoOTSU); + resultFileOutputOTSU.SaveTextFile(outputCropGeneralInfoOTSU.toString()); } + public static void main(String[] args) throws Exception { DebugTools.enableLogging("OFF"); computeNucleusParameters( @@ -102,24 +105,22 @@ public static String getColnameResult() { "OTSUThreshold\n"; } + public static int recomputeOTSU(ImagePlus _Raw, ImagePlus _Segmented) { - int OTSUthreshold = Integer.MAX_VALUE; + int OTSUThreshold = Integer.MAX_VALUE; ImageStack imageStackRaw = _Raw.getStack(); ImageStack imageStackSeg = _Segmented.getStack(); for (int k = 0; k < _Raw.getStackSize(); ++k) { for (int i = 0; i < _Raw.getWidth(); ++i) { for (int j = 0; j < _Raw.getHeight(); ++j) { if ((imageStackSeg.getVoxel(i, j, k) == 255) && - (OTSUthreshold >= imageStackRaw.getVoxel(i, j, k))) { - OTSUthreshold = (int) (imageStackRaw.getVoxel(i, j, k)); + (OTSUThreshold >= imageStackRaw.getVoxel(i, j, k))) { + OTSUThreshold = (int) (imageStackRaw.getVoxel(i, j, k)); } - } } } - return OTSUthreshold; - + return OTSUThreshold; } - } diff --git a/src/main/java/gred/nucleus/mains/computeSegmentationParametersDL.java b/src/main/java/gred/nucleus/mains/computeSegmentationParametersDL.java index a00c1f0c..414e11f6 100644 --- a/src/main/java/gred/nucleus/mains/computeSegmentationParametersDL.java +++ b/src/main/java/gred/nucleus/mains/computeSegmentationParametersDL.java @@ -1,8 +1,8 @@ package gred.nucleus.mains; +import gred.nucleus.core.Measure3D; import gred.nucleus.filesInputOutput.Directory; import gred.nucleus.filesInputOutput.OutputTextFile; -import gred.nucleus.core.Measure3D; import gred.nucleus.plugins.PluginParameters; import gred.nucleus.utils.Histogram; import ij.ImagePlus; @@ -27,25 +27,26 @@ public static void computeNucleusParameters(String RawImageSourceFile, Directory directoryInput = new Directory(pluginParameters.getInputFolder()); directoryInput.listImageFiles(pluginParameters.getInputFolder()); directoryInput.checkIfEmpty(); - ArrayList rawImages = directoryInput.m_listeOfFiles; - String outputCropGeneralInfoOTSU = pluginParameters.getAnalyseParameters() + getColnameResult(); + ArrayList rawImages = directoryInput.m_fileList; + StringBuilder outputCropGeneralInfoOTSU = + new StringBuilder(pluginParameters.getAnalyseParameters() + getResultsColumnNames()); for (File currentFile : rawImages) { ImagePlus Raw = new ImagePlus(currentFile.getAbsolutePath()); System.out.println("current File " + currentFile.getName()); ImagePlus[] Segmented = BF.openImagePlus(pluginParameters.getOutputFolder() + currentFile.getName()); - Measure3D mesure3D = new Measure3D(Segmented, + Measure3D measure3D = new Measure3D(Segmented, Raw, - pluginParameters.getXcalibration(Raw), - pluginParameters.getYcalibration(Raw), - pluginParameters.getZcalibration(Raw)); - outputCropGeneralInfoOTSU += mesure3D.nucleusParameter3D() + "\n"; + pluginParameters.getXCalibration(Raw), + pluginParameters.getYCalibration(Raw), + pluginParameters.getZCalibration(Raw)); + outputCropGeneralInfoOTSU.append(measure3D.nucleusParameter3D()).append("\n"); } OutputTextFile resultFileOutputOTSU = new OutputTextFile(pluginParameters.getOutputFolder() + directoryInput.getSeparator() + "result_Segmentation_Analyse.csv"); - resultFileOutputOTSU.SaveTextFile(outputCropGeneralInfoOTSU); + resultFileOutputOTSU.SaveTextFile(outputCropGeneralInfoOTSU.toString()); } @@ -56,8 +57,9 @@ public static void computeNucleusParametersDL(String RawImageSourceFile, String Directory directoryInput = new Directory(pluginParameters.getOutputFolder()); directoryInput.listImageFiles(pluginParameters.getOutputFolder()); directoryInput.checkIfEmpty(); - ArrayList segImages = directoryInput.m_listeOfFiles; - String outputCropGeneralInfoOTSU = pluginParameters.getAnalyseParameters() + getColnameResult(); + ArrayList segImages = directoryInput.m_fileList; + StringBuilder outputCropGeneralInfoOTSU = + new StringBuilder(pluginParameters.getAnalyseParameters() + getResultsColumnNames()); for (File currentFile : segImages) { System.out.println("current File " + currentFile.getName()); ImagePlus Raw = new ImagePlus(pluginParameters.getInputFolder() + @@ -72,22 +74,23 @@ public static void computeNucleusParametersDL(String RawImageSourceFile, String Histogram histogram = new Histogram(); histogram.run(Segmented[0]); if (histogram.getNbLabels() > 0) { - Measure3D mesure3D = new Measure3D(Segmented, + Measure3D measure3D = new Measure3D(Segmented, Raw, - pluginParameters.getXcalibration(Raw), - pluginParameters.getYcalibration(Raw), - pluginParameters.getZcalibration(Raw)); - outputCropGeneralInfoOTSU += mesure3D.nucleusParameter3D() + "\tNA" + "\n"; + pluginParameters.getXCalibration(Raw), + pluginParameters.getYCalibration(Raw), + pluginParameters.getZCalibration(Raw)); + outputCropGeneralInfoOTSU.append(measure3D.nucleusParameter3D()).append("\tNA").append("\n"); } } OutputTextFile resultFileOutputOTSU = new OutputTextFile(pluginParameters.getOutputFolder() + directoryInput.getSeparator() + "result_Segmentation_Analyse.csv"); - resultFileOutputOTSU.SaveTextFile(outputCropGeneralInfoOTSU); + resultFileOutputOTSU.SaveTextFile(outputCropGeneralInfoOTSU.toString()); } + public static void main(String[] args) throws Exception { DebugTools.enableLogging("OFF"); @@ -98,6 +101,7 @@ public static void main(String[] args) throws Exception { } + public static ImagePlus imageSEGTransform(ImagePlus SegmentedTMP) { LabelImages.removeBorderLabels(SegmentedTMP); return SegmentedTMP; @@ -105,6 +109,7 @@ public static ImagePlus imageSEGTransform(ImagePlus SegmentedTMP) { } + public static ImagePlus generateSegmentedImage(ImagePlus imagePlusInput, int threshold) { ImageStack imageStackInput = imagePlusInput.getStack(); @@ -118,8 +123,6 @@ public static ImagePlus generateSegmentedImage(ImagePlus imagePlusInput, double voxelValue = imageStackInput.getVoxel(i, j, k); if (voxelValue > 1) { imageStackSegmented.setVoxel(i, j, k, 255); - imageStackInput.getVoxel(i, j, k); - } else { imageStackSegmented.setVoxel(i, j, k, 0); } @@ -131,7 +134,7 @@ public static ImagePlus generateSegmentedImage(ImagePlus imagePlusInput, } - public static String getColnameResult() { + public static String getResultsColumnNames() { return "NucleusFileName\t" + "Volume\t" + "Flatness\t" + @@ -151,6 +154,7 @@ public static String getColnameResult() { "OTSUThreshold\n"; } + private static void saveFile(ImagePlus imagePlusInput, String pathFile) { FileSaver fileSaver = new FileSaver(imagePlusInput); fileSaver.saveAsTiffStack(pathFile); diff --git a/src/main/java/gred/nucleus/mains/main.java b/src/main/java/gred/nucleus/mains/main.java index b8366520..f0656438 100644 --- a/src/main/java/gred/nucleus/mains/main.java +++ b/src/main/java/gred/nucleus/mains/main.java @@ -4,11 +4,11 @@ import fr.igred.omero.ImageContainer; import fr.igred.omero.repository.DatasetContainer; import fr.igred.omero.repository.ProjectContainer; -import gred.nucleus.cli.*; -import gred.nucleus.machineLeaningUtils.ComputeNucleiParametersML; import gred.nucleus.autocrop.*; +import gred.nucleus.cli.*; import gred.nucleus.core.ComputeNucleiParameters; import gred.nucleus.exceptions.fileInOut; +import gred.nucleus.machineLeaningUtils.ComputeNucleiParametersML; import gred.nucleus.segmentation.SegmentationCalling; import gred.nucleus.segmentation.SegmentationParameters; import ij.ImagePlus; @@ -18,10 +18,12 @@ import org.apache.commons.cli.*; import java.io.Console; +import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.regex.Pattern; public class main { @@ -29,43 +31,33 @@ public class main { /** * Method to run autocrop with only input output folder and with default parameters which are: *

- * xCropBoxSize:40 yCropBoxSize:40 zCropBoxSize:20 thresholdOTSUcomputing:20 slicesOTSUcomputing:0 + * xCropBoxSize:40 yCropBoxSize:40 zCropBoxSize:20 thresholdOTSUComputing:20 slicesOTSUComputing:0 * channelToComputeThreshold:1 maxVolumeNucleus:2147483647 minVolumeNucleus:1 * * @param inputDirectory path to the raw image's folder * @param outputDirectory path to output folder analysis - * - * @throws IOException - * @throws FormatException - * @throws fileInOut - * @throws Exception */ - public static void runAutoCropFolder(String inputDirectory, String outputDirectory) - throws IOException, FormatException, fileInOut, Exception { + public static void runAutoCropFolder(String inputDirectory, String outputDirectory) { AutocropParameters autocropParameters = new AutocropParameters(inputDirectory, outputDirectory); AutoCropCalling autoCrop = new AutoCropCalling(autocropParameters); autoCrop.runFolder(); } + /** * Method to run autocrop with input folder, output folder and with config file analysis : * * @param inputDirectory path to the raw image's folder * @param outputDirectory path to output folder analysis * @param pathToConfig path to config file - * - * @throws IOException - * @throws FormatException - * @throws fileInOut - * @throws Exception */ - public static void runAutoCropFolder(String inputDirectory, String outputDirectory, String pathToConfig) - throws IOException, FormatException, fileInOut, Exception { + public static void runAutoCropFolder(String inputDirectory, String outputDirectory, String pathToConfig) { AutocropParameters autocropParameters = new AutocropParameters(inputDirectory, outputDirectory, pathToConfig); AutoCropCalling autoCrop = new AutoCropCalling(autocropParameters); autoCrop.runFolder(); } + /** * Method to run autocrop with input folder, output folder : * @@ -84,11 +76,12 @@ public static void runAutoCropFile(String inputDirectory, String outputDirectory autoCrop.runFile(inputDirectory); } + public static void runAutoCropOmero(String inputDirectory, String outputDirectory, Client client, AutoCropCalling autoCrop) throws Exception { - String[] param = inputDirectory.split("/"); + String[] param = inputDirectory.split(Pattern.quote(File.separator)); if (param.length >= 2) { if (param[0].equals("image")) { @@ -107,8 +100,8 @@ public static void runAutoCropOmero(String inputDirectory, autoCrop.runImageOmero(image, outputsDat, client); } else { - Long id = Long.parseLong(param[1]); - List images = null; + Long id = Long.parseLong(param[1]); + List images; String name = ""; @@ -145,6 +138,7 @@ public static void runAutoCropOmero(String inputDirectory, } } + public static void runAutoCropOmero(String inputDirectory, String outputDirectory, String pathToConfig, @@ -155,6 +149,7 @@ public static void runAutoCropOmero(String inputDirectory, runAutoCropOmero(inputDirectory, outputDirectory, client, autoCrop); } + public static void runAutoCropOmero(String inputDirectory, String outputDirectory, Client client) throws Exception { AutocropParameters autocropParameters = new AutocropParameters(".", "."); AutoCropCalling autoCrop = new AutoCropCalling(autocropParameters); @@ -176,9 +171,9 @@ public static void runAutoCropOmero(String inputDirectory, String outputDirector public static void segmentationFolder(String inputDirectory, String outputDirectory) throws Exception { System.out.println("test " + inputDirectory); SegmentationParameters segmentationParameters = new SegmentationParameters(inputDirectory, outputDirectory); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { - String log = otsuModif.runSeveralImages2(); + String log = otsuModified.runSeveralImages2(); if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); } @@ -187,6 +182,7 @@ public static void segmentationFolder(String inputDirectory, String outputDirect } } + /** * Method to run segmentation with input folder, output folder with config file : * @@ -200,9 +196,9 @@ public static void segmentationFolder(String inputDirectory, String outputDirect throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(inputDirectory, outputDirectory, config); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { - String log = otsuModif.runSeveralImages2(); + String log = otsuModified.runSeveralImages2(); if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); } @@ -211,6 +207,7 @@ public static void segmentationFolder(String inputDirectory, String outputDirect } } + /** * Method to run segmentation on one image : * @@ -221,9 +218,9 @@ public static void segmentationFolder(String inputDirectory, String outputDirect */ public static void segmentationOneImage(String inputDirectory, String outputDirectory) throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(inputDirectory, outputDirectory); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { - String log = otsuModif.runOneImage(inputDirectory); + String log = otsuModified.runOneImage(inputDirectory); if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); } @@ -232,11 +229,14 @@ public static void segmentationOneImage(String inputDirectory, String outputDire } } + public static void segmentationOmero(String inputDirectory, String outputDirectory, Client client, - SegmentationCalling otsuModif) throws Exception { - String[] param = inputDirectory.split("/"); + SegmentationCalling otsuModified) + throws Exception { + + String[] param = inputDirectory.split(Pattern.quote(File.separator)); if (param.length >= 2) { if (param[0].equals("image")) { @@ -246,9 +246,9 @@ public static void segmentationOmero(String inputDirectory, try { String log; if (param.length == 3 && param[2].equals("ROI")) { - log = otsuModif.runOneImageOmeroROI(image, Long.parseLong(outputDirectory), client); + log = otsuModified.runOneImageOmeroROI(image, Long.parseLong(outputDirectory), client); } else { - log = otsuModif.runOneImageOmero(image, Long.parseLong(outputDirectory), client); + log = otsuModified.runOneImageOmero(image, Long.parseLong(outputDirectory), client); } if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); @@ -257,8 +257,8 @@ public static void segmentationOmero(String inputDirectory, e.printStackTrace(); } } else { - Long id = Long.parseLong(param[1]); - List images = null; + Long id = Long.parseLong(param[1]); + List images; switch (param[0]) { case "dataset": @@ -289,9 +289,9 @@ public static void segmentationOmero(String inputDirectory, String log; if ((param.length == 3 && param[2].equals("ROI")) || (param.length == 5 && param[4].equals("ROI"))) { - log = otsuModif.runSeveralImageOmeroROI(images, Long.parseLong(outputDirectory), client); + log = otsuModified.runSeveralImageOmeroROI(images, Long.parseLong(outputDirectory), client); } else { - log = otsuModif.runSeveralImageOmero(images, Long.parseLong(outputDirectory), client); + log = otsuModified.runSeveralImageOmero(images, Long.parseLong(outputDirectory), client); } if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); @@ -305,38 +305,35 @@ public static void segmentationOmero(String inputDirectory, } } + public static void segmentationOmero(String inputDirectory, String outputDirectory, String config, Client client) throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(".", ".", config); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); - segmentationOmero(inputDirectory, outputDirectory, client, otsuModif); + segmentationOmero(inputDirectory, outputDirectory, client, otsuModified); } + public static void segmentationOmero(String inputDirectory, String outputDirectory, Client client) throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(".", "."); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); - segmentationOmero(inputDirectory, outputDirectory, client, otsuModif); + segmentationOmero(inputDirectory, outputDirectory, client, otsuModified); } + /** * Compute parameter from raw data folder and segmented data : * * @param rawImagesInputDirectory path to the raw image's folder * @param segmentedImagesDirectory path to the segmented image's folder * @param pathToConfig path to config file - * - * @throws IOException - * @throws FormatException - * @throws fileInOut - * @throws Exception */ public static void computeNucleusParameters(String rawImagesInputDirectory, String segmentedImagesDirectory, - String pathToConfig) - throws IOException, FormatException, fileInOut, Exception { + String pathToConfig) { ComputeNucleiParameters generateParameters = new ComputeNucleiParameters(rawImagesInputDirectory, segmentedImagesDirectory, pathToConfig); generateParameters.run(); @@ -349,14 +346,8 @@ public static void computeNucleusParameters(String rawImagesInputDirectory, * * @param rawImagesInputDirectory path to the raw image's folder * @param segmentedImagesDirectory path to the segmented image's folder - * - * @throws IOException - * @throws FormatException - * @throws fileInOut - * @throws Exception */ - public static void computeNucleusParameters(String rawImagesInputDirectory, String segmentedImagesDirectory) - throws IOException, FormatException, fileInOut, Exception { + public static void computeNucleusParameters(String rawImagesInputDirectory, String segmentedImagesDirectory) { ComputeNucleiParameters generateParameters = new ComputeNucleiParameters(rawImagesInputDirectory, segmentedImagesDirectory); generateParameters.run(); @@ -391,8 +382,6 @@ public static void computeNucleusParametersDL(String rawImagesInputFolder, Strin * @param pathToCoordinates : folder containing coordinate files * @param pathToRaw : folder containing raw images associate * - * @throws IOException - * @throws FormatException * @throws Exception */ @@ -400,12 +389,13 @@ public static void computeNucleusParametersDL(String rawImagesInputFolder, Strin // UN DOSSIER AVEC LES ZPROJECTION // UN DOSSIER AVEC LES COORDONNEES public static void generateProjectionFromCoordinates(String pathToCoordinates, String pathToRaw) - throws IOException, FormatException, Exception { + throws Exception { generateProjectionFromCoordinates projection = new generateProjectionFromCoordinates(pathToCoordinates, pathToRaw); projection.generateCoordinate(); } + /** * Method to draw missing boxes in initial projection after manual filtering. * @@ -428,6 +418,7 @@ public static void generateProjectionFromCoordinates(String pathToGIFTSeg, projection.generateCoordinateFiltered(); } + /** * Method to crop an image from coordinates (case of multi channels). Tabulated file containing associate coordinate * file and images , 1 association per line example : @@ -444,6 +435,7 @@ public static void cropFromCoordinates(String coordinatesDir) throws Exception { test.runCropFromCoordinate(); } + /** * Method merge overlay and raw images together (cellular population annotation , example guard cells pavement * cells). This method contrast Tabulated file containing associate coordinate file and images , @@ -456,24 +448,25 @@ public static void cropFromCoordinates(String coordinatesDir) throws Exception { */ - public static void genereOV(String linkOverlayProjection) throws Exception { + public static void generateOV(String linkOverlayProjection) throws Exception { GenerateOverlay ov = new GenerateOverlay(linkOverlayProjection); ov.run(); } + public static void saveFile(ImagePlus imagePlusInput, String pathFile) { FileSaver fileSaver = new FileSaver(imagePlusInput); fileSaver.saveAsTiff(pathFile); } + public static void main(String[] args) throws Exception { DebugTools.enableLogging("OFF"); List listArgs = Arrays.asList(args); System.setProperty("java.awt.headless", "false"); - if (listArgs.contains("-h") || listArgs.contains("-help")) { CLIHelper command = new CLIHelper(args); } else if ((listArgs.contains("-ome")) || (listArgs.contains("-omero"))) { @@ -485,6 +478,7 @@ public static void main(String[] args) throws Exception { } } + public static boolean OMEROAvailableAction(String action) { ArrayList actionAvailableInOmero = new ArrayList<>(); actionAvailableInOmero.add("autocrop"); @@ -505,11 +499,11 @@ public static void main2(String[] args) throws Exception { options.addOption("a", "action", true, "Action to make"); options.addOption("in", "input", true, "Input path"); options.addOption("out", "output", true, "Output path"); - options.addOption("co", "coodinates", true, "Coordinates file"); + options.addOption("co", "coordinates", true, "Coordinates file"); options.addOption("f", "file", false, "Input is a file"); options.addOption("c", "config", true, "Path to config file"); options.addOption("ome", "omero", false, "Usage of OMERO"); - options.addOption("h", "hostname", true, "Hostname of the OMERO serveur"); + options.addOption("h", "hostname", true, "Hostname of the OMERO server"); options.addOption("pt", "port", true, "Port used by OMERO"); options.addOption("u", "username", true, "Username in OMERO"); options.addOption("p", "password", true, "Password in OMERO"); @@ -642,7 +636,7 @@ public static void main2(String[] args) throws Exception { cropFromCoordinates(cmd.getOptionValue("input")); break; case "GenerateOverlay": - genereOV(cmd.getOptionValue("input")); + generateOV(cmd.getOptionValue("input")); break; default: formatter.printHelp("NucleusJ2.0", options, true); @@ -657,7 +651,6 @@ public static void main2(String[] args) throws Exception { } System.out.println("Fin du programme"); } - } diff --git a/src/main/java/gred/nucleus/mains/noiseComputing.java b/src/main/java/gred/nucleus/mains/noiseComputing.java index 33dbeab0..dd87d351 100644 --- a/src/main/java/gred/nucleus/mains/noiseComputing.java +++ b/src/main/java/gred/nucleus/mains/noiseComputing.java @@ -14,21 +14,21 @@ public class noiseComputing { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { computeMeanNoise( "/media/titus/DATA/ML_ANALYSE_DATA/ANALYSE_COMPARAISON_REANALYSE/129_ANNOTATION_FULL/RAW/", "/media/titus/DATA/ML_ANALYSE_DATA/ANALYSE_COMPARAISON_REANALYSE/129_ANNOTATION_FULL/TMP_PARAMETERS/" ); } - public static void computeMeanNoise(String RawImageSourceFile, String SegmentedImagesSourceFile) - throws Exception { + + public static void computeMeanNoise(String RawImageSourceFile, String SegmentedImagesSourceFile) { PluginParameters pluginParameters = new PluginParameters(RawImageSourceFile, SegmentedImagesSourceFile); Directory directoryInput = new Directory(pluginParameters.getOutputFolder()); directoryInput.listImageFiles(pluginParameters.getOutputFolder()); directoryInput.checkIfEmpty(); - ArrayList segImages = directoryInput.m_listeOfFiles; - String ResultNoise = "NucleusFileName\tMeanNoise\n"; + ArrayList segImages = directoryInput.m_fileList; + StringBuilder ResultNoise = new StringBuilder("NucleusFileName\tMeanNoise\n"); for (File currentFile : segImages) { System.out.println("current File " + currentFile.getName()); ImagePlus Raw = new ImagePlus(pluginParameters.getInputFolder() + @@ -38,13 +38,15 @@ public static void computeMeanNoise(String RawImageSourceFile, String SegmentedI // TODO TRANSFORMATION FACTORISABLE AVEC METHODE DU DESSUS !!!!! double meanNoise = meanIntensityNoise(Raw, Segmented); - ResultNoise = ResultNoise + currentFile.getName() + "\t" + meanNoise + "\t" + medianComputing(Raw) + "\n"; + ResultNoise.append(currentFile.getName()).append("\t") + .append(meanNoise).append("\t") + .append(medianComputing(Raw)).append("\n"); System.out.println("Noise mean " + meanNoise); } OutputTextFile resultFileOutputOTSU = new OutputTextFile( "/media/titus/DATA/ML_ANALYSE_DATA/ANALYSE_COMPARAISON_REANALYSE/129_ANNOTATION_FULL/NoiseGIFT.csv"); - resultFileOutputOTSU.SaveTextFile(ResultNoise); + resultFileOutputOTSU.SaveTextFile(ResultNoise.toString()); } @@ -60,7 +62,6 @@ private static double meanIntensityNoise(ImagePlus _Raw, ImagePlus _Segmented) { meanIntensity += imageStackRaw.getVoxel(i, j, k); voxelCounted++; } - } } } @@ -69,21 +70,23 @@ private static double meanIntensityNoise(ImagePlus _Raw, ImagePlus _Segmented) { } + public static double medianComputing(ImagePlus _Raw) { double voxelMedianValue = 0; Histogram histogram = new Histogram(); histogram.run(_Raw); - HashMap _segmentedNucleusHisto = histogram.getHistogram(); - int medianElementStop = (_Raw.getHeight() * _Raw.getWidth() * _Raw.getNSlices()) / 2; - int increment = 0; - for (HashMap.Entry entry : _segmentedNucleusHisto.entrySet()) { + + HashMap _segmentedNucleusHistogram = histogram.getHistogram(); + + int medianElementStop = (_Raw.getHeight() * _Raw.getWidth() * _Raw.getNSlices()) / 2; + int increment = 0; + + for (HashMap.Entry entry : _segmentedNucleusHistogram.entrySet()) { increment += entry.getValue(); if (increment > medianElementStop) { voxelMedianValue = entry.getKey(); break; } - - } return voxelMedianValue; } diff --git a/src/main/java/gred/nucleus/myGradient/FJ.java b/src/main/java/gred/nucleus/myGradient/FJ.java index 66be2bf7..815e22a4 100644 --- a/src/main/java/gred/nucleus/myGradient/FJ.java +++ b/src/main/java/gred/nucleus/myGradient/FJ.java @@ -1,146 +1,150 @@ -package gred.nucleus.myGradient; - -import ij.CompositeImage; -import ij.IJ; -import ij.ImagePlus; -import ij.WindowManager; -import ij.process.LUT; -import imagescience.image.Image; -import imagescience.utility.I5DResource; -import imagescience.utility.ImageScience; - -public final class FJ { - - static final int SINGLEIMAGE = 1, IMAGESTACK = 2, HYPERSTACK = 3, COMPOSITEIMAGE = 4, IMAGE5D = 5; - private static final String NAME = "FeatureJ"; - private static final String VERSION = "1.6.0"; - private static final String MINIJVERSION = "1.44a"; - private static final String MINISVERSION = "2.4.0"; - - public static String name() { - return NAME; - } - - public static String version() { - return VERSION; - } - - static boolean libcheck() { - - if (IJ.getVersion().compareTo(MINIJVERSION) < 0) { - error("This plugin requires ImageJ version " + MINIJVERSION + " or higher"); - return false; - } - - try { - if (ImageScience.version().compareTo(MINISVERSION) < 0) { - throw new IllegalStateException(); - } - } catch (Throwable e) { - error("This plugin requires ImageScience version " + MINISVERSION + " or higher"); - return false; - } - - return true; - } - - static ImagePlus imageplus() { - - final ImagePlus imp = WindowManager.getCurrentImage(); - if (imp == null) { - error("There are no images open"); - return null; - } - - final int type = imp.getType(); - if (type != ImagePlus.GRAY8 && type != ImagePlus.GRAY16 && type != ImagePlus.GRAY32) { - error("The image is not a gray-scale image"); - return null; - } - - return imp; - } - - static void show(final Image img, final ImagePlus imp) { - - ImagePlus newimp = img.imageplus(); - newimp.setCalibration(imp.getCalibration()); - final double[] minmax = img.extrema(); - final double min = minmax[0], max = minmax[1]; - newimp.setDisplayRange(min, max); - - switch (type(imp)) { - - case IMAGE5D: { - newimp = I5DResource.convert(newimp, true); - I5DResource.transfer(imp, newimp); - I5DResource.minmax(newimp, min, max); - I5DResource.mode(newimp, I5DResource.GRAY); - break; - } - case COMPOSITEIMAGE: { - final CompositeImage newcimp = new CompositeImage(newimp); - newcimp.copyLuts(imp); - newcimp.setMode(CompositeImage.GRAYSCALE); - final int nc = newcimp.getNChannels(); - for (int c = 1; c <= nc; ++c) { - final LUT lut = newcimp.getChannelLut(c); - lut.min = min; - lut.max = max; - } - newimp = newcimp; - break; - } - case HYPERSTACK: { - newimp.setOpenAsHyperStack(true); - break; - } - } - - newimp.changes = FJ_Options.save; - - log("Showing result image"); - newimp.show(); - } - - static void close(final ImagePlus imp) { - - if (FJ_Options.close) { - log("Closing input image"); - imp.close(); - } - } - - static int type(final ImagePlus imp) { - - int type = SINGLEIMAGE; - boolean i5dexist = false; - try { - Class.forName("i5d.Image5D"); - i5dexist = true; - } catch (Throwable e) { - e.printStackTrace(); - } - if (i5dexist && I5DResource.instance(imp)) { - type = IMAGE5D; - } else if (imp.isComposite()) { - type = COMPOSITEIMAGE; - } else if (imp.isHyperStack()) { - type = HYPERSTACK; - } else if (imp.getImageStackSize() > 1) type = IMAGESTACK; - return type; - } - - static void error(final String message) { - - IJ.showMessage(NAME + ": Error", message + "."); - IJ.showProgress(1); - IJ.showStatus(""); - } - - static void log(final String message) { - - if (FJ_Options.log) IJ.log(message); - } - -} +package gred.nucleus.myGradient; + +import ij.CompositeImage; +import ij.IJ; +import ij.ImagePlus; +import ij.WindowManager; +import ij.process.LUT; +import imagescience.image.Image; +import imagescience.utility.I5DResource; +import imagescience.utility.ImageScience; + +public final class FJ { + static final int SINGLE_IMAGE = 1; + static final int IMAGE_STACK = 2; + static final int HYPERSTACK = 3; + static final int COMPOSITE_IMAGE = 4; + static final int IMAGE5D = 5; + private static final String NAME = "FeatureJ"; + private static final String VERSION = "1.6.0"; + private static final String MIN_IJ_VERSION = "1.44a"; + private static final String MIN_IS_VERSION = "2.4.0"; + + public static String name() { + return NAME; + } + + + public static String version() { + return VERSION; + } + + static boolean libCheck() { + + if (IJ.getVersion().compareTo(MIN_IJ_VERSION) < 0) { + error("This plugin requires ImageJ version " + MIN_IJ_VERSION + " or higher"); + return false; + } + + try { + if (ImageScience.version().compareTo(MIN_IS_VERSION) < 0) { + throw new IllegalStateException(); + } + } catch (Throwable e) { + error("This plugin requires ImageScience version " + MIN_IS_VERSION + " or higher"); + return false; + } + + return true; + } + + static ImagePlus imageplus() { + + final ImagePlus imp = WindowManager.getCurrentImage(); + if (imp == null) { + error("There are no images open"); + return null; + } + + final int type = imp.getType(); + if (type != ImagePlus.GRAY8 && type != ImagePlus.GRAY16 && type != ImagePlus.GRAY32) { + error("The image is not a gray-scale image"); + return null; + } + + return imp; + } + + static void show(final Image img, final ImagePlus imp) { + + ImagePlus newImagePlus = img.imageplus(); + newImagePlus.setCalibration(imp.getCalibration()); + final double[] min_max = img.extrema(); + final double min = min_max[0]; + final double max = min_max[1]; + newImagePlus.setDisplayRange(min, max); + + switch (type(imp)) { + + case IMAGE5D: { + newImagePlus = I5DResource.convert(newImagePlus, true); + I5DResource.transfer(imp, newImagePlus); + I5DResource.minmax(newImagePlus, min, max); + I5DResource.mode(newImagePlus, I5DResource.GRAY); + break; + } + case COMPOSITE_IMAGE: { + final CompositeImage newCompositeImage = new CompositeImage(newImagePlus); + newCompositeImage.copyLuts(imp); + newCompositeImage.setMode(CompositeImage.GRAYSCALE); + final int nc = newCompositeImage.getNChannels(); + for (int c = 1; c <= nc; ++c) { + final LUT lut = newCompositeImage.getChannelLut(c); + lut.min = min; + lut.max = max; + } + newImagePlus = newCompositeImage; + break; + } + case HYPERSTACK: { + newImagePlus.setOpenAsHyperStack(true); + break; + } + } + + newImagePlus.changes = FJ_Options.save; + + log("Showing result image"); + newImagePlus.show(); + } + + static void close(final ImagePlus imp) { + + if (FJ_Options.close) { + log("Closing input image"); + imp.close(); + } + } + + static int type(final ImagePlus imp) { + + int type = SINGLE_IMAGE; + boolean i5dExist = false; + try { + Class.forName("i5d.Image5D"); + i5dExist = true; + } catch (Throwable e) { + e.printStackTrace(); + } + if (i5dExist && I5DResource.instance(imp)) { + type = IMAGE5D; + } else if (imp.isComposite()) { + type = COMPOSITE_IMAGE; + } else if (imp.isHyperStack()) { + type = HYPERSTACK; + } else if (imp.getImageStackSize() > 1) type = IMAGE_STACK; + return type; + } + + static void error(final String message) { + + IJ.showMessage(NAME + ": Error", message + "."); + IJ.showProgress(1); + IJ.showStatus(""); + } + + static void log(final String message) { + + if (FJ_Options.log) IJ.log(message); + } +} diff --git a/src/main/java/gred/nucleus/myGradient/FJ_About.java b/src/main/java/gred/nucleus/myGradient/FJ_About.java index 9a262d99..d8846bf5 100644 --- a/src/main/java/gred/nucleus/myGradient/FJ_About.java +++ b/src/main/java/gred/nucleus/myGradient/FJ_About.java @@ -1,20 +1,18 @@ -package gred.nucleus.myGradient; - -import ij.IJ; -import ij.plugin.PlugIn; - -import java.util.Calendar; - -public class FJ_About implements PlugIn { - - public void run(String arg) { - - IJ.showMessage( - FJ.name() + ": About", - FJ.name() + " is a plugin package for image feature extraction.\n" + - "The version number of the present installation is " + FJ.version() + ".\n" + - "Copyright (C) 2002-" + Calendar.getInstance().get(Calendar.YEAR) + " by Erik Meijering.\n" - ); - } - -} +package gred.nucleus.myGradient; + +import ij.IJ; +import ij.plugin.PlugIn; + +import java.util.Calendar; + +public class FJ_About implements PlugIn { + + public void run(String arg) { + + IJ.showMessage( + FJ.name() + ": About", + FJ.name() + " is a plugin package for image feature extraction.\n" + + "The version number of the present installation is " + FJ.version() + ".\n" + + "Copyright (C) 2002-" + Calendar.getInstance().get(Calendar.YEAR) + " by Erik Meijering.\n"); + } +} diff --git a/src/main/java/gred/nucleus/myGradient/FJ_Derivatives.java b/src/main/java/gred/nucleus/myGradient/FJ_Derivatives.java index 8731f5f5..1e4144c9 100644 --- a/src/main/java/gred/nucleus/myGradient/FJ_Derivatives.java +++ b/src/main/java/gred/nucleus/myGradient/FJ_Derivatives.java @@ -1,129 +1,134 @@ -package gred.nucleus.myGradient; - -import ij.ImagePlus; -import ij.gui.GenericDialog; -import ij.plugin.PlugIn; -import imagescience.feature.Differentiator; -import imagescience.image.Aspects; -import imagescience.image.FloatImage; -import imagescience.image.Image; - -import java.awt.*; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; - -public class FJ_Derivatives implements PlugIn, WindowListener { - - private static int xorder = 0; - private static int yorder = 0; - private static int zorder = 0; - - private static String scale = "1.0"; - - private static Point pos = new Point(-1, -1); - - public void run(String arg) { - - if (!FJ.libcheck()) return; - final ImagePlus imp = FJ.imageplus(); - if (imp == null) return; - - FJ.log(FJ.name() + " " + FJ.version() + ": Derivatives"); - - GenericDialog gd = new GenericDialog(FJ.name() + ": Derivatives"); - final String[] orders = new String[11]; - for (int i = 0; i < 11; ++i) orders[i] = String.valueOf(i); - gd.addChoice("x-order of differentiation:", orders, orders[xorder]); - gd.addChoice("y-order of differentiation:", orders, orders[yorder]); - gd.addChoice("z-order of differentiation:", orders, orders[zorder]); - gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); - gd.addStringField("Smoothing scale:", scale); - - if (pos.x >= 0 && pos.y >= 0) { - gd.centerDialog(false); - gd.setLocation(pos); - } else { - gd.centerDialog(true); - } - gd.addWindowListener(this); - gd.showDialog(); - - if (gd.wasCanceled()) return; - - xorder = gd.getNextChoiceIndex(); - yorder = gd.getNextChoiceIndex(); - zorder = gd.getNextChoiceIndex(); - scale = gd.getNextString(); - - (new FJDerivatives()).run(imp, xorder, yorder, zorder, scale); - } - - public void windowActivated(final WindowEvent e) { - } - - public void windowClosed(final WindowEvent e) { - - pos.x = e.getWindow().getX(); - pos.y = e.getWindow().getY(); - } - - public void windowClosing(final WindowEvent e) { - } - - public void windowDeactivated(final WindowEvent e) { - } - - public void windowDeiconified(final WindowEvent e) { - } - - public void windowIconified(final WindowEvent e) { - } - - public void windowOpened(final WindowEvent e) { - } - -} - -class FJDerivatives { - - void run( - final ImagePlus imp, - final int xorder, - final int yorder, - final int zorder, - final String scale - ) { - - try { - final Image img = Image.wrap(imp); - final Aspects aspects = img.aspects(); - if (!FJ_Options.isotropic) img.aspects(new Aspects()); - double scaleval; - try { - scaleval = Double.parseDouble(scale); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid smoothing scale value"); - } - final Image newimg = new FloatImage(img); - final Differentiator diff = new Differentiator(); - diff.messenger.log(FJ_Options.log); - diff.messenger.status(FJ_Options.pgs); - diff.progressor.display(FJ_Options.pgs); - diff.run(newimg, scaleval, xorder, yorder, zorder); - newimg.aspects(aspects); - FJ.show(newimg, imp); - FJ.close(imp); - - } catch (OutOfMemoryError e) { - FJ.error("Not enough memory for this operation"); - - } catch (IllegalArgumentException | IllegalStateException e) { - FJ.error(e.getMessage()); - - } catch (Throwable e) { - FJ.error("An unidentified error occurred while running the plugin"); - - } - } - -} +package gred.nucleus.myGradient; + +import ij.ImagePlus; +import ij.gui.GenericDialog; +import ij.plugin.PlugIn; +import imagescience.feature.Differentiator; +import imagescience.image.Aspects; +import imagescience.image.FloatImage; +import imagescience.image.Image; + +import java.awt.*; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +public class FJ_Derivatives implements PlugIn, WindowListener { + + private static int xOrder = 0; + private static int yOrder = 0; + private static int zOrder = 0; + + private static String scale = "1.0"; + + private static Point pos = new Point(-1, -1); + + public void run(String arg) { + + if (!FJ.libCheck()) return; + final ImagePlus imp = FJ.imageplus(); + if (imp == null) return; + + FJ.log(FJ.name() + " " + FJ.version() + ": Derivatives"); + + GenericDialog gd = new GenericDialog(FJ.name() + ": Derivatives"); + final String[] orders = new String[11]; + for (int i = 0; i < 11; ++i) orders[i] = String.valueOf(i); + gd.addChoice("x-order of differentiation:", orders, orders[xOrder]); + gd.addChoice("y-order of differentiation:", orders, orders[yOrder]); + gd.addChoice("z-order of differentiation:", orders, orders[zOrder]); + gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); + gd.addStringField("Smoothing scale:", scale); + + if (pos.x >= 0 && pos.y >= 0) { + gd.centerDialog(false); + gd.setLocation(pos); + } else { + gd.centerDialog(true); + } + gd.addWindowListener(this); + gd.showDialog(); + + if (gd.wasCanceled()) return; + + xOrder = gd.getNextChoiceIndex(); + yOrder = gd.getNextChoiceIndex(); + zOrder = gd.getNextChoiceIndex(); + scale = gd.getNextString(); + + (new FJDerivatives()).run(imp, xOrder, yOrder, zOrder, scale); + } + + + public void windowActivated(final WindowEvent e) { + } + + + public void windowClosed(final WindowEvent e) { + + pos.x = e.getWindow().getX(); + pos.y = e.getWindow().getY(); + } + + + public void windowClosing(final WindowEvent e) { + } + + + public void windowDeactivated(final WindowEvent e) { + } + + + public void windowDeiconified(final WindowEvent e) { + } + + + public void windowIconified(final WindowEvent e) { + } + + + public void windowOpened(final WindowEvent e) { + } +} + +class FJDerivatives { + + void run( + final ImagePlus imp, + final int xOrder, + final int yOrder, + final int zOrder, + final String scale + ) { + + try { + final Image img = Image.wrap(imp); + final Aspects aspects = img.aspects(); + if (!FJ_Options.isotropic) img.aspects(new Aspects()); + double scaleVal; + try { + scaleVal = Double.parseDouble(scale); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid smoothing scale value"); + } + final Image newImg = new FloatImage(img); + final Differentiator diff = new Differentiator(); + diff.messenger.log(FJ_Options.log); + diff.messenger.status(FJ_Options.pgs); + diff.progressor.display(FJ_Options.pgs); + diff.run(newImg, scaleVal, xOrder, yOrder, zOrder); + newImg.aspects(aspects); + FJ.show(newImg, imp); + FJ.close(imp); + + } catch (OutOfMemoryError e) { + FJ.error("Not enough memory for this operation"); + + } catch (IllegalArgumentException | IllegalStateException e) { + FJ.error(e.getMessage()); + + } catch (Throwable e) { + FJ.error("An unidentified error occurred while running the plugin"); + + } + } +} diff --git a/src/main/java/gred/nucleus/myGradient/FJ_Edges.java b/src/main/java/gred/nucleus/myGradient/FJ_Edges.java index c9dbeeec..5b204b25 100644 --- a/src/main/java/gred/nucleus/myGradient/FJ_Edges.java +++ b/src/main/java/gred/nucleus/myGradient/FJ_Edges.java @@ -1,205 +1,214 @@ -package gred.nucleus.myGradient; - -import ij.ImagePlus; -import ij.gui.GenericDialog; -import ij.plugin.PlugIn; -import imagescience.feature.Edges; -import imagescience.image.Aspects; -import imagescience.image.FloatImage; -import imagescience.image.Image; -import imagescience.segment.Thresholder; -import imagescience.utility.Progressor; - -import java.awt.*; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; - -public class FJ_Edges implements PlugIn, ItemListener, WindowListener { - - private static boolean compute = true; - private static boolean suppress = false; - - private static String scale = "1.0"; - private static String lower = ""; - private static String higher = ""; - private static Point pos = new Point(-1, -1); - private Checkbox computebox, suppressbox; - - public void run(String arg) { - - if (!FJ.libcheck()) return; - final ImagePlus imp = FJ.imageplus(); - if (imp == null) return; - - FJ.log(FJ.name() + " " + FJ.version() + ": Edges"); - - GenericDialog gd = new GenericDialog(FJ.name() + ": Edges"); - gd.addCheckbox(" Compute gradient-magnitude image ", compute); - gd.addStringField(" Smoothing scale:", scale); - gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); - gd.addCheckbox(" Suppress non-maximum gradients ", suppress); - gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); - gd.addStringField(" Lower threshold value:", lower); - gd.addStringField(" Higher threshold value:", higher); - computebox = (Checkbox) gd.getCheckboxes().get(0); - computebox.addItemListener(this); - suppressbox = (Checkbox) gd.getCheckboxes().get(1); - suppressbox.addItemListener(this); - - if (pos.x >= 0 && pos.y >= 0) { - gd.centerDialog(false); - gd.setLocation(pos); - } else { - gd.centerDialog(true); - } - gd.addWindowListener(this); - gd.showDialog(); - - if (gd.wasCanceled()) return; - - compute = gd.getNextBoolean(); - scale = gd.getNextString(); - suppress = gd.getNextBoolean(); - lower = gd.getNextString(); - higher = gd.getNextString(); - - (new FJEdges()).run(imp, compute, scale, suppress, lower, higher); - } - - public void itemStateChanged(final ItemEvent e) { - - if (e.getSource() == computebox) { - if (!computebox.getState()) suppressbox.setState(false); - } else if (e.getSource() == suppressbox) { - if (suppressbox.getState()) computebox.setState(true); - } - } - - public void windowActivated(final WindowEvent e) { - } - - public void windowClosed(final WindowEvent e) { - - pos.x = e.getWindow().getX(); - pos.y = e.getWindow().getY(); - } - - public void windowClosing(final WindowEvent e) { - } - - public void windowDeactivated(final WindowEvent e) { - } - - public void windowDeiconified(final WindowEvent e) { - } - - public void windowIconified(final WindowEvent e) { - } - - public void windowOpened(final WindowEvent e) { - } - -} - -class FJEdges { - - void run( - final ImagePlus imp, - final boolean compute, - final String scale, - final boolean suppress, - final String lower, - final String higher - ) { - - try { - double scaleval, lowval = 0, highval = 0; - boolean lowthres = true, highthres = true; - try { - scaleval = Double.parseDouble(scale); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid smoothing scale value"); - } - try { - if (lower.equals("")) { - lowthres = false; - } else { - lowval = Double.parseDouble(lower); - } - } catch (Exception e) { - throw new IllegalArgumentException("Invalid lower threshold value"); - } - try { - if (higher.equals("")) { - highthres = false; - } else { - highval = Double.parseDouble(higher); - } - } catch (Exception e) { - throw new IllegalArgumentException("Invalid higher threshold value"); - } - final int thresmode = (lowthres ? 10 : 0) + (highthres ? 1 : 0); - - final Image img = Image.wrap(imp); - Image newimg = new FloatImage(img); - - double[] pls = {0, 1}; - int pl = 0; - if ((compute || suppress) && thresmode > 0) { - pls = new double[]{0, 0.9, 1}; - } - final Progressor progressor = new Progressor(); - progressor.display(FJ_Options.pgs); - - if (compute || suppress) { - final Aspects aspects = newimg.aspects(); - if (!FJ_Options.isotropic) newimg.aspects(new Aspects()); - final Edges edges = new Edges(); - progressor.range(pls[pl], pls[++pl]); - edges.progressor.parent(progressor); - edges.messenger.log(FJ_Options.log); - edges.messenger.status(FJ_Options.pgs); - newimg = edges.run(newimg, scaleval, suppress); - newimg.aspects(aspects); - } - - if (thresmode > 0) { - final Thresholder thres = new Thresholder(); - progressor.range(pls[pl], pls[++pl]); - thres.progressor.parent(progressor); - thres.messenger.log(FJ_Options.log); - thres.messenger.status(FJ_Options.pgs); - switch (thresmode) { - case 1: { - thres.hard(newimg, highval); - break; - } - case 10: { - thres.hard(newimg, lowval); - break; - } - case 11: { - thres.hysteresis(newimg, lowval, highval); - break; - } - } - } - - FJ.show(newimg, imp); - FJ.close(imp); - - } catch (OutOfMemoryError e) { - FJ.error("Not enough memory for this operation"); - - } catch (IllegalArgumentException | IllegalStateException e) { - FJ.error(e.getMessage()); - - } catch (Throwable e) { - FJ.error("An unidentified error occurred while running the plugin"); - - } - } - -} +package gred.nucleus.myGradient; + +import ij.ImagePlus; +import ij.gui.GenericDialog; +import ij.plugin.PlugIn; +import imagescience.feature.Edges; +import imagescience.image.Aspects; +import imagescience.image.FloatImage; +import imagescience.image.Image; +import imagescience.segment.Thresholder; +import imagescience.utility.Progressor; + +import java.awt.*; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +public class FJ_Edges implements PlugIn, ItemListener, WindowListener { + + private static final Point pos = new Point(-1, -1); + private static boolean compute = true; + private static boolean suppress = false; + private static String scale = "1.0"; + private static String lower = ""; + private static String higher = ""; + private Checkbox computeBox; + private Checkbox suppressBox; + + public void run(String arg) { + + if (!FJ.libCheck()) return; + final ImagePlus imp = FJ.imageplus(); + if (imp == null) return; + + FJ.log(FJ.name() + " " + FJ.version() + ": Edges"); + + GenericDialog gd = new GenericDialog(FJ.name() + ": Edges"); + gd.addCheckbox(" Compute gradient-magnitude image ", compute); + gd.addStringField(" Smoothing scale:", scale); + gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); + gd.addCheckbox(" Suppress non-maximum gradients ", suppress); + gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); + gd.addStringField(" Lower threshold value:", lower); + gd.addStringField(" Higher threshold value:", higher); + computeBox = (Checkbox) gd.getCheckboxes().get(0); + computeBox.addItemListener(this); + suppressBox = (Checkbox) gd.getCheckboxes().get(1); + suppressBox.addItemListener(this); + + if (pos.x >= 0 && pos.y >= 0) { + gd.centerDialog(false); + gd.setLocation(pos); + } else { + gd.centerDialog(true); + } + gd.addWindowListener(this); + gd.showDialog(); + + if (gd.wasCanceled()) return; + + compute = gd.getNextBoolean(); + scale = gd.getNextString(); + suppress = gd.getNextBoolean(); + lower = gd.getNextString(); + higher = gd.getNextString(); + + (new FJEdges()).run(imp, compute, scale, suppress, lower, higher); + } + + + public void itemStateChanged(final ItemEvent e) { + + if (e.getSource() == computeBox) { + if (!computeBox.getState()) suppressBox.setState(false); + } else if (e.getSource() == suppressBox) { + if (suppressBox.getState()) computeBox.setState(true); + } + } + + + public void windowActivated(final WindowEvent e) { + } + + + public void windowClosed(final WindowEvent e) { + + pos.x = e.getWindow().getX(); + pos.y = e.getWindow().getY(); + } + + + public void windowClosing(final WindowEvent e) { + } + + + public void windowDeactivated(final WindowEvent e) { + } + + + public void windowDeiconified(final WindowEvent e) { + } + + + public void windowIconified(final WindowEvent e) { + } + + + public void windowOpened(final WindowEvent e) { + } +} + +class FJEdges { + + void run( + final ImagePlus imp, + final boolean compute, + final String scale, + final boolean suppress, + final String lower, + final String higher + ) { + + try { + double scaleVal; + double lowVal = 0; + double highVal = 0; + boolean lowThreshold = true; + boolean highThreshold = true; + try { + scaleVal = Double.parseDouble(scale); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid smoothing scale value"); + } + try { + if (lower.equals("")) { + lowThreshold = false; + } else { + lowVal = Double.parseDouble(lower); + } + } catch (Exception e) { + throw new IllegalArgumentException("Invalid lower threshold value"); + } + try { + if (higher.equals("")) { + highThreshold = false; + } else { + highVal = Double.parseDouble(higher); + } + } catch (Exception e) { + throw new IllegalArgumentException("Invalid higher threshold value"); + } + final int thresholdMode = (lowThreshold ? 10 : 0) + (highThreshold ? 1 : 0); + + final Image img = Image.wrap(imp); + Image newImg = new FloatImage(img); + + double[] pls = {0, 1}; + int pl = 0; + if ((compute || suppress) && thresholdMode > 0) { + pls = new double[]{0, 0.9, 1}; + } + final Progressor progressor = new Progressor(); + progressor.display(FJ_Options.pgs); + + if (compute || suppress) { + final Aspects aspects = newImg.aspects(); + if (!FJ_Options.isotropic) newImg.aspects(new Aspects()); + final Edges edges = new Edges(); + progressor.range(pls[pl], pls[++pl]); + edges.progressor.parent(progressor); + edges.messenger.log(FJ_Options.log); + edges.messenger.status(FJ_Options.pgs); + newImg = edges.run(newImg, scaleVal, suppress); + newImg.aspects(aspects); + } + + if (thresholdMode > 0) { + final Thresholder thresholder = new Thresholder(); + progressor.range(pls[pl], pls[++pl]); + thresholder.progressor.parent(progressor); + thresholder.messenger.log(FJ_Options.log); + thresholder.messenger.status(FJ_Options.pgs); + switch (thresholdMode) { + case 1: { + thresholder.hard(newImg, highVal); + break; + } + case 10: { + thresholder.hard(newImg, lowVal); + break; + } + case 11: { + thresholder.hysteresis(newImg, lowVal, highVal); + break; + } + } + } + + FJ.show(newImg, imp); + FJ.close(imp); + + } catch (OutOfMemoryError e) { + FJ.error("Not enough memory for this operation"); + + } catch (IllegalArgumentException | IllegalStateException e) { + FJ.error(e.getMessage()); + + } catch (Throwable e) { + FJ.error("An unidentified error occurred while running the plugin"); + + } + } +} diff --git a/src/main/java/gred/nucleus/myGradient/FJ_Hessian.java b/src/main/java/gred/nucleus/myGradient/FJ_Hessian.java index 9a5cc246..66e23b06 100644 --- a/src/main/java/gred/nucleus/myGradient/FJ_Hessian.java +++ b/src/main/java/gred/nucleus/myGradient/FJ_Hessian.java @@ -1,146 +1,151 @@ -package gred.nucleus.myGradient; - -import ij.ImagePlus; -import ij.gui.GenericDialog; -import ij.plugin.PlugIn; -import imagescience.feature.Hessian; -import imagescience.image.Aspects; -import imagescience.image.FloatImage; -import imagescience.image.Image; - -import java.awt.*; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.Vector; - -public class FJ_Hessian implements PlugIn, WindowListener { - - private static boolean largest = true; - private static boolean middle = false; - private static boolean smallest = true; - - private static boolean absolute = true; - - private static String scale = "1.0"; - private static Point pos = new Point(-1, -1); - @SuppressWarnings("unused") - private ImagePlus imp = null; - - public void run(String arg) { - - if (!FJ.libcheck()) return; - final ImagePlus imp = FJ.imageplus(); - if (imp == null) return; - - FJ.log(FJ.name() + " " + FJ.version() + ": Hessian"); - - GenericDialog gd = new GenericDialog(FJ.name() + ": Hessian"); - gd.addCheckbox(" Largest eigenvalue of Hessian tensor ", largest); - gd.addCheckbox(" Middle eigenvalue of Hessian tensor ", middle); - gd.addCheckbox(" Smallest eigenvalue of Hessian tensor ", smallest); - gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(5, 0, 0, 0)); - gd.addCheckbox(" Absolute eigenvalue comparison ", absolute); - gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(5, 0, 0, 0)); - gd.addStringField(" Smoothing scale:", scale); - - if (pos.x >= 0 && pos.y >= 0) { - gd.centerDialog(false); - gd.setLocation(pos); - } else { - gd.centerDialog(true); - } - gd.addWindowListener(this); - gd.showDialog(); - - if (gd.wasCanceled()) return; - - largest = gd.getNextBoolean(); - middle = gd.getNextBoolean(); - smallest = gd.getNextBoolean(); - absolute = gd.getNextBoolean(); - scale = gd.getNextString(); - - (new FJHessian()).run(imp, largest, middle, smallest, absolute, scale); - } - - public void windowActivated(final WindowEvent e) { - } - - public void windowClosed(final WindowEvent e) { - - pos.x = e.getWindow().getX(); - pos.y = e.getWindow().getY(); - } - - public void windowClosing(final WindowEvent e) { - } - - public void windowDeactivated(final WindowEvent e) { - } - - public void windowDeiconified(final WindowEvent e) { - } - - public void windowIconified(final WindowEvent e) { - } - - public void windowOpened(final WindowEvent e) { - } - -} - -class FJHessian { - - void run( - final ImagePlus imp, - final boolean largest, - final boolean middle, - final boolean smallest, - final boolean absolute, - final String scale - ) { - - try { - double scaleval; - try { - scaleval = Double.parseDouble(scale); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid smoothing scale value"); - } - - final Image img = Image.wrap(imp); - final Aspects aspects = img.aspects(); - if (!FJ_Options.isotropic) img.aspects(new Aspects()); - final Hessian hess = new Hessian(); - hess.messenger.log(FJ_Options.log); - hess.messenger.status(FJ_Options.pgs); - hess.progressor.display(FJ_Options.pgs); - - final Vector eigenimages = hess.run(new FloatImage(img), scaleval, absolute); - - final int nrimgs = eigenimages.size(); - for (Image eigenimage : eigenimages) eigenimage.aspects(aspects); - if (nrimgs == 2) { - if (largest) FJ.show(eigenimages.get(0), imp); - if (smallest) FJ.show(eigenimages.get(1), imp); - } else if (nrimgs == 3) { - if (largest) FJ.show(eigenimages.get(0), imp); - if (middle) FJ.show(eigenimages.get(1), imp); - if (smallest) FJ.show(eigenimages.get(2), imp); - } - - FJ.close(imp); - - } catch (OutOfMemoryError e) { - FJ.error("Not enough memory for this operation"); - - } catch (IllegalArgumentException | IllegalStateException e) { - FJ.error(e.getMessage()); - - } catch (Throwable e) { - FJ.error("An unidentified error occurred while running the plugin"); - - } - } - -} +package gred.nucleus.myGradient; + +import ij.ImagePlus; +import ij.gui.GenericDialog; +import ij.plugin.PlugIn; +import imagescience.feature.Hessian; +import imagescience.image.Aspects; +import imagescience.image.FloatImage; +import imagescience.image.Image; + +import java.awt.*; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.util.Vector; + +public class FJ_Hessian implements PlugIn, WindowListener { + + private static boolean largest = true; + private static boolean middle = false; + private static boolean smallest = true; + + private static boolean absolute = true; + + private static String scale = "1.0"; + private static Point pos = new Point(-1, -1); + @SuppressWarnings("unused") + private ImagePlus imp = null; + + public void run(String arg) { + + if (!FJ.libCheck()) return; + final ImagePlus imp = FJ.imageplus(); + if (imp == null) return; + + FJ.log(FJ.name() + " " + FJ.version() + ": Hessian"); + + GenericDialog gd = new GenericDialog(FJ.name() + ": Hessian"); + gd.addCheckbox(" Largest eigenvalue of Hessian tensor ", largest); + gd.addCheckbox(" Middle eigenvalue of Hessian tensor ", middle); + gd.addCheckbox(" Smallest eigenvalue of Hessian tensor ", smallest); + gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(5, 0, 0, 0)); + gd.addCheckbox(" Absolute eigenvalue comparison ", absolute); + gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(5, 0, 0, 0)); + gd.addStringField(" Smoothing scale:", scale); + + if (pos.x >= 0 && pos.y >= 0) { + gd.centerDialog(false); + gd.setLocation(pos); + } else { + gd.centerDialog(true); + } + gd.addWindowListener(this); + gd.showDialog(); + + if (gd.wasCanceled()) return; + + largest = gd.getNextBoolean(); + middle = gd.getNextBoolean(); + smallest = gd.getNextBoolean(); + absolute = gd.getNextBoolean(); + scale = gd.getNextString(); + + (new FJHessian()).run(imp, largest, middle, smallest, absolute, scale); + } + + + public void windowActivated(final WindowEvent e) { + } + + + public void windowClosed(final WindowEvent e) { + + pos.x = e.getWindow().getX(); + pos.y = e.getWindow().getY(); + } + + + public void windowClosing(final WindowEvent e) { + } + + + public void windowDeactivated(final WindowEvent e) { + } + + + public void windowDeiconified(final WindowEvent e) { + } + + + public void windowIconified(final WindowEvent e) { + } + + + public void windowOpened(final WindowEvent e) { + } +} + +class FJHessian { + + void run( + final ImagePlus imp, + final boolean largest, + final boolean middle, + final boolean smallest, + final boolean absolute, + final String scale + ) { + + try { + double scaleVal; + try { + scaleVal = Double.parseDouble(scale); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid smoothing scale value"); + } + + final Image img = Image.wrap(imp); + final Aspects aspects = img.aspects(); + if (!FJ_Options.isotropic) img.aspects(new Aspects()); + final Hessian hess = new Hessian(); + hess.messenger.log(FJ_Options.log); + hess.messenger.status(FJ_Options.pgs); + hess.progressor.display(FJ_Options.pgs); + + final Vector eigenImages = hess.run(new FloatImage(img), scaleVal, absolute); + + final int nImages = eigenImages.size(); + for (Image eigenImage : eigenImages) eigenImage.aspects(aspects); + if (nImages == 2) { + if (largest) FJ.show(eigenImages.get(0), imp); + if (smallest) FJ.show(eigenImages.get(1), imp); + } else if (nImages == 3) { + if (largest) FJ.show(eigenImages.get(0), imp); + if (middle) FJ.show(eigenImages.get(1), imp); + if (smallest) FJ.show(eigenImages.get(2), imp); + } + + FJ.close(imp); + + } catch (OutOfMemoryError e) { + FJ.error("Not enough memory for this operation"); + + } catch (IllegalArgumentException | IllegalStateException e) { + FJ.error(e.getMessage()); + + } catch (Throwable e) { + FJ.error("An unidentified error occurred while running the plugin"); + + } + } +} diff --git a/src/main/java/gred/nucleus/myGradient/FJ_Laplacian.java b/src/main/java/gred/nucleus/myGradient/FJ_Laplacian.java index b8cbfefa..723307b8 100644 --- a/src/main/java/gred/nucleus/myGradient/FJ_Laplacian.java +++ b/src/main/java/gred/nucleus/myGradient/FJ_Laplacian.java @@ -1,149 +1,154 @@ -package gred.nucleus.myGradient; - -import ij.ImagePlus; -import ij.gui.GenericDialog; -import ij.plugin.PlugIn; -import imagescience.feature.Laplacian; -import imagescience.image.Aspects; -import imagescience.image.FloatImage; -import imagescience.image.Image; -import imagescience.segment.ZeroCrosser; -import imagescience.utility.Progressor; - -import java.awt.*; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; - -public class FJ_Laplacian implements PlugIn, WindowListener { - - private static boolean compute = true; - private static boolean zerocross = false; - - private static String scale = "1.0"; - - private static Point pos = new Point(-1, -1); - - public void run(String arg) { - - if (!FJ.libcheck()) return; - final ImagePlus imp = FJ.imageplus(); - if (imp == null) return; - - FJ.log(FJ.name() + " " + FJ.version() + ": Laplacian"); - - GenericDialog gd = new GenericDialog(FJ.name() + ": Laplacian"); - gd.addCheckbox(" Compute Laplacian image ", compute); - gd.addStringField(" Smoothing scale:", scale); - gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(1, 0, 0, 0)); - gd.addCheckbox(" Detect zero-crossings ", zerocross); - gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); - - if (pos.x >= 0 && pos.y >= 0) { - gd.centerDialog(false); - gd.setLocation(pos); - } else { - gd.centerDialog(true); - } - gd.addWindowListener(this); - gd.showDialog(); - - if (gd.wasCanceled()) return; - - compute = gd.getNextBoolean(); - scale = gd.getNextString(); - zerocross = gd.getNextBoolean(); - - (new FJLaplacian()).run(imp, compute, scale, zerocross); - } - - public void windowActivated(final WindowEvent e) { - } - - public void windowClosed(final WindowEvent e) { - - pos.x = e.getWindow().getX(); - pos.y = e.getWindow().getY(); - } - - public void windowClosing(final WindowEvent e) { - } - - public void windowDeactivated(final WindowEvent e) { - } - - public void windowDeiconified(final WindowEvent e) { - } - - public void windowIconified(final WindowEvent e) { - } - - public void windowOpened(final WindowEvent e) { - } - -} - -class FJLaplacian { - - void run( - final ImagePlus imp, - final boolean compute, - final String scale, - final boolean zerocross - ) { - - try { - double scaleval; - try { - scaleval = Double.parseDouble(scale); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid smoothing scale value"); - } - - final Image img = Image.wrap(imp); - Image newimg = new FloatImage(img); - - double[] pls = {0, 1}; - int pl = 0; - if (compute && zerocross) { - pls = new double[]{0, 0.95, 1}; - } - final Progressor progressor = new Progressor(); - progressor.display(FJ_Options.pgs); - - if (compute) { - final Aspects aspects = newimg.aspects(); - if (!FJ_Options.isotropic) newimg.aspects(new Aspects()); - final Laplacian laplace = new Laplacian(); - progressor.range(pls[pl], pls[++pl]); - laplace.progressor.parent(progressor); - laplace.messenger.log(FJ_Options.log); - laplace.messenger.status(FJ_Options.pgs); - newimg = laplace.run(newimg, scaleval); - newimg.aspects(aspects); - } - - if (zerocross) { - final ZeroCrosser zc = new ZeroCrosser(); - progressor.range(pls[pl], pls[++pl]); - zc.progressor.parent(progressor); - zc.messenger.log(FJ_Options.log); - zc.messenger.status(FJ_Options.pgs); - zc.run(newimg); - } - - FJ.show(newimg, imp); - FJ.close(imp); - - } catch (OutOfMemoryError e) { - FJ.error("Not enough memory for this operation"); - - } catch (IllegalArgumentException | IllegalStateException e) { - FJ.error(e.getMessage()); - - } catch (Throwable e) { - FJ.error("An unidentified error occurred while running the plugin"); - - } - } - -} +package gred.nucleus.myGradient; + +import ij.ImagePlus; +import ij.gui.GenericDialog; +import ij.plugin.PlugIn; +import imagescience.feature.Laplacian; +import imagescience.image.Aspects; +import imagescience.image.FloatImage; +import imagescience.image.Image; +import imagescience.segment.ZeroCrosser; +import imagescience.utility.Progressor; + +import java.awt.*; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +public class FJ_Laplacian implements PlugIn, WindowListener { + + private static boolean compute = true; + private static boolean zeroCross = false; + + private static String scale = "1.0"; + + private static Point pos = new Point(-1, -1); + + public void run(String arg) { + + if (!FJ.libCheck()) return; + final ImagePlus imp = FJ.imageplus(); + if (imp == null) return; + + FJ.log(FJ.name() + " " + FJ.version() + ": Laplacian"); + + GenericDialog gd = new GenericDialog(FJ.name() + ": Laplacian"); + gd.addCheckbox(" Compute Laplacian image ", compute); + gd.addStringField(" Smoothing scale:", scale); + gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(1, 0, 0, 0)); + gd.addCheckbox(" Detect zero-crossings ", zeroCross); + gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); + + if (pos.x >= 0 && pos.y >= 0) { + gd.centerDialog(false); + gd.setLocation(pos); + } else { + gd.centerDialog(true); + } + gd.addWindowListener(this); + gd.showDialog(); + + if (gd.wasCanceled()) return; + + compute = gd.getNextBoolean(); + scale = gd.getNextString(); + zeroCross = gd.getNextBoolean(); + + (new FJLaplacian()).run(imp, compute, scale, zeroCross); + } + + + public void windowActivated(final WindowEvent e) { + } + + + public void windowClosed(final WindowEvent e) { + + pos.x = e.getWindow().getX(); + pos.y = e.getWindow().getY(); + } + + + public void windowClosing(final WindowEvent e) { + } + + + public void windowDeactivated(final WindowEvent e) { + } + + + public void windowDeiconified(final WindowEvent e) { + } + + + public void windowIconified(final WindowEvent e) { + } + + + public void windowOpened(final WindowEvent e) { + } +} + +class FJLaplacian { + + void run( + final ImagePlus imp, + final boolean compute, + final String scale, + final boolean zeroCross + ) { + + try { + double scaleVal; + try { + scaleVal = Double.parseDouble(scale); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid smoothing scale value"); + } + + final Image img = Image.wrap(imp); + Image newImg = new FloatImage(img); + + double[] pls = {0, 1}; + int pl = 0; + if (compute && zeroCross) { + pls = new double[]{0, 0.95, 1}; + } + final Progressor progressor = new Progressor(); + progressor.display(FJ_Options.pgs); + + if (compute) { + final Aspects aspects = newImg.aspects(); + if (!FJ_Options.isotropic) newImg.aspects(new Aspects()); + final Laplacian laplace = new Laplacian(); + progressor.range(pls[pl], pls[++pl]); + laplace.progressor.parent(progressor); + laplace.messenger.log(FJ_Options.log); + laplace.messenger.status(FJ_Options.pgs); + newImg = laplace.run(newImg, scaleVal); + newImg.aspects(aspects); + } + + if (zeroCross) { + final ZeroCrosser zc = new ZeroCrosser(); + progressor.range(pls[pl], pls[++pl]); + zc.progressor.parent(progressor); + zc.messenger.log(FJ_Options.log); + zc.messenger.status(FJ_Options.pgs); + zc.run(newImg); + } + + FJ.show(newImg, imp); + FJ.close(imp); + + } catch (OutOfMemoryError e) { + FJ.error("Not enough memory for this operation"); + + } catch (IllegalArgumentException | IllegalStateException e) { + FJ.error(e.getMessage()); + + } catch (Throwable e) { + FJ.error("An unidentified error occurred while running the plugin"); + + } + } +} diff --git a/src/main/java/gred/nucleus/myGradient/FJ_Options.java b/src/main/java/gred/nucleus/myGradient/FJ_Options.java index e273fd5f..e3f68fd5 100644 --- a/src/main/java/gred/nucleus/myGradient/FJ_Options.java +++ b/src/main/java/gred/nucleus/myGradient/FJ_Options.java @@ -1,114 +1,120 @@ -package gred.nucleus.myGradient; - -import ij.Prefs; -import ij.gui.GenericDialog; -import ij.plugin.PlugIn; - -import java.awt.*; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; - -public class FJ_Options implements PlugIn, WindowListener { - - static boolean isotropic = Prefs.get("fj.isotropic", false); - static boolean close = Prefs.get("fj.close", false); - static boolean save = Prefs.get("fj.save", false); - static boolean pgs = Prefs.get("fj.pgs", true); - static boolean log = Prefs.get("fj.log", false); - - private static Point pos = new Point(-1, -1); - - public void run(String arg) { - - if (!FJ.libcheck()) return; - - FJ.log(FJ.name() + " " + FJ.version() + ": Options"); - - final String space = " "; - GenericDialog gd = new GenericDialog(FJ.name() + ": Options"); - gd.addCheckbox(" Isotropic Gaussian image smoothing" + space, isotropic); - gd.addCheckbox(" Close input images after processing" + space, close); - gd.addCheckbox(" Save result images before closing" + space, save); - gd.addCheckbox(" Progress indication" + space, pgs); - gd.addCheckbox(" Log messaging" + space, log); - gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); - - if (pos.x >= 0 && pos.y >= 0) { - gd.centerDialog(false); - gd.setLocation(pos); - } else { - gd.centerDialog(true); - } - gd.addWindowListener(this); - gd.showDialog(); - - if (gd.wasCanceled()) return; - - isotropic = gd.getNextBoolean(); - close = gd.getNextBoolean(); - save = gd.getNextBoolean(); - pgs = gd.getNextBoolean(); - log = gd.getNextBoolean(); - - Prefs.set("fj.isotropic", isotropic); - Prefs.set("fj.close", close); - Prefs.set("fj.save", save); - Prefs.set("fj.pgs", pgs); - Prefs.set("fj.log", log); - - if (isotropic) { - FJ.log("Dividing smoothing scales by aspect-ratio values"); - } else { - FJ.log("Assuming pixel units for smoothing scales"); - } - - if (close) { - FJ.log("Closing input images after processing"); - } else { - FJ.log("Keeping input images after processing"); - } - - if (save) { - FJ.log("Asking to save result images before closing"); - } else { - FJ.log("Closing result images without asking to save"); - } - - if (pgs) { - FJ.log("Enabling progress indication"); - } else { - FJ.log("Disabling progress indication"); - } - - if (log) { - FJ.log("Enabling log messaging"); - } else { - FJ.log("Disabling log messaging"); - } - } - - public void windowActivated(final WindowEvent e) { - } - - public void windowClosed(final WindowEvent e) { - - pos.x = e.getWindow().getX(); - pos.y = e.getWindow().getY(); - } - - public void windowClosing(final WindowEvent e) { - } - - public void windowDeactivated(final WindowEvent e) { - } - - public void windowDeiconified(final WindowEvent e) { - } - - public void windowIconified(final WindowEvent e) { - } - - public void windowOpened(final WindowEvent e) { - } - -} +package gred.nucleus.myGradient; + +import ij.Prefs; +import ij.gui.GenericDialog; +import ij.plugin.PlugIn; + +import java.awt.*; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +public class FJ_Options implements PlugIn, WindowListener { + + static boolean isotropic = Prefs.get("fj.isotropic", false); + static boolean close = Prefs.get("fj.close", false); + static boolean save = Prefs.get("fj.save", false); + static boolean pgs = Prefs.get("fj.pgs", true); + static boolean log = Prefs.get("fj.log", false); + + private static Point pos = new Point(-1, -1); + + public void run(String arg) { + + if (!FJ.libCheck()) return; + + FJ.log(FJ.name() + " " + FJ.version() + ": Options"); + + final String space = " "; + GenericDialog gd = new GenericDialog(FJ.name() + ": Options"); + gd.addCheckbox(" Isotropic Gaussian image smoothing" + space, isotropic); + gd.addCheckbox(" Close input images after processing" + space, close); + gd.addCheckbox(" Save result images before closing" + space, save); + gd.addCheckbox(" Progress indication" + space, pgs); + gd.addCheckbox(" Log messaging" + space, log); + gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); + + if (pos.x >= 0 && pos.y >= 0) { + gd.centerDialog(false); + gd.setLocation(pos); + } else { + gd.centerDialog(true); + } + gd.addWindowListener(this); + gd.showDialog(); + + if (gd.wasCanceled()) return; + + isotropic = gd.getNextBoolean(); + close = gd.getNextBoolean(); + save = gd.getNextBoolean(); + pgs = gd.getNextBoolean(); + log = gd.getNextBoolean(); + + Prefs.set("fj.isotropic", isotropic); + Prefs.set("fj.close", close); + Prefs.set("fj.save", save); + Prefs.set("fj.pgs", pgs); + Prefs.set("fj.log", log); + + if (isotropic) { + FJ.log("Dividing smoothing scales by aspect-ratio values"); + } else { + FJ.log("Assuming pixel units for smoothing scales"); + } + + if (close) { + FJ.log("Closing input images after processing"); + } else { + FJ.log("Keeping input images after processing"); + } + + if (save) { + FJ.log("Asking to save result images before closing"); + } else { + FJ.log("Closing result images without asking to save"); + } + + if (pgs) { + FJ.log("Enabling progress indication"); + } else { + FJ.log("Disabling progress indication"); + } + + if (log) { + FJ.log("Enabling log messaging"); + } else { + FJ.log("Disabling log messaging"); + } + } + + + public void windowActivated(final WindowEvent e) { + } + + + public void windowClosed(final WindowEvent e) { + + pos.x = e.getWindow().getX(); + pos.y = e.getWindow().getY(); + } + + + public void windowClosing(final WindowEvent e) { + } + + + public void windowDeactivated(final WindowEvent e) { + } + + + public void windowDeiconified(final WindowEvent e) { + } + + + public void windowIconified(final WindowEvent e) { + } + + + public void windowOpened(final WindowEvent e) { + } +} diff --git a/src/main/java/gred/nucleus/myGradient/FJ_Panel.java b/src/main/java/gred/nucleus/myGradient/FJ_Panel.java index 39d41b64..04138082 100644 --- a/src/main/java/gred/nucleus/myGradient/FJ_Panel.java +++ b/src/main/java/gred/nucleus/myGradient/FJ_Panel.java @@ -1,115 +1,123 @@ -package gred.nucleus.myGradient; - -import ij.IJ; -import ij.gui.GUI; -import ij.plugin.PlugIn; - -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; - -public class FJ_Panel implements PlugIn, ActionListener, WindowListener { - - private static Point pos = new Point(-1, -1); - Panel panel; - private Dialog dialog; - private Button derivatives, edges, hessian; - private Button laplacian, statistics, structure; - private Button about, options, website; - - public void run(String arg) { - - if (!FJ.libcheck()) return; - - FJ.log(FJ.name() + " " + FJ.version() + ": Panel"); - - final Frame parent = (IJ.getInstance() != null) ? IJ.getInstance() : new Frame(); - dialog = new Dialog(parent, FJ.name(), false); - dialog.setLayout(new FlowLayout()); - dialog.addWindowListener(this); - - panel = new Panel(); - panel.setLayout(new GridLayout(3, 3, 5, 5)); - - derivatives = addButton("Derivatives"); - edges = addButton("Edges"); - hessian = addButton("Hessian"); - - laplacian = addButton("Laplacian"); - statistics = addButton("Statistics"); - structure = addButton("Structure"); - - about = addButton("About"); - options = addButton("Options"); - website = addButton("Website"); - - dialog.add(panel); - dialog.pack(); - if (pos.x < 0 || pos.y < 0) { - GUI.center(dialog); - } else { - dialog.setLocation(pos); - } - dialog.setVisible(true); - } - - private Button addButton(String label) { - - final Button b = new Button(" " + label + " "); - b.addActionListener(this); - panel.add(b); - return b; - } - - public void actionPerformed(ActionEvent e) { - - final Object source = e.getSource(); - if (source == derivatives) { - IJ.doCommand("FeatureJ Derivatives"); - } else if (source == edges) { - IJ.doCommand("FeatureJ Edges"); - } else if (source == hessian) { - IJ.doCommand("FeatureJ Hessian"); - } else if (source == laplacian) { - IJ.doCommand("FeatureJ Laplacian"); - } else if (source == statistics) { - IJ.doCommand("FeatureJ Statistics"); - } else if (source == structure) { - IJ.doCommand("FeatureJ Structure"); - } else if (source == about) { - (new FJ_About()).run(""); - } else if (source == options) { - IJ.doCommand("FeatureJ Options"); - } else if (source == website) (new FJ_Website()).run(""); - } - - public void windowActivated(final WindowEvent e) { - } - - public void windowClosed(final WindowEvent e) { - - pos.x = e.getWindow().getX(); - pos.y = e.getWindow().getY(); - } - - public void windowClosing(final WindowEvent e) { - - dialog.setVisible(false); - dialog.dispose(); - } - - public void windowDeactivated(final WindowEvent e) { - } - - public void windowDeiconified(final WindowEvent e) { - } - - public void windowIconified(final WindowEvent e) { - } - - public void windowOpened(final WindowEvent e) { - } - -} +package gred.nucleus.myGradient; + +import ij.IJ; +import ij.gui.GUI; +import ij.plugin.PlugIn; + +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +public class FJ_Panel implements PlugIn, ActionListener, WindowListener { + + private static Point pos = new Point(-1, -1); + Panel panel; + private Dialog dialog; + private Button derivatives, edges, hessian; + private Button laplacian, statistics, structure; + private Button about, options, website; + + public void run(String arg) { + + if (!FJ.libCheck()) return; + + FJ.log(FJ.name() + " " + FJ.version() + ": Panel"); + + final Frame parent = (IJ.getInstance() != null) ? IJ.getInstance() : new Frame(); + dialog = new Dialog(parent, FJ.name(), false); + dialog.setLayout(new FlowLayout()); + dialog.addWindowListener(this); + + panel = new Panel(); + panel.setLayout(new GridLayout(3, 3, 5, 5)); + + derivatives = addButton("Derivatives"); + edges = addButton("Edges"); + hessian = addButton("Hessian"); + + laplacian = addButton("Laplacian"); + statistics = addButton("Statistics"); + structure = addButton("Structure"); + + about = addButton("About"); + options = addButton("Options"); + website = addButton("Website"); + + dialog.add(panel); + dialog.pack(); + if (pos.x < 0 || pos.y < 0) { + GUI.center(dialog); + } else { + dialog.setLocation(pos); + } + dialog.setVisible(true); + } + + + private Button addButton(String label) { + + final Button b = new Button(" " + label + " "); + b.addActionListener(this); + panel.add(b); + return b; + } + + + public void actionPerformed(ActionEvent e) { + + final Object source = e.getSource(); + if (source == derivatives) { + IJ.doCommand("FeatureJ Derivatives"); + } else if (source == edges) { + IJ.doCommand("FeatureJ Edges"); + } else if (source == hessian) { + IJ.doCommand("FeatureJ Hessian"); + } else if (source == laplacian) { + IJ.doCommand("FeatureJ Laplacian"); + } else if (source == statistics) { + IJ.doCommand("FeatureJ Statistics"); + } else if (source == structure) { + IJ.doCommand("FeatureJ Structure"); + } else if (source == about) { + (new FJ_About()).run(""); + } else if (source == options) { + IJ.doCommand("FeatureJ Options"); + } else if (source == website) (new FJ_Website()).run(""); + } + + + public void windowActivated(final WindowEvent e) { + } + + + public void windowClosed(final WindowEvent e) { + + pos.x = e.getWindow().getX(); + pos.y = e.getWindow().getY(); + } + + + public void windowClosing(final WindowEvent e) { + + dialog.setVisible(false); + dialog.dispose(); + } + + + public void windowDeactivated(final WindowEvent e) { + } + + + public void windowDeiconified(final WindowEvent e) { + } + + + public void windowIconified(final WindowEvent e) { + } + + + public void windowOpened(final WindowEvent e) { + } +} diff --git a/src/main/java/gred/nucleus/myGradient/FJ_Statistics.java b/src/main/java/gred/nucleus/myGradient/FJ_Statistics.java index aef70db0..60b647a3 100644 --- a/src/main/java/gred/nucleus/myGradient/FJ_Statistics.java +++ b/src/main/java/gred/nucleus/myGradient/FJ_Statistics.java @@ -1,387 +1,395 @@ -package gred.nucleus.myGradient; - -import ij.IJ; -import ij.ImagePlus; -import ij.gui.GenericDialog; -import ij.gui.Roi; -import ij.plugin.PlugIn; -import ij.process.ByteProcessor; -import ij.process.ImageProcessor; -import ij.text.TextPanel; -import imagescience.feature.Statistics; -import imagescience.image.Coordinates; -import imagescience.image.Dimensions; -import imagescience.image.Image; -import imagescience.utility.Formatter; -import imagescience.utility.Messenger; -import imagescience.utility.Progressor; - -import java.awt.*; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.Vector; - -public class FJ_Statistics implements PlugIn, ItemListener, WindowListener { - - private static final String[] labels = { - " Minimum", - " Maximum", - " Mean", - " Median", - " Elements", - " Mass", - " Variance", - " Mode", - " S-Deviation", - " A-Deviation", - " L1-Norm", - " L2-Norm", - " Skewness", - " Kurtosis" - }; - - private static final boolean[] values = { - true, - true, - true, - false, - true, - false, - false, - false, - true, - false, - false, - false, - false, - false - }; - - private static boolean clear = false; - private static boolean name = true; - private static boolean channel = false; - private static boolean time = false; - private static boolean slice = false; - - private static int decimals = 3; - private static Point pos = new Point(-1, -1); - private Checkbox channelbox, timebox, slicebox; - - @SuppressWarnings("rawtypes") - public void run(String arg) { - - if (!FJ.libcheck()) return; - final ImagePlus imp = FJ.imageplus(); - if (imp == null) return; - - FJ.log(FJ.name() + " " + FJ.version() + ": Statistics"); - - GenericDialog gd = new GenericDialog(FJ.name() + ": Statistics"); - gd.addCheckboxGroup(7, 2, labels, values); - gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(5, 0, 0, 0)); - gd.addCheckbox(" Clear previous results", clear); - gd.addCheckbox(" Image name displaying", name); - gd.addCheckbox(" Channel numbering", channel); - gd.addCheckbox(" Time frame numbering", time); - gd.addCheckbox(" Slice numbering", slice); - final Vector checkboxes = gd.getCheckboxes(); - final int veclen = checkboxes.size(); - slicebox = (Checkbox) checkboxes.get(veclen - 1); - slicebox.addItemListener(this); - timebox = (Checkbox) checkboxes.get(veclen - 2); - timebox.addItemListener(this); - channelbox = (Checkbox) checkboxes.get(veclen - 3); - channelbox.addItemListener(this); - gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); - final String[] decslist = new String[11]; - for (int i = 0; i < 11; ++i) decslist[i] = String.valueOf(i); - gd.addChoice(" Decimal places:", decslist, String.valueOf(decimals)); - - if (pos.x >= 0 && pos.y >= 0) { - gd.centerDialog(false); - gd.setLocation(pos); - } else { - gd.centerDialog(true); - } - gd.addWindowListener(this); - gd.showDialog(); - - if (gd.wasCanceled()) return; - - for (int i = 0; i < values.length; ++i) values[i] = gd.getNextBoolean(); - clear = gd.getNextBoolean(); - name = gd.getNextBoolean(); - channel = gd.getNextBoolean(); - time = gd.getNextBoolean(); - slice = gd.getNextBoolean(); - decimals = gd.getNextChoiceIndex(); - - (new FJStatistics()).run(imp, values, clear, name, channel, time, slice, decimals); - } - - public void itemStateChanged(final ItemEvent e) { - if (e.getSource() == slicebox) { - if (slicebox.getState()) { - timebox.setState(true); - channelbox.setState(true); - } - } else if (e.getSource() == timebox) { - if (timebox.getState()) { - channelbox.setState(true); - } else { - slicebox.setState(false); - } - } else if (e.getSource() == channelbox) { - if (!channelbox.getState()) { - timebox.setState(false); - slicebox.setState(false); - } - } - } - - public void windowActivated(final WindowEvent e) { - } - - public void windowClosed(final WindowEvent e) { - pos.x = e.getWindow().getX(); - pos.y = e.getWindow().getY(); - } - - public void windowClosing(final WindowEvent e) { - } - - public void windowDeactivated(final WindowEvent e) { - } - - public void windowDeiconified(final WindowEvent e) { - } - - public void windowIconified(final WindowEvent e) { - } - - public void windowOpened(final WindowEvent e) { - } - -} - -class FJStatistics { - private static int number = 0; - private final Statistics stats = new Statistics(); - - private final Formatter fmt = new Formatter(); - - private boolean[] values = null; - @SuppressWarnings("unused") - private boolean clear = false; - private boolean name = true; - private boolean channel = false; - private boolean time = false; - - private boolean slice = false; - @SuppressWarnings("unused") - private int decimals = 3; - - void run( - final ImagePlus imp, - final boolean[] values, - final boolean clear, - final boolean name, - final boolean channel, - final boolean time, - final boolean slice, - final int decimals - ) { - - this.values = new boolean[values.length]; - System.arraycopy(values, 0, this.values, 0, values.length); - this.clear = clear; - this.name = name; - this.channel = channel; - this.time = time; - this.slice = slice; - this.decimals = decimals; - - try { - // Initialize: - if (decimals < 0 || decimals > 10) { - throw new IllegalArgumentException("Invalid number of decimals"); - } else { - fmt.decs(decimals); - fmt.chop(0); - } - - // Determine region of interest: - final Image img = Image.wrap(imp); - final Dimensions dims = img.dimensions(); - final Coordinates cmin = new Coordinates(); - final Coordinates cmax = new Coordinates(); - Roi roi = imp.getRoi(); - if (roi == null) roi = new Roi(0, 0, dims.x, dims.y); - ImageProcessor maskip = null; - switch (roi.getType()) { - case Roi.COMPOSITE: - case Roi.FREEROI: - case Roi.OVAL: - case Roi.POINT: - case Roi.POLYGON: - case Roi.TRACED_ROI: - maskip = roi.getMask(); - break; - case Roi.RECTANGLE: - maskip = new ByteProcessor(1, 1); - maskip.set(0, 0, 255); - break; - } - if (maskip == null) throw new IllegalArgumentException("Region of interest not supported"); - final ImagePlus maskimp = new ImagePlus("Mask", maskip); // maskimp.show(); - final Image mask = Image.wrap(maskimp); - final Rectangle bounds = roi.getBounds(); - cmin.x = bounds.x; - cmin.y = bounds.y; - cmax.x = bounds.x + bounds.width - 1; - cmax.y = bounds.y + bounds.height - 1; - - // Compute and show statistics: - final String nameprelude = name ? ("\t" + imp.getTitle()) : ""; - final TextPanel textpanel = IJ.getTextPanel(); - final String headings = headings(); - if (clear || !headings.equals(textpanel.getColumnHeadings())) { - textpanel.setColumnHeadings(headings); - number = 0; - } - - final Progressor pgs = new Progressor(); - final Messenger msg = new Messenger(); - pgs.display(FJ_Options.pgs); - msg.status(FJ_Options.pgs); - - if (slice) { - msg.status("Computing statistics per slice / time / channel..."); - pgs.steps(dims.c * dims.t * dims.z); - pgs.start(); - for (cmin.c = cmax.c = 0; cmin.c < dims.c; ++cmin.c, ++cmax.c) { - for (cmin.t = cmax.t = 0; cmin.t < dims.t; ++cmin.t, ++cmax.t) { - for (cmin.z = cmax.z = 0; cmin.z < dims.z; ++cmin.z, ++cmax.z) { - stats.run(img, cmin, cmax, mask); - final String prelude = (++number) + - nameprelude + "\t" + - (cmin.c + 1) + "\t" + - (cmin.t + 1) + "\t" + - (cmin.z + 1); - textpanel.append(prelude + results()); - pgs.step(); - } - } - } - pgs.stop(); - msg.status(""); - - } else if (time) { - msg.status("Computing statistics per time / channel..."); - pgs.steps(dims.c * dims.t); - pgs.start(); - cmax.z = dims.z - 1; - for (cmin.c = cmax.c = 0; cmin.c < dims.c; ++cmin.c, ++cmax.c) { - for (cmin.t = cmax.t = 0; cmin.t < dims.t; ++cmin.t, ++cmax.t) { - stats.run(img, cmin, cmax, mask); - final String prelude = (++number) + nameprelude + "\t" + (cmin.c + 1) + "\t" + (cmin.t + 1); - textpanel.append(prelude + results()); - pgs.step(); - } - } - pgs.stop(); - msg.status(""); - - } else if (channel) { - msg.status("Computing statistics per channel..."); - pgs.steps(dims.c); - pgs.start(); - cmax.z = dims.z - 1; - cmax.t = dims.t - 1; - for (cmin.c = cmax.c = 0; cmin.c < dims.c; ++cmin.c, ++cmax.c) { - stats.run(img, cmin, cmax, mask); - final String prelude = (++number) + nameprelude + "\t" + (cmin.c + 1); - textpanel.append(prelude + results()); - pgs.step(); - } - pgs.stop(); - msg.status(""); - - } else { - cmax.z = dims.z - 1; - cmax.t = dims.t - 1; - cmax.c = dims.c - 1; - stats.messenger.status(FJ_Options.pgs); - stats.progressor.display(FJ_Options.pgs); - stats.run(img, cmin, cmax, mask); - final String prelude = (++number) + nameprelude; - textpanel.append(prelude + results()); - } - - } catch (OutOfMemoryError e) { - FJ.error("Not enough memory for this operation"); - - } catch (IllegalArgumentException e) { - FJ.error(e.getMessage()); - - } catch (Throwable e) { - FJ.error("An unidentified error occurred while running the plugin"); - - } - } - - private String headings() { - - final StringBuilder cols = new StringBuilder(); - - cols.append("Nr"); - if (name) cols.append("\tImage"); - if (slice) { - cols.append("\tChan\tTime\tSlice"); - } else if (time) { - cols.append("\tChan\tTime"); - } else if (channel) cols.append("\tChan"); - if (values[4]) cols.append("\tElements"); - if (values[0]) cols.append("\tMin"); - if (values[1]) cols.append("\tMax"); - if (values[2]) cols.append("\tMean"); - if (values[6]) cols.append("\tVar"); - if (values[8]) cols.append("\tS-Dev"); - if (values[9]) cols.append("\tA-Dev"); - if (values[3]) cols.append("\tMedian"); - if (values[7]) cols.append("\tMode"); - if (values[5]) cols.append("\tMass"); - if (values[10]) cols.append("\tL1"); - if (values[11]) cols.append("\tL2"); - if (values[12]) cols.append("\tSkew"); - if (values[13]) cols.append("\tKurt"); - - return cols.toString(); - } - - @SuppressWarnings("static-access") - private String results() { - - final StringBuilder res = new StringBuilder(); - - if (values[4]) res.append("\t").append(fmt.d2s(stats.get(stats.ELEMENTS))); - if (values[0]) res.append("\t").append(fmt.d2s(stats.get(stats.MINIMUM))); - if (values[1]) res.append("\t").append(fmt.d2s(stats.get(stats.MAXIMUM))); - if (values[2]) res.append("\t").append(fmt.d2s(stats.get(stats.MEAN))); - if (values[6]) res.append("\t").append(fmt.d2s(stats.get(stats.VARIANCE))); - if (values[8]) res.append("\t").append(fmt.d2s(stats.get(stats.SDEVIATION))); - if (values[9]) res.append("\t").append(fmt.d2s(stats.get(stats.ADEVIATION))); - if (values[3]) res.append("\t").append(fmt.d2s(stats.get(stats.MEDIAN))); - if (values[7]) res.append("\t").append(fmt.d2s(stats.get(stats.MODE))); - if (values[5]) res.append("\t").append(fmt.d2s(stats.get(stats.MASS))); - if (values[10]) res.append("\t").append(fmt.d2s(stats.get(stats.L1NORM))); - if (values[11]) res.append("\t").append(fmt.d2s(stats.get(stats.L2NORM))); - if (values[12]) res.append("\t").append(fmt.d2s(stats.get(stats.SKEWNESS))); - if (values[13]) res.append("\t").append(fmt.d2s(stats.get(stats.KURTOSIS))); - - return res.toString(); - } - -} +package gred.nucleus.myGradient; + +import ij.IJ; +import ij.ImagePlus; +import ij.gui.GenericDialog; +import ij.gui.Roi; +import ij.plugin.PlugIn; +import ij.process.ByteProcessor; +import ij.process.ImageProcessor; +import ij.text.TextPanel; +import imagescience.feature.Statistics; +import imagescience.image.Coordinates; +import imagescience.image.Dimensions; +import imagescience.image.Image; +import imagescience.utility.Formatter; +import imagescience.utility.Messenger; +import imagescience.utility.Progressor; + +import java.awt.*; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.util.Vector; + +public class FJ_Statistics implements PlugIn, ItemListener, WindowListener { + + private static final String[] labels = { + " Minimum", + " Maximum", + " Mean", + " Median", + " Elements", + " Mass", + " Variance", + " Mode", + " S-Deviation", + " A-Deviation", + " L1-Norm", + " L2-Norm", + " Skewness", + " Kurtosis" + }; + + private static final boolean[] values = { + true, + true, + true, + false, + true, + false, + false, + false, + true, + false, + false, + false, + false, + false + }; + + private static boolean clear = false; + private static boolean name = true; + private static boolean channel = false; + private static boolean time = false; + private static boolean slice = false; + + private static int decimals = 3; + private static Point pos = new Point(-1, -1); + private Checkbox channelBox; + private Checkbox timeBox; + private Checkbox sliceBox; + + @SuppressWarnings("rawtypes") + public void run(String arg) { + + if (!FJ.libCheck()) return; + final ImagePlus imp = FJ.imageplus(); + if (imp == null) return; + + FJ.log(FJ.name() + " " + FJ.version() + ": Statistics"); + + GenericDialog gd = new GenericDialog(FJ.name() + ": Statistics"); + gd.addCheckboxGroup(7, 2, labels, values); + gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(5, 0, 0, 0)); + gd.addCheckbox(" Clear previous results", clear); + gd.addCheckbox(" Image name displaying", name); + gd.addCheckbox(" Channel numbering", channel); + gd.addCheckbox(" Time frame numbering", time); + gd.addCheckbox(" Slice numbering", slice); + final Vector checkboxes = gd.getCheckboxes(); + final int vecLen = checkboxes.size(); + sliceBox = (Checkbox) checkboxes.get(vecLen - 1); + sliceBox.addItemListener(this); + timeBox = (Checkbox) checkboxes.get(vecLen - 2); + timeBox.addItemListener(this); + channelBox = (Checkbox) checkboxes.get(vecLen - 3); + channelBox.addItemListener(this); + gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(0, 0, 0, 0)); + final String[] decsList = new String[11]; + for (int i = 0; i < 11; ++i) decsList[i] = String.valueOf(i); + gd.addChoice(" Decimal places:", decsList, String.valueOf(decimals)); + + if (pos.x >= 0 && pos.y >= 0) { + gd.centerDialog(false); + gd.setLocation(pos); + } else { + gd.centerDialog(true); + } + gd.addWindowListener(this); + gd.showDialog(); + + if (gd.wasCanceled()) return; + + for (int i = 0; i < values.length; ++i) values[i] = gd.getNextBoolean(); + clear = gd.getNextBoolean(); + name = gd.getNextBoolean(); + channel = gd.getNextBoolean(); + time = gd.getNextBoolean(); + slice = gd.getNextBoolean(); + decimals = gd.getNextChoiceIndex(); + + (new FJStatistics()).run(imp, values, clear, name, channel, time, slice, decimals); + } + + + public void itemStateChanged(final ItemEvent e) { + if (e.getSource() == sliceBox) { + if (sliceBox.getState()) { + timeBox.setState(true); + channelBox.setState(true); + } + } else if (e.getSource() == timeBox) { + if (timeBox.getState()) { + channelBox.setState(true); + } else { + sliceBox.setState(false); + } + } else if (e.getSource() == channelBox) { + if (!channelBox.getState()) { + timeBox.setState(false); + sliceBox.setState(false); + } + } + } + + + public void windowActivated(final WindowEvent e) { + } + + + public void windowClosed(final WindowEvent e) { + pos.x = e.getWindow().getX(); + pos.y = e.getWindow().getY(); + } + + + public void windowClosing(final WindowEvent e) { + } + + + public void windowDeactivated(final WindowEvent e) { + } + + + public void windowDeiconified(final WindowEvent e) { + } + + + public void windowIconified(final WindowEvent e) { + } + + + public void windowOpened(final WindowEvent e) { + } +} + +class FJStatistics { + private static int number = 0; + private final Statistics stats = new Statistics(); + + private final Formatter fmt = new Formatter(); + + private boolean[] values = null; + @SuppressWarnings("unused") + private boolean clear = false; + private boolean name = true; + private boolean channel = false; + private boolean time = false; + + private boolean slice = false; + @SuppressWarnings("unused") + private int decimals = 3; + + void run( + final ImagePlus imp, + final boolean[] values, + final boolean clear, + final boolean name, + final boolean channel, + final boolean time, + final boolean slice, + final int decimals + ) { + + this.values = new boolean[values.length]; + System.arraycopy(values, 0, this.values, 0, values.length); + this.clear = clear; + this.name = name; + this.channel = channel; + this.time = time; + this.slice = slice; + this.decimals = decimals; + + try { + // Initialize: + if (decimals < 0 || decimals > 10) { + throw new IllegalArgumentException("Invalid number of decimals"); + } else { + fmt.decs(decimals); + fmt.chop(0); + } + + // Determine region of interest: + final Image img = Image.wrap(imp); + final Dimensions dims = img.dimensions(); + final Coordinates cMin = new Coordinates(); + final Coordinates cMax = new Coordinates(); + Roi roi = imp.getRoi(); + if (roi == null) roi = new Roi(0, 0, dims.x, dims.y); + ImageProcessor maskImageProcessor = null; + switch (roi.getType()) { + case Roi.COMPOSITE: + case Roi.FREEROI: + case Roi.OVAL: + case Roi.POINT: + case Roi.POLYGON: + case Roi.TRACED_ROI: + maskImageProcessor = roi.getMask(); + break; + case Roi.RECTANGLE: + maskImageProcessor = new ByteProcessor(1, 1); + maskImageProcessor.set(0, 0, 255); + break; + } + if (maskImageProcessor == null) throw new IllegalArgumentException("Region of interest not supported"); + final ImagePlus maskImagePlus = new ImagePlus("Mask", maskImageProcessor); // maskImagePlus.show(); + final Image mask = Image.wrap(maskImagePlus); + final Rectangle bounds = roi.getBounds(); + cMin.x = bounds.x; + cMin.y = bounds.y; + cMax.x = bounds.x + bounds.width - 1; + cMax.y = bounds.y + bounds.height - 1; + + // Compute and show statistics: + final String namePrelude = name ? ("\t" + imp.getTitle()) : ""; + final TextPanel textpanel = IJ.getTextPanel(); + final String headings = headings(); + if (clear || !headings.equals(textpanel.getColumnHeadings())) { + textpanel.setColumnHeadings(headings); + number = 0; + } + + final Progressor pgs = new Progressor(); + final Messenger msg = new Messenger(); + pgs.display(FJ_Options.pgs); + msg.status(FJ_Options.pgs); + + if (slice) { + msg.status("Computing statistics per slice / time / channel..."); + pgs.steps(dims.c * dims.t * dims.z); + pgs.start(); + for (cMin.c = cMax.c = 0; cMin.c < dims.c; ++cMin.c, ++cMax.c) { + for (cMin.t = cMax.t = 0; cMin.t < dims.t; ++cMin.t, ++cMax.t) { + for (cMin.z = cMax.z = 0; cMin.z < dims.z; ++cMin.z, ++cMax.z) { + stats.run(img, cMin, cMax, mask); + final String prelude = (++number) + + namePrelude + "\t" + + (cMin.c + 1) + "\t" + + (cMin.t + 1) + "\t" + + (cMin.z + 1); + textpanel.append(prelude + results()); + pgs.step(); + } + } + } + pgs.stop(); + msg.status(""); + + } else if (time) { + msg.status("Computing statistics per time / channel..."); + pgs.steps(dims.c * dims.t); + pgs.start(); + cMax.z = dims.z - 1; + for (cMin.c = cMax.c = 0; cMin.c < dims.c; ++cMin.c, ++cMax.c) { + for (cMin.t = cMax.t = 0; cMin.t < dims.t; ++cMin.t, ++cMax.t) { + stats.run(img, cMin, cMax, mask); + final String prelude = (++number) + namePrelude + "\t" + (cMin.c + 1) + "\t" + (cMin.t + 1); + textpanel.append(prelude + results()); + pgs.step(); + } + } + pgs.stop(); + msg.status(""); + + } else if (channel) { + msg.status("Computing statistics per channel..."); + pgs.steps(dims.c); + pgs.start(); + cMax.z = dims.z - 1; + cMax.t = dims.t - 1; + for (cMin.c = cMax.c = 0; cMin.c < dims.c; ++cMin.c, ++cMax.c) { + stats.run(img, cMin, cMax, mask); + final String prelude = (++number) + namePrelude + "\t" + (cMin.c + 1); + textpanel.append(prelude + results()); + pgs.step(); + } + pgs.stop(); + msg.status(""); + + } else { + cMax.z = dims.z - 1; + cMax.t = dims.t - 1; + cMax.c = dims.c - 1; + stats.messenger.status(FJ_Options.pgs); + stats.progressor.display(FJ_Options.pgs); + stats.run(img, cMin, cMax, mask); + final String prelude = (++number) + namePrelude; + textpanel.append(prelude + results()); + } + } catch (OutOfMemoryError e) { + FJ.error("Not enough memory for this operation"); + + } catch (IllegalArgumentException e) { + FJ.error(e.getMessage()); + + } catch (Throwable e) { + FJ.error("An unidentified error occurred while running the plugin"); + + } + } + + + private String headings() { + + final StringBuilder cols = new StringBuilder(); + + cols.append("Nr"); + if (name) cols.append("\tImage"); + if (slice) { + cols.append("\tChan\tTime\tSlice"); + } else if (time) { + cols.append("\tChan\tTime"); + } else if (channel) cols.append("\tChan"); + if (values[4]) cols.append("\tElements"); + if (values[0]) cols.append("\tMin"); + if (values[1]) cols.append("\tMax"); + if (values[2]) cols.append("\tMean"); + if (values[6]) cols.append("\tVar"); + if (values[8]) cols.append("\tS-Dev"); + if (values[9]) cols.append("\tA-Dev"); + if (values[3]) cols.append("\tMedian"); + if (values[7]) cols.append("\tMode"); + if (values[5]) cols.append("\tMass"); + if (values[10]) cols.append("\tL1"); + if (values[11]) cols.append("\tL2"); + if (values[12]) cols.append("\tSkew"); + if (values[13]) cols.append("\tKurt"); + + return cols.toString(); + } + + @SuppressWarnings("static-access") + private String results() { + + final StringBuilder res = new StringBuilder(); + + if (values[4]) res.append("\t").append(fmt.d2s(stats.get(stats.ELEMENTS))); + if (values[0]) res.append("\t").append(fmt.d2s(stats.get(stats.MINIMUM))); + if (values[1]) res.append("\t").append(fmt.d2s(stats.get(stats.MAXIMUM))); + if (values[2]) res.append("\t").append(fmt.d2s(stats.get(stats.MEAN))); + if (values[6]) res.append("\t").append(fmt.d2s(stats.get(stats.VARIANCE))); + if (values[8]) res.append("\t").append(fmt.d2s(stats.get(stats.SDEVIATION))); + if (values[9]) res.append("\t").append(fmt.d2s(stats.get(stats.ADEVIATION))); + if (values[3]) res.append("\t").append(fmt.d2s(stats.get(stats.MEDIAN))); + if (values[7]) res.append("\t").append(fmt.d2s(stats.get(stats.MODE))); + if (values[5]) res.append("\t").append(fmt.d2s(stats.get(stats.MASS))); + if (values[10]) res.append("\t").append(fmt.d2s(stats.get(stats.L1NORM))); + if (values[11]) res.append("\t").append(fmt.d2s(stats.get(stats.L2NORM))); + if (values[12]) res.append("\t").append(fmt.d2s(stats.get(stats.SKEWNESS))); + if (values[13]) res.append("\t").append(fmt.d2s(stats.get(stats.KURTOSIS))); + + return res.toString(); + } +} diff --git a/src/main/java/gred/nucleus/myGradient/FJ_Structure.java b/src/main/java/gred/nucleus/myGradient/FJ_Structure.java index c75a3776..6fb9ca94 100644 --- a/src/main/java/gred/nucleus/myGradient/FJ_Structure.java +++ b/src/main/java/gred/nucleus/myGradient/FJ_Structure.java @@ -1,148 +1,153 @@ -package gred.nucleus.myGradient; - -import ij.ImagePlus; -import ij.gui.GenericDialog; -import ij.plugin.PlugIn; -import imagescience.feature.Structure; -import imagescience.image.Aspects; -import imagescience.image.FloatImage; -import imagescience.image.Image; - -import java.awt.*; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.Vector; - -public class FJ_Structure implements PlugIn, WindowListener { - - private static boolean largest = true; - private static boolean middle = false; - private static boolean smallest = true; - - private static String sscale = "1.0"; - private static String iscale = "3.0"; - - private static Point pos = new Point(-1, -1); - - public void run(String arg) { - - if (!FJ.libcheck()) return; - final ImagePlus imp = FJ.imageplus(); - if (imp == null) return; - - FJ.log(FJ.name() + " " + FJ.version() + ": Structure"); - - GenericDialog gd = new GenericDialog(FJ.name() + ": Structure"); - gd.addCheckbox(" Largest eigenvalue of structure tensor ", largest); - gd.addCheckbox(" Middle eigenvalue of structure tensor ", middle); - gd.addCheckbox(" Smallest eigenvalue of structure tensor ", smallest); - gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(5, 0, 0, 0)); - gd.addStringField(" Smoothing scale:", sscale); - gd.addStringField(" Integration scale:", iscale); - - if (pos.x >= 0 && pos.y >= 0) { - gd.centerDialog(false); - gd.setLocation(pos); - } else { - gd.centerDialog(true); - } - gd.addWindowListener(this); - gd.showDialog(); - - if (gd.wasCanceled()) return; - - largest = gd.getNextBoolean(); - middle = gd.getNextBoolean(); - smallest = gd.getNextBoolean(); - sscale = gd.getNextString(); - iscale = gd.getNextString(); - - (new FJStructure()).run(imp, largest, middle, smallest, sscale, iscale); - } - - public void windowActivated(final WindowEvent e) { - } - - public void windowClosed(final WindowEvent e) { - - pos.x = e.getWindow().getX(); - pos.y = e.getWindow().getY(); - } - - public void windowClosing(final WindowEvent e) { - } - - public void windowDeactivated(final WindowEvent e) { - } - - public void windowDeiconified(final WindowEvent e) { - } - - public void windowIconified(final WindowEvent e) { - } - - public void windowOpened(final WindowEvent e) { - } - -} - -class FJStructure { - - void run( - final ImagePlus imp, - final boolean largest, - final boolean middle, - final boolean smallest, - final String sscale, - final String iscale - ) { - - try { - double sscaleval, iscaleval; - try { - sscaleval = Double.parseDouble(sscale); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid smoothing scale value"); - } - try { - iscaleval = Double.parseDouble(iscale); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid integration scale value"); - } - - final Image img = Image.wrap(imp); - final Aspects aspects = img.aspects(); - if (!FJ_Options.isotropic) img.aspects(new Aspects()); - final Structure structure = new Structure(); - structure.messenger.log(FJ_Options.log); - structure.messenger.status(FJ_Options.pgs); - structure.progressor.display(FJ_Options.pgs); - - final Vector eigenimages = structure.run(new FloatImage(img), sscaleval, iscaleval); - - final int nrimgs = eigenimages.size(); - for (Image eigenimage : eigenimages) eigenimage.aspects(aspects); - if (nrimgs == 2) { - if (largest) FJ.show(eigenimages.get(0), imp); - if (smallest) FJ.show(eigenimages.get(1), imp); - } else if (nrimgs == 3) { - if (largest) FJ.show(eigenimages.get(0), imp); - if (middle) FJ.show(eigenimages.get(1), imp); - if (smallest) FJ.show(eigenimages.get(2), imp); - } - - FJ.close(imp); - - } catch (OutOfMemoryError e) { - FJ.error("Not enough memory for this operation"); - - } catch (IllegalArgumentException | IllegalStateException e) { - FJ.error(e.getMessage()); - - } catch (Throwable e) { - FJ.error("An unidentified error occurred while running the plugin"); - - } - } - -} +package gred.nucleus.myGradient; + +import ij.ImagePlus; +import ij.gui.GenericDialog; +import ij.plugin.PlugIn; +import imagescience.feature.Structure; +import imagescience.image.Aspects; +import imagescience.image.FloatImage; +import imagescience.image.Image; + +import java.awt.*; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.util.Vector; + +public class FJ_Structure implements PlugIn, WindowListener { + + private static boolean largest = true; + private static boolean middle = false; + private static boolean smallest = true; + + private static String smoothingScale = "1.0"; + private static String integrationScale = "3.0"; + + private static Point pos = new Point(-1, -1); + + public void run(String arg) { + + if (!FJ.libCheck()) return; + final ImagePlus imp = FJ.imageplus(); + if (imp == null) return; + + FJ.log(FJ.name() + " " + FJ.version() + ": Structure"); + + GenericDialog gd = new GenericDialog(FJ.name() + ": Structure"); + gd.addCheckbox(" Largest eigenvalue of structure tensor ", largest); + gd.addCheckbox(" Middle eigenvalue of structure tensor ", middle); + gd.addCheckbox(" Smallest eigenvalue of structure tensor ", smallest); + gd.addPanel(new Panel(), GridBagConstraints.EAST, new Insets(5, 0, 0, 0)); + gd.addStringField(" Smoothing scale:", smoothingScale); + gd.addStringField(" Integration scale:", integrationScale); + + if (pos.x >= 0 && pos.y >= 0) { + gd.centerDialog(false); + gd.setLocation(pos); + } else { + gd.centerDialog(true); + } + gd.addWindowListener(this); + gd.showDialog(); + + if (gd.wasCanceled()) return; + + largest = gd.getNextBoolean(); + middle = gd.getNextBoolean(); + smallest = gd.getNextBoolean(); + smoothingScale = gd.getNextString(); + integrationScale = gd.getNextString(); + + (new FJStructure()).run(imp, largest, middle, smallest, smoothingScale, integrationScale); + } + + + public void windowActivated(final WindowEvent e) { + } + + + public void windowClosed(final WindowEvent e) { + + pos.x = e.getWindow().getX(); + pos.y = e.getWindow().getY(); + } + + + public void windowClosing(final WindowEvent e) { + } + + + public void windowDeactivated(final WindowEvent e) { + } + + + public void windowDeiconified(final WindowEvent e) { + } + + + public void windowIconified(final WindowEvent e) { + } + + + public void windowOpened(final WindowEvent e) { + } +} + +class FJStructure { + + void run( + final ImagePlus imp, + final boolean largest, + final boolean middle, + final boolean smallest, + final String smoothingScale, + final String integrationScale + ) { + + try { + double sScaleVal, iScaleVal; + try { + sScaleVal = Double.parseDouble(smoothingScale); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid smoothing scale value"); + } + try { + iScaleVal = Double.parseDouble(integrationScale); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid integration scale value"); + } + + final Image img = Image.wrap(imp); + final Aspects aspects = img.aspects(); + if (!FJ_Options.isotropic) img.aspects(new Aspects()); + final Structure structure = new Structure(); + structure.messenger.log(FJ_Options.log); + structure.messenger.status(FJ_Options.pgs); + structure.progressor.display(FJ_Options.pgs); + + final Vector eigenImages = structure.run(new FloatImage(img), sScaleVal, iScaleVal); + + final int nImages = eigenImages.size(); + for (Image eigenImage : eigenImages) eigenImage.aspects(aspects); + if (nImages == 2) { + if (largest) FJ.show(eigenImages.get(0), imp); + if (smallest) FJ.show(eigenImages.get(1), imp); + } else if (nImages == 3) { + if (largest) FJ.show(eigenImages.get(0), imp); + if (middle) FJ.show(eigenImages.get(1), imp); + if (smallest) FJ.show(eigenImages.get(2), imp); + } + + FJ.close(imp); + + } catch (OutOfMemoryError e) { + FJ.error("Not enough memory for this operation"); + + } catch (IllegalArgumentException | IllegalStateException e) { + FJ.error(e.getMessage()); + + } catch (Throwable e) { + FJ.error("An unidentified error occurred while running the plugin"); + + } + } +} diff --git a/src/main/java/gred/nucleus/myGradient/FJ_Website.java b/src/main/java/gred/nucleus/myGradient/FJ_Website.java index a3746da0..6230bc9b 100644 --- a/src/main/java/gred/nucleus/myGradient/FJ_Website.java +++ b/src/main/java/gred/nucleus/myGradient/FJ_Website.java @@ -1,17 +1,16 @@ -package gred.nucleus.myGradient; - -import ij.plugin.BrowserLauncher; -import ij.plugin.PlugIn; - -public class FJ_Website implements PlugIn { - - public void run(String arg) { - - try { - BrowserLauncher.openURL("http://www.imagescience.org/meijering/software/featurej/"); - } catch (Throwable e) { - FJ.error("Could not open default internet browser"); - } - } - -} +package gred.nucleus.myGradient; + +import ij.plugin.BrowserLauncher; +import ij.plugin.PlugIn; + +public class FJ_Website implements PlugIn { + + public void run(String arg) { + + try { + BrowserLauncher.openURL("http://www.imagescience.org/meijering/software/featurej/"); + } catch (Throwable e) { + FJ.error("Could not open default internet browser"); + } + } +} diff --git a/src/main/java/gred/nucleus/myGradient/MyEdges.java b/src/main/java/gred/nucleus/myGradient/MyEdges.java index 1d710658..b71c5455 100644 --- a/src/main/java/gred/nucleus/myGradient/MyEdges.java +++ b/src/main/java/gred/nucleus/myGradient/MyEdges.java @@ -7,23 +7,24 @@ import imagescience.utility.*; /* - Modification in this class to adapte this class for this image processing poulet axel + Modification in this class to adapt this class for this image processing poulet axel */ /** Detects edges in images. */ public class MyEdges { /** The object used for message displaying. */ - public final Messenger messenger = new Messenger(); + public final Messenger messenger = new Messenger(); /** The object used for progress displaying. */ - public final Progressor progressor = new Progressor(); + public final Progressor progressor = new Progressor(); /** The object used for image differentiation. */ public final Differentiator differentiator = new Differentiator(); - private double[][][] tabMask = null; + private double[][][] tabMask = null; /** Default constructor. */ public MyEdges() { } + /** * Detects edges in images. * @@ -32,7 +33,7 @@ public MyEdges() { * image in the z-dimension equals {@code 1}, this method will compute, for every image element, * the magnitude of the two-dimensional (2D) gradient vector. Otherwise it will compute for every * image element the magnitude of the full three-dimensional (3D) gradient vector. These - * computations are performed on every x-y(-z) subimage in a 5D image. + * computations are performed on every x-y(-z) sub-image in a 5D image. * @param scale the smoothing scale at which the required image derivatives are computed. The scale is equal to * the standard deviation of the Gaussian kernel used for differentiation and must be larger than * {@code 0}. In order to enforce physical isotropy, for each dimension, the scale is divided by @@ -65,29 +66,19 @@ public Image run(final Image image, final double scale, final boolean nonmaxsup) final Dimensions dims = image.dimensions(); messenger.log("Input image dimensions: (x,y,z,t,c) = (" + - dims.x + - "," + - dims.y + - "," + - dims.z + - "," + - dims.t + - "," + - dims.c + - ")"); + dims.x + "," + + dims.y + "," + + dims.z + "," + + dims.t + "," + + dims.c + ")"); final Aspects asps = image.aspects(); messenger.log("Element aspect-ratios: (" + - asps.x + - "," + - asps.y + - "," + - asps.z + - "," + - asps.t + - "," + - asps.c + - ")"); + asps.x + "," + + asps.y + "," + + asps.z + "," + + asps.t + "," + + asps.c + ")"); if (asps.x <= 0) throw new IllegalStateException("Aspect-ratio value in x-dimension less than or equal to 0"); if (asps.y <= 0) throw new IllegalStateException("Aspect-ratio value in y-dimension less than or equal to 0"); if (asps.z <= 0) throw new IllegalStateException("Aspect-ratio value in z-dimension less than or equal to 0"); @@ -107,19 +98,19 @@ public Image run(final Image image, final double scale, final boolean nonmaxsup) if (nonmaxsup) pls = new double[]{0, 0.32, 0.64, 0.9, 0.92, 1}; // Compute gradient vector: - logstatus("Computing Ix"); + logStatus("Computing Ix"); progressor.range(pls[pl], pls[++pl]); final Image Ix = differentiator.run(edgeImage.duplicate(), scale, 1, 0, 0); - logstatus("Computing Iy"); + logStatus("Computing Iy"); progressor.range(pls[pl], pls[++pl]); final Image Iy = differentiator.run(edgeImage.duplicate(), scale, 0, 1, 0); - logstatus("Computing Iz"); + logStatus("Computing Iz"); progressor.range(pls[pl], pls[++pl]); final Image Iz = differentiator.run(edgeImage, scale, 0, 0, 1); // Compute gradient magnitude (Ix is reused to save memory in case //non-maxima suppression is not applied): - logstatus("Computing gradient magnitude"); + logStatus("Computing gradient magnitude"); progressor.steps(dims.c * dims.t * dims.z * dims.y); progressor.range(pls[pl], pls[++pl]); edgeImage = nonmaxsup ? new FloatImage(dims) : Ix; @@ -127,28 +118,28 @@ public Image run(final Image image, final double scale, final boolean nonmaxsup) Iy.axes(Axes.X); Iz.axes(Axes.X); edgeImage.axes(Axes.X); - final double[] aIx = new double[dims.x]; - final double[] aIy = new double[dims.x]; - final double[] aIz = new double[dims.x]; - final Coordinates coords = new Coordinates(); + final double[] aIx = new double[dims.x]; + final double[] aIy = new double[dims.x]; + final double[] aIz = new double[dims.x]; + final Coordinates coordinates = new Coordinates(); progressor.start(); - for (coords.c = 0; coords.c < dims.c; ++coords.c) { - for (coords.t = 0; coords.t < dims.t; ++coords.t) { - for (coords.z = 0; coords.z < dims.z; ++coords.z) { - for (coords.y = 0; coords.y < dims.y; ++coords.y) { - Ix.get(coords, aIx); - Iy.get(coords, aIy); - Iz.get(coords, aIz); + for (coordinates.c = 0; coordinates.c < dims.c; ++coordinates.c) { + for (coordinates.t = 0; coordinates.t < dims.t; ++coordinates.t) { + for (coordinates.z = 0; coordinates.z < dims.z; ++coordinates.z) { + for (coordinates.y = 0; coordinates.y < dims.y; ++coordinates.y) { + Ix.get(coordinates, aIx); + Iy.get(coordinates, aIy); + Iz.get(coordinates, aIz); for (int x = 0; x < dims.x; ++x) { if (tabMask != null) { - if (tabMask[x][coords.y][coords.z] > 0) { + if (tabMask[x][coordinates.y][coordinates.z] > 0) { aIx[x] = Math.sqrt(aIx[x] * aIx[x] + aIy[x] * aIy[x] + aIz[x] * aIz[x]); - edgeImage.set(coords, aIx); + edgeImage.set(coordinates, aIx); progressor.step(); } else { aIx[x] = 0; - edgeImage.set(coords, aIx); + edgeImage.set(coordinates, aIx); } } } @@ -160,7 +151,7 @@ public Image run(final Image image, final double scale, final boolean nonmaxsup) // Apply non-maxima suppression if requested (using mirror-boundary conditions and linear interpolation): if (nonmaxsup) { - logstatus("Suppressing non-maxima"); + logStatus("Suppressing non-maxima"); progressor.steps(dims.c * dims.t * dims.z); progressor.range(pls[pl], pls[++pl]); Ix.axes(Axes.X + Axes.Y); @@ -174,46 +165,46 @@ public Image run(final Image image, final double scale, final boolean nonmaxsup) final double[][] aaIz = new double[dims.y][dims.x]; final Coordinates cgm = new Coordinates(); cgm.y = cgm.x = -1; - coords.reset(); - final int dimszm1 = dims.z - 1; - double[][] atmp = null; + coordinates.reset(); + final int dimsZm1 = dims.z - 1; + double[][] atmp; progressor.start(); - for (coords.c = 0, cgm.c = 0; coords.c < dims.c; ++coords.c, ++cgm.c) { - for (coords.t = 0, cgm.t = 0; coords.t < dims.t; ++coords.t, ++cgm.t) { + for (coordinates.c = 0, cgm.c = 0; coordinates.c < dims.c; ++coordinates.c, ++cgm.c) { + for (coordinates.t = 0, cgm.t = 0; coordinates.t < dims.t; ++coordinates.t, ++cgm.t) { // First slice: - coords.z = 0; - Ix.get(coords, aaIx); - Iy.get(coords, aaIy); - Iz.get(coords, aaIz); + coordinates.z = 0; + Ix.get(coordinates, aaIx); + Iy.get(coordinates, aaIy); + Iz.get(coordinates, aaIz); cgm.z = 0; edgeImage.get(cgm, gm[1]); cgm.z = 1; edgeImage.get(cgm, gm[0]); edgeImage.get(cgm, gm[2]); suppress3D(gm, aaIx, aaIy, aaIz); - supImage.set(coords, aaIx); + supImage.set(coordinates, aaIx); progressor.step(); // Intermediate slices: - for (coords.z = 1, cgm.z = 2; coords.z < dimszm1; ++coords.z, ++cgm.z) { - Ix.get(coords, aaIx); - Iy.get(coords, aaIy); - Iz.get(coords, aaIz); + for (coordinates.z = 1, cgm.z = 2; coordinates.z < dimsZm1; ++coordinates.z, ++cgm.z) { + Ix.get(coordinates, aaIx); + Iy.get(coordinates, aaIy); + Iz.get(coordinates, aaIz); atmp = gm[0]; gm[0] = gm[1]; gm[1] = gm[2]; gm[2] = atmp; edgeImage.get(cgm, gm[2]); suppress3D(gm, aaIx, aaIy, aaIz); - supImage.set(coords, aaIx); + supImage.set(coordinates, aaIx); progressor.step(); } // Last slice: - Ix.get(coords, aaIx); - Iy.get(coords, aaIy); - Iz.get(coords, aaIz); + Ix.get(coordinates, aaIx); + Iy.get(coordinates, aaIy); + Iz.get(coordinates, aaIz); atmp = gm[0]; gm[0] = gm[1]; gm[1] = gm[2]; @@ -221,7 +212,7 @@ public Image run(final Image image, final double scale, final boolean nonmaxsup) cgm.z = dims.z - 2; edgeImage.get(cgm, gm[2]); suppress3D(gm, aaIx, aaIy, aaIz); - supImage.set(coords, aaIx); + supImage.set(coordinates, aaIx); progressor.step(); } } @@ -238,58 +229,59 @@ public Image run(final Image image, final double scale, final boolean nonmaxsup) return edgeImage; } + private void suppress3D(final double[][][] gm, final double[][] aaIx, final double[][] aaIy, final double[][] aaIz) { // Initialize: - final int dimsy = aaIx.length; - final int dimsyp1 = dimsy + 1; - final int dimsym1 = dimsy - 1; - final int dimsx = aaIx[0].length; - final int dimsxp1 = dimsx + 1; - final int dimsxm1 = dimsx - 1; - double rx, ry, rz, fx, fy, fz, gmval, gmval1, gmval2; + final int dimsY = aaIx.length; + final int dimsYp1 = dimsY + 1; + final int dimsYm1 = dimsY - 1; + final int dimsX = aaIx[0].length; + final int dimsXp1 = dimsX + 1; + final int dimsXm1 = dimsX - 1; + double rx, ry, rz, fx, fy, fz, gmVal, gmVal1, gmVal2; double fdx, fdy, fdz, f1mdx, f1mdy, f1mdz; int ix, iy, iz, ixp1, iyp1, izp1; // Mirror x-borders: - if (dimsx == 1) { + if (dimsX == 1) { for (int z = 0; z < 3; ++z) { final double[][] slice = gm[z]; - for (int y = 1; y < dimsyp1; ++y) { + for (int y = 1; y < dimsYp1; ++y) { slice[y][0] = slice[y][1]; - slice[y][dimsxp1] = slice[y][dimsx]; + slice[y][dimsXp1] = slice[y][dimsX]; } } } else { for (int z = 0; z < 3; ++z) { final double[][] slice = gm[z]; - for (int y = 1; y < dimsyp1; ++y) { + for (int y = 1; y < dimsYp1; ++y) { slice[y][0] = slice[y][2]; - slice[y][dimsxp1] = slice[y][dimsxm1]; + slice[y][dimsXp1] = slice[y][dimsXm1]; } } } // Mirror y-borders: - if (dimsy == 1) { + if (dimsY == 1) { for (int z = 0; z < 3; ++z) { final double[] y0 = gm[z][0]; final double[] y1 = gm[z][1]; final double[] y2 = gm[z][2]; - for (int x = 0; x <= dimsxp1; ++x) y0[x] = y2[x] = y1[x]; + for (int x = 0; x <= dimsXp1; ++x) y0[x] = y2[x] = y1[x]; } } else { for (int z = 0; z < 3; ++z) { final double[] y0 = gm[z][0]; final double[] y2 = gm[z][2]; - final double[] ydimsym1 = gm[z][dimsym1]; - final double[] ydimsyp1 = gm[z][dimsyp1]; - for (int x = 0; x <= dimsxp1; ++x) { + final double[] yDimsYm1 = gm[z][dimsYm1]; + final double[] yDimsYp1 = gm[z][dimsYp1]; + for (int x = 0; x <= dimsXp1; ++x) { y0[x] = y2[x]; - ydimsyp1[x] = ydimsym1[x]; + yDimsYp1[x] = yDimsYm1[x]; } } } @@ -297,23 +289,23 @@ private void suppress3D(final double[][][] gm, // Suppress non-maxima: final double[][] gm1 = gm[1]; - for (int y = 0, yp1 = 1; y < dimsy; ++y, ++yp1) { + for (int y = 0, yp1 = 1; y < dimsY; ++y, ++yp1) { final double[] gm1yp1 = gm1[yp1]; final double[] aIx = aaIx[y]; final double[] aIy = aaIy[y]; final double[] aIz = aaIz[y]; - for (int x = 0, xp1 = 1; x < dimsx; ++x, ++xp1) { + for (int x = 0, xp1 = 1; x < dimsX; ++x, ++xp1) { - gmval = gm1yp1[xp1]; - if (gmval == 0) { + gmVal = gm1yp1[xp1]; + if (gmVal == 0) { aIx[x] = 0; } else { // Compute direction vector: - rx = 0.7f * aIx[x] / gmval; - ry = 0.7f * aIy[x] / gmval; - rz = 0.7f * aIz[x] / gmval; + rx = 0.7f * aIx[x] / gmVal; + ry = 0.7f * aIy[x] / gmVal; + rz = 0.7f * aIz[x] / gmVal; // Compute gradient magnitude in one direction: fx = xp1 + rx; @@ -332,7 +324,7 @@ private void suppress3D(final double[][][] gm, f1mdy = 1 - fdy; f1mdz = 1 - fdz; - gmval1 = ( + gmVal1 = ( f1mdz * f1mdy * f1mdx * gm[iz][iy][ix] + f1mdz * f1mdy * fdx * gm[iz][iy][ixp1] + f1mdz * fdy * f1mdx * gm[iz][iyp1][ix] + @@ -360,7 +352,7 @@ private void suppress3D(final double[][][] gm, f1mdy = 1 - fdy; f1mdz = 1 - fdz; - gmval2 = ( + gmVal2 = ( f1mdz * f1mdy * f1mdx * gm[iz][iy][ix] + f1mdz * f1mdy * fdx * gm[iz][iy][ixp1] + f1mdz * fdy * f1mdx * gm[iz][iyp1][ix] + @@ -372,19 +364,20 @@ private void suppress3D(final double[][][] gm, ); // Suppress current gradient magnitude if non-maximum: - if (gmval1 >= gmval || gmval2 >= gmval) { + if (gmVal1 >= gmVal || gmVal2 >= gmVal) { aIx[x] = 0; } else { - aIx[x] = gmval; + aIx[x] = gmVal; } } } } } + /** - * MĂ©thode permettant d'obtenir le masque d'un objet et de le stocker - * dans une matrice + * MĂ©thode permettant d'obtenir le masque d'un objet et de le stocker dans une matrice + * * @param imagePlus => image binaire de l'image en cours de traitement */ public void setMask(ImagePlus imagePlus) { @@ -404,10 +397,9 @@ public void setMask(ImagePlus imagePlus) { } } - private void logstatus(final String s) { - + + private void logStatus(final String s) { messenger.log(s); messenger.status(s + "..."); } - } diff --git a/src/main/java/gred/nucleus/myGradient/MyGradient.java b/src/main/java/gred/nucleus/myGradient/MyGradient.java index 2f5f5fc7..e471c96b 100644 --- a/src/main/java/gred/nucleus/myGradient/MyGradient.java +++ b/src/main/java/gred/nucleus/myGradient/MyGradient.java @@ -22,15 +22,16 @@ public class MyGradient { private static String lower = ""; private static String higher = ""; ImagePlus _imagePlus; - ImagePlus _imagePlusBinaire; - private boolean mask; + ImagePlus _imagePlusBinary; + private boolean mask; - public MyGradient(ImagePlus imp, ImagePlus imagePlusBinaire) { + public MyGradient(ImagePlus imp, ImagePlus imagePlusBinary) { _imagePlus = imp; - _imagePlusBinaire = imagePlusBinaire; + _imagePlusBinary = imagePlusBinary; mask = true; } + public MyGradient(ImagePlus imp) { _imagePlus = imp; mask = false; @@ -38,66 +39,70 @@ public MyGradient(ImagePlus imp) { @SuppressWarnings("unused") public ImagePlus run() { - ImagePlus newimp = new ImagePlus(); + ImagePlus newImagePlus = new ImagePlus(); try { - double scaleval, lowval = 0, highval = 0; - boolean lowthres = true, highthres = true; + double scaleVal; + double lowVal = 0; + double highVal = 0; + boolean lowThreshold = true; + boolean highThreshold = true; try { - scaleval = Double.parseDouble(scale); + scaleVal = Double.parseDouble(scale); } catch (Exception e) { throw new IllegalArgumentException("Invalid smoothing scale value"); } try { if (lower.equals("")) { - lowthres = false; + lowThreshold = false; } else { - lowval = Double.parseDouble(lower); + lowVal = Double.parseDouble(lower); } } catch (Exception e) { throw new IllegalArgumentException("Invalid lower threshold value"); } try { if (higher.equals("")) { - highthres = false; + highThreshold = false; } else { - highval = Double.parseDouble(higher); + highVal = Double.parseDouble(higher); } } catch (Exception e) { throw new IllegalArgumentException("Invalid higher threshold value"); } - final int thresmode = (lowthres ? 10 : 0) + (highthres ? 1 : 0); - final Image img = Image.wrap(_imagePlus); - Image newimg = new FloatImage(img); - double[] pls = {0, 1}; - int pl = 0; - if ((compute || suppress) && thresmode > 0) { + final int threshMode = (lowThreshold ? 10 : 0) + (highThreshold ? 1 : 0); + final Image image = Image.wrap(_imagePlus); + Image newImage = new FloatImage(image); + double[] pls = {0, 1}; + int pl = 0; + if ((compute || suppress) && threshMode > 0) { pls = new double[]{0, 0.9, 1}; } final Progressor progressor = new Progressor(); progressor.display(FJ_Options.pgs); if (compute || suppress) { - final Aspects aspects = newimg.aspects(); - if (!FJ_Options.isotropic) newimg.aspects(new Aspects()); + final Aspects aspects = newImage.aspects(); + if (!FJ_Options.isotropic) newImage.aspects(new Aspects()); final MyEdges myEdges = new MyEdges(); - if (mask) myEdges.setMask(_imagePlusBinaire); + if (mask) myEdges.setMask(_imagePlusBinary); progressor.range(pls[pl], pls[++pl]); myEdges.progressor.parent(progressor); myEdges.messenger.log(FJ_Options.log); myEdges.messenger.status(FJ_Options.pgs); - newimg = myEdges.run(newimg, scaleval, suppress); - newimg.aspects(aspects); + newImage = myEdges.run(newImage, scaleVal, suppress); + newImage.aspects(aspects); } - newimp = newimg.imageplus(); - _imagePlus.setCalibration(newimp.getCalibration()); - final double[] minmax = newimg.extrema(); - final double min = minmax[0], max = minmax[1]; - newimp.setDisplayRange(min, max); + newImagePlus = newImage.imageplus(); + _imagePlus.setCalibration(newImagePlus.getCalibration()); + final double[] min_max = newImage.extrema(); + final double min = min_max[0]; + final double max = min_max[1]; + newImagePlus.setDisplayRange(min, max); } catch (OutOfMemoryError e) { FJ.error("Not enough memory for this operation"); } catch (IllegalArgumentException | IllegalStateException e) { FJ.error(e.getMessage()); } //catch (Throwable e) { FJ.error("An unidentified error occurred while running the plugin"); } - return newimp; + return newImagePlus; } } diff --git a/src/main/java/gred/nucleus/nucleusCaracterisations/NucleusAnalysis.java b/src/main/java/gred/nucleus/nucleusCaracterisations/NucleusAnalysis.java index 1a8b7a17..0269aebf 100644 --- a/src/main/java/gred/nucleus/nucleusCaracterisations/NucleusAnalysis.java +++ b/src/main/java/gred/nucleus/nucleusCaracterisations/NucleusAnalysis.java @@ -5,7 +5,7 @@ /** - * Analysis of nuclear segmented image, method call Measure3D class, to copute the 3D parameters of interest + * Analysis of nuclear segmented image, method call Measure3D class, to compute the 3D parameters of interest * * @author Tristan Dubos and Axel Poulet */ @@ -15,7 +15,7 @@ public class NucleusAnalysis { /** ImagePlus segmented image */ private ImagePlus _imgSeg; /** String stocking the the parameters 3D results */ - private String _resu = ""; + private String _results = ""; private SegmentationParameters m_segmentationParameters; /** @@ -29,6 +29,7 @@ public NucleusAnalysis(ImagePlus raw, ImagePlus seg) { this._imgSeg = seg; } + public NucleusAnalysis(ImagePlus raw, ImagePlus seg, SegmentationParameters segmentationParameters) { this._imgRaw = raw; this._imgSeg = seg; @@ -45,36 +46,36 @@ public NucleusAnalysis(ImagePlus raw, ImagePlus seg, SegmentationParameters segm Esr SurfaceArea => //TODO can be removed after test if the correction is OK SurfaceAreaCorrected => with surfel method - SphericityCorrected => compute sphericty with SurfaceAreaCorrected + SphericityCorrected => compute sphericity with SurfaceAreaCorrected @return String results of the 3D parameter */ /* - public String nucleusParameter3D() { - Measure3D measure3D = new Measure3D(); - double volume = measure3D.computeVolumeObject(this._imgSeg, 255); - double surfaceArea = measure3D.computeSurfaceObject(255); - double bis = measure3D.computeComplexSurface(this._imgRaw, this._imgSeg); - double[] tEigenValues = measure3D.computeEigenValue3D(this._imgSeg, 255); - IJ.log(" " + tEigenValues[0] + " " + tEigenValues[1] + " " + tEigenValues[2]); - this._resu = this._imgRaw.getTitle() + "\t" + - measure3D.computeVolumeObject(this._imgSeg, 255) + "\t" + - measure3D.computeFlatnessAndElongation(this._imgSeg, 255)[0] + "\t" + - measure3D.computeFlatnessAndElongation(this._imgSeg, 255)[1] + "\t" + - measure3D.computeSphericity(volume, surfaceArea) + "\t" + - measure3D.equivalentSphericalRadius(volume) + "\t" + - surfaceArea + "\t" + - bis + "\t" + - measure3D.computeSphericity(volume, bis) + "\n"; - return this._resu; - } -

*/ + public String nucleusParameter3D() { + Measure3D measure3D = new Measure3D(); + double volume = measure3D.computeVolumeObject(this._imgSeg, 255); + double surfaceArea = measure3D.computeSurfaceObject(255); + double bis = measure3D.computeComplexSurface(this._imgRaw, this._imgSeg); + double[] tEigenValues = measure3D.computeEigenValue3D(this._imgSeg, 255); + IJ.log(" " + tEigenValues[0] + " " + tEigenValues[1] + " " + tEigenValues[2]); + this._results = this._imgRaw.getTitle() + "\t" + + measure3D.computeVolumeObject(this._imgSeg, 255) + "\t" + + measure3D.computeFlatnessAndElongation(this._imgSeg, 255)[0] + "\t" + + measure3D.computeFlatnessAndElongation(this._imgSeg, 255)[1] + "\t" + + measure3D.computeSphericity(volume, surfaceArea) + "\t" + + measure3D.equivalentSphericalRadius(volume) + "\t" + + surfaceArea + "\t" + + bis + "\t" + + measure3D.computeSphericity(volume, bis) + "\n"; + return this._results; + } + */ /** - * Setter of _resu. + * Setter of _results. * - * @param resu String + * @param results String */ - public void setResu(String resu) { - this._resu = resu; + public void setResults(String results) { + this._results = results; } } \ No newline at end of file diff --git a/src/main/java/gred/nucleus/plugins/Autocrop_.java b/src/main/java/gred/nucleus/plugins/Autocrop_.java index 29594a86..d74b24ed 100644 --- a/src/main/java/gred/nucleus/plugins/Autocrop_.java +++ b/src/main/java/gred/nucleus/plugins/Autocrop_.java @@ -4,16 +4,14 @@ import gred.nucleus.autocrop.AutocropParameters; import gred.nucleus.dialogs.AutocropConfigDialog; import gred.nucleus.dialogs.AutocropDialog; -import gred.nucleus.exceptions.fileInOut; import ij.IJ; import ij.plugin.PlugIn; import java.io.File; -import java.io.IOException; public class Autocrop_ implements PlugIn { public static void runAutoCropFolder(String imageSource, String output, String pathToConfig) - throws IOException, fileInOut, Exception { + throws Exception { AutocropParameters autocropParameters = new AutocropParameters(imageSource, output, pathToConfig); AutoCropCalling autoCrop = new AutoCropCalling(autocropParameters); File file = new File(imageSource); @@ -24,7 +22,8 @@ public static void runAutoCropFolder(String imageSource, String output, String p } } - public static void runAutoCropFolder(String imageSource, String output) throws IOException, fileInOut, Exception { + + public static void runAutoCropFolder(String imageSource, String output) throws Exception { AutocropParameters autocropParameters = new AutocropParameters(imageSource, output); AutoCropCalling autoCrop = new AutoCropCalling(autocropParameters); File file = new File(imageSource); @@ -35,31 +34,32 @@ public static void runAutoCropFolder(String imageSource, String output) throws I } } + public static void runAutoCropFolder(String imageSource, String output, String xCropBoxSize, String yCropBoxSize, String zCropBoxSize, - String slicesOTSUcomputing, - String thresholdOTSUcomputing, + String slicesOTSUComputing, + String thresholdOTSUComputing, String channelToComputeThreshold, String minVolumeNucleus, String maxVolumeNucleus, String boxesPercentSurfaceToFilter, - boolean boxesRegroupement) throws IOException, fileInOut, Exception { + boolean regroupBoxes) throws Exception { AutocropParameters autocropParameters = new AutocropParameters(imageSource, output, Integer.parseInt(xCropBoxSize), Integer.parseInt(yCropBoxSize), Integer.parseInt(zCropBoxSize), - Integer.parseInt(slicesOTSUcomputing), - Integer.parseInt(thresholdOTSUcomputing), + Integer.parseInt(slicesOTSUComputing), + Integer.parseInt(thresholdOTSUComputing), Integer.parseInt(channelToComputeThreshold), Integer.parseInt(minVolumeNucleus), Integer.parseInt(maxVolumeNucleus), Integer.parseInt(boxesPercentSurfaceToFilter), - boxesRegroupement); + regroupBoxes); AutoCropCalling autoCrop = new AutoCropCalling(autocropParameters); File file = new File(imageSource); @@ -70,6 +70,7 @@ public static void runAutoCropFolder(String imageSource, } } + public static void runAutoCropFolder(String imageSource, String output, String xCal, @@ -78,13 +79,13 @@ public static void runAutoCropFolder(String imageSource, String xCropBoxSize, String yCropBoxSize, String zCropBoxSize, - String slicesOTSUcomputing, - String thresholdOTSUcomputing, + String slicesOTSUComputing, + String thresholdOTSUComputing, String channelToComputeThreshold, String minVolumeNucleus, String maxVolumeNucleus, String boxesPercentSurfaceToFilter, - boolean boxesRegroupement) throws IOException, fileInOut, Exception { + boolean regroupBoxes) throws Exception { AutocropParameters autocropParameters = new AutocropParameters(imageSource, output, @@ -94,13 +95,13 @@ public static void runAutoCropFolder(String imageSource, Integer.parseInt(xCropBoxSize), Integer.parseInt(yCropBoxSize), Integer.parseInt(zCropBoxSize), - Integer.parseInt(slicesOTSUcomputing), - Integer.parseInt(thresholdOTSUcomputing), + Integer.parseInt(slicesOTSUComputing), + Integer.parseInt(thresholdOTSUComputing), Integer.parseInt(channelToComputeThreshold), Integer.parseInt(minVolumeNucleus), Integer.parseInt(maxVolumeNucleus), Integer.parseInt(boxesPercentSurfaceToFilter), - boxesRegroupement); + regroupBoxes); AutoCropCalling autoCrop = new AutoCropCalling(autocropParameters); File file = new File(imageSource); @@ -111,6 +112,7 @@ public static void runAutoCropFolder(String imageSource, } } + /** * Run method for imageJ plugin for the autocrop * @@ -152,38 +154,38 @@ public void run(String arg) { } } else if (autocropDialog.getConfigMode() == 1) { AutocropConfigDialog acd = autocropDialog.getAutocropConfigFileDialog(); - if (acd.isCalibSelected()) { - IJ.log("w/ calib"); + if (acd.isCalibrationSelected()) { + IJ.log("w/ calibration"); runAutoCropFolder(input, output, - acd.getxCalibration(), - acd.getyCalibration(), - acd.getzCalibration(), - acd.getxCropBoxSize(), - acd.getyCropBoxSize(), - acd.getzCropBoxSize(), - acd.getSlicesOTSUcomputing(), + acd.getXCalibration(), + acd.getYCalibration(), + acd.getZCalibration(), + acd.getXCropBoxSize(), + acd.getYCropBoxSize(), + acd.getZCropBoxSize(), + acd.getSlicesOTSUComputing(), acd.getThresholdOTSUComputing(), acd.getChannelToComputeThreshold(), acd.getMinVolume(), acd.getMaxVolume(), acd.getBoxesPercentSurfaceToFilter(), - acd.getBoxesRegroupementSelected() + acd.isRegroupBoxesSelected() ); } else { - IJ.log("w/out calib"); + IJ.log("w/out calibration"); runAutoCropFolder(input, output, - acd.getxCropBoxSize(), - acd.getyCropBoxSize(), - acd.getzCropBoxSize(), - acd.getSlicesOTSUcomputing(), + acd.getXCropBoxSize(), + acd.getYCropBoxSize(), + acd.getZCropBoxSize(), + acd.getSlicesOTSUComputing(), acd.getThresholdOTSUComputing(), acd.getChannelToComputeThreshold(), acd.getMinVolume(), acd.getMaxVolume(), acd.getBoxesPercentSurfaceToFilter(), - acd.getBoxesRegroupementSelected() + acd.isRegroupBoxesSelected() ); } } else { diff --git a/src/main/java/gred/nucleus/plugins/ChromocenterSegmentationBatchPlugin_.java b/src/main/java/gred/nucleus/plugins/ChromocenterSegmentationBatchPlugin_.java index 1ebbfd9c..f9c7b2b5 100644 --- a/src/main/java/gred/nucleus/plugins/ChromocenterSegmentationBatchPlugin_.java +++ b/src/main/java/gred/nucleus/plugins/ChromocenterSegmentationBatchPlugin_.java @@ -38,13 +38,13 @@ public void run(String arg) { if (fileList.isDirectoryOrFileExist(".+RawDataNucleus.+", tFileRawData) && fileList.isDirectoryOrFileExist(".+SegmentedDataNucleus.+", tFileRawData)) { - ArrayList arrayListImageSegmenetedDataNucleus = + ArrayList arrayListImageSegmentedDataNucleus = fileList.fileSearchList(".+SegmentedDataNucleus.+", tFileRawData); String workDirectory = _chromocenterSegmentationPipelineBatchDialog.getWorkDirectory(); - for (int i = 0; i < arrayListImageSegmenetedDataNucleus.size(); ++i) { - IJ.log("image" + (i + 1) + " / " + arrayListImageSegmenetedDataNucleus.size()); - String pathImageSegmentedNucleus = arrayListImageSegmenetedDataNucleus.get(i); + for (int i = 0; i < arrayListImageSegmentedDataNucleus.size(); ++i) { + IJ.log("image" + (i + 1) + " / " + arrayListImageSegmentedDataNucleus.size()); + String pathImageSegmentedNucleus = arrayListImageSegmentedDataNucleus.get(i); String pathNucleusRaw = pathImageSegmentedNucleus.replaceAll("SegmentedDataNucleus", "RawDataNucleus"); IJ.log(pathNucleusRaw); @@ -75,11 +75,11 @@ public void run(String arg) { calibration = imagePlusInput.getCalibration(); } ChromocentersEnhancement chromocenterSegmentation = new ChromocentersEnhancement(); - ImagePlus imagePlusConstraste = + ImagePlus imagePlusContrast = chromocenterSegmentation.applyEnhanceChromocenters(imagePlusInput, imagePlusSegmented); - imagePlusConstraste.setTitle(imagePlusInput.getTitle()); - imagePlusConstraste.setCalibration(calibration); - saveFile(imagePlusConstraste, workDirectory + File.separator + "ContrastDataNucleus"); + imagePlusContrast.setTitle(imagePlusInput.getTitle()); + imagePlusContrast.setCalibration(calibration); + saveFile(imagePlusContrast, workDirectory + File.separator + "ContrastDataNucleus"); } } IJ.log("End of the chromocenter segmentation , the results are in " + @@ -91,6 +91,7 @@ public void run(String arg) { } } + /** * saving file method * diff --git a/src/main/java/gred/nucleus/plugins/ChromocenterSegmentationPlugin_.java b/src/main/java/gred/nucleus/plugins/ChromocenterSegmentationPlugin_.java index ffc56737..f4f5f00d 100644 --- a/src/main/java/gred/nucleus/plugins/ChromocenterSegmentationPlugin_.java +++ b/src/main/java/gred/nucleus/plugins/ChromocenterSegmentationPlugin_.java @@ -19,8 +19,8 @@ public class ChromocenterSegmentationPlugin_ implements PlugIn { * */ public void run(String arg) { - int indiceRawImage = 0; - int indiceSementedImage = 0; + int indexRawImage = 0; + int indexSegmentedImage = 0; double xCalibration = 1, yCalibration = 1, zCalibration = 1; String unit = "pixel"; int[] wList = WindowManager.getIDList(); @@ -45,9 +45,9 @@ public void run(String arg) { } } GenericDialog genericDialog = new GenericDialog("Chromocenter Segmentation", IJ.getInstance()); - genericDialog.addChoice("Raw image", titles, titles[indiceRawImage]); - genericDialog.addChoice("Nucleus segmeneted image", titles, titles[indiceSementedImage]); - genericDialog.addNumericField("x calibartion", xCalibration, 3); + genericDialog.addChoice("Raw image", titles, titles[indexRawImage]); + genericDialog.addChoice("Nucleus segmented image", titles, titles[indexSegmentedImage]); + genericDialog.addNumericField("x calibration", xCalibration, 3); genericDialog.addNumericField("y calibration", yCalibration, 3); genericDialog.addNumericField("z calibration", zCalibration, 3); genericDialog.addStringField("Unit", unit, 10); @@ -69,9 +69,9 @@ public void run(String arg) { imagePlusInput.setCalibration(calibration); imagePlusSegmented.setCalibration(calibration); ChromocentersEnhancement chromocentersSegmentation = new ChromocentersEnhancement(); - ImagePlus imagePlusContraste = + ImagePlus imagePlusContrast = chromocentersSegmentation.applyEnhanceChromocenters(imagePlusInput, imagePlusSegmented); - imagePlusContraste.setTitle("ContrastedImage"); - imagePlusContraste.show(); + imagePlusContrast.setTitle("ContrastedImage"); + imagePlusContrast.show(); } } \ No newline at end of file diff --git a/src/main/java/gred/nucleus/plugins/ChromocentersAnalysisPlugin_.java b/src/main/java/gred/nucleus/plugins/ChromocentersAnalysisPlugin_.java index 4f9d9baf..433ad6c2 100644 --- a/src/main/java/gred/nucleus/plugins/ChromocentersAnalysisPlugin_.java +++ b/src/main/java/gred/nucleus/plugins/ChromocentersAnalysisPlugin_.java @@ -20,12 +20,12 @@ public class ChromocentersAnalysisPlugin_ implements PlugIn { * */ public void run(String arg) { - int indiceCcImage = 0; - int indiceRawImage = 0; - int indiceSegmentedImage = 0; - double xCalibration = 1, yCalibration = 1, zCalibration = 1; - String unit = "pixel"; - int[] wList = WindowManager.getIDList(); + int indexCcImage = 0; + int indexRawImage = 0; + int indexSegmentedImage = 0; + double xCalibration = 1, yCalibration = 1, zCalibration = 1; + String unit = "pixel"; + int[] wList = WindowManager.getIDList(); if (wList == null) { IJ.noImage(); return; @@ -47,10 +47,10 @@ public void run(String arg) { } } GenericDialog genericDialog = new GenericDialog("Chromocenter Analysis", IJ.getInstance()); - genericDialog.addChoice("Raw image", titles, titles[indiceRawImage]); - genericDialog.addChoice("Nucleus Segmented", titles, titles[indiceSegmentedImage]); - genericDialog.addChoice("Chromocenters image Segmented", titles, titles[indiceCcImage]); - genericDialog.addNumericField("x calibartion", xCalibration, 3); + genericDialog.addChoice("Raw image", titles, titles[indexRawImage]); + genericDialog.addChoice("Nucleus Segmented", titles, titles[indexSegmentedImage]); + genericDialog.addChoice("Chromocenters image Segmented", titles, titles[indexCcImage]); + genericDialog.addNumericField("x calibration", xCalibration, 3); genericDialog.addNumericField("y calibration", yCalibration, 3); genericDialog.addNumericField("z calibration).", zCalibration, 3); genericDialog.addStringField("Unit", unit, 10); diff --git a/src/main/java/gred/nucleus/plugins/CropFromCoordinate_.java b/src/main/java/gred/nucleus/plugins/CropFromCoordinate_.java index a7148d76..1eaac6d0 100644 --- a/src/main/java/gred/nucleus/plugins/CropFromCoordinate_.java +++ b/src/main/java/gred/nucleus/plugins/CropFromCoordinate_.java @@ -4,13 +4,10 @@ import gred.nucleus.dialogs.CropFromCoodinateDialog; import ij.IJ; import ij.plugin.PlugIn; -import loci.formats.FormatException; - -import java.io.IOException; public class CropFromCoordinate_ implements PlugIn { - public static void cropFromCoordinates(String coordinateDir) throws IOException, FormatException, Exception { + public static void cropFromCoordinates(String coordinateDir) throws Exception { CropFromCoordinates test = new CropFromCoordinates(coordinateDir); test.runCropFromCoordinate(); @@ -49,5 +46,4 @@ public void run(String arg) { } } } - } diff --git a/src/main/java/gred/nucleus/plugins/NucleusAnalysis_.java b/src/main/java/gred/nucleus/plugins/NucleusAnalysis_.java index dac7d833..615f3eca 100644 --- a/src/main/java/gred/nucleus/plugins/NucleusAnalysis_.java +++ b/src/main/java/gred/nucleus/plugins/NucleusAnalysis_.java @@ -19,11 +19,11 @@ public class NucleusAnalysis_ implements PlugIn { * @param arg */ public void run(String arg) { - int indiceRawImage = 0; - int indiceSementedImage = 0; - double xCalibration = 1, yCalibration = 1, zCalibration = 1; - String unit = "pixel"; - int[] wList = WindowManager.getIDList(); + int indexRawImage = 0; + int indexSementedImage = 0; + double xCalibration = 1, yCalibration = 1, zCalibration = 1; + String unit = "pixel"; + int[] wList = WindowManager.getIDList(); if (wList == null) { IJ.noImage(); return; @@ -46,9 +46,9 @@ public void run(String arg) { } GenericDialog genericDialog = new GenericDialog("Chromocenter Segmentation", IJ.getInstance()); - genericDialog.addChoice("Raw image", titles, titles[indiceRawImage]); - genericDialog.addChoice("Nucleus segmeneted image", titles, titles[indiceSementedImage]); - genericDialog.addNumericField("x calibartion", xCalibration, 3); + genericDialog.addChoice("Raw image", titles, titles[indexRawImage]); + genericDialog.addChoice("Nucleus segmented image", titles, titles[indexSementedImage]); + genericDialog.addNumericField("x calibration", xCalibration, 3); genericDialog.addNumericField("y calibration", yCalibration, 3); genericDialog.addNumericField("z calibration", zCalibration, 3); genericDialog.addStringField("Unit", unit, 10); diff --git a/src/main/java/gred/nucleus/plugins/NucleusSegmentationAndAnalysisBatchPlugin_.java b/src/main/java/gred/nucleus/plugins/NucleusSegmentationAndAnalysisBatchPlugin_.java index f766b994..72007643 100644 --- a/src/main/java/gred/nucleus/plugins/NucleusSegmentationAndAnalysisBatchPlugin_.java +++ b/src/main/java/gred/nucleus/plugins/NucleusSegmentationAndAnalysisBatchPlugin_.java @@ -24,14 +24,15 @@ public void run(String arg) { } } if (_nucleusPipelineBatchDialog.isStart()) { - IJ.log("Begining of the segmentation of nuclei, the data are in " + + IJ.log("Beginning of the segmentation of nuclei, the data are in " + _nucleusPipelineBatchDialog.getRawDataDirectory()); - SegmentationCalling otsuModif = new SegmentationCalling(_nucleusPipelineBatchDialog.getRawDataDirectory(), - _nucleusPipelineBatchDialog.getWorkDirectory(), - (short) _nucleusPipelineBatchDialog.getMinVolume(), - (short) _nucleusPipelineBatchDialog.getMaxVolume()); + SegmentationCalling otsuModified = + new SegmentationCalling(_nucleusPipelineBatchDialog.getRawDataDirectory(), + _nucleusPipelineBatchDialog.getWorkDirectory(), + (short) _nucleusPipelineBatchDialog.getMinVolume(), + (short) _nucleusPipelineBatchDialog.getMaxVolume()); try { - String log = otsuModif.runSeveralImages2(); + String log = otsuModified.runSeveralImages2(); } catch (Exception e) { e.printStackTrace(); } @@ -41,54 +42,63 @@ public void run(String arg) { } } - /** @return */ + + /** @return */ public int getNbCpu() { return _nucleusPipelineBatchDialog.getNbCpu(); } - /** @return */ + + /** @return */ public double getZCalibration() { return _nucleusPipelineBatchDialog.getZCalibration(); } - /** @return */ + + /** @return */ public double getXCalibration() { return _nucleusPipelineBatchDialog.getXCalibration(); } - /** @return */ + + /** @return */ public double getYCalibration() { return _nucleusPipelineBatchDialog.getYCalibration(); } - /** @return */ + + /** @return */ public String getUnit() { return _nucleusPipelineBatchDialog.getUnit(); } - /** @return */ + + /** @return */ public double getMinVolume() { return _nucleusPipelineBatchDialog.getMinVolume(); } - /** @return */ + + /** @return */ public double getMaxVolume() { return _nucleusPipelineBatchDialog.getMaxVolume(); } - /** @return */ + + /** @return */ public String getWorkDirectory() { return _nucleusPipelineBatchDialog.getWorkDirectory(); } - /** @return */ + + /** @return */ public boolean is2D3DAnalysis() { return _nucleusPipelineBatchDialog.is2D3DAnalysis(); } - /** @return */ + + /** @return */ public boolean is3DAnalysis() { return _nucleusPipelineBatchDialog.is3D(); } - } diff --git a/src/main/java/gred/nucleus/plugins/NucleusSegmentationAndAnalysisPlugin_.java b/src/main/java/gred/nucleus/plugins/NucleusSegmentationAndAnalysisPlugin_.java index 5835176e..f512bc43 100644 --- a/src/main/java/gred/nucleus/plugins/NucleusSegmentationAndAnalysisPlugin_.java +++ b/src/main/java/gred/nucleus/plugins/NucleusSegmentationAndAnalysisPlugin_.java @@ -10,7 +10,7 @@ /** * @author Tristan Dubos and Axel Poulet - * @deprecated Method to segment and analyse the nucleus on one image //TODO add a paramter in GUI to chose true or + * @deprecated Method to segment and analyse the nucleus on one image //TODO add a parameter in GUI to chose true or * false for the giftWrapping 3D */ public class NucleusSegmentationAndAnalysisPlugin_ implements PlugIn { diff --git a/src/main/java/gred/nucleus/plugins/NucleusSegmentationBatchPlugin_.java b/src/main/java/gred/nucleus/plugins/NucleusSegmentationBatchPlugin_.java index 81e608c7..29f717a7 100644 --- a/src/main/java/gred/nucleus/plugins/NucleusSegmentationBatchPlugin_.java +++ b/src/main/java/gred/nucleus/plugins/NucleusSegmentationBatchPlugin_.java @@ -39,12 +39,12 @@ public void run(String arg) { return; } try { - SegmentationCalling otsuModif = + SegmentationCalling otsuModified = new SegmentationCalling(_nucleusSegmentationBatchDialog.getRawDataDirectory(), _nucleusSegmentationBatchDialog.getWorkDirectory(), (short) _nucleusSegmentationBatchDialog.getMinVolume(), (short) _nucleusSegmentationBatchDialog.getMaxVolume()); - otsuModif.runOneImage(); + otsuModified.runOneImage(); } catch (Exception e) { e.printStackTrace(); } @@ -52,42 +52,50 @@ public void run(String arg) { } } - /** @return */ + + /** @return */ public int getNbCpu() { return _nucleusSegmentationBatchDialog.getNbCpu(); } - /** @return */ + + /** @return */ public double getZCalibration() { return _nucleusSegmentationBatchDialog.getZCalibration(); } - /** @return */ + + /** @return */ public double getXCalibration() { return _nucleusSegmentationBatchDialog.getXCalibration(); } - /** @return */ + + /** @return */ public double getYCalibration() { return _nucleusSegmentationBatchDialog.getYCalibration(); } - /** @return */ + + /** @return */ public String getUnit() { return _nucleusSegmentationBatchDialog.getUnit(); } - /** @return */ + + /** @return */ public double getMinVolume() { return _nucleusSegmentationBatchDialog.getMinVolume(); } - /** @return */ + + /** @return */ public double getMaxVolume() { return _nucleusSegmentationBatchDialog.getMaxVolume(); } - /** @return */ + + /** @return */ public String getWorkDirectory() { return _nucleusSegmentationBatchDialog.getWorkDirectory(); } diff --git a/src/main/java/gred/nucleus/plugins/PluginParameters.java b/src/main/java/gred/nucleus/plugins/PluginParameters.java index 0d70630d..dfd126a0 100644 --- a/src/main/java/gred/nucleus/plugins/PluginParameters.java +++ b/src/main/java/gred/nucleus/plugins/PluginParameters.java @@ -30,6 +30,7 @@ public class PluginParameters { public PluginParameters() { } + /** * Constructor with default parameter * @@ -45,6 +46,7 @@ public PluginParameters(String inputFolder, String outputFolder) { } + /** * Constructor with specific calibration in x y and z * @@ -66,6 +68,7 @@ public PluginParameters(String inputFolder, String outputFolder, double xCal, do } + /** * Constructor using input , output folders and config file (for command line execution) * @@ -82,13 +85,13 @@ public PluginParameters(String inputFolder, String outputFolder, String pathToCo } + public void addGeneralProperties(String pathToConfigFile) { Properties prop = new Properties(); - String fileName = pathToConfigFile; InputStream is = null; try { - is = new FileInputStream(fileName); + is = new FileInputStream(pathToConfigFile); } catch (FileNotFoundException ex) { System.err.println(pathToConfigFile + " : can't find the config file !"); System.exit(-1); @@ -100,18 +103,21 @@ public void addGeneralProperties(String pathToConfigFile) { System.exit(-1); } for (String idProp : prop.stringPropertyNames()) { - if (idProp.equals("xcal")) { - setXCal(Double.parseDouble(prop.getProperty("xcal"))); - } - if (idProp.equals("ycal")) { - setYCal(Double.parseDouble(prop.getProperty("ycal"))); - } - if (idProp.equals("zcal")) { - setZCal(Double.parseDouble(prop.getProperty("zcal"))); + switch (idProp) { + case "xCal": + setXCal(Double.parseDouble(prop.getProperty("xCal"))); + break; + case "yCal": + setYCal(Double.parseDouble(prop.getProperty("yCal"))); + break; + case "zCal": + setZCal(Double.parseDouble(prop.getProperty("zCal"))); + break; } } } + private void checkInputPaths(String inputFolder, String outputFolder) { File input = new File(inputFolder); if (input.isDirectory()) { @@ -140,6 +146,7 @@ public String getInputFolder() { return this.m_inputFolder; } + /** * Getter : output path * @@ -149,6 +156,7 @@ public String getOutputFolder() { return this.m_outputFolder; } + /** * Getter : HEADER parameter of the analyse containing path input output folder and x y z calibration on parameter * per line @@ -165,6 +173,7 @@ public String getAnalyseParameters() { } + /** * Getter : image x y z calibration * @@ -181,53 +190,62 @@ public String getInfoCalibration() { } + /** * get local time start analyse information yyyy-MM-dd:HH-mm-ss format * * @return time in yyyy-MM-dd:HH-mm-ss format */ public String getLocalTime() { - String timeStamp = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss").format(Calendar.getInstance().getTime()); - return timeStamp; + return new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss").format(Calendar.getInstance().getTime()); } + public double getVoxelVolume() { return this.m_xCal * this.m_yCal * this.m_zCal; } + public double getXCal() { return this.m_xCal; } - public void setXCal(double nanualXcal) { - this.m_xCal = nanualXcal; + + public void setXCal(double manualXCal) { + this.m_xCal = manualXCal; this.m_manualParameter = true; } + public double getYCal() { return this.m_yCal; } - public void setYCal(double nanualYcal) { - this.m_yCal = nanualYcal; + + public void setYCal(double manualYCal) { + this.m_yCal = manualYCal; this.m_manualParameter = true; } + public double getZCal() { return this.m_zCal; } - public void setZCal(double nanualZcal) { - this.m_zCal = nanualZcal; + + public void setZCal(double manualZCal) { + this.m_zCal = manualZCal; this.m_manualParameter = true; } + public boolean getManualParameter() { return this.m_manualParameter; } - public double getXcalibration(ImagePlus raw) { + + public double getXCalibration(ImagePlus raw) { double xCal; if (this.m_manualParameter) { xCal = this.getXCal(); @@ -238,7 +256,8 @@ public double getXcalibration(ImagePlus raw) { return xCal; } - public double getYcalibration(ImagePlus raw) { + + public double getYCalibration(ImagePlus raw) { double yCal; if (this.m_manualParameter) { yCal = this.getYCal(); @@ -248,7 +267,8 @@ public double getYcalibration(ImagePlus raw) { return yCal; } - public double getZcalibration(ImagePlus raw) { + + public double getZCalibration(ImagePlus raw) { double zCal; if (this.getManualParameter()) { zCal = this.getZCal(); @@ -257,5 +277,4 @@ public double getZcalibration(ImagePlus raw) { } return zCal; } - } diff --git a/src/main/java/gred/nucleus/plugins/Segmentation_.java b/src/main/java/gred/nucleus/plugins/Segmentation_.java index 190ac90d..9bb04868 100644 --- a/src/main/java/gred/nucleus/plugins/Segmentation_.java +++ b/src/main/java/gred/nucleus/plugins/Segmentation_.java @@ -13,14 +13,14 @@ public class Segmentation_ implements PlugIn { public static void segmentationFolder(String inputDirectory, String outputDirectory) throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(inputDirectory, outputDirectory); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { File file = new File(inputDirectory); String log = ""; if (file.isDirectory()) { - log = otsuModif.runSeveralImages2(); + log = otsuModified.runSeveralImages2(); } else if (file.isFile()) { - log = otsuModif.runOneImage(inputDirectory); + log = otsuModified.runOneImage(inputDirectory); } if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); @@ -30,18 +30,19 @@ public static void segmentationFolder(String inputDirectory, String outputDirect } } + public static void segmentationFolder(String inputDirectory, String outputDirectory, String config) throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(inputDirectory, outputDirectory, config); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { File file = new File(inputDirectory); String log = ""; if (file.isDirectory()) { - log = otsuModif.runSeveralImages2(); + log = otsuModified.runSeveralImages2(); } else if (file.isFile()) { - log = otsuModif.runOneImage(inputDirectory); + log = otsuModified.runOneImage(inputDirectory); } if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); @@ -51,6 +52,7 @@ public static void segmentationFolder(String inputDirectory, String outputDirect } } + public static void segmentationFolder(String inputDirectory, String outputDirectory, String minVolume, @@ -61,14 +63,14 @@ public static void segmentationFolder(String inputDirectory, Integer.parseInt(minVolume), Integer.parseInt(maxVolume), isGiftWrapping); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { File file = new File(inputDirectory); String log = ""; if (file.isDirectory()) { - log = otsuModif.runSeveralImages2(); + log = otsuModified.runSeveralImages2(); } else if (file.isFile()) { - log = otsuModif.runOneImage(inputDirectory); + log = otsuModified.runOneImage(inputDirectory); } if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); @@ -78,6 +80,7 @@ public static void segmentationFolder(String inputDirectory, } } + public static void segmentationFolder(String inputDirectory, String outputDirectory, String xCal, @@ -94,14 +97,14 @@ public static void segmentationFolder(String inputDirectory, segmentationParameters.setXCal(Integer.parseInt(xCal)); segmentationParameters.setYCal(Integer.parseInt(yCal)); segmentationParameters.setZCal(Integer.parseInt(zCal)); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { File file = new File(inputDirectory); String log = ""; if (file.isDirectory()) { - log = otsuModif.runSeveralImages2(); + log = otsuModified.runSeveralImages2(); } else if (file.isFile()) { - log = otsuModif.runOneImage(inputDirectory); + log = otsuModified.runOneImage(inputDirectory); } if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); @@ -111,6 +114,7 @@ public static void segmentationFolder(String inputDirectory, } } + /** * Run method for imageJ plugin for the segmentation * @@ -155,17 +159,17 @@ public void run(String arg) { } } else if (segmentationDialog.getConfigMode() == 1) { SegmentationConfigDialog scd = segmentationDialog.getSegmentationConfigFileDialog(); - if (scd.isCalibSelected()) { - IJ.log("w/ calib" + - "\nx: " + scd.getxCalibration() + - "\ny: " + scd.getyCalibration() + - "\nz: " + scd.getzCalibration()); + if (scd.isCalibrationSelected()) { + IJ.log("w/ calibration" + + "\nx: " + scd.getXCalibration() + + "\ny: " + scd.getYCalibration() + + "\nz: " + scd.getZCalibration()); segmentationFolder(input, output, - scd.getxCalibration(), scd.getyCalibration(), scd.getzCalibration(), + scd.getXCalibration(), scd.getYCalibration(), scd.getZCalibration(), scd.getMinVolume(), scd.getMaxVolume(), scd.getGiftWrapping() ); } else { - IJ.log("w/out calib"); + IJ.log("w/out calibration"); segmentationFolder(input, output, scd.getMinVolume(), scd.getMaxVolume(), scd.getGiftWrapping() ); diff --git a/src/main/java/gred/nucleus/plugins/computeParametersPlugin_.java b/src/main/java/gred/nucleus/plugins/computeParametersPlugin_.java index 0d75513d..774834f9 100644 --- a/src/main/java/gred/nucleus/plugins/computeParametersPlugin_.java +++ b/src/main/java/gred/nucleus/plugins/computeParametersPlugin_.java @@ -17,7 +17,6 @@ public void run(String arg) { } catch (InterruptedException e) { e.printStackTrace(); } - } try { if (_computeParametersDialog.isStart()) { @@ -38,11 +37,9 @@ public void run(String arg) { _computeParametersDialog.getWorkDirectory()); generateParameters.run(); } - } } catch (Exception e) { e.printStackTrace(); } } - } \ No newline at end of file diff --git a/src/main/java/gred/nucleus/segmentation/SegmentationCalling.java b/src/main/java/gred/nucleus/segmentation/SegmentationCalling.java index dcd313fc..59357047 100644 --- a/src/main/java/gred/nucleus/segmentation/SegmentationCalling.java +++ b/src/main/java/gred/nucleus/segmentation/SegmentationCalling.java @@ -27,9 +27,9 @@ /** - * This class call the different segmentation methods available to detect the nucleus. The Ostu method modified and the + * This class call the different segmentation methods available to detect the nucleus. The Otsu method modified and the * gift wrapping 3D. Methods can be call for analysis of several images or only one. The gift wrapping is initialized by - * teh Otsu method modified, then the gift wrapping algorithm process the result obtain with the first method. If the + * the Otsu method modified, then the gift wrapping algorithm process the result obtain with the first method. If the * first method doesn't detect a nucleus, a message is print on the console. *

* if the nucleus input image is 16bit, a preprocess is done to convert it in 8bit, and also increase the contrast and @@ -57,6 +57,7 @@ public class SegmentationCalling { public SegmentationCalling() { } + /** * Constructor for ImagePlus input * @@ -64,18 +65,19 @@ public SegmentationCalling() { */ public SegmentationCalling(SegmentationParameters segmentationParameters) { this.m_segmentationParameters = segmentationParameters; - this.m_outputCropGeneralInfoOTSU = this.m_segmentationParameters.getAnalyseParameters() + getColnameResult(); - this.m_outputCropGeneralInfoGIFT = this.m_segmentationParameters.getAnalyseParameters() + getColnameResult(); + this.m_outputCropGeneralInfoOTSU = this.m_segmentationParameters.getAnalyseParameters() + getResultsColumnNames(); + this.m_outputCropGeneralInfoGIFT = this.m_segmentationParameters.getAnalyseParameters() + getResultsColumnNames(); } public SegmentationCalling(String inputDir, String outputDir) { this._inputDir = inputDir; this._output = outputDir; - this.m_outputCropGeneralInfoOTSU = this.m_segmentationParameters.getAnalyseParameters() + getColnameResult(); - this.m_outputCropGeneralInfoGIFT = this.m_segmentationParameters.getAnalyseParameters() + getColnameResult(); + this.m_outputCropGeneralInfoOTSU = this.m_segmentationParameters.getAnalyseParameters() + getResultsColumnNames(); + this.m_outputCropGeneralInfoGIFT = this.m_segmentationParameters.getAnalyseParameters() + getResultsColumnNames(); } + /** * Constructor for ImagePlus input * @@ -91,6 +93,7 @@ public SegmentationCalling(ImagePlus img, short vMin, int vMax, String outputImg this._output = outputImg + File.separator + "Segmented" + this._imgInput.getTitle(); } + /** * Constructor for ImagePlus input * @@ -104,6 +107,7 @@ public SegmentationCalling(ImagePlus img, short vMin, int vMax) { this._imgInput = img; } + /** * Constructor for directory input * @@ -122,6 +126,7 @@ public SegmentationCalling(String inputDir, String outputDir, short vMin, int vM this._output = dirOutput.get_dirPath(); } + /** * @return ImagePlus the segmented nucleus * @@ -150,7 +155,7 @@ public int runOneImage() throws Exception { "and" + this.m_segmentationParameters.getM_maxVolumeNucleus()); } else { - System.out.println("otsu modif threshold: " + nucleusSegmentation.getBestThreshold() + "\n"); + System.out.println("otsu modified threshold: " + nucleusSegmentation.getBestThreshold() + "\n"); if (this.m_segmentationParameters.getGiftWrapping()) { ConvexHullSegmentation nuc = new ConvexHullSegmentation(); imgSeg = nuc.runGIFTWrapping(imgSeg, this.m_segmentationParameters); @@ -167,6 +172,7 @@ public int runOneImage() throws Exception { return nucleusSegmentation.getBestThreshold(); } + /** * getter of the image segmented * @@ -201,7 +207,7 @@ public String runSeveralImages2() throws Exception { File currentFile = directoryInput.getFile(i); String fileImg = currentFile.toString(); FilesNames outPutFilesNames = new FilesNames(fileImg); - this._prefix = outPutFilesNames.PrefixeNameFile(); + this._prefix = outPutFilesNames.prefixNameFile(); System.out.println("Current image in process " + currentFile); String timeStampStart = @@ -211,7 +217,7 @@ public String runSeveralImages2() throws Exception { NucleusSegmentation nucleusSegmentation = new NucleusSegmentation(currentFile, this._prefix, this.m_segmentationParameters); nucleusSegmentation.preProcessImage(); - nucleusSegmentation.findOTSUmaximisingSephericity(); + nucleusSegmentation.findOTSUMaximisingSphericity(); nucleusSegmentation.checkBadCrop(this.m_segmentationParameters.m_inputFolder); nucleusSegmentation.saveOTSUSegmented(); this.m_outputCropGeneralInfoOTSU = @@ -242,12 +248,13 @@ public String runSeveralImages2() throws Exception { return log; } + public String runOneImage(String filePath) throws Exception { String log = ""; File currentFile = new File(filePath); String fileImg = currentFile.toString(); FilesNames outPutFilesNames = new FilesNames(fileImg); - this._prefix = outPutFilesNames.PrefixeNameFile(); + this._prefix = outPutFilesNames.prefixNameFile(); System.out.println("Current image in process " + currentFile); String timeStampStart = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss").format(Calendar.getInstance().getTime()); @@ -255,7 +262,7 @@ public String runOneImage(String filePath) throws Exception { NucleusSegmentation nucleusSegmentation = new NucleusSegmentation(currentFile, this._prefix, this.m_segmentationParameters); nucleusSegmentation.preProcessImage(); - nucleusSegmentation.findOTSUmaximisingSephericity(); + nucleusSegmentation.findOTSUMaximisingSphericity(); nucleusSegmentation.checkBadCrop(this.m_segmentationParameters.m_inputFolder); nucleusSegmentation.saveOTSUSegmented(); this.m_outputCropGeneralInfoOTSU = @@ -269,6 +276,7 @@ public String runOneImage(String filePath) throws Exception { return log; } + public String runOneImageOmero(ImageContainer image, Long output, Client client) throws Exception { String log = ""; @@ -279,7 +287,7 @@ public String runOneImageOmero(ImageContainer image, Long output, Client client) System.out.println("Start :" + timeStampStart); NucleusSegmentation nucleusSegmentation = new NucleusSegmentation(image, this.m_segmentationParameters, client); nucleusSegmentation.preProcessImage(); - nucleusSegmentation.findOTSUmaximisingSephericity(); + nucleusSegmentation.findOTSUMaximisingSphericity(); nucleusSegmentation.checkBadCrop(image, client); nucleusSegmentation.saveOTSUSegmentedOmero(client, output); @@ -295,11 +303,12 @@ public String runOneImageOmero(ImageContainer image, Long output, Client client) return log; } + public String runSeveralImageOmero(List images, Long output, Client client) throws Exception { - String log = ""; + StringBuilder log = new StringBuilder(); for (ImageContainer image : images) { - log += runOneImageOmero(image, output, client); + log.append(runOneImageOmero(image, output, client)); } DatasetContainer dataset = client.getProject(output).getDatasets("OTSU").get(0); @@ -307,7 +316,7 @@ public String runSeveralImageOmero(List images, Long output, Cli String path = new java.io.File(".").getCanonicalPath() + dataset.getName() + "result_Segmentation_Analyse.csv"; OutputTexteFile resultFileOutputOTSU = new OutputTexteFile(path); - resultFileOutputOTSU.SaveTexteFile(this.m_outputCropGeneralInfoOTSU); + resultFileOutputOTSU.saveTextFile(this.m_outputCropGeneralInfoOTSU); File file = new File(path); dataset.addFile(client, file); @@ -316,14 +325,14 @@ public String runSeveralImageOmero(List images, Long output, Cli if (this.m_segmentationParameters.getGiftWrapping()) { dataset = client.getProject(output).getDatasets("GIFT").get(0); OutputTexteFile resultFileOutputGIFT = new OutputTexteFile(path); - resultFileOutputGIFT.SaveTexteFile(this.m_outputCropGeneralInfoGIFT); + resultFileOutputGIFT.saveTextFile(this.m_outputCropGeneralInfoGIFT); file = new File(path); dataset.addFile(client, file); file.delete(); } - return log; + return log.toString(); } @@ -347,7 +356,7 @@ public String runOneImageOmeroROI(ImageContainer image, Long output, Client clie NucleusSegmentation nucleusSegmentation = new NucleusSegmentation(image, roi, i, this.m_segmentationParameters, client); nucleusSegmentation.preProcessImage(); - nucleusSegmentation.findOTSUmaximisingSephericity(); + nucleusSegmentation.findOTSUMaximisingSphericity(); nucleusSegmentation.checkBadCrop(roi, client); @@ -369,7 +378,7 @@ public String runOneImageOmeroROI(ImageContainer image, Long output, Client clie String path = new java.io.File(".").getCanonicalPath() + "result_Segmentation_Analyse.csv"; OutputTexteFile resultFileOutputOTSU = new OutputTexteFile(path); - resultFileOutputOTSU.SaveTexteFile(this.m_outputCropGeneralInfoOTSU); + resultFileOutputOTSU.saveTextFile(this.m_outputCropGeneralInfoOTSU); File file = new File(path); dataset.addFile(client, file); @@ -378,7 +387,7 @@ public String runOneImageOmeroROI(ImageContainer image, Long output, Client clie if (this.m_segmentationParameters.getGiftWrapping()) { dataset = client.getProject(output).getDatasets("GIFT").get(0); OutputTexteFile resultFileOutputGIFT = new OutputTexteFile(path); - resultFileOutputGIFT.SaveTexteFile(this.m_outputCropGeneralInfoGIFT); + resultFileOutputGIFT.saveTextFile(this.m_outputCropGeneralInfoGIFT); file = new File(path); dataset.addFile(client, file); @@ -388,14 +397,15 @@ public String runOneImageOmeroROI(ImageContainer image, Long output, Client clie return log; } + public String runSeveralImageOmeroROI(List images, Long output, Client client) throws Exception { - String log = ""; + StringBuilder log = new StringBuilder(); for (ImageContainer image : images) { - log += runOneImageOmeroROI(image, output, client); + log.append(runOneImageOmeroROI(image, output, client)); } - return log; + return log.toString(); } @@ -410,8 +420,9 @@ private void saveFile(ImagePlus imagePlusInput, String pathFile) { fileSaver.saveAsTiffStack(pathFile); } + /** - * 16bits image preprocessing normalised the histohram distribution apply a gaussian filter to smooth the signal + * 16bits image preprocessing normalised the histogram distribution apply a gaussian filter to smooth the signal * convert the image in 8bits * * @param img 16bits ImagePlus @@ -429,7 +440,7 @@ private void preProcessImage(ImagePlus img) { } - public String getColnameResult() { + public String getResultsColumnNames() { return "NucleusFileName\t" + "Volume\t" + "Flatness\t" + diff --git a/src/main/java/gred/nucleus/segmentation/SegmentationParameters.java b/src/main/java/gred/nucleus/segmentation/SegmentationParameters.java index bb5f0949..0fe353ca 100644 --- a/src/main/java/gred/nucleus/segmentation/SegmentationParameters.java +++ b/src/main/java/gred/nucleus/segmentation/SegmentationParameters.java @@ -11,7 +11,7 @@ public class SegmentationParameters extends PluginParameters { /** GIFT wrapping option */ - boolean m_giftVrapping = true; + boolean m_giftWrapping = true; /** Minimal object volume to segment */ int m_minVolumeNucleus = 1; /** Maximal object volume to segment */ @@ -28,14 +28,16 @@ public SegmentationParameters(String inputFolder, String outputFolder) { super(inputFolder, outputFolder); } + public SegmentationParameters(String inputFolder, String outputFolder, int minVolume, int maxVolume, boolean gift) { super(inputFolder, outputFolder); this.m_minVolumeNucleus = minVolume; this.m_maxVolumeNucleus = maxVolume; - this.m_giftVrapping = gift; + this.m_giftWrapping = gift; } + public SegmentationParameters(String inputFolder, String outputFolder, int xCal, @@ -47,21 +49,22 @@ public SegmentationParameters(String inputFolder, super(inputFolder, outputFolder, xCal, yCal, zCal); this.m_minVolumeNucleus = minVolume; this.m_maxVolumeNucleus = maxVolume; - this.m_giftVrapping = gift; + this.m_giftWrapping = gift; } + public SegmentationParameters(String inputFolder, String outputFolder, String pathToConfigFile) { super(inputFolder, outputFolder, pathToConfigFile); addProperties(pathToConfigFile); } + public void addProperties(String pathToConfigFile) { Properties prop = new Properties(); - String fileName = pathToConfigFile; InputStream is = null; try { - is = new FileInputStream(fileName); + is = new FileInputStream(pathToConfigFile); } catch (FileNotFoundException ex) { System.err.println(pathToConfigFile + " : can't find the config file !"); System.exit(-1); @@ -74,7 +77,7 @@ public void addProperties(String pathToConfigFile) { } for (String idProp : prop.stringPropertyNames()) { if (idProp.equals("GiftWrapping")) { - this.m_giftVrapping = Boolean.parseBoolean(prop.getProperty("GiftWrapping")); + this.m_giftWrapping = Boolean.parseBoolean(prop.getProperty("GiftWrapping")); } if (idProp.equals("maxVolumeNucleus")) { this.m_maxVolumeNucleus = Integer.parseInt(prop.getProperty("maxVolumeNucleus")); @@ -85,10 +88,12 @@ public void addProperties(String pathToConfigFile) { } } + public void setMinVolumeNucleus(int vMin) { this.m_minVolumeNucleus = vMin; } + public void setMaxVolumeNucleus(int vMax) { this.m_maxVolumeNucleus = vMax; } @@ -102,16 +107,18 @@ public String getAnalyseParameters() { return this.m_headerInfo; } + public int getM_minVolumeNucleus() { return this.m_minVolumeNucleus; } + public int getM_maxVolumeNucleus() { return this.m_maxVolumeNucleus; } + public boolean getGiftWrapping() { - return this.m_giftVrapping; + return this.m_giftWrapping; } - } diff --git a/src/main/java/gred/nucleus/test/AutocropImageIntegration.java b/src/main/java/gred/nucleus/test/AutocropImageIntegration.java index f2aaf3c2..3c6ddb9d 100644 --- a/src/main/java/gred/nucleus/test/AutocropImageIntegration.java +++ b/src/main/java/gred/nucleus/test/AutocropImageIntegration.java @@ -10,22 +10,21 @@ public class AutocropImageIntegration { static ArrayList m_test; - public static void runAutoCrop(String imageSourceFile, String output, String pathToConfig) - throws Exception { + public static void runAutoCrop(String imageSourceFile, String output, String pathToConfig) { AutocropParameters autocropParameters = new AutocropParameters(imageSourceFile, output, pathToConfig); AutoCropCalling autoCrop = new AutoCropCalling(autocropParameters); autoCrop.runFolder(); } - public static void testStupid(String imageSourceFile, String output) - throws Exception { + + public static void testStupid(String imageSourceFile, String output) { AutocropParameters autocropParameters = new AutocropParameters(imageSourceFile, output); AutoCropCalling autoCrop = new AutoCropCalling(); autoCrop.runFolder(); } - public static void runAutoCrop(String imageSourceFile, String output) - throws Exception { + + public static void runAutoCrop(String imageSourceFile, String output) { //AutocropParameters autocropParameters= new AutocropParameters(imageSourceFile,output); AutocropParameters autocropParameters = new AutocropParameters(imageSourceFile, output, 40, 40, 20, 0, 20, 0, 1, 1000000000); @@ -33,12 +32,13 @@ public static void runAutoCrop(String imageSourceFile, String output) autoCrop.runFolder(); } + /** * Main function of the package's tests. * - * @param args + * @param args arguments */ - public static void main(String[] args) throws Exception { + public static void main(String[] args) { String pathToTest = "/home/tridubos/Bureau/IMAGES_TEST_CICD/AUTOCROP_IMAGES/AUTOCROP_RAW"; String pathToOutput = "/home/tridubos/Bureau/IMAGES_TEST_CICD/AUTOCROP"; @@ -67,7 +67,7 @@ public static void main(String[] args) throws Exception { //String outputTristan = "/home/tridubos/Bureau/TEST_AUTOCROP/out_test_Version"; //OutputFileVerification fw = new OutputFileVerification(); - //fw.GetFileResultExpeted(ExpectedResult); + //fw.GetFileResultExpected(ExpectedResult); //fw.GetFilesOutputFolder(outputTristan); //testStupid(inputOneImageTristan, outputTristan); @@ -102,6 +102,4 @@ public static void main(String[] args) throws Exception { System.out.println("Total memory (bytes): " + Runtime.getRuntime().totalMemory() * 1e-9); } - - } diff --git a/src/main/java/gred/nucleus/test/ImagesIntegrationTest.java b/src/main/java/gred/nucleus/test/ImagesIntegrationTest.java index ec991c47..fe8fab16 100644 --- a/src/main/java/gred/nucleus/test/ImagesIntegrationTest.java +++ b/src/main/java/gred/nucleus/test/ImagesIntegrationTest.java @@ -13,7 +13,7 @@ public static void main(String[] args) throws IOException, FormatException, file OutputFileVerification fw = new OutputFileVerification(); - fw.GetFileResultExpeted(ExpectedResult); + fw.GetFileResultExpected(ExpectedResult); fw.GetFilesOutputFolder(outputTristan); fw.GetFilesResultingOfAnalysis(outputTristan); fw.CompareAnalysisResult(); diff --git a/src/main/java/gred/nucleus/test/SegmentationImageIntegrationCheck.java b/src/main/java/gred/nucleus/test/SegmentationImageIntegrationCheck.java index f0eb09dc..f3eda179 100644 --- a/src/main/java/gred/nucleus/test/SegmentationImageIntegrationCheck.java +++ b/src/main/java/gred/nucleus/test/SegmentationImageIntegrationCheck.java @@ -19,19 +19,20 @@ public class SegmentationImageIntegrationCheck { /* public static void testStupid(ImagePlus img, short vMin, int vMax, String outputImgString ) throws FormatException { SegmentationParameters segmentationParameters = new SegmentationParameters(); - SegmentationCalling otsuModif = new SegmentationCalling(img, vMin, vMax, outputImgString); - otsuModif.runSeveralImages2(); + SegmentationCalling otsuModified = new SegmentationCalling(img, vMin, vMax, outputImgString); + otsuModified.runSeveralImages2(); } */ + /** * @param input * @param output */ public static void testStupidSeveralImages(String input, String output) throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(input, output); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { - String log = otsuModif.runSeveralImages2(); + String log = otsuModified.runSeveralImages2(); if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); } @@ -40,11 +41,12 @@ public static void testStupidSeveralImages(String input, String output) throws E } } + public static void testStupidSeveralImages(String input, String output, String config) throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(input, output, config); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { - String log = otsuModif.runSeveralImages2(); + String log = otsuModified.runSeveralImages2(); if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); } @@ -53,12 +55,13 @@ public static void testStupidSeveralImages(String input, String output, String c } } + /** * Main function of the package's tests. * * @param args */ - public static void main(String[] args) throws IOException { + public static void main(String[] args) { String pathToTest = "/home/tridubos/Bureau/IMAGES_TEST/SEGMENTATION_IMAGES/SEGMENTATION_VERIF"; String pathToExpected = "/home/tridubos/Bureau/IMAGES_TEST/SEGMENTATION_IMAGES/SEGMENTATION"; @@ -78,13 +81,11 @@ public static void main(String[] args) throws IOException { fw.CompareAnalysisResult(); /* OutputFileVerification fw = new OutputFileVerification(); - fw.GetFileResultExpeted(ExpectedResult); + fw.GetFileResultExpected(ExpectedResult); fw.GetFilesOutputFolder(outputTristan); fw.GetFilesResultingOfAnalysis(outputTristan); fw.CompareAnalysisResult(); */ System.err.println("The program ended normally."); } - - } diff --git a/src/main/java/gred/nucleus/test/SegmentationImagesIntegration.java b/src/main/java/gred/nucleus/test/SegmentationImagesIntegration.java index 2481f916..01c25bb2 100644 --- a/src/main/java/gred/nucleus/test/SegmentationImagesIntegration.java +++ b/src/main/java/gred/nucleus/test/SegmentationImagesIntegration.java @@ -16,19 +16,20 @@ public class SegmentationImagesIntegration { /* public static void testStupid(ImagePlus img, short vMin, int vMax, String outputImgString ) throws FormatException { SegmentationParameters segmentationParameters = new SegmentationParameters(); - SegmentationCalling otsuModif = new SegmentationCalling(img, vMin, vMax, outputImgString); - otsuModif.runSeveralImages2(); + SegmentationCalling otsuModified = new SegmentationCalling(img, vMin, vMax, outputImgString); + otsuModified.runSeveralImages2(); } */ + /** * @param input * @param output */ public static void testStupidSeveralImages(String input, String output) throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(input, output); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { - String log = otsuModif.runSeveralImages2(); + String log = otsuModified.runSeveralImages2(); if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); } @@ -37,11 +38,12 @@ public static void testStupidSeveralImages(String input, String output) throws E } } + public static void testStupidSeveralImages(String input, String output, String config) throws Exception { SegmentationParameters segmentationParameters = new SegmentationParameters(input, output, config); - SegmentationCalling otsuModif = new SegmentationCalling(segmentationParameters); + SegmentationCalling otsuModified = new SegmentationCalling(segmentationParameters); try { - String log = otsuModif.runSeveralImages2(); + String log = otsuModified.runSeveralImages2(); if (!(log.equals(""))) { System.out.println("Nuclei which didn't pass the segmentation\n" + log); } @@ -50,6 +52,7 @@ public static void testStupidSeveralImages(String input, String output, String c } } + /** * Main function of the package's tests. * @@ -71,7 +74,7 @@ public static void main(String[] args) throws Exception { /*fw.GetFilesResultingOfAnalysis(inputTristan); fw.CompareAnalysisResult(); OutputFileVerification fw = new OutputFileVerification(); - fw.GetFileResultExpeted(ExpectedResult); + fw.GetFileResultExpected(ExpectedResult); fw.GetFilesOutputFolder(outputTristan); fw.GetFilesResultingOfAnalysis(outputTristan); fw.CompareAnalysisResult(); diff --git a/src/main/java/gred/nucleus/utils/ComponentConnexe.java b/src/main/java/gred/nucleus/utils/ComponentConnexe.java index 1766497a..c97db0b2 100644 --- a/src/main/java/gred/nucleus/utils/ComponentConnexe.java +++ b/src/main/java/gred/nucleus/utils/ComponentConnexe.java @@ -8,13 +8,13 @@ public class ComponentConnexe { private String _axesName; /** - * Parcour de l'image pixel par pixel et recherche ces composantes connexes + * Iterates over the image pixels and look for these connected components * * @param labelIni */ void computeLabel(double labelIni) { int currentLabel = 2; - // Parcour des différents Pixels de l'images + // Iterate over the image pixels for (int i = 0; i < _image.length; ++i) { for (int j = 0; j < _image[i].length; ++j) { if (_image[i][j] == labelIni) { @@ -29,6 +29,7 @@ void computeLabel(double labelIni) { } } + /** * @param labelIni * @param voxelRecord @@ -53,82 +54,82 @@ private void breadthFirstSearch(double labelIni, VoxelRecord voxelRecord, int cu VoxelRecord voxel = new VoxelRecord(); voxel.setLocation(ii, jj, 0); voxelBoundary.add(0, voxel); - } else if (ii == 0) { - if (jj == 0) { - if (_image[ii][jj] == labelIni && - (_image[ii + 1][jj] == currentLabel || - _image[ii][jj + 1] == currentLabel)) { - _image[ii][jj] = currentLabel; - VoxelRecord voxel = new VoxelRecord(); - voxel.setLocation(ii, jj, 0); - voxelBoundary.add(0, voxel); - } else if (jj == _image[0].length - 1) { - if (_image[ii][jj] == labelIni && - (_image[ii + 1][jj] == currentLabel || - _image[ii][jj - 1] == currentLabel)) { - _image[ii][jj] = currentLabel; - VoxelRecord voxel = new VoxelRecord(); - voxel.setLocation(ii, jj, 0); - voxelBoundary.add(0, voxel); - } else if (_image[ii][jj] == labelIni && - (_image[ii + 1][jj] == currentLabel || - _image[ii][jj - 1] == currentLabel || - _image[ii][jj + 1] == currentLabel)) { - _image[ii][jj] = currentLabel; - VoxelRecord voxel = new VoxelRecord(); - voxel.setLocation(ii, jj, 0); - voxelBoundary.add(0, voxel); - } else if (ii == _image.length - 1) { - if (jj == 0) { - if (_image[ii][jj] == labelIni && - (_image[ii - 1][jj] == currentLabel || - _image[ii][jj + 1] == currentLabel)) { - _image[ii][jj] = currentLabel; - VoxelRecord voxel = new VoxelRecord(); - voxel.setLocation(ii, jj, 0); - voxelBoundary.add(0, voxel); - } else if (jj == _image[0].length - 1) { - if (_image[ii][jj] == labelIni && - (_image[ii - 1][jj] == currentLabel || - _image[ii][jj - 1] == currentLabel)) { - _image[ii][jj] = currentLabel; - VoxelRecord voxel = new VoxelRecord(); - voxel.setLocation(ii, jj, 0); - voxelBoundary.add(0, voxel); - } else if (_image[ii][jj] == labelIni && - (_image[ii - 1][jj] == currentLabel || - _image[ii][jj - 1] == currentLabel || - _image[ii][jj + 1] == currentLabel)) { - _image[ii][jj] = currentLabel; - VoxelRecord voxel = new VoxelRecord(); - voxel.setLocation(ii, jj, 0); - voxelBoundary.add(0, voxel); - } else if (jj == 0) { - if (_image[ii][jj] == labelIni && - (_image[ii - 1][jj] == currentLabel || - _image[ii + 1][jj] == currentLabel || - _image[ii][jj + 1] == currentLabel)) { - _image[ii][jj] = currentLabel; - VoxelRecord voxel = new VoxelRecord(); - voxel.setLocation(ii, jj, 0); - voxelBoundary.add(0, voxel); - } else if (jj == _image[0].length - 1 && - _image[ii][jj] == labelIni && - (_image[ii - 1][jj] == currentLabel || - _image[ii + 1][jj] == currentLabel || - _image[ii][jj - 1] == currentLabel)) { - _image[ii][jj] = currentLabel; - VoxelRecord voxel = new VoxelRecord(); - voxel.setLocation(ii, jj, 0); - voxelBoundary.add(0, voxel); - } - } - } - } - } - } + } + } else if (ii == 0) { + if (jj == 0) { + if (_image[ii][jj] == labelIni && + (_image[ii + 1][jj] == currentLabel || _image[ii][jj + 1] == currentLabel)) { + _image[ii][jj] = currentLabel; + VoxelRecord voxel = new VoxelRecord(); + voxel.setLocation(ii, jj, 0); + voxelBoundary.add(0, voxel); + } + } else if (jj == _image[0].length - 1) { + if (_image[ii][jj] == labelIni && + (_image[ii + 1][jj] == currentLabel || _image[ii][jj - 1] == currentLabel)) { + _image[ii][jj] = currentLabel; + VoxelRecord voxel = new VoxelRecord(); + voxel.setLocation(ii, jj, 0); + voxelBoundary.add(0, voxel); + } + } else { + if (_image[ii][jj] == labelIni && + (_image[ii + 1][jj] == currentLabel || + _image[ii][jj - 1] == currentLabel || + _image[ii][jj + 1] == currentLabel)) { + _image[ii][jj] = currentLabel; + VoxelRecord voxel = new VoxelRecord(); + voxel.setLocation(ii, jj, 0); + voxelBoundary.add(0, voxel); + } + } + } else if (ii == _image.length - 1) { + if (jj == 0) { + if (_image[ii][jj] == labelIni && + (_image[ii - 1][jj] == currentLabel || _image[ii][jj + 1] == currentLabel)) { + _image[ii][jj] = currentLabel; + VoxelRecord voxel = new VoxelRecord(); + voxel.setLocation(ii, jj, 0); + voxelBoundary.add(0, voxel); + } + } else if (jj == _image[0].length - 1) { + if (_image[ii][jj] == labelIni && + (_image[ii - 1][jj] == currentLabel || _image[ii][jj - 1] == currentLabel)) { + _image[ii][jj] = currentLabel; + VoxelRecord voxel = new VoxelRecord(); + voxel.setLocation(ii, jj, 0); + voxelBoundary.add(0, voxel); + } + } else { + if (_image[ii][jj] == labelIni && + (_image[ii - 1][jj] == currentLabel || + _image[ii][jj - 1] == currentLabel || + _image[ii][jj + 1] == currentLabel)) { + _image[ii][jj] = currentLabel; + VoxelRecord voxel = new VoxelRecord(); + voxel.setLocation(ii, jj, 0); + voxelBoundary.add(0, voxel); } } + } else if (jj == 0) { + if (_image[ii][jj] == labelIni && + (_image[ii - 1][jj] == currentLabel || + _image[ii + 1][jj] == currentLabel || + _image[ii][jj + 1] == currentLabel)) { + _image[ii][jj] = currentLabel; + VoxelRecord voxel = new VoxelRecord(); + voxel.setLocation(ii, jj, 0); + voxelBoundary.add(0, voxel); + } + } else if (jj == _image[0].length - 1 && + _image[ii][jj] == labelIni && + (_image[ii - 1][jj] == currentLabel || + _image[ii + 1][jj] == currentLabel || + _image[ii][jj - 1] == currentLabel)) { + _image[ii][jj] = currentLabel; + VoxelRecord voxel = new VoxelRecord(); + voxel.setLocation(ii, jj, 0); + voxelBoundary.add(0, voxel); } } } @@ -136,6 +137,7 @@ private void breadthFirstSearch(double labelIni, VoxelRecord voxelRecord, int cu } } + /** * @param label * @@ -214,6 +216,7 @@ private ArrayList detectVoxelBoundary(double label) { return lVoxelBoundary; } + /** * @param labelIni * @@ -224,29 +227,33 @@ public ArrayList getListLabel(double labelIni) { return _listLabel; } - /** @return */ + + /** @return */ public double[][] getImageTable() { return _image; } - /** @param _image */ + + /** @param _image */ public void setImageTable(double[][] _image) { this._image = _image; } + /** - * @param labelInitial + * @param initialLabel * @param voxelRecord * * @return */ - double[][] computeLabelOfOneObject(int labelInitial, VoxelRecord voxelRecord) { + double[][] computeLabelOfOneObject(int initialLabel, VoxelRecord voxelRecord) { int currentLabel = 2; // IJ.log(""+ getClass().getName()+" L-"+ new Exception().getStackTrace()[0].getLineNumber()+ " \nstart " +labelInitial+"\n j "+voxelRecord._j+"\n i "+voxelRecord._i+ " \n "+currentLabel+ "\n euu "+_image[(int)voxelRecord._i][(int)voxelRecord._j]+" end"); - breadthFirstSearch(labelInitial, voxelRecord, currentLabel); + breadthFirstSearch(initialLabel, voxelRecord, currentLabel); return _image; } + /** * @param label * diff --git a/src/main/java/gred/nucleus/utils/ConvexeHullDetection.java b/src/main/java/gred/nucleus/utils/ConvexeHullDetection.java index 547f25a2..dbb44b0a 100644 --- a/src/main/java/gred/nucleus/utils/ConvexeHullDetection.java +++ b/src/main/java/gred/nucleus/utils/ConvexeHullDetection.java @@ -72,8 +72,7 @@ public ArrayList findConvexeHull(double[][] image, double distanceThreshold) { double anglesSum = 0.0; int compteur = 0; - VoxelRecord voxelTest = new VoxelRecord(); - voxelTest = _p0; + VoxelRecord voxelTest = _p0; VoxelRecord voxelPrecedent = new VoxelRecord(); double xcal = calibration.pixelWidth; double ycal = calibration.pixelHeight; @@ -92,25 +91,29 @@ public ArrayList findConvexeHull(double[][] image, } for (int i = 0; i < lVoxelBoundary.size(); i++) { - //IJ.log("anglesSum " +lVoxelBoundary.get(i)._i + " "+lVoxelBoundary.get(i)._j + " "+lVoxelBoundary.get(i)._k + " "); + // IJ.log("anglesSum " +lVoxelBoundary.get(i)._i + " "+lVoxelBoundary.get(i)._j + " "+lVoxelBoundary.get(i)._k + " "); // IJ.log(""+ getClass().getName()+" L-"+ new Exception().getStackTrace()[0].getLineNumber()+" size "+lVoxelBoundary.size()+ " le i "+i); if (voxelTest.compareCoordinatesTo(lVoxelBoundary.get(i)) == 1) { VoxelRecord vectorCourant = new VoxelRecord(); vectorCourant.setLocation(lVoxelBoundary.get(i)._i - voxelTest._i, lVoxelBoundary.get(i)._j - voxelTest._j, lVoxelBoundary.get(i)._k - voxelTest._k); - if (_axesName == "xy") { - distance = Math.sqrt(vectorCourant._i * xcal * vectorCourant._i * xcal + - vectorCourant._j * ycal * vectorCourant._j * ycal); - } else if (_axesName == "xz") { - distance = Math.sqrt(vectorCourant._i * xcal * vectorCourant._i * xcal + - vectorCourant._k * zcal * vectorCourant._k * zcal); - } else if (_axesName == "yz") { - distance = Math.sqrt(vectorCourant._k * zcal * vectorCourant._k * zcal + - vectorCourant._j * ycal * vectorCourant._j * ycal); + switch (_axesName) { + case "xy": + distance = Math.sqrt(vectorCourant._i * xcal * vectorCourant._i * xcal + + vectorCourant._j * ycal * vectorCourant._j * ycal); + break; + case "xz": + distance = Math.sqrt(vectorCourant._i * xcal * vectorCourant._i * xcal + + vectorCourant._k * zcal * vectorCourant._k * zcal); + break; + case "yz": + distance = Math.sqrt(vectorCourant._k * zcal * vectorCourant._k * zcal + + vectorCourant._j * ycal * vectorCourant._j * ycal); + break; } - // IJ.log("distance " +distance+ " "+vectorCourant._i + " "+vectorCourant._k ); - // IJ.log("distance " + distance +"<="+ distanceThreshold); + // IJ.log("distance " +distance+ " "+vectorCourant._i + " "+vectorCourant._k ); + // IJ.log("distance " + distance +"<="+ distanceThreshold); if (distance <= distanceThreshold) { double angle = computeAngle(vectorTest, vectorCourant, calibration); double anglePlusPiSurDeux = angle - _pi / 2; @@ -133,7 +136,6 @@ public ArrayList findConvexeHull(double[][] image, iMin = i; } } - } } } @@ -168,6 +170,7 @@ public ArrayList findConvexeHull(double[][] image, return convexHull; } + /** * sweetsweet sun * @@ -190,21 +193,25 @@ public ArrayList findConvexeHull(double[][] image, double normesProduct = normeVector1 * normeVector2; double sinAlpha = 0, cosAlpha = 0; - if (_axesName == "xy") { - sinAlpha = ((vector1._i * xcal) * (vector2._j * ycal) - (vector1._j * ycal) * (vector2._i * xcal)) / - normesProduct; - cosAlpha = ((vector1._i * xcal) * (vector2._i * xcal) + (vector1._j * ycal) * (vector2._j * ycal)) / - normesProduct; - } else if (_axesName == "xz") { - sinAlpha = ((vector1._i * xcal) * (vector2._k * zcal) - (vector1._k * zcal) * (vector2._i * xcal)) / - normesProduct; - cosAlpha = ((vector1._i * xcal) * (vector2._i * xcal) + (vector1._k * zcal) * (vector2._k * zcal)) / - normesProduct; - } else if (_axesName == "yz") { - sinAlpha = ((vector1._j * ycal) * (vector2._k * zcal) - (vector1._k * zcal) * (vector2._j * ycal)) / - normesProduct; - cosAlpha = ((vector1._j * ycal) * (vector2._j * ycal) + (vector1._k * zcal) * (vector2._k * zcal)) / - normesProduct; + switch (_axesName) { + case "xy": + sinAlpha = ((vector1._i * xcal) * (vector2._j * ycal) - (vector1._j * ycal) * (vector2._i * xcal)) / + normesProduct; + cosAlpha = ((vector1._i * xcal) * (vector2._i * xcal) + (vector1._j * ycal) * (vector2._j * ycal)) / + normesProduct; + break; + case "xz": + sinAlpha = ((vector1._i * xcal) * (vector2._k * zcal) - (vector1._k * zcal) * (vector2._i * xcal)) / + normesProduct; + cosAlpha = ((vector1._i * xcal) * (vector2._i * xcal) + (vector1._k * zcal) * (vector2._k * zcal)) / + normesProduct; + break; + case "yz": + sinAlpha = ((vector1._j * ycal) * (vector2._k * zcal) - (vector1._k * zcal) * (vector2._j * ycal)) / + normesProduct; + cosAlpha = ((vector1._j * ycal) * (vector2._j * ycal) + (vector1._k * zcal) * (vector2._k * zcal)) / + normesProduct; + break; } if (cosAlpha > 1) { cosAlpha = 1; @@ -221,6 +228,7 @@ public ArrayList findConvexeHull(double[][] image, return alpha; } + /** * @param p * @param q @@ -233,16 +241,19 @@ int orientation(VoxelRecord p, VoxelRecord q, VoxelRecord r) { return Integer.signum(turn); } + /** @return */ public String getAxes() { return _axesName; } + /** @param axes */ public void setAxes(String axes) { _axesName = axes; } + /** @param voxelRecord */ public void setInitialVoxel(VoxelRecord voxelRecord) { _p0 = voxelRecord; @@ -278,10 +289,10 @@ private double angleThreshold(double[][] image, int nbPixelHeight = (int) (distance / calibration.pixelHeight); int x = (int) voxelRecord._i; int y = (int) voxelRecord._j; - if (_axesName == "xz") { + if (_axesName.equals("xz")) { y = (int) voxelRecord._k; nbPixelHeight = (int) (distance / calibration.pixelDepth); - } else if (_axesName == "yz") { + } else if (_axesName.equals("yz")) { x = (int) voxelRecord._j; y = (int) voxelRecord._k; nbPixelWidth = (int) (distance / calibration.pixelHeight); @@ -305,11 +316,11 @@ private double angleThreshold(double[][] image, vectorCourant.setLocation(record._i - nbPixelWidth, record._j - nbPixelHeight, 0); - if (_axesName == "xz") { + if (_axesName.equals("xz")) { vectorCourant.setLocation(record._i - nbPixelWidth, 0, record._k - nbPixelHeight); - } else if (_axesName == "yz") { + } else if (_axesName.equals("yz")) { vectorCourant.setLocation(0, record._j - nbPixelWidth, record._k - nbPixelHeight); @@ -326,6 +337,7 @@ private double angleThreshold(double[][] image, return angleMax; } + /** * @param image * @param nbPixelWidth diff --git a/src/main/java/gred/nucleus/utils/ConvexeHullImageMaker.java b/src/main/java/gred/nucleus/utils/ConvexeHullImageMaker.java index 295516eb..2cfc311c 100644 --- a/src/main/java/gred/nucleus/utils/ConvexeHullImageMaker.java +++ b/src/main/java/gred/nucleus/utils/ConvexeHullImageMaker.java @@ -21,7 +21,7 @@ public class ConvexeHullImageMaker { /** * */ - private final VoxelRecord _p0 = new VoxelRecord(); + private final VoxelRecord _p0 = new VoxelRecord(); /** * */ @@ -29,12 +29,12 @@ public class ConvexeHullImageMaker { /** * */ - private String _axesName = ""; + private String _axesName = ""; /** * */ - private Calibration _calibration; - private SegmentationParameters m_segmentationParameters; + private Calibration _calibration; + private SegmentationParameters m_segmentationParameters; /* Constructor * @see VoxelRecord @@ -62,13 +62,13 @@ public ImagePlus giftWrapping(ImagePlus imagePlusBinary, SegmentationParameters double equivalentSphericalRadius = (mesure3d.equivalentSphericalRadius(imagePlusBinary) / 2); VoxelRecord tVoxelRecord = mesure3d.computeBarycenter3D(false, imagePlusBinary, 255.0); ImagePlus imagePlusCorrected = new ImagePlus(); - int indice = 0, width = 0, height = 0; ImagePlus imagePlusBlack = new ImagePlus(); - if (_axesName == "xy") { + int indice, width, height; + if (_axesName.equals("xy")) { width = imagePlusBinary.getWidth(); height = imagePlusBinary.getHeight(); indice = imagePlusBinary.getNSlices(); - } else if (_axesName == "xz") { + } else if (_axesName.equals("xz")) { width = imagePlusBinary.getWidth(); height = imagePlusBinary.getNSlices(); indice = imagePlusBinary.getHeight(); @@ -118,6 +118,7 @@ public ImagePlus giftWrapping(ImagePlus imagePlusBinary, SegmentationParameters return imagePlusCorrected; } + /** * Determine l'ensemble des pixels "frontieres" et le plus extreme * @@ -136,15 +137,15 @@ ArrayList detectVoxelBoundary(double[][] image, double label, int i if (image[i][j] == label) { if (image[i - 1][j] == 0 || image[i + 1][j] == 0 || image[i][j - 1] == 0 || image[i][j + 1] == 0) { VoxelRecord voxelTest = new VoxelRecord(); - if (_axesName == "xy") { + if (_axesName.equals("xy")) { voxelTest.setLocation(i, j, indice); - } else if (_axesName == "xz") { + } else if (_axesName.equals("xz")) { voxelTest.setLocation(i, indice, j); } else { voxelTest.setLocation(indice, i, j); } lVoxelBoundary.add(voxelTest); - if (_axesName == "xy") { + if (_axesName.equals("xy")) { if (j > _p0._j) { _p0.setLocation(i, j, indice); } else if (j == _p0._j) { @@ -152,7 +153,7 @@ ArrayList detectVoxelBoundary(double[][] image, double label, int i _p0.setLocation(i, j, indice); } } - } else if (_axesName == "xz") { + } else if (_axesName.equals("xz")) { if (j > _p0._k) { _p0.setLocation(i, indice, j); } else if (j == _p0._k) { @@ -176,6 +177,7 @@ ArrayList detectVoxelBoundary(double[][] image, double label, int i return lVoxelBoundary; } + /** * @param lVoxelBoundary * @param width @@ -192,9 +194,9 @@ public ImagePlus imageMaker(double[][] image, ArrayList convexHull = new ArrayList<>(); convexHull.add(_p0); VoxelRecord vectorTest = new VoxelRecord(); - if (_axesName == "xy" || _axesName == "xz") { + if (_axesName.equals("xy") || _axesName.equals("xz")) { vectorTest.setLocation(-10, 0, 0); - } else if (_axesName == "yz") { + } else if (_axesName.equals("yz")) { vectorTest.setLocation(0, -10, 0); } @@ -207,10 +209,10 @@ public ImagePlus imageMaker(double[][] image, vectorTest, _calibration, equivalentSphericalRadius); - ImagePlus ip = makerPolygon(convexHull, width, height); - return ip; + return makePolygon(convexHull, width, height); } + /** * @param convexHull * @param width @@ -218,33 +220,41 @@ public ImagePlus imageMaker(double[][] image, * * @return */ - public ImagePlus makerPolygon(ArrayList convexHull, int width, int height) { + public ImagePlus makePolygon(ArrayList convexHull, int width, int height) { ImagePlus ip = new ImagePlus(); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); int[] tableWidth = new int[convexHull.size() + 1]; int[] tableHeight = new int[convexHull.size() + 1]; for (int i = 0; i < convexHull.size(); ++i) { - if (_axesName == "xy") { - tableWidth[i] = (int) convexHull.get(i)._i; - tableHeight[i] = (int) convexHull.get(i)._j; - } else if (_axesName == "xz") { - tableWidth[i] = (int) convexHull.get(i)._i; - tableHeight[i] = (int) convexHull.get(i)._k; - } else if (_axesName == "yz") { - tableWidth[i] = (int) convexHull.get(i)._j; - tableHeight[i] = (int) convexHull.get(i)._k; + switch (_axesName) { + case "xy": + tableWidth[i] = (int) convexHull.get(i)._i; + tableHeight[i] = (int) convexHull.get(i)._j; + break; + case "xz": + tableWidth[i] = (int) convexHull.get(i)._i; + tableHeight[i] = (int) convexHull.get(i)._k; + break; + case "yz": + tableWidth[i] = (int) convexHull.get(i)._j; + tableHeight[i] = (int) convexHull.get(i)._k; + break; } } - if (_axesName == "xy") { - tableWidth[convexHull.size()] = (int) convexHull.get(0)._i; - tableHeight[convexHull.size()] = (int) convexHull.get(0)._j; - } else if (_axesName == "xz") { - tableWidth[convexHull.size()] = (int) convexHull.get(0)._i; - tableHeight[convexHull.size()] = (int) convexHull.get(0)._k; - } else if (_axesName == "yz") { - tableWidth[convexHull.size()] = (int) convexHull.get(0)._j; - tableHeight[convexHull.size()] = (int) convexHull.get(0)._k; + switch (_axesName) { + case "xy": + tableWidth[convexHull.size()] = (int) convexHull.get(0)._i; + tableHeight[convexHull.size()] = (int) convexHull.get(0)._j; + break; + case "xz": + tableWidth[convexHull.size()] = (int) convexHull.get(0)._i; + tableHeight[convexHull.size()] = (int) convexHull.get(0)._k; + break; + case "yz": + tableWidth[convexHull.size()] = (int) convexHull.get(0)._j; + tableHeight[convexHull.size()] = (int) convexHull.get(0)._k; + break; } /* Polygon p = new Polygon(tableWidth, tableHeight,tableWidth.length ); @@ -261,6 +271,7 @@ public ImagePlus makerPolygon(ArrayList convexHull, int width, int return ip; } + /** * @param imagePlusInput stack * @param width @@ -274,9 +285,9 @@ public ImagePlus makerPolygon(ArrayList convexHull, int width, int double[][] image = new double[width][height]; for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { - if (_axesName == "xy") { + if (_axesName.equals("xy")) { image[i][j] = imageStackInput.getVoxel(i, j, indice); - } else if (_axesName == "xz") { + } else if (_axesName.equals("xz")) { image[i][j] = imageStackInput.getVoxel(i, indice, j); } else { image[i][j] = imageStackInput.getVoxel(indice, i, j); @@ -290,6 +301,7 @@ public ImagePlus makerPolygon(ArrayList convexHull, int width, int return image; } + /** * Return current combined axis analysing * @@ -299,6 +311,7 @@ public String getAxes() { return _axesName; } + /** * Set the current combined axis analysing * diff --git a/src/main/java/gred/nucleus/utils/Distance_Map.java b/src/main/java/gred/nucleus/utils/Distance_Map.java index a6de5a04..d21b7bd7 100644 --- a/src/main/java/gred/nucleus/utils/Distance_Map.java +++ b/src/main/java/gred/nucleus/utils/Distance_Map.java @@ -10,7 +10,7 @@ /* Bob Dougherty 8/8/2006 -Saito-Toriwaki algorithm for Euclidian Distance Transformation. +Saito-Toriwaki algorithm for Euclidean Distance Transformation. Direct application of Algorithm 1. Version S1A: lower memory usage. Version S1A.1 A fixed indexing bug for 666-bin data set @@ -19,7 +19,7 @@ Version S1B.1 Sept. 6, 2006. Changed comments. Version S1C Oct. 1, 2006. Option for inverse case. Fixed inverse behavior in y and z directions. -Version D July 30, 2007. Multithread processing for step 2. +Version D July 30, 2007. Multithreaded processing for step 2. This version assumes the input stack is already in memory, 8-bit, and outputs to a new 32-bit stack. Versions that are more stingy with memory @@ -67,6 +67,7 @@ public int setup(String arg, ImagePlus imp) { return DOES_8G; } + public void run(ImageProcessor ip) { apply(imp); } @@ -87,7 +88,7 @@ public void apply(ImagePlus imagePlus) { //Create references to input data data = new byte[d][]; for (int k = 0; k < d; k++) data[k] = (byte[]) stack.getPixels(k + 1); - //Create 32 bit floating point stack for output, s. Will also use it for g in Transormation 1. + //Create 32 bit floating point stack for output, s. Will also use it for g in Transformation 1. ImageStack sStack = new ImageStack(w, h); float[][] s = new float[d][]; for (int k = 0; k < d; k++) { @@ -151,7 +152,7 @@ public void apply(ImagePlus imagePlus) { } else { dist = (float) Math.sqrt(sk[ind]); sk[ind] = dist; - distMax = (dist > distMax) ? dist : distMax; + distMax = Math.max(dist, distMax); } } } @@ -192,6 +193,7 @@ public Step1Thread(int thread, int nThreads, int w, int h, int d, int thresh, fl this.s = s; } + public void run() { float[] sk; byte[] dk; @@ -236,7 +238,7 @@ public void run() { }//run }//Step1Thread - class Step2Thread extends Thread { + static class Step2Thread extends Thread { int thread, nThreads, w, h, d; float[][] s; @@ -249,6 +251,7 @@ public Step2Thread(int thread, int nThreads, int w, int h, int d, float[][] s) { this.s = s; } + public void run() { float[] sk; int n = w; @@ -302,6 +305,7 @@ public Step3Thread(int thread, int nThreads, int w, int h, int d, float[][] s, b this.data = data; } + public void run() { int zStart, zStop, zBegin, zEnd; @SuppressWarnings("unused") diff --git a/src/main/java/gred/nucleus/utils/FileList.java b/src/main/java/gred/nucleus/utils/FileList.java index fb4f6667..3204e439 100644 --- a/src/main/java/gred/nucleus/utils/FileList.java +++ b/src/main/java/gred/nucleus/utils/FileList.java @@ -1,230 +1,239 @@ -package gred.nucleus.utils; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; - -/** - * @author Tristan Dubos and Axel Poulet - *

- * Several method on the file - */ -public class FileList { - boolean _windows = false; - - /** - * - */ - public FileList() { - _windows = System.getProperty("os.name").startsWith("Windows"); - } - - /** - * run the methods to list all the file in one input directory - * - * @param repertoire - * - * @return Liste of file - */ - public File[] run(String repertoire) { - return repertoryFileList(repertoire); - } - - /** - * method to list all the file in one input directory - * - * @param directory - * - * @return list file - */ - public File[] repertoryFileList(String directory) { - File directoryToScan = new File(directory); - File[] tFileDirectory = null; - tFileDirectory = directoryToScan.listFiles(); - for (int i = 0; i < tFileDirectory.length; ++i) { - if (tFileDirectory[i].isDirectory()) { - File[] tTempBeforeElement = stockFileBefore(i, tFileDirectory); - File[] tTempAfterElement = stockFileAfter(i, tFileDirectory); - File[] tTempFile = repertoryFileList(tFileDirectory[i].toString()); - if (tTempFile.length != 0) { - tFileDirectory = this.resize(tTempBeforeElement, tTempAfterElement, tTempFile, i); - } - } - } - return tFileDirectory; - } - - /** - * methode to list on subdirectory - * - * @param tTempBeforeElement - * @param tTempAfterElement - * @param tTempFile - * @param indiceMax - * - * @return - */ - public File[] resize(File[] tTempBeforeElement, File[] tTempAfterElement, File[] tTempFile, int indiceMax) { - File[] tFile = new File[tTempBeforeElement.length + tTempFile.length + tTempAfterElement.length - 1]; - //element insertion in the file list - for (int j = 0; j < tFile.length; ++j) { - //list file before the directory : - if (j < indiceMax) { - tFile[j] = tTempBeforeElement[j]; - } - //listed file in the directory : - else { - if (j < indiceMax + tTempFile.length) { - tFile[j] = tTempFile[j - indiceMax]; - } - //listed files after directory : - else { - tFile[j] = tTempAfterElement[j - indiceMax - tTempFile.length]; - } - } - } - return tFile; - } - - /** - * @param indiceMax - * @param tFile - * - * @return - */ - public File[] stockFileBefore(int indiceMax, File[] tFile) { - File[] tTempBeforeElement = new File[indiceMax]; - if (indiceMax >= 0) System.arraycopy(tFile, 0, tTempBeforeElement, 0, indiceMax); - return tTempBeforeElement; - } - - /** - * @param indiceMax - * @param tFile - * - * @return - */ - public File[] stockFileAfter(int indiceMax, File[] tFile) { - File[] tTempAfterElement = new File[tFile.length - indiceMax]; - int j = 0; - for (int k = (indiceMax + 1); k < tFile.length; ++k) { - tTempAfterElement[j] = tFile[k]; - ++j; - } - return tTempAfterElement; - } - - /** - * @param filePathway - * @param tableFile - * - * @return - */ - public boolean isInDirectory(String filePathway, File[] tableFile) { - boolean testFile = false; - for (File file : tableFile) { - if (file.toString().equals(filePathway)) { - testFile = true; - break; - } - } - return testFile; - } - - /** - * @param regex - * @param tFile - * - * @return - */ - public String fileSearch(String regex, File[] tFile) { - if (_windows) { - String as = "\\"; - String das = "\\\\"; - regex = regex.replace(as, das); - } - String file = null; - for (File value : tFile) { - if (value.toString().matches((regex))) { - file = value.toString(); - break; - } - } - return file; - } - - - /** - * @param regex - * @param tFile - * - * @return - */ - public boolean isDirectoryOrFileExist(String regex, File[] tFile) { - if (_windows) { - String as = "\\"; - String das = "\\\\"; - regex = regex.replace(as, das); - } - boolean testFile = false; - for (File file : tFile) { - if (file.toString().matches((regex))) { - testFile = true; - break; - } - } - return testFile; - } - - - /** - * @param directory - * @param tFile - * - * @return - */ - public String[] getDirectoryFiles(String directory, File[] tFile) { - String[] tRef = directory.split("\\" + File.separator); - String[] tTemp = new String[0]; - ArrayList arrayList = new ArrayList<>(); - HashMap hasMapDirectory = new HashMap<>(); - for (File file : tFile) { - String[] temp = file.toString().split("\\" + File.separator); - if (temp.length > tRef.length + 1) { - if (!hasMapDirectory.containsKey(temp[tRef.length])) { - hasMapDirectory.put(temp[tRef.length], 1); - arrayList.add(temp[tRef.length]); - } - } - } - if (arrayList.size() > 0) { - tTemp = new String[arrayList.size()]; - for (int i = 0; i < arrayList.size(); ++i) { - tTemp[i] = arrayList.get(i); - } - } - return tTemp; - } - - - /** - * @param regex - * @param tFile - * - * @return - */ - public ArrayList fileSearchList(String regex, File[] tFile) { - if (_windows) { - String as = "\\"; - String das = "\\\\"; - regex = regex.replace(as, das); - } - ArrayList arrayListFile = new ArrayList<>(); - for (File file : tFile) { - if (file.toString().matches((regex))) { - arrayListFile.add(file.toString()); - } - } - return arrayListFile; - } +package gred.nucleus.utils; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Objects; +import java.util.regex.Pattern; + +/** + * @author Tristan Dubos and Axel Poulet + *

+ * Several method on the file + */ +public class FileList { + boolean _windows; + + /** + * + */ + public FileList() { + _windows = System.getProperty("os.name").startsWith("Windows"); + } + + + /** + * run the methods to list all the files in one input directory + * + * @param directory input directory + * + * @return List of files + */ + public File[] run(String directory) { + return repertoryFileList(directory); + } + + + /** + * method to list all the files in one input directory + * + * @param directory input directory + * + * @return list file + */ + public File[] repertoryFileList(String directory) { + File directoryToScan = new File(directory); + File[] tFileDirectory; + tFileDirectory = directoryToScan.listFiles(); + for (int i = 0; i < Objects.requireNonNull(tFileDirectory).length; ++i) { + if (tFileDirectory[i].isDirectory()) { + File[] tTempBeforeElement = stockFileBefore(i, tFileDirectory); + File[] tTempAfterElement = stockFileAfter(i, tFileDirectory); + File[] tTempFile = repertoryFileList(tFileDirectory[i].toString()); + if (tTempFile.length != 0) { + tFileDirectory = this.resize(tTempBeforeElement, tTempAfterElement, tTempFile, i); + } + } + } + return tFileDirectory; + } + + + /** + * methode to list on subdirectory + * + * @param tTempBeforeElement + * @param tTempAfterElement + * @param tTempFile + * @param indexMax + * + * @return + */ + public File[] resize(File[] tTempBeforeElement, File[] tTempAfterElement, File[] tTempFile, int indexMax) { + File[] tFile = new File[tTempBeforeElement.length + tTempFile.length + tTempAfterElement.length - 1]; + //element insertion in the file list + for (int j = 0; j < tFile.length; ++j) { + //list file before the directory : + if (j < indexMax) { + tFile[j] = tTempBeforeElement[j]; + } + //listed file in the directory : + else { + if (j < indexMax + tTempFile.length) { + tFile[j] = tTempFile[j - indexMax]; + } + //listed files after directory : + else { + tFile[j] = tTempAfterElement[j - indexMax - tTempFile.length]; + } + } + } + return tFile; + } + + + /** + * @param indexMax + * @param tFile + * + * @return + */ + public File[] stockFileBefore(int indexMax, File[] tFile) { + File[] tTempBeforeElement = new File[indexMax]; + if (indexMax >= 0) System.arraycopy(tFile, 0, tTempBeforeElement, 0, indexMax); + return tTempBeforeElement; + } + + + /** + * @param indexMax + * @param tFile + * + * @return + */ + public File[] stockFileAfter(int indexMax, File[] tFile) { + File[] tTempAfterElement = new File[tFile.length - indexMax]; + int j = 0; + for (int k = (indexMax + 1); k < tFile.length; ++k) { + tTempAfterElement[j] = tFile[k]; + ++j; + } + return tTempAfterElement; + } + + + /** + * @param filePathway + * @param tableFile + * + * @return + */ + public boolean isInDirectory(String filePathway, File[] tableFile) { + boolean testFile = false; + for (File file : tableFile) { + if (file.toString().equals(filePathway)) { + testFile = true; + break; + } + } + return testFile; + } + + + /** + * @param regex + * @param tFile + * + * @return + */ + public String fileSearch(String regex, File[] tFile) { + if (_windows) { + String as = "\\"; + String das = "\\\\"; + regex = regex.replace(as, das); + } + String file = null; + for (File value : tFile) { + if (value.toString().matches((regex))) { + file = value.toString(); + break; + } + } + return file; + } + + + /** + * @param regex + * @param tFile + * + * @return + */ + public boolean isDirectoryOrFileExist(String regex, File[] tFile) { + if (_windows) { + String as = "\\"; + String das = "\\\\"; + regex = regex.replace(as, das); + } + boolean testFile = false; + for (File file : tFile) { + if (file.toString().matches((regex))) { + testFile = true; + break; + } + } + return testFile; + } + + + /** + * @param directory + * @param tFile + * + * @return + */ + public String[] getDirectoryFiles(String directory, File[] tFile) { + String[] tRef = directory.split(Pattern.quote(File.separator)); + String[] tTemp = new String[0]; + ArrayList arrayList = new ArrayList<>(); + HashMap hasMapDirectory = new HashMap<>(); + for (File file : tFile) { + String[] temp = file.toString().split(Pattern.quote(File.separator)); + if (temp.length > tRef.length + 1) { + if (!hasMapDirectory.containsKey(temp[tRef.length])) { + hasMapDirectory.put(temp[tRef.length], 1); + arrayList.add(temp[tRef.length]); + } + } + } + if (arrayList.size() > 0) { + tTemp = new String[arrayList.size()]; + for (int i = 0; i < arrayList.size(); ++i) { + tTemp[i] = arrayList.get(i); + } + } + return tTemp; + } + + + /** + * @param regex + * @param tFile + * + * @return + */ + public ArrayList fileSearchList(String regex, File[] tFile) { + if (_windows) { + String as = "\\"; + String das = "\\\\"; + regex = regex.replace(as, das); + } + ArrayList arrayListFile = new ArrayList<>(); + for (File file : tFile) { + if (file.toString().matches(regex)) { + arrayListFile.add(file.toString()); + } + } + return arrayListFile; + } } \ No newline at end of file diff --git a/src/main/java/gred/nucleus/utils/FillingHoles.java b/src/main/java/gred/nucleus/utils/FillingHoles.java index 82af39ca..b81ea697 100644 --- a/src/main/java/gred/nucleus/utils/FillingHoles.java +++ b/src/main/java/gred/nucleus/utils/FillingHoles.java @@ -15,6 +15,7 @@ public class FillingHoles { public FillingHoles() { } + /** Method which process the image in the three dimensions (x, y, z) in the same time. */ public ImagePlus apply3D(ImagePlus imagePlusInput) { // image inversion (0 became 255 and 255 became 0) @@ -36,9 +37,6 @@ public ImagePlus apply3D(ImagePlus imagePlusInput) { int label; boolean[] tEdgeFlags = new boolean[(int) imagePlusCorrected.getStatistics().max + 1]; imageStackCorrected = imagePlusCorrected.getImageStack(); - for (int a = 0; a < tEdgeFlags.length; ++a) { - tEdgeFlags[a] = false; - } // Analyse of plans extreme in the dim x for (int k = 0; k < imageStackCorrected.getSize(); ++k) { for (int j = 0; j < imageStackCorrected.getHeight(); ++j) { @@ -95,49 +93,46 @@ public ImagePlus apply2D(ImagePlus imagePlusInput) { ImageStack imageStackOutput = new ImageStack(imageStackCorrected.getWidth(), imageStackCorrected.getHeight()); for (int k = 1; k <= imageStackCorrected.getSize(); ++k) { - ImageProcessor imageProcessorLabellised = imageStackCorrected.getProcessor(k); + ImageProcessor imageProcessorLabeled = imageStackCorrected.getProcessor(k); for (int i = 0; i < imageStackCorrected.getWidth(); ++i) { for (int j = 0; j < imageStackCorrected.getHeight(); ++j) { - voxelValue = imageProcessorLabellised.getPixel(i, j); + voxelValue = imageProcessorLabeled.getPixel(i, j); if (voxelValue > 0) { - imageProcessorLabellised.putPixelValue(i, j, 0); + imageProcessorLabeled.putPixelValue(i, j, 0); } else { - imageProcessorLabellised.putPixelValue(i, j, 255); + imageProcessorLabeled.putPixelValue(i, j, 255); } } } - imageProcessorLabellised = BinaryImages.componentsLabeling(imageProcessorLabellised, 26, 32); + imageProcessorLabeled = BinaryImages.componentsLabeling(imageProcessorLabeled, 26, 32); int label; - boolean[] tEdgeFlags = new boolean[(int) imageProcessorLabellised.getMax() + 1]; - for (int a = 0; a < tEdgeFlags.length; ++a) { - tEdgeFlags[a] = false; - } - // Analyse des plans extremes selon la dim x + boolean[] tEdgeFlags = new boolean[(int) imageProcessorLabeled.getMax() + 1]; + // Analysis of extreme plans along x axis for (int j = 0; j < imageStackCorrected.getHeight(); ++j) { - label = (int) imageProcessorLabellised.getf(0, j); + label = (int) imageProcessorLabeled.getf(0, j); tEdgeFlags[label] = true; - label = (int) imageProcessorLabellised.getf(imageStackCorrected.getWidth() - 1, j); + label = (int) imageProcessorLabeled.getf(imageStackCorrected.getWidth() - 1, j); tEdgeFlags[label] = true; } - // Analyse des plans extremes selon la dim y + // Analysis of extreme plans along y axis for (int i = 0; i < imageStackCorrected.getWidth(); ++i) { - label = (int) imageProcessorLabellised.getf(i, 0); + label = (int) imageProcessorLabeled.getf(i, 0); tEdgeFlags[label] = true; - label = (int) imageProcessorLabellised.getf(i, imageStackCorrected.getHeight() - 1); + label = (int) imageProcessorLabeled.getf(i, imageStackCorrected.getHeight() - 1); tEdgeFlags[label] = true; } for (int i = 0; i < imageStackCorrected.getWidth(); ++i) { for (int j = 0; j < imageStackCorrected.getHeight(); ++j) { - label = (int) imageProcessorLabellised.getf(i, j); + label = (int) imageProcessorLabeled.getf(i, j); if (label == 0 || !tEdgeFlags[label]) { - imageProcessorLabellised.putPixelValue(i, j, 255); + imageProcessorLabeled.putPixelValue(i, j, 255); } else { - imageProcessorLabellised.putPixelValue(i, j, 0); + imageProcessorLabeled.putPixelValue(i, j, 0); } } } - imageStackOutput.addSlice(imageProcessorLabellised); + imageStackOutput.addSlice(imageProcessorLabeled); } imagePlusCorrected.setStack(imageStackOutput); StackConverter stackConverter = new StackConverter(imagePlusCorrected); diff --git a/src/main/java/gred/nucleus/utils/Gradient.java b/src/main/java/gred/nucleus/utils/Gradient.java index 7997dffe..e666c469 100644 --- a/src/main/java/gred/nucleus/utils/Gradient.java +++ b/src/main/java/gred/nucleus/utils/Gradient.java @@ -15,7 +15,7 @@ public class Gradient { /** * */ - private ArrayList[][][] _tableUnitaire; + private ArrayList[][][] _tableUnitary; @SuppressWarnings("unchecked") public Gradient(ImagePlus imagePlusInput) { @@ -23,10 +23,11 @@ public Gradient(ImagePlus imagePlusInput) { int h = imagePlusInput.getHeight(); int d = imagePlusInput.getStackSize(); _tableGradient = (ArrayList[][][]) new ArrayList[w][h][d]; - _tableUnitaire = (ArrayList[][][]) new ArrayList[w][h][d]; + _tableUnitary = (ArrayList[][][]) new ArrayList[w][h][d]; computeGradient(imagePlusInput); } + /** * @param imagePlusInput * @@ -58,30 +59,32 @@ private void computeGradient(ImagePlus imagePlusInput) { list.add(dy); list.add(dz); _tableGradient[i][j][k] = list; - /*variable intermediaire*/ - double norme = Math.sqrt(dx * dx + dy * dy + dz * dz); + /* temp variable */ + double norm = Math.sqrt(dx * dx + dy * dy + dz * dz); double nx = 0, ny = 0, nz = 0; - if (norme > 1e-15) { - nx = dx / norme; - ny = dy / norme; - nz = dz / norme; + if (norm > 1e-15) { + nx = dx / norm; + ny = dy / norm; + nz = dz / norm; } ArrayList listN = new ArrayList<>(); listN.add(nx); listN.add(ny); listN.add(nz); - _tableUnitaire[i][j][k] = listN; + _tableUnitary[i][j][k] = listN; } } } // IJ.log("fin Gradient"); } + /** @return */ - public ArrayList[][][] getUnitaire() { - return _tableUnitaire; + public ArrayList[][][] getUnitary() { + return _tableUnitary; } + /** @return */ public ArrayList[][][] getGradient() { return _tableGradient; diff --git a/src/main/java/gred/nucleus/utils/Histogram.java b/src/main/java/gred/nucleus/utils/Histogram.java index a4db210c..63d36194 100644 --- a/src/main/java/gred/nucleus/utils/Histogram.java +++ b/src/main/java/gred/nucleus/utils/Histogram.java @@ -12,7 +12,7 @@ * @author Tristan Dubos and Axel Poulet */ public class Histogram { - /** HashMap which stock the diffents value voxel and the number of voxel for each value present on the image */ + /** HashMap which stock the different values of voxels and the number of voxels for each value present on the image */ private final HashMap _hHistogram = new HashMap<>(); /** All the value present on the image */ private double[] _label; @@ -31,7 +31,8 @@ public class Histogram { public Histogram() { } - /** @param imagePlusInput */ + + /** @param imagePlusInput */ public void run(ImagePlus imagePlusInput) { Object[] tTemp = computeHistogram(imagePlusInput).keySet().toArray(); _label = new double[tTemp.length]; @@ -44,6 +45,7 @@ public void run(ImagePlus imagePlusInput) { } } + /** * this method return a Histogram of the image input in hashMap form * @@ -74,6 +76,7 @@ private HashMap computeHistogram(ImagePlus imagePlusInput) { return _hHistogram; } + /** * this method return a double table which contain the all the value voxel present on the input image * @@ -83,17 +86,20 @@ public double[] getLabels() { return _label; } - /** @return */ + + /** @return */ public HashMap getHistogram() { return _hHistogram; } - /** @return */ + + /** @return */ public double getLabelMax() { return _labelMax; } - /** @return */ + + /** @return */ public int getNbLabels() { return _nbLabel; } diff --git a/src/main/java/gred/nucleus/utils/RegionalExtremaFilter.java b/src/main/java/gred/nucleus/utils/RegionalExtremaFilter.java index 8d26fc29..a4316d19 100644 --- a/src/main/java/gred/nucleus/utils/RegionalExtremaFilter.java +++ b/src/main/java/gred/nucleus/utils/RegionalExtremaFilter.java @@ -28,6 +28,7 @@ public int setup(String arg, ImagePlus imagePlusInput) { return 0; } + /** * To run the plugin with imageJ * @@ -37,6 +38,7 @@ public void run(ImageProcessor imageProcessor) { applyWithMask(_imagePlusInput); } + /** * Method used to scan the deconvolved image, and the image having undergone the filter min in the binary mask of * nucleus. For each voxel, the user can determine if the voxel value is a minima or belong to a minima region. All @@ -51,9 +53,9 @@ public ImagePlus applyWithMask(ImagePlus imagePlusInput) { double width = _imagePlusInput.getWidth(); double height = _imagePlusInput.getHeight(); double depth = _imagePlusInput.getStackSize(); - int kcurrent; - int icurrent; - int jcurrent; + int kCurrent; + int iCurrent; + int jCurrent; int ii; int jj; int kk; @@ -74,12 +76,12 @@ public ImagePlus applyWithMask(ImagePlus imagePlusInput) { arrayListVoxel.add(voxelRecord); while (arrayListVoxel.size() > 0) { voxelRecord = arrayListVoxel.remove(0); - icurrent = (int) voxelRecord.getI(); - jcurrent = (int) voxelRecord.getJ(); - kcurrent = (int) voxelRecord.getK(); - for (kk = kcurrent - 1; kk <= kcurrent + 1; ++kk) { - for (ii = icurrent - 1; ii <= icurrent + 1; ++ii) { - for (jj = jcurrent - 1; jj <= jcurrent + 1; ++jj) { + iCurrent = (int) voxelRecord.getI(); + jCurrent = (int) voxelRecord.getJ(); + kCurrent = (int) voxelRecord.getK(); + for (kk = kCurrent - 1; kk <= kCurrent + 1; ++kk) { + for (ii = iCurrent - 1; ii <= iCurrent + 1; ++ii) { + for (jj = jCurrent - 1; jj <= jCurrent + 1; ++jj) { if (kk >= 0 && kk < depth && ii >= 0 && @@ -121,6 +123,7 @@ public void computeImageMoreOne() { } } + /** Filter minimum in 3D with a neighboring 3 */ void filterMin3DWithMask() { @@ -160,6 +163,7 @@ void filterMin3DWithMask() { } } + /** * Initialise a matrix of a binary mask to search the minima regions in the mask * @@ -169,21 +173,22 @@ public void setMask(double[][][] tab) { _tabMask = tab; } + /** * Initialise a matrix of a binary mask to search the minima regions in the mask * * @param imagePlusEntree Binary image */ public void setMask(ImagePlus imagePlusEntree) { - ImageStack imagePluslabel = imagePlusEntree.getStack(); - final int size1 = imagePluslabel.getWidth(); - final int size2 = imagePluslabel.getHeight(); - final int size3 = imagePluslabel.getSize(); + ImageStack imagePlusLabel = imagePlusEntree.getStack(); + final int size1 = imagePlusLabel.getWidth(); + final int size2 = imagePlusLabel.getHeight(); + final int size3 = imagePlusLabel.getSize(); _tabMask = new double[size1][size2][size3]; for (int i = 0; i < size1; ++i) { for (int j = 0; j < size2; ++j) { for (int k = 0; k < size3; ++k) { - _tabMask[i][j][k] = imagePluslabel.getVoxel(i, j, k); + _tabMask[i][j][k] = imagePlusLabel.getVoxel(i, j, k); } } } diff --git a/src/main/java/gred/nucleus/utils/Voxel.java b/src/main/java/gred/nucleus/utils/Voxel.java index 0f8cffad..4a2fb31b 100644 --- a/src/main/java/gred/nucleus/utils/Voxel.java +++ b/src/main/java/gred/nucleus/utils/Voxel.java @@ -43,6 +43,7 @@ public Voxel(short x, short y, short z) { this.m_coordinates[2] = z; } + /** * Constructor from given coordinates * @@ -58,6 +59,7 @@ public Voxel(short x, short y, short z, short value) { this.m_value = value; } + /** * Constructor * @@ -65,12 +67,13 @@ public Voxel(short x, short y, short z, short value) { * @param y second coordinate of the voxel * @param z third coordinate of the voxel */ - public void setCoordinates(short x, short y, short z) { + public void setCoordinate(short x, short y, short z) { this.m_coordinates[0] = x; this.m_coordinates[1] = y; this.m_coordinates[2] = z; } + /** * Override of the clone operation * @@ -81,38 +84,42 @@ protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } + /** * Increments the i^th coordinates of a voxel, with i = 0, 1 or 2 * * @param i the coordinate's index (0, 1 or 2) */ - public void incrementCoord(int i) { + public void incrementCoordinate(int i) { this.m_coordinates[i]++; } + /** * sets the i^th coordinates of a voxel, with i = 0, 1 or 2 * * @param i the coordinate's index (0, 1 or 2) * @param value the new value of the i^th coordinate of the voxel */ - public void setCoord(int i, short value) { + public void setCoordinate(int i, short value) { this.m_coordinates[i] = value; } + /** - * Return the i^th coordinates of a voxel, with i = 0, 1 or 2 + * Returns the i^th coordinates of a voxel, with i = 0, 1 or 2 * * @param i the coordinate's index (0, 1 or 2) * * @return the i^th coordinate of the voxel */ - public short getCoord(int i) { + public short getCoordinate(int i) { return this.m_coordinates[i]; } + /** - * Return the x coordinates of a voxel + * Returns the x coordinates of a voxel * * @return the first coordinate of the voxel */ @@ -120,6 +127,7 @@ public short getX() { return this.m_coordinates[0]; } + /** * sets the first coordinate of a voxel * @@ -129,8 +137,9 @@ public void setX(short value) { this.m_coordinates[0] = value; } + /** - * Return the y coordinate of a voxel + * Returns the y coordinate of a voxel * * @return the second coordinate of the voxel */ @@ -138,6 +147,7 @@ public short getY() { return this.m_coordinates[1]; } + /** * sets the second coordinate of a voxel * @@ -147,8 +157,9 @@ public void setY(short value) { this.m_coordinates[1] = value; } + /** - * Return the z coordinate of a voxel + * Returns the z coordinate of a voxel * * @return the third coordinate of a voxel */ @@ -156,6 +167,7 @@ public short getZ() { return this.m_coordinates[2]; } + /** * sets the third coordinate of a voxel * @@ -165,6 +177,7 @@ public void setZ(short value) { this.m_coordinates[2] = value; } + /** * Computes the coordinate by coordinate addition between two voxels * @@ -176,6 +189,7 @@ public void shiftCoordinates(Voxel voxel) { this.m_coordinates[2] += voxel.m_coordinates[2]; } + /** * Multiplies the coordinates of voxel with a different factor on each coordinates * @@ -189,6 +203,7 @@ public void multiply(short a, short b, short c) { this.m_coordinates[2] *= c; } + /** * Multiplied the coordinates of voxel with a same factor for each coordinates * @@ -200,6 +215,7 @@ public void multiply(short a) { this.m_coordinates[2] *= a; } + /** * Returns a human readable representation of a voxel as a string * @@ -210,10 +226,12 @@ public String toString() { return "(" + this.m_coordinates[0] + ", " + this.m_coordinates[1] + ", " + this.m_coordinates[2] + ")"; } + public short getValue() { return m_value; } + public void setValue(short m_value) { this.m_value = m_value; } diff --git a/src/main/java/gred/nucleus/utils/VoxelRecord.java b/src/main/java/gred/nucleus/utils/VoxelRecord.java index 99b979d0..23fa6bc9 100644 --- a/src/main/java/gred/nucleus/utils/VoxelRecord.java +++ b/src/main/java/gred/nucleus/utils/VoxelRecord.java @@ -24,8 +24,9 @@ public void setLocation(double i, double j, double k) { this._k = k; } + /** - * Return the x coordinates of a voxel + * Returns the x coordinates of a voxel * * @return */ @@ -33,8 +34,9 @@ public double getI() { return _i; } + /** - * Return the y coordinates of a voxel + * Returns the y coordinates of a voxel * * @return */ @@ -42,8 +44,9 @@ public double getJ() { return _j; } + /** - * Return the z coordinates of a voxel + * Returns the z coordinates of a voxel * * @return */ @@ -51,8 +54,9 @@ public double getK() { return _k; } + /** - * Return the voxel value + * Returns the voxel value * * @return */ @@ -60,8 +64,9 @@ public double getValue() { return _value; } + /** - * Initialise the voxel value + * Initializes the voxel value * * @param value */ @@ -75,7 +80,7 @@ public void setValue(double value) { -1 if value of voxel input > value voxel 1 if value of voxel input < value voxel @param object a voxel - * @return results of comparaison + * @return results of comparison */ /*public int compareTo(Object object) { @@ -90,12 +95,12 @@ else if ( _value < voxelRecord._value ) }*/ /** - * Compare the values of two voxel 0 if same voxel value -1 if value of voxel input > value voxel 1 if value of + * Compares the values of two voxel 0 if same voxel value -1 if value of voxel input > value voxel 1 if value of * voxel input < value voxel * * @param object a voxel * - * @return results of comparaison + * @return results of comparison */ public int compareCoordinatesTo(Object object) { VoxelRecord voxelRecord = (VoxelRecord) object; @@ -107,8 +112,9 @@ public int compareCoordinatesTo(Object object) { } } + /** - * Compute a addition between the coordinates between two voxel + * Computes a addition between the coordinates between two voxel * * @param p a VoxelRecord */ @@ -116,8 +122,9 @@ public void shiftCoordinates(VoxelRecord p) { this.setLocation(this._i + p._i, this._j + p._j, this._k + p._k); } + /** - * Multiplied the coordinates of voxel with a different factor for each coordinates + * Multiplies the coordinates of voxel with a different factor for each coordinates * * @param a * @param b @@ -127,8 +134,9 @@ public void multiply(double a, double b, double c) { this.setLocation(this._i * a, this._j * b, this._k * c); } + /** - * Multiplied the coordinates of voxel with a same factor for each coordinates + * Multiplies the coordinates of voxel with a same factor for each coordinates * * @param a */ diff --git a/src/main/resources/nucleusj.properties b/src/main/resources/nucleusj.properties new file mode 100644 index 00000000..e5683df8 --- /dev/null +++ b/src/main/resources/nucleusj.properties @@ -0,0 +1 @@ +version=${project.version} \ No newline at end of file diff --git a/src/main/resources/plugins.config b/src/main/resources/plugins.config index 9c3240d1..2bf2591c 100644 --- a/src/main/resources/plugins.config +++ b/src/main/resources/plugins.config @@ -12,5 +12,5 @@ Plugins>NucleusJ2.0, "Segmentation NucleusJ 2",gred.nucleus.plugins.Segmentation Plugins>NucleusJ2.0, "Crop From Coordinate NucleusJ 2",gred.nucleus.plugins.CropFromCoordinate_ Plugins>NucleusJ2.0, "Compute parameters", gred.nucleus.plugins.computeParametersPlugin_ Plugins>NucleusJ2.0,"-" -Plugins>NucleusJ2.0, "Chomocenters Segmentation", gred.nucleus.plugins.ChromocenterSegmentationBatchPlugin_ -Plugins>NucleusJ2.0, "Chomocenters Analysis", gred.nucleus.plugins.ChromocentersAnalysisBatchPlugin_ +Plugins>NucleusJ2.0, "Chromocenters Segmentation", gred.nucleus.plugins.ChromocenterSegmentationBatchPlugin_ +Plugins>NucleusJ2.0, "Chromocenters Analysis", gred.nucleus.plugins.ChromocentersAnalysisBatchPlugin_