]> Creatis software - clitk.git/blob - tools/clitkImage2DicomDoseGenericFilter.txx
Deal with Dose Grid Scaling Dicom tag in clitkImage2DicomDose
[clitk.git] / tools / clitkImage2DicomDoseGenericFilter.txx
1 /*=========================================================================
2   Program:   vv                     http://www.creatis.insa-lyon.fr/rio/vv
3
4   Authors belong to:
5   - University of LYON              http://www.universite-lyon.fr/
6   - Léon Bérard cancer center       http://www.centreleonberard.fr
7   - CREATIS CNRS laboratory         http://www.creatis.insa-lyon.fr
8
9   This software is distributed WITHOUT ANY WARRANTY; without even
10   the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11   PURPOSE.  See the copyright notices for more information.
12
13   It is distributed under dual licence
14
15   - BSD        See included LICENSE.txt file
16   - CeCILL-B   http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
17 ===========================================================================**/
18 #ifndef clitkImage2DicomDoseGenericFilter_txx
19 #define clitkImage2DicomDoseGenericFilter_txx
20
21 /* =================================================
22  * @file   clitkImage2DicomDosemGenericFilter.txx
23  * @author
24  * @date
25  *
26  * @brief
27  *
28  ===================================================*/
29
30 #include "math.h"
31
32 #include "clitkImage2DicomDoseGenericFilter.h"
33 #include "clitkCommon.h"
34 #include "itkMinimumMaximumImageCalculator.h"
35 #include "itkImageRegionIterator.h"
36 #include "itkImageRegionConstIterator.h"
37 #if GDCM_MAJOR_VERSION >= 2
38 #include "gdcmUIDGenerator.h"
39 #include <gdcmImageHelper.h>
40 #include <gdcmAttribute.h>
41 #include <gdcmReader.h>
42 #include <gdcmWriter.h>
43 #else
44 #include "gdcmFile.h"
45 #include "gdcmUtil.h"
46 #endif
47
48 //#include "gdcmBase.h"
49 //#include "gdcmDocEntry.h"
50
51
52
53 namespace clitk
54 {
55
56
57 //-----------------------------------------------------------
58 // Constructor
59 //-----------------------------------------------------------
60 template<class args_info_type>
61 Image2DicomDoseGenericFilter<args_info_type>::Image2DicomDoseGenericFilter()
62 {
63   m_Verbose=false;
64   m_InputFileName="";
65 }
66
67
68 //-----------------------------------------------------------
69 // Update
70 //-----------------------------------------------------------
71 template<class args_info_type>
72 void Image2DicomDoseGenericFilter<args_info_type>::Update()
73 {
74   // Read the Dimension and PixelType
75   int Dimension;
76   std::string PixelType;
77   ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType);
78
79
80   // Call UpdateWithDim
81   if(Dimension==2) UpdateWithDim<2>(PixelType);
82   else if(Dimension==3) UpdateWithDim<3>(PixelType);
83   // else if (Dimension==4)UpdateWithDim<4>(PixelType);
84   else {
85     std::cout<<"Error, Only for 2 or 3  Dimensions!!!"<<std::endl ;
86     return;
87   }
88 }
89
90 //-------------------------------------------------------------------
91 // Update with the number of dimensions
92 //-------------------------------------------------------------------
93 template<class args_info_type>
94 template<unsigned int Dimension>
95 void
96 Image2DicomDoseGenericFilter<args_info_type>::UpdateWithDim(std::string PixelType)
97 {
98   if (m_Verbose) std::cout << "Image was detected to be "<<Dimension<<"D and "<< PixelType<<"..."<<std::endl;
99
100   if(PixelType == "short") {
101     if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed short..." << std::endl;
102     UpdateWithDimAndPixelType<Dimension, signed short>();
103   }
104   else if(PixelType == "unsigned_short"){
105     if (m_Verbose) std::cout  << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl;
106     UpdateWithDimAndPixelType<Dimension, unsigned short>();
107   }
108
109   else if (PixelType == "unsigned_char") {
110     if (m_Verbose) std::cout  << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl;
111     UpdateWithDimAndPixelType<Dimension, unsigned char>();
112   }
113
114   //     else if (PixelType == "char"){
115   //       if (m_Verbose) std::cout  << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl;
116   //       UpdateWithDimAndPixelType<Dimension, signed char>();
117   //     }
118   else if (PixelType == "double") {
119     if (m_Verbose) std::cout  << "Launching filter in "<< Dimension <<"D and double..." << std::endl;
120     UpdateWithDimAndPixelType<Dimension, double>();
121   }
122   else {
123     if (m_Verbose) std::cout  << "Launching filter in "<< Dimension <<"D and float..." << std::endl;
124     UpdateWithDimAndPixelType<Dimension, float>();
125   }
126 }
127
128 //-------------------------------------------------------------------
129 // Update with the number of dimensions and the pixeltype read from
130 // the dicom files. The MHD files may be resampled to match the
131 // dicom spacing (and number of slices). Rounding errors in resampling
132 // are handled by removing files when generating the output dicom
133 // series.
134 //-------------------------------------------------------------------
135 template<class args_info_type>
136 template <unsigned int Dimension, class  PixelType>
137 void
138 Image2DicomDoseGenericFilter<args_info_type>::UpdateWithDimAndPixelType()
139 {
140
141 #if GDCM_MAJOR_VERSION == 2
142   // ImageTypes
143   typedef itk::Image<PixelType, Dimension> InputImageType;
144   typedef unsigned short int OutputPixelType;
145   typedef itk::Image<OutputPixelType, Dimension> OutputImageType;
146   typedef itk::ImageFileReader< InputImageType >     ReaderType;
147   typedef itk::ImageSeriesReader< InputImageType >     ReaderSeriesType;
148   typedef itk::ImageSeriesWriter<OutputImageType, OutputImageType>  WriterSerieType;
149   typedef itk::ImageRegionIterator< InputImageType > IteratorType;
150   typedef itk::MinimumMaximumImageCalculator <InputImageType> ImageCalculatorFilterType;
151   typedef itk::GDCMImageIO ImageIOType;
152
153   //-----------------------------------------------------------------------------
154   // opening image input file
155   typename ReaderType::Pointer reader = ReaderType::New();
156   const char * filename = m_ArgsInfo.input_arg;
157   reader->SetFileName( filename );
158   reader->Update();
159   typename InputImageType::Pointer image = reader->GetOutput();
160   std::ostringstream value;
161
162   // Read Dicom model file
163   typename ReaderSeriesType::Pointer readerSeries = ReaderSeriesType::New();
164   ImageIOType::Pointer gdcmIO = ImageIOType::New();
165   std::string filename_out = m_ArgsInfo.output_arg;
166   gdcmIO->LoadPrivateTagsOn();
167   gdcmIO->KeepOriginalUIDOn();
168   typename ReaderSeriesType::FileNamesContainer fileNames;
169   fileNames.push_back(m_ArgsInfo.DicomInputFile_arg);
170   readerSeries->SetImageIO( gdcmIO );
171   readerSeries->SetFileNames( fileNames );
172   try {
173     readerSeries->Update();
174   } catch (itk::ExceptionObject &excp) {
175     std::cerr << "Error: Exception thrown while reading the DICOM model file !!" << std::endl;
176     std::cerr << excp << std::endl;
177   }
178
179   // update output dicom keys/tags
180   typename ReaderSeriesType::DictionaryRawPointer inputDict = (*(readerSeries->GetMetaDataDictionaryArray()))[0];
181   typename ReaderSeriesType::DictionaryArrayType outputArray;
182   typename ReaderSeriesType::DictionaryRawPointer outputDict = new typename ReaderSeriesType::DictionaryType;
183   CopyDictionary (*inputDict, *outputDict);
184
185   // origin
186   typename InputImageType::PointType origin = image->GetOrigin();
187   value.str("");
188   value<<origin[0]<<'\\'<<origin[1]<<'\\'<<origin[2];
189   itk::EncapsulateMetaData<std::string>(*outputDict, "0020|0032", value.str());
190   DD(origin);
191
192   // size
193   typename InputImageType::SizeType imageSize = image->GetLargestPossibleRegion().GetSize();
194   //DD(imageSize);
195   int NbCols=imageSize[0];      // col
196   int NbRows=imageSize[1];      // row
197   int NbFrames=imageSize[2];    // frame
198   itk::EncapsulateMetaData<std::string>(*outputDict, "0028|0008", NumberToString(NbFrames));
199   itk::EncapsulateMetaData<std::string>(*outputDict, "0028|0010", NumberToString(NbRows));
200   itk::EncapsulateMetaData<std::string>(*outputDict, "0028|0011", NumberToString(NbCols));
201   DD(NbCols);
202   DD(NbRows);
203   DD(NbFrames);
204
205   // spacing
206   typename InputImageType::SpacingType Spacing = image->GetSpacing();
207   value.str("");
208   value<<Spacing[0]<<'\\'<<Spacing[1];
209   itk::EncapsulateMetaData<std::string>(*outputDict, "0028|0030", value.str());
210   value.str("");
211   value<<Spacing[2];
212   itk::EncapsulateMetaData<std::string>(*outputDict, "0018|0050", value.str());
213   DD(Spacing);
214
215   // offset
216   float offset = 0.;
217   value.str("");
218   value << offset;
219   for (int i=1; i<NbFrames ; i++){
220     offset+=Spacing[2];
221     value << '\\';
222     value << offset;
223   }
224   itk::EncapsulateMetaData<std::string>(*outputDict, "3004|000c", value.str());
225   DD(value.str());
226
227   // scaling
228   typename ImageCalculatorFilterType::Pointer imageCalculatorFilter = ImageCalculatorFilterType::New();
229   imageCalculatorFilter->SetImage(image);
230   imageCalculatorFilter->ComputeMaximum();
231   float highestValue=imageCalculatorFilter->GetMaximum();
232   double doseScaling = highestValue/(pow(2,16)-1);
233   value.str("");
234   value<<doseScaling;
235   itk::EncapsulateMetaData<std::string>(*outputDict, "3004|000e", value.str());
236   DD(value.str());
237
238   // image data
239   typename OutputImageType::Pointer imageOutput = OutputImageType::New();
240   imageOutput->SetRegions(image->GetLargestPossibleRegion());
241   imageOutput->SetSpacing(image->GetSpacing());
242   imageOutput->SetOrigin(image->GetOrigin());
243   imageOutput->SetDirection(image->GetDirection());
244   imageOutput->Allocate();
245
246   typename itk::ImageRegionConstIterator<InputImageType> imageIterator(image,image->GetLargestPossibleRegion());
247   typename itk::ImageRegionIterator<OutputImageType> imageOutputIterator(imageOutput,imageOutput->GetLargestPossibleRegion());
248   while(!imageIterator.IsAtEnd()) {
249     // Set the current pixel to white
250     imageOutputIterator.Set((signed short int)(imageIterator.Get()/doseScaling));
251
252     ++imageIterator;
253     ++imageOutputIterator;
254   }
255
256   // Output directory and filenames
257   typename WriterSerieType::Pointer writerSerie = WriterSerieType::New();
258   outputArray.push_back(outputDict);
259   writerSerie->SetInput( imageOutput );
260   writerSerie->SetImageIO( gdcmIO );
261   typename ReaderSeriesType::FileNamesContainer fileNamesOutput;
262   fileNamesOutput.push_back(filename_out);
263   writerSerie->SetFileNames( fileNamesOutput );
264   writerSerie->SetMetaDataDictionaryArray(&outputArray);
265
266   // Write
267   try {
268     if (m_ArgsInfo.verbose_flag)
269       std::cout << writerSerie << std::endl;
270     writerSerie->Update();
271   } catch( itk::ExceptionObject & excp ) {
272     std::cerr << "Error: Exception thrown while writing the series!!" << std::endl;
273     std::cerr << excp << std::endl;
274   }
275
276   //Read sequence dicom tag with gdcm
277   gdcm::Reader readerTemplateGDCM;
278   readerTemplateGDCM.SetFileName( fileNames[0].c_str() );
279   readerTemplateGDCM.Read();
280   gdcm::File &fileTemplate = readerTemplateGDCM.GetFile();
281   gdcm::DataSet &dsTemplate = fileTemplate.GetDataSet();
282   const unsigned int ptr_len = 42;
283   char *ptrTemplate = new char[ptr_len];
284   memset(ptrTemplate,0,ptr_len);
285
286   const gdcm::DataElement &referenceRTPlanSq = dsTemplate.GetDataElement(gdcm::Tag(0x300c, 0x02));
287
288   //Create the Dose Grid Scaling data element (ITK 4.13 do not take into account - it works well with ITK 4.5.1)
289   gdcm::DataElement deDoseGridScaling( gdcm::Tag(0x3004,0x0e) );
290   deDoseGridScaling.SetVR( gdcm::VR::DS );
291   deDoseGridScaling.SetByteValue(NumberToString(doseScaling).c_str(), (uint32_t)strlen(NumberToString(doseScaling).c_str()));
292
293   //Copy/Write sequence dicom tag with gdcm
294   gdcm::Reader readerOutputGDCM;
295   readerOutputGDCM.SetFileName( fileNamesOutput[0].c_str() );
296   readerOutputGDCM.Read();
297   gdcm::File &file = readerOutputGDCM.GetFile();
298   gdcm::DataSet &dsOutput = file.GetDataSet();
299
300   dsOutput.Insert(referenceRTPlanSq);
301   dsOutput.Replace(deDoseGridScaling);
302   gdcm::Writer w;
303   w.SetFile( file );
304   w.SetFileName( fileNamesOutput[0].c_str() );
305   w.Write();
306
307 //---------------------------------------------------------------------------------------
308 //WRITE DICOM BIS
309 // The previous way of writting DICOM-RT-DOSE works only for ITK
310 // and resulting RT-DOSE files are not readable by commercial systems.
311 // The nex step is to copy again the output file with another syntax, allowing to make RT-DOSE files readable by commercial systems.
312 // see Jean-Pierre Roux comment below.
313
314 /*gdcm::FileHelper *fh = new gdcm::FileHelper(args_info.OutputFile_arg);
315    void *imageData;
316    int dataSize;
317   
318    dataSize  = fh->GetImageDataRawSize();
319    imageData = fh->GetImageDataRaw();// somewhat important : Loads the Pixels in memory !
320   
321    fh->SetWriteModeToRaw();
322    fh->SetWriteTypeToDcmExplVR();
323
324    bool res = fh->Write(args_info.OutputFile_arg);
325
326    if(!res)
327       std::cout <<"Fail to write [" << args_info.OutputFile_arg << "]" <<std::endl;   
328    else std::cout<<"\n DICOM File re-written, using the FileHelper syntax, in order to be processed by commercial systems !"<<std::endl;
329
330 delete fh; */
331 /*  gdcm::Writer w;
332   w.SetFile(mDCMFile);
333   w.SetFileName(m_ArgsInfo.output_arg);
334   w.Write();*/
335 //   fh->Delete();
336
337 //---------------------------------------------------------------------------------------
338 //---------------------------------------------------------------------------------------
339 // Jean-Pierre Roux help for DICOM-RT-DOSE writting
340 //---------------------------------------------------------------------------------------
341 //---------------------------------------------------------------------------------------
342
343 //      de      Jean-Pierre Roux <jpr@creatis.insa-lyon.fr>
344 // répondre à jpr@creatis.insa-lyon.fr
345 // à   Loic Grevillot <loic.grevillot@gmail.com>
346 // cc   jpr@creatis.insa-lyon.fr,
347 // Joël Schaerer <joel.schaerer@gmail.com>,
348 // David Sarrut <David.Sarrut@creatis.insa-lyon.fr>,
349 // Joel Schaerer <joel.schaerer@creatis.insa-lyon.fr>
350 // date 12 juillet 2010 12:23
351 // objet        Re: DICOM RT DOSE
352 //      
353 // masquer les détails 12:23 (Il y a 21 heures)
354 //      
355 // Bonjour,
356 // 
357 // J'aurais écrit à peut prèt la même chose.
358 // (Ci après un extrait de mon code -Example/ReWrite.cxx-)
359 // 
360 // L'utilisation d'un FileHelper (qui ne changera rien dans ce cas précis) est une mesure de précaution, car,  l'élément 7FE0|0010 peut être compressé (ce qui n'est pas le cas pour tes images), que la manière de stocker les pixels ainsi compressés était parfois un peu ... curieuse.
361 // Je décompresse, et réécrit non compressé.
362 // 
363 // ============================
364 //    gdcm::File *f = new gdcm::File();
365 //    f->SetMaxSizeLoadEntry(0x7fffffff);
366 //    f->SetFileName( fileName );
367 //    bool res = f->Load(); 
368 //    if ( !res )
369 //    {
370 //       delete f;
371 //       return 0;
372 //    }
373 // 
374 //    if (!f->IsReadable())
375 //    {
376 //        std::cerr << "Sorry, not a Readable DICOM / ACR File"  <<std::endl;
377 //        delete f;
378 //        return 0;
379 //    }
380 // 
381 //    gdcm::FileHelper *fh = new gdcm::FileHelper(f);
382 //    void *imageData;
383 //    int dataSize;
384 //   
385 //    dataSize  = fh->GetImageDataRawSize();
386 //    imageData = fh->GetImageDataRaw();// somewhat important : Loads the Pixels in memory !
387 //   
388 //    fh->SetWriteModeToRaw();
389 //    fh->SetWriteTypeToDcmExplVR();
390 //    res = fh->Write(outputFileName);
391 //   
392 //    if(!res)
393 //       std::cout <<"Fail to write [" << outputFileName << "]" <<std::endl;   
394 // 
395 //    f->Delete();
396 //    fh->Delete();
397
398 //---------------------------------------------------------------------------------------
399 //---------------------------------------------------------------------------------------
400 // pour supprimer des tags:
401 //---------------------------------------------------------------------------------------
402 //---------------------------------------------------------------------------------------
403 //      SOLUCE 1 QUI MARCHE POUR UN SQItem SIMPLE
404 /*
405 gdcm::DocEntry *a;
406 //a= ((gdcm::SQItem*)mDCMFile)->GetDocEntry(0xfffe,0xe00d);
407 a= ((gdcm::SQItem*)mDCMFile)->GetDocEntry(0x3004,0x000e);
408 ((gdcm::SQItem*)mDCMFile)->RemoveEntry(a);
409 mDCMFile->Write (args_info.OutputFile_arg, type);
410 */
411
412 //      SOLUCE 2 QUI MARCHE POUR UNE SeqEntry->SQItem 
413 /*
414 std::cout<<"\ntest correction fichier apres ecriture\n"<<std::endl;
415 gdcm::SeqEntry *seqEntry = mDCMFile->GetSeqEntry(0x300c,0x0002);
416 gdcm::SQItem* currentItem = seqEntry->GetFirstSQItem();
417 gdcm::DocEntry *a;
418 //a= currentItem->GetDocEntry(0x0008,0x1155);
419 a= currentItem->GetDocEntry(0xfffe,0xe00d);
420 currentItem->RemoveEntry(a);
421 mDCMFile->Write (args_info.OutputFile_arg, type);
422 */
423
424 //gdcm::DocEntry *a;
425 //a=GetDocEntry(0x7fe0,0x0000);
426 //((gdcm::SQItem*)mDCMFile)->RemoveEntry(a);
427
428 //-----------------------------------------------------------------------------------
429   std::cout <<"\n## DICOM Image to RT DOSE application is ended..."<<std::endl;
430   std::cout <<"#########################################################\n" << std::endl;
431
432 #else
433   std::cout << "Use GDCM2" << std::endl;
434 #endif
435 }
436 //---------------------------------------------------------------------------
437
438
439 //---------------------------------------------------------------------------
440 void CopyDictionary (itk::MetaDataDictionary &fromDict, itk::MetaDataDictionary &toDict)
441 {
442   typedef itk::MetaDataDictionary DictionaryType;
443
444   DictionaryType::ConstIterator itr = fromDict.Begin();
445   DictionaryType::ConstIterator end = fromDict.End();
446   typedef itk::MetaDataObject< std::string > MetaDataStringType;
447
448   while( itr != end )
449     {
450     itk::MetaDataObjectBase::Pointer  entry = itr->second;
451
452     MetaDataStringType::Pointer entryvalue =
453       dynamic_cast<MetaDataStringType *>( entry.GetPointer() ) ;
454     if( entryvalue )
455       {
456       std::string tagkey   = itr->first;
457       std::string tagvalue = entryvalue->GetMetaDataObjectValue();
458       itk::EncapsulateMetaData<std::string>(toDict, tagkey, tagvalue);
459       }
460     ++itr;
461     }
462 }
463 //---------------------------------------------------------------------------
464
465 //---------------------------------------------------------------------------
466 template <typename T> std::string NumberToString ( T Number )
467 {
468    std::ostringstream ss;
469    ss << Number;
470    return ss.str();
471 }
472 //---------------------------------------------------------------------------
473
474
475 }//end clitk
476
477 #endif //#define clitkImage2DicomDoseGenericFilter_txx