-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathMitoGraph.cxx
More file actions
1889 lines (1537 loc) · 67.8 KB
/
MitoGraph.cxx
File metadata and controls
1889 lines (1537 loc) · 67.8 KB
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
// ==================================================================
// MitoGraph: Quantifying Mitochondrial Content in Living Cells
// Written by Matheus P. Viana - vianamp@gmail.com - 2018.01.08
// Last update: 2024.06.20
//
// Susanne Rafelski Lab, University of California Irvine
//
// The official documentation can be found at
//
// The official software website
// - https://github.com/vianamp/MitoGraph
//
// A protocol paper describing how to use MitoGraph is available in:
// Quantifying mitochondrial content in living cells
// http://www.sciencedirect.com/science/article/pii/S0091679X14000041
// ==================================================================
#include "ssThinning.h"
#include "MitoThinning.h"
double _rad = 0.150;
double _dxy, _dz = -1.0;
bool _export_graph_files = true;
bool _export_image_binary = false;
bool _export_image_resampled = false;
bool _scale_polydata_before_save = true;
bool _export_nodes_label = true;
double _div_threshold = 0.1666667;
bool _checkonly = false;
double _resample = -1.0;
bool _improve_skeleton_quality = true; // when this is true nodes with degree zero
// expanded and detected. Additional checking
// is also done to garantee that all non-zero
// voxels were analysized.
std::string MITOGRAPH_VERSION = "v3.1";
// |------06------|
// |------------------------18------------------------|
// |---------------------------------------26----------------------------------|
int ssdx_sort[26] = { 0,-1, 0, 1, 0, 0,-1, 0, 1, 0,-1, 1, 1,-1,-1, 0, 1, 0, -1, 1, 1,-1,-1, 1, 1,-1};
int ssdy_sort[26] = { 0, 0,-1, 0, 1, 0, 0,-1, 0, 1,-1,-1, 1, 1, 0,-1, 0, 1, -1,-1, 1, 1,-1,-1, 1, 1};
int ssdz_sort[26] = {-1, 0, 0, 0, 0, 1,-1,-1,-1,-1, 0, 0, 0, 0, 1, 1, 1, 1, -1,-1,-1,-1, 1, 1, 1, 1};
/**========================================================
Auxiliar functions
=========================================================*/
// This routine returns the x of the id-th point of a 3D volume
// of size Dim[0]xDim[1]xDim[2]
int GetX(vtkIdType id, int *Dim);
// This routine returns the y of the id-th point of a 3D volume
// of size Dim[0]xDim[1]xDim[2]
int GetY(vtkIdType id, int *Dim);
// This routine returns the z of the id-th point of a 3D volume
// of size Dim[0]xDim[1]xDim[2]
int GetZ(vtkIdType id, int *Dim);
// This routine returns the id of a point located at coordinate
// (x,y,z) of a 3D volume of size Dim[0]xDim[1]xDim[2]
vtkIdType GetId(int x, int y, int z, int *Dim);
// Swap values
void Swap(double *x, double *y);
// Simple sorting algorithm and the output is such that
// l3 >= l2 >= l3
void Sort(double *l1, double *l2, double *l3);
// Calculate the Frobenius norm of a given 3x3 matrix
// http://mathworld.wolfram.com/FrobeniusNorm.html
double FrobeniusNorm(double M[3][3]);
// This routine scales the polydata points to the correct dimension
// given by parameters _dxy and _dz.
void ScalePolyData(vtkSmartPointer<vtkPolyData> PolyData, _mitoObject *mitoObject);
// Stores all files with a given extension in a vector
int ScanFolderForThisExtension(std::string _impath, std::string ext, std::vector<std::string> List);
/* ================================================================
IMAGE TRANSFORM
=================================================================*/
// This routine converts 16-bit volumes into 8-bit volumes by
// linearly scaling the original range of intensities [min,max]
// in [0,255] (http://rsbweb.nih.gov/ij/docs/guide/146-28.html)
vtkSmartPointer<vtkImageData> Convert16To8bit(vtkSmartPointer<vtkImageData> Image);
// Apply a threshold to a ImageData and converts the result in
// a 8-bit ImageData.
vtkSmartPointer<vtkImageData> BinarizeAndConvertDoubleToChar(vtkSmartPointer<vtkImageData> Image, double threshold);
// Fill holes in the 3D image
void FillHoles(vtkSmartPointer<vtkImageData> ImageData);
// This routine uses a nearest neighbour filter to deblur the
// 16bit original image before applying MitoGraph.
// [1] - Qiang Wu Fatima A. Merchant Kenneth R. Castleman
// Microscope Image Processing (pg.340)
// ????
/* ================================================================
I/O ROUTINES
=================================================================*/
// Export maximum projection of a given ImageData as a
// PNG file.
void ExportMaxProjection(vtkSmartPointer<vtkImageData> Image, const char FileName[], bool binary);
// Export maximum projection of bottom and top parts of
// a given Tiff image as a PNG file as well as the polydata
// surface points
void ExportDetailedMaxProjection(_mitoObject *mitoObject);
// Export results in global as well as individual files
void DumpResults(_mitoObject mitoObject);
// Export configuration file used to run MitoGraph
void ExportConfigFile(_mitoObject *mitoObject);
/* ================================================================
ROUTINES FOR VESSELNESS CALCUATION VIA DISCRETE APPROCH
=================================================================*/
// This routine uses a discrete differential operator to
// calculate the derivatives of a given 3D volume
void GetImageDerivativeDiscrete(vtkSmartPointer<vtkDataArray> Image, int *dim, char direction, vtkSmartPointer<vtkFloatArray> Derivative);
// This routine calculate the Hessian matrix for each point
// of a 3D volume and its eigenvalues (Discrete Approach)
void GetHessianEigenvaluesDiscrete(double sigma, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkDoubleArray> L1, vtkSmartPointer<vtkDoubleArray> L2, vtkSmartPointer<vtkDoubleArray> L3);
void GetHessianEigenvaluesDiscreteZDependentThreshold(double sigma, vtkImageData *Image, vtkSmartPointer<vtkDoubleArray> L1, vtkSmartPointer<vtkDoubleArray> L2, vtkSmartPointer<vtkDoubleArray> L3, _mitoObject *mitoObjectt);
// Calculate the vesselness at each point of a 3D volume based
// based on the Hessian eigenvalues
void GetVesselness(double sigma, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkDoubleArray> L1, vtkSmartPointer<vtkDoubleArray> L2, vtkSmartPointer<vtkDoubleArray> L3, _mitoObject *mitoObjectt);
// Calculate the vesselness over a range of different scales
int MultiscaleVesselness(_mitoObject *mitoObject);
/* ================================================================
DIVERGENCE FILTER
=================================================================*/
// This routine calculates the divergence filter of a 3D volume
// based on the orientation of the gradient vector field
void GetDivergenceFilter(int *Dim, vtkSmartPointer<vtkDoubleArray> Scalars);
/* ================================================================
WIDTH ANALYSIS
=================================================================*/
// Approximation of tubule width by the distance of the skeleton
// to the closest point over the surface.
void EstimateTubuleWidth(vtkSmartPointer<vtkPolyData> Skeleton, vtkSmartPointer<vtkPolyData> Surface, _mitoObject *mitoObject);
/* ================================================================
INTENSITY MAPPING
=================================================================*/
// Intensities of the original TIFF image is mapped into a scalar
// component of the skeleton.
void MapImageIntensity(vtkSmartPointer<vtkPolyData> Skeleton, vtkSmartPointer<vtkImageData> ImageData, int nneigh);
/**========================================================
Auxiliar functions
=========================================================*/
int GetX(vtkIdType id, int *Dim) {
return (int) ( id % (vtkIdType)Dim[0] );
}
int GetY(vtkIdType id, int *Dim) {
return (int) ( ( id % (vtkIdType)(Dim[0]*Dim[1]) ) / (vtkIdType)Dim[0] );
}
int GetZ(vtkIdType id, int *Dim) {
return (int) ( id / (vtkIdType)(Dim[0]*Dim[1]) );
}
vtkIdType GetId(int x, int y, int z, int *Dim) {
return (vtkIdType)(x+y*Dim[0]+z*Dim[0]*Dim[1]);
}
vtkIdType GetReflectedId(int x, int y, int z, int *Dim) {
int rx = ceil(0.5*Dim[0]);
int ry = ceil(0.5*Dim[1]);
int rz = ceil(0.5*Dim[2]);
int sx = (x-(rx-0.5)<0) ? -rx : Dim[0]-rx;
int sy = (y-(ry-0.5)<0) ? -ry : Dim[1]-ry;
int sz = (z-(rz-0.5)<0) ? -rz : Dim[2]-rz;
return GetId(x-sx,y-sy,z-sz,Dim);
}
void Swap(double *x, double *y) {
double t = *y; *y = *x; *x = t;
}
void Sort(double *l1, double *l2, double *l3) {
if (fabs(*l1) > fabs(*l2)) Swap(l1,l2);
if (fabs(*l2) > fabs(*l3)) Swap(l2,l3);
if (fabs(*l1) > fabs(*l2)) Swap(l1,l2);
}
double FrobeniusNorm(double M[3][3]) {
double f = 0.0;
for (int i = 3;i--;)
for (int j = 3;j--;)
f += M[i][j]*M[i][j];
return sqrt(f);
}
void ScalePolyData(vtkSmartPointer<vtkPolyData> PolyData, _mitoObject *mitoObject) {
double r[3];
vtkPoints *Points = PolyData -> GetPoints();
for (vtkIdType id = 0; id < Points -> GetNumberOfPoints(); id++) {
Points -> GetPoint(id,r);
Points -> SetPoint(id,_dxy*(r[0]+mitoObject->Ox),_dxy*(r[1]+mitoObject->Oy),_dz*(r[2]+mitoObject->Oz));
}
Points -> Modified();
}
double SampleBackgroundIntensity(vtkDataArray *Scalar) {
int N = 1000;
double v = 1E6;
vtkIdType i, j;
for (i = N; i--;) {
j = (vtkIdType) (rand() % (Scalar->GetNumberOfTuples()));
v = (Scalar->GetTuple1(j)<v) ? Scalar->GetTuple1(j) : v;
}
return v;
}
int PoissonGen(double mu) {
int k = 0;
double p = 1.0, L = exp(-mu);
do {
k++;
p *= (double)(rand()) / RAND_MAX;
} while (p>L);
return k;
}
int ScanFolderForThisExtension(std::string _root, std::string ext, std::vector<std::string> *List) {
DIR *dir;
int ext_p;
struct dirent *ent;
std::string _dir_name;
if ((dir = opendir (_root.c_str())) != NULL) {
while ((ent = readdir (dir)) != NULL) {
_dir_name = std::string(ent->d_name);
ext_p = (int)_dir_name.find(ext);
if (ext_p > 0) {
#ifdef DEBUG
printf("File found: %s\n",_dir_name.c_str());
#endif
List -> push_back(std::string(_root)+_dir_name.substr(0,ext_p));
}
}
closedir (dir);
} else {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/* ================================================================
I/O ROUTINES
=================================================================*/
void ExportMaxProjection(vtkSmartPointer<vtkImageData> Image, const char FileName[]) {
#ifdef DEBUG
printf("Saving Max projection...\n");
#endif
int *Dim = Image -> GetDimensions();
vtkSmartPointer<vtkImageData> MaxP = vtkSmartPointer<vtkImageData>::New();
MaxP -> SetDimensions(Dim[0],Dim[1],1);
vtkIdType N = Dim[0] * Dim[1];
vtkSmartPointer<vtkUnsignedCharArray> MaxPArray = vtkSmartPointer<vtkUnsignedCharArray>::New();
MaxPArray -> SetNumberOfComponents(1);
MaxPArray -> SetNumberOfTuples(N);
int x, y, z;
double v, vproj;
for (x = Dim[0]; x--;) {
for (y = Dim[1]; y--;) {
vproj = 0;
for (z = Dim[2]; z--;) {
v = Image -> GetScalarComponentAsFloat(x,y,z,0);
vproj = (v > vproj) ? v : vproj;
}
double point[3] = {(double)x, (double)y, 0.0};
MaxPArray -> SetTuple1(MaxP->FindPoint(point),(unsigned char)vproj);
}
}
MaxPArray -> Modified();
MaxP -> GetPointData() -> SetScalars(MaxPArray);
vtkSmartPointer<vtkPNGWriter> PNGWriter = vtkSmartPointer<vtkPNGWriter>::New();
PNGWriter -> SetFileName(FileName);
PNGWriter -> SetFileDimensionality(2);
PNGWriter -> SetCompressionLevel(0);
PNGWriter -> SetInputData(MaxP);
PNGWriter -> Write();
#ifdef DEBUG
printf("File Saved!\n");
#endif
}
void ExportDetailedMaxProjection(_mitoObject *mitoObject) {
// =======================================================================================
// | | | | |
// Total MaxProj | First | Top | Top | Top |
// (original tiff) | Slice | 8 slices | surface | skeleton |
// | | | | |
// =======================================================================================
// | | | | |
// Total MaxProj | Last | Bottom | Bottom | Bottom |
// (surface) | Slice | 8 slices | surface | skeleton |
// | | | | |
// =======================================================================================
#ifdef DEBUG
printf("Saving Detailed Max projection...\n");
#endif
vtkSmartPointer<vtkTIFFReader> TIFFReader = vtkSmartPointer<vtkTIFFReader>::New();
int errlog = TIFFReader -> CanReadFile((mitoObject->FileName+".tif").c_str());
// File cannot be opened
if (!errlog) {
printf("File %s connot be opened.\n",(mitoObject->FileName+".tif").c_str());
} else {
// Loading TIFF File
TIFFReader -> SetFileName((mitoObject->FileName+".tif").c_str());
TIFFReader -> Update();
vtkSmartPointer<vtkImageData> Image = TIFFReader -> GetOutput();
//16bit to 8bit Conversion
Image = Convert16To8bit(Image);
// Loading PolyData Surface
vtkSmartPointer<vtkPolyDataReader> PolyDaTaReader = vtkSmartPointer<vtkPolyDataReader>::New();
PolyDaTaReader -> SetFileName((mitoObject->FileName+"_mitosurface.vtk").c_str());
PolyDaTaReader -> Update();
vtkSmartPointer<vtkPolyData> Surface = PolyDaTaReader -> GetOutput();
// Loading Skeleton
vtkSmartPointer<vtkPolyDataReader> PolyDaTaReaderSkell = vtkSmartPointer<vtkPolyDataReader>::New();
PolyDaTaReaderSkell -> SetFileName((mitoObject->FileName+"_skeleton.vtk").c_str());
PolyDaTaReaderSkell -> Update();
vtkSmartPointer<vtkPolyData> Skeleton = PolyDaTaReaderSkell -> GetOutput();
#ifdef DEBUG
printf("\t#Points [%s] = %d\n",(mitoObject->FileName+"_mitosurface.vtk").c_str(),(int)Surface->GetNumberOfPoints());
printf("\t#Points [%s] = %d\n",(mitoObject->FileName+"_skeleton.vtk").c_str(),(int)Skeleton->GetNumberOfPoints());
#endif
// Stack Dimensions
int *Dim = Image -> GetDimensions();
#ifdef DEBUG
printf("Dim = [%d,%d,%d]\n",Dim[0],Dim[1],Dim[2]);
#endif
// Surface Bounds
double *Bounds = Surface -> GetBounds();
int zi = round(Bounds[4]/_dz); zi -= (zi>1) ? 1 : 0;
int zf = round(Bounds[5]/_dz); zf += (zi<Dim[2]-1) ? 1 : 0;
#ifdef DEBUG
printf("Z = [%d,%d]\n",zi,zf);
#endif
// Plane
vtkSmartPointer<vtkImageData> Plane = vtkSmartPointer<vtkImageData>::New();
Plane -> SetDimensions(5*Dim[0],2*Dim[1],1);
vtkIdType N = 10 * Dim[0] * Dim[1];
// Scalar VEctor
vtkSmartPointer<vtkUnsignedCharArray> MaxPArray = vtkSmartPointer<vtkUnsignedCharArray>::New();
MaxPArray -> SetNumberOfComponents(1);
MaxPArray -> SetNumberOfTuples(N);
double range[2];
Image -> GetScalarRange(range);
MaxPArray -> FillComponent(0,range[0]);
#ifdef DEBUG
printf("Range = [%f,%f]\n",range[0],range[1]);
#endif
//Max Projection bottom
int x, y, z;
double v, vproj;
for (x = Dim[0]; x--;) {
for (y = Dim[1]; y--;) {
vproj = 0;
for (z = zi; z <= zi+8; z++) {
v = Image -> GetScalarComponentAsFloat(x,y,z,0);
vproj = (v > vproj) ? v : vproj;
}
double point[3] = {(double)(x+2*Dim[0]), (double)y, 0.0};
MaxPArray -> SetTuple1(Plane->FindPoint(point),(unsigned char)vproj);
}
}
//Max Projection top
for (x = Dim[0]; x--;) {
for (y = Dim[1]; y--;) {
vproj = 0;
for (z = zf-8; z <= zf; z++) {
v = Image -> GetScalarComponentAsFloat(x,y,z,0);
vproj = (v > vproj) ? v : vproj;
}
double point[3] = {(double)(x+2*Dim[0]), (double)(y+Dim[1]), 0.0};
MaxPArray -> SetTuple1(Plane->FindPoint(point),(unsigned char)vproj);
}
}
// Partial surface Projection
double r[3];
for (vtkIdType id=0; id < Surface -> GetPoints() -> GetNumberOfPoints(); id++) {
Surface -> GetPoints() -> GetPoint(id,r);
x = round(r[0]/_dxy);
y = round(r[1]/_dxy);
z = round(r[2]/_dz);
if ( z >= zi && z <= zi+8 ) {
double point[3] = {(double)(x+3*Dim[0]), (double)y, 0.0};
MaxPArray -> SetTuple1(Plane->FindPoint(point),255);
}
if ( z >= zf-8 && z <= zf ) {
double point2[3] = {(double)(x+3*Dim[0]), (double)(y+Dim[1]), 0.0};
MaxPArray -> SetTuple1(Plane->FindPoint(point2),255);
}
}
// Complete surface Projection
for (vtkIdType id=0; id < Surface -> GetPoints() -> GetNumberOfPoints(); id++) {
Surface -> GetPoints() -> GetPoint(id,r);
x = round(r[0]/_dxy);
y = round(r[1]/_dxy);
z = round(r[2]/_dz);
double point[3] = {(double)x, (double)y, 0.0};
MaxPArray -> SetTuple1(Plane->FindPoint(point),255);
}
// Partial skeleton Projection
for (vtkIdType id=0; id < Skeleton -> GetPoints() -> GetNumberOfPoints(); id++) {
Skeleton -> GetPoints() -> GetPoint(id,r);
x = round(r[0]/_dxy);
y = round(r[1]/_dxy);
z = round(r[2]/_dz);
if ( z >= zi && z <= zi+8 ) {
double point[3] = {(double)(x+4*Dim[0]), (double)y, 0.0};
MaxPArray -> SetTuple1(Plane->FindPoint(point),255);
}
if ( z >= zf-8 && z <= zf ) {
double point2[3] = {(double)(x+4*Dim[0]), (double)(y+Dim[1]), 0.0};
MaxPArray -> SetTuple1(Plane->FindPoint(point2),255);
}
}
//Complete max projection
for (x = Dim[0]; x--;) {
for (y = Dim[1]; y--;) {
vproj = 0;
for (z = 0; z < Dim[2]; z++) {
v = Image -> GetScalarComponentAsFloat(x,y,z,0);
vproj = (v > vproj) ? v : vproj;
}
double point[3] = {(double)x, (double)(y+Dim[1]), 0.0};
MaxPArray -> SetTuple1(Plane->FindPoint(point),(unsigned char)vproj);
}
}
//First and last slice
for (x = Dim[0]; x--;) {
for (y = Dim[1]; y--;) {
v = Image -> GetScalarComponentAsFloat(x,y,0,0);
double point1[3] = {(double)(x+Dim[1]), (double)y, 0.0};
MaxPArray -> SetTuple1(Plane->FindPoint(point1),(unsigned char)v);
v = Image -> GetScalarComponentAsFloat(x,y,Dim[2]-1,0);
double point2[3] = {(double)(x+Dim[1]), (double)(y+Dim[1]), 0.0};
MaxPArray -> SetTuple1(Plane->FindPoint(point2),(unsigned char)v);
}
}
MaxPArray -> Modified();
Plane -> GetPointData() -> SetScalars(MaxPArray);
// Saving PNG File
vtkSmartPointer<vtkPNGWriter> PNGWriter = vtkSmartPointer<vtkPNGWriter>::New();
PNGWriter -> SetFileName((mitoObject->FileName+"_detailed.png").c_str());
PNGWriter -> SetFileDimensionality(2);
PNGWriter -> SetCompressionLevel(0);
PNGWriter -> SetInputData(Plane);
PNGWriter -> Write();
printf("%s\t[done]\n",mitoObject->FileName.c_str());
}
#ifdef DEBUG
printf("File Saved!\n");
#endif
}
void DumpResults(const _mitoObject mitoObject) {
// Saving network attributes in the individual file
FILE *findv = fopen((mitoObject.FileName+".mitograph").c_str(),"w");
for (int i = 0; i < mitoObject.attributes.size(); i++)
fprintf(findv,"%s\t",mitoObject.attributes[i].name.c_str());
fprintf(findv,"\n");
for (int i = 0; i < mitoObject.attributes.size(); i++)
fprintf(findv,"%1.5f\t",mitoObject.attributes[i].value);
fprintf(findv,"\n");
fclose(findv);
// Also printing on the screen
printf("%s\t[done]\n",mitoObject.FileName.c_str());
}
void ExportConfigFile(const _mitoObject mitoObject) {
const char *_t = "[True]";
const char *_f = "[False]";
FILE *f = fopen((mitoObject.Folder+"/mitograph.config").c_str(),"w");
if (mitoObject._adaptive_threshold) {
fprintf(f,"MitoGraph %s [Adaptive Algorithm]\n",MITOGRAPH_VERSION.c_str());
} else {
fprintf(f,"MitoGraph %s\n",MITOGRAPH_VERSION.c_str());
}
fprintf(f,"Folder: %s\n",mitoObject.Folder.c_str());
if (mitoObject._adaptive_threshold) {
fprintf(f,"NBlocks: %d\n",mitoObject._nblks);
}
fprintf(f,"Pixel size: -xy %1.4fum, -z %1.4fum\n",_dxy,_dz);
fprintf(f,"Average tubule radius: -r %1.4fum\n",_rad);
fprintf(f,"Scales: -scales %1.2f",mitoObject._sigmai);
for ( double sigma = mitoObject._sigmai+mitoObject._dsigma; sigma < mitoObject._sigmaf+0.5*mitoObject._dsigma; sigma += mitoObject._dsigma )
fprintf(f," %1.2f",sigma);
fprintf(f,"\nPost-divergence threshold: -threshold %1.5f\n",_div_threshold);
fprintf(f,"Input type: %s\n",mitoObject.Type.c_str());
fprintf(f,"Analyze: %s\n",mitoObject._analyze?_t:_f);
fprintf(f,"Binary input: %s\n",mitoObject._binary_input?_t:_f);
time_t now = time(0);
fprintf(f,"%s\n",ctime(&now));
fclose(f);
}
/* ================================================================
IMAGE TRANSFORM
=================================================================*/
vtkSmartPointer<vtkImageData> Convert16To8bit(vtkSmartPointer<vtkImageData> Image) {
// 8-Bit images
if (Image -> GetScalarType() == VTK_UNSIGNED_CHAR) {
return Image;
// 16-Bit images
} else if (Image -> GetScalarType() == VTK_UNSIGNED_SHORT) {
#ifdef DEBUG
printf("Converting from 16-bit to 8-bit...\n");
#endif
vtkSmartPointer<vtkImageData> Image8 = vtkImageData::New();
Image8 -> ShallowCopy(Image);
vtkDataArray *ScalarsShort = Image -> GetPointData() -> GetScalars();
unsigned long int N = ScalarsShort -> GetNumberOfTuples();
double range[2];
ScalarsShort -> GetRange(range);
#ifdef DEBUG
printf("\tOriginal intensities range: [%d-%d]\n",(int)range[0],(int)range[1]);
#endif
vtkSmartPointer<vtkUnsignedCharArray> ScalarsChar = vtkSmartPointer<vtkUnsignedCharArray>::New();
ScalarsChar -> SetNumberOfComponents(1);
ScalarsChar -> SetNumberOfTuples(N);
double x, y;
vtkIdType id;
for ( id = N; id--; ) {
x = ScalarsShort -> GetTuple1(id);
y = 255.0 * (x-range[0]) / (range[1]-range[0]);
ScalarsChar -> SetTuple1(id,(unsigned char)y);
}
ScalarsChar -> Modified();
Image8 -> GetPointData() -> SetScalars(ScalarsChar);
return Image8;
// Other depth
} else {
return NULL;
}
}
vtkSmartPointer<vtkImageData> BinarizeAndConvertDoubleToChar(vtkSmartPointer<vtkImageData> Image, double threshold) {
vtkSmartPointer<vtkImageData> Image8 = vtkImageData::New();
Image8 -> ShallowCopy(Image);
vtkDataArray *ScalarsDouble = Image -> GetPointData() -> GetScalars();
unsigned long int N = ScalarsDouble -> GetNumberOfTuples();
double range[2];
ScalarsDouble -> GetRange(range);
vtkSmartPointer<vtkUnsignedCharArray> ScalarsChar = vtkSmartPointer<vtkUnsignedCharArray>::New();
ScalarsChar -> SetNumberOfComponents(1);
ScalarsChar -> SetNumberOfTuples(N);
double x;
if (threshold > 0) {
for ( vtkIdType id = N; id--; ) {
x = ScalarsDouble -> GetTuple1(id);
if (x<=threshold) {
ScalarsChar -> SetTuple1(id,0);
} else {
ScalarsChar -> SetTuple1(id,255);
}
}
} else {
for ( vtkIdType id = N; id--; ) {
x = ScalarsDouble -> GetTuple1(id);
ScalarsChar -> SetTuple1(id,(int)(255*(x-range[0])/(range[1]-range[0])));
}
}
ScalarsChar -> Modified();
Image8 -> GetPointData() -> SetScalars(ScalarsChar);
return Image8;
}
void FillHoles(vtkSmartPointer<vtkImageData> ImageData) {
#ifdef DEBUG
printf("\tSearching for holes in the image...\n");
#endif
int *Dim = ImageData -> GetDimensions();
vtkIdType N = ImageData -> GetNumberOfPoints();
vtkIdType i, s, ido, id;
int x, y, z;
double v, r[3];
bool find = true;
long long int ro[3];
long int scluster, label;
ro[0] = Dim[0] * Dim[1] * Dim[2];
ro[1] = Dim[0] * Dim[1];
vtkSmartPointer<vtkIdList> CurrA = vtkSmartPointer<vtkIdList>::New();
vtkSmartPointer<vtkIdList> NextA = vtkSmartPointer<vtkIdList>::New();
vtkSmartPointer<vtkTypeInt64Array> CSz = vtkSmartPointer<vtkTypeInt64Array>::New();
vtkSmartPointer<vtkTypeInt64Array> Volume = vtkSmartPointer<vtkTypeInt64Array>::New();
Volume -> SetNumberOfComponents(1);
Volume -> SetNumberOfTuples(N);
Volume -> FillComponent(0,0);
for (x = 1; x < Dim[0]-1; x++) {
for (y = 1; y < Dim[1]-1; y++) {
for (z = 1; z < Dim[2]-1; z++) {
double point[3] = {(double)x, (double)y, (double)z};
id = ImageData -> FindPoint(point);
if ((unsigned short int)ImageData->GetScalarComponentAsDouble(x,y,z,0)) {
Volume -> SetTuple1(id,0);
} else {
Volume -> SetTuple1(id,1);
}
}
}
}
Volume -> Modified();
label = 0;
while (find) {
for (s = 0; s < CurrA->GetNumberOfIds(); s++) {
ido = CurrA -> GetId(s);
ImageData -> GetPoint(ido,r);
x = (int)r[0]; y = (int)r[1]; z = (int)r[2];
for (i = 0; i < 6; i++) {
double point[3] = {(double)(x+ssdx_sort[i]), (double)(y+ssdy_sort[i]), (double)(z+ssdz_sort[i])};
id = ImageData -> FindPoint(point);
v = Volume -> GetTuple1(id);
if ((long int)v > 0) {
NextA -> InsertNextId(id);
Volume -> SetTuple1(id,-label);
scluster++;
}
}
}
if (!NextA->GetNumberOfIds()) {
find = false;
for (id=ro[0]; id--;) {
v = Volume -> GetTuple1(id);
if ((long int)v > 0) {
find = true;
ro[0] = id;
break;
}
}
if (label) {
CSz -> InsertNextTuple1(scluster);
}
if (find) {
label++;
scluster = 1;
Volume -> SetTuple1(id,-label);
CurrA -> InsertNextId(id);
}
} else {
CurrA -> Reset();
CurrA -> DeepCopy(NextA);
NextA -> Reset();
}
}
for (id = N; id--;) {
if ((long int)Volume->GetTuple1(id)<-1) {
ImageData -> GetPointData() -> GetScalars() -> SetTuple1(id,255);
}
}
ImageData -> GetPointData() -> GetScalars() -> Modified();
#ifdef DEBUG
printf("\tNumber of filled holes: %ld\n",(long int)CSz->GetNumberOfTuples()-1);
#endif
}
/* ================================================================
ROUTINES FOR VESSELNESS CALCUATION VIA DISCRETE APPROCH
=================================================================*/
void GetImageDerivativeDiscrete(vtkSmartPointer<vtkDataArray> Image, int *dim, char direction, vtkSmartPointer<vtkFloatArray> Derivative) {
#ifdef DEBUG
printf("Calculating Image Derivatives (Discrete)...\n");
#endif
double d, f1, f2;
vtkIdType i, j, k;
if (direction=='x') {
for (i = (vtkIdType)dim[0]; i--;) {
for (j = (vtkIdType)dim[1]; j--;) {
for (k = (vtkIdType)dim[2]; k--;) {
if (i==0) {
Image -> GetTuple(GetId(1,j,k,dim),&f1);
Image -> GetTuple(GetId(0,j,k,dim),&f2);
}
if (i==dim[0]-1) {
Image -> GetTuple(GetId(dim[0]-1,j,k,dim),&f1);
Image -> GetTuple(GetId(dim[0]-2,j,k,dim),&f2);
}
if (i>0&i<dim[0]-1) {
Image -> GetTuple(GetId(i+1,j,k,dim),&f1);
Image -> GetTuple(GetId(i-1,j,k,dim),&f2);
f1 /= 2.0; f2 /= 2.0;
}
d = f1 - f2;
Derivative -> SetTuple(GetId(i,j,k,dim),&d);
}
}
}
}
if (direction=='y') {
for (i = (vtkIdType)dim[0]; i--;) {
for (j = (vtkIdType)dim[1]; j--;) {
for (k = (vtkIdType)dim[2]; k--;) {
if (j==0) {
Image -> GetTuple(GetId(i,1,k,dim),&f1);
Image -> GetTuple(GetId(i,0,k,dim),&f2);
}
if (j==dim[1]-1) {
Image -> GetTuple(GetId(i,dim[1]-1,k,dim),&f1);
Image -> GetTuple(GetId(i,dim[1]-2,k,dim),&f2);
}
if (j>0&j<dim[1]-1) {
Image -> GetTuple(GetId(i,j+1,k,dim),&f1);
Image -> GetTuple(GetId(i,j-1,k,dim),&f2);
f1 /= 2.0; f2 /= 2.0;
}
d = f1 - f2;
Derivative -> SetTuple(GetId(i,j,k,dim),&d);
}
}
}
}
if (direction=='z') {
for (i = (vtkIdType)dim[0]; i--;) {
for (j = (vtkIdType)dim[1]; j--;) {
for (k = (vtkIdType)dim[2]; k--;) {
if (k==0) {
Image -> GetTuple(GetId(i,j,1,dim),&f1);
Image -> GetTuple(GetId(i,j,0,dim),&f2);
}
if (k==dim[2]-1) {
Image -> GetTuple(GetId(i,j,dim[2]-1,dim),&f1);
Image -> GetTuple(GetId(i,j,dim[2]-2,dim),&f2);
}
if (k>0&k<dim[2]-1) {
Image -> GetTuple(GetId(i,j,k+1,dim),&f1);
Image -> GetTuple(GetId(i,j,k-1,dim),&f2);
f1 /= 2.0; f2 /= 2.0;
}
d = f1 - f2;
Derivative -> SetTuple(GetId(i,j,k,dim),&d);
}
}
}
}
}
void GetHessianEigenvaluesDiscrete(double sigma, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkDoubleArray> L1, vtkSmartPointer<vtkDoubleArray> L2, vtkSmartPointer<vtkDoubleArray> L3) {
#ifdef DEBUG
printf("Calculating Hessian Eigeinvalues (Discrete)...\n");
#endif
int *Dim = Image -> GetDimensions();
vtkIdType id, N = Image -> GetNumberOfPoints();
double H[3][3], Eva[3], Eve[3][3], dxx, dyy, dzz, dxy, dxz, dyz, l1, l2, l3, frobnorm;
#ifdef DEBUG
printf("Calculating Gaussian Convolution...\n");
#endif
vtkSmartPointer<vtkImageGaussianSmooth> Gauss = vtkSmartPointer<vtkImageGaussianSmooth>::New();
Gauss -> SetInputData(Image);
Gauss -> SetDimensionality(3);
Gauss -> SetRadiusFactors(10,10,10);
Gauss -> SetStandardDeviations(sigma,sigma,sigma);
Gauss -> Update();
vtkFloatArray *ImageG = (vtkFloatArray*) Gauss -> GetOutput() -> GetPointData() -> GetScalars();
vtkSmartPointer<vtkFloatArray> Dx = vtkSmartPointer<vtkFloatArray>::New(); Dx -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dy = vtkSmartPointer<vtkFloatArray>::New(); Dy -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dz = vtkSmartPointer<vtkFloatArray>::New(); Dz -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dxx = vtkSmartPointer<vtkFloatArray>::New(); Dxx -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dyy = vtkSmartPointer<vtkFloatArray>::New(); Dyy -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dzz = vtkSmartPointer<vtkFloatArray>::New(); Dzz -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dxy = vtkSmartPointer<vtkFloatArray>::New(); Dxy -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dxz = vtkSmartPointer<vtkFloatArray>::New(); Dxz -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dyz = vtkSmartPointer<vtkFloatArray>::New(); Dyz -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Fro = vtkSmartPointer<vtkFloatArray>::New();
Fro -> SetNumberOfComponents(1);
Fro -> SetNumberOfTuples(N);
GetImageDerivativeDiscrete(ImageG,Dim,'x',Dx);
GetImageDerivativeDiscrete(ImageG,Dim,'y',Dy);
GetImageDerivativeDiscrete(ImageG,Dim,'z',Dz);
GetImageDerivativeDiscrete(Dx,Dim,'x',Dxx);
GetImageDerivativeDiscrete(Dy,Dim,'y',Dyy);
GetImageDerivativeDiscrete(Dz,Dim,'z',Dzz);
GetImageDerivativeDiscrete(Dy,Dim,'x',Dxy);
GetImageDerivativeDiscrete(Dz,Dim,'x',Dxz);
GetImageDerivativeDiscrete(Dz,Dim,'y',Dyz);
for ( id = N; id--; ) {
l1 = l2 = l3 = 0.0;
H[0][0]=Dxx->GetTuple1(id); H[0][1]=Dxy->GetTuple1(id); H[0][2]=Dxz->GetTuple1(id);
H[1][0]=Dxy->GetTuple1(id); H[1][1]=Dyy->GetTuple1(id); H[1][2]=Dyz->GetTuple1(id);
H[2][0]=Dxz->GetTuple1(id); H[2][1]=Dyz->GetTuple1(id); H[2][2]=Dzz->GetTuple1(id);
frobnorm = FrobeniusNorm(H);
if (H[0][0]+H[1][1]+H[2][2]<0.0) {
vtkMath::Diagonalize3x3(H,Eva,Eve);
l1 = Eva[0]; l2 = Eva[1]; l3 = Eva[2];
Sort(&l1,&l2,&l3);
}
L1 -> SetTuple1(id,l1);
L2 -> SetTuple1(id,l2);
L3 -> SetTuple1(id,l3);
Fro -> SetTuple1(id,frobnorm);
}
double ftresh,frobenius_norm_range[2];
Fro -> GetRange(frobenius_norm_range);
ftresh = sqrt(frobenius_norm_range[1]);
for ( id = N; id--; ) {
if ( Fro->GetTuple1(id) < ftresh) {
L1 -> SetTuple1(id,0.0);
L2 -> SetTuple1(id,0.0);
L3 -> SetTuple1(id,0.0);
}
}
L1 -> Modified();
L2 -> Modified();
L3 -> Modified();
}
void GetHessianEigenvaluesDiscreteZDependentThreshold(double sigma, vtkSmartPointer<vtkImageData> Image, vtkSmartPointer<vtkDoubleArray> L1, vtkSmartPointer<vtkDoubleArray> L2, vtkSmartPointer<vtkDoubleArray> L3, _mitoObject *mitoObject) {
#ifdef DEBUG
printf("Calculating Hessian Eigeinvalues (Discrete)...\n");
#endif
int *Dim = Image -> GetDimensions();
vtkIdType id, N = Image -> GetNumberOfPoints();
double H[3][3], Eva[3], Eve[3][3], dxx, dyy, dzz, dxy, dxz, dyz, l1, l2, l3, frobnorm;
#ifdef DEBUG
printf("Calculating Gaussian Convolution...\n");
#endif
vtkSmartPointer<vtkImageGaussianSmooth> Gauss = vtkSmartPointer<vtkImageGaussianSmooth>::New();
Gauss -> SetInputData(Image);
Gauss -> SetDimensionality(3);
Gauss -> SetRadiusFactors(10,10,10);
Gauss -> SetStandardDeviations(sigma,sigma,sigma);
Gauss -> Update();
vtkFloatArray *ImageG = (vtkFloatArray*) Gauss -> GetOutput() -> GetPointData() -> GetScalars();
vtkSmartPointer<vtkFloatArray> Dx = vtkSmartPointer<vtkFloatArray>::New(); Dx -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dy = vtkSmartPointer<vtkFloatArray>::New(); Dy -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dz = vtkSmartPointer<vtkFloatArray>::New(); Dz -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dxx = vtkSmartPointer<vtkFloatArray>::New(); Dxx -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dyy = vtkSmartPointer<vtkFloatArray>::New(); Dyy -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dzz = vtkSmartPointer<vtkFloatArray>::New(); Dzz -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dxy = vtkSmartPointer<vtkFloatArray>::New(); Dxy -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dxz = vtkSmartPointer<vtkFloatArray>::New(); Dxz -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Dyz = vtkSmartPointer<vtkFloatArray>::New(); Dyz -> SetNumberOfTuples(N);
vtkSmartPointer<vtkFloatArray> Fro = vtkSmartPointer<vtkFloatArray>::New();
Fro -> SetNumberOfComponents(1);
Fro -> SetNumberOfTuples(N);
GetImageDerivativeDiscrete(ImageG,Dim,'x',Dx);
GetImageDerivativeDiscrete(ImageG,Dim,'y',Dy);
GetImageDerivativeDiscrete(ImageG,Dim,'z',Dz);
GetImageDerivativeDiscrete(Dx,Dim,'x',Dxx);
GetImageDerivativeDiscrete(Dy,Dim,'y',Dyy);
GetImageDerivativeDiscrete(Dz,Dim,'z',Dzz);
GetImageDerivativeDiscrete(Dy,Dim,'x',Dxy);
GetImageDerivativeDiscrete(Dz,Dim,'x',Dxz);
GetImageDerivativeDiscrete(Dz,Dim,'y',Dyz);
int x, y, z;
int nblks = mitoObject->_nblks;
double ***FThresh = new double**[nblks];
for ( int qx = nblks; qx--; ) {
FThresh[qx] = new double*[nblks];
for ( int qy = nblks; qy--; ) {
FThresh[qx][qy] = new double[Dim[2]];
for ( id = Dim[2]; id--; ) {
FThresh[qx][qy][id] = 0.0;
}
}
}
for ( id = N; id--; ) {
l1 = l2 = l3 = 0.0;
H[0][0]=Dxx->GetTuple1(id); H[0][1]=Dxy->GetTuple1(id); H[0][2]=Dxz->GetTuple1(id);
H[1][0]=Dxy->GetTuple1(id); H[1][1]=Dyy->GetTuple1(id); H[1][2]=Dyz->GetTuple1(id);
H[2][0]=Dxz->GetTuple1(id); H[2][1]=Dyz->GetTuple1(id); H[2][2]=Dzz->GetTuple1(id);
frobnorm = FrobeniusNorm(H);
if (H[0][0]+H[1][1]+H[2][2]<0.0) {
vtkMath::Diagonalize3x3(H,Eva,Eve);
l1 = Eva[0]; l2 = Eva[1]; l3 = Eva[2];
Sort(&l1,&l2,&l3);
}
L1 -> SetTuple1(id,l1);
L2 -> SetTuple1(id,l2);
L3 -> SetTuple1(id,l3);
Fro -> SetTuple1(id,frobnorm);
x = GetX(id,Dim);
y = GetY(id,Dim);
z = GetZ(id,Dim);