-
Notifications
You must be signed in to change notification settings - Fork 5
/
itkFuzzyClassificationImageFilter.txx
1847 lines (1594 loc) · 60.1 KB
/
itkFuzzyClassificationImageFilter.txx
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
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: itkFuzzyClassificationImageFilter.txx,v $
Language: C++
Date: $Date: 2009/07/02 13:59:34 $
Version: $Revision: 1.4 $
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef __itkFuzzyClassificationImageFilter_txx
#define __itkFuzzyClassificationImageFilter_txx
#include "itkFuzzyClassificationImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIterator.h"
#include "itkNumericTraits.h"
#include "itkListSample.h"
#include "itkObjectFactory.h"
#include "itkProgressReporter.h"
namespace itk{
bool func4sortpairs( const std::pair<int, float> & a, const std::pair<int, float> & b)
{
if (a.second < b.second)
{
return true;
}
else
{
return false;
}
}
/**
*
*/
template <class TInputImage, class TOutputImage>
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::FuzzyClassificationImageFilter()
{
m_NumberOfClasses = 3;
m_BiasCorrectionOption = 0;
m_ImageMask = NULL;
typename TOutputImage::Pointer output = TOutputImage::New();
this->ProcessObject::SetNumberOfIndexedOutputs( m_NumberOfClasses );
this->ProcessObject::SetNthOutput(1, output.GetPointer());
this->m_ClassCentroid.resize( m_NumberOfClasses );
this->m_ClassStandardDeviation.resize( m_NumberOfClasses );
}
/**
*
*/
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os,indent);
os << indent << "Number Of Classes: "
<< m_NumberOfClasses
<< std::endl;
os << indent << "Bias Correction Option: "
<< m_BiasCorrectionOption
<< std::endl;
}
/**
*
*/
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::GenerateData( )
{
itkDebugMacro(<<"Actually executing");
this->m_ClassStandardDeviation.resize( m_NumberOfClasses );
// Get the input and output pointers
InputImageConstPointer inputPtr = this->GetInput();
// generate a masked image
InputImagePointer img = InputImageType::New();
img->CopyInformation( inputPtr );
img->SetRegions( inputPtr->GetLargestPossibleRegion() );
img->Allocate();
itk::ImageRegionIteratorWithIndex<InputImageType> it( img, img->GetLargestPossibleRegion() );
if (m_ImageMask)
{
for (it.GoToBegin(); !it.IsAtEnd(); ++it)
{
typename InputImageType::IndexType idx = it.GetIndex();
typename InputImageType::PointType pt;
img->TransformIndexToPhysicalPoint( idx, pt );
m_ImageMask->TransformPhysicalPointToIndex( pt, idx );
if ( !m_ImageMask->GetLargestPossibleRegion().IsInside(idx) )
{
it.Set( 0 );
}
else if (m_ImageMask->GetPixel(idx) == 0)
{
it.Set( 0 );
}
else
{
it.Set( inputPtr->GetPixel(it.GetIndex()) );
}
}
}
else
{
for (it.GoToBegin(); !it.IsAtEnd(); ++it)
{
typename InputImageType::IndexType idx = it.GetIndex();
it.Set( inputPtr->GetPixel(idx) );
}
}
// allocate local image variables
//Initialize the image of gain field g[] to 1.
InputImagePointer gain_field_g = InputImageType::New();
gain_field_g->CopyInformation (img);
gain_field_g->SetRegions (img->GetLargestPossibleRegion());
gain_field_g->Allocate();
gain_field_g->FillBuffer (1.0f);
//Initialize the images of the membership functions u1[], u2[], u3[]
//and a updated storage u1n[], u2n[], u3n[].
std::vector<InputImagePointer> mem_fun_u (this->m_NumberOfClasses);
std::vector<InputImagePointer> mem_fun_un (this->m_NumberOfClasses);
for (int k = 0; k < this->m_NumberOfClasses; k++) {
mem_fun_u[k] = InputImageType::New();
mem_fun_u[k] -> CopyInformation( img );
mem_fun_u[k] -> SetRegions (img->GetLargestPossibleRegion());
mem_fun_u[k] -> Allocate();
mem_fun_u[k]->FillBuffer (0.0f);
mem_fun_un[k] = InputImageType::New();
mem_fun_un[k] -> CopyInformation( img );
mem_fun_un[k] -> SetRegions (img->GetLargestPossibleRegion());
mem_fun_un[k] -> Allocate();
mem_fun_un[k]->FillBuffer (0.0f);
}
std::vector<float> centroid_v;
if (this->m_BiasCorrectionOption == 0 || this->m_BiasCorrectionOption == 1 || this->m_BiasCorrectionOption == 2)
{
afcm_segmentation (img, this->m_NumberOfClasses, 200, 5.0f, 1500.0f,
0, this->m_BiasCorrectionOption,
0.8, 0.8,
0.01, gain_field_g,
mem_fun_u, mem_fun_un, this->m_ClassCentroid);
}
else
{
afcm_segmentation_grid (img, this->m_NumberOfClasses, 200, 25.0f, 1500.0f,
0, this->m_BiasCorrectionOption,
0.8, 0.8,
0.01, 3,
gain_field_g,
mem_fun_u, mem_fun_un, this->m_ClassCentroid);
}
// mask out output
if (m_ImageMask)
{
for (it.GoToBegin(); !it.IsAtEnd(); ++it)
{
typename InputImageType::IndexType idx = it.GetIndex();
typename InputImageType::PointType pt;
img->TransformIndexToPhysicalPoint( idx, pt );
m_ImageMask->TransformPhysicalPointToIndex( pt, idx );
if ( m_ImageMask->GetLargestPossibleRegion().IsInside(idx) )
{
if (m_ImageMask->GetPixel(idx) != 0)
{
continue;
}
}
idx = it.GetIndex();
for (int k = 0; k < this->m_NumberOfClasses; k++)
{
mem_fun_u[k]->SetPixel( idx, 0 );
}
}
}
// copy bias field;
this->m_BiasField = InputImageType::New();
this->m_BiasField->CopyInformation( gain_field_g );
this->m_BiasField->SetRegions( gain_field_g->GetLargestPossibleRegion() );
this->m_BiasField->Allocate();
itk::ImageRegionIteratorWithIndex<InputImageType> itg(gain_field_g, gain_field_g->GetLargestPossibleRegion());
for (itg.GoToBegin(); !itg.IsAtEnd(); ++itg)
{
typename InputImageType::IndexType idx = itg.GetIndex();
this->m_BiasField->SetPixel( idx, itg.Get() );
}
// map things to output of the filter
// sort classes into ascending order the class centroid
std::vector< std::pair<int, float> > classCentroidWithIndex( this->m_NumberOfClasses );
std::vector<float> stdCopy( this->m_NumberOfClasses );
for (int k = 0; k < this->m_NumberOfClasses; k++)
{
classCentroidWithIndex[k].first = k;
classCentroidWithIndex[k].second = this->m_ClassCentroid[k];
stdCopy[k] = this->m_ClassStandardDeviation[k];
}
std::sort(classCentroidWithIndex.begin(), classCentroidWithIndex.end(), func4sortpairs );
this->SetNumberOfIndexedOutputs( this->m_NumberOfClasses );
for (int k = 0; k < this->m_NumberOfClasses; k++)
{
OutputImagePointer oPtr = OutputImageType::New();
oPtr->CopyInformation( inputPtr );
oPtr->SetRegions( oPtr->GetLargestPossibleRegion() );
this->SetNthOutput(k, oPtr);
}
this->AllocateOutputs();
for (int k = 0; k < this->m_NumberOfClasses; k++)
{
this->m_ClassCentroid[k] = classCentroidWithIndex[k].second;
this->m_ClassStandardDeviation[k] = stdCopy[classCentroidWithIndex[k].first];
OutputImagePointer oPtr = this->GetOutput( classCentroidWithIndex[k].first );
itk::ImageRegionIteratorWithIndex<OutputImageType> itcpy(oPtr, oPtr->GetLargestPossibleRegion());
for (itcpy.GoToBegin(); !itcpy.IsAtEnd(); ++itcpy)
{
//std::cout << itcpy.GetIndex() << std::endl;
itcpy.Set( mem_fun_u[k]->GetPixel( itcpy.GetIndex() ) );
}
}
// std::cout << "class centroid: " ;
// for (int k = 0; k < this->m_NumberOfClasses; k++)
// {
// std::cout << this->m_ClassCentroid[k] << ", ";
// }
// std::cout << "\n";
// std::cout << "class std: " ;
// for (int k = 0; k < this->m_NumberOfClasses; k++)
// {
// std::cout << this->m_ClassStandardDeviation[k] << ", ";
// }
std::cout << "\n";
}
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::afcm_segmentation (InputImagePointer img_y,
const int n_class, const int n_bin,
const float low_th, const float high_th,
const float bg_thresh,
const int gain_fit_option,
const float gain_th, const float /*gain_min*/,
const float conv_thresh,
InputImagePointer& gain_field_g,
std::vector<InputImagePointer>& mem_fun_u,
std::vector<InputImagePointer>& mem_fun_un,
std::vector<float>& centroid_v)
{
//Initializtion:
//Find the initial guess of the centroid for different classes v1, v2, v3.
compute_init_centroid (img_y, n_class, n_bin, low_th, high_th, centroid_v);
//Iteration: five steps:
bool conv;
int iter = 0;
do {
printf ("\nIteration %d:\n", iter);
//1) Compute new membership functions u1[], u2[], u3[].
compute_new_mem_fun_u (centroid_v, gain_field_g, img_y, bg_thresh, mem_fun_u);
//2) Compute the new centroids v1, v2, v3.
compute_new_centroids (mem_fun_u, gain_field_g, img_y, centroid_v);
//3) Compute a new gain field g[]:
// Initially, we assume g[]=1 is know and fixed in our case.
// Here we update it by a regression fit of the white matter (mem_fun_u[2])
if (gain_fit_option == 1 || gain_fit_option == 2) {
compute_new_gain_field (mem_fun_u, gain_field_g,
gain_fit_option, gain_th);
//debug: save gain field file for debugging.
///save_01_img8 ("gain_field_g.mhd", gain_field_g);
}
//4) Compute a new membership function u1n[], u2n[], u3n[] using step 1.
compute_new_mem_fun_u (centroid_v, gain_field_g, img_y, bg_thresh, mem_fun_un);
//5) Test convergence.
// if max(u1n[]-u1[], u2n[]-u2[], u3n[]-u3[]) < 0.01, converge and finish.
conv = test_convergence (mem_fun_u, mem_fun_un, conv_thresh);
iter++;
if (conv)
{
std::cout << "Iter " << iter << " and stop.\n";
}
else
{
std::cout << "Iter " << iter << " and go on.\n";
}
}
while ( conv == false );
itk::ImageRegionIteratorWithIndex<InputImageType> it( img_y, img_y->GetLargestPossibleRegion() );
std::vector <float> count( this->m_NumberOfClasses );
for (int k = 0; k < this->m_NumberOfClasses; k++)
{
this->m_ClassStandardDeviation[k] = 0;
count[k] = 0;
}
for (it.GoToBegin(); !it.IsAtEnd(); ++it)
{
typename InputImageType::IndexType idx = it.GetIndex();
float p = static_cast<float>( it.Get() );
for (int k = 0; k < this->m_NumberOfClasses; k++)
{
if (mem_fun_u[k]->GetPixel(idx) <= 0.5)
{
continue;
}
else
{
count[k] += 1.0;
p -= this->m_ClassCentroid[k];
this->m_ClassStandardDeviation[k] += (p*p);
}
}
}
for (int k = 0; k < this->m_NumberOfClasses; k++)
{
this->m_ClassStandardDeviation[k] /= (count[k]-1);
this->m_ClassStandardDeviation[k] = sqrt( this->m_ClassStandardDeviation[k] );
}
}
//===================================================================
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::compute_init_centroid (InputImagePointer image,
const int n_class, const int n_bin,
const float low_th, const float high_th,
std::vector<float>& centroid_v)
{
// std::printf ("\ncompute_init_centroid():\n");
// std::printf (" n_class %d, n_bin %d, low_t %f, high_t %f.\n",
// n_class, n_bin, low_th, high_th);
// Exclude pixels whose intensity is outside the range [low_th, high_th]
// from computation. The range is divided into n_bin bins to computer the kernal
// estimator, and then used to compute the parameters
std::vector<float> histVector;
std::vector<float> binMin;
std::vector<float> binMax;
int nBinHistogram = 0;
// let program decide how many bins are there for the histogram
compute_histogram (image, histVector, binMax, binMin, nBinHistogram);
assert (histVector.size() == static_cast<unsigned long>(nBinHistogram));
assert (binMin.size() == static_cast<unsigned long>(nBinHistogram));
assert (binMax.size() == static_cast<unsigned long>(nBinHistogram));
// the variable n_bin below is used to devide the range of intensity used for kernal
// estimator calculation.
std::vector<float> kernalEstimator;
kernalEstimator.resize (n_bin);
assert (n_bin != 1);
float deltaX = (high_th-low_th)/(n_bin-1);
std::vector<float> xVector (n_bin);
for (int k = 0; k < n_bin; k++) {
xVector[k] = low_th + k*deltaX;
}
bool Done = false;
float h0 = 0;
float h1 = 50;
float h = (h0 + h1)/2;
while (!Done) {
for (int k = 0; k < n_bin; k++) {
kernalEstimator[k] = 0;
for (int n = 0; n < nBinHistogram; n ++ ) {
float b = binMin[n];
if ( b < low_th )
continue;
float d = binMax[n];
if ( d > high_th )
continue;
d = (d + b) / 2.0;
d = exp(-(xVector[k]-d)*(xVector[k]-d)/(2*h*h));
kernalEstimator[k] = kernalEstimator[k] + d * histVector[n];
}
}
int C = CountMode (kernalEstimator);
if (C > n_class)
h0 = h;
else
h1 = h;
float hNew = (h0 + h1)/2;
if (fabs(hNew-h) < 0.01)
Done = true;
h = hNew;
}
centroid_v.clear();
int kernalLength = kernalEstimator.size();
assert (kernalLength > 0);
assert (xVector.size() == static_cast<unsigned long>(kernalLength));
for (int k = 1; k < kernalLength-1; k++) {
if (kernalEstimator[k] < kernalEstimator[k-1])
continue;
if (kernalEstimator[k] < kernalEstimator[k+1])
continue;
centroid_v.push_back (xVector[k]);
if (static_cast<int>(centroid_v.size()) >= n_class)
break;
}
// std::printf (" centroid_v: C0 %f, C1 %f, C2 %f.\n\n",
// centroid_v[0], centroid_v[1], centroid_v[2]);
}
// Compute new membership functions u1[], u2[], u3[].
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::compute_new_mem_fun_u (const std::vector<float>& centroid_v,
InputImagePointer gain_field_g,
InputImagePointer img_y,
const float bg_thresh,
std::vector<InputImagePointer>& mem_fun_u)
{
// std::printf (" compute_new_mem_fun_u(): \n");
const int n_class = mem_fun_u.size();
for (int k = 0; k < n_class; k++) {
//iterate through each pixel j:
typedef itk::ImageRegionConstIterator< InputImageType > ConstIteratorType;
typedef itk::ImageRegionIterator< InputImageType > IteratorType;
ConstIteratorType ity (img_y, img_y->GetRequestedRegion());
ConstIteratorType itg (gain_field_g, gain_field_g->GetRequestedRegion());
IteratorType itu (mem_fun_u[k], mem_fun_u[k]->GetRequestedRegion());
for (ity.GoToBegin(), itg.GoToBegin(), itu.GoToBegin();
!ity.IsAtEnd();
++ity, ++itg, ++itu) {
//Skip background pixels.
float img_y_j = ity.Get();
if (img_y_j < bg_thresh)
continue;
float gain_field_g_j = itg.Get();
///double numerator = img_y[j] - centroid_v[k] * gain_field_g[j];
double numerator = img_y_j - centroid_v[k] * gain_field_g_j;
if (numerator != 0)
numerator = 1 / (numerator * numerator);
else if (gain_field_g_j == 1) {
//The divide-by-zero happens when img_y[j] == centroid_v[k].
//In this case, the membership function should be 1 for this class and
//0 for all other classes (for normalization).
itu.Set (1);
continue; //Done for the current pixel.
}
else {
//Keep numerator as 0 for this unlikely-to-happen case.
///assert (0);
}
double denominator = 0;
for (int l = 0; l < n_class; l++) {
///double denominator_l = img_y[j] - centroid_v[l] * gain_field_g[j];
double denominator_l = img_y_j - centroid_v[l] * gain_field_g_j;
if (denominator_l != 0)
denominator_l = 1 / (denominator_l * denominator_l);
else {
//This is the case when the same pixel of other class than k has mem_fun == 1.
//Set the membership function to 0.
itu.Set (0);
continue;
}
denominator += denominator_l;
}
///mem_fun_u[k][j] = numerator / denominator;
if (denominator == 0)
{
itu.Set (0);
}
else
{
itu.Set (numerator / denominator);
}
}
}
}
// Compute the new centroids v1, v2, v3.
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::compute_new_centroids (const std::vector<InputImagePointer>& mem_fun_u,
InputImagePointer& gain_field_g,
InputImagePointer& img_y,
std::vector<float>& centroid_v)
{
std::cout << " compute_new_centroids(): \n";
const int n_class = mem_fun_u.size();
for (int k = 0; k < n_class; k++) {
//iterate through each pixel j:
typedef itk::ImageRegionConstIterator< InputImageType > ConstIteratorType;
ConstIteratorType ity (img_y, img_y->GetRequestedRegion());
ConstIteratorType itg (gain_field_g, gain_field_g->GetRequestedRegion());
ConstIteratorType itu (mem_fun_u[k], mem_fun_u[k]->GetRequestedRegion());
double numerator = 0;
double denominator = 0;
for (ity.GoToBegin(), itg.GoToBegin(), itu.GoToBegin(); !ity.IsAtEnd(); ++ity, ++itg, ++itu) {
float mem_fun_u_kj = itu.Get();
assert (vnl_math::isnan(mem_fun_u_kj) == false);
float gain_field_g_j = itg.Get();
assert (vnl_math::isnan(gain_field_g_j) == false);
float img_y_j = ity.Get();
assert (vnl_math::isnan(img_y_j) == false);
///double numerator = mem_fun_u[k][j] * mem_fun_u[k][j] * gain_field_g[j] * img_y[j];
numerator += mem_fun_u_kj * mem_fun_u_kj * gain_field_g_j * img_y_j;
assert (vnl_math::isnan(numerator) == false);
///double denominator = mem_fun_u[k][j] * mem_fun_u[k][j] * gain_field_g[j] * gain_field_g[j];
denominator += mem_fun_u_kj * mem_fun_u_kj * gain_field_g_j * gain_field_g_j;
assert (vnl_math::isnan(denominator) == false);
}
if (denominator == 0) {
if (numerator == 0)
centroid_v[k] = 0;
else {
// std::printf (" Error: divide by 0!\n");
centroid_v[k] = itk::NumericTraits<float>::min();
}
}
else {
centroid_v[k] = numerator / denominator;
}
}
// std::printf ("C0 %f, C1 %f, C2 %f.\n",
// centroid_v[0], centroid_v[1], centroid_v[2]);
}
// Compute a new gain field g[]:
// Initially, we assume g[]=1 is know and fixed in our case.
// Here we update it by a regression fit of the white matter (mem_fun_u[2])
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::compute_new_gain_field (std::vector<InputImagePointer>& mem_fun_u,
InputImagePointer& gain_field_g,
const int gain_fit_option,
const float gain_th)
{
assert (gain_fit_option == 1 || gain_fit_option == 2);
std::cout << " -- compute_new_gain_field():\n";
// std::printf (" %s fitting, gain_th %f.\n",
// (gain_fit_option==1) ? "linear" : "quadratic",
// gain_th);
//Quadratic regression fiting to get the parameter B
vnl_matrix<double> B;
typename InputImageType::PixelType maxGain = itk::NumericTraits<typename InputImageType::PixelType>::min();
itk::ImageRegionIteratorWithIndex<InputImageType> it( mem_fun_u[2], mem_fun_u[2]->GetLargestPossibleRegion() );
for (it.GoToBegin(); !it.IsAtEnd(); ++it)
{
if (it.Get() > maxGain)
{
maxGain = it.Get();
}
}
if (gain_fit_option == 1) {
img_regression_linear (mem_fun_u[2], gain_th*maxGain, B);
//Use B to compute a new gain_field_g[]
compute_linear_fit_img (B, gain_field_g);
}
else if (gain_fit_option == 2) {
img_regression_quadratic (mem_fun_u[2], gain_th*maxGain, B);
//Use B to compute a new gain_field_g[]
compute_quadratic_fit_img (B, gain_field_g);
}
}
// Test convergence.
template <class TInputImage, class TOutputImage>
bool
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::test_convergence (const std::vector<InputImagePointer>& mem_fun_u,
const std::vector<InputImagePointer>& mem_fun_un,
const float conv_thresh)
{
// std::printf (" test_convergence(): ");
const int n_class = mem_fun_u.size();
float max_value = 0;
for (int k = 0; k < n_class; k++) {
//iterate through each pixel j:
typedef itk::ImageRegionConstIterator< InputImageType > ConstIteratorType;
ConstIteratorType it (mem_fun_u[k], mem_fun_u[k]->GetRequestedRegion());
ConstIteratorType itn (mem_fun_un[k], mem_fun_un[k]->GetRequestedRegion());
for (it.GoToBegin(), itn.GoToBegin(); !it.IsAtEnd(); ++it, ++itn) {
float mem_fun_u_kj = it.Get();
assert (vnl_math::isnan(mem_fun_u_kj) == false);
float mem_fun_un_kj = itn.Get();
assert (vnl_math::isnan(mem_fun_un_kj) == false);
///float diff = member_fun_u[k][j] - member_fun_un[k][j];
float diff = mem_fun_u_kj - mem_fun_un_kj;
diff = std::fabs (diff);
if (diff > max_value)
max_value = diff;
}
}
std::cout << "max_value " << max_value << " (conv_th " << conv_thresh << ").\n";
if (max_value < conv_thresh)
return true;
else
return false;
}
template <class TInputImage, class TOutputImage>
int
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::CountMode (const std::vector<float>& v)
{
int c = 0;
for (unsigned int k = 1; k < v.size()-1; k++) {
if ( v[k] > v[k-1] && v[k] > v[k+1])
c++;
}
return (c);
}
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::img_regression_linear (InputImagePointer& image,
const float thresh,
vnl_matrix<double>& B)
{
// std::printf (" img_regression_linear(): \n");
int i;
//Put image intensity into y[].
//Put image pixel coordinates into x1[], x2[], x3[].
typedef itk::ImageRegionIteratorWithIndex < InputImageType > IndexedIteratorType;
IndexedIteratorType iit (image, image->GetRequestedRegion());
iit.GoToBegin();
assert (iit.GetIndex().GetIndexDimension() == 3);
//Determine the total number of pixels > thresh.
///InputImageType::SizeType requestedSize = image->GetRequestedRegion().GetSize();
///int SZ = requestedSize[0] * requestedSize[1] * requestedSize[2];
int SZ = 0;
for (i=0, iit.GoToBegin(); !iit.IsAtEnd(); ++iit) {
typename InputImageType::IndexType idx = iit.GetIndex();
float pixel = iit.Get();
if (pixel > thresh)
SZ++;
}
// std::printf (" # pixels > thresh (%f) = %d\n", thresh, SZ);
vnl_matrix<double> y (SZ,1);
vnl_matrix<double> x1 (SZ,1);
vnl_matrix<double> x2 (SZ,1);
vnl_matrix<double> x3 (SZ,1);
for (i=0, iit.GoToBegin(); !iit.IsAtEnd(); ++iit) {
typename InputImageType::IndexType idx = iit.GetIndex();
float pixel = iit.Get();
if (pixel > thresh) {
assert (i < SZ);
y(i, 0) = pixel;
int x_1 = idx[0];
int x_2 = idx[1];
int x_3 = idx[2];
x1(i, 0) = x_1;
x2(i, 0) = x_2;
x3(i, 0) = x_3;
i++;
}
}
//Prepare the design matrix X
vnl_matrix<double> X (SZ,4);
X.set_column (0, 1.0);
X.update (x1, 0, 1);
X.update (x2, 0, 2);
X.update (x3, 0, 3);
///std::cerr << X;
x1.clear();
x2.clear();
x3.clear();
vnl_matrix<double> Xt = X.transpose();
vnl_matrix<double> Xt_X = Xt * X; //(x'*x)
X.clear();
vnl_matrix<double> Xt_y = Xt * y; //(x'*y)
Xt.clear();
y.clear();
//Solve for the linear normal equation: (x'*x) * b = (x'*y)
vnl_matrix<double> Xt_X_inv = vnl_matrix_inverse<double>(Xt_X);
Xt_X.clear();
//b = inv(x'*x) * (x'*y);
B = Xt_X_inv * Xt_y;
// std::printf ("B: \n");
// std::cerr << B;
}
//Use B to compute a new fitting
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::compute_linear_fit_img (const vnl_matrix<double>& B,
InputImagePointer& fit_image)
{
// std::printf (" compute_linear_fit_img(): \n");
//Traverse through the fit_image and compute a new quadratic value via B.
//Image coordinates into x1[], x2[], x3[].
typedef itk::ImageRegionIteratorWithIndex < InputImageType > IndexedIteratorType;
IndexedIteratorType iit (fit_image, fit_image->GetRequestedRegion());
assert (iit.GetIndex().GetIndexDimension() == 3);
assert (B.rows() == 4);
for (iit.GoToBegin(); !iit.IsAtEnd(); ++iit) {
typename InputImageType::IndexType idx = iit.GetIndex();
int x_1 = idx[0];
int x_2 = idx[1];
int x_3 = idx[2];
double pixel = B(0,0) + B(1,0)*x_1 + B(2,0)*x_2 + B(3,0)*x_3;
iit.Set (pixel);
}
}
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::img_regression_quadratic (InputImagePointer& image,
const float thresh,
vnl_matrix<double>& B)
{
// std::printf (" img_regression_quadratic(): \n");
int i;
//Put image intensity into y[].
//Put image pixel coordinates into x1[], x2[], x3[].
typedef itk::ImageRegionConstIteratorWithIndex < InputImageType > IndexedIteratorType;
IndexedIteratorType iit (image, image->GetRequestedRegion());
assert (iit.GetIndex().GetIndexDimension() == 3);
//Determine the total number of pixels > thresh.
///InputImageType::SizeType requestedSize = image->GetRequestedRegion().GetSize();
///int SZ = requestedSize[0] * requestedSize[1] * requestedSize[2];
int SZ = 0;
for (iit.GoToBegin(); !iit.IsAtEnd(); ++iit)
{
if (iit.Get() > thresh)
{
SZ++;
}
}
std::printf (" # pixels > thresh (%f) = %d\n", thresh, SZ);
vnl_matrix<double> y (SZ,1);
vnl_matrix<double> x1 (SZ,1);
vnl_matrix<double> x2 (SZ,1);
vnl_matrix<double> x3 (SZ,1);
for (i=0, iit.GoToBegin(); !iit.IsAtEnd(); ++iit)
{
if (iit.Get() > thresh)
{
assert (i < SZ);
y(i, 0) = iit.Get();
x1(i, 0) = static_cast<double> (iit.GetIndex()[0]);
x2(i, 0) = static_cast<double> (iit.GetIndex()[1]);
x3(i, 0) = static_cast<double> (iit.GetIndex()[2]);
i++;
}
}
//Prepare the design matrix X
vnl_matrix<double> X (SZ,10);
X.set_column (0, 1.0);
X.update (x1, 0, 1);
X.update (x2, 0, 2);
X.update (x3, 0, 3);
x1.clear();
x2.clear();
x3.clear();
vnl_matrix<double> x1x2 (SZ,1);
vnl_matrix<double> x1x3 (SZ,1);
vnl_matrix<double> x2x3 (SZ,1);
for (i=0, iit.GoToBegin(); !iit.IsAtEnd(); ++iit) {
typename InputImageType::IndexType idx = iit.GetIndex();
double pixel = iit.Get();
if (pixel > thresh) {
assert (i < SZ);
int x_1 = idx[0];
int x_2 = idx[1];
int x_3 = idx[2];
x1x2 (i, 0) = x_1 * x_2;
x1x3 (i, 0) = x_1 * x_3;
x2x3 (i, 0) = x_2 * x_3;
i++;
}
}
X.update (x1x2, 0, 4);
X.update (x1x3, 0, 5);
X.update (x2x3, 0, 6);
x1x2.clear();
x1x3.clear();
x2x3.clear();
vnl_matrix<double> x1x1 (SZ,1);
vnl_matrix<double> x2x2 (SZ,1);
vnl_matrix<double> x3x3 (SZ,1);
for (i=0, iit.GoToBegin(); !iit.IsAtEnd(); ++iit) {
typename InputImageType::IndexType idx = iit.GetIndex();
double pixel = iit.Get();
if (pixel > thresh) {
assert (i < SZ);
int x_1 = idx[0];
int x_2 = idx[1];
int x_3 = idx[2];
x1x1 (i, 0) = x_1 * x_1;
x2x2 (i, 0) = x_2 * x_2;
x3x3 (i, 0) = x_3 * x_3;
i++;
}
}
X.update (x1x1, 0, 7);
X.update (x2x2, 0, 8);
X.update (x3x3, 0, 9);
x1x1.clear();
x2x2.clear();
x3x3.clear();
///// std::printf ("X: \n");
///std::cerr << X;
vnl_matrix<double> Xt = X.transpose();
vnl_matrix<double> Xt_X = Xt * X; //(x'*x)
X.clear();
vnl_matrix<double> Xt_y = Xt * y; //(x'*y)
Xt.clear();
y.clear();
//Solve for the linear normal equation: (x'*x) * b = (x'*y)
vnl_matrix<double> Xt_X_inv = vnl_matrix_inverse<double>(Xt_X);
Xt_X.clear();
//b = inv(x'*x) * (x'*y);
B = Xt_X_inv * Xt_y;
// std::printf ("B: \n");
// std::cerr << B;
}
//Use B to compute a new fitting
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::compute_quadratic_fit_img (const vnl_matrix<double>& B,
InputImagePointer& fit_image)
{
// std::printf (" compute_quadratic_fit_img(): \n");
//Traverse through the fit_image and compute a new quadratic value via B.
//Image coordinates into x1[], x2[], x3[].
typedef itk::ImageRegionIteratorWithIndex < InputImageType > IndexedIteratorType;
IndexedIteratorType iit (fit_image, fit_image->GetRequestedRegion());
assert (iit.GetIndex().GetIndexDimension() == 3);
assert (B.rows() == 10);
for (iit.GoToBegin(); !iit.IsAtEnd(); ++iit) {
typename InputImageType::IndexType idx = iit.GetIndex();
int x_1 = idx[0];
int x_2 = idx[1];
int x_3 = idx[2];
double pixel = B(0,0) + B(1,0)*x_1 + B(2,0)*x_2 + B(3,0)*x_3 +
B(4,0)*x_1*x_2 + B(5,0)*x_1*x_3 + B(6,0)*x_2*x_3 +
B(7,0)*x_1*x_1 + B(8,0)*x_2*x_2 + B(9,0)*x_3*x_3;
iit.Set (pixel);
}
}
template <class TInputImage, class TOutputImage>
void
FuzzyClassificationImageFilter<TInputImage, TOutputImage>
::afcm_segmentation_grid (InputImagePointer img_y,
const int n_class, const int n_bin,
const float low_th, const float high_th,
const float bg_thresh,
const int gain_fit_option,
const float gain_th, const float gain_min,
const float conv_thresh,
const int n_grid,
InputImagePointer& gain_field_g,
std::vector<InputImagePointer>& mem_fun_u,
std::vector<InputImagePointer>& mem_fun_un,
std::vector<float>& centroid_v)
{
int i;
assert (gain_fit_option == 3 || gain_fit_option == 4);
//Detect the bounding box of the non-background brain block B.
int xmin=0;
int ymin=0;
int zmin=0;
int xmax=0;
int ymax=0;
int zmax=0;
//Space division: into nxnxn: 3x3x3 or 4x4x4 blocks.
std::vector<InputImagePointer> img_y_grid;
std::vector<typename InputImageType::IndexType> grid_center_index;
compute_grid_imgs (img_y, xmin, ymin, zmin, xmax, ymax, zmax, n_grid,
img_y_grid, grid_center_index);
//Allocate space for the centroid_v_grid[] and centroid_vn_grid.
const int total_grids = (int) img_y_grid.size();
std::vector<std::vector<float> > centroid_v_grid (total_grids);
std::vector<float> centroid_vn_grid (total_grids);
//Allocate space for the gain_field_g_grid[].
std::vector<InputImagePointer> gain_field_g_grid (total_grids);
//Allocate space for the mem_fun_u_grid[][] and mem_fun_un_grid[][]
std::vector<std::vector<InputImagePointer> > mem_fun_u_grid (total_grids);
std::vector<std::vector<InputImagePointer> > mem_fun_un_grid (total_grids);
for (i=0; i<total_grids; i++) {
//Initialize gain_field_g_grid[].
gain_field_g_grid[i] = InputImageType::New();
gain_field_g_grid[i]->SetRegions (img_y_grid[i]->GetLargestPossibleRegion());
gain_field_g_grid[i]->SetSpacing (img_y_grid[i]->GetSpacing());
gain_field_g_grid[i]->SetOrigin (img_y_grid[i]->GetOrigin());
gain_field_g_grid[i]->Allocate();