-
Notifications
You must be signed in to change notification settings - Fork 224
/
DICOM.java
6118 lines (6036 loc) · 244 KB
/
DICOM.java
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
package ij.plugin;
import java.io.*;
import java.util.*;
import java.net.URL;
import ij.*;
import ij.io.*;
import ij.process.*;
import ij.util.Tools;
import ij.measure.Calibration;
/** This plugin decodes DICOM files. If 'arg' is empty, it
displays a file open dialog and opens and displays the
image selected by the user. If 'arg' is a path, it opens the
specified image and the calling routine can display it using
"((ImagePlus)IJ.runPlugIn("ij.plugin.DICOM", path)).show()".
*/
/* RAK (Richard Kirk, rak@cre.canon.co.uk) changes 14/7/99
InputStream.skip() looped to check the actual number of
bytes is read.
Big/little-endian options on element length.
Explicit check for each known VR to make mistaken identifications
of explicit VR's less likely.
Variables b1..b4 renamed as b0..b3.
Increment of 4 to offset on (7FE0,0010) tag removed.
Queries on some other unrecognized tags.
Anyone want to claim them?
RAK changes 15/7/99
Bug fix on magic values for explicit VRs with 32-bit lengths.
Various bits of tidying up, including...
'location' incremented on read using getByte() or getString().
simpler debug mode message generation (values no longer reported).
Added z pixel aspect ratio support for multi-slice DICOM volumes.
Michael Abramoff, 31-10-2000
Added DICOM tags to the dictionary (now contains about 2700 tags).
implemented getDouble() for VR = FD (Floating Double) and getFloat()
for VR = FL (Floating Single).
Extended case statement in getHeaderInfo to retrieve FD and FL values.
Johannes Hermen, Christian Moll, 25-04-2008
*/
public class DICOM extends ImagePlus implements PlugIn {
private boolean showErrors = true;
private boolean gettingInfo;
private BufferedInputStream inputStream;
private String info;
/** Default constructor. */
public DICOM() {
}
/** Constructs a DICOM reader that using an InputStream. Here
is an example that shows how to open and display a DICOM:
<pre>
DICOM dcm = new DICOM(is);
dcm.run("Name");
dcm.show();
<pre>
*/
public DICOM(InputStream is) {
this(new BufferedInputStream(is));
}
/** Constructs a DICOM reader that using an BufferredInputStream. */
public DICOM(BufferedInputStream bis) {
inputStream = bis;
}
public void run(String arg) {
OpenDialog od = new OpenDialog("Open Dicom...", arg);
String directory = od.getDirectory();
String fileName = od.getFileName();
if (fileName==null)
return;
DicomDecoder dd = new DicomDecoder(directory, fileName);
dd.inputStream = inputStream;
FileInfo fi = null;
try {
fi = dd.getFileInfo();
} catch (IOException e) {
String msg = e.getMessage();
IJ.showStatus("");
if (msg.indexOf("EOF")<0&&showErrors) {
IJ.error("DICOM Reader", e.getClass().getName()+"\n \n"+msg);
return;
} else if (!dd.dicmFound()&&showErrors) {
msg = "This does not appear to be a valid\n"
+ "DICOM file. It does not have the\n"
+ "characters 'DICM' at offset 128.";
IJ.error("DICOM Reader", msg);
return;
}
}
if (gettingInfo) {
info = dd.getDicomInfo();
return;
}
if (fi!=null && fi.width>0 && fi.height>0 && fi.offset>0) {
FileOpener fo = new FileOpener(fi);
ImagePlus imp = fo.openImage();
// Avoid opening as float even if slope != 1.0 in case ignoreRescaleSlope or fixedDicomScaling
// were checked in the DICOM preferences.
boolean openAsFloat = (dd.rescaleSlope!=1.0 && !(Prefs.ignoreRescaleSlope || Prefs.fixedDicomScaling))
|| Prefs.openDicomsAsFloat;
String options = Macro.getOptions();
if (openAsFloat) {
IJ.run(imp, "32-bit", "");
if (dd.rescaleSlope!=1.0)
IJ.run(imp, "Multiply...", "value="+dd.rescaleSlope+" stack");
if (dd.rescaleIntercept!=0.0)
IJ.run(imp, "Add...", "value="+dd.rescaleIntercept+" stack");
if (imp.getStackSize()>1) {
imp.setSlice(imp.getStackSize()/2);
ImageStatistics stats = imp.getRawStatistics();
imp.setDisplayRange(stats.min,stats.max);
}
} else if (fi.fileType==FileInfo.GRAY16_SIGNED) {
if (dd.rescaleIntercept!=0.0 && (dd.rescaleSlope==1.0||Prefs.fixedDicomScaling)) {
double[] coeff = new double[2];
coeff[0] = dd.rescaleSlope*(-32768) + dd.rescaleIntercept;
coeff[1] = dd.rescaleSlope;
imp.getCalibration().setFunction(Calibration.STRAIGHT_LINE, coeff, "Gray Value");
}
} else if (dd.rescaleIntercept!=0.0 &&
(dd.rescaleSlope==1.0||Prefs.fixedDicomScaling||fi.fileType==FileInfo.GRAY8)) {
double[] coeff = new double[2];
coeff[0] = dd.rescaleIntercept;
coeff[1] = dd.rescaleSlope;
imp.getCalibration().setFunction(Calibration.STRAIGHT_LINE, coeff, "Gray Value");
}
Macro.setOptions(options);
if (dd.windowWidth>0.0) {
double min = dd.windowCenter-dd.windowWidth/2;
double max = dd.windowCenter+dd.windowWidth/2;
if (!openAsFloat) {
Calibration cal = imp.getCalibration();
min = cal.getRawValue(min);
max = cal.getRawValue(max);
}
ImageProcessor ip = imp.getProcessor();
ip.setMinAndMax(min, max);
if (IJ.debugMode) IJ.log("window: "+min+"-"+max);
}
if (imp.getStackSize()>1)
setStack(fileName, imp.getStack());
else
setProcessor(fileName, imp.getProcessor());
setCalibration(imp.getCalibration());
setProperty("Info", dd.getDicomInfo());
setFileInfo(fi); // needed for revert
if (arg.equals("")) show();
} else if (showErrors)
IJ.error("DICOM Reader","Unable to decode DICOM header.");
IJ.showStatus("");
}
/** Opens the specified file as a DICOM. Does not
display a message if there is an error.
Here is an example:
<pre>
DICOM dcm = new DICOM();
dcm.open(path);
if (dcm.getWidth()==0)
IJ.log("Error opening '"+path+"'");
else
dcm.show();
</pre>
*/
public void open(String path) {
showErrors = false;
run(path);
}
/** Returns the DICOM tags of the specified file as a string. */
public String getInfo(String path) {
showErrors = false;
gettingInfo = true;
run(path);
return info;
}
/** Convert 16-bit signed to unsigned if all pixels>=0. */
void convertToUnsigned(ImagePlus imp, FileInfo fi) {
ImageProcessor ip = imp.getProcessor();
short[] pixels = (short[])ip.getPixels();
int min = Integer.MAX_VALUE;
int value;
for (int i=0; i<pixels.length; i++) {
value = pixels[i]&0xffff;
if (value<min)
min = value;
}
if (IJ.debugMode) IJ.log("min: "+(min-32768));
if (min>=32768) {
for (int i=0; i<pixels.length; i++)
pixels[i] = (short)(pixels[i]-32768);
ip.resetMinAndMax();
Calibration cal = imp.getCalibration();
cal.setFunction(Calibration.NONE, null, "Gray Value");
fi.fileType = FileInfo.GRAY16_UNSIGNED;
}
}
/** Returns the name of the specified DICOM tag id. */
public static String getTagName(String id) {
id = id.replaceAll(",", "");
DicomDictionary d = new DicomDictionary();
Properties dictionary = d.getDictionary();
String name = (String)dictionary.get(id);
if (name!=null)
name = name.substring(2);
return name;
}
}
class DicomDecoder {
private static final int PIXEL_REPRESENTATION = 0x00280103;
private static final int TRANSFER_SYNTAX_UID = 0x00020010;
private static final int MODALITY = 0x00080060;
private static final int SLICE_THICKNESS = 0x00180050;
private static final int SLICE_SPACING = 0x00180088;
private static final int IMAGER_PIXEL_SPACING = 0x00181164;
private static final int SAMPLES_PER_PIXEL = 0x00280002;
private static final int PHOTOMETRIC_INTERPRETATION = 0x00280004;
private static final int PLANAR_CONFIGURATION = 0x00280006;
private static final int NUMBER_OF_FRAMES = 0x00280008;
private static final int ROWS = 0x00280010;
private static final int COLUMNS = 0x00280011;
private static final int PIXEL_SPACING = 0x00280030;
private static final int BITS_ALLOCATED = 0x00280100;
private static final int WINDOW_CENTER = 0x00281050;
private static final int WINDOW_WIDTH = 0x00281051;
private static final int RESCALE_INTERCEPT = 0x00281052;
private static final int RESCALE_SLOPE = 0x00281053;
private static final int RED_PALETTE = 0x00281201;
private static final int GREEN_PALETTE = 0x00281202;
private static final int BLUE_PALETTE = 0x00281203;
private static final int ACQUISITION_CONTEXT_SEQUENCE = 0x00400555;
private static final int VIEW_CODE_SEQUENCE = 0x00540220;
private static final int ICON_IMAGE_SEQUENCE = 0x00880200;
private static final int ITEM = 0xFFFEE000;
private static final int ITEM_DELIMINATION = 0xFFFEE00D;
private static final int SEQUENCE_DELIMINATION = 0xFFFEE0DD;
private static final int FLOAT_PIXEL_DATA = 0x7FE00008;
private static final int PIXEL_DATA = 0x7FE00010;
private static final int AE=0x4145, AS=0x4153, AT=0x4154, CS=0x4353, DA=0x4441, DS=0x4453, DT=0x4454,
FD=0x4644, FL=0x464C, IS=0x4953, LO=0x4C4F, LT=0x4C54, PN=0x504E, SH=0x5348, SL=0x534C,
SS=0x5353, ST=0x5354, TM=0x544D, UI=0x5549, UL=0x554C, US=0x5553, UT=0x5554,
OB=0x4F42, OW=0x4F57, SQ=0x5351, UN=0x554E, QQ=0x3F3F,
OF=0x4F46, OL=0x4F4C, OD=0x4F44, UC=0x5543, UR=0x5552, OV=0x4F56, SV=0x5356, UV=0x5556;
private static Properties dictionary;
private String directory, fileName;
private static final int ID_OFFSET = 128; //location of "DICM"
private static final String DICM = "DICM";
private BufferedInputStream f;
private int location = 0;
private boolean littleEndian = true;
private int elementLength;
private int vr; // Value Representation
private static final int IMPLICIT_VR = 0x2D2D; // '--'
private byte[] vrLetters = new byte[2];
private int previousGroup;
private String previousInfo;
private StringBuffer dicomInfo = new StringBuffer(1000);
private boolean dicmFound; // "DICM" found at offset 128
private boolean oddLocations; // one or more tags at odd locations
private boolean bigEndianTransferSyntax = false;
double windowCenter, windowWidth;
double rescaleIntercept, rescaleSlope=1.0;
boolean inSequence;
BufferedInputStream inputStream;
String modality;
private boolean acquisitionSequence;
public DicomDecoder(String directory, String fileName) {
this.directory = directory;
this.fileName = fileName;
String path = null;
if (dictionary==null && IJ.getApplet()==null) {
path = Prefs.getImageJDir()+"DICOM_Dictionary.txt";
File f = new File(path);
if (f.exists()) try {
dictionary = new Properties();
InputStream is = new BufferedInputStream(new FileInputStream(f));
dictionary.load(is);
is.close();
if (IJ.debugMode) IJ.log("DicomDecoder: using "+dictionary.size()+" tag dictionary at "+path);
} catch (Exception e) {
dictionary = null;
}
}
if (dictionary==null) {
DicomDictionary d = new DicomDictionary();
dictionary = d.getDictionary();
if (IJ.debugMode) IJ.log("DicomDecoder: "+path+" not found; using "+dictionary.size()+" tag built in dictionary");
}
}
String getString(int length) throws IOException {
byte[] buf = new byte[length];
int pos = 0;
while (pos<length) {
int count = f.read(buf, pos, length-pos);
if (count==-1)
throw new IOException("unexpected EOF");
pos += count;
}
location += length;
return new String(buf);
}
String getUNString(int length) throws IOException {
String s = getString(length);
if (s!=null && s.length()>60)
s = s.substring(0,60);
return s;
}
int getByte() throws IOException {
int b = f.read();
if (b ==-1)
throw new IOException("unexpected EOF");
++location;
return b;
}
int getShort() throws IOException {
int b0 = getByte();
int b1 = getByte();
if (littleEndian)
return ((b1 << 8) + b0);
else
return ((b0 << 8) + b1);
}
int getSShort() throws IOException {
short b0 = (short)getByte();
short b1 = (short)getByte();
if (littleEndian)
return ((b1 << 8) + b0);
else
return ((b0 << 8) + b1);
}
final int getInt() throws IOException {
int b0 = getByte();
int b1 = getByte();
int b2 = getByte();
int b3 = getByte();
if (littleEndian)
return ((b3<<24) + (b2<<16) + (b1<<8) + b0);
else
return ((b0<<24) + (b1<<16) + (b2<<8) + b3);
}
long getUInt() throws IOException {
long b0 = getByte();
long b1 = getByte();
long b2 = getByte();
long b3 = getByte();
if (littleEndian)
return ((b3<<24) + (b2<<16) + (b1<<8) + b0);
else
return ((b0<<24) + (b1<<16) + (b2<<8) + b3);
}
double getDouble() throws IOException {
int b0 = getByte();
int b1 = getByte();
int b2 = getByte();
int b3 = getByte();
int b4 = getByte();
int b5 = getByte();
int b6 = getByte();
int b7 = getByte();
long res = 0;
if (littleEndian) {
res += b0;
res += ( ((long)b1) << 8);
res += ( ((long)b2) << 16);
res += ( ((long)b3) << 24);
res += ( ((long)b4) << 32);
res += ( ((long)b5) << 40);
res += ( ((long)b6) << 48);
res += ( ((long)b7) << 56);
} else {
res += b7;
res += ( ((long)b6) << 8);
res += ( ((long)b5) << 16);
res += ( ((long)b4) << 24);
res += ( ((long)b3) << 32);
res += ( ((long)b2) << 40);
res += ( ((long)b1) << 48);
res += ( ((long)b0) << 56);
}
return Double.longBitsToDouble(res);
}
float getFloat() throws IOException {
int b0 = getByte();
int b1 = getByte();
int b2 = getByte();
int b3 = getByte();
int res = 0;
if (littleEndian) {
res += b0;
res += ( ((long)b1) << 8);
res += ( ((long)b2) << 16);
res += ( ((long)b3) << 24);
} else {
res += b3;
res += ( ((long)b2) << 8);
res += ( ((long)b1) << 16);
res += ( ((long)b0) << 24);
}
return Float.intBitsToFloat(res);
}
byte[] getLut(int length) throws IOException {
if ((length&1)!=0) { // odd
String dummy = getString(length);
return null;
}
length /= 2;
byte[] lut = new byte[length];
for (int i=0; i<length; i++)
lut[i] = (byte)(getShort()>>>8);
return lut;
}
int getLength() throws IOException {
int b0 = getByte();
int b1 = getByte();
int b2 = getByte();
int b3 = getByte();
// We cannot know whether the VR is implicit or explicit
// without the full DICOM Data Dictionary for public and
// private groups.
// We will assume the VR is explicit if the two bytes
// match the known codes. It is possible that these two
// bytes are part of a 32-bit length for an implicit VR.
vr = (b0<<8) + b1;
switch (vr) {
case OB: case OW: case SQ: case UN: case UT:
case OF: case OL: case OD: case UC: case UR:
case OV: case SV: case UV:
// Explicit VR with 32-bit length if other two bytes are zero
if ( (b2 == 0) || (b3 == 0) ) return getInt();
// Implicit VR with 32-bit length
vr = IMPLICIT_VR;
if (littleEndian)
return ((b3<<24) + (b2<<16) + (b1<<8) + b0);
else
return ((b0<<24) + (b1<<16) + (b2<<8) + b3);
case AE: case AS: case AT: case CS: case DA: case DS: case DT: case FD:
case FL: case IS: case LO: case LT: case PN: case SH: case SL: case SS:
case ST: case TM: case UI: case UL: case US: case QQ:
// Explicit vr with 16-bit length
if (littleEndian)
return ((b3<<8) + b2);
else
return ((b2<<8) + b3);
default:
// Implicit VR with 32-bit length...
vr = IMPLICIT_VR;
if (littleEndian)
return ((b3<<24) + (b2<<16) + (b1<<8) + b0);
else
return ((b0<<24) + (b1<<16) + (b2<<8) + b3);
}
}
int getNextTag() throws IOException {
int groupWord = getShort();
if (groupWord==0x0800 && bigEndianTransferSyntax) {
littleEndian = false;
groupWord = 0x0008;
}
int elementWord = getShort();
int tag = groupWord<<16 | elementWord;
elementLength = getLength();
// hack needed to read some GE files
// The element length must be even!
if (elementLength==13 && !oddLocations) elementLength = 10;
// "Undefined" element length.
// This is a sort of bracket that encloses a sequence of elements.
if (elementLength==-1) {
elementLength = 0;
inSequence = true;
}
//IJ.log("getNextTag: "+tag+" "+elementLength);
return tag;
}
FileInfo getFileInfo() throws IOException {
long skipCount;
FileInfo fi = new FileInfo();
int bitsAllocated = 16;
fi.fileFormat = fi.RAW;
fi.fileName = fileName;
if (directory.indexOf("://")>0) { // is URL
URL u = new URL(directory+fileName);
inputStream = new BufferedInputStream(u.openStream());
fi.inputStream = inputStream;
} else if (inputStream!=null)
fi.inputStream = inputStream;
else
fi.directory = directory;
fi.width = 0;
fi.height = 0;
fi.offset = 0;
fi.intelByteOrder = true;
fi.fileType = FileInfo.GRAY16_UNSIGNED;
fi.fileFormat = FileInfo.DICOM;
int samplesPerPixel = 1;
int planarConfiguration = 0;
String photoInterpretation = "";
if (inputStream!=null) {
// Use large buffer to allow URL stream to be reset after reading header
f = inputStream;
f.mark(400000);
} else
f = new BufferedInputStream(new FileInputStream(directory + fileName));
if (IJ.debugMode) {
IJ.log("");
IJ.log("DicomDecoder: decoding "+fileName);
}
int[] bytes = new int[ID_OFFSET];
for (int i=0; i<ID_OFFSET; i++)
bytes[i] = getByte();
if (!getString(4).equals(DICM)) {
if (!((bytes[0]==8||bytes[0]==2) && bytes[1]==0 && bytes[3]==0))
throw new IOException("This is not a DICOM or ACR/NEMA file");
if (inputStream==null) f.close();
if (inputStream!=null)
f.reset();
else
f = new BufferedInputStream(new FileInputStream(directory + fileName));
location = 0;
if (IJ.debugMode) IJ.log(DICM + " not found at offset "+ID_OFFSET+"; reseting to offset 0");
} else {
dicmFound = true;
if (IJ.debugMode) IJ.log(DICM + " found at offset " + ID_OFFSET);
}
boolean decodingTags = true;
boolean signed = false;
while (decodingTags) {
int tag = getNextTag();
if ((location&1)!=0) // DICOM tags must be at even locations
oddLocations = true;
if (inSequence && !acquisitionSequence) {
addInfo(tag, null);
continue;
}
String s;
switch (tag) {
case TRANSFER_SYNTAX_UID:
s = getString(elementLength);
addInfo(tag, s);
if (s.indexOf("1.2.4")>-1||s.indexOf("1.2.5")>-1) {
f.close();
String msg = "ImageJ cannot open compressed DICOM images.\n \n";
msg += "Transfer Syntax UID = "+s;
throw new IOException(msg);
}
if (s.indexOf("1.2.840.10008.1.2.2")>=0)
bigEndianTransferSyntax = true;
break;
case MODALITY:
modality = getString(elementLength);
addInfo(tag, modality);
break;
case NUMBER_OF_FRAMES:
s = getString(elementLength);
addInfo(tag, s);
double frames = s2d(s);
if (frames>1.0)
fi.nImages = (int)frames;
break;
case SAMPLES_PER_PIXEL:
samplesPerPixel = getShort();
addInfo(tag, samplesPerPixel);
break;
case PHOTOMETRIC_INTERPRETATION:
photoInterpretation = getString(elementLength);
addInfo(tag, photoInterpretation);
break;
case PLANAR_CONFIGURATION:
planarConfiguration = getShort();
addInfo(tag, planarConfiguration);
break;
case ROWS:
fi.height = getShort();
addInfo(tag, fi.height);
break;
case COLUMNS:
fi.width = getShort();
addInfo(tag, fi.width);
break;
case IMAGER_PIXEL_SPACING: case PIXEL_SPACING:
String scale = getString(elementLength);
getSpatialScale(fi, scale);
addInfo(tag, scale);
break;
case SLICE_THICKNESS: case SLICE_SPACING:
String spacing = getString(elementLength);
fi.pixelDepth = s2d(spacing);
addInfo(tag, spacing);
break;
case BITS_ALLOCATED:
bitsAllocated = getShort();
if (bitsAllocated==8)
fi.fileType = FileInfo.GRAY8;
else if (bitsAllocated==32)
fi.fileType = FileInfo.GRAY32_UNSIGNED;
addInfo(tag, bitsAllocated);
break;
case PIXEL_REPRESENTATION:
int pixelRepresentation = getShort();
if (pixelRepresentation==1) {
fi.fileType = FileInfo.GRAY16_SIGNED;
signed = true;
}
addInfo(tag, pixelRepresentation);
break;
case WINDOW_CENTER:
String center = getString(elementLength);
int index = center.indexOf('\\');
if (index!=-1) center = center.substring(index+1);
windowCenter = s2d(center);
addInfo(tag, center);
break;
case WINDOW_WIDTH:
String width = getString(elementLength);
index = width.indexOf('\\');
if (index!=-1) width = width.substring(index+1);
windowWidth = s2d(width);
addInfo(tag, width);
break;
case RESCALE_INTERCEPT:
String intercept = getString(elementLength);
rescaleIntercept = s2d(intercept);
addInfo(tag, intercept);
break;
case RESCALE_SLOPE:
String slop = getString(elementLength);
rescaleSlope = s2d(slop);
addInfo(tag, slop);
break;
case RED_PALETTE:
fi.reds = getLut(elementLength);
addInfo(tag, elementLength/2);
break;
case GREEN_PALETTE:
fi.greens = getLut(elementLength);
addInfo(tag, elementLength/2);
break;
case BLUE_PALETTE:
fi.blues = getLut(elementLength);
addInfo(tag, elementLength/2);
break;
case FLOAT_PIXEL_DATA:
fi.fileType = FileInfo.GRAY32_FLOAT;
// continue without break
case PIXEL_DATA:
// Start of image data...
if (elementLength!=0) {
fi.offset = location;
addInfo(tag, location);
decodingTags = false;
} else
addInfo(tag, null);
break;
case 0x7F880010:
// What is this? - RAK
if (elementLength!=0) {
fi.offset = location+4;
decodingTags = false;
}
break;
default:
// Not used, skip over it...
addInfo(tag, null);
}
} // while(decodingTags)
if (fi.fileType==FileInfo.GRAY8) {
if (fi.reds!=null && fi.greens!=null && fi.blues!=null
&& fi.reds.length==fi.greens.length
&& fi.reds.length==fi.blues.length) {
fi.fileType = FileInfo.COLOR8;
fi.lutSize = fi.reds.length;
}
}
if (fi.fileType==FileInfo.GRAY32_UNSIGNED && signed)
fi.fileType = FileInfo.GRAY32_INT;
if (samplesPerPixel==3 && photoInterpretation.startsWith("RGB")) {
if (planarConfiguration==0)
fi.fileType = FileInfo.RGB;
else if (planarConfiguration==1)
fi.fileType = FileInfo.RGB_PLANAR;
} else if (photoInterpretation.endsWith("1 "))
fi.whiteIsZero = true;
if (!littleEndian)
fi.intelByteOrder = false;
if (IJ.debugMode) {
IJ.log("width: " + fi.width);
IJ.log("height: " + fi.height);
IJ.log("images: " + fi.nImages);
IJ.log("bits allocated: " + bitsAllocated);
IJ.log("offset: " + fi.offset);
}
if (inputStream!=null)
f.reset();
else
f.close();
return fi;
}
String getDicomInfo() {
String s = new String(dicomInfo);
char[] chars = new char[s.length()];
s.getChars(0, s.length(), chars, 0);
for (int i=0; i<chars.length; i++) {
if (chars[i]<' ' && chars[i]!='\n') chars[i] = ' ';
}
return new String(chars);
}
void addInfo(int tag, String value) throws IOException {
String info = getHeaderInfo(tag, value);
if (inSequence && info!=null && vr!=SQ) info = ">" + info;
if (info!=null && tag!=ITEM) {
int group = tag>>>16;
//if (group!=previousGroup && (previousInfo!=null&&previousInfo.indexOf("Sequence:")==-1))
// dicomInfo.append("\n");
previousGroup = group;
previousInfo = info;
dicomInfo.append(tag2hex(tag)+info+"\n");
}
if (IJ.debugMode) {
if (info==null) info = "";
vrLetters[0] = (byte)(vr >> 8);
vrLetters[1] = (byte)(vr & 0xFF);
String VR = new String(vrLetters);
IJ.log("(" + tag2hex(tag) + VR
+ " " + elementLength
+ " bytes from "
+ (location-elementLength)+") "
+ info);
}
}
void addInfo(int tag, int value) throws IOException {
addInfo(tag, Integer.toString(value));
}
String getHeaderInfo(int tag, String value) throws IOException {
if (tag==ITEM_DELIMINATION || tag==SEQUENCE_DELIMINATION) {
inSequence = false;
if (!IJ.debugMode) return null;
}
String key = i2hex(tag);
//while (key.length()<8)
// key = '0' + key;
String id = (String)dictionary.get(key);
if (id!=null) {
if (vr==IMPLICIT_VR && id!=null)
vr = (id.charAt(0)<<8) + id.charAt(1);
id = id.substring(2);
}
if (tag==ITEM)
return id!=null?id+":":null;
if (value!=null)
return id+": "+value;
switch (vr) {
case FD:
if (elementLength==8)
value = Double.toString(getDouble());
else
for (int i=0; i<elementLength; i++) getByte();
break;
case FL:
if (elementLength==4)
value = Float.toString(getFloat());
else
for (int i=0; i<elementLength; i++) getByte();
break;
//case UT:
//throw new IOException("ImageJ cannot read UT (unlimited text) DICOMs");
case AE: case AS: case AT: case CS: case DA: case DS: case DT: case IS: case LO:
case LT: case PN: case SH: case ST: case TM: case UI:
value = getString(elementLength);
break;
case UN:
value = getUNString(elementLength);
break;
case US:
if (elementLength==2)
value = Integer.toString(getShort());
else {
int n = elementLength/2;
StringBuilder sb = new StringBuilder();
for (int i=0; i<n; i++) {
sb.append(Integer.toString(getShort()));
sb.append(" ");
}
value = sb.toString();
}
break;
case SS:
if (elementLength==2)
value = Integer.toString(getSShort());
else {
int n = elementLength/2;
StringBuilder sb = new StringBuilder();
for (int i=0; i<n; i++) {
sb.append(Integer.toString(getSShort()));
sb.append(" ");
}
value = sb.toString();
}
break;
case UL:
if (elementLength==4)
value = Long.toString(getUInt());
else {
int n = elementLength/4;
StringBuilder sb = new StringBuilder();
for (int i=0; i<n; i++) {
sb.append(Long.toString(getUInt()));
sb.append(" ");
}
value = sb.toString();
}
break;
case SL:
if (elementLength==4)
value = Long.toString(getInt());
else {
int n = elementLength/4;
StringBuilder sb = new StringBuilder();
for (int i=0; i<n; i++) {
sb.append(Long.toString(getInt()));
sb.append(" ");
}
value = sb.toString();
}
break;
case IMPLICIT_VR:
value = getString(elementLength);
if (elementLength>44) value=null;
break;
case SQ:
value = "";
if (tag==ACQUISITION_CONTEXT_SEQUENCE)
acquisitionSequence = true;
if (tag==VIEW_CODE_SEQUENCE)
acquisitionSequence = false;
boolean privateTag = ((tag>>16)&1)!=0;
if (tag!=ICON_IMAGE_SEQUENCE && !privateTag)
break;
// else fall through and skip icon image sequence or private sequence
default:
long skipCount = (long)elementLength;
while (skipCount > 0) skipCount -= f.skip(skipCount);
location += elementLength;
value = "";
}
if (value!=null && id==null && !value.equals(""))
return "---: "+value;
else if (id==null)
return null;
else
return id+": "+value;
}
static char[] buf8 = new char[8];
/** Converts an int to an 8 byte hex string. */
String i2hex(int i) {
for (int pos=7; pos>=0; pos--) {
buf8[pos] = Tools.hexDigits[i&0xf];
i >>>= 4;
}
return new String(buf8);
}
char[] buf10;
String tag2hex(int tag) {
if (buf10==null) {
buf10 = new char[11];
buf10[4] = ',';
buf10[9] = ' ';
}
int pos = 8;
while (pos>=0) {
buf10[pos] = Tools.hexDigits[tag&0xf];
tag >>>= 4;
pos--;
if (pos==4) pos--; // skip coma
}
return new String(buf10);
}
double s2d(String s) {
if (s==null) return 0.0;
if (s.startsWith("\\"))
s = s.substring(1);
Double d;
try {d = Double.valueOf(s);}
catch (NumberFormatException e) {d = null;}
if (d!=null)
return(d.doubleValue());
else
return(0.0);
}
void getSpatialScale(FileInfo fi, String scale) {
double xscale=0, yscale=0;
int i = scale.indexOf('\\');
if (i>0) {
yscale = s2d(scale.substring(0, i));
xscale = s2d(scale.substring(i+1));
}
if (xscale!=0.0 && yscale!=0.0) {
fi.pixelWidth = xscale;
fi.pixelHeight = yscale;
fi.unit = "mm";
}
}
boolean dicmFound() {
return dicmFound;
}
}
class DicomDictionary {
Properties getDictionary() {
Properties p = new Properties();
for (int i=0; i<dict.length; i++) {
p.put(dict[i].substring(0,8), dict[i].substring(9));
}
return p;
}
String[] dict = {
"00020000=ULFile Meta Information Group Length",
"00020001=OBFile Meta Information Version",
"00020002=UIMedia Storage SOP Class UID",
"00020003=UIMedia Storage SOP Instance UID",
"00020010=UITransfer Syntax UID",
"00020012=UIImplementation Class UID",
"00020013=SHImplementation Version Name",
"00020016=AESource Application Entity Title",
"00020017=AESending Application Entity Title",
"00020018=AEReceiving Application Entity Title",
"00020026=URSource Presentation Address",