-
Notifications
You must be signed in to change notification settings - Fork 33
/
drawvolume.pas
1768 lines (1665 loc) · 56.9 KB
/
drawvolume.pas
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
unit drawvolume;
{$mode Delphi}
{$H+} {$M+}
{$DEFINE DILATE}
interface
uses
VectorMath, Classes, SysUtils, SimdUtils, dialogs;
const
kDrawModeAppend = 0;
kDrawModeDelete = 1;
kDrawModeConstrain = 2;
kDrawModeDeleteDark = 3;
kDrawModeAddDark = 4;
kDrawModeDeleteBright = 5;
kDrawModeAddBright = 6;
Type
TSlice2D = array of single;
Type
TDraw = Class //(TNIfTI) // This is an actual class definition :
// Internal class field definitions - only accessible in this unit
private
dim3d: array [0..3] of int64; //unused,X,Y,Z voxels in volume space
dim2d: array [0..3] of int64; //orient,X,Y,Slice in slice space
currSlice, prevSlice, prevOrient: int64;
clickStartX, clickStartY,clickPrevX,clickPrevY: int64; //location of previous mouse buttons
colorLut: TLUT;
penColor : integer;
fOpacityFrac: single;
view3d, view2d, undo2d, modified2d: TUInt8s;
//start2dOXYZ, prev2dOXYZ : array [0..3] of integer; //orient,X,Y,Slice for pixel coordinates
doRedraw,doAlpha, isMouseDown, isModified, isModifiedSinceSave: boolean;
procedure borderPixel (x,y: int64);
procedure fillPixel (x,y: int64);
procedure fillPixelBound (x,y: int64);
function isFillNewColor (x,y: int64): boolean;
procedure setColor (x,y: int64; clr: byte);
procedure fillBubbles;
procedure fillRegion;
procedure doFloodFill(x,y: int64; newColor, oldColor: byte);
procedure voiMouseFloodFill(Color, Orient: int64; Xfrac, Yfrac, Zfrac: single);
procedure drawPixel (x,y: int64);
procedure DrawLine (x,y, x2, y2: int64);
procedure SmoothVol(lColor: int64; intenVol: TFloat32s);
protected
public
//constructor Create();
Filename: string;
PenColorOnRelease: integer;
property OpacityFraction: single read fOpacityFrac write fOpacityFrac;
property ColorTable: TLUT read colorLUt;
property VolRawBytes: TUInt8s read view3d;
function voiActiveOrient: integer;
property MouseDown: boolean read isMouseDown;
property ActivePenColor: integer read penColor write penColor;
property NeedsUpdate : boolean read isModified write isModified;
property NeedsSave: boolean read isModifiedSinceSave write isModifiedSinceSave;
function IsOpen: boolean;
function voiDescriptives: int64;
procedure PasteSlice2D(Orient: int64; var in2D, out3D: TUInt8s);
procedure voiCloseSlice;
procedure UpdateView3d;
procedure voiColor (idx, r, g, b: byte);
function voiIsEmpty: boolean;
function voiIsOpen: boolean;
procedure click2pix (var Xpix, Ypix: int64; Xfrac, Yfrac, Zfrac: single);
function setDim2D(Orient: int64): int64;
procedure CopySlice2D(Orient: int64; var out2D: TUInt8s);
procedure voiMouseDown(Color, Orient: int64; Xfrac, Yfrac, Zfrac: single); overload;
procedure voiMouseDown(Orient: int64; XYZfrac: TVec3); overload;
procedure voiMouseDown(Orient: int64; XYZfrac: TVec3; isInvertPenColor: boolean); overload;
procedure voiFloodFill(Orient: int64; XYZfrac: TVec3); overload;
procedure voiFloodFill(Orient: int64; XYZfrac: TVec3; isInvertPenColor: boolean); overload;
procedure voiPasteSlice(Xfrac, Yfrac, Zfrac: single);
procedure voiUndo;
procedure voiMouseUp ( autoClose, overwriteColors: boolean);
procedure preserveColors;
function voiMouseMove (Xfrac, Yfrac, Zfrac: single): boolean;
function Dim: TVec3i;
procedure voiCreate(X,Y,Z: int64; rawBytes: TUInt8s; binarize: boolean = false);
procedure voiBinarize (Color: int64); //set all non-zero voxels to Color
procedure voiInterpolate (Orient: int64);
procedure voiInterpolateAllGaps(Orient: int64);
procedure voiInterpolateCore(orient, zLoIn, zHiIn: int64);
function CopySlice2DSingle(Orient: int64; out out2D: TSlice2D; lSmooth: boolean = true): boolean;
procedure SmoothSlice(var slice: TSlice2D; Xdim, Ydim: int64);
procedure voiClose;
procedure voiSmoothIntensity();
procedure voiDefaultLUT;
procedure voiMorphologyFill(intenVol: TUInt8s; Color: int64; Xmm, Ymm, Zmm, Xfrac, Yfrac, Zfrac: single; dxOrigin, radiusMM: int64; drawMode: int64);
procedure voiIntensityFilter(intenVol: TUInt8s; Color: int64; rampAbove, rampBelow, drawMode: integer);
procedure voiDilate(dilationInVoxels: single);
function voiGetVolume: TUInt8s;
procedure voiChangeAlpha (a: byte);
procedure morphFill(volImg, volVoi: TUInt8s; Color: int64; Xmm,Ymm,Zmm: single; xOri, yOri, zOri, dxOrigin, radiusMM : int64; drawMode: int64);
constructor Create();//niftiFileName: string; tarMat: TMat4; tarDim: TVec3i; isInterpolate: boolean; out isOK: boolean); overload; //overlay
destructor Destroy; override;
published
end;
implementation
//uses mainunit;
{$IFDEF DILATE}
uses math;
{$ENDIF}
const
kOrientSagRL = 8;
kOrientSagLR = 4;
kOrientCoro = 2;
kOrientAx = 1;
kOrient3D = 0;
kFillNewColor = 255;//255;
kIgnoreColor = 253;//253;
kFillOldColor = 0;
{$IFDEF DILATE}
type
FloatRA = array [0..32767] of single;
FloatRAp = ^FloatRA;
procedure edt(var f: FloatRAp; var d,z: TFloat32s; var v: TInt32s; n: integer); inline;
function vx(p, q: integer): single; inline;
begin
try
result := ((f[q] + q*q) - (f[p] + p*p)) / (2.0*q - 2.0*p);
except
result := infinity;
end;
if isnan(result) then result := infinity;
end;
var
p, k, q: integer;
s, dx: single;
begin
(*# Find the lower envelope of a sequence of parabolas.
# f...source data (returns the Y of the parabola vertex at X)
# d...destination data (final distance values are written here)
# z...temporary used to store X coords of parabola intersections
# v...temporary used to store X coords of parabola vertices
# i...resulting X coords of parabola vertices
# n...number of pixels in "f" to process
# Always add the first pixel to the enveloping set since it is
# obviously lower than all parabolas processed so far.*)
k := 0;
v[0] := 0;
z[0] := -infinity;
z[1] := infinity;
for q := 1 to n-1 do begin
(*# If the new parabola is lower than the right-most parabola in
# the envelope, remove it from the envelope. To make this
# determination, find the X coordinate of the intersection (s)
# between the parabolas with vertices at (q,f[q]) and (p,f[p]).
*)
p := v[k];
s := vx(p,q);
while (s <= z[k]) and (k > 0) do begin
k := k - 1;
p := v[k];
s := vx(p,q);
end;
//# Add the new parabola to the envelope.
k := k + 1;
v[k] := q;
z[k] := s;
z[k + 1] := infinity;
end;
(*# Go back through the parabolas in the envelope and evaluate them
# in order to populate the distance values at each X coordinate.*)
k := 0;
for q := 0 to n-1 do begin
while z[k + 1] < q do
k := k + 1;
dx := (q - v[k]);
d[q] := dx * dx + f[v[k]];
//i[q] = v[k];
end;
for q := 0 to n-1 do
f[q] := d[q];
end;
procedure edt1(var df: FloatRAp; n: integer); inline;
var
q, prevX : integer;
prevY, v : single;
begin
prevX := 0;
prevY := infinity;
//forward
for q := 0 to (n-1) do begin
if (df[q] = 0) then begin
prevX := q;
prevY := 0;
end else
df[q] := sqr(q-prevX)+prevY;
end;
//reverse
prevX := n;
prevY := infinity;
for q := (n-1) downto 0 do begin
v := sqr(q-prevX)+prevY;
if (df[q] < v) then begin
prevX := q;
prevY := df[q];
end else
df[q] := v;
end
end;
procedure distanceFieldLR(var dim: TVec3i; var img: TFloat32s);
//filter data in the X dimension (Left/Right)
var
s, r, cols: int64;
f: FloatRAp;
begin
cols := dim.x;
s := dim.y * max(dim.z, 1);
for r := 0 to (s-1) do begin
f := @img[r*cols];
edt1(f,cols);
end;
end;
(*function hasZeros(var df: FloatRAp; n: integer): boolean;
var
q: integer;
begin
result := false;
for q := 0 to (n-1) do
if df[q] = 0 then
exit(true);
end;
procedure report(var df: FloatRAp; n: integer);
var
q: integer;
begin
writeln(format('n=%d', [n]));
writeln('m=[');
for q := 0 to (n-1) do
write(format('%g, ',[df[q]]));
writeln('];');
end; *)
procedure distanceFieldAP(var dim: TVec3i; var img: TFloat32s);
//filter data in the Y dimension (Anterior/Posterior)
(*const
kn = 255;
c: array [0..kn] of single =(Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, 144, 0, 0, 0, 0, 144, 144, 1, 1, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity);
*)
var
//j : integer;
slices: int64;
x,y, k, s, r, rows, cols: int64;
f: FloatRAp;
d,z, img2D : TFloat32s;
v: TInt32s;
//zeros: boolean;
begin
cols := dim.y;
rows := dim.x;
setlength(z, cols+1);
setlength(d, cols+1);
setlength(v, cols+1);
setlength(img2D, rows*cols);
slices := 1;
slices := slices * max(dim.z, 1);
for s := 0 to (slices-1) do begin
//transpose
k := s * (rows * cols); //slice offset
for x := 0 to (cols-1) do begin
for y := 0 to (rows-1) do begin
img2D[x+(y*cols)] := img[k];
k := k + 1;
end;
end;
for r := 0 to (rows-1) do begin
//for j := 0 to kn do
// img2D[j] := c[j];
f := @img2D[r*cols];
(*zeros := hasZeros(f, cols);
if zeros then
report(f,cols); *)
edt(f, d, z, v, cols);
(*if zeros then begin
report(f,cols);
exit;
end;*)
end;
//transpose
k := s * (rows * cols); //slice offset
for x := 0 to (cols-1) do begin
for y := 0 to (rows-1) do begin
img[k] := img2D[x+(y*cols)];
k := k + 1;
end;
end;
end;
end;
procedure distanceFieldHF(var dim: TVec3i; var img: TFloat32s);
//filter data in the Z dimension (Head/Foot)
//by far the most computationally expensive pass
// unlike LR and AP, we must process 3rd (Z) and 4th (volume number) dimension separately
var
sx, sxy, x,y,k, s, r, rows, cols: int64;
f: FloatRAp;
d,z, img2D : TFloat32s;
v: TInt32s;
begin
if (dim.z < 2) then exit; //2D images have height and width but not depth
//we could transpose [3,2,1] or [3,1,2] - latter improves cache?
cols := dim.z;
rows := dim.x;
sxy := dim.x * dim.y;
setlength(z, cols+1);
setlength(d, cols+1);
setlength(v, cols+1);
setlength(img2D, rows*cols);
for s := 0 to (dim.y-1) do begin
//transpose
sx := (s * rows);
k := 0; //slice offset along Y axis
for x := 0 to (rows-1) do begin
for y := 0 to (cols-1) do begin
img2D[k] := img[x + sx + (y*sxy)];
k := k + 1;
end;
end;
for r := 0 to (rows-1) do begin
f := @img2D[r*cols];
edt(f, d, z, v, cols);
end;
//transpose
k := 0; //slice offset along Y axis
for x := 0 to (rows-1) do begin
for y := 0 to (cols-1) do begin
img[x + sx + (y*sxy)] := img2D[k];
k := k + 1;
end;
end;
end; //slice
end; //distanceFieldHF()
function distanceFieldVolume3D(var dim: TVec3i; var img32: TFloat32s): boolean;
var
i, vx: int64;
begin
result := false;
if (dim.x < 1) or (dim.y < 1) or (dim.z < 1) then exit;
vx := dim.x * dim.y * dim.z;
distanceFieldLR(dim, img32);
distanceFieldAP(dim, img32);
distanceFieldHF(dim, img32);
for i := 0 to (vx-1) do
img32[i] := sqrt(img32[i]) ;
result := true;
end;
procedure TDraw.voiDilate(dilationInVoxels: single);
var
nPix, i : int64;
dim: TVec3i;
color : byte;
img32: TFloat32s;
//f : File;
begin
color := min(max(1, penColor), 255);
if (view3d = nil) and (Color = 0) then exit; //nothing to erase
if (dim3d[1] < 1) or (dim3d[2] < 1) or (dim3d[3] < 1) then exit;
dim := pti(dim3d[1], dim3d[2], dim3d[3]);
nPix := dim3d[1] * dim3d[2] * dim3d[3];
//GLForm1.SliceBox.Caption := inttostr(Color)+'b'+ inttostr(nPix);
voiCloseSlice;
dim2d[0] := kOrient3D; //dim[0] = slice orientation 0 = 3d volume
setlength(view2d, nPix);
setlength(undo2d, nPix);
Move(view3d[0], undo2d[0],nPix);//source/dest
Move(undo2d[0],view2d[0],nPix);//source/dest
setlength(img32, nPix);
if (dilationInVoxels < 0) then begin
dilationInVoxels := abs(dilationInVoxels);
for i := 0 to (nPix -1) do begin
if view2d[i] > 0 then
img32[i] := infinity
else
img32[i] := 0;
end;
distanceFieldVolume3D(dim, img32);
for i := 0 to (nPix -1) do begin
if img32[i] > dilationInVoxels then
view2d[i] := color
else
view2d[i] := 0;
end;
end else begin
for i := 0 to (nPix -1) do begin
if view2d[i] > 0 then
img32[i] := 0
else
img32[i] := infinity;
end;
distanceFieldVolume3D(dim, img32);
(*AssignFile(f, '/Users/chris/dx.img');
ReWrite(f, 1);
BlockWrite(f, img32[0], nPix * 4); // Write 2 'records' of 4 bytes
CloseFile(f); *)
for i := 0 to (nPix -1) do begin
//if img32[i] < dilationInVoxels then
if img32[i] < dilationInVoxels then
view2d[i] := 1
else
view2d[i] := 0;
end;
end;
img32 := nil;
// if (intenVol[i] > threshold) then view2d[i] := Color;
doRedraw := true;
UpdateView3d;
isModified := true;
isModifiedSinceSave := true;
end;
{$ELSE}
procedure TDraw.voiDilate(dilationInVoxels: single);
begin
printf('voiDilate not supported');
end;
{$ENDIF}
function TDraw.Dim: TVec3i;
begin
result := pti(dim3d[1], dim3d[2], dim3d[3]);
end;
destructor TDraw.Destroy;
begin
view3d := nil;
view2d := nil;
undo2d := nil;
modified2d := nil;
end;
procedure TDraw.voiClose;
begin
view3d := nil;
view2d := nil;
undo2d := nil;
modified2d := nil;
//isMouseDown:= false;
isModified := true; // <- update on GPU
voiCloseSlice;
end;
function TDraw.voiActiveOrient: integer;
begin
if (view3d <> nil) and (isMouseDown) then
result := dim2d[0] //return 3D(0), Axial(1), Coronal(2) or Sagittal(3)
else
result := -1;
end;
procedure TDraw.voiMouseDown(Orient: int64; XYZfrac: TVec3); overload;
begin
voiMouseDown(penColor, Orient, XYZfrac.X, XYZfrac.Y, XYZfrac.Z);
end;
procedure TDraw.voiMouseDown(Orient: int64; XYZfrac: TVec3; isInvertPenColor: boolean); overload;
//https://bugs.freepascal.org/view.php?id=35480
begin
if (isInvertPenColor) then begin
if PenColorOnRelease <> 0 then
voiMouseDown(0, Orient, XYZfrac.X, XYZfrac.Y, XYZfrac.Z)
else
voiMouseDown(1, Orient, XYZfrac.X, XYZfrac.Y, XYZfrac.Z);
end else
voiMouseDown(penColor, Orient, XYZfrac.X, XYZfrac.Y, XYZfrac.Z);
end;
function frac2pix (frac: single; dimPix: int64): int64;
begin
result := round((frac * dimPix)-0.5);
if (result < 0) then result := 0;
if (result >= dimPix) then result := dimPix - 1;
end;
procedure SortInt (var lMin,lMax: int64); overload;
var
lSwap: int64;
begin
if lMin <= lMax then
exit;
lSwap := lMax;
lMax := lMin;
lMin := lSwap;
end;
procedure TDraw.voiChangeAlpha (a: byte);
var
i: int64;
begin
//alpha := a;
doAlpha := true;
colorLut[0].A := 0;
for i := 1 to 255 do
colorLut[i].A := a;
end;
function TDraw.voiGetVolume: TUInt8s;
begin
result := view3d;
end;
function makeRGB(r,g,b: byte): TRGBA;
begin
result.r := r;
result.g := g;
result.b := b;
end;
procedure TDraw.voiDefaultLUT;
var
i:int64;
begin
colorLut[0] := makeRGB(0,0,0);
colorLut[1] := makeRGB(255,0,0);//red
colorLut[2] := makeRGB(0,128,0);//green
colorLut[3] := makeRGB(0,0,255);//blue
colorLut[4] := makeRGB(255,128,0);//orange
colorLut[5] := makeRGB(128,0,255);//purple
colorLut[6] := makeRGB(0,200,200);//cyan
colorLut[7] := makeRGB(160,48,48);//brick
colorLut[8] := makeRGB(32,255,32);//lime
colorLut[9] := makeRGB(128,160,230);//lightblue
for i := 10 to 255 do
colorLut[i] := colorLut[((i-1) mod 9)+1];
end;
(*procedure TDraw.SmoothSlice(var slice: TSlice2D; Xdim, Ydim: int64);
var
x,y, pos: int64;
sliceTemp : TSlice2D;
begin
if (Xdim < 3) or (Ydim < 3) then exit;
setlength(sliceTemp, Xdim * Ydim);
//emulate 2D Gaussian blur: since function is separable, compute as two 1D filter
//smooth in X dimension
pos := 0;
sliceTemp := Copy(slice, Low(slice), Length(slice)); //really clean, but unnecessary
for x := 0 to (Xdim -1) do begin
for y := 0 to (Ydim -1) do begin
pos := pos + 1;
if (x = 0) or (x = (Xdim-1)) then continue;
sliceTemp[pos] := (slice[pos-1] + slice[pos] + slice[pos] + slice[pos+1]) * 0.25;
end;
end;
//smooth in Y dimension
pos := 0;
for x := 0 to (Xdim -1) do begin
for y := 0 to (Ydim -1) do begin
pos := pos + 1;
if (y = 0) or (y = (Ydim-1)) then continue;
slice[pos] := (sliceTemp[pos-Ydim] + sliceTemp[pos] + sliceTemp[pos] + sliceTemp[pos+Ydim]) * 0.25;
end;
end;
sliceTemp := nil; //free
end;*)
procedure TDraw.SmoothSlice(var slice: TSlice2D; Xdim, Ydim: int64);
var
x,y, pos: int64;
sliceTemp : TSlice2D;
begin
if (Xdim < 3) or (Ydim < 3) then exit;
setlength(sliceTemp, Xdim * Ydim);
//emulate 2D Gaussian blur: since function is separable, compute as two 1D filter
//smooth in X dimension
pos := 0;
sliceTemp := Copy(slice, Low(slice), Length(slice)); //really clean, but unnecessary
for x := 0 to (Xdim -1) do begin
for y := 0 to (Ydim -1) do begin
pos := pos + 1;
if (x = 0) or (x = (Xdim-1)) then continue;
sliceTemp[pos] := (slice[pos-1] + slice[pos] + slice[pos] + slice[pos+1]) * 0.25;
end;
end;
//smooth in Y dimension
pos := 0;
for x := 0 to (Xdim -1) do begin
for y := 0 to (Ydim -1) do begin
pos := pos + 1;
if (y = 0) or (y = (Ydim-1)) then continue;
//slice[pos] := (sliceTemp[pos-Ydim] + sliceTemp[pos] + sliceTemp[pos] + sliceTemp[pos+Ydim]) * 0.25;
slice[pos] := (sliceTemp[pos-Xdim] + sliceTemp[pos] + sliceTemp[pos] + sliceTemp[pos+Xdim]) * 0.25;
end;
end;
sliceTemp := nil; //free
end;
procedure SmoothImg(vol: TFloat32s; X,Y,Z: int64);
var
vol2: TFloat32s;
i, nPix, dimOff: int64;
begin
if (X < 5) or (Y < 5) or (Z < 5) then exit;
nPix := X * Y * Z;
setlength(vol2, nPix * sizeof(single));
Move(vol[0], vol2[0],nPix * sizeof(single));//source/dest -> only for edges
for i := 2 to (nPix-1-2) do //smooth in X direction
vol[i] := vol2[i-2] + 2*vol2[i-1] + 3* vol2[i] + 2* vol2[i+1] + vol2[i+2]; //x9 of original value
dimOff := X;
for i := 2*dimOff to (nPix-1-(2*dimOff)) do //smooth in Y direction
vol2[i] := vol[i-2*dimOff] + 2*vol[i-dimOff] + 3* vol[i] + 2* vol[i+dimOff] + vol[i+2*dimOff]; //x9 of original value
dimOff := X * Y;
for i := 2*dimOff to (nPix-1-(2*dimOff)) do //smooth in Z direction
vol[i] := vol2[i-2*dimOff] + 2*vol2[i-dimOff] + 3* vol2[i] + 2* vol2[i+dimOff] + vol2[i+2*dimOff]; //x9 of original value
vol2 := nil;
end;
function maxVol (v: TFloat32s; lStart,lEnd: int64): single; //brightest and darkest
var
i: int64;
begin
result := v[0];
for i := lStart to lEnd do
if v[i] >= result then result := v[i];
end;
procedure meanStdInMask(mask, v: TFloat32s; lStart,lEnd: int64) ;
//modulate mask based on variance - in v
const
kFrac = 0.7; //0..1 what proportion of signal modulatated by intensity
var
mx: single;
mean, stdev, delta,m2: double;
i,n: int64;
begin
//1.) determine max intensity in mask, e.g. if a binary 0/1 mask this will be 1
mx := maxVol(mask,lStart,lEnd);
if mx = 0 then exit;
mx := 0.75 * mx;
//calculate stdev and mean with Welford on pass methodhttp://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
n := 0;
mean := 0.0;
m2 := 0.0;
for i := lStart to lEnd do begin
if (mask[i] >= mx) then begin
n := n + 1;
delta := v[i] - mean;
mean := mean + (delta/n);
m2 := m2 + (delta * (v[i] -mean) );
end;
end;
if (n < 2) then exit;
stdev := sqrt(m2/(n-1)); //convert to standard deviation
//GLForm1.Caption := inttostr(n)+' '+ floattostr(mean)+' '+floattostr(stdev);
for i := lStart to lEnd do begin
delta := (v[i] - mean)/stdev; //z-score
delta := abs(delta)/3; //e.g. Z= -1.5 -> 0.5
if delta > kFrac then delta := kFrac; //delta is clipped to 0..kFrac
delta := 1-delta;
//if (mask[i] > 0) then mask[i] := 243 * delta; //purely drive by intensity
mask[i] := mask[i] * (delta + (1-kFrac) );
end;
end;
function numThresh (v: TFloat32s; lStart,lEnd: int64; thresh: single): int64; //how many members of the array are >= thresh?
var
i: int64;
begin
result := 0;
for i := lStart to lEnd do
if v[i] >= thresh then inc(result);
end;
procedure TDraw.SmoothVol(lColor: int64; intenVol: TFloat32s);
label
666;
var
vol: TFloat32s;
nPix,i, origVol,
tLo,tMid,tHi, nMid,t1stVox, tLastVox: int64;
begin
//volume dimensions must be at least 5x5x5 voxels for smooth
nPix := dim3d[1] * dim3d[2]*dim3d[3];
setlength(vol, nPix * sizeof(single));
origVol := 0;
for i := 0 to (nPix-1) do
if (view2d[i] = lColor) then begin
vol[i] := 1;
inc(origVol);
end else
vol[i] := 0;
if (origVol < 1) then goto 666;
SmoothImg(vol, dim3d[1], dim3d[2], dim3d[3]);
t1stVox := -1;
tLastVox := -1;
for i := 0 to (nPix-1) do begin
vol[i] := vol[i] * (1/3); //normalize from 0..729 to 0..243
if vol[i] = 0.0 then begin
tLastVox := i;
if (t1stVox < 0) then t1stVox := i;
end;
end;
if (intenVol <> nil) then
meanStdInMask(vol, intenVol, t1stVox,tLastVox) ;
//find threshold that maintains overall volume
tLo := 1;
tMid := 121;
tHi := 243;
nMid := numThresh (vol, t1stVox,tLastVox , tMid);
while (tHi-tLo) > 3 do begin
if (nMid > origVol) then
tLo := tMid
else
tHi := tMid;
tMid := ((tHi-tLo) div 2) + tLo;
nMid := numThresh (vol, t1stVox,tLastVox , tMid);
end;
for i := 0 to (nPix-1) do
if (vol[i] >= tMid) then
view2d[i] := lColor
else
view2d[i] := 0;
666:
vol := nil;
end;
procedure TDraw.voiSmoothIntensity();
var
nPix, dark, bright, i: int64;
begin
if (view3d = nil) then exit;
if (dim3d[1] < 5) or (dim3d[2] < 5) or (dim3d[3] < 5) then exit;
nPix := dim3d[1] * dim3d[2]*dim3d[3];
dark := 256;
bright := 0;
for i := 0 to (nPix -1) do begin
if (view3d[i] < dark) then dark := view3d[i];
if (view3d[i] > bright) then bright := view3d[i];
end;
if (bright = dark) then exit; //no variability
voiCloseSlice; //2015
dim2d[0] := kOrient3D; //dim[0] = slice orientation 0 = 3d volume
setlength(view2d, nPix);
setlength(undo2d, nPix);
Move(view3d[0], undo2d[0],nPix);//source/dest
Move(undo2d[0],view2d[0],nPix);//source/dest
if (dark = 0) then dark := 1;
for i := dark to bright do
SmoothVol(i, nil);
doRedraw := true;
UpdateView3d;
isModified := true;
isModifiedSinceSave := true;
end;
function TDraw.CopySlice2DSingle(Orient: int64; out out2D: TSlice2D; lSmooth: boolean = true): boolean;
var
u8_2D: TUInt8s;
nPix, i: int64;
begin
nPix := dim2d[1]*dim2d[2];
setlength(u8_2D, nPix);
setlength(out2D, nPix);
CopySlice2D(Orient,u8_2D);
result := false;
for i := 0 to (nPix -1) do
if u8_2D[i] <> u8_2D[0] then
result := true; //variability
for i := 0 to (nPix -1) do
out2D[i] := u8_2D[i];
if lSmooth then
SmoothSlice(out2D, dim2d[1], dim2d[2]);
u8_2D := nil;
end;
procedure TDraw.voiInterpolateCore(orient, zLoIn, zHiIn: int64);
//interpolate voi between two 2D slices, slices indexed from 0
label
666;
var
xy, z, zLo, zHi, nSlices, nPix: int64;
FracLo, FracHi: double;
sliceLo, sliceHi: TSlice2D;
outSlice: TUInt8s;
begin
zLo := zLoIn;
zHi := zHiIn;
SortInt(zLo, zHi);
nSlices := setDim2D(Orient);
nPix := dim2d[1]*dim2d[2];
if (zLo >= zHi) or (zLo < 0) or (zHi >= nSlices) or (nPix < 9) then exit;
setlength(outSlice, nPix);
setlength(sliceLo, 0);
setLength(sliceHi, 0);
//get bottom slice
dim2d[3] :=zLo;
if not CopySlice2DSingle(orient, sliceLo) then begin
showmessage('Error: no variability in 1st slice '+inttostr(zLo));
goto 666;
end;
//set top slice
dim2d[3] :=zHi;
if not CopySlice2DSingle(orient, sliceHi) then begin
showmessage('Error: no variability in 2nd slice '+inttostr(zHi));
goto 666;
end;
//estimate intensity at each voxel in between
for z := (zLo+1) to (zHi -1) do begin
fracHi := abs(z-zLo) / abs(zHi - zLo);//weighting for of lower slice
fracLo := 1 - fracHi; //weighting for upper slice
for xy := 0 to (nPix-1) do begin
if ((sliceLo[xy]*fracLo) + (sliceHi[xy]*fracHi)) >= 0.375 then
outSlice[xy] := 1
else
outSlice[xy] := 0;
//outSlice[xy] := 1;
end; //each pixel in 2D slice
dim2d[3] :=z;
PasteSlice2D(Orient, outSlice, view2d);
end;
666:
outSlice := nil;
sliceLo := nil;
sliceHi := nil;
end;
procedure TDraw.voiInterpolateAllGaps(Orient: int64);
label
666;
var
zHi, zLo, i, z, nPix2D, nZ, nGaps: int64;
isEmpty: array of boolean;
slice2D: TUInt8s;
s :string;
begin
nZ := setDim2D(Orient);
nPix2D := dim2d[1] * dim2d[2];
setlength(slice2D,nPix2D);
setlength(isEmpty, dim2d[3]);
zHi := 0;
zLo := nZ;
for z := 0 to (nZ -1) do begin
isEmpty[z] := true;
dim2d[3] :=z;
CopySlice2D(Orient,slice2D);
for i := 0 to (nPix2D -1) do begin
if slice2D[i] <> 0 then begin
isEmpty[z] := false; //variability
if (z < zLo) then zLo := z;
zHi := z;
break;
end; //if slice has ROI in it
end; //for each voxel in slice
//if not isEmpty[z] then showmessage(inttostr(z));
end; //for each slice
if (zHi < 1) or (zLo >= zHi) then begin
showmessage(format('No gaps in drawing slices. %d %d',[zLo, zHi]));
goto 666; //nothing to do: all slices empty or only one slice filled
end;
//GLForm1.Caption := format('interpolate %d %d',[zLo, zHi]);
nGaps := 0;
while zLo < nZ do begin //for each slice, -2 since we need a gap
if (isEmpty[zLo]) or (not isEmpty[zLo+1]) then begin //don't interpolate if current slice is empty or next slice not empty
zLo := zLo + 1;
continue;
end;
zHi := zLo + 1;
while (isEmpty[zHi]) and (zHi < nZ) do
zHi := zHi + 1;
if zHi >= nZ then break;
inc(nGaps);
voiInterpolateCore(Orient, zLo, zHi);
//showmessage(format('interpolating %d %d',[zLo, zHi]));
//look for next gap
zLo := zHi;
end;
if nGaps = 0 then begin
if Orient = kOrientCoro then
s := 'Coronal'
else if (Orient = kOrientSagRL) or (Orient = kOrientSagLR) then
s := 'Sagittal'
else
s := 'Axial';
showmessage('No gaps found in the '+s+' direction');
end;
666:
slice2D := nil;
doRedraw := true;
UpdateView3d;
isModified := true;
isModifiedSinceSave := true;
end;
procedure TDraw.voiInterpolate (Orient: int64);
//mode is one of these options:
// kOrientSag = 3;
// kOrientCoro = 2;
// kOrientAx = 1;
// kLast = 0; //last two slices
var
nPix3D: int64;
begin
if (view3d = nil) then begin
showmessage('No drawing to interpolate');
exit; //nothing to erase
end;
if (Orient < kOrientAx) or (Orient > kOrientSagRL) then begin
if (prevSlice < 0) or (prevSlice = currSlice) then begin
showmessage('You need to draw on two different slices of the same orientation (Axial, Coronal, Sagittal)');
exit;
end;
end;
if (dim3d[1] < 5) or (dim3d[2] < 5) or (dim3d[3] < 1) then exit;
nPix3D := dim3d[3] * dim3d[1] * dim3d[2];
UpdateView3d;
voiCloseSlice;
dim2d[0] := kOrient3D; //dim[0] = slice orientation 0 = 3d volume
setlength(view2d, nPix3D);
setlength(undo2d, nPix3D);
Move(view3d[0], undo2d[0],nPix3D);//source/dest
Move(undo2d[0],view2d[0],nPix3D);//source/dest
if (Orient < kOrientAx) or (Orient > kOrientSagRL) then
voiInterpolateCore(prevOrient, prevSlice, currSlice)
else
voiInterpolateAllGaps(Orient);
dim2d[0] := kOrient3D; //dim[0] = slice orientation 0 = 3d volume
doRedraw := true;
UpdateView3d;
isModified := true;
isModifiedSinceSave := true;
end;
procedure TDraw.voiBinarize (Color: int64); //set all non-zero voxels to Color
var
nPix, i: int64;
begin
if (Color < 0) then exit;
if (view3d = nil) and (Color = 0) then exit; //nothing to erase
if (dim3d[1] < 5) or (dim3d[2] < 5) or (dim3d[3] < 1) then exit;
nPix := dim3d[1] * dim3d[2]*dim3d[3];
UpdateView3d;
voiCloseSlice;
dim2d[0] := kOrient3D; //dim[0] = slice orientation 0 = 3d volume
setlength(view2d, nPix);
setlength(undo2d, nPix);
Move(view3d[0], undo2d[0],nPix);//source/dest
Move(undo2d[0],view2d[0],nPix);//source/dest
for i := 0 to (nPix-1) do
if view3d[i] <> 0 then
view2d[i] := 1;
doRedraw := true;
UpdateView3d;
isModified := true;
isModifiedSinceSave := true;
end;
procedure TDraw.voiCreate(X,Y,Z: int64; rawBytes: TUInt8s; binarize: boolean = false);
var
i, vx: int64;
begin
isModified := true;
isModifiedSinceSave := false;
dim3d[0] := 3;
dim3d[1] := X;
dim3d[2] := Y;
dim3d[3] := Z;
prevSlice := -1;
voiCloseSlice;
view3d := nil;
vx := dim3d[1] * dim3d[2] * dim3d[3];
if (vx <1) or (dim3d[1] < 1) or (dim3d[2] < 1) or (dim3d[3] < 1) then //requires 3D image
exit;
//isForceCreate := true;
setlength(view3d, vx);
if (rawBytes <> nil) then begin
Move(rawBytes[0],view3d[0],vx);//source/dest
if (binarize) then
for i := 0 to (vx-1) do
if view3d[i] <> 0 then
view3d[i] := 1;
end else
FillChar(view3d[0],vx,0); //set all to zero
doRedraw := true;
UpdateView3d;
end; //voiCreate()
function TDraw.voiMouseMove (Xfrac, Yfrac, Zfrac: single): boolean;