-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathMitoThinning.cxx
executable file
·1177 lines (988 loc) · 42.9 KB
/
MitoThinning.cxx
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
// =====================================================================================================
// MitoThinning: This routine receives as input an ImageData binary from MitoGraph main routine a and
// apply a thinning process over it, resulting in a new but topologically equivalent image.
//
// Matheus P. Viana - [email protected] - 2014.06.10
// Susanne Rafelski Lab, University of California Irvine
// =====================================================================================================
#include "MitoThinning.h"
int ssdx[26] = {-1, 0, 1,-1, 0, 1,-1, 0, 1,-1, 0, 1,-1, 1,-1, 0, 1,-1, 0, 1,-1, 0, 1,-1, 0, 1};
int ssdy[26] = {-1,-1,-1,-1,-1,-1,-1,-1,-1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int ssdz[26] = { 1, 1, 1, 0, 0, 0,-1,-1,-1, 1, 1, 1, 0, 0,-1,-1,-1, 1, 1, 1, 0, 0, 0,-1,-1,-1};
// Routine used to save .gnet and .coo files representing
// the skeleton of the mitochondrial network.
void ExportGraphFiles(vtkSmartPointer<vtkPolyData> PolyData, long int nnodes, const char Prefix[]);
// Routine to create the file _nodes.vtk. This file contains
// little speres located at the junctions (nodes) coordinates
// and might have the nodes label depending on if the variable
// export_node_labels is true or false.
void ExportNodes(vtkSmartPointer<vtkPolyData> PolyData, long int nnodes, long int *ValidId, _mitoObject *mitoObject);
// Routine used to check whether a voxel is locates at the border
// of the binary image or not. A border voxel is defined as those
// that have at least one of their 6-neighbors equal to zero.
bool IsBorder(vtkIdType id, vtkSmartPointer<vtkImageData> Image);
// Routine used to smooth the parametric curves that describe the
// skeleton edges. A simple average filter is used to do the job.
// Sigma represents the number of times the filter is applied.
void SmoothEdgesCoordinates(vtkSmartPointer<vtkPolyData> PolyData, double sigma);
// Estimate the mitochondrial volume by counting the number of
// pixels in the binary image used as input for thinning.
void GetVolumeFromVoxels(vtkSmartPointer<vtkImageData> Image, std::vector<attribute> *Atts);
// Estimate the mitochondrial volume by using the skeleton
// total length and assuming constant radius.
//void GetVolumeFromSkeletonLength(vtkSmartPointer<vtkPolyData> PolyData, double *attributes);
// Calculate the length of a given edge.
//double GetEdgeLength(vtkIdType edge, vtkSmartPointer<vtkPolyData> PolyData);
// Returns the number of voxels around the voxel (x,y,z) with
// value given different of "value".
char GetNumberOfNeighborsWithoutValue(vtkSmartPointer<vtkImageData> Image, int x, int y, int z, long int value);
// Returns the number of voxels around the voxel (x,y,z) with
// value different of "value" in the vector "Volume".
char GetNumberOfNeighborsWithoutValue(vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume, int x, int y, int z, long int value);
// Returns the number of voxels around the voxel (x,y,z) with
// value given by "value".
char GetNumberOfNeighborsWithValue(vtkSmartPointer<vtkImageData> Image, int x, int y, int z, long int value);
// Returns the number of voxels around the voxel (x,y,z) with
// value "value" in the vector "Volume".
char GetNumberOfNeighborsWithValue(vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume, int x, int y, int z, long int value);
// Returns one neighbor of (x,y,z) with value "value" in the
// vector "Volume".
vtkIdType GetOneNeighborWithValue(int x, int y, int z, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume, long int value);
// Returns one neighbor of (x,y,z) with value different of
// "value" in the vector "Volume".
vtkIdType GetOneNeighborWithoutValue(int x, int y, int z, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume, long int value);
// Returns one neighbor of (x,y,z) with value different of
// "value".
vtkIdType GetOneNeighborWithoutValue(int x, int y, int z, vtkSmartPointer<vtkImageData> Image, long int value);
// Merge together junctions that touch each other.
bool JunctionsMerge(std::list<vtkIdType> Junctions, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume);
// Track an edge starting at voxel (x,y,z) in the volume "Volume".
std::list<vtkIdType> GetEdgeStartingAt(int x, int y, int z, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume);
// Returns an adjacency edge "edge_label".
long int GetOneAdjacentEdge(vtkSmartPointer<vtkPolyData> PolyData, long int edge_label, long int junction_label, bool *found_on_left);
// Track all the nodes and edges of a 3D structured thinned by
// the routine Thinning3D.
vtkSmartPointer<vtkPolyData> Skeletonization(vtkSmartPointer<vtkImageData> Image, _mitoObject *mitoObject);
// Replace two edges A and B attached to a node of degree 2
// with one edge C that corresponds to A + B. The degree of the
// node is set to -1 and A and B are moreved from PolyData.
bool MergeEdgesOfDegree2Nodes(vtkSmartPointer<vtkPolyData> PolyData, long int nedges_before_filtering, int *K);
// After merging edges attached to nodes of degree 2, the original
// edges must be deleted throught this routine.
void RemoveCellsWithInvalidNodes(vtkSmartPointer<vtkPolyData> PolyData, int *K);
/* ================================================================
I/O ROUTINES
=================================================================*/
void SaveImageData(vtkSmartPointer<vtkImageData> Image, const char FileName[], bool _resample) {
#ifdef DEBUG
printf("Saving ImageData File...\n");
#endif
vtkSmartPointer<vtkImageFlip> Flip = vtkSmartPointer<vtkImageFlip>::New();
Flip -> SetInputData(Image);
Flip -> SetFilteredAxis(1);
Flip -> PreserveImageExtentOn();
Flip -> Update();
vtkSmartPointer<vtkTIFFWriter> writer = vtkSmartPointer<vtkTIFFWriter>::New();
writer -> SetFileName(FileName);
// TIF writer does not support data of type double
if (Image -> GetScalarType() == VTK_DOUBLE) {
double range[2];
Image -> GetScalarRange( range );
vtkSmartPointer<vtkImageShiftScale> ShiftFilter = vtkSmartPointer<vtkImageShiftScale>::New();
ShiftFilter -> SetInputData(Flip->GetOutput());
ShiftFilter -> SetScale( 65535./(range[1]-range[0]));
ShiftFilter -> SetShift( -range[0] );
ShiftFilter -> SetOutputScalarTypeToUnsignedShort();
ShiftFilter -> Update();
writer -> SetInputData(ShiftFilter->GetOutput());
} else {
if (_resample) {
#ifdef DEBUG
printf("\tResampling data...%f\t%f\n",_dxy,_dz);
#endif
vtkSmartPointer<vtkImageResample> Resample = vtkSmartPointer<vtkImageResample>::New();
Resample -> SetInterpolationModeToLinear();
Resample -> SetDimensionality(3);
Resample -> SetInputData(Flip->GetOutput());
Resample -> SetAxisMagnificationFactor(0,1.0);
Resample -> SetAxisMagnificationFactor(1,1.0);
Resample -> SetAxisMagnificationFactor(2,_dz/_dxy);
Resample -> Update();
vtkSmartPointer<vtkImageData> ImageResampled = Resample -> GetOutput();
ImageResampled -> SetSpacing(1,1,1);
writer -> SetInputData(ImageResampled);
} else {
writer -> SetInputData(Flip->GetOutput());
}
}
writer -> Write();
#ifdef DEBUG
printf("\tFile Saved!\n");
#endif
}
void SavePolyData(vtkSmartPointer<vtkPolyData> PolyData, const char FileName[]) {
#ifdef DEBUG
printf("Saving PolyData...\n");
#endif
#ifdef DEBUG
printf("\t#Points in PolyData file: %llu.\n",(vtkIdType)PolyData->GetNumberOfPoints());
#endif
vtkSmartPointer<vtkPolyDataWriter> Writer = vtkSmartPointer<vtkPolyDataWriter>::New();
#ifndef DEBUG
Writer -> SetFileType(VTK_BINARY);
#endif
Writer -> SetFileName(FileName);
Writer -> SetInputData(PolyData);
Writer -> Write();
#ifdef DEBUG
printf("\tFile Saved!\n");
#endif
}
void ExportGraphFiles(vtkSmartPointer<vtkPolyData> PolyData, long int nnodes, long int *ValidId, const char Prefix[]) {
#ifdef DEBUG
printf("Saving .coo file...\n");
#endif
char _fullpath[256];
vtkPoints *Points = PolyData -> GetPoints();
double r[3];
long int node, exact_nnodes = 0;
for (node = 0; node < nnodes; node++) {
if (ValidId[node]>=0) exact_nnodes++;
}
sprintf(_fullpath,"%s.coo",Prefix);
FILE *fcoo = fopen(_fullpath,"w");
for (node = 0; node < nnodes; node++) {
if (ValidId[node]>=0) {
Points -> GetPoint(node,r);
fprintf(fcoo,"%1.4f\t%1.4f\t%1.4f\n",_dxy*r[0],_dxy*r[1],_dz*r[2]);
}
}
fclose(fcoo);
double length;
vtkIdType edge, npoints, i, j;
sprintf(_fullpath,"%s.gnet",Prefix);
FILE *fgnet = fopen(_fullpath,"w");
fprintf(fgnet,"%ld\n",exact_nnodes);
for (edge = 0; edge < PolyData -> GetNumberOfCells(); edge++) {
npoints = PolyData -> GetCell(edge) -> GetNumberOfPoints();
i = PolyData -> GetCell(edge) -> GetPointId(0);
j = PolyData -> GetCell(edge) -> GetPointId(npoints-1);
if ( ValidId[i] >= 0 && ValidId[j] >= 0 ) {
length = GetEdgeLength(edge,PolyData);
fprintf(fgnet,"%ld\t%ld\t%1.5f\n",ValidId[i],ValidId[j],length);
}
}
fclose(fgnet);
}
void ExportNodes(vtkSmartPointer<vtkPolyData> PolyData, long int nnodes, long int *ValidId, _mitoObject *mitoObject) {
#ifdef DEBUG
if (_export_nodes_label) {
printf("Exporting nodes and their labels...\n");
} else {
printf("Exporting nodes...\n");
}
#endif
vtkPoints *Points = PolyData -> GetPoints();
vtkSmartPointer<vtkAppendPolyData> Append = vtkSmartPointer<vtkAppendPolyData>::New();
Append -> SetOutputPointsPrecision(vtkAlgorithm::DEFAULT_PRECISION);
double r[3];
long int node;
char node_txt[16];
for (node = 0; node < nnodes; node++) {
if ( ValidId[node] >= 0 ) {
Points -> GetPoint(node,r);
#ifdef DEBUG
printf("Node = %d\n",(int)node);
#endif
vtkSmartPointer<vtkSphereSource> Node = vtkSmartPointer<vtkSphereSource>::New();
if (_scale_polydata_before_save) {
Node -> SetRadius(2*_dxy);
Node -> SetCenter(_dxy*(r[0]+mitoObject->Ox),_dxy*(r[1]+mitoObject->Oy),_dz*(r[2]+mitoObject->Oz));
} else {
Node -> SetRadius(2.0);
Node -> SetCenter(r[0]+mitoObject->Ox,r[1]+mitoObject->Oy,r[2]+mitoObject->Oz);
}
Node -> SetThetaResolution(6);
Node -> SetPhiResolution(6);
Node -> Update();
Append -> AddInputData(Node->GetOutput());
Append -> Update();
if (_export_nodes_label) {
sprintf(node_txt,"%ld",ValidId[node]);
vtkSmartPointer<vtkVectorText> PolyText = vtkSmartPointer<vtkVectorText>::New();
PolyText -> SetText(node_txt);
PolyText -> Update();
vtkSmartPointer<vtkTransform> T = vtkSmartPointer<vtkTransform>::New();
if (_scale_polydata_before_save) {
T -> Translate(_dxy*(r[0]+1+mitoObject->Ox),_dxy*(r[1]+1+mitoObject->Oy),_dz*(r[2]+mitoObject->Oz));
T -> Scale(2*_dxy,2*_dxy,1);
} else {
T -> Translate(r[0]+2+mitoObject->Ox,r[1]+mitoObject->Oy,r[2]+mitoObject->Oz);
T -> Scale(2,2,1);
}
vtkSmartPointer<vtkTransformPolyDataFilter> Trans = vtkSmartPointer<vtkTransformPolyDataFilter>::New();
Trans -> SetInputData(PolyText->GetOutput());
Trans -> SetTransform(T);
Trans -> Update();
Append -> AddInputData(Trans -> GetOutput());
Append -> Update();
}
}
}
SavePolyData(Append->GetOutput(),(mitoObject->FileName+"_nodes.vtk").c_str());
}
/* ================================================================
IMAGE TRANSFORMATION
=================================================================*/
void CleanImageBoundaries(vtkSmartPointer<vtkImageData> ImageData) {
#ifdef DEBUG
printf("Cleaning the image boundaries...\n");
#endif
int p, q;
int *Dim = ImageData -> GetDimensions();
for ( p = Dim[0]; p--; ) {
for ( q = Dim[1]; q--; ) {
ImageData -> SetScalarComponentFromDouble(p,q,0,0,0);
ImageData -> SetScalarComponentFromDouble(p,q,Dim[2]-1,0,0);
}
}
for ( p = Dim[0]; p--; ) {
for ( q = Dim[2]; q--; ) {
ImageData -> SetScalarComponentFromDouble(p,0,q,0,0);
ImageData -> SetScalarComponentFromDouble(p,Dim[1]-1,q,0,0);
}
}
for ( p = Dim[1]; p--; ) {
for ( q = Dim[2]; q--; ) {
ImageData -> SetScalarComponentFromDouble(0,p,q,0,0);
ImageData -> SetScalarComponentFromDouble(Dim[0]-1,p,q,0,0);
}
}
}
/* ================================================================
AUXILIAR ROUTINES
=================================================================*/
bool IsBorder(vtkIdType id, vtkSmartPointer<vtkImageData> Image) {
double r[3];
int x, y, z;
Image -> GetPoint(id,r);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
if(!Image->GetScalarComponentAsDouble(x,y,z,0)) return false;
if(!Image->GetScalarComponentAsDouble(x+1,y,z,0)) return true;
if(!Image->GetScalarComponentAsDouble(x-1,y,z,0)) return true;
if(!Image->GetScalarComponentAsDouble(x,y+1,z,0)) return true;
if(!Image->GetScalarComponentAsDouble(x,y-1,z,0)) return true;
if(!Image->GetScalarComponentAsDouble(x,y,z+1,0)) return true;
if(!Image->GetScalarComponentAsDouble(x,y,z-1,0)) return true;
return false;
}
void SmoothEdgesCoordinates(vtkSmartPointer<vtkPolyData> PolyData, double sigma){
double r1[3], r2[3], r3[3];
long int id, line, nlines, n, s;
vtkPoints *Points = PolyData -> GetPoints();
vtkCell *Line;
nlines = PolyData -> GetNumberOfCells();
for (line = 0; line < nlines; line++){
Line = PolyData -> GetCell(line);
n = Line -> GetNumberOfPoints();
double *X = new double[n];
double *Y = new double[n];
double *Z = new double[n];
for (s = 0; s < int(sigma); s++) {
for (id = 1; id < n-1; id++ ) {
Points -> GetPoint(Line->GetPointId(id-1),r1);
Points -> GetPoint(Line->GetPointId(id+0),r2);
Points -> GetPoint(Line->GetPointId(id+1),r3);
X[id] = 0.125*(r1[0]+6*r2[0]+r3[0]);
Y[id] = 0.125*(r1[1]+6*r2[1]+r3[1]);
Z[id] = (1.0/3.0)*(r1[2]+r2[2]+r3[2]);
}
for (id = 1; id < n-1; id++ ) {
Points -> SetPoint(Line->GetPointId(id),X[id],Y[id],Z[id]);
}
}
delete[] X; delete[] Y; delete[] Z;
}
PolyData -> Modified();
}
void GetVolumeFromVoxels(vtkSmartPointer<vtkImageData> Image, std::vector<attribute> *Atts) {
double v;
unsigned long int nv = 0;
for (vtkIdType id=Image->GetNumberOfPoints();id--;) {
v = Image -> GetPointData() -> GetScalars() -> GetTuple1(id);
if (v) nv++;
}
attribute newAtt = {"Volume from voxels",nv * (_dxy * _dxy * _dz)};
Atts -> push_back(newAtt);
}
/*
void GetVolumeFromSkeletonLength(vtkSmartPointer<vtkPolyData> PolyData, double *attributes) {
double r1[3], r2[3], length = 0.0;
vtkPoints *Points = PolyData -> GetPoints();
for (vtkIdType edge=PolyData->GetNumberOfCells();edge--;) {
length += GetEdgeLength(edge,PolyData);
}
attributes[1] = length;
attributes[2] = length * (acos(-1.0)*pow(_rad,2));
}
*/
double GetEdgeLength(vtkIdType edge, vtkSmartPointer<vtkPolyData> PolyData) {
double r1[3], r2[3];
double length = 0.0;
for (vtkIdType n = 1; n < PolyData->GetCell(edge)->GetNumberOfPoints(); n++) {
PolyData -> GetPoint(PolyData->GetCell(edge)->GetPointId(n-1),r1);
PolyData -> GetPoint(PolyData->GetCell(edge)->GetPointId(n ),r2);
length += sqrt(pow(_dxy*(r2[0]-r1[0]),2)+pow(_dxy*(r2[1]-r1[1]),2)+pow(_dz*(r2[2]-r1[2]),2));
}
return length;
}
/* ================================================================
THINNING 3D
=================================================================*/
vtkSmartPointer<vtkPolyData> Thinning3D(vtkSmartPointer<vtkImageData> ImageData, _mitoObject *mitoObject) {
#ifdef DEBUG
SaveImageData(ImageData,(mitoObject->FileName+"_binary.tif").c_str());
#endif
vtkIdType N = ImageData -> GetNumberOfPoints();
GetVolumeFromVoxels(ImageData,&mitoObject->attributes);
int x, y, z;
double r[3], v, vl;
vtkIdType ndels, id;
ssThinVox *STV = new ssThinVox();
CleanImageBoundaries(ImageData);
int i, j, ***Vol = new int**[3];
for (i = 0; i < 3; i++) {
Vol[i] = new int*[3];
for (j = 0; j < 3; j++) {
Vol[i][j] = new int[3];
}
}
#ifdef DEBUG
printf("Starting thinning process...\n");
#endif
std::list<vtkIdType> ToBeDeleted;
std::list<vtkIdType> OnTheSurface;
std::list<vtkIdType>::iterator itId;
do {
ndels = 0;
for (id = N; id--;) {
if (IsBorder(id, ImageData)) {
OnTheSurface.insert(OnTheSurface.begin(),id);
}
}
for (int direction = 6; direction--;) {
for ( itId=OnTheSurface.begin(); itId!=OnTheSurface.end(); itId++) {
id = *itId;
ImageData -> GetPoint(id,r);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
v = ImageData -> GetScalarComponentAsDouble(x,y,z,0);
if (v) {
for (i = 26; i--;) {
vl = ImageData -> GetScalarComponentAsDouble(x+ssdx[i],y+ssdy[i],z+ssdz[i],0);
Vol[1+ssdx[i]][1+ssdy[i]][1+ssdz[i]] = (vl) ? 1 : 0;
}
if ( STV -> match(direction,Vol) ) ToBeDeleted.insert(ToBeDeleted.begin(),id);
}
}
itId = ToBeDeleted.begin();
while (itId != ToBeDeleted.end()) {
ndels++;
ImageData -> GetPoint(*itId,r);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
ImageData -> SetScalarComponentFromDouble(x,y,z,0,0);
ToBeDeleted.erase(itId++);
}
}
#ifdef DEBUG
printf("\t#Surface = %llu / #Deletions = %llu\n",(long long int)OnTheSurface.size(),ndels);
#endif
OnTheSurface.clear();
} while(ndels);
delete STV;
#ifdef DEBUG
printf("Thinning done!\n");
#endif
OnTheSurface.clear();
ToBeDeleted.clear();
return Skeletonization(ImageData,mitoObject);
}
/* ================================================================
SKELETONIZATION
=================================================================*/
char GetNumberOfNeighborsWithoutValue(vtkSmartPointer<vtkImageData> Image, int x, int y, int z, long int value) {
double r[3];
char nn = 0;
for (char k = 26; k--;) {
if (Image->GetScalarComponentAsDouble(x+ssdx[k],y+ssdy[k],z+ssdz[k],0) != value) nn++;
}
return nn;
}
char GetNumberOfNeighborsWithoutValue(vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume, int x, int y, int z, long int value) {
double r[3];
char nn = 0;
vtkIdType idk;
for (char k = 26; k--;) {
idk = Image->FindPoint(x+ssdx[k],y+ssdy[k],z+ssdz[k]);
if (Volume->GetTuple1(idk) != value) nn++;
}
return nn;
}
char GetNumberOfNeighborsWithValue(vtkSmartPointer<vtkImageData> Image, int x, int y, int z, long int value) {
double r[3];
char nn = 0;
for (char k = 26; k--;) {
if (Image->GetScalarComponentAsDouble(x+ssdx[k],y+ssdy[k],z+ssdz[k],0) == value) nn++;
}
return nn;
}
char GetNumberOfNeighborsWithValue(vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume, int x, int y, int z, long int value) {
double r[3];
char nn = 0;
vtkIdType idk;
for (char k = 26; k--;) {
idk = Image -> FindPoint(x+ssdx[k],y+ssdy[k],z+ssdz[k]);
if (Volume->GetTuple1(idk) == value) nn++;
}
return nn;
}
vtkIdType GetOneNeighborWithValue(int x, int y, int z, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume, long int value) {
vtkIdType idk;
for (char k = 26; k--;) {
idk = Image -> FindPoint(x+ssdx[k],y+ssdy[k],z+ssdz[k]);
if (Volume -> GetTuple1(idk) == value) {
return idk;
}
}
return 0; // We can do it because, by construction the voxel at id 0 should always be empty
}
vtkIdType GetOneNeighborWithoutValue(int x, int y, int z, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume, long int value) {
vtkIdType idk;
for (char k = 26; k--;) {
idk = Image -> FindPoint(x+ssdx[k],y+ssdy[k],z+ssdz[k]);
if (Volume -> GetTuple1(idk) && Volume -> GetTuple1(idk) != value) {
return idk;
}
}
return 0; // We can do it because, by construction the voxel at id 0 should always be empty
}
vtkIdType GetOneNeighborWithoutValue(int x, int y, int z, vtkSmartPointer<vtkImageData> Image, long int value) {
vtkIdType idk;
for (char k = 26; k--;) {
idk = Image -> FindPoint(x+ssdx[k],y+ssdy[k],z+ssdz[k]);
if (Image->GetScalarComponentAsDouble(x+ssdx[k],y+ssdy[k],z+ssdz[k],0)!=value) return idk;
}
return 0; // We can do it because, by construction the voxel at id 0 should always be empty
}
bool JunctionsMerge(std::list<vtkIdType> Junctions, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume) {
char nk;
double r[3];
vtkIdType id;
int x, y, z, k;
bool _has_changed = false;
std::list<vtkIdType>::iterator itId;
long int junction_label, neigh_junction_label;
for (itId=Junctions.begin(); itId!=Junctions.end(); itId++) {
Image -> GetPoint(*itId,r);
junction_label = Volume -> GetTuple1(*itId);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
for (k = 0; k < 26; k++) {
id = Image->FindPoint(x+ssdx[k],y+ssdy[k],z+ssdz[k]);
neigh_junction_label = Volume -> GetTuple1(id);
if (junction_label < neigh_junction_label) {
_has_changed = true;
Volume -> SetTuple1(id,junction_label);
}
}
}
Volume -> Modified();
return _has_changed;
}
std::list<vtkIdType> GetEdgeStartingAt(int x, int y, int z, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkTypeInt64Array> Volume) {
double r[3];
vtkIdType idk;
std::list<vtkIdType> Edge;
do {
idk = GetOneNeighborWithValue(x,y,z,Image,Volume,-1);
if (idk) {
Volume -> SetTuple1(idk,0);
Edge.insert(Edge.end(),idk);
Image -> GetPoint(idk,r);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
}
} while(idk);
return Edge;
}
long int GetOneAdjacentEdge(vtkSmartPointer<vtkPolyData> PolyData, long int edge_label, long int original_source, bool *_common_source) {
vtkCell *Edge;
long int source, target;
for (long int edge = PolyData->GetNumberOfCells();edge--;) {
if (edge != edge_label) {
Edge = PolyData -> GetCell((vtkIdType)edge);
source = Edge -> GetPointId(0);
target = Edge -> GetPointId(Edge->GetNumberOfPoints()-1);
if (original_source==source) {
*_common_source = true;
return edge;
}
if (original_source==target) {
*_common_source = false;
return edge;
}
}
}
return -1;
}
vtkSmartPointer<vtkPolyData> Skeletonization(vtkSmartPointer<vtkImageData> Image, _mitoObject *mitoObject) {
#ifdef DEBUG
SaveImageData(Image,(mitoObject->FileName+"_thinned.tif").c_str());
#endif
double r[3];
int x, y, z;
vtkIdType id;
long int junction_label = 1;
vtkIdType N = Image -> GetNumberOfPoints();
std::list<vtkIdType> Junctions;
std::list<vtkIdType>::iterator itId;
// Inside this IF statement, isolated voxels and isolated pairs of voxels
// are expanded. If this is not done, these voxels will not be detected.
// This requires O(N).
if (_improve_skeleton_quality) {
#ifdef DEBUG
printf("Improving skeletonization [step 1: isolated single and pair of voxels]\n");
#endif
char nn;
double rn[3];
vtkIdType idn;
int xn, yn, zn;
for (id = N; id--;) {
Image -> GetPoint(id,r);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
if (Image->GetScalarComponentAsDouble(x,y,z,0)) {
nn = GetNumberOfNeighborsWithoutValue(Image,x,y,z,0);
if (nn==0) {
// Expanding isolated voxel
Image -> SetScalarComponentFromDouble(x+1,y,z,0,255);
Image -> SetScalarComponentFromDouble(x-1,y,z,0,255);
} else if (nn==1) {
idn = GetOneNeighborWithoutValue(x,y,z,Image,0);
Image -> GetPoint(idn,rn);
xn = (int)rn[0]; yn = (int)rn[1]; zn = (int)rn[2];
if (GetNumberOfNeighborsWithoutValue(Image,xn,yn,zn,0)==1) {
// Expanding isolated pair of voxels
Image -> SetScalarComponentFromDouble(x-(int)(rn[0]-r[0]),y-(int)(rn[1]-r[1]),z-(int)(rn[2]-r[2]),0,255);
Image -> SetScalarComponentFromDouble(xn+(int)(rn[0]-r[0]),yn+(int)(rn[1]-r[1]),zn+(int)(rn[2]-r[2]),0,255);
}
}
}
}
}
vtkSmartPointer<vtkTypeInt64Array> Volume = vtkSmartPointer<vtkTypeInt64Array>::New();
Volume -> SetNumberOfComponents(1);
Volume -> SetNumberOfTuples(N);
// Inside this IF statement, we label all connected components
// and we search for those cc that don't have junctions. If any
// is found, we force it to have a junction by adding its first
// voxel to the list Junctions. This fixes the problem of not
// detecting loop-shaped ccs.
if (_improve_skeleton_quality) {
#ifdef DEBUG
printf("Improving skeletonization [step 2: verifying connected components]\n");
#endif
long int n_fixed = 0;
std::vector<long int> CSz;
long int cc, ncc = LabelConnectedComponents(Image,Volume,CSz,26,0);
bool *HasJunction = new bool[ncc];
for (cc = ncc; cc--;) HasJunction[cc] = 0;
for (id = N; id--;) {
Image -> GetPoint(id,r);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
cc = (long int)Volume -> GetTuple1(id);
if (cc) {
if (GetNumberOfNeighborsWithValue(Image,Volume,x,y,z,cc) != 2) {
HasJunction[(unsigned long int)(-cc-1)] = true;
}
}
Image -> SetScalarComponentFromDouble(x,y,z,0,-cc);
}
for (id = N; id--;) {
Image -> GetPoint(id,r);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
cc = (long int)Volume -> GetTuple1(id);
if (cc) {
if (!HasJunction[(unsigned long int)(-cc-1)]) {
HasJunction[(unsigned long int)(-cc-1)] = true;
Junctions.insert(Junctions.begin(),id);
Volume -> SetTuple1(id,junction_label);
junction_label++;
n_fixed++;
} else {
Volume -> SetTuple1(id,-1);
}
} else {
Volume -> SetTuple1(id,0);
}
}
delete[] HasJunction;
#ifdef DEBUG
printf("\t#Components fixed = %ld\n",n_fixed);
#endif
Image -> GetPointData() -> GetScalars() -> Modified();
} else {
for (id = N; id--;) {
if (Image -> GetPointData() -> GetScalars() -> GetTuple1(id)) {
Volume -> SetTuple1(id,-1);
} else {
Volume -> SetTuple1(id,0);
}
}
Volume -> Modified();
}
#ifdef DEBUG
printf("Starting skeletonization...\n");
printf("\tSearching for junctions...\n");
#endif
for (id = N; id--;) {
Image -> GetPoint(id,r);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
if (Image->GetScalarComponentAsDouble(x,y,z,0)) {
if (GetNumberOfNeighborsWithoutValue(Image,x,y,z,0) != 2) {
Junctions.insert(Junctions.begin(),id);
Volume -> SetTuple1(id,junction_label);
junction_label++;
}
}
}
Volume -> Modified();
if (!Junctions.size()) {
printf("Z-stack seems to be empty. Aborting...\n");
return 0;
}
#ifdef DEBUG
printf("\t#Junctions before merging = %ld\n",Junctions.size());
#endif
// MERGING: During the merging process, voxels belonging to
// the same junction are merged together forming nodes.
while (JunctionsMerge(Junctions,Image,Volume));
// Listing all nodes label we have until this point
std::list<long int> Labels;
std::list<long int>::iterator itLabel;
for (itId=Junctions.begin(); itId!=Junctions.end(); itId++) {
Labels.insert(Labels.begin(),(long int)Volume->GetTuple1(*itId));
}
// UNIQUE of labels
Labels.sort(); // must sort first
Labels.unique();
long int NumberOfNodes = Labels.size();
#ifdef DEBUG
printf("\t#Junctions (nodes) after merging = %ld\n",NumberOfNodes);
#endif
// COORDINATES of nodes
// Vectors with static size to make the average calculation easy.
long int node;
double *X = new double[NumberOfNodes]; //Vector for x-coordinate
double *Y = new double[NumberOfNodes]; //Vector for y-coordinate
double *Z = new double[NumberOfNodes]; //Vector for z-coordinate
double *S = new double[NumberOfNodes]; //Vector for junctions size
int *K = new int[NumberOfNodes]; //Vector for junctions degree
for (node = 0; node < NumberOfNodes; node++) {
K[node] = 0;
X[node] = Y[node] = Z[node] = S[node] = 0.0;
}
for (itId=Junctions.begin(); itId!=Junctions.end(); itId++) {
junction_label = (long int)Volume -> GetTuple1(*itId);
itLabel = std::find(Labels.begin(),Labels.end(),junction_label);
node = (long int)std::distance(Labels.begin(),itLabel);
Volume -> SetTuple1(*itId,node+1);
Image -> GetPoint(*itId,r);
X[node] += r[0];
Y[node] += r[1];
Z[node] += r[2];
S[node] ++;
}
Volume -> Modified();
// Dynamic list to make easy the insertion of the coordinates
// of remaining voxels detected during the edge tracking process.
std::list<double> PointsListX;
std::list<double> PointsListY;
std::list<double> PointsListZ;
for (node=0;node<NumberOfNodes;node++) {
PointsListX.insert(PointsListX.end(),X[node]/S[node]);
PointsListY.insert(PointsListY.end(),Y[node]/S[node]);
PointsListZ.insert(PointsListZ.end(),Z[node]/S[node]);
}
delete[] X; delete[] Y; delete[] Z; delete[] S;
// CellArray to add new edges as they are being tracked.
vtkSmartPointer<vtkCellArray> EdgeArray = vtkSmartPointer<vtkCellArray>::New();
bool _should_add;
itId = Junctions.begin();
long int voxel_label = NumberOfNodes;
long int junction_label_left, junction_label_right;
long int source_node, target_node;
while (itId != Junctions.end()) {
Image -> GetPoint(*itId,r);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
if (GetNumberOfNeighborsWithValue(Image,Volume,x,y,z,-1)) {
_should_add = true;
//Tracking new edge
std::list<vtkIdType> Edge = GetEdgeStartingAt(x,y,z,Image,Volume);
//Identifying junctions on left side of the edge
source_node = Volume -> GetTuple1(*itId);
//Identifying junctions on right side of the edge
Image -> GetPoint(Edge.back(),r);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
target_node = Volume -> GetTuple1(GetOneNeighborWithoutValue(x,y,z,Image,Volume,source_node));
// When target_node is equal to 0 at this point, we are
// dealing with loops. These loops can be real loops or noise
// loops of very small length. This very short loops are often
// related to noise around junctions or 1-voxel holes in the
// data.
// @@PARAMETER: Minimum loop length (in voxels)
if (!target_node) {
target_node = source_node;
if (Edge.size() < 3) _should_add = false;
}
if (_should_add) {
// Creating new cell for this edge
EdgeArray -> InsertNextCell(Edge.size()+2);
// Adding node 1
EdgeArray -> InsertCellPoint(source_node-1);
// Addint the new points coordinates as well as the edge itself
for (std::list<vtkIdType>::iterator itIde=Edge.begin(); itIde!=Edge.end(); itIde++) {
Image -> GetPoint(*itIde,r);
PointsListX.insert(PointsListX.end(),r[0]);
PointsListY.insert(PointsListY.end(),r[1]);
PointsListZ.insert(PointsListZ.end(),r[2]);
EdgeArray -> InsertCellPoint(voxel_label);
voxel_label++;
}
// Adding node 2
EdgeArray -> InsertCellPoint(target_node-1);
// Updating nodes degree
K[source_node-1]++;
K[target_node-1]++;
}
} else {
Junctions.erase(itId++);
}
}
vtkSmartPointer<vtkPoints> Points = vtkSmartPointer<vtkPoints>::New();
Points -> SetNumberOfPoints(PointsListX.size());
#ifdef DEBUG
printf("#Points in vtkPoints = %lld\n",Points -> GetNumberOfPoints());
#endif
voxel_label = 0;
std::list<double>::iterator itX = PointsListX.begin();
std::list<double>::iterator itY = PointsListY.begin();
std::list<double>::iterator itZ = PointsListZ.begin();
while (itX != PointsListX.end()) {
Points -> SetPoint(voxel_label,*itX,*itY,*itZ);
itX++; itY++; itZ++;
voxel_label++;
}
Points -> Modified();
PointsListX.clear();
PointsListY.clear();
PointsListZ.clear();
// Creating raw polyData
vtkSmartPointer<vtkPolyData> PolyData = vtkPolyData::New();
PolyData -> SetPoints(Points);
PolyData -> SetLines(EdgeArray);
PolyData -> Modified();
PolyData -> BuildLinks();
long int nedges_before_filtering = PolyData -> GetNumberOfCells();
#ifdef DEBUG
printf("\t#Edges before filtering = %ld\n",nedges_before_filtering);
SavePolyData(PolyData,(mitoObject->FileName+"_skeleton_raw.vtk").c_str());
#endif
// PolyData filtering by removing degree-2 nodes. These nodes rise
// for two reasons: 1) very short edges that are not detected,
// although the bifurcation is detected. 2) Short loops that were
// removed.
#ifdef DEBUG
printf("\t#Filtering...\n");
#endif
while (
MergeEdgesOfDegree2Nodes(PolyData,nedges_before_filtering,K)
);
#ifdef DEBUG
printf("\t#Creating new ids...\n");
#endif
//Creating a list with final Ids of nodes after degree-2 nodes
//deletetion.
long int valid_id = 0;
long int *ValidId = new long int[NumberOfNodes];
for (node = 0; node < NumberOfNodes; node++) {
if (K[node] > 0) {
//printf("%d] - k = %d\n",(int)node,(int)K[node]);
ValidId[node] = valid_id;
valid_id++;
} else {
ValidId[node] = -1;
}
}
// for (node = 0; node < NumberOfNodes; node++) {
// printf("%d\t%d\n",(int)node,(int)ValidId[node]);
// }
//Creating an array called nodes used to mark true nodes
vtkSmartPointer<vtkTypeInt64Array> TrueNode = vtkSmartPointer<vtkTypeInt64Array>::New();
TrueNode -> SetNumberOfComponents(1);
TrueNode -> SetNumberOfTuples(PolyData->GetNumberOfPoints());
TrueNode -> FillComponent(0,-1);
TrueNode -> SetName("Nodes");
valid_id = 0;
for (node = 0; node < NumberOfNodes; node++) {
if (ValidId[node]>-1) {
TrueNode -> SetTuple1(node,valid_id);
valid_id++;
}
}
TrueNode -> Modified();
PolyData -> GetPointData() -> AddArray(TrueNode);
// Export graph files