forked from pixmeo/osirix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDICOMExport.mm
1338 lines (1141 loc) · 51.4 KB
/
DICOMExport.mm
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
/*=========================================================================
Program: OsiriX
Copyright (c) OsiriX Team
All rights reserved.
Distributed under GNU - LGPL
See http://www.osirix-viewer.com/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#import "DICOMExport.h"
#import <OsiriX/DCM.h>
#import "BrowserController.h"
#import "dicomFile.h"
#import "DCMView.h"
#import "DCMPix.h"
#import "altivecFunctions.h"
#import "DICOMToNSString.h"
#import "DicomDatabase+DCMTK.h"
static float deg2rad = M_PI / 180.0f;
@implementation DICOMExport
@synthesize rotateRawDataBy90degrees, metaDataDict;
- (NSString*) seriesDescription
{
return exportSeriesDescription;
}
- (void) setSeriesDescription: (NSString*) desc
{
if( desc != exportSeriesDescription)
{
[exportSeriesDescription release];
exportSeriesDescription = [desc retain];
}
}
- (void) setSeriesNumber: (long) no
{
if( exportSeriesNumber != no)
{
exportSeriesNumber = no;
[exportSeriesUID release];
exportSeriesUID = [[DCMObject newSeriesInstanceUID] retain];
}
}
- (id)init
{
self = [super init];
if (self)
{
dcmSourcePath = nil;
dcmDst = nil;
data = nil;
width = height = spp = bps = 0;
image = nil;
imageData = nil;
freeImageData = NO;
imageRepresentation = nil;
ww = wl = -1;
exportInstanceNumber = 1;
exportSeriesNumber = 5000;
#ifndef OSIRIX_LIGHT
exportSeriesUID = [[DCMObject newSeriesInstanceUID] retain];
exportSeriesDescription = [@"OsiriX SC" retain];
#endif
spacingX = 0;
spacingY = 0;
sliceThickness = 0;
sliceInterval = 0;
slicePosition = 0;
slope = 1;
int i;
for( i = 0; i < 6; i++) orientation[ i] = 0;
for( i = 0; i < 3; i++) position[ i] = 0;
metaDataDict = [[NSMutableDictionary dictionaryWithObjectsAndKeys:@"unknown", @"patientsName",
@"unknown ID", @"patientID",
[NSCalendarDate dateWithYear: 1900 month: 1 day: 1 hour: 1 minute: 1 second: 1 timeZone: nil], @"patientsBirthdate",
@"M", @"patientsSex",
[NSCalendarDate date], @"studyDate",
nil] retain];
}
return self;
}
- (void) dealloc
{
NSLog(@"DICOMExport released");
if( localData)
free( localData);
localData = nil;
[image release];
[imageRepresentation release];
if( freeImageData) free( imageData);
[exportSeriesUID release];
[exportSeriesDescription release];
[dcmSourcePath release];
[dcmDst release];
if( dcmtkFileFormat)
delete dcmtkFileFormat;
[metaDataDict release];
[super dealloc];
}
- (void) setSourceFile:(NSString*) isource
{
[dcmSourcePath release];
dcmSourcePath = [isource retain];
}
- (void) setSigned: (BOOL) s
{
isSigned = s;
}
- (void) setOffset: (int) o
{
offset = o;
}
- (void) setSlope: (float) s
{
slope = s;
}
- (long) setPixelData: (unsigned char*) idata
samplesPerPixel: (int) ispp
bitsPerSample: (int) ibps
width: (long) iwidth
height: (long) iheight
{
if( localData)
free( localData);
localData = nil;
spp = ispp;
bps = ibps;
width = iwidth;
height = iheight;
data = idata;
isSigned = NO;
offset = -1024;
if( spp == 4 && bps == 8)
{
localData = (unsigned char*) malloc( width * height * 3);
if( localData)
{
spp = 3;
for( int y = 0; y < height; y++)
{
for( int x = 0; x < width; x++)
{
float alpha = (float)data[ 3+ x*4 + y*width*4] / 255.;
localData[ 0 + x*3 + y*width*3] = data[ 0+ x*4 + y*width*4]*alpha;
localData[ 1 + x*3 + y*width*3] = data[ 1+ x*4 + y*width*4]*alpha;
localData[ 2 + x*3 + y*width*3] = data[ 2+ x*4 + y*width*4]*alpha;
}
}
data = localData;
}
}
return 0;
}
- (long) setPixelData: (unsigned char*) idata
samplePerPixel: (long) ispp
bitsPerPixel: (long) ibps
width: (long) iwidth
height: (long) iheight
{
return [self setPixelData:idata samplesPerPixel:ispp bitsPerSample:ibps width:iwidth height:iheight];
}
- (long) setPixelNSImage: (NSImage*) iimage
{
if( image != iimage)
{
[image release];
image = nil;
[imageRepresentation release];
imageRepresentation = nil;
if( freeImageData) free( imageData);
freeImageData = NO;
imageData = nil;
image = [iimage retain];
}
if( image)
{
NSData *tiffRep = [image TIFFRepresentation];
NSSize imageSize;
long w, h, i;
if( tiffRep)
{
imageRepresentation = [[NSBitmapImageRep alloc] initWithData:tiffRep];
imageSize = [imageRepresentation size];
w = imageSize.width;
h = imageSize.height;
if( [imageRepresentation bytesPerRow] != w)
{
imageData = (unsigned char*) malloc( h * w * [imageRepresentation samplesPerPixel]);
freeImageData = YES;
for( i = 0; i < height; i++)
{
memcpy( imageData + i * width * [imageRepresentation samplesPerPixel], [imageRepresentation bitmapData] + i * [imageRepresentation bytesPerRow], width * [imageRepresentation samplesPerPixel]);
}
}
else imageData = [imageRepresentation bitmapData];
return [self setPixelData: imageData
samplesPerPixel: [imageRepresentation samplesPerPixel]
bitsPerSample: [imageRepresentation bitsPerPixel] / [imageRepresentation samplesPerPixel]
width: w
height: h];
}
else return -1;
}
else return -1;
}
- (void) setDefaultWWWL: (long) iww :(long) iwl
{
wl = iwl;
ww = iww;
}
- (void) setPixelSpacing: (float) x :(float) y;
{
spacingX = x;
spacingY = y;
}
- (void) setSliceThickness: (double) t
{
sliceThickness = t;
}
- (void) setOrientation: (float*) o
{
for( int i = 0; i < 6; i++) orientation[ i] = o[ i];
}
- (void) setPosition: (float*) p
{
for( int i = 0; i < 3; i++) position[ i] = p[ i];
}
- (void) setSlicePosition: (float) p
{
slicePosition = p;
}
- (void) setModalityAsSource: (BOOL) v
{
modalityAsSource = v;
}
- (BOOL) createDICOMHeader: (DcmItem *) dataset dictionary: (NSDictionary*) dict
{
OFCondition result = EC_Normal;
char buf[80];
// insert empty type 2 attributes
if (result.good()) result = dataset->insertEmptyElement(DCM_StudyDate);
if (result.good()) result = dataset->insertEmptyElement(DCM_StudyTime);
if (result.good()) result = dataset->insertEmptyElement(DCM_AccessionNumber);
if (result.good()) result = dataset->insertEmptyElement(DCM_Manufacturer);
if (result.good()) result = dataset->insertEmptyElement(DCM_ReferringPhysiciansName);
if (result.good()) result = dataset->insertEmptyElement(DCM_StudyID);
if (result.good()) result = dataset->insertEmptyElement(DCM_ContentDate);
if (result.good()) result = dataset->insertEmptyElement(DCM_ContentTime);
if (result.good()) result = dataset->insertEmptyElement(DCM_AcquisitionDate);
if (result.good()) result = dataset->insertEmptyElement(DCM_AcquisitionTime);
if (result.good()) result = dataset->insertEmptyElement(DCM_AcquisitionDatetime);
if (result.good()) result = dataset->insertEmptyElement(DCM_ConceptNameCodeSequence);
if (result.good()) result = dataset->putAndInsertString(DCM_SOPClassUID, UID_SecondaryCaptureImageStorage);
// insert const value attributes
if (result.good()) result = dataset->putAndInsertString(DCM_SpecificCharacterSet, "ISO_IR 100");
// there is no way we could determine a meaningful series number, so we just use a constant.
if (result.good()) result = dataset->putAndInsertString(DCM_SeriesNumber, "1");
// insert variable value attributes
if (result.good() && [dict objectForKey: @"patientsName"])
result = dataset->putAndInsertString(DCM_PatientsName, [[dict objectForKey: @"patientsName"] UTF8String]);
if (result.good() && [dict objectForKey: @"patientID"])
result = dataset->putAndInsertString(DCM_PatientID, [[dict objectForKey: @"patientID"] UTF8String]);
if (result.good() && [dict objectForKey: @"patientsBirthdate"])
result = dataset->putAndInsertString(DCM_PatientsBirthDate, [[[DCMCalendarDate dicomDateWithDate: [dict objectForKey: @"patientsBirthdate"]] dateString] UTF8String]);
if (result.good() && [dict objectForKey: @"patientsSex"])
result = dataset->putAndInsertString(DCM_PatientsSex, [[dict objectForKey: @"patientsSex"] UTF8String]);
if (result.good() && [dict objectForKey: @"studyDate"])
result = dataset->putAndInsertString(DCM_AcquisitionDate, [[[DCMCalendarDate dicomDateWithDate: [dict objectForKey: @"studyDate"]] dateString] UTF8String]);
if (result.good() && [dict objectForKey: @"studyDate"])
result = dataset->putAndInsertString(DCM_AcquisitionTime, [[[DCMCalendarDate dicomTimeWithDate: [dict objectForKey: @"studyDate"]] timeString] UTF8String]);
if (result.good() && [dict objectForKey: @"studyDescription"])
result = dataset->putAndInsertString(DCM_StudyDescription, [[dict objectForKey: @"studyDescription"] UTF8String]);
if (result.good() && [(NSString*)[dict objectForKey: @"modality"] length])
result = dataset->putAndInsertString(DCM_Modality, [[dict objectForKey: @"modality"] UTF8String]);
else
result = dataset->putAndInsertString(DCM_Modality, "OT");
dcmGenerateUniqueIdentifier(buf, SITE_STUDY_UID_ROOT);
if (result.good())
{
if( [dict objectForKey: @"studyUID"])
result = dataset->putAndInsertString(DCM_StudyInstanceUID, [[dict objectForKey: @"studyUID"] UTF8String]);
else
result = dataset->putAndInsertString(DCM_StudyInstanceUID, buf);
}
dcmGenerateUniqueIdentifier(buf, SITE_SERIES_UID_ROOT);
if (result.good())
{
if( [dict objectForKey: @"seriesUID"])
result = dataset->putAndInsertString(DCM_SeriesInstanceUID, [[dict objectForKey: @"seriesUID"] UTF8String]);
else
result = dataset->putAndInsertString(DCM_SeriesInstanceUID, buf);
}
dcmGenerateUniqueIdentifier(buf, SITE_INSTANCE_UID_ROOT);
if (result.good()) result = dataset->putAndInsertString(DCM_SOPInstanceUID, buf);
// set instance creation date and time
OFString s;
if (result.good()) result = DcmDate::getCurrentDate(s);
if (result.good()) result = dataset->putAndInsertOFStringArray(DCM_InstanceCreationDate, s);
if (result.good()) result = DcmTime::getCurrentTime(s);
if (result.good()) result = dataset->putAndInsertOFStringArray(DCM_InstanceCreationTime, s);
return result.good();
}
- (NSString*) writeDCMFile: (NSString*) dstPath
{
return [self writeDCMFile: dstPath withExportDCM: nil];
}
- (void) removeAllFieldsOfGroup: (Uint16) groupNumber dataset: (DcmItem *) dset
{
DcmStack stack;
DcmObject *dobj = NULL;
DcmTagKey tag;
OFCondition status = dset->nextObject(stack, OFTrue);
while (status.good())
{
dobj = stack.top();
tag = dobj->getTag();
if (tag.getGroup() == groupNumber)
{
stack.pop();
delete ((DcmItem *)(stack.top()))->remove(dobj);
}
status = dset->nextObject(stack, OFTrue);
}
}
- (NSString*) writeDCMFile: (NSString*) dstPath withExportDCM:(DCMExportPlugin*) dcmExport
{
#ifdef OSIRIX_LIGHT
NSLog( @"---- OSIRIX LIGHT CANNOT write DICOM files");
#endif
if( spp != 1 && spp != 3)
{
NSLog( @"**** DICOM Export: sample per pixel not supported: %ld", spp);
return nil;
}
if( spp == 3)
{
if( bps != 8)
{
NSLog( @"**** DICOM Export: for RGB images, only 8 bits per sample is supported: %ld", bps);
return nil;
}
}
if( bps != 8 && bps != 16 && bps != 32)
{
NSLog( @"**** DICOM Export: unknown bits per sample: %ld", bps);
return nil;
}
if( width != 0 && height != 0 && data != nil)
{
@try
{
if( [[NSUserDefaults standardUserDefaults] boolForKey: @"useDCMTKForDicomExport"])
{
const char *string = nil, *modality = nil;
unsigned char *squaredata = nil;
if( spacingX != 0 && spacingY != 0)
{
if( spacingX != spacingY) // Convert to square pixels
{
if( bps == 16)
{
vImage_Buffer srcVimage, dstVimage;
long newHeight = ((float) height * spacingY) / spacingX;
newHeight /= 2;
newHeight *= 2;
squaredata = (unsigned char*) malloc( newHeight * width * bps/8);
float *tempFloatSrc = (float*) malloc( height * width * sizeof( float));
float *tempFloatDst = (float*) malloc( newHeight * width * sizeof( float));
if( squaredata != nil && tempFloatSrc != nil && tempFloatDst != nil)
{
long err;
// Convert Source to float
srcVimage.data = data;
srcVimage.height = height;
srcVimage.width = width;
srcVimage.rowBytes = width* bps/8;
dstVimage.data = tempFloatSrc;
dstVimage.height = height;
dstVimage.width = width;
dstVimage.rowBytes = width*sizeof( float);
if( isSigned)
err = vImageConvert_16SToF(&srcVimage, &dstVimage, 0, 1, 0);
else
err = vImageConvert_16UToF(&srcVimage, &dstVimage, 0, 1, 0);
// Scale the image
srcVimage.data = tempFloatSrc;
srcVimage.height = height;
srcVimage.width = width;
srcVimage.rowBytes = width*sizeof( float);
dstVimage.data = tempFloatDst;
dstVimage.height = newHeight;
dstVimage.width = width;
dstVimage.rowBytes = width*sizeof( float);
err = vImageScale_PlanarF( &srcVimage, &dstVimage, nil, kvImageHighQualityResampling);
// if( err) NSLog(@"%d", err);
// Convert Destination to 16 bits
srcVimage.data = tempFloatDst;
srcVimage.height = newHeight;
srcVimage.width = width;
srcVimage.rowBytes = width*sizeof( float);
dstVimage.data = squaredata;
dstVimage.height = newHeight;
dstVimage.width = width;
dstVimage.rowBytes = width* bps/8;
if( isSigned)
err = vImageConvert_FTo16S( &srcVimage, &dstVimage, 0, 1, 0);
else
err = vImageConvert_FTo16U( &srcVimage, &dstVimage, 0, 1, 0);
spacingY = spacingX;
height = newHeight;
data = squaredata;
free( tempFloatSrc);
free( tempFloatDst);
}
}
}
}
if( rotateRawDataBy90degrees)
{
float copySpacingX = spacingX;
spacingX = spacingY;
spacingY = copySpacingX;
long copyWidth = width;
width = height;
height = copyWidth;
//Origin and vector
if( orientation[ 0] != 0 || orientation[ 1] != 0 || orientation[ 2] != 0)
{
float x = 0, y = width;
float newOrigin[ 3];
if( spacingX != 0 && spacingY != 0)
{
newOrigin[0] = position[0] + y*orientation[3]*spacingY + x*orientation[0]*spacingX;
newOrigin[1] = position[1] + y*orientation[4]*spacingY + x*orientation[1]*spacingX;
newOrigin[2] = position[2] + y*orientation[5]*spacingY + x*orientation[2]*spacingX;
}
else
{
newOrigin[0] = position[0] + y*orientation[3] + x*orientation[0];
newOrigin[1] = position[1] + y*orientation[4] + x*orientation[1];
newOrigin[2] = position[2] + y*orientation[5] + x*orientation[2];
}
position[0] = newOrigin[0];
position[1] = newOrigin[1];
position[2] = newOrigin[2];
float o[ 9];
o[0] = orientation[0]; o[1] = orientation[1]; o[2] = orientation[2];
o[3] = orientation[3]; o[4] = orientation[4]; o[5] = orientation[5];
// Compute normal vector
o[6] = o[1]*o[5] - o[2]*o[4];
o[7] = o[2]*o[3] - o[0]*o[5];
o[8] = o[0]*o[4] - o[1]*o[3];
XYZ vector, rotationVector;
rotationVector.x = o[ 6]; rotationVector.y = o[ 7]; rotationVector.z = o[ 8];
vector.x = o[ 0]; vector.y = o[ 1]; vector.z = o[ 2];
vector = ArbitraryRotate(vector, -90*deg2rad, rotationVector);
o[ 0] = vector.x; o[ 1] = vector.y; o[ 2] = vector.z;
vector.x = o[ 3]; vector.y = o[ 4]; vector.z = o[ 5];
vector = ArbitraryRotate(vector, -90*deg2rad, rotationVector);
o[ 3] = vector.x; o[ 4] = vector.y; o[ 5] = vector.z;
// Compute normal vector
o[6] = o[1]*o[5] - o[2]*o[4];
o[7] = o[2]*o[3] - o[0]*o[5];
o[8] = o[0]*o[4] - o[1]*o[3];
orientation[0] = o[0]; orientation[1] = o[1]; orientation[2] = o[2];
orientation[3] = o[3]; orientation[4] = o[4]; orientation[5] = o[5];
}
//Pixels data
switch( bps)
{
case 8:
if (spp == 3)
{
unsigned char *olddata = (unsigned char*) data;
unsigned char *newdata = (unsigned char*) malloc( height * width * bps*spp / 8);
for( long x = 0 ; x < width; x++)
{
for( long y = 0 ; y < height; y++)
{
*(newdata+y*width*3+x +0) = *(olddata+(width-x-1)*height*3+y +0);
*(newdata+y*width*3+x +1) = *(olddata+(width-x-1)*height*3+y +1);
*(newdata+y*width*3+x +2) = *(olddata+(width-x-1)*height*3+y +2);
}
}
memcpy( olddata, newdata, height * width * bps*spp / 8);
free( newdata);
}
else
{
unsigned char *olddata = (unsigned char*) data;
unsigned char *newdata = (unsigned char*) malloc( height * width * bps / 8);
for( long x = 0 ; x < width; x++)
{
for( long y = 0 ; y < height; y++)
{
*(newdata+y*width+x) = *(olddata+(width-x-1)*height+y);
}
}
memcpy( olddata, newdata, height * width * bps / 8);
free( newdata);
}
break;
case 16:
{
unsigned short *olddata = (unsigned short*) data;
unsigned short *newdata = (unsigned short*) malloc( height * width * bps / 8);
for( long x = 0 ; x < width; x++)
{
for( long y = 0 ; y < height; y++)
{
*(newdata+y*width+x) = *(olddata+(width-x-1)*height+y);
}
}
memcpy( olddata, newdata, height * width * bps / 8);
free( newdata);
}
break;
case 32:
{
float *olddata = (float*) data;
float *newdata = (float*) malloc( height * width * bps / 8);
for( long x = 0 ; x < width; x++)
{
for( long y = 0 ; y < height; y++)
{
*(newdata+y*width+x) = *(olddata+(width-x-1)*height+y);
}
}
memcpy( olddata, newdata, height * width * bps / 8);
free( newdata);
}
break;
default:
NSLog( @"**** unknown bps during rotate90 DICOMExport");
break;
}
}
#if __BIG_ENDIAN__
if( bps == 16)
{
//Convert to little endian
InverseShorts( (vector unsigned short*) data, height * width);
}
#endif
int elemLength = height * width * spp * bps / 8;
if( elemLength%2 != 0)
{
height--;
elemLength = height * width * spp * bps / 8;
if( elemLength%2 != 0) NSLog( @"***************** ODD element !!!!!!!!!!");
}
int highBit;
int bitsAllocated;
float numberBytes;
switch( bps)
{
case 8:
highBit = 7;
bitsAllocated = 8;
numberBytes = 1;
break;
case 16:
highBit = 15;
bitsAllocated = 16;
numberBytes = 2;
break;
case 32: // float support
highBit = 31;
bitsAllocated = 32;
numberBytes = 4;
break;
default:
NSLog(@"Unsupported bps: %ld", bps);
return nil;
break;
}
NSString *photometricInterpretation = @"MONOCHROME2";
if (spp == 3) photometricInterpretation = @"RGB";
if( dcmtkFileFormat)
delete dcmtkFileFormat;
dcmtkFileFormat = new DcmFileFormat();
BOOL succeed = NO;
if( dcmSourcePath)
{
if( [DicomFile isDICOMFile: dcmSourcePath])
{
OFCondition cond = dcmtkFileFormat->loadFile( [dcmSourcePath UTF8String], EXS_Unknown, EGL_noChange);
succeed = (cond.good()) ? YES : NO;
}
else
{
DicomFile* file = [[[DicomFile alloc] init:dcmSourcePath] autorelease];
if( file)
{
succeed = [self createDICOMHeader: dcmtkFileFormat->getDataset()
dictionary: [NSDictionary dictionaryWithObjectsAndKeys:
[file elementForKey: @"patientName"], @"patientsName",
[file elementForKey: @"patientID"], @"patientID",
[file elementForKey: @"patientBirthDate"], @"patientsBirthdate",
[file elementForKey: @"patientSex"], @"patientsSex",
[file elementForKey: @"studyDate"], @"studyDate",
nil]];
dcmtkFileFormat->getMetaInfo()->putAndInsertString(DCM_MediaStorageSOPClassUID, UID_SecondaryCaptureImageStorage);
}
}
}
if( succeed == NO)
{
succeed = [self createDICOMHeader: dcmtkFileFormat->getDataset() dictionary: metaDataDict];
dcmtkFileFormat->getMetaInfo()->putAndInsertString(DCM_MediaStorageSOPClassUID, UID_SecondaryCaptureImageStorage);
}
if( succeed)
{
NSStringEncoding encoding[ 10];
for( int i = 0; i < 10; i++) encoding[ i] = 0;
encoding[ 0] = NSISOLatin1StringEncoding;
dcmtkFileFormat->loadAllDataIntoMemory();
DcmItem *dataset = dcmtkFileFormat->getDataset();
DcmMetaInfo *metaInfo = dcmtkFileFormat->getMetaInfo();
[self removeAllFieldsOfGroup: 0x0028 dataset: dataset];
[self removeAllFieldsOfGroup: 0x5200 dataset: dataset]; //We don't support multiframe export
if (dataset->findAndGetString(DCM_SpecificCharacterSet, string, OFFalse).good() && string != NULL)
{
NSArray *c = [[NSString stringWithCString:string encoding: NSISOLatin1StringEncoding] componentsSeparatedByString:@"\\"];
if( [c count] >= 10) NSLog( @"Encoding number >= 10 ???");
if( [c count] < 10)
{
for( int i = 0; i < [c count]; i++) encoding[ i] = [NSString encodingForDICOMCharacterSet: [c objectAtIndex: i]];
for( int i = [c count]; i < 10; i++) encoding[ i] = [NSString encodingForDICOMCharacterSet: [c lastObject]];
}
}
if( exportSeriesUID)
dataset->putAndInsertString( DCM_SeriesInstanceUID, [exportSeriesUID UTF8String]);
if( exportSeriesDescription)
dataset->putAndInsertString( DCM_SeriesDescription, [exportSeriesDescription cStringUsingEncoding: encoding[ 0]]);
if( exportSeriesNumber != -1)
dataset->putAndInsertString( DCM_SeriesNumber, [[NSString stringWithFormat: @"%d", exportSeriesNumber] UTF8String]);
if( modalityAsSource == NO || spp == 3)
{
dataset->putAndInsertString( DCM_Modality, "SC");
metaInfo->putAndInsertString( DCM_MediaStorageSOPClassUID, UID_SecondaryCaptureImageStorage);
dataset->putAndInsertString( DCM_SOPClassUID, UID_SecondaryCaptureImageStorage);
}
else
delete dataset->remove( DCM_MediaStorageSOPClassUID);
dataset->putAndInsertString( DCM_ManufacturersModelName, "OsiriX");
dataset->putAndInsertString( DCM_InstanceNumber, [[NSString stringWithFormat: @"%d", exportInstanceNumber++] UTF8String]);
dataset->putAndInsertString( DCM_AcquisitionNumber, "1");
dataset->putAndInsertString( DCM_Rows, [[NSString stringWithFormat: @"%d", (int) height] UTF8String]);
dataset->putAndInsertString( DCM_Columns, [[NSString stringWithFormat: @"%d", (int) width] UTF8String]);
dataset->putAndInsertString( DCM_SamplesPerPixel, [[NSString stringWithFormat: @"%d", (int) spp] UTF8String]);
dataset->putAndInsertString( DCM_PhotometricInterpretation, [photometricInterpretation UTF8String]);
dataset->putAndInsertString( DCM_PixelRepresentation, [[NSString stringWithFormat: @"%d", isSigned] UTF8String]);
dataset->putAndInsertString( DCM_HighBit, [[NSString stringWithFormat: @"%d", highBit] UTF8String]);
dataset->putAndInsertString( DCM_BitsAllocated, [[NSString stringWithFormat: @"%d", bitsAllocated] UTF8String]);
dataset->putAndInsertString( DCM_BitsStored, [[NSString stringWithFormat: @"%d", bitsAllocated] UTF8String]);
delete dataset->remove( DCM_ImagerPixelSpacing);
delete dataset->remove( DCM_EstimatedRadiographicMagnificationFactor);
if( spacingX != 0 && spacingY != 0)
dataset->putAndInsertString( DCM_PixelSpacing, [[NSString stringWithFormat: @"%f\\%f", spacingY, spacingX] UTF8String]);
delete dataset->remove( DCM_SliceThickness);
if( sliceThickness != 0)
dataset->putAndInsertString( DCM_SliceThickness, [[NSString stringWithFormat: @"%f", sliceThickness] UTF8String]);
delete dataset->remove( DCM_ImageOrientationPatient);
if( orientation[ 0] != 0 || orientation[ 1] != 0 || orientation[ 2] != 0)
dataset->putAndInsertString( DCM_ImageOrientationPatient, [[NSString stringWithFormat: @"%f\\%f\\%f\\%f\\%f\\%f", orientation[ 0], orientation[ 1], orientation[ 2], orientation[ 3], orientation[ 4], orientation[ 5]] UTF8String]);
delete dataset->remove( DCM_ImagePositionPatient);
if( position[ 0] != 0 || position[ 1] != 0 || position[ 2] != 0)
{
dataset->putAndInsertString( DCM_ImagePositionPatient, [[NSString stringWithFormat: @"%f\\%f\\%f", position[ 0], position[ 1], position[ 2]] UTF8String]);
}
delete dataset->remove( DCM_SliceLocation);
if( slicePosition != 0)
dataset->putAndInsertString( DCM_SliceLocation, [[NSString stringWithFormat: @"%f", slicePosition] UTF8String]);
delete dataset->remove( DCM_PlanarConfiguration);
if( spp == 3)
dataset->putAndInsertString( DCM_PlanarConfiguration, "0");
if( dataset->findAndGetString( DCM_Modality, string, OFFalse).good() && string != NULL)
modality = string;
delete dataset->remove( DCM_PixelData);
delete dataset->remove( DcmTagKey( 0x0009, 0x1110)); // "GEIIS" The problematic private group, containing a *always* JPEG compressed PixelData
if( bps == 32) // float support
{
dataset->putAndInsertString( DCM_RescaleIntercept, "0");
dataset->putAndInsertString( DCM_RescaleSlope, "1");
if( modality && strcmp( modality, "CT") == 0)
dataset->putAndInsertString( DCM_RescaleType, "HU");
else
dataset->putAndInsertString( DCM_RescaleType, "US");
if( ww != -1 && ww != -1)
{
dataset->putAndInsertString( DCM_WindowCenter, [[NSString stringWithFormat: @"%d", (int) wl] UTF8String]);
dataset->putAndInsertString( DCM_WindowWidth, [[NSString stringWithFormat: @"%d", (int) ww] UTF8String]);
}
dataset->putAndInsertUint8Array(DCM_PixelData, OFstatic_cast(Uint8 *, OFconst_cast(void *, (void*) data)), height*width*4);
}
else if( bps == 16)
{
if( isSigned == NO)
dataset->putAndInsertString( DCM_RescaleIntercept, [[NSString stringWithFormat: @"%d", offset] UTF8String]);
else
dataset->putAndInsertString( DCM_RescaleIntercept, "0");
dataset->putAndInsertString( DCM_RescaleSlope, [[NSString stringWithFormat: @"%f", slope] UTF8String]);
if( modality && strcmp( modality, "CT") == 0)
dataset->putAndInsertString( DCM_RescaleType, "HU");
else
dataset->putAndInsertString( DCM_RescaleType, "US");
if( ww != -1 && ww != -1)
{
dataset->putAndInsertString( DCM_WindowCenter, [[NSString stringWithFormat: @"%d", (int) wl] UTF8String]);
dataset->putAndInsertString( DCM_WindowWidth, [[NSString stringWithFormat: @"%d", (int) ww] UTF8String]);
}
dataset->putAndInsertUint16Array(DCM_PixelData, OFstatic_cast(Uint16 *, OFconst_cast(void *, (void*) data)), height*width*spp);
}
else
{
delete dataset->remove( DCM_WindowWidth);
delete dataset->remove( DCM_WindowCenter);
if( spp != 3)
{
dataset->putAndInsertString( DCM_RescaleIntercept, "0");
dataset->putAndInsertString( DCM_RescaleSlope, "1");
dataset->putAndInsertString( DCM_RescaleType, "US");
}
else
{
delete dataset->remove( DCM_RescaleIntercept);
delete dataset->remove( DCM_RescaleSlope);
delete dataset->remove( DCM_WindowCenterWidthExplanation);
}
dataset->putAndInsertUint8Array(DCM_PixelData, OFstatic_cast(Uint8 *, OFconst_cast(void *, (void*) data)), height*width*spp);
}
delete dataset->remove( DCM_SmallestImagePixelValue);
delete dataset->remove( DCM_LargestImagePixelValue);
delete dataset->remove( DCM_MediaStorageSOPInstanceUID);
delete dataset->remove( DCM_PerFrameFunctionalGroupsSequence);
delete dataset->remove( DCM_IconImageSequence); // GE bug
char buf[ 128];
dcmGenerateUniqueIdentifier( buf);
dataset->putAndInsertString( DCM_SOPInstanceUID, buf);
metaInfo->putAndInsertString( DCM_MediaStorageSOPInstanceUID, buf);
dcmtkFileFormat->chooseRepresentation( EXS_LittleEndianExplicit, NULL);
if( dcmtkFileFormat->canWriteXfer( EXS_LittleEndianExplicit))
{
// Add to the current DB
if( dstPath == nil)
dstPath = [[BrowserController currentBrowser] getNewFileDatabasePath: @"dcm"];
OFCondition cond = dcmtkFileFormat->saveFile( [dstPath UTF8String], EXS_LittleEndianExplicit, EET_ExplicitLength, EGL_recalcGL, EPD_withoutPadding);
OFBool fileWriteSucceeded = (cond.good()) ? YES : NO;
if( fileWriteSucceeded == NO)
NSLog( @"******* dcmtkFileFormat->saveFile failed");
}
else if( triedToDecompress == NO)
{
NSLog( @"------ dcmtkFileFormat->canWriteXfer( EXS_LittleEndianExplicit) failed: try to decompress the file");
// Try to decompress the file
NSString *tmpFile = [@"/tmp" stringByAppendingPathComponent: dcmSourcePath.lastPathComponent];
[[NSFileManager defaultManager] removeItemAtPath: tmpFile error: nil];
[[NSFileManager defaultManager] copyItemAtPath: dcmSourcePath toPath: tmpFile error: nil];
[DicomDatabase decompressDicomFilesAtPaths: @[tmpFile]];
if( [[NSFileManager defaultManager] fileExistsAtPath: tmpFile])
{
if( squaredata)
free( squaredata);
squaredata = nil;
triedToDecompress = YES;
[dcmSourcePath release];
dcmSourcePath = [tmpFile retain];
NSString *f = [self writeDCMFile: dstPath];
[[NSFileManager defaultManager] removeItemAtPath: tmpFile error: nil];
triedToDecompress = YES;
return f;
}
}
if( squaredata)
free( squaredata);
squaredata = nil;
return dstPath;
}
}
// else
// {
// DCMCalendarDate *studyDate = nil, *studyTime = nil;
// DCMCalendarDate *acquisitionDate = nil, *acquisitionTime = nil;
// DCMCalendarDate *seriesDate = nil, *seriesTime = nil;
// DCMCalendarDate *contentDate = nil, *contentTime = nil;
//
// DCMObject *dcmObject = nil;
// NSString *patientName = nil, *patientID = nil, *studyDescription = nil, *studyUID = nil, *studyID = nil, *charSet = nil;
// NSNumber *seriesNumber = nil;
// unsigned char *squaredata = nil;
//
// seriesNumber = [NSNumber numberWithInt:exportSeriesNumber];
//
// if( dcmSourcePath)
// {
// if ([DicomFile isDICOMFile:dcmSourcePath])
// {
// dcmObject = [DCMObject objectWithContentsOfFile:dcmSourcePath decodingPixelData:NO];
//
// patientName = [dcmObject attributeValueWithName:@"PatientsName"];
// patientID = [dcmObject attributeValueWithName:@"PatientID"];
// studyDescription = [dcmObject attributeValueWithName:@"StudyDescription"];
// studyUID = [dcmObject attributeValueWithName:@"StudyInstanceUID"];