]> Creatis software - gdcm.git/blob - Example/PhilipsToBrucker2.cxx
ENH: Finally I got ArgMgr to be const string instead of char*... strcasecmp is POSIX...
[gdcm.git] / Example / PhilipsToBrucker2.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: PhilipsToBrucker2.cxx,v $
5   Language:  C++
6   Date:      $Date: 2006/01/26 15:52:43 $
7   Version:   $Revision: 1.10 $
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, 0x1060) Trigger Time                                  ",
55    "           (0x0018, 0x1312) In-plane Phase Encoding Direction             ",
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    " or                                                                       ",
61    " - fills a tree-like structure of directories as :                        ",
62    "        - Patient                                                         ",
63    "        -- Serie                                                          ",
64    "        --- Position                                                      ",
65    "            Images are (sorted by Trigger Time /                          ",
66    "                     Encoding Direction (Row, Column)                     ",
67    "      use :                                                               ",
68    "           0x0021, 0x1020 : 'SLICE INDEX'                                 ",
69    "           0x0021, 0x1040 : 'FRAME INDEX'                                 ",
70    "           0x0020, 0x0012 : 'SESSION INDEX'  (Acquisition Number)         ",
71    " usage:                                                                   ",
72    " PhilipsToBrucker dirin=rootDirectoryName                                 ",
73    "                  dirout=outputDirectoryName                              ",
74    "                  {  [keep= list of seriesNumber to process]              ",
75    "                   | [drop= list of seriesNumber to ignore] }             ",
76    "                  [input = {ACR|DCM}]                                     ", 
77    "                  [extent=image suffix (.IMA, .NEMA, .DCM, ...)]          ",
78    "                  [listonly] [split]                                      ",
79    "                  [noshadowseq][noshadow][noseq] [verbose] [debug]        ",
80    "                                                                          ",
81    " dirout : will be created if doesn't exist                                ",
82    " keep : if user wants to process a limited number of series               ",
83    "            he gives the list of 'SeriesNumber' (tag 0020|0011)           ",
84    " drop : if user wants to ignore a limited number of series                ",
85    "            he gives the list of 'SeriesNumber' (tag 0020|0011)           ",   
86    "        SeriesNumber are short enough to be human readable                ",
87    "        e.g : 1030,1035,1043                                              ",
88    " extent : DO NOT forget the leading '.' !                                 ",
89    " split: creates a tree-like structure of directories as :                 ",
90    "        - Patient                                                         ",
91    "        -- Serie                                                          ",
92    "        --- Position                                                      ",
93    "            Images are (sorted by Trigger Time /                          ",
94    "                     Encoding Direction (Row, Column)                     ",
95    " noshadowseq: user doesn't want to load Private Sequences                 ",
96    " noshadow : user doesn't want to load Private groups (odd number)         ",
97    " noseq    : user doesn't want to load Sequences                           ",
98    " verbose  : user wants to run the program in 'verbose mode'               ",
99    " debug    : *developer*  wants to run the program in 'debug mode'         ",
100    FINISH_USAGE
101
102    // ----- Initialize Arguments Manager ------
103       
104    gdcm::ArgMgr *am = new gdcm::ArgMgr(argc, argv);
105   
106    if (argc == 1 || am->ArgMgrDefined("usage")) 
107    {
108       am->ArgMgrUsage(usage); // Display 'usage'
109       delete am;
110       return 0;
111    }
112
113    const char *dirNamein;   
114    dirNamein  = am->ArgMgrGetString("dirin","."); 
115
116    const char *dirNameout;   
117    dirNameout  = am->ArgMgrGetString("dirout",".");  
118    
119    int loadMode = gdcm::LD_ALL;
120    if ( am->ArgMgrDefined("noshadowseq") )
121       loadMode |= gdcm::LD_NOSHADOWSEQ;
122    else 
123    {
124    if ( am->ArgMgrDefined("noshadow") )
125          loadMode |= gdcm::LD_NOSHADOW;
126       if ( am->ArgMgrDefined("noseq") )
127          loadMode |= gdcm::LD_NOSEQ;
128    }
129
130    if (am->ArgMgrDefined("debug"))
131       gdcm::Debug::DebugOn();
132       
133    bool verbose  = am->ArgMgrDefined("verbose");
134    bool split    = am->ArgMgrDefined("split");
135    bool listonly = am->ArgMgrDefined("listonly");
136          
137    int nbSeriesToKeep;
138    int *seriesToKeep = am->ArgMgrGetListOfInt("keep", &nbSeriesToKeep);
139    int nbSeriesToDrop;
140    int *seriesToDrop = am->ArgMgrGetListOfInt("drop", &nbSeriesToDrop);
141  
142    if ( nbSeriesToKeep!=0 && nbSeriesToDrop!=0)
143    {
144       std::cout << "KEEP and DROP are mutually exclusive !" << std::endl;
145       delete am;
146       return 0;         
147    }
148    
149    const char *extent  = am->ArgMgrGetString("extent",".DCM");
150    
151    // if unused Param we give up
152    if ( am->ArgMgrPrintUnusedLabels() )
153    { 
154       am->ArgMgrUsage(usage);
155       delete am;
156       return 0;
157    }
158    delete am;  // we don't need Argument Manager any longer
159
160    // ----- Begin Processing -----
161    
162    if ( ! gdcm::DirList::IsDirectory(dirNamein) )
163    {
164       std::cout << "KO : [" << dirNamein << "] is not a Directory." << std::endl;
165       exit(0);
166    }
167    else
168    {
169       std::cout << "OK : [" << dirNamein << "] is a Directory." << std::endl;
170    }
171
172    std::string systemCommand;
173    
174    std::cout << "Check for output directory :[" << dirNameout << "]."
175              <<std::endl;
176    if ( ! gdcm::DirList::IsDirectory(dirNameout) )    // dirout not found
177    {
178       std::string strDirNameout(dirNameout);          // to please gcc 4
179       systemCommand = "mkdir " +strDirNameout;        // create it!
180       if (verbose)
181          std::cout << systemCommand << std::endl;
182       system (systemCommand.c_str());
183       if ( ! gdcm::DirList::IsDirectory(dirNameout) ) // be sure it worked
184       {
185           std::cout << "KO : not a dir : [" << dirNameout << "] (creation failure ?)" << std::endl;
186           exit(0);
187       }
188       else
189       {
190         std::cout << "Directory [" << dirNameout << "] created." << std::endl;
191       }
192    }
193    else
194    {
195        std::cout << "Output Directory [" << dirNameout << "] already exists; Used as is." << std::endl;
196    }
197     
198    std::string strDirNamein(dirNamein);
199    gdcm::DirList dirList(strDirNamein, true); // get recursively the list of files
200    
201    if (listonly)
202    {
203       std::cout << "------------List of found files ------------" << std::endl;
204       dirList.Print();
205    }
206
207    gdcm::DirListType fileNames;
208    fileNames = dirList.GetFilenames();
209    gdcm::SerieHelper *s;              // Needed only to may use SerieHelper::AddSeriesDetail()
210    s = gdcm::SerieHelper::New();
211
212 /*       
213    std::cout << "---------------Print Serie--------------" << std::endl; 
214    s->SetDirectory(dirNamein, true); // true : recursive exploration 
215    s->SetUseSeriesDetails(true);  
216    s->AddSeriesDetail(0x0018, 0x1312);   
217    s->Print();
218 */
219   
220    gdcm::File *f;
221    gdcm::FileHelper *fh;
222    std::vector<std::string> tokens;
223 /*   
224    std::cout << "---------------Print Unique Series identifiers---------"  
225              << std::endl;     
226    std::string uniqueSeriesIdentifier;
227  
228    for (gdcm::DirListType::iterator it = fileNames.begin();  
229                                     it != fileNames.end();
230                                   ++it)
231    {
232       std::cout << "File Name : " << *it << std::endl;
233       f = gdcm::File::New();
234       f->SetLoadMode(gdcm::LD_ALL);
235       f->SetFileName( *it );
236       f->Load();
237         
238       uniqueSeriesIdentifier=s->CreateUniqueSeriesIdentifier(f);
239       std::cout << "                           [" <<
240                uniqueSeriesIdentifier  << "]" << std::endl;       
241       f->Delete();
242    }
243 */
244    
245    if (verbose)
246       std::cout << "------------------Print Break levels-----------------" << std::endl;
247
248    std::string userFileIdentifier; 
249    SortedFiles sf;
250
251    s->AddSeriesDetail(0x0010, 0x0010, false); // Patient's Name
252    s->AddSeriesDetail(0x0020, 0x000e, false); // Series Instance UID
253    s->AddSeriesDetail(0x0020, 0x0032, false); // Image Position (Patient)     
254    s->AddSeriesDetail(0x0018, 0x1060, true);  // Trigger Time (true: convert to keep numerical order)
255    s->AddSeriesDetail(0x0018, 0x1312, false); // In-plane Phase Encoding Direction 
256       
257    for (gdcm::DirListType::iterator it = fileNames.begin();  
258                                     it != fileNames.end();
259                                   ++it)
260    {
261       f = gdcm::File::New();
262       f->SetLoadMode(loadMode);
263       f->SetFileName( *it );
264       f->Load();
265       
266       // keep only requested Series
267       std::string strSeriesNumber;
268       int seriesNumber;
269       int j;
270       
271       bool keep = false;
272       if (nbSeriesToKeep != 0)
273       {     
274          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
275          seriesNumber = atoi( strSeriesNumber.c_str() );
276          for (j=0;j<nbSeriesToKeep; j++)
277          {
278             if(seriesNumber == seriesToKeep[j])
279             {
280                keep = true;
281                break;
282             }
283          }
284          if ( !keep)
285          {
286             f->Delete();
287             continue;
288          } 
289       }
290       // drop all unrequested Series
291       bool drop = false;
292       if (nbSeriesToDrop != 0)
293       {     
294          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
295          seriesNumber = atoi( strSeriesNumber.c_str() );
296          for (j=0;j<nbSeriesToDrop; j++)
297          {
298             if(seriesNumber == seriesToDrop[j])
299             { 
300                drop = true;
301                break;
302             }
303         }
304         if (drop)
305         {
306            f->Delete();
307            continue;
308         }
309       }      
310
311       userFileIdentifier=s->CreateUserDefinedFileIdentifier(f); 
312      // userFileIdentifier += "_";
313       //userFileIdentifier += *it;       
314       
315       tokens.clear();
316       gdcm::Util::Tokenize (userFileIdentifier, tokens, "_"); 
317    
318       if ( tokens[3] == "gdcmUnfound")  // sometimes Trigger Time is not found. CreateUserDefinedFileIdentifier is not aware of the pb.
319       {
320          tokens[3] = gdcm::Util::GetName( *it );
321          userFileIdentifier = tokens[0] + "_" + tokens[1] + "_" + tokens[2] + "_" + tokens[3] + "_" + tokens[4];
322       }   
323  
324        std::cout << "                           [" <<
325               userFileIdentifier  << "]" << std::endl;
326                
327       // storing in a map ensures automatic sorting !      
328       sf[userFileIdentifier] = f;
329    }
330       
331    std::string fullFilename, lastFilename;
332    std::string previousPatientName, currentPatientName;
333    std::string previousSerieInstanceUID, currentSerieInstanceUID;
334    std::string previousImagePosition, currentImagePosition;
335    std::string previousPhaseEncodingDirection, currentPhaseEncodingDirection;
336    std::string previousTriggerTime, currentTriggerTime;
337       
338    std::string writeDir, currentWriteDir;
339    std::string currentPatientWriteDir, currentSerieWriteDir, 
340                currentPositionWriteDir, currentPhaseEncodingDirectionWriteDir;
341
342    std::string fullWriteFilename;
343    std::string strExtent(extent); 
344            
345    writeDir = gdcm::Util::NormalizePath(dirNameout);     
346    SortedFiles::iterator it2;
347  
348    previousPatientName            = "";
349    previousSerieInstanceUID       = "";   
350    previousImagePosition          = "";
351    previousPhaseEncodingDirection = "";
352    previousTriggerTime            = "";
353    
354    int sliceIndex = 0; // Is incremented *at the beginning* of processing
355    int frameIndex = 1;
356    int flag       = 0;
357        
358    gdcm::File *currentFile;
359      
360    for (it2 = sf.begin() ; it2 != sf.end(); ++it2)
361    {  
362       currentFile = it2->second;
363        
364       fullFilename =  currentFile->GetFileName();
365       lastFilename =  gdcm::Util::GetName( fullFilename ); 
366       std::cout << "Try to write [" <<lastFilename << "]" << std::endl;
367      
368       tokens.clear();
369       gdcm::Util::Tokenize (it2->first, tokens, "_");
370       
371       currentPatientName            = tokens[0];
372       currentSerieInstanceUID       = tokens[1];
373       currentImagePosition          = tokens[2];
374       currentTriggerTime            = tokens[3];
375       currentPhaseEncodingDirection = tokens[4];           
376       
377       if ( currentImagePosition[0] == '-')
378           currentImagePosition[0] = 'M';
379       if ( currentImagePosition[0] == '+')
380           currentImagePosition[0] = 'P'; 
381       
382       if (previousPatientName != currentPatientName)
383       {
384          previousPatientName = currentPatientName;
385          if (verbose)   
386             std::cout << "==== new Patient  [" << currentPatientName  << "]" << std::endl;
387     
388          previousPatientName            = currentPatientName;
389          previousSerieInstanceUID       = ""; //currentSerieInstanceUID;
390          previousImagePosition          = ""; //currentImagePosition;
391          previousTriggerTime            = "";
392          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
393   
394          currentPatientWriteDir = writeDir + currentPatientName;
395          //if ( ! gdcm::DirList::IsDirectory(currentPatientWriteDir) )
396            {
397               systemCommand   = "mkdir " + currentPatientWriteDir;
398               if (verbose)
399                  std::cout << systemCommand << std::endl;
400               system ( systemCommand.c_str() );
401          }
402       }
403
404       if (previousSerieInstanceUID != currentSerieInstanceUID)
405       {        
406          if (verbose)   
407             std::cout << "==== === new Serie [" << currentSerieInstanceUID << "]"
408                       << std::endl;
409          if (split)
410          {
411              currentSerieWriteDir  = currentPatientWriteDir + gdcm::GDCM_FILESEPARATOR
412                              + currentSerieInstanceUID;
413              systemCommand   = "mkdir " + currentSerieWriteDir;  
414              system (systemCommand.c_str());
415          }
416          previousSerieInstanceUID       = currentSerieInstanceUID;
417          previousImagePosition          = ""; //currentImagePosition;
418          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
419       }
420
421       if (previousImagePosition != currentImagePosition)
422       {
423          frameIndex = 1;
424          flag = 0;        
425          if (verbose)   
426             std::cout << "=== === === new Position [" << currentImagePosition  << "]"
427                       << std::endl;
428          if (split)
429          {
430              currentPositionWriteDir  = currentSerieWriteDir + gdcm::GDCM_FILESEPARATOR
431                              + currentImagePosition;
432              systemCommand   = "mkdir " + currentPositionWriteDir;     
433              system (systemCommand.c_str()); 
434          }
435          previousImagePosition          = currentImagePosition;
436          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
437          if (split)
438             sliceIndex = 1; // only *one* slice in a given directory
439          else
440             sliceIndex += 1;
441       }      
442
443 // We don't split on Row/Column!
444 /*
445       if (previousPhaseEncodingDirection != currentPhaseEncodingDirection)
446       {        
447          if (verbose)   
448             std::cout << "==== === === === new PhaseEncodingDirection [" 
449                       << currentPhaseEncodingDirection  << "]" << std::endl;
450       
451          if (split)
452          {
453              currentPhaseEncodingDirectionWriteDir  = currentPositionWriteDir 
454                              + gdcm::GDCM_FILESEPARATOR
455                              + currentPhaseEncodingDirection;
456              systemCommand   = "mkdir " + currentPhaseEncodingDirectionWriteDir;     
457              system (systemCommand.c_str());     
458          }      
459     
460          previousPhaseEncodingDirection = currentPhaseEncodingDirection;
461       } 
462 */    
463       
464       if (verbose)
465          std::cout << "--- --- --- --- --- " << (it2->second)->GetFileName() 
466                    << std::endl;
467    
468       if ( gdcm::Debug::GetDebugFlag())
469          std::cout << "--- --- --- --- --- " << it2->first << "  " 
470                    << (it2->second)->GetFileName() << " " 
471                    << gdcm::Util::GetName( fullFilename ) << std::endl;           
472       
473       // Transform the image to be 'Brucker-Like'
474       // ----------------------------------------   
475     
476       // Deal with 0x0019, 0x1000 : 'FOV'
477       int nX = currentFile->GetXSize();
478       int nY = currentFile->GetYSize();
479       float pxSzX = currentFile->GetXSpacing();
480       float pxSzY = currentFile->GetYSpacing();
481       char fov[64];
482       sprintf(fov, "%f\\%f",nX*pxSzX, nY*pxSzY);
483       currentFile->InsertEntryString(fov, 0x0019, 0x1000, "DS");
484      
485       // Deal with 0x0020, 0x0012 : 'SESSION INDEX'  (Acquisition Number)
486       std::string chSessionIndex;
487       // CLEANME
488       if (currentPhaseEncodingDirection == "COL" || currentPhaseEncodingDirection == "COL " || currentPhaseEncodingDirection == " COL")
489          chSessionIndex = "1";
490       else if (currentPhaseEncodingDirection == "RAW" || currentPhaseEncodingDirection == "RAW "|| currentPhaseEncodingDirection == " RAW")
491          chSessionIndex = "2"; 
492       else
493       {
494          std::cout << "====================== PhaseEncodingDirection "
495                    << " neither COL nor RAW (?!?) : [ "
496                    << currentPhaseEncodingDirection << "]" << std::endl;
497          chSessionIndex = "2";
498       }
499       currentFile->InsertEntryString(chSessionIndex, 0x0020, 0x0012, "IS");
500    
501       // Deal with  0x0021, 0x1020 : 'SLICE INDEX'
502       char chSliceIndex[5];
503       sprintf(chSliceIndex, "%04d", sliceIndex);
504       std::string strChSliceIndex(chSliceIndex);
505       currentFile->InsertEntryString(strChSliceIndex, 0x0021, 0x1020, "IS");
506        
507       // Deal with  0x0021, 0x1040 : 'FRAME INDEX' 
508       char chFrameIndex[5];
509       sprintf(chFrameIndex, "%04d", frameIndex);
510       currentFile->InsertEntryString(chFrameIndex, 0x0021, 0x1040, "IS"); 
511       
512       if (flag == 0)
513       {       
514          flag = 1;
515       }
516       else
517       {
518          frameIndex++;
519          flag = 0;
520       }
521                     
522       if (split)
523       
524          //fullWriteFilename = currentPhaseEncodingDirectionWriteDir + gdcm::GDCM_FILESEPARATOR 
525          //                                + lastFilename + strExtent;      
526          fullWriteFilename = currentPositionWriteDir + gdcm::GDCM_FILESEPARATOR 
527                                          + lastFilename + strExtent; 
528       else
529          fullWriteFilename = currentPatientWriteDir + gdcm::GDCM_FILESEPARATOR 
530                                          + lastFilename + strExtent; 
531       
532       /*           
533       systemCommand  = "cp " + fullFilename + " " + fullWriteFilename;
534       std::cout << systemCommand << std::endl;
535       system (  systemCommand.c_str() );
536       */
537             
538       // Load the pixels in RAM.    
539       
540       fh = gdcm::FileHelper::New(currentFile);     
541       fh->GetImageDataRaw(); // Don't convert (Gray Pixels + LUT) into (RGB pixels) ?!?
542       fh->SetWriteTypeToDcmExplVR();
543       if (!fh->Write(fullWriteFilename))
544       {
545          std::cout << "Fail to write :[" << fullWriteFilename << "]"
546                    << std::endl;
547       } 
548       fh->Delete();                
549    }
550  }