-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathContourAlignmentTool.m
More file actions
5143 lines (4347 loc) · 244 KB
/
Copy pathContourAlignmentTool.m
File metadata and controls
5143 lines (4347 loc) · 244 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
classdef ContourAlignmentTool < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
ContourAlignmentToolUIFigure matlab.ui.Figure
FileMenu matlab.ui.container.Menu
ExportMenu matlab.ui.container.Menu
ExportAsMenu matlab.ui.container.Menu
NewPatientMenu matlab.ui.container.Menu
NewFractionMenu matlab.ui.container.Menu
ExitMenu matlab.ui.container.Menu
DisplayMenu matlab.ui.container.Menu
DRRViewerMenu matlab.ui.container.Menu
ContourFillMenu matlab.ui.container.Menu
ContourColourMenu matlab.ui.container.Menu
RedMenu matlab.ui.container.Menu
OrangeMenu matlab.ui.container.Menu
YellowMenu matlab.ui.container.Menu
GreenMenu matlab.ui.container.Menu
BlueMenu matlab.ui.container.Menu
PurpleMenu matlab.ui.container.Menu
InvertIntensityMenu matlab.ui.container.Menu
QuickExportMenu matlab.ui.container.Menu
HelpMenu matlab.ui.container.Menu
ManualMenu matlab.ui.container.Menu
KeyboardShortcutsMenu matlab.ui.container.Menu
CheckforUpdatesMenu matlab.ui.container.Menu
ReportMenu matlab.ui.container.Menu
AboutMenu matlab.ui.container.Menu
GridLayout matlab.ui.container.GridLayout
DataProcessingPanel matlab.ui.container.Panel
TempDir matlab.ui.control.EditField
TempdirEditFieldLabel matlab.ui.control.Label
ImagingTypeDropDown matlab.ui.control.DropDown
ImagingTypeDropDownLabel matlab.ui.control.Label
MasterBrowse matlab.ui.control.Button
PatientDropDown matlab.ui.control.DropDown
FractionDropDown matlab.ui.control.DropDown
CTBrowse matlab.ui.control.Button
CTLabel matlab.ui.control.Label
StructureBrowse matlab.ui.control.Button
StructureLabel matlab.ui.control.Label
SelectStructure matlab.ui.control.DropDown
SelectStructureStatus matlab.ui.control.Label
PlanBrowse matlab.ui.control.Button
PlanLabel matlab.ui.control.Label
ProjectionsBrowse matlab.ui.control.Button
ProjectionsLabel matlab.ui.control.Label
ExportBrowse matlab.ui.control.Button
ExportLabel matlab.ui.control.Label
kVImagingParametersPanel matlab.ui.container.Panel
Model matlab.ui.control.DropDown
ModelLamp matlab.ui.control.Lamp
ImagingSystemLabel matlab.ui.control.Label
MatrixSizeX matlab.ui.control.NumericEditField
MatrixSizeY matlab.ui.control.NumericEditField
PixelSpacingY matlab.ui.control.NumericEditField
CollimatorCassetteDropDownLabel matlab.ui.control.Label
MachineDropDown matlab.ui.control.DropDown
MachineDropDownLamp matlab.ui.control.Lamp
MachineDropDownLabel matlab.ui.control.Label
MatrixSizeLamp matlab.ui.control.Lamp
MatrixSizeLabel matlab.ui.control.Label
CollimatorCassetteDropDown matlab.ui.control.DropDown
Label matlab.ui.control.Label
KVDetStartAngleLamp matlab.ui.control.Lamp
KVDetStartAngleValue matlab.ui.control.NumericEditField
KVDetStartAngleLabel matlab.ui.control.Label
KVDetStopAngleLamp matlab.ui.control.Lamp
KVDetStopAngleValue matlab.ui.control.NumericEditField
KVDetStopAngleLabel matlab.ui.control.Label
NumberProj matlab.ui.control.Spinner
AllCheckBox matlab.ui.control.CheckBox
PixelSpacingLamp matlab.ui.control.Lamp
PixelSpacingX matlab.ui.control.NumericEditField
SIDLamp matlab.ui.control.Lamp
SIDvalue matlab.ui.control.NumericEditField
SDDLamp matlab.ui.control.Lamp
SDDvalue matlab.ui.control.NumericEditField
offsetLamp matlab.ui.control.Lamp
PixelspacingmmLabel matlab.ui.control.Label
NumberofimagestoloadLabel matlab.ui.control.Label
offsetValue matlab.ui.control.NumericEditField
DetectoroffsetxcoordinatemmLabel matlab.ui.control.Label
SourcetodetectordistanceSDDmmLabel matlab.ui.control.Label
SourcetoisocenterdistanceSIDmmEditFieldLabel matlab.ui.control.Label
parametersWarning matlab.ui.control.Label
StartProcessing matlab.ui.control.Button
DirectoriesImage matlab.ui.control.Image
ContourAlignmentandConfidenceScoringPanel matlab.ui.container.Panel
ConfidenceButtonGroup matlab.ui.container.ButtonGroup
ClinicalAcceptButton matlab.ui.control.StateButton
C0Button matlab.ui.control.RadioButton
C1Button matlab.ui.control.RadioButton
C2Button matlab.ui.control.RadioButton
C3Button matlab.ui.control.RadioButton
C4Button matlab.ui.control.RadioButton
C5Button matlab.ui.control.RadioButton
ContourAlignmentPanel matlab.ui.container.Panel
SW matlab.ui.control.Image
NW matlab.ui.control.Image
W matlab.ui.control.Image
S matlab.ui.control.Image
SE matlab.ui.control.Image
NE matlab.ui.control.Image
N matlab.ui.control.Image
E matlab.ui.control.Image
ClickdragCheckBox matlab.ui.control.CheckBox
clickdragstatus matlab.ui.control.Label
position matlab.ui.control.Label
reset matlab.ui.control.Image
ContrastAdjustmentPanel matlab.ui.container.Panel
contrastROIButton matlab.ui.control.StateButton
contrastContourButton matlab.ui.control.StateButton
contrastAutoButton matlab.ui.control.StateButton
contrastManualButton matlab.ui.control.StateButton
UpperSlider matlab.ui.control.Slider
LowerSlider matlab.ui.control.Slider
Histogram matlab.ui.control.UIAxes
NavigationPanel matlab.ui.container.Panel
First matlab.ui.control.Button
Previous matlab.ui.control.Button
projectionnumber matlab.ui.control.Label
Next matlab.ui.control.Button
End matlab.ui.control.Button
Tree matlab.ui.container.Tree
C0Node matlab.ui.container.TreeNode
C1Node matlab.ui.container.TreeNode
C2Node matlab.ui.container.TreeNode
C3Node matlab.ui.container.TreeNode
C4Node matlab.ui.container.TreeNode
C5Node matlab.ui.container.TreeNode
ClinicalOKNode matlab.ui.container.TreeNode
PassedNode matlab.ui.container.TreeNode
FailedNode matlab.ui.container.TreeNode
ROIselectionLabel matlab.ui.control.Label
UIAxes matlab.ui.control.UIAxes
end
% Private properties
properties (Access = private)
% This is now set in file "version.txt" - added by the deploy script.
version;
margin = 10; % mm. Contours within this margin are considered cropped.
minAngle = 180; % This is the minimum angle coverage required for a positive case in the patient selection tool.
isRetro = false; % Tracks if we're looking at prospective/retrospective patients in the PST.
% Configure folder names - might need to change depending on your
% folder structure.
folders = struct( ...
'default_projections_options', ["kV", "CBCT1", fullfile("CBCT", "CBCT1"), "."], ...
'default_ct_options', ["CT", "Planning CT"], ...
'default_rtplan_options', ["Plan"], ...
'default_rtstruct_options', ["Structures", "Structure Set", "Structure set"], ...
'images_options', ["PatientImages", "Patient Images", "TreatmentFiles", "Treatment Files", "Treatment files"], ...
'plans_options', ["PatientPlans", "Patient Plans", "PlanningFiles", "Planning Files"] ...
);
% Parameters
paths
dcmHeaders
displaySize
pointerManager
% Images
projection
Projections
Masks
DRRs
ROIrange
% Supporting Apps
AboutApp
HelpApp
UpdatesApp
DrrApp
end
% Public properties
properties (Access = public)
% This is now set in file "mode.txt" added by the deploy script.
mode; % This switches between "Contour Alignment Tool" and "Patient Selection Tool".
marginX; % The margin in pixels.
marginY;
% Images
originalMasks
DRR
Mask
MaskOutline
dispContour = 1;
% Parameters
fileType
currentFrame
colour
end
methods (Access = private)
% This method allows us to browse a folder without the Matlab app
% minimising. Unfortunately, it does create a dummy figure that
% appears in the task bar while the browse window is open.
function path = uigetdir_safe(app, varargin)
f = figure('Renderer', 'painters', 'Position', [-100 -100 0 0], 'Name', 'Please ignore: Creating this figure stops the Matlab window from minimising on folder browse', 'NumberTitle', 'off');
cleanup = onCleanup(@() delete(f));
path = uigetdir(varargin{:});
end
% This method allows us to browse a file without the Matlab app
% minimising. Unfortunately, it does create a dummy figure that
% appears in the task bar while the browse window is open.
function [file, path] = uigetfile_safe(app, varargin)
f = figure('Renderer', 'painters', 'Position', [-100 -100 0 0], 'Name', 'Please ignore', 'NumberTitle', 'off');
cleanup = onCleanup(@() delete(f));
[file, path] = uigetfile(varargin{:});
end
% AUTHOR : Andy Shieh, School of Physics, The University of Sydney
% DATE : 2012-11-08 Created.
% ------------------------------------------
% PURPOSE
% Read metaimage mha header and image.
% If the file is a archived file in the format of .7z, .zip, or .rar, the
% program will unzip and read.
% ------------------------------------------
% INPUT
% filename : The full path to the file.
% ------------------------------------------
% OUTPUT
% info : header information in a struct.
% M : the image stored in a 3D matrix.
% ------------------------------------------
function [info, M] = MhaReader(app, filename)
%% Checking input arguments & Opening the file
M = [];
% If no input filename => Open file-open-dialog
if nargin < 1
% go into a default directory
DefaultDir = pwd;
% get the input file (hnc) & extract path & base name
[FileName,PathName] = uigetfile_safe(app, ...
{'*.mha;*.7z;*.zip;*.rar','MetaImage (*.mha) or Archive file (*.7z, *.zip, *.rar)';...
'*.*','All files (*.*)'},...
'Select an image or image archive file', ...
DefaultDir);
% make same format as input
filename = fullfile(PathName, FileName);
end
filename = strtrim(filename);
%% Reading the header and body using external module
info = MhaHeaderReader(app,filename);
if nargout == 1
if exist('tempdir','var')
rmdir(tempdir,'s');
end
return;
else
M = MhaVolumeReader(app,info);
if exist('tempdir','var')
rmdir(tempdir,'s');
end
end
return
end
% AUTHOR : Andy Shieh, School of Physics, The University of Sydney
% DATE : 2013-01-09 Created.
% ------------------------------------------
% PURPOSE
% Write the input header and 3D image to a Metaimage file. Support only
% 3D data.
% ------------------------------------------
% INPUT
% info: The header MATLAB struct. The template of the info struct:
% Filename: 'SideADisBin01.mha'
% Format: 'MHA'
% CompressedData: 'false'
% ObjectType: 'image'
% NumberOfDimensions: 3
% BinaryData: 'true'
% ByteOrder: 'false'
% TransformMatrix: [1 0 0 0 1 0 0 0 1]
% Offset: [-224.8400 -99 -224.8400]
% CenterOfRotation: [0 0 0]
% AnatomicalOrientation: 'RAI'
% PixelDimensions: [0.8800 2 0.8800]
% Dimensions: [512 100 512]
% DataType: 'float'
% DataFile: 'LOCAL'
% BitDepth: 32
% HeaderSize: 318
% M: The image body, 3D.
% outputfp: The path of the output file.
% ------------------------------------------
function MhaWriter(~,info,M,outputfp)
%% Input argument check
if ~(strcmp(info.DataType,'float') || strcmp(info.DataType,'double') || ...
strcmp(info.DataType,'int8') || strcmp(info.DataType,'char') || ...
strcmp(info.DataType,'uint8') || strcmp(info.DataType,'uchar') || ...
strcmp(info.DataType,'int16') || strcmp(info.DataType,'short') || ...
strcmp(info.DataType,'uint16') || strcmp(info.DataType,'ushort') || ...
strcmp(info.DataType,'int'))
error('ERROR: Unsupported data type.');
end
if ~strcmp(info.CompressedData,'false')
error('ERROR: MHA is an uncompressed format.');
end
if ~strcmp(info.DataFile,'LOCAL')
error('ERROR: MHA is a single file format.');
end
fid = fopen(strtrim(outputfp),'w');
if(fid<=0)
error('ERROR: Invalid file path %s\n', outputfp);
end
%% Writing the header
fprintf(fid, 'ObjectType = Image\n');
fprintf(fid, num2str(info.NumberOfDimensions,'NDims = %d\\n'));
if isfield(info,'BinaryData')
fprintf(fid, ['BinaryData = ',info.BinaryData,'\n']);
end
fprintf(fid, ['BinaryDataByteOrderMSB = ',info.ByteOrder,'\n']);
fprintf(fid, ['CompressedData = ',info.CompressedData,'\n']);
if isfield(info,'TransformMatrix')
fprintf(fid, ['TransformMatrix =',num2str(info.TransformMatrix,' %g'),'\n']);
end
fprintf(fid, ['Offset =',num2str(info.Offset,' %g'),'\n']);
if isfield(info,'CenterOfRotation')
fprintf(fid, ['CenterOfRotation =',num2str(info.CenterOfRotation,' %g'),'\n']);
end
if isfield(info,'AnatomicalOrientation')
fprintf(fid, ['AnatomicalOrientation = ',info.AnatomicalOrientation,'\n']);
end
fprintf(fid, ['ElementSpacing =',num2str(info.PixelDimensions,' %g'),'\n']);
fprintf(fid, ['DimSize =',num2str(info.Dimensions,' %d'),'\n']);
if isfield(info,'ElementNumberOfChannels')
fprintf(fid, ['ElementNumberOfChannels =',num2str(info.ElementNumberOfChannels,' %d'),'\n']);
end
switch (info.DataType)
case 'float'
fprintf(fid, 'ElementType = MET_FLOAT\n');
case 'double'
fprintf(fid, 'ElementType = MET_DOUBLE\n');
case {'uchar','uint8'}
fprintf(fid, 'ElementType = MET_UCHAR\n');
case {'char','int8'}
fprintf(fid, 'ElementType = MET_CHAR\n');
case {'short','int16'}
fprintf(fid, 'ElementType = MET_SHORT\n');
case {'ushort','uint16'}
fprintf(fid, 'ElementType = MET_USHORT\n');
case 'int'
fprintf(fid, 'ElementType = MET_INT\n');
end
fprintf(fid, ['ElementDataFile = ',info.DataFile,'\n']);
%% Writing the body
% Need to reverse the dimension order if there are multi-entries
if isfield(info,'ElementNumberOfChannels') && info.ElementNumberOfChannels > 1
M = reshape(M,[prod(info.Dimensions),str2double(info.ElementNumberOfChannels)]);
M = M';
end
switch(info.DataType)
case {'char','int8'}
fwrite(fid,M,'char');
case {'uchar','uint8'}
fwrite(fid,M,'uchar');
case {'short','int16'}
fwrite(fid,M,'short');
case {'ushort','uint16'}
fwrite(fid,M,'ushort');
case 'int'
fwrite(fid,M,'int');
case 'uint'
fwrite(fid,M,'uint');
case 'float'
fwrite(fid,M,'float');
case 'double'
fwrite(fid,M,'double');
end
fclose(fid);
return
end
% From open source: https://github.com/FNNDSC/matlab/blob/master/misc/mha_read_header.m
% Function for reading the header of a Insight Meta-Image (.mha,.mhd) file
function info = MhaHeaderReader(~,filename)
info = struct();
if(exist('filename','var')==0)
[filename, pathname] = uigetfile_safe(app, '*.mha', 'Read mha-file');
filename = [pathname filename];
end
fid=fopen(filename,'rb');
if(fid<0)
error('MhaHeaderReader:FileOpenFailed', 'Could not open file %s', filename);
end
info.Filename=filename;
info.Format='MHA';
info.CompressedData='false';
readelementdatafile=false;
while(~readelementdatafile)
str=fgetl(fid);
s=find(str=='=',1,'first');
if(~isempty(s))
type=str(1:s-1);
data=str(s+1:end);
while(type(end)==' '); type=type(1:end-1); end
while(data(1)==' '); data=data(2:end); end
else
type=''; data=str;
end
switch(lower(type))
case 'ndims'
info.NumberOfDimensions=sscanf(data, '%d')';
case 'dimsize'
info.Dimensions=sscanf(data, '%d')';
case 'elementspacing'
info.PixelDimensions=sscanf(data, '%lf')';
case 'elementsize'
info.ElementSize=sscanf(data, '%lf')';
if(~isfield(info,'PixelDimensions'))
info.PixelDimensions=info.ElementSize;
end
case 'elementbyteordermsb'
info.ByteOrder=lower(data);
case 'anatomicalorientation'
info.AnatomicalOrientation=data;
case 'centerofrotation'
info.CenterOfRotation=sscanf(data, '%lf')';
case 'offset'
info.Offset=sscanf(data, '%lf')';
case 'binarydata'
info.BinaryData=lower(data);
case 'compresseddatasize'
info.CompressedDataSize=sscanf(data, '%d')';
case 'objecttype'
info.ObjectType=lower(data);
case 'transformmatrix'
info.TransformMatrix=sscanf(data, '%lf')';
case 'compresseddata'
info.CompressedData=lower(data);
case 'binarydatabyteordermsb'
info.ByteOrder=lower(data);
case 'elementdatafile'
info.DataFile=data;
readelementdatafile=true;
case 'elementtype'
info.DataType=lower(data(5:end));
case 'headersize'
val=sscanf(data, '%d')';
if(val(1)>0), info.HeaderSize=val(1); end
otherwise
info.(type)=data;
end
end
switch(info.DataType)
case 'char', info.BitDepth=8;
case 'uchar', info.BitDepth=8;
case 'short', info.BitDepth=16;
case 'ushort', info.BitDepth=16;
case 'int', info.BitDepth=32;
case 'uint', info.BitDepth=32;
case 'float', info.BitDepth=32;
case 'double', info.BitDepth=64;
otherwise, info.BitDepth=0;
end
if(~isfield(info,'HeaderSize'))
info.HeaderSize=ftell(fid);
end
fclose(fid);
end
% Modified from open source: https://github.com/FNNDSC/matlab/blob/master/misc/mha_read_volume.m
% Function for reading the volume of a Insight Meta-Image (.mha, .mhd) file
function [V,info] = MhaVolumeReader(app,info)
if(~isstruct(info)), info=MhaHeaderReader(app,info); end
switch(lower(info.DataFile))
case 'local'
otherwise
% Seperate file
info.Filename=fullfile(fileparts(info.Filename),info.DataFile);
end
% Open file
switch(info.ByteOrder(1))
case ('true')
fid=fopen(info.Filename,'rb','ieee-be');
otherwise
fid=fopen(info.Filename,'rb','ieee-le');
end
datasize=prod(info.Dimensions)*info.BitDepth/8;
datasummary = dir(info.Filename);
totalsize = datasummary.bytes;
switch(lower(info.DataFile))
case 'local'
fseek(fid,mod(totalsize,datasize),'bof');
otherwise
fseek(fid,0,'bof');
end
switch(info.CompressedData(1))
case 'f'
% Read the Data
switch(info.DataType)
case 'char'
V = int8(fread(fid,datasize,'char'));
case 'uchar'
V = uint8(fread(fid,datasize,'uchar'));
case 'short'
V = int16(fread(fid,datasize,'short'));
case 'ushort'
V = uint16(fread(fid,datasize,'ushort'));
case 'int'
V = int32(fread(fid,datasize,'int'));
case 'uint'
V = uint32(fread(fid,datasize,'uint'));
case 'float'
V = single(fread(fid,datasize,'float'));
case 'double'
V = double(fread(fid,datasize,'double'));
end
case 't'
error('Data is compressed. \n');
end
fclose(fid);
% Support reading multi-entries (e.g. vector field)
if isfield(info,'ElementNumberOfChannels') && info.ElementNumberOfChannels > 1
V = reshape(V,[str2double(info.ElementNumberOfChannels),prod(info.Dimensions)]);
V = V';
V = reshape(V,[info.Dimensions,str2double(info.ElementNumberOfChannels)]);
else
V = reshape(V,info.Dimensions);
end
end
% Convert the RTStructure to a MHA volume
function [Segmentation] = RTStructuretoMHA(app, structure, zLocs_sorted)
try
RSinfo = dicominfo(app.paths.structure);
contour = dicomContours(RSinfo);
catch
RSinfo = dicominfo(app.paths.structure,'UseVRHeuristic',false);
contour = dicomContours(RSinfo);
end
index = find(strcmp(contour.ROIs{:,2},structure));
% Build affine transformation
dr = app.dcmHeaders{1}.PixelSpacing(1);
dc = app.dcmHeaders{1}.PixelSpacing(2);
F(:,1) = app.dcmHeaders{1}.ImageOrientationPatient(1:3);
F(:,2) = app.dcmHeaders{1}.ImageOrientationPatient(4:6);
T1 = [app.dcmHeaders{1}.ImagePositionPatient(1:2); zLocs_sorted{1}(1)];
TN = [app.dcmHeaders{1}.ImagePositionPatient(1:2); zLocs_sorted{1}(end)];
offset = (T1 - TN) ./ (1 - length(app.dcmHeaders));
% Build affine transformation
xfm = [[F(1,1)*dr F(1,2)*dc offset(1) T1(1)]; ...
[F(2,1)*dr F(2,2)*dc offset(2) T1(2)]; ...
[F(3,1)*dr F(3,2)*dc offset(3) T1(3)]; ...
[0 0 0 1 ]];
%% From readRTStructures.
dimmin = [0 0 0 1]';
dimmax = double([app.dcmHeaders{1}.Columns-1 app.dcmHeaders{1}.Rows-1 length(app.dcmHeaders)-1 1])';
Segmentation = false([app.dcmHeaders{1}.Columns app.dcmHeaders{1}.Rows length(app.dcmHeaders)]);
ROIContourSequence = fieldnames(RSinfo.ROIContourSequence);
ContourSequence = fieldnames(RSinfo.ROIContourSequence.(ROIContourSequence{index}).ContourSequence);
%% Loop through segments (slices)
segments = cell(1,length(ContourSequence));
for j = 1:length(ContourSequence)
%% Read points
segments{j} = reshape(RSinfo.ROIContourSequence.(ROIContourSequence{index}).ContourSequence.(ContourSequence{j}).ContourData, ...
3, RSinfo.ROIContourSequence.(ROIContourSequence{index}).ContourSequence.(ContourSequence{j}).NumberOfContourPoints)';
%% Make lattice
points = xfm \ [segments{j} ones(size(segments{j},1), 1)]';
start = xfm \ [segments{j}(1,:) 1]';
minvox = max(floor(min(points, [], 2)), dimmin);
maxvox = min( ceil(max(points, [], 2)), dimmax);
minvox(3) = round(start(3));
maxvox(3) = round(start(3));
[x,y,z] = meshgrid(minvox(1):maxvox(1), minvox(2):maxvox(2), minvox(3):maxvox(3));
points = xfm * [x(:) y(:) z(:) ones(size(x(:)))]';
%% Make binary image
in = inpolygon(points(1,:), points(2,:), segments{j}(:,1), segments{j}(:,2));
Segmentation((minvox(1):maxvox(1))+1, (minvox(2):maxvox(2))+1, (minvox(3):maxvox(3))+1) = permute(reshape(in, size(x)), [2 1]);
end
end
% AUTHOR : Andy Shieh, School of Physics, The University of Sydney
% DATE : 2016-01-10 Created.
% ------------------------------------------
% PURPOSE
% Read Varian hnd header and image.
% ------------------------------------------
% INPUT
% filename : The full path to the hnd file.
% ------------------------------------------
% OUTPUT
% info : Header information in a struct.
% M : The image stored in a 2D matrix.
% ------------------------------------------
function [info, M] = HndReader(~, filename)
%% Checking input arguments & Opening the file
M = [];
% If no input filename => Open file-open-dialog
if nargin < 1
% go into a default directory
DefaultDir = pwd;
% get the input file (hnc) & extract path & base name
[FileName,PathName] = uigetfile_safe(app, {'*.hnd;*.hnc;','Varian Image Files (*.hnd,*.hnc,*.mat,*.mdl)';
'*.hnc', 'Portal Images (*.hnc)'; ...
'*.hnd', 'OBI kv Images (*.hnd)'}, ...
'Select an image file', ...
DefaultDir);
% make same format as input
filename = fullfile(PathName, FileName);
end
filename = strtrim(filename);
% Open the file
fid = fopen(filename,'r');
% catch error if failure to open the file
if fid == -1
error('ERROR : Failure in opening the file. \n');
end
%% Reading the header (same for hnc and hnd)
info.('bFileType') = fread(fid,32,'uint8=>char')';
info.('uiFileLength') = fread(fid,1,'uint32')';
% Sometimes the actual file length is different from the one specified in
% the header
fileinfo = dir(filename);
info.('uiActualFileLength') = fileinfo.('bytes');
info.('bChecksumSpec') = fread(fid,4,'uint8=>char')';
info.('uiCheckSum') = fread(fid,1,'uint32')';
info.('bCreationDate') = fread(fid,8,'uint8=>char')';
info.('bCreationTime') = fread(fid,8,'uint8=>char')';
info.('bPatientID') = fread(fid,16,'uint8=>char')';
info.('uiPatientSer') = fread(fid,1,'uint32')';
info.('bSeriesID') = fread(fid,16,'uint8=>char')';
info.('uiSeriesSer') = fread(fid,1,'uint32')';
info.('bSliceID') = fread(fid,16,'uint8=>char')';
info.('uiSliceSer') = fread(fid,1,'uint32')';
info.('uiSizeX') = fread(fid,1,'uint32')';
info.('uiSizeY') = fread(fid,1,'uint32')';
info.('dSliceZPos') = fread(fid,1,'double')';
info.('bModality') = fread(fid,16,'uint8=>char')';
info.('uiWindow') = fread(fid,1,'uint32')';
info.('uiLevel') = fread(fid,1,'uint32')';
info.('uiPixelOffset') = fread(fid,1,'uint32')';
info.('bImageType') = fread(fid,4,'uint8=>char')';
info.('dGantryRtn') = fread(fid,1,'double')';
info.('dSAD') = fread(fid,1,'double')';
info.('dSFD') = fread(fid,1,'double')';
info.('dCollX1') = fread(fid,1,'double')';
info.('dCollX2') = fread(fid,1,'double')';
info.('dCollY1') = fread(fid,1,'double')';
info.('dCollY2') = fread(fid,1,'double')';
info.('dCollRtn') = fread(fid,1,'double')';
info.('dFieldX') = fread(fid,1,'double')';
info.('dFieldY') = fread(fid,1,'double')';
info.('dBladeX1') = fread(fid,1,'double')';
info.('dBladeX2') = fread(fid,1,'double')';
info.('dBladeY1') = fread(fid,1,'double')';
info.('dBladeY2') = fread(fid,1,'double')';
info.('dIDUPosLng') = fread(fid,1,'double')';
info.('dIDUPosLat') = fread(fid,1,'double')';
info.('dIDUPosVrt') = fread(fid,1,'double')';
info.('dIDUPosRtn') = fread(fid,1,'double')';
info.('dPatientSupportAngle') = fread(fid,1,'double')';
info.('dTableTopEccentricAngle') = fread(fid,1,'double')';
info.('dCouchVrt') = fread(fid,1,'double')';
info.('dCouchLng') = fread(fid,1,'double')';
info.('dCouchLat') = fread(fid,1,'double')';
info.('dIDUResolutionX') = fread(fid,1,'double')';
info.('dIDUResolutionY') = fread(fid,1,'double')';
info.('dImageResolutionX') = fread(fid,1,'double')';
info.('dImageResolutionY') = fread(fid,1,'double')';
info.('dEnergy') = fread(fid,1,'double')';
info.('dDoseRate') = fread(fid,1,'double')';
info.('dXRayKV') = fread(fid,1,'double')';
info.('dXRayMA') = fread(fid,1,'double')';
info.('dMetersetExposure') = fread(fid,1,'double')';
info.('dAcqAdjustment') = fread(fid,1,'double')';
info.('dCTProjectionAngle') = fread(fid,1,'double')';
info.('dCBCTPositiveAngle') = mod(info.('dCTProjectionAngle') + 270.0, 360.0);
info.('dCTNormChamber') = fread(fid,1,'double')';
info.('dGatingTimeTag') = fread(fid,1,'double')';
info.('dGating4DInfoX') = fread(fid,1,'double')';
info.('dGating4DInfoY') = fread(fid,1,'double')';
info.('dGating4DInfoZ') = fread(fid,1,'double')';
info.('dGating4DInfoTime') = fread(fid,1,'double')';
info.('dOffsetX') = fread(fid,1,'double');
info.('dOffsetY') = fread(fid,1,'double');
info.('dUnusedField') = fread(fid,1,'double');
if nargout == 1
fclose(fid);
return
end
fclose(fid);
%% Use Varian Image toolbox to read the image body
javaaddpath(fullfile(pwd,'Dependencies', 'VarianReader.jar'));
readerObj = CPS_Reader();
M = readerObj.getHNC_HND(filename);
clear readerObj;
javarmpath(fullfile(pwd,'Dependencies', 'VarianReader.jar'));
% Reshape the projection data matrix
M = reshape(M,info.('uiSizeX'),info.('uiSizeY'));
return
end
% AUTHOR : Andy Shieh, The University of Sydney
% DATE : 2016-10-11 Created.
% ------------------------------------------
% PURPOSE
% Read Varian XIM image and header.
% This program was adapted from the original version developed by
% Fredrik Nordström in 2015.
% ------------------------------------------
% INPUT
% filename : The full path to the xim file.
% ------------------------------------------
% OUTPUT
% info : Header information in a struct.
% M : The image stored in a 2D matrix.
% ------------------------------------------
function [info,M] = XimReader(~,filename)
%% Input filename
if nargin < 1
filename = uigetfilepath( {'*.xim;*.XIM;','Varian XIM Files (*.xim,*.XIM)';
'*.xim', 'Varian XIM Files (*.xim)'; ...
'*.XIM', 'Varian XIM Files (*.XIM)'}, ...
'Select an image file', ...
pwd);
end
%% Read header
fid = fopen(filename,'r');
% Decode header
info.file_name = filename;
info.file_format_identifier = fread(fid,8,'*char')';
info.file_format_version = fread(fid,1,'*int32');
info.image_width = fread(fid,1,'*int32');
info.image_height = fread(fid,1,'*int32');
info.bits_per_pixel = fread(fid,1,'*int32');
info.bytes_per_pixel = fread(fid,1,'*int32');
info.compression_indicator = fread(fid,1,'*int32');
%% Read image
if nargout < 2
read_pixel_data = 0;
else
read_pixel_data = 1;
end
% Decode pixel data
if info.compression_indicator == 1
lookup_table_size = fread(fid,1,'int32');
lookup_table = fread(fid,lookup_table_size*4,'ubit2=>uint8');
compressed_pixel_buffer_size = fread(fid,1,'int32');
if read_pixel_data==1
disp('reading pixel data')
% Decompress image
% BC: This uses variable-length, differential compression as neighbouring
% pixels are assumed to have similar intensity values.
pixel_data = int32(zeros(info.image_width*info.image_height,1));
pixel_data(1:info.image_width+1) = fread(fid,info.image_width+1,'*int32');
disp('read')
% Switch between old/new decompression versions.
decompress_method = "old";
if decompress_method == "old"
lookup_table_pos = 1;
for image_pos = (info.image_width+2):(info.image_width*info.image_height)
% Variable-length: how many bytes are needed to store the diff?
if lookup_table(lookup_table_pos) == 0
diff = int32(fread(fid,1,'*int8'));
elseif lookup_table(lookup_table_pos) == 1
diff = int32(fread(fid,1,'*int16'));
else
diff = int32(fread(fid,1,'*int32'));
end
% Differential: add the left/top/top-left pixel values.
pixel_data(image_pos) = ...
diff+pixel_data(image_pos-1) + ...
pixel_data(image_pos-info.image_width) - ...
pixel_data(image_pos-info.image_width-1);
lookup_table_pos = lookup_table_pos + 1;
end
else
% BC: This didn't work for all patients -
% issue for Prostate/Pat02/Fx2
% New lookup table stuff.
% Although diffs are stored as variable-length, we can read them all as the lowest
% possible length (single byte) and reconstruct them in matlab. The purpose is to
% reduce the number of filesystem ('fread') calls from N=<size of image> to N=1.
% Read all bytes.
n_bytes = sum(lookup_table == 0) * 1 + ...
sum(lookup_table == 1) * 2 + ...
sum(lookup_table == 2) * 4;
raw_bytes = fread(fid, n_bytes, '*uint8');
% Compute actual intensities.
lookup_table_pos = 1;
raw_bytes_pos = 1;
for image_pos = (info.image_width+2):(info.image_width*info.image_height)
% Variable-length: how many bytes are needed to store the diff?
if lookup_table(lookup_table_pos) == 0
diff = typecast(raw_bytes(raw_bytes_pos), 'int8');
raw_bytes_pos = raw_bytes_pos + 1;
elseif lookup_table(lookup_table_pos) == 1
diff = typecast(raw_bytes(raw_bytes_pos:raw_bytes_pos + 1), 'int16');
raw_bytes_pos = raw_bytes_pos + 2;
else
diff = typecast(raw_bytes(raw_bytes_pos:raw_bytes_pos + 3), 'int32');
raw_bytes_pos = raw_bytes_pos + 4;
end
% Differential: add the left/top/top-left pixel values.
pixel_data(image_pos) = ...
int32(diff) + pixel_data(image_pos-1) + ...
pixel_data(image_pos-info.image_width) - ...
pixel_data(image_pos-info.image_width-1);
lookup_table_pos = lookup_table_pos + 1;
end
end
disp('lookup table stuff')
if info.bytes_per_pixel == 2
info.pixel_data = ...
int16(reshape(pixel_data,info.image_width,info.image_height));
else
info.pixel_data = ...
reshape(pixel_data,info.image_width,info.image_height);
end
disp('reshaping stuff')
else
fseek(fid,compressed_pixel_buffer_size,'cof');
end
uncompressed_pixel_buffer_size = fread(fid,1,'*int32');
else
disp('loading uncompressed xim')
uncompressed_pixel_buffer_size = fread(fid,1,'*int32');
if read_pixel_data == 1
disp('reading pixel data')
switch info.bytes_per_pixel
case 1
pixel_data = fread(fid,uncompressed_pixel_buffer_size,'*int8');
case 2
pixel_data = fread(fid,uncompressed_pixel_buffer_size/2,'*int16');
otherwise
pixel_data = fread(fid,uncompressed_pixel_buffer_size/4,'*int32');
end
disp('read')
info.pixel_data = reshape(pixel_data,info.image_width,info.image_height);
else
% fseek(fid,uncompressed_pixel_buffer_size,'cof');
switch info.bytes_per_pixel
case 1
fseek(fid, uncompressed_pixel_buffer_size, 'cof');
case 2
fseek(fid, uncompressed_pixel_buffer_size/2, 'cof');
otherwise
fseek(fid, uncompressed_pixel_buffer_size/4, 'cof');
end
end
end
% Decode histogram
number_of_bins_in_histogram = fread(fid,1,'*int32');
if number_of_bins_in_histogram>0
info.histogram.number_of_bins_in_histogram=number_of_bins_in_histogram;
info.histogram.histogram_data = fread(fid,number_of_bins_in_histogram,'*int32');
end
% Decode properties
number_of_properties = fread(fid,1,'*int32');
if number_of_properties>0
info.properties=[];
end
for property_nr=1:number_of_properties
property_name_length = fread(fid,1,'*int32');
property_name = fread(fid,property_name_length,'*char')';
property_type = fread(fid,1,'*int32');
switch property_type
case 0
property_value = fread(fid,1,'*int32');
case 1
property_value = fread(fid,1,'double');
case 2
property_value_length = fread(fid,1,'*int32');
property_value = fread(fid,property_value_length,'*char')';
case 4
property_value_length = fread(fid,1,'*int32');
property_value = fread(fid,property_value_length/8,'double');
case 5
property_value_length = fread(fid,1,'*int32');
property_value = fread(fid,property_value_length/4,'*int32');
otherwise
disp(' ')
disp([property_name ': Property type ' num2str(property_type) ' is not supported! Aborting property decoding!']);
fclose(fid);
return;
end
info.properties=setfield(info.properties,property_name,property_value);
end
if nargout > 1
M = info.pixel_data;
rmfield(info,'pixel_data');
end
fclose(fid);
end