-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpr2mask.cxx
2286 lines (1986 loc) · 99.3 KB
/
pr2mask.cxx
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
#include <cstddef>
#include "itkGDCMImageIO.h"
#include "itkGDCMSeriesFileNames.h"
#include "itkImageFileWriter.h"
#include "itkImageSeriesReader.h"
#include "itkMetaDataObject.h"
#include "itkBinaryBallStructuringElement.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkImageAdaptor.h"
#include "itkImageRegionConstIterator.h"
#include "itkImageRegionIterator.h"
#include "itkRGBPixel.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkPolyLineParametricPath.h"
#include "itkPolylineMask2DImageFilter.h"
#include "itkPolylineMask2DScanlineImageFilter.h"
#include "itkRGBPixel.h"
#include "itkScalarImageToHistogramGenerator.h"
#include "itkConnectedComponentImageFilter.h"
#include "itkLabelImageToShapeLabelMapFilter.h"
#include "itkLabelShapeKeepNObjectsImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "gdcmAnonymizer.h"
#include "gdcmAttribute.h"
#include "gdcmDataSetHelper.h"
#include "gdcmDirectoryHelper.h"
#include "gdcmFileDerivation.h"
#include "gdcmFileExplicitFilter.h"
#include "gdcmGlobal.h"
#include "gdcmImageApplyLookupTable.h"
#include "gdcmImageChangePlanarConfiguration.h"
#include "gdcmImageChangeTransferSyntax.h"
#include "gdcmImageHelper.h"
#include "gdcmImageReader.h"
#include "gdcmImageWriter.h"
#include "gdcmMediaStorage.h"
#include "gdcmReader.h"
#include "gdcmRescaler.h"
#include "gdcmStringFilter.h"
#include "gdcmUIDGenerator.h"
#include "itkConstantPadImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkAddImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkDenseFrequencyContainer2.h"
#include "itkHistogramToTextureFeaturesFilter.h"
#include "itkMultiplyImageFilter.h"
#include "itkRegionOfInterestImageFilter.h"
#include "itkScalarImageToCooccurrenceMatrixFilter.h"
#include "itkGDCMImageIO.h"
#include "itkMetaDataDictionary.h"
#include "json.hpp"
#include "metaCommand.h"
#include <boost/algorithm/string.hpp>
#include <boost/date_time.hpp>
#include <boost/filesystem.hpp>
#include <codecvt>
#include <locale> // wstring_convert
#include <map>
#include "mytypes.h"
#include "report.h"
using json = nlohmann::json;
using namespace boost::filesystem;
json resultJSON;
// We need to identify for each series if they are a presentation state object and if we can extract some
// contours from them.
struct Polygon {
std::vector<float> coords; // the vector of pixel coordinates extracted from presentation state
std::string ReferencedSOPInstanceUID; // the referenced SOP instance UID (identifies the image)
std::string ReferencedSeriesInstanceUID;
std::string StudyInstanceUID;
std::string SeriesInstanceUID;
std::string UnformattedTextValue;
std::string Filename; // the name of the DICOM file
std::string PatientName;
std::string PatientID;
std::string ContributionDateTime; // 0018,a002 (when the PR object was list updated)
};
using ImageType2D = itk::Image<PixelType, 2>;
void writeSecondaryCapture(ImageType2D::Pointer maskFromPolys, std::string filename, std::string p_out, bool uidFixedFlag,
std::string newFusedSeriesInstanceUID, std::string newFusedSOPInstanceUID, bool verbose, float lowerT, float upperT) {
typedef itk::ImageFileReader<ImageType2D> ReaderType;
ReaderType::Pointer r = ReaderType::New();
r->SetFileName(filename);
typedef itk::GDCMImageIO ImageIOType;
ImageIOType::Pointer gdcmImageIO = ImageIOType::New();
r->SetImageIO(gdcmImageIO);
try {
r->Update();
} catch (itk::ExceptionObject &e) {
std::cerr << "exception in file reader " << std::endl;
std::cerr << e.GetDescription() << std::endl;
std::cerr << e.GetLocation() << std::endl;
return;
}
itk::MetaDataDictionary &dictionarySlice = r->GetOutput()->GetMetaDataDictionary();
std::string SeriesNumber("");
std::string studyID("");
std::string AcquisitionNumber("");
std::string InstanceNumber("");
std::string frameOfReferenceUID("");
itk::ExposeMetaData<std::string>(dictionarySlice, "0020|000d", studyID);
itk::ExposeMetaData<std::string>(dictionarySlice, "0020|0011", SeriesNumber);
itk::ExposeMetaData<std::string>(dictionarySlice, "0020|0012", AcquisitionNumber);
itk::ExposeMetaData<std::string>(dictionarySlice, "0020|0013", InstanceNumber); // keep that number
itk::ExposeMetaData<std::string>(dictionarySlice, "0020|0052", frameOfReferenceUID);
int newSeriesNumber = atoi(SeriesNumber.c_str()) + 1003;
ImageType2D::Pointer im2change = r->GetOutput();
ImageType2D::RegionType region;
region = im2change->GetBufferedRegion();
ImageType2D::SizeType size = region.GetSize();
ImageType2D::PixelContainer *container;
container = im2change->GetPixelContainer();
container->SetContainerManageMemory(false);
// unsigned int bla = sizeof(InputImageType::PixelType);
ImageType2D::PixelType *buffer2 = container->GetBufferPointer();
gdcm::PixelFormat pf = gdcm::PixelFormat::UINT8;
pf.SetSamplesPerPixel(3);
gdcm::SmartPointer<gdcm::Image> simage = new gdcm::Image;
gdcm::Image &image = *simage;
image.SetNumberOfDimensions(2);
// typedef itk::Image<PixelType, 2> ImageType2D;
ImageType2D::RegionType inRegion = im2change->GetLargestPossibleRegion();
image.SetDimension(0, static_cast<unsigned int>(inRegion.GetSize()[0]));
image.SetDimension(1, static_cast<unsigned int>(inRegion.GetSize()[1]));
// image.SetDimension(2, m_Dimensions[2] );
image.SetSpacing(0, im2change->GetSpacing()[0]);
image.SetSpacing(1, im2change->GetSpacing()[1]);
image.SetPixelFormat(pf);
gdcm::PhotometricInterpretation pi = gdcm::PhotometricInterpretation::RGB;
image.SetPhotometricInterpretation(pi);
image.SetTransferSyntax(gdcm::TransferSyntax::ExplicitVRLittleEndian);
// copy the DICOM tags over from inputImage to image
gdcm::DataElement pixeldata(gdcm::Tag(0x7fe0, 0x0010));
// create a fused volume using im2change and maskFromPolys
using CPixelType = itk::RGBPixel<unsigned char>;
using CImageType = itk::Image<CPixelType, 2>;
using CWriterType = itk::ImageFileWriter<CImageType>;
CImageType::Pointer fused = CImageType::New();
CImageType::RegionType fusedRegion = im2change->GetLargestPossibleRegion();
fused->SetRegions(fusedRegion);
fused->Allocate();
fused->FillBuffer(itk::NumericTraits<CPixelType>::Zero);
fused->SetOrigin(im2change->GetOrigin());
fused->SetSpacing(im2change->GetSpacing());
fused->SetDirection(im2change->GetDirection());
itk::ImageRegionIterator<ImageType2D> fusedLabelIterator(maskFromPolys, fusedRegion);
itk::ImageRegionIterator<ImageType2D> inputIterator(im2change, fusedRegion);
itk::ImageRegionIterator<CImageType> fusedIterator(fused, fusedRegion);
using ImageCalculatorFilterType = itk::MinimumMaximumImageCalculator<ImageType2D>;
ImageCalculatorFilterType::Pointer imageCalculatorFilter = ImageCalculatorFilterType::New();
imageCalculatorFilter->SetImage(im2change);
imageCalculatorFilter->Compute();
int minGray = imageCalculatorFilter->GetMinimum();
int maxGray = imageCalculatorFilter->GetMaximum();
// what are good contrast and brightness values?
// compute a histogram first
using HistogramGeneratorType = itk::Statistics::ScalarImageToHistogramGenerator<ImageType2D>;
HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New();
histogramGenerator->SetInput(im2change);
int histogramSize = 1024;
histogramGenerator->SetNumberOfBins(histogramSize);
histogramGenerator->SetHistogramMin(minGray);
histogramGenerator->SetHistogramMax(maxGray);
histogramGenerator->Compute();
using HistogramType = HistogramGeneratorType::HistogramType;
const HistogramType *histogram = histogramGenerator->GetOutput();
// defined in calling function
//double lowerT = 0.01;
//double upperT = 0.999;
double t1 = -1;
double t2 = -1;
double sum = 0;
double total = 0;
for (unsigned int bin = 0; bin < histogramSize; bin++) {
total += histogram->GetFrequency(bin, 0);
}
for (unsigned int bin = 0; bin < histogramSize; bin++) {
double f = histogram->GetFrequency(bin, 0) / total;
// fprintf(stdout, "bin %d, value is %f\n", bin, f);
sum += f;
if (t1 == -1 && sum > lowerT) {
t1 = minGray + (maxGray - minGray) * (bin / (float)histogramSize);
}
if (t2 == -1 && sum > upperT) {
t2 = minGray + (maxGray - minGray) * (bin / (float)histogramSize);
break;
}
}
if (verbose) {
fprintf(stdout, "CumSum threshold [%.2f, %.2f]\n", t1, t2);
}
std::vector<std::vector<float>> labelColors = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
// do this in two steps, first compute three label color channels, smooth them and alpha-blend last
typedef float FPixelType;
// typedef itk::Image<FPixelType, 2> FloatImageType;
using FloatImageType = itk::Image<FPixelType, 2>;
FloatImageType::Pointer red_channel = FloatImageType::New();
FloatImageType::Pointer green_channel = FloatImageType::New();
FloatImageType::Pointer blue_channel = FloatImageType::New();
fusedRegion = im2change->GetLargestPossibleRegion();
red_channel->SetRegions(fusedRegion);
red_channel->Allocate();
red_channel->FillBuffer(itk::NumericTraits<FPixelType>::Zero);
red_channel->SetOrigin(im2change->GetOrigin());
red_channel->SetSpacing(im2change->GetSpacing());
red_channel->SetDirection(im2change->GetDirection());
green_channel->SetRegions(fusedRegion);
green_channel->Allocate();
green_channel->FillBuffer(itk::NumericTraits<FPixelType>::Zero);
green_channel->SetOrigin(im2change->GetOrigin());
green_channel->SetSpacing(im2change->GetSpacing());
green_channel->SetDirection(im2change->GetDirection());
blue_channel->SetRegions(fusedRegion);
blue_channel->Allocate();
blue_channel->FillBuffer(itk::NumericTraits<FPixelType>::Zero);
blue_channel->SetOrigin(im2change->GetOrigin());
blue_channel->SetSpacing(im2change->GetSpacing());
blue_channel->SetDirection(im2change->GetDirection());
itk::ImageRegionIterator<FloatImageType> redIterator(red_channel, fusedRegion);
itk::ImageRegionIterator<FloatImageType> greenIterator(green_channel, fusedRegion);
itk::ImageRegionIterator<FloatImageType> blueIterator(blue_channel, fusedRegion);
fusedLabelIterator.GoToBegin();
redIterator.GoToBegin();
greenIterator.GoToBegin();
blueIterator.GoToBegin();
while (!fusedLabelIterator.IsAtEnd() && !redIterator.IsAtEnd() && !greenIterator.IsAtEnd() && !blueIterator.IsAtEnd()) {
// this will crash with many labels (more than in our const array)
redIterator.Set(labelColors[fusedLabelIterator.Get()][0]); // values are 0..1
greenIterator.Set(labelColors[fusedLabelIterator.Get()][1]);
blueIterator.Set(labelColors[fusedLabelIterator.Get()][2]);
++redIterator;
++greenIterator;
++blueIterator;
++fusedLabelIterator;
}
// now smooth with Gaussian (each channel independently)
using GFilterType = itk::DiscreteGaussianImageFilter<FloatImageType, FloatImageType>;
auto gaussFilterR = GFilterType::New();
gaussFilterR->SetInput(red_channel);
// gaussFilterR->SetMaximumKernelWidth(3);
gaussFilterR->SetVariance(1.5f);
gaussFilterR->Update();
FloatImageType::Pointer smoothRed = gaussFilterR->GetOutput();
auto gaussFilterG = GFilterType::New();
gaussFilterG->SetInput(green_channel);
// gaussFilterG->SetMaximumKernelWidth(3);
gaussFilterG->SetVariance(1.5f);
gaussFilterG->Update();
FloatImageType::Pointer smoothGreen = gaussFilterG->GetOutput();
auto gaussFilterB = GFilterType::New();
gaussFilterB->SetInput(blue_channel);
// gaussFilterB->SetMaximumKernelWidth(3);
gaussFilterB->SetVariance(1.5f);
gaussFilterB->Update();
FloatImageType::Pointer smoothBlue = gaussFilterB->GetOutput();
itk::ImageRegionIterator<FloatImageType> redSIterator(smoothRed, fusedRegion);
itk::ImageRegionIterator<FloatImageType> greenSIterator(smoothGreen, fusedRegion);
itk::ImageRegionIterator<FloatImageType> blueSIterator(smoothBlue, fusedRegion);
// now use the smaoothed color channels (clamp them between 0 and 1)
inputIterator.GoToBegin();
fusedIterator.GoToBegin();
redSIterator.GoToBegin();
greenSIterator.GoToBegin();
blueSIterator.GoToBegin();
float f = 0.7;
float red, green, blue;
while (!inputIterator.IsAtEnd() && !fusedIterator.IsAtEnd() && !redSIterator.IsAtEnd() && !greenSIterator.IsAtEnd() && !blueSIterator.IsAtEnd()) {
float scaledP = ((float) inputIterator.Get() - t1) / (t2 - t1);
CPixelType value = fusedIterator.Value();
red = redSIterator.Get();
green = greenSIterator.Get();
blue = blueSIterator.Get();
// alpha blend
red = f * scaledP + red * (1 - f);
green = f * scaledP + green * (1 - f);
blue = f * scaledP + blue * (1 - f);
red = std::min<float>(1, std::max<float>(0, red));
green = std::min<float>(1, std::max<float>(0, green));
blue = std::min<float>(1, std::max<float>(0, blue));
value.SetRed((int)(red * 255));
value.SetGreen((int)(green * 255));
value.SetBlue((int)(blue * 255));
fusedIterator.Set(value);
++inputIterator;
++fusedIterator;
++redSIterator;
++greenSIterator;
++blueSIterator;
}
//float f = 0.6;
/*float alphaB = 0.75;
fusedLabelIterator.GoToBegin();
fusedIterator.GoToBegin();
inputIterator.GoToBegin();
while (!fusedLabelIterator.IsAtEnd() && !fusedIterator.IsAtEnd() && !inputIterator.IsAtEnd()) {
// is this a copy of do we really write the color here?
CPixelType value = fusedIterator.Value();
float scaledP = (inputIterator.Get() - t1) / (t2 - t1);
float red = scaledP;
float blue = scaledP;
float green = scaledP;
// if (fusedLabelIterator.Get() > 0) {
red = f * scaledP + labelColors[fusedLabelIterator.Get()][0] * alphaB * (1 - f);
green = f * scaledP + labelColors[fusedLabelIterator.Get()][1] * alphaB * (1 - f);
blue = f * scaledP + labelColors[fusedLabelIterator.Get()][2] * alphaB * (1 - f);
//}
red = std::min<float>(1, std::max<float>(0, red));
green = std::min<float>(1, std::max<float>(0, green));
blue = std::min<float>(1, std::max<float>(0, blue));
// fprintf(stdout, "red: %f, green: %f, blue: %f\n", red, green, blue);
value.SetRed((int)(red * 255));
value.SetGreen((int)(green * 255));
value.SetBlue((int)(blue * 255));
fusedIterator.Set(value);
++fusedIterator;
++fusedLabelIterator;
++inputIterator;
} */
// now change the DICOM tags for the series and save it again
// itk::MetaDataDictionary &dictionarySlice = r->GetOutput()->GetMetaDataDictionary();
itk::EncapsulateMetaData<std::string>(dictionarySlice, "0020|000d", studyID);
// itk::EncapsulateMetaData<std::string>(dictionarySlice, "0020|000E", newFusedSeriesInstanceUID); // provided in call to this function
itk::EncapsulateMetaData<std::string>(dictionarySlice, "0020|0011", std::to_string(newSeriesNumber));
itk::EncapsulateMetaData<std::string>(dictionarySlice, "0020|0012", AcquisitionNumber);
itk::EncapsulateMetaData<std::string>(dictionarySlice, "0020|0013", InstanceNumber);
itk::EncapsulateMetaData<std::string>(dictionarySlice, "0020|0052", frameOfReferenceUID); // apply
itk::EncapsulateMetaData<std::string>(dictionarySlice, "0008|0018", newFusedSOPInstanceUID);
// get Pixel buffer from fused
CImageType::Pointer fusedNImage = fused;
CImageType::PixelContainer *container22 = fusedNImage->GetPixelContainer();
CImageType::PixelType *buffer22 = container22->GetBufferPointer();
// now copy all the DICOM tags over
using DictionaryType = itk::MetaDataDictionary;
const DictionaryType &dictionaryIn = gdcmImageIO->GetMetaDataDictionary();
using MetaDataStringType = itk::MetaDataObject<std::string>;
auto itr = dictionaryIn.Begin();
auto end = dictionaryIn.End();
std::string imagePositionPatient; // we might be able to get them this way, but can we set them?
itk::ExposeMetaData<std::string>(dictionarySlice, "0020|0032", imagePositionPatient);
// perhaps we have to use the parsed values to write them again further down?
double origin3D[3];
sscanf(imagePositionPatient.c_str(), "%lf\\%lf\\%lf", &(origin3D[0]), &(origin3D[1]), &(origin3D[2]));
// fprintf(stdout, "image position patient field: %lf, %lf, %lf\n", origin3D[0], origin3D[1], origin3D[2]);
std::string imageOrientation;
itk::ExposeMetaData<std::string>(dictionarySlice, "0020|0037", imageOrientation);
double imageOrientationField[6];
sscanf(imageOrientation.c_str(), "%lf\\%lf\\%lf\\%lf\\%lf\\%lf", &(imageOrientationField[0]), &(imageOrientationField[1]), &(imageOrientationField[2]),
&(imageOrientationField[3]), &(imageOrientationField[4]), &(imageOrientationField[5]));
// fprintf(stdout, "image orientation field: %lf, %lf, %lf, %lf, %lf, %lf\n", imageOrientationField[0], imageOrientationField[1],
// imageOrientationField[2], imageOrientationField[3], imageOrientationField[4], imageOrientationField[5]);
std::string sliceThicknessString;
double sliceThickness = 0.0;
itk::ExposeMetaData<std::string>(dictionarySlice, "0018|0050", sliceThicknessString);
sscanf(sliceThicknessString.c_str(), "%lf", &sliceThickness);
std::string imageInstanceString;
int imageInstance = 0;
itk::ExposeMetaData<std::string>(dictionarySlice, "0020|0013", imageInstanceString);
sscanf(imageInstanceString.c_str(), "%d", &imageInstance);
// fprintf(stdout, "FOUND INSTANCE: %d\n", imageInstance); // start counting with 0 when we use this value to pick the slice
std::string sliceLocationString;
float sliceLocation = 0.0f;
itk::ExposeMetaData<std::string>(dictionarySlice, "0020|1041", sliceLocationString);
sscanf(sliceLocationString.c_str(), "%f", &sliceLocation);
std::string imageAcquisitionString;
int acquisitionNumber = 0;
itk::ExposeMetaData<std::string>(dictionarySlice, "0020|0012", imageAcquisitionString);
sscanf(imageAcquisitionString.c_str(), "%d", &acquisitionNumber);
// go into slice by applying offset
// here the problem is that slices can be in a different order from the number in sliceNames
// we should therefore use an i that corresponds to the image instance number - not the slice name
// sort order
uint32_t len = inRegion.GetSize()[0] * inRegion.GetSize()[1] * 3 * sizeof(unsigned char);
pixeldata.SetByteValue((char *)(((unsigned char *)buffer22)), len);
image.SetDataElement(pixeldata);
// create an image (see
// http://gdcm.sourceforge.net/html/GenFakeImage_8cxx-example.html#_a1)
gdcm::SmartPointer<gdcm::File> file = new gdcm::File; // empty file
gdcm::FileDerivation fd;
const char ReferencedSOPClassUID[] = "1.2.840.10008.5.1.4.1.1.7"; // Secondary Capture
// create a new frameOfRefenceUID
gdcm::UIDGenerator fuid;
fuid.SetRoot("1.3.6.1.4.1.45037");
// do we need a new one here? - only if we don't find one from before
if (frameOfReferenceUID == "")
frameOfReferenceUID = fuid.Generate();
fd.AddReference(ReferencedSOPClassUID, frameOfReferenceUID.c_str());
fd.SetPurposeOfReferenceCodeSequenceCodeValue(
121324); // segmentation (see
// https://github.com/malaterre/GDCM/blob/master/Source/MediaStorageAndFileFormat/gdcmFileDerivation.cxx)
// CID 7203 Image Derivation
// { "DCM",113072,"Multiplanar reformatting" },
fd.SetDerivationCodeSequenceCodeValue(113076);
fd.SetFile(*file);
// If all Code Value are ok the filter will execute properly
if (!fd.Derive()) {
std::cerr << "Sorry could not derive using input info" << std::endl;
return;
}
gdcm::DataSet &ds = fd.GetFile().GetDataSet();
gdcm::Anonymizer ano;
ano.SetFile(fd.GetFile());
std::string seriesDescription;
int seriesNumber;
while (itr != end) {
itk::MetaDataObjectBase::Pointer entry = itr->second;
MetaDataStringType::Pointer entryvalue = dynamic_cast<MetaDataStringType *>(entry.GetPointer());
if (entryvalue) {
std::string tagkey = itr->first;
std::string labelId;
bool found = itk::GDCMImageIO::GetLabelFromTag(tagkey, labelId);
std::string tagvalue = entryvalue->GetMetaDataObjectValue();
if (strcmp(tagkey.c_str(), "0008|103e") == 0) {
seriesDescription = tagvalue;
}
if (strcmp(tagkey.c_str(), "0020|0011") == 0) {
seriesNumber = atoi(tagvalue.c_str());
}
// if (strcmp(tagkey.c_str(), "0020|1041") == 0) {
// // don't overwrite the slice position
// ++itr;
// continue;
// }
// change window level from -400..600 to 150..180 (why don't we use the computed values? or 0 and 255?)
if (strcmp(tagkey.c_str(), "0028|1050") == 0) {
tagvalue = std::string("150");
}
if (strcmp(tagkey.c_str(), "0028|1051") == 0) {
tagvalue = std::string("260");
}
unsigned int f1;
unsigned int f2;
sscanf(tagkey.c_str(), "%x|%x", &f1, &f2);
ano.Replace(gdcm::Tag(f1, f2), tagvalue.c_str());
}
++itr;
}
gdcm::Attribute<0x0008, 0x2111> at1; // Derivative Description
at1.SetValue("Fused Segmentation");
ds.Replace(at1.GetAsDataElement());
gdcm::Attribute<0x0008, 0x0060> at2; // Derivative Description
at2.SetValue("MR");
ds.Replace(at2.GetAsDataElement());
gdcm::Attribute<0x0020, 0x000E> at3;
at3.SetValue(newFusedSeriesInstanceUID);
ds.Replace(at3.GetAsDataElement());
gdcm::Attribute<0x0008, 0x103E> at4;
std::string extension = " (fused segmentation)";
std::ostringstream value;
value.str("");
value << seriesDescription;
// This is a long string and there is a 64 character limit in the
// standard
unsigned lengthDesc = value.str().length();
std::string seriesDesc(value.str(), 0, lengthDesc + extension.length() > 64 ? 64 - extension.length() : lengthDesc + extension.length());
// itk::EncapsulateMetaData<std::string>(dictionary, "0008|103e", seriesDesc + extension);
at4.SetValue(seriesDesc + extension);
ds.Replace(at4.GetAsDataElement());
// seriesInstance
gdcm::Attribute<0x0020, 0x0011> at5;
at5.SetValue(1000 + seriesNumber + 3);
ds.Replace(at5.GetAsDataElement());
// use a unique SOPInstanceUID
gdcm::Attribute<0x0008, 0x0018> at6;
at6.SetValue(newFusedSOPInstanceUID);
ds.Replace(at6.GetAsDataElement());
gdcm::Attribute<0x0008, 0x0008> at_image_type;
static const gdcm::CSComp values[] = {"DERIVED","SECONDARY"};
at_image_type.SetValues( values, 2, true ); // true => copy data !
if ( ds.FindDataElement( at_image_type.GetTag() ) ) {
const gdcm::DataElement &de = ds.GetDataElement( at_image_type.GetTag() );
//at_image_type.SetFromDataElement( de );
// Make sure that value #1 is at least 'DERIVED', so override in all cases:
at_image_type.SetValue( 0, values[0] );
at_image_type.SetValue( 1, values[1] );
}
ds.Replace( at_image_type.GetAsDataElement() );
// image position patient from input
// These values are actually not getting written to the files (RGB has no origin, values are 0\0\0, but see set origin further down)
gdcm::Attribute<0x0020, 0x0032> at7;
at7.SetValue(origin3D[0], 0);
at7.SetValue(origin3D[1], 1);
at7.SetValue(origin3D[2], 2);
ds.Replace(at7.GetAsDataElement());
std::ostringstream value2;
value2.str("");
at7.Print(value2);
// fprintf(stdout, "origin is now supposed to be: %lf\\%lf\\%lf %s\n", origin3D[0], origin3D[1], origin3D[2], value2.str().c_str());
// For RGB we can set this to make sure they show up at the right location in Horos/OsiriX
image.SetOrigin(0, origin3D[0]);
image.SetOrigin(1, origin3D[1]);
image.SetOrigin(2, origin3D[2]);
gdcm::Attribute<0x0018, 0x0050> at8;
at8.SetValue(sliceThickness);
ds.Replace(at8.GetAsDataElement());
gdcm::Attribute<0x0020, 0x0037> at9;
at9.SetValue(imageOrientationField[0], 0);
at9.SetValue(imageOrientationField[1], 1);
at9.SetValue(imageOrientationField[2], 2);
at9.SetValue(imageOrientationField[3], 3);
at9.SetValue(imageOrientationField[4], 4);
at9.SetValue(imageOrientationField[5], 5);
ds.Replace(at9.GetAsDataElement());
// gdcm::Attribute<0x0020, 0x0013> at10;
// at10.SetValue(imageInstance);
// ds.Replace(at10.GetAsDataElement());
gdcm::Attribute<0x0020, 0x1041> at11;
at11.SetValue(sliceLocation);
ds.Replace(at11.GetAsDataElement());
gdcm::Attribute<0x0020, 0x0012> at12;
at12.SetValue(1000 + acquisitionNumber + 3);
ds.Replace(at12.GetAsDataElement());
gdcm::Attribute<0x0020, 0x0013> at13;
at13.SetValue(imageInstance); // count starts at 1 and increments for all slices
ds.Replace(at13.GetAsDataElement());
gdcm::Attribute<0x0020, 0x0052> at14;
at14.SetValue(frameOfReferenceUID.c_str());
ds.Replace(at14.GetAsDataElement());
gdcm::Attribute<0x0020, 0x000e> at15;
at15.SetValue(newFusedSeriesInstanceUID);
ds.Replace(at15.GetAsDataElement());
gdcm::ImageWriter writer;
writer.SetImage(image);
writer.SetFile(fd.GetFile());
// std::ostringstream o;
// o << outputSeries << "/dicom" << i << ".dcm";
writer.SetFileName(p_out.c_str());
if (!writer.Write()) {
return;
}
return;
}
// remove all polygons for a series that are old, based on ContributionDateTime
void keepOnlyLast(std::vector<Polygon> *storage) {
// keep a list of all SeriesInstanceUIDs and their newest ContributionDateTime
std::map<std::string, std::string> seriesByContributionDateTime;
for (int i = 0; i < storage->size(); i++) {
std::string ReferencedSeriesInstanceUID = (*storage)[i].ReferencedSeriesInstanceUID;
std::string d = (*storage)[i].ContributionDateTime;
if (auto p = seriesByContributionDateTime.find(ReferencedSeriesInstanceUID); p == seriesByContributionDateTime.end()) {
seriesByContributionDateTime.insert(std::pair<std::string, std::string>{ReferencedSeriesInstanceUID,d});
} else {
// already in there, is our date newer?
std::string d_in_there = p->second;
if (d > d_in_there) {
// we found a newer date (larger string), use that date for this ReferencedSeriesInstanceUID
seriesByContributionDateTime[p->first] = d;
}
}
}
// now remove all non-matching storage entries
std::vector<Polygon>::iterator iter;
for (iter = storage->begin(); iter != storage->end();) {
std::string ReferencedSeriesInstanceUID = iter->ReferencedSeriesInstanceUID;
std::string ContributionDateTime = iter->ContributionDateTime;
if (auto p = seriesByContributionDateTime.find(ReferencedSeriesInstanceUID); p != seriesByContributionDateTime.end()) {
std::string d = p->second;
if (d != ContributionDateTime) {
// must be an old entry, delete it now
iter = storage->erase(iter);
continue;
}
}
++iter;
}
}
bool invalidChar(char c) { return !isprint(static_cast<unsigned char>(c)); }
void stripUnicode(std::string &str) { str.erase(remove_if(str.begin(), str.end(), invalidChar), str.end()); }
bool parseForPolygons(std::string input, std::vector<Polygon> *storage, std::map<std::string, std::string> *SOPInstanceUID2SeriesInstanceUID, bool verbose) {
// read from input and create polygon structs in storage
// a local cache of the Series that might be referenced
for (boost::filesystem::recursive_directory_iterator end, dir(input); dir != end; ++dir) {
// std::cout << *dir << "\n"; // full path
// std::cout << dir->path().filename() << "\n"; // just last bit
std::string filename = dir->path().string();
// this could be a folder ... don't try to read folders as files
if (boost::filesystem::is_directory(dir->path())) {
continue; // ignore
}
// filter out some files that we expect but that are not DICOM
boost::filesystem::path p(filename);
if (p.extension() == ".json") {
continue; // ignore this file
}
// Instantiate the reader:
gdcm::Reader reader;
reader.SetFileName(filename.c_str());
if (!reader.Read()) {
if (verbose) {
std::cerr << "Could not read \"" << filename << "\" as DICOM, ignore." << std::endl;
}
continue;
}
// The output of gdcm::Reader is a gdcm::File
gdcm::File &file = reader.GetFile();
// the dataset is the the set of element we are interested in:
gdcm::DataSet &ds = file.GetDataSet();
// is this Modality PR?
std::string SeriesInstanceUID;
std::string StudyInstanceUID;
std::string SOPInstanceUID;
std::string Modality;
std::string PatientID;
std::string PatientName;
std::string ContributionDateTime;
const gdcm::Tag graphicType(0x0070, 0x0023); // GraphicType
const gdcm::Tag numberOfGraphicPoints(0x0070, 0x0021); // NumberOfGraphicPoints
const gdcm::Tag graphicData(0x0070, 0x0022); // GraphicData - n-tupel of Single
const gdcm::Tag graphicObjectSequence(0x0070, 0x0009); // GraphicObjectSequence
const gdcm::Tag textObjectSequence(0x0070, 0x0008); // TextObjectSequence
const gdcm::Tag unformattedTextValue(0x0070, 0x0006); // unformattedTextValue
const gdcm::Tag referencedImageSequence(0x0008, 0x1140); // ReferencedImageSequence its inside 0x0070,0x0001
const gdcm::Tag referencedSOPInstanceUID(0x0008, 0x1155); // ReferencedSOPInstanceUID
const gdcm::Tag contributionDateTime(0x0018, 0xA002); // ContributionDateTime
gdcm::Attribute<0x0008, 0x0060> modalityAttr;
modalityAttr.Set(ds);
if (std::string(modalityAttr.GetValue()) != std::string("PR")) { // PR's might reference these
// we should create a cache here for the SeriesInstanceUID the ReferencedSOPInstanceUID might point to
gdcm::Attribute<0x0020, 0x000E> seriesinstanceuidAttr;
seriesinstanceuidAttr.Set(ds);
SeriesInstanceUID = seriesinstanceuidAttr.GetValue();
if (SeriesInstanceUID.back() == '\0')
SeriesInstanceUID.replace(SeriesInstanceUID.end() - 1, SeriesInstanceUID.end(), "");
gdcm::Attribute<0x0008, 0x0018> sopInstanceUIDAttr;
sopInstanceUIDAttr.Set(ds);
SOPInstanceUID = sopInstanceUIDAttr.GetValue();
if (SOPInstanceUID.back() == '\0')
SOPInstanceUID.replace(SOPInstanceUID.end() - 1, SOPInstanceUID.end(), "");
// fprintf(stdout, " add to cache %s -> %s\n", SOPInstanceUID.c_str(), SeriesInstanceUID.c_str());
SOPInstanceUID2SeriesInstanceUID->insert(std::pair<std::string, std::string>(SOPInstanceUID, SeriesInstanceUID));
continue;
}
// get the PatientID and PatientName
gdcm::Attribute<0x0010, 0x0020> patientIDAttr;
patientIDAttr.Set(ds);
PatientID = patientIDAttr.GetValue();
gdcm::Attribute<0x0010, 0x0010> patientNameAttr;
patientNameAttr.Set(ds);
PatientName = patientNameAttr.GetValue();
// get the StudyInstanceUID
gdcm::Attribute<0x0020, 0x000D> studyinstanceuidAttr;
studyinstanceuidAttr.Set(ds);
StudyInstanceUID = studyinstanceuidAttr.GetValue();
// fprintf(stdout, " found StudyInstanceUID: %s\n", StudyInstanceUID.c_str());
// get the ContributionDateTime for Sectra from sequence 0018,a001 item 0040,a170
// (0018,a001) SQ (Sequence with explicit length #=1) # 148, 1 Unknown Tag & Data
// (fffe,e000) na (Item with explicit length #=5) # 140, 1 Item
// (0008,0070) LO [SECTRA] # 6, 1 Unknown Tag & Data
// (0008,0080) LO [-] # 2, 1 Unknown Tag & Data
// (0008,1010) SH [DICOM_QR_SCP] # 12, 1 Unknown Tag & Data
// (0018,a002) DT [20240314170104] # 14, 1 Unknown Tag & Data
// (0040,a170) SQ (Sequence with explicit length #=1) # 62, 1 Unknown Tag & Data
// (fffe,e000) na (Item with explicit length #=3) # 54, 1 Item
// (0008,0100) SH [109103] # 6, 1 Unknown Tag & Data
// (0008,0102) SH [DCM] # 4, 1 Unknown Tag & Data
// (0008,0104) LO [Modifying Equipment] # 20, 1 Unknown Tag & Data
// (fffe,e00d) na (ItemDelimitationItem for re-encoding) # 0, 0 ItemDelimitationItem
// (fffe,e0dd) na (SequenceDelimitationItem for re-encod.) # 0, 0 SequenceDelimitationItem
// (fffe,e00d) na (ItemDelimitationItem for re-encoding) # 0, 0 ItemDelimitationItem
//(fffe,e0dd) na (SequenceDelimitationItem for re-encod.) # 0, 0 SequenceDelimitationItem
const gdcm::DataElement &de_sectra = ds.GetDataElement(gdcm::Tag(0x0018, 0xA001));
// SequenceOfItems * sqi = (SequenceOfItems*)de.GetSequenceOfItems();
gdcm::SmartPointer<gdcm::SequenceOfItems> sqi2 = de_sectra.GetValueAsSQ();
if (sqi2) {
gdcm::SequenceOfItems::SizeType nitems = sqi2->GetNumberOfItems();
// fprintf(stdout, "found %lu items\n", nitems);
for (int itemNr = 1; itemNr <= nitems; itemNr++) { // we should create our polys at this level....
gdcm::Item &item = sqi2->GetItem(itemNr);
gdcm::DataSet &subds = item.GetNestedDataSet();
gdcm::Attribute<0x0018, 0xA002> contributionDateTimeAttr;
contributionDateTimeAttr.Set(subds);
ContributionDateTime = contributionDateTimeAttr.GetValue();
}
}
// get the StudyInstanceUID
gdcm::Attribute<0x0020, 0x000E> seriesinstanceuidAttr;
seriesinstanceuidAttr.Set(ds);
SeriesInstanceUID = seriesinstanceuidAttr.GetValue();
if (verbose) {
fprintf(stdout, " \033[0;32mfound\033[0m SeriesInstanceUID [%s]: \033[0;33m%s\033[0m\n", modalityAttr.GetValue().c_str(), SeriesInstanceUID.c_str());
}
const gdcm::DataElement &de = ds.GetDataElement(gdcm::Tag(0x0070, 0x0001));
// SequenceOfItems * sqi = (SequenceOfItems*)de.GetSequenceOfItems();
gdcm::SmartPointer<gdcm::SequenceOfItems> sqi = de.GetValueAsSQ();
if (sqi) {
/* (0070,0009) SQ (Sequence with explicit length #=1) # 180, 1 GraphicObjectSequence
(fffe,e000) na (Item with explicit length #=6) # 172, 1 Item
(0070,0005) CS [PIXEL] # 6, 1 GraphicAnnotationUnits
(0070,0020) US 2 # 2, 1 GraphicDimensions
(0070,0021) US 13 # 2, 1 NumberOfGraphicPoints
(0070,0022) FL 92\113\99\129\110\142\132\146\153\135\164\118\172\98\162\75\132\67... # 104,26 GraphicData
(0070,0023) CS [POLYLINE] # 8, 1 GraphicType
(0070,0024) CS [N] # 2, 1 GraphicFilled
(fffe,e00d) na (ItemDelimitationItem for re-encoding) # 0, 0 ItemDelimitationItem
(fffe,e0dd) na (SequenceDelimitationItem for re-encod.) # 0, 0 SequenceDelimitationItem
*/
gdcm::SequenceOfItems::SizeType nitems = sqi->GetNumberOfItems();
// fprintf(stdout, "found %lu items\n", nitems);
for (int itemNr = 1; itemNr <= nitems; itemNr++) { // we should create our polys at this level....
Polygon poly;
poly.StudyInstanceUID = boost::algorithm::trim_copy(StudyInstanceUID);
poly.ContributionDateTime = boost::algorithm::trim_copy(ContributionDateTime);
// the string above might contain a utf-8 version of a null character
if (poly.StudyInstanceUID.back() == '\0')
poly.StudyInstanceUID.replace(poly.StudyInstanceUID.end() - 1, poly.StudyInstanceUID.end(), "");
poly.SeriesInstanceUID = boost::algorithm::trim_copy(SeriesInstanceUID);
// the string above might contain a utf-8 version of a null character
if (poly.SeriesInstanceUID.back() == '\0')
poly.SeriesInstanceUID.replace(poly.SeriesInstanceUID.end() - 1, poly.SeriesInstanceUID.end(), "");
poly.Filename = filename;
poly.PatientID = PatientID;
if (poly.StudyInstanceUID.back() == '\0')
poly.PatientID.replace(poly.PatientID.end() - 1, poly.PatientID.end(), "");
poly.PatientName = PatientName;
if (poly.PatientName.back() == '\0')
poly.PatientName.replace(poly.PatientName.end() - 1, poly.PatientName.end(), "");
gdcm::Item &item = sqi->GetItem(itemNr);
gdcm::DataSet &subds = item.GetNestedDataSet();
// lookup the ReferencedImageSequence
/* (0008,1140) SQ (Sequence with explicit length #=1) # 114, 1 ReferencedImageSequence
(fffe,e000) na (Item with explicit length #=2) # 106, 1 Item
(0008,1150) UI =MRImageStorage # 26, 1 ReferencedSOPClassUID
(0008,1155) UI [1.3.6.1.4.1.45037.091a6b29babb817c5ffcc7199d0c0de4cf9d52c155360] # 64, 1 ReferencedSOPInstanceUID
(fffe,e00d) na (ItemDelimitationItem for re-encoding) # 0, 0 ItemDelimitationItem
(fffe,e0dd) na (SequenceDelimitationItem for re-encod.) # 0, 0 SequenceDelimitationItem
*/
if (!subds.FindDataElement(referencedImageSequence)) {
if (verbose)
fprintf(stdout, " %d does not have a referenced image sequence\n", itemNr);
continue;
} else {
if (verbose)
fprintf(stdout, " [item %d] \033[0;32mfound\033[0m a ReferencedImageSequence\n", itemNr);
}
const gdcm::DataElement &de3 = subds.GetDataElement(referencedImageSequence);
gdcm::SmartPointer<gdcm::SequenceOfItems> sqiReferencedImageSequence = de3.GetValueAsSQ();
gdcm::SequenceOfItems::SizeType nitems3 = sqiReferencedImageSequence->GetNumberOfItems();
// fprintf(stdout, " referenced image sequence with %lu item(-s)\n", nitems3);
for (int itemNr2 = 1; itemNr2 <= nitems3; itemNr2++) {
gdcm::Item &item3 = sqiReferencedImageSequence->GetItem(itemNr2);
gdcm::DataSet &subds3 = item3.GetNestedDataSet();
if (!subds3.FindDataElement(referencedSOPInstanceUID)) {
if (verbose)
fprintf(stdout, " %d no referencedSOPInstanceUID\n", itemNr);
continue;
}
const gdcm::DataElement &deReferencedSOPInstanceUID = subds3.GetDataElement(referencedSOPInstanceUID);
const gdcm::ByteValue *bv = deReferencedSOPInstanceUID.GetByteValue();
std::string refUID(bv->GetPointer(), bv->GetLength());
if (verbose)
fprintf(stdout, " \033[0;32mfound\033[0m: %s as ReferencedSOPInstanceUID\n", refUID.c_str());
poly.ReferencedSOPInstanceUID = boost::algorithm::trim_copy(refUID);
// the string above might contain a utf-8 version of a null character
if (poly.ReferencedSOPInstanceUID.back() == '\0')
poly.ReferencedSOPInstanceUID.replace(poly.ReferencedSOPInstanceUID.end() - 1, poly.ReferencedSOPInstanceUID.end(), "");
}
//
// this is for items in 0070,0008 textObjectSequence
//
if (subds.FindDataElement(textObjectSequence)) { // optional
/*
(0070,0008) SQ (Sequence with explicit length #=1) # 150, 1 TextObjectSequence
(fffe,e000) na (Item with explicit length #=4) # 142, 1 Item
(0070,0004) CS [PIXEL] # 6, 1 AnchorPointAnnotationUnits
(0070,0006) ST [Min/Max: 7 / 349
Mean: 132, Deviation: 103
Total: 657?860
Pixel... # 94, 1 UnformattedTextValue
(0070,0014) FL 190.5\108.5 # 8, 2 AnchorPoint
(0070,0015) CS [Y] # 2, 1 AnchorPointVisibility
(fffe,e00d) na (ItemDelimitationItem for re-encoding) # 0, 0 ItemDelimitationItem
(fffe,e0dd) na (SequenceDelimitationItem for re-encod.) # 0, 0 SequenceDelimitationItem
*/
const gdcm::DataElement &de2 = subds.GetDataElement(textObjectSequence);
gdcm::SmartPointer<gdcm::SequenceOfItems> sqiTextObjectSequence = de2.GetValueAsSQ();
gdcm::SequenceOfItems::SizeType nitems2 = sqiTextObjectSequence->GetNumberOfItems();
if (verbose)
fprintf(stdout, " unformatted text object sequence with %lu item%s\n", nitems2, nitems2!=1?"s":"");
for (int itemNr2 = 1; itemNr2 <= nitems2; itemNr2++) {
gdcm::Item &item2 = sqiTextObjectSequence->GetItem(itemNr2);
gdcm::DataSet &subds2 = item2.GetNestedDataSet();
if (!subds2.FindDataElement(unformattedTextValue)) {
if (verbose)
fprintf(stdout, " %d no unformatted text value\n", itemNr2);
continue;
}
const gdcm::DataElement &deUnformattedTextValue = subds2.GetDataElement(unformattedTextValue);
const gdcm::ByteValue *bv = deUnformattedTextValue.GetByteValue();
std::string uTV(bv->GetPointer(), bv->GetLength());
poly.UnformattedTextValue = boost::algorithm::trim_copy(uTV);
}
}
//
// this is for items in 0070,0001, now we need to look for 0070,0009
//
if (!subds.FindDataElement(graphicObjectSequence)) {
// fprintf(stdout, " %d does not have GraphicObjectSequence\n", itemNr);
continue;
} else {
// fprintf(stdout, " %d \033[0;32mfound\033[0m a GraphicObjectSequence\n", itemNr);
}
const gdcm::DataElement &de2 = subds.GetDataElement(graphicObjectSequence);
gdcm::SmartPointer<gdcm::SequenceOfItems> sqiGraphicObjectSequence = de2.GetValueAsSQ();
gdcm::SequenceOfItems::SizeType nitems2 = sqiGraphicObjectSequence->GetNumberOfItems();
if (verbose)
fprintf(stdout, " graphic object sequence with %lu item%s\n", nitems2, nitems2!=1?"s":"");
for (int itemNr2 = 1; itemNr2 <= nitems2; itemNr2++) {
gdcm::Item &item2 = sqiGraphicObjectSequence->GetItem(itemNr2);
gdcm::DataSet &subds2 = item2.GetNestedDataSet();
if (!subds2.FindDataElement(graphicType)) {
if (verbose)
fprintf(stdout, " %d no graphic type\n", itemNr);
continue;
}
const gdcm::DataElement &deGraphicType = subds2.GetDataElement(graphicType);
const gdcm::ByteValue *bv = deGraphicType.GetByteValue();
std::string gT(bv->GetPointer(), bv->GetLength());
if (!subds2.FindDataElement(numberOfGraphicPoints)) {
if (verbose)
fprintf(stdout, " %d no number of graphic points\n", itemNr);
continue;
}
const gdcm::DataElement &deNumberOfGraphicPoints = subds2.GetDataElement(numberOfGraphicPoints);
// std::string nGP = gdcm::DirectoryHelper::GetStringValueFromTag(numberOfGraphicPoints, subds2);
const gdcm::ByteValue *bv2 = deNumberOfGraphicPoints.GetByteValue();
std::string nGP(bv2->GetPointer(), bv2->GetLength());
int numberOfPoints = *(nGP.c_str());
if (!subds2.FindDataElement(graphicData)) {
if (verbose)
fprintf(stdout, " %d no graphic data\n", itemNr);
continue;
}
const gdcm::DataElement &deGraphicData = subds2.GetDataElement(graphicData);
const gdcm::ByteValue *bv3 = deGraphicData.GetByteValue();
std::string gD(bv3->GetPointer(), bv3->GetLength());
// we can read the values now based on the value representation (VR::FL is single float)
gdcm::Element<gdcm::VR::FL, gdcm::VM::VM1_n> elwc;
gdcm::VR vr = gdcm::VR::FL;
unsigned int vrsize = vr.GetSizeof();
unsigned int count = gD.size() / vrsize;
elwc.SetLength(count * vrsize);
std::stringstream ss1;
ss1.str(gD);
elwc.Read(ss1);
poly.coords.resize(elwc.GetLength());
for (unsigned int i = 0; i < elwc.GetLength(); ++i) {
poly.coords[i] = elwc.GetValue(i);
}
// now store the poly
storage->push_back(poly);
if (verbose) {
std::string utv = poly.UnformattedTextValue;
stripUnicode(utv);
fprintf(stdout, " added poly with %lu points (\"%s\")\n", poly.coords.size(), utv.c_str());
}
}
}
} else {
if (verbose)
fprintf(stdout, "\033[0;31mWarning\033[0m: no GraphicAnnotationSequence (0070,0001) in %s\n", filename.c_str());
}
}
return true;
}
ImageType2D::Pointer createMaskFromStorage(ImageType2D::Pointer im2change, std::vector<int> polyIds, std::vector<Polygon> storage) {
// Use a copy of im2change and return the image of all the masks applied to that slice.
ImageType2D::Pointer mask = ImageType2D::New();
ImageType2D::RegionType maskRegionInput = im2change->GetLargestPossibleRegion();
mask->SetRegions(maskRegionInput);
mask->Allocate();
mask->FillBuffer(itk::NumericTraits<PixelType>::Zero);
mask->SetOrigin(im2change->GetOrigin());
mask->SetSpacing(im2change->GetSpacing());
mask->SetDirection(im2change->GetDirection());
ImageType2D::Pointer lmask = ImageType2D::New();
lmask->SetRegions(maskRegionInput);
lmask->Allocate();
lmask->SetOrigin(im2change->GetOrigin());
lmask->SetSpacing(im2change->GetSpacing());
lmask->SetDirection(im2change->GetDirection());
for (int p = 0; p < polyIds.size(); p++) {
lmask->FillBuffer(itk::NumericTraits<PixelType>::One);
using InputPolylineType = itk::PolyLineParametricPath<2>;
InputPolylineType::Pointer inputPolyline = InputPolylineType::New();
using InputFilterType = itk::PolylineMask2DScanlineImageFilter<ImageType2D, InputPolylineType, ImageType2D>;
InputFilterType::Pointer filter = InputFilterType::New();
// tolerance as 1/10 of a voxel, does this do something?
double tol = std::min(im2change->GetSpacing()[2], std::min(im2change->GetSpacing()[0], im2change->GetSpacing()[1])) / 10.0;
filter->SetCoordinateTolerance(tol);