]> Creatis software - gdcm.git/blob - Example/PhilipsToBrucker.cxx
a532b83adb3a06ada8bd239402c88731dfd705c8
[gdcm.git] / Example / PhilipsToBrucker.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: PhilipsToBrucker.cxx,v $
5   Language:  C++
6   Date:      $Date: 2006/01/18 15:45:20 $
7   Version:   $Revision: 1.5 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18 #include "gdcmDocEntry.h"
19 #include "gdcmDicomDir.h"
20 #include "gdcmDicomDirPatient.h"
21 #include "gdcmFile.h"
22 #include "gdcmFileHelper.h"
23 #include "gdcmDirList.h"
24 #include "gdcmDebug.h"
25 #include "gdcmArgMgr.h"
26 #include "gdcmUtil.h"
27 #include "gdcmSerieHelper.h"
28
29 #include <iostream>
30
31 /**
32   * \brief   
33   *          - explores recursively the given directory
34   *          - keeps the requested series
35   *          - orders the gdcm-readable found Files
36   *            according to their Patient/Study/Serie/Image characteristics
37   *          - fills a single level Directory with *all* the files,
38   *            converted into a Brucker-like Dicom, Intags compliant
39   * 
40   */  
41
42 typedef std::map<std::string, gdcm::File*> SortedFiles;
43
44 int main(int argc, char *argv[]) 
45 {
46    START_USAGE(usage)
47    " \n PhilipsToBrucker :\n                                                  ",
48    " - explores recursively the given directory,                              ",
49    " - keeps the requested series/ drops the unrequested series               ",
50    " - orders the gdcm-readable found Files according to their                ",
51    "           (0x0010, 0x0010) Patient's Name                                ",
52    "           (0x0020, 0x000e) Series Instance UID                           ",
53    "           (0x0020, 0x0032) Image Position (Patient)                      ",
54    "           (0x0018, 0x1312) In-plane Phase Encoding Direction             ",
55    "           (0x0018, 0x1060) Trigger Time                                  ",
56    " - fills a single level (*) Directory with *all* the files,               ",
57    "           converted into a Brucker-like Dicom, InTags compliant          ",
58    "   (*) actually : creates as many directories as Patients                 ",
59    "                  -that shouldn't appear, but being carefull is better ! -",
60    "                                                                          ",
61    " usage:                                                                   ",
62    " PhilipsToBrucker dirin=rootDirectoryName                                 ",
63    "                  dirout=outputDirectoryName                              ",
64    "                  {  [keep= list of seriesNumber to process]              ",
65    "                   | [drop= list of seriesNumber to ignore] }             ",
66    "                  [extent=image suffix (.IMA, .NEMA, .DCM, ...)]          ",
67    "                  [noshadowseq][noshadow][noseq] [verbose] [debug]        ",
68    "                                                                          ",
69    " dirout : will be created if doesn't exist                                ",
70    " keep : if user wants to process a limited number of series               ",
71    "            he gives the list of 'SeriesNumber' (tag 0020|0011)           ",
72    " drop : if user wants to ignore a limited number of series                ",
73    "            he gives the list of 'SeriesNumber' (tag 0020|0011)           ",   
74    "        SeriesNumber are short enough to be human readable                ",
75    "        e.g : 1030,1035,1043                                              ",
76    " extent : DO NOT forget the leading '.' !                                 ",  
77    " noshadowseq: user doesn't want to load Private Sequences                 ",
78    " noshadow : user doesn't want to load Private groups (odd number)         ",
79    " noseq    : user doesn't want to load Sequences                           ",
80    " verbose  : user wants to run the program in 'verbose mode'               ",
81    " debug    : *developer*  wants to run the program in 'debug mode'         ",
82    FINISH_USAGE
83
84    // ----- Initialize Arguments Manager ------
85       
86    gdcm::ArgMgr *am = new gdcm::ArgMgr(argc, argv);
87   
88    if (argc == 1 || am->ArgMgrDefined("usage")) 
89    {
90       am->ArgMgrUsage(usage); // Display 'usage'
91       delete am;
92       return 0;
93    }
94
95    char *dirNamein;
96    dirNamein  = am->ArgMgrGetString("dirin",(char *)"."); 
97
98    char *dirNameout;   
99    dirNameout  = am->ArgMgrGetString("dirout",(char *)".");  
100    
101    int loadMode = gdcm::LD_ALL;
102    if ( am->ArgMgrDefined("noshadowseq") )
103       loadMode |= gdcm::LD_NOSHADOWSEQ;
104    else 
105    {
106    if ( am->ArgMgrDefined("noshadow") )
107          loadMode |= gdcm::LD_NOSHADOW;
108       if ( am->ArgMgrDefined("noseq") )
109          loadMode |= gdcm::LD_NOSEQ;
110    }
111
112    if (am->ArgMgrDefined("debug"))
113       gdcm::Debug::DebugOn();
114       
115    bool verbose = am->ArgMgrDefined("verbose");
116    
117    int nbSeriesToKeep;
118    int *seriesToKeep = am->ArgMgrGetListOfInt("keep", &nbSeriesToKeep);
119    int nbSeriesToDrop;
120    int *seriesToDrop = am->ArgMgrGetListOfInt("drop", &nbSeriesToDrop);
121  
122    if ( nbSeriesToKeep!=0 && nbSeriesToDrop!=0)
123    {
124       std::cout << "KEEP and DROP are mutually exclusive !" << std::endl;
125       delete am;
126       return 0;         
127    }
128    
129    char *extent  = am->ArgMgrGetString("extent",".DCM");
130         
131    // if unused Param we give up
132    if ( am->ArgMgrPrintUnusedLabels() )
133    { 
134       am->ArgMgrUsage(usage);
135       delete am;
136       return 0;
137    }
138    delete am;  // we don't need Argument Manager any longer
139
140    // ----- Begin Processing -----
141    
142    if ( ! gdcm::DirList::IsDirectory(dirNamein) )
143    {
144       std::cout << "KO : [" << dirNamein << "] is not a Directory : " << std::endl;
145       exit(0);
146    }
147    else
148    {
149       std::cout << "OK : [" << dirNamein << "]" << " is a Directory" << std::endl;
150    }
151
152
153    std::string systemCommand;
154    if ( ! gdcm::DirList::IsDirectory(dirNameout) )     // dirout not found
155    {
156       std::string strDirNameout(dirNameout);          // to please gcc 4
157       systemCommand = "mkdir " +strDirNameout;        // create it!
158       if (verbose)
159          std::cout << systemCommand << std::endl;
160       system (systemCommand.c_str());
161       if ( ! gdcm::DirList::IsDirectory(dirNameout) ) // be sure it worked
162       {
163           std::cout << "KO : not a dir : [" << dirNameout << "] (creation failure ?)" << std::endl;
164           exit(0);
165       }
166       else
167      {
168         std::cout << "Directory [" << dirNameout << "]" << " created" << std::endl;
169      }
170    }
171    else
172    {
173        std::cout << "Output Directory [" << dirNameout << "]" << " already exists; Used as is." << std::endl;
174    }
175    std::string strDirNamein(dirNamein);
176    gdcm::DirList dirList(strDirNamein, true); // get recursively the list of files
177    
178 /*   
179    std::cout << "---------------List of found files ------------" << std::endl;
180    dirList.Print();
181  */   
182
183    gdcm::DirListType fileNames;
184    fileNames = dirList.GetFilenames();
185    gdcm::SerieHelper *s;              // Needed only to may use SerieHelper::AddSeriesDetail()
186    s = gdcm::SerieHelper::New();
187
188 /*       
189    std::cout << "---------------Print Serie--------------" << std::endl; 
190    s->SetDirectory(dirNamein, true); // true : recursive exploration 
191    s->SetUseSeriesDetails(true);  
192    s->AddSeriesDetail(0x0018, 0x1312);   
193    s->Print();
194 */
195   
196    gdcm::File *f;
197    gdcm::FileHelper *fh;
198 /*   
199    std::cout << "---------------Print Unique Series identifiers---------"  
200              << std::endl;     
201    std::string uniqueSeriesIdentifier;
202  
203    for (gdcm::DirListType::iterator it = fileNames.begin();  
204                                     it != fileNames.end();
205                                   ++it)
206    {
207       std::cout << "File Name : " << *it << std::endl;
208       f = gdcm::File::New();
209       f->SetLoadMode(gdcm::LD_ALL);
210       f->SetFileName( *it );
211       f->Load();
212         
213       uniqueSeriesIdentifier=s->CreateUniqueSeriesIdentifier(f);
214       std::cout << "                           [" <<
215                uniqueSeriesIdentifier  << "]" << std::endl;       
216       f->Delete();
217    }
218 */
219    
220    if (verbose)
221       std::cout << "------------------Print Break levels-----------------" 
222                 << std::endl;
223
224    std::string userFileIdentifier; 
225    SortedFiles sf;
226
227    s->AddSeriesDetail(0x0010, 0x0010, false); // Patient's Name
228    s->AddSeriesDetail(0x0020, 0x000e, false); // Series Instance UID
229    s->AddSeriesDetail(0x0020, 0x0032, false); // Image Position (Patient)     
230    s->AddSeriesDetail(0x0018, 0x1312, false); // In-plane Phase Encoding Direction 
231    s->AddSeriesDetail(0x0018, 0x1060, true);  // Trigger Time 
232    
233    for (gdcm::DirListType::iterator it = fileNames.begin();  
234                                     it != fileNames.end();
235                                   ++it)
236    {
237       f = gdcm::File::New();
238       f->SetLoadMode(loadMode);
239       f->SetFileName( *it );
240       f->Load();
241       
242       // keep only requested Series
243       std::string strSeriesNumber;
244       int seriesNumber;
245       int j;
246       
247       bool keep = false;
248       if (nbSeriesToKeep != 0)
249       {     
250          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
251          seriesNumber = atoi( strSeriesNumber.c_str() );
252          for (j=0;j<nbSeriesToKeep; j++)
253          {
254             if(seriesNumber == seriesToKeep[j])
255             {
256                keep = true;
257                break;
258             }
259          }
260          if ( !keep)
261          {
262             f->Delete();
263             continue;
264          } 
265       }
266       // drop all unrequested Series
267       bool drop = false;
268       if (nbSeriesToDrop != 0)
269       {     
270          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
271          seriesNumber = atoi( strSeriesNumber.c_str() );
272          for (j=0;j<nbSeriesToDrop; j++)
273          {
274             if(seriesNumber == seriesToDrop[j])
275             {
276                drop = true;
277                break;
278             }
279         }
280         if (drop)
281         {
282            f->Delete();
283            continue;
284         }
285       }      
286
287       userFileIdentifier=s->CreateUserDefinedFileIdentifier(f);        
288       //std::cout << "                           [" <<
289       //        userFileIdentifier  << "]" << std::endl;
290       
291       // storing in a map ensures automatic sorting !      
292       sf[userFileIdentifier] = f;
293    }
294       
295    std::vector<std::string> tokens;
296    std::string fullFilename, lastFilename;
297    std::string previousPatientName, currentPatientName;
298    std::string previousSerieInstanceUID, currentSerieInstanceUID;
299    std::string previousImagePosition, currentImagePosition;
300    std::string previousPhaseEncodingDirection, currentPhaseEncodingDirection;
301    
302    std::string writeDir, currentWriteDir;
303    
304    writeDir = gdcm::Util::NormalizePath(dirNameout);     
305    SortedFiles::iterator it2;
306  
307    previousPatientName            = "";
308    previousSerieInstanceUID       = "";   
309    previousImagePosition          = "";
310    previousPhaseEncodingDirection = "";
311    
312    int sliceIndex = 0;
313    int frameIndex = 0;
314       
315    gdcm::File *currentFile;
316      
317    for (it2 = sf.begin() ; it2 != sf.end(); ++it2)
318    {  
319       currentFile = it2->second;
320        
321       fullFilename =  currentFile->GetFileName();
322       lastFilename =  gdcm::Util::GetName( fullFilename ); 
323
324       
325       tokens.clear();
326       gdcm::Util::Tokenize (it2->first, tokens, "_");
327       
328       currentPatientName            = tokens[0];
329       currentSerieInstanceUID       = tokens[1];
330       currentImagePosition          = tokens[2];
331       currentPhaseEncodingDirection = tokens[3];     
332       
333       if (previousPatientName != currentPatientName)
334       {
335          previousPatientName = currentPatientName;
336          if (verbose)   
337             std::cout << "==== new Patient " << currentPatientName << std::endl;
338          previousPatientName            = currentPatientName;
339          previousSerieInstanceUID       = ""; //currentSerieInstanceUID;
340          previousImagePosition          = ""; //currentImagePosition;
341          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
342  
343          currentWriteDir = writeDir + currentPatientName;
344          if ( ! gdcm::DirList::IsDirectory(currentWriteDir) )
345            {
346               systemCommand   = "mkdir " + currentWriteDir;
347               if (verbose)
348                  std::cout << systemCommand << std::endl;
349               system ( systemCommand.c_str() );
350          }
351       }
352
353       if (previousSerieInstanceUID != currentSerieInstanceUID)
354       {        
355          if (verbose)   
356             std::cout << "==== === new Serie " << currentSerieInstanceUID 
357                       << std::endl;
358          previousSerieInstanceUID       = currentSerieInstanceUID;
359          previousImagePosition          = ""; //currentImagePosition;
360          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
361       }
362
363       if (previousImagePosition != currentImagePosition)
364       {        
365          if (verbose)   
366             std::cout << "=== === === new Position " << currentImagePosition 
367                       << std::endl;
368          previousImagePosition          = currentImagePosition;
369          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
370          sliceIndex += 1;
371       }      
372
373       if (previousPhaseEncodingDirection != currentPhaseEncodingDirection)
374       {        
375          if (verbose)   
376             std::cout << "==== === === === new PhaseEncodingDirection " 
377                       << currentPhaseEncodingDirection << std::endl;
378          previousPhaseEncodingDirection = currentPhaseEncodingDirection;
379       }      
380       frameIndex++; 
381       if (verbose)
382          std::cout << "--- --- --- --- --- " << (it2->second)->GetFileName() 
383                    << std::endl;
384       if ( gdcm::Debug::GetDebugFlag())
385          std::cout << "--- --- --- --- --- " << it2->first << "  " 
386                    << (it2->second)->GetFileName() << " " 
387                    << gdcm::Util::GetName( fullFilename ) << std::endl;           
388       
389       // Transform the image to be 'Brucker-Like'
390       // ----------------------------------------   
391     
392       // Deal with 0x0019, 0x1000 : 'FOV'
393       int nX = currentFile->GetXSize();
394       int nY = currentFile->GetYSize();
395       float pxSzX = currentFile->GetXSpacing();
396       float pxSzY = currentFile->GetYSpacing();
397       char fov[64];
398       sprintf(fov, "%f\\%f",nX*pxSzX, nY*pxSzY);
399       currentFile->InsertEntryString(fov, 0x0019, 0x1000, "DS");
400      
401       // Deal with 0x0020, 0x0012 : 'SESSION INDEX'
402       std::string chSessionIndex;
403       if (currentPhaseEncodingDirection == "ROW")
404          chSessionIndex = "1";
405       else
406          chSessionIndex = "2"; // suppose it's "COLUMN" !
407       currentFile->InsertEntryString(chSessionIndex, 0x0020, 0x0012, "IS");
408    
409       // Deal with  0x0021, 01020 : 'SLICE INDEX'
410       char chSliceIndex[5];
411       sprintf(chSliceIndex, "%04d", sliceIndex);
412       std::string strChSliceIndex(chSliceIndex);
413       currentFile->InsertEntryString(strChSliceIndex, 0x0021, 0x1020, "IS");
414        
415       // Deal with  0x0021, 01040 : 'FRAME INDEX' 
416       char chFrameIndex[5];
417       sprintf(chFrameIndex, "%04d", frameIndex);
418       currentFile->InsertEntryString(chFrameIndex, 0x0021, 0x1040, "IS"); 
419                     
420       std::string strExtent(extent);
421       std::string fullWriteFilename = currentWriteDir + gdcm::GDCM_FILESEPARATOR + lastFilename + strExtent;
422       
423       /*           
424       systemCommand  = "cp " + fullFilename + " " + fullWriteFilename;
425       std::cout << systemCommand << std::endl;
426       system (  systemCommand.c_str() );
427       */
428             
429       // Load the pixels in RAM.      
430       
431       fh = gdcm::FileHelper::New(currentFile);     
432       fh->GetImageDataRaw(); // Don't convert (Gray Pixels + LUT) into (RGB pixels) ?!?
433       fh->SetWriteTypeToDcmExplVR();
434       fh->Write(fullWriteFilename);
435       fh->Delete();       
436    }
437  }