-
Notifications
You must be signed in to change notification settings - Fork 61
/
WekaSegmentation.java
7674 lines (6761 loc) · 235 KB
/
WekaSegmentation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-
* #%L
* Fiji distribution of ImageJ for the life sciences.
* %%
* Copyright (C) 2010 - 2023 Fiji developers.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package trainableSegmentation;
import java.awt.Point;
import java.awt.Rectangle;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.scijava.vecmath.Point3f;
import hr.irb.fastRandomForest.FastRandomForest;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.Prefs;
import ij.gui.Line;
import ij.gui.PolygonRoi;
import ij.gui.Roi;
import ij.gui.ShapeRoi;
import ij.plugin.Duplicator;
import ij.process.Blitter;
import ij.process.ByteProcessor;
import ij.process.FloatPolygon;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import ij.process.ImageStatistics;
import trainableSegmentation.utils.Utils;
import weka.attributeSelection.BestFirst;
import weka.attributeSelection.CfsSubsetEval;
import weka.classifiers.AbstractClassifier;
import weka.classifiers.Evaluation;
import weka.classifiers.pmml.consumer.PMMLClassifier;
import weka.classifiers.trees.RandomForest;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instances;
import weka.core.pmml.PMMLFactory;
import weka.core.pmml.PMMLModel;
import weka.filters.Filter;
import weka.filters.supervised.attribute.AttributeSelection;
import weka.filters.supervised.instance.Resample;
import weka.gui.explorer.ClassifierPanel;
/**
*
* License: GPL
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Authors: Ignacio Arganda-Carreras (iarganda@mit.edu), Verena Kaynig (verena.kaynig@inf.ethz.ch),
* Albert Cardona (acardona@ini.phys.ethz.ch)
*/
/**
* This class contains all the library methods to perform image segmentation
* based on the Weka classifiers.
*/
public class WekaSegmentation {
/** maximum number of classes (labels) allowed */
public static final int MAX_NUM_CLASSES = 100;
/** array of lists of Rois for each slice (vector index)
* and each class (arraylist index) of the training image */
private Vector<ArrayList<Roi>>[] examples;
/** image to be used in the training */
private ImagePlus trainingImage;
/** result image after classification */
private ImagePlus classifiedImage;
/** features to be used in the training */
private FeatureStackArray featureStackArray = null;
/** set of instances from loaded data (previously saved segmentation) */
private Instances loadedTrainingData = null;
/** set of instances from the user's traces */
private Instances traceTrainingData = null;
/** current classifier */
private AbstractClassifier classifier = null;
/** train header */
private Instances trainHeader = null;
/** default classifier (Fast Random Forest) */
private FastRandomForest rf;
/** flag to update the feature stack (used when there is any change on the features) */
private boolean updateFeatures = false;
/** array of boolean flags to update (or not) specific feature stacks during training */
private boolean[] featureStackToUpdateTrain;
/** array of boolean flags to update (or not) specific feature stacks during test */
private boolean[] featureStackToUpdateTest;
/** current number of classes */
private int numOfClasses = 0;
/** names of the current classes */
private String[] classLabels = new String[MAX_NUM_CLASSES];
// Random Forest parameters
/** current number of trees in the fast random forest classifier */
private int numOfTrees = 200;
/** current number of random features per tree in the fast random forest classifier */
private int randomFeatures = 2;
/** maximum depth per tree in the fast random forest classifier */
private int maxDepth = 0;
/** list of class names on the loaded data */
private ArrayList<String> loadedClassNames = null;
/** expected membrane thickness */
private int membraneThickness = 1;
/** size of the patch to use to enhance the membranes */
private int membranePatchSize = 19;
/** minimum sigma to use on the filters */
private float minimumSigma = 1f;
/** maximum sigma to use on the filters */
private float maximumSigma = 16f;
private boolean isProcessing3D = false;
private FeatureStack3D fs3d = null;
/** flags of filters to be used in 2D */
private boolean[] enabledFeatures = new boolean[]{
true, /* Gaussian_blur */
true, /* Sobel_filter */
true, /* Hessian */
true, /* Difference_of_gaussians */
true, /* Membrane_projections */
false, /* Variance */
false, /* Mean */
false, /* Minimum */
false, /* Maximum */
false, /* Median */
false, /* Anisotropic_diffusion */
false, /* Bilateral */
false, /* Lipschitz */
false, /* Kuwahara */
false, /* Gabor */
false, /* Derivatives */
false, /* Laplacian */
false, /* Structure */
false, /* Entropy */
false /* Neighbors */
};
/** flags of filters to be used in 3D */
private boolean[] enabled3Dfeatures = FeatureStack3D.getDefaultEnabledFeatures();
/** use neighborhood flag */
private boolean useNeighbors = false;
/** list of the names of features to use */
private ArrayList<String> featureNames = null;
/**
* flag to set the resampling of the training data in order to guarantee
* the same number of instances per class (class balance)
* */
private boolean balanceClasses = false;
/** Project folder name. It is used to stored temporary data if different from null */
private String projectFolder = null;
/** executor service to launch threads for the library operations */
private ExecutorService exe = Executors.newFixedThreadPool( Prefs.getThreads() );
/**
* Default constructor.
*
* @param trainingImage The image to be segmented/trained
*/
public WekaSegmentation(ImagePlus trainingImage)
{
// set class label names
for(int i=0; i<MAX_NUM_CLASSES; i++)
this.classLabels[ i ] = new String("class " + (i+1));
this.trainingImage = trainingImage;
// Initialization of Fast Random Forest classifier
rf = new FastRandomForest();
rf.setNumTrees(numOfTrees);
//this is the default that Breiman suggests
//rf.setNumFeatures((int) Math.round(Math.sqrt(featureStack.getSize())));
//but this seems to work better
rf.setNumFeatures(randomFeatures);
// Random seed
rf.setSeed( (new Random()).nextInt() );
// Set number of threads
rf.setNumThreads( Prefs.getThreads() );
classifier = rf;
// Initialize feature stack (no features yet)
featureStackArray = new FeatureStackArray(trainingImage.getImageStackSize(),
minimumSigma, maximumSigma, useNeighbors, membraneThickness, membranePatchSize,
enabledFeatures);
featureStackToUpdateTrain = new boolean[trainingImage.getImageStackSize()];
featureStackToUpdateTest = new boolean[trainingImage.getImageStackSize()];
Arrays.fill(featureStackToUpdateTest, true);
examples = new Vector[trainingImage.getImageStackSize()];
for(int i=0; i< trainingImage.getImageStackSize(); i++)
{
examples[i] = new Vector<ArrayList<Roi>>(MAX_NUM_CLASSES);
for(int j=0; j<MAX_NUM_CLASSES; j++)
examples[i].add(new ArrayList<Roi>());
// Initialize each feature stack (one per slice)
featureStackArray.set(new FeatureStack(trainingImage.getImageStack().getProcessor(i+1)), i);
}
// start with two classes
addClass();
addClass();
}
/**
* No-image constructor. If you use this constructor, the image has to be
* set using <code>setTrainingImage()</code>. Another option is to use the
* object to load a classifier and apply it to other images without
* additional training.
*/
public WekaSegmentation()
{
// set class label names
for(int i=0; i<MAX_NUM_CLASSES; i++)
this.classLabels[ i ] = new String("class " + (i+1));
// Initialization of Fast Random Forest classifier
rf = new FastRandomForest();
rf.setNumTrees(numOfTrees);
//this is the default that Breiman suggests
//rf.setNumFeatures((int) Math.round(Math.sqrt(featureStack.getSize())));
//but this seems to work better
rf.setNumFeatures(randomFeatures);
// Random seed
rf.setSeed( (new Random()).nextInt() );
// Set number of threads
rf.setNumThreads( Prefs.getThreads() );
classifier = rf;
// start with two classes
addClass();
addClass();
}
/**
* Constructor for both 2D and 3D images. No training image is set yet, so
* it can be used by loading a classifier (using
* <code>loadClassifier()</code> or by setting later a training image
* (using <code>setTrainingImage()</code>).
* @param isProcessing3D true to process images in 3D and false to do it in 2D
*/
public WekaSegmentation( boolean isProcessing3D )
{
this();
this.isProcessing3D = isProcessing3D;
// when working in 3D, set maximum filter radius to 8 (otherwise the
// feature calculation is too slow)
if( isProcessing3D )
this.maximumSigma = 8f;
}
/**
* Set the training image (single image or stack)
*
* @param imp training image
*/
public void setTrainingImage(ImagePlus imp)
{
this.trainingImage = imp;
// Initialize feature stack (no features yet)
featureStackArray = new FeatureStackArray(trainingImage.getImageStackSize(),
minimumSigma, maximumSigma, useNeighbors, membraneThickness, membranePatchSize,
enabledFeatures );
featureStackToUpdateTrain = new boolean[trainingImage.getImageStackSize()];
featureStackToUpdateTest = new boolean[trainingImage.getImageStackSize()];
Arrays.fill(featureStackToUpdateTest, true);
// update list of examples
examples = new Vector[trainingImage.getImageStackSize()];
for(int i=0; i < trainingImage.getImageStackSize(); i++)
{
examples[i] = new Vector<ArrayList<Roi>>(MAX_NUM_CLASSES);
for(int j=0; j<MAX_NUM_CLASSES; j++)
examples[i].add(new ArrayList<Roi>());
if ( !isProcessing3D )
// Initialize each feature stack (one per slice)
featureStackArray.set(
new FeatureStack(
trainingImage.getImageStack().getProcessor(i+1) ), i);
}
if( isProcessing3D )
{
fs3d = new FeatureStack3D( trainingImage );
fs3d.setMaximumSigma( maximumSigma );
fs3d.setMinimumSigma( minimumSigma );
featureStackArray = fs3d.getFeatureStackArray();
}
}
/**
* Adds a ROI to the list of examples for a certain class
* and slice.
*
* @param classNum the number of the class
* @param roi the ROI containing the new example
* @param n number of the current slice
*/
public void addExample(int classNum, Roi roi, int n)
{
// In 2D: if the feature stack of that slice is not set
// to be updated during training
if( !isProcessing3D && !featureStackToUpdateTrain[n - 1] )
{
boolean updated = false;
// check if it has any trace yet of any class
for(final ArrayList<Roi> list : examples[n-1])
if(!list.isEmpty())
{
updated = true;
break;
}
// if it does not contain any trace yet, set it
// to be updated during training
if(!updated && featureStackToUpdateTest[n - 1])
{
//IJ.log("Feature stack for slice " + n
// + " needs to be updated");
featureStackToUpdateTrain[n-1] = true;
featureStackToUpdateTest[n-1] = false;
updateFeatures = true;
}
}
examples[n-1].get(classNum).add(roi);
}
/**
* Remove an example list from a class and specific slice
*
* @param classNum the number of the examples' class
* @param nSlice the slice number
* @param index the index of the example list to remove
*/
public void deleteExample(int classNum, int nSlice, int index)
{
getExamples(classNum, nSlice).remove(index);
}
/**
* Return the list of examples for a certain class.
*
* @param classNum the number of the examples' class
* @param n the slice number
* @return list of examples (ROIs) of a specific class on a given slice
*/
public List<Roi> getExamples(int classNum, int n)
{
return examples[n-1].get(classNum);
}
/**
* Set flag to homogenize classes before training
*
* @param homogenizeClasses true to resample the classes before training
* @deprecated use setClassBalance
*/
public void setHomogenizeClasses(boolean homogenizeClasses)
{
this.balanceClasses = homogenizeClasses;
}
/**
* Set flag to balance classes before training
*
* @param balanceClasses true to resample the classes before training
*/
public void setClassBalance( boolean balanceClasses )
{
this.balanceClasses = balanceClasses;
}
/**
* Set the current number of classes. Should not be used to create new
* classes. Use {@link #addClass} instead.
*
* @param numOfClasses the new number of classes
*/
public void setNumOfClasses(int numOfClasses) {
this.numOfClasses = numOfClasses;
}
/**
* Get the current number of classes.
*
* @return the current number of classes
*/
public int getNumOfClasses()
{
return numOfClasses;
}
/**
* Add new segmentation class.
*/
public void addClass()
{
if(null != trainingImage)
for(int i=1; i <= trainingImage.getImageStackSize(); i++)
examples[i-1].add(new ArrayList<Roi>());
// increase number of available classes
numOfClasses ++;
}
/**
* Set the name of a class.
*
* @param classNum class index
* @param label new name for the class
*/
public void setClassLabel(int classNum, String label)
{
this.classLabels[ classNum ] = label;
}
/**
* Get the label name of a class.
*
* @param classNum class index
* @return label name of a class
*/
public String getClassLabel(int classNum)
{
return this.classLabels[ classNum ];
}
/**
* Load training data
*
* @param pathname complete path name of the training data file (.arff)
* @return false if error
*/
public boolean loadTrainingData(String pathname)
{
IJ.log("Loading data from " + pathname + "...");
loadedTrainingData = readDataFromARFF(pathname);
if( null == loadedTrainingData )
{
IJ.log( "Unable to load training data from " + pathname );
return false;
}
// Check the features that were used in the loaded data
Enumeration<Attribute> attributes = loadedTrainingData.enumerateAttributes();
final String[] availableFeatures = isProcessing3D ?
FeatureStack3D.availableFeatures :
FeatureStack.availableFeatures;
final int numFeatures = availableFeatures.length;
boolean[] usedFeatures = new boolean[numFeatures];
while(attributes.hasMoreElements())
{
final Attribute a = attributes.nextElement();
for(int i = 0 ; i < numFeatures; i++)
if(a.name().startsWith((isProcessing3D ?
FeatureStack3D.availableFeatures :
FeatureStack.availableFeatures)[i]))
usedFeatures[i] = true;
}
// Check if classes match
Attribute classAttribute = loadedTrainingData.classAttribute();
Enumeration<Object> classValues = classAttribute.enumerateValues();
// Update list of names of loaded classes
loadedClassNames = new ArrayList<String>();
int j = 0;
while(classValues.hasMoreElements())
{
final String className = ((String)classValues.nextElement()).trim();
loadedClassNames.add(className);
IJ.log("Read class name: " + className);
// If classes do not match
if( !className.equals( getClassLabel( j )))
{
// Store current GUI class names
String guiClasses = getClassLabel( 0 );
for(int i = 1; i < numOfClasses; i++)
guiClasses = guiClasses.concat(", " + getClassLabel( i ));
// Store file class names
String fileClasses = loadedClassNames.get( 0 );
for(int i = 1; i < loadedClassNames.size(); i++)
fileClasses += ", " + loadedClassNames.get( i );
while( classValues.hasMoreElements() )
fileClasses += ", "
+ ( (String) classValues.nextElement() ).trim();
// Show error message displaying both lists of names
IJ.error("WekaSegmentation: load ARFF",
"<html>"
+ "<b>Error</b>: Loaded classes and current classes do "
+ "not match:"
+ "<ul>"
+ "<li>Expected names: <i>" + guiClasses + "</i>"
+ "<li>ARFF class names: <i>" + fileClasses + "</i>"
+ "</ul>"
+ "Please adjust names in GUI before loading ARFF." );
loadedTrainingData = null;
return false;
}
j++;
}
if(j != numOfClasses)
{
IJ.error( "WekaSegmentation: load ARFF",
"ERROR: Loaded number of classes and current number do not "
+ "match!" );
loadedTrainingData = null;
return false;
}
boolean featuresChanged = false;
final boolean[] oldEnableFeatures = enabledFeatures;
// Read checked features and check if any of them chasetButtonsEnablednged
for(int i = 0; i < numFeatures; i++)
{
if (usedFeatures[i] != oldEnableFeatures[i])
featuresChanged = true;
}
// Update feature stack if necessary
if(featuresChanged)
{
//this.setButtonsEnabled(false);
this.setEnabledFeatures( usedFeatures );
// Force features to be updated
updateFeatures = true;
}
if (!adjustSegmentationStateToData(loadedTrainingData))
loadedTrainingData = null;
else
IJ.log("Loaded data: " + loadedTrainingData.numInstances() + " instances (" + loadedTrainingData.numAttributes() + " attributes)");
return true;
}
/**
* Returns a the loaded training data or null, if no training data was
* loaded.
* @return set of training instances loaded from file or null if nothing has been loaded
*/
public Instances getLoadedTrainingData() {
return loadedTrainingData;
}
/**
* Returns a the trace training data or null, if no examples have been
* given.
* @return current set of training samples calculated from the user traces
*/
public Instances getTraceTrainingData() {
return traceTrainingData;
}
/**
* Get current classification result
* @return classified image
*/
public ImagePlus getClassifiedImage()
{
return classifiedImage;
}
/**
* Get the current training header
*
* @return training header (empty set of instances with the current attributes and classes)
*/
public Instances getTrainHeader()
{
return this.trainHeader;
}
/**
* bag class for getting the result of the loaded classifier
*/
private static class LoadedClassifier {
private AbstractClassifier newClassifier = null;
private Instances newHeader = null;
}
/**
* load a binary classifier
*
* @param classifierInputStream
* @throws Exception
* exception is thrown if the reading is not properly done, the
* caller has to handle this exception
*/
private LoadedClassifier internalLoadClassifier(
InputStream classifierInputStream) throws Exception {
ObjectInputStream objectInputStream = new ObjectInputStream(
classifierInputStream);
LoadedClassifier lc = new LoadedClassifier();
lc.newClassifier = (AbstractClassifier) objectInputStream.readObject();
try { // see if we can load the header
lc.newHeader = (Instances) objectInputStream.readObject();
} finally {
objectInputStream.close();
}
return lc;
}
/**
* load a binary classifier from a stream
*
* @param classifierInputStream
* the input stream
* @return true if properly read, false otherwise
*/
public boolean loadClassifier(InputStream classifierInputStream) {
assert classifierInputStream != null;
try {
LoadedClassifier loadresult = internalLoadClassifier(classifierInputStream);
try {
// Check if the loaded information corresponds to current state
// of
// the segmentator
// (the attributes can be adjusted, but the classes must match)
if (!adjustSegmentationStateToData(loadresult.newHeader)) {
IJ.log("Error: current segmentator state could not be updated to loaded data requirements (attributes and classes)");
return false;
}
} catch (Exception e) {
IJ.log("Error while adjusting data!");
e.printStackTrace();
return false;
}
this.classifier = loadresult.newClassifier;
this.trainHeader = loadresult.newHeader;
// check model version to assign Hessian format
if( null != this.featureStackArray )
this.getFeatureStackArray().setOldHessianFormat(
getModelVersion().startsWith("segment") );
return true;
} catch (Exception e) {
IJ.error("Load Failed", "Error while loading classifier");
e.printStackTrace();
return false;
}
}
/**
* Read header classifier from a .model file
* @param filename complete path and file name
* @return false if error
*/
public boolean loadClassifier(String filename)
{
AbstractClassifier newClassifier = null;
Instances newHeader = null;
File selected = new File(filename);
try {
InputStream is = new FileInputStream( selected );
if (selected.getName().endsWith(ClassifierPanel.PMML_FILE_EXTENSION))
{
PMMLModel model = PMMLFactory.getPMMLModel(is, null);
if (model instanceof PMMLClassifier)
newClassifier = (PMMLClassifier)model;
else
throw new Exception("PMML model is not a classification/regression model!");
}
else
{
if (selected.getName().endsWith(".gz"))
is = new GZIPInputStream(is);
try {
LoadedClassifier loadresult = internalLoadClassifier(is);
newHeader = loadresult.newHeader;
newClassifier = loadresult.newClassifier;
} catch (Exception e) {
IJ.error("Load Failed", "Error while loading train header");
e.printStackTrace();
return false;
}
}
}
catch (Exception e)
{
IJ.error("Load Failed", "Error while loading classifier");
e.printStackTrace();
return false;
}
try{
// Check if classifier was trained on the same image type
// (grayscale or color) as the training image
if( null != trainingImage )
{
if( containsColorFeatures( newHeader ) )
{
if( trainingImage.getType() != ImagePlus.COLOR_RGB )
{
IJ.log( "Error: new classifier contains color features " +
"and training image is grayscale." );
return false;
}
}
else if( trainingImage.getType() == ImagePlus.COLOR_RGB )
{
IJ.log( "Error: new classifier was trained on grayscale images " +
"and training image is color." );
return false;
}
}
// Check if classifier was trained using the same dimensions as
// the training image (2D or 3D).
if( containsExclusive2DFeatures( newHeader ) && isProcessing3D )
{
IJ.log( "Error: new classifier was trained on 2D images " +
"and you are using Trainable Weka Segmentation 3D." );
return false;
}
else if( containsExclusive3DFeatures( newHeader ) && !isProcessing3D )
{
IJ.log( "Error: new classifier was trained on 3D images " +
"and you are using Trainable Weka Segmentation 2D." );
return false;
}
// Check if the loaded information corresponds to current state of the segmentator
// (the attributes can be adjusted, but the classes must match)
if(!adjustSegmentationStateToData(newHeader))
{
IJ.log("Error: current segmentator state could not be updated to loaded data requirements (attributes and classes)");
return false;
}
}catch(Exception e)
{
IJ.log("Error while adjusting data!");
e.printStackTrace();
return false;
}
this.classifier = newClassifier;
this.trainHeader = newHeader;
// check model version to assign Hessian format
if( null != this.featureStackArray )
{
this.getFeatureStackArray().setOldHessianFormat(
getModelVersion().startsWith("segment") );
// Check if the feature stacks of the slices with
// traces have been updated yet, otherwise set them
// to be updated in test
for(int i = 0; i < featureStackArray.getSize(); i++)
if( featureStackToUpdateTrain[i] && featureStackArray.get(i).isEmpty() )
featureStackToUpdateTest[i] = true;
}
return true;
}
/**
* Check if a set of Weka instances has color attributes
* (given by the presence of the attribute names "Hue",
* "Saturation" or "Brightness").
* @param data set of Weka instances
* @return true if the set contains color attributes, false otherwise
*/
public boolean containsColorFeatures( Instances data )
{
if( data.relationName().contains("RGB") )
return true;
Enumeration<Attribute> attributes = data.enumerateAttributes();
while(attributes.hasMoreElements())
{
final Attribute a = attributes.nextElement();
if( a.name().equals( "Hue" ) ||
a.name().equals( "Saturation" ) ||
a.name().equals( "Brightness" ) )
return true;
}
return false;
}
/**
* Check if a set of Weka instances has 2D image attributes
* (given by the presence of the attribute names from FeatureStack
* which are not present in FeatureStack3D).
* @param data set of Weka instances
* @return true if the set contains exclusive 2D attributes, false otherwise
*/
public boolean containsExclusive2DFeatures( Instances data )
{
if( data.relationName().contains("2D") )
return true;
// make list of exclusive 2D feature names
final ArrayList<String> names2D = new ArrayList<String>();
for( int i=0; i<FeatureStack.availableFeatures.length; i++ )
names2D.add( FeatureStack.availableFeatures[ i ] );
for( int i=0; i<FeatureStack3D.availableFeatures.length; i++ )
{
if( names2D.contains( FeatureStack3D.availableFeatures[ i ] ) )
names2D.remove( FeatureStack3D.availableFeatures[ i ] );
}
Enumeration<Attribute> attributes = data.enumerateAttributes();
while(attributes.hasMoreElements())
{
final Attribute a = attributes.nextElement();
for( String s : names2D )
if( a.name().startsWith( s ) )
return true;
}
return false;
}
/**
* Check if a set of Weka instances has 3D image attributes
* (given by the presence of the attribute names from FeatureStack3D
* which are not present in FeatureStack).
* @param data set of Weka instances
* @return true if the set contains exclusive 3D attributes, false otherwise
*/
public boolean containsExclusive3DFeatures( Instances data )
{
if( data.relationName().contains("3D") )
return true;
// make list of exclusive 3D feature names
final ArrayList<String> names3D = new ArrayList<String>();
for( int i=0; i<FeatureStack3D.availableFeatures.length; i++ )
names3D.add( FeatureStack3D.availableFeatures[ i ] );
for( int i=0; i<FeatureStack.availableFeatures.length; i++ )
{
if( names3D.contains( FeatureStack.availableFeatures[ i ] ) )
names3D.remove( FeatureStack.availableFeatures[ i ] );
}
Enumeration<Attribute> attributes = data.enumerateAttributes();
while(attributes.hasMoreElements())
{
final Attribute a = attributes.nextElement();
for( String s : names3D )
if( a.name().startsWith( s ) )
return true;
}
return false;
}
/**
* Returns the current classifier.
* @return current classifier
*/
public AbstractClassifier getClassifier() {
return classifier;
}
/**
* Write current classifier into a file
*
* @param filename name (with complete path) of the destination file
* @return false if error
*/
public boolean saveClassifier(String filename)
{
File sFile = null;
boolean saveOK = true;
IJ.log("Saving model to file...");
try {
sFile = new File(filename);
OutputStream os = new FileOutputStream(sFile);
if (sFile.getName().endsWith(".gz"))
{
os = new GZIPOutputStream(os);
}
ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
objectOutputStream.writeObject(classifier);
trainHeader = trainHeader.stringFreeStructure();
if (trainHeader != null)
objectOutputStream.writeObject(trainHeader);
objectOutputStream.flush();
objectOutputStream.close();
}
catch (Exception e)
{
IJ.error("Save Failed", "Error when saving classifier into a file");
saveOK = false;
}
if (saveOK)
IJ.log("Saved model into " + filename );
return saveOK;
}
/**
* Save training data into a file (.arff)
* @param pathname complete path name
* @return false if error
*/
public boolean saveData(final String pathname)
{
boolean examplesEmpty = true;
for(int i = 0; i < numOfClasses; i ++)
{
for(int n=0; n<trainingImage.getImageStackSize(); n++)
if(!examples[n].get(i).isEmpty())
{
examplesEmpty = false;
break;
}
}
if (examplesEmpty && loadedTrainingData == null){
IJ.log("There is no data to save");
return false;
}
if(featureStackArray.isEmpty() || updateFeatures)
{
IJ.log("Creating feature stack...");
if ( !isProcessing3D &&
!featureStackArray.updateFeaturesMT(