]> Creatis software - gdcm.git/blob - Example/SplitIntoDirectories.cxx
Allow user to ask to use SerieDescription+serieNumber instead od
[gdcm.git] / Example / SplitIntoDirectories.cxx
1 /*=========================================================================
2
3   Program:   gdcm
4   Module:    $RCSfile: SplitIntoDirectories.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/10/19 14:12:31 $
7   Version:   $Revision: 1.3 $
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   */  
38
39 typedef std::map<std::string, GDCM_NAME_SPACE::File*> SortedFiles;
40
41 int main(int argc, char *argv[]) 
42 {
43    START_USAGE(usage)
44    " \n SplitIntoDirectories :\n                                              ",
45    " - explores recursively the given directory,                              ",
46    " - keeps the requested series / drops the unrequested series              ",
47    " - orders the gdcm-readable found Files according to their                ",
48    "           (0x0010, 0x0010) Patient's Name                                ",
49    "           (0x0020, 0x000d) Study Instance UID                            ",   
50    "           (0x0020, 0x000e) Series Instance UID                           ",
51    " - fills a tree-like structure of directories as :                        ",
52    "        - Patient                                                         ",
53    "        -- Study                                                          ",
54    "        --- Serie                                                         ",
55    "                                                                          ",
56    " usage:                                                                   ",
57    " -----                                                                    ",
58    " SplitIntoDirectories                                                     ",
59    "                  dirin=rootDirectoryName                                 ",
60    "                  dirout=outputDirectoryName                              ",
61    "                  {  [keep= list of seriesNumber to process]              ",
62    "                   | [drop= list of seriesNumber to ignore] }             ",
63    "                  [listonly]  [skel] [seriedescr]                         ",
64    "                  [noshadowseq][noshadow][noseq] [verbose] [debug]        ",
65    "                                                                          ",
66    " dirout : will be created if doesn't exist                                ",
67    " keep : if user wants to process a limited number of series               ",
68    "            he gives the list of 'SeriesNumber' (tag 0020|0011)           ",
69    " drop : if user wants to ignore a limited number of series                ",
70    "            he gives the list of 'SeriesNumber' (tag 0020|0011)           ",
71    "        SeriesNumber are short enough to be human readable                ",
72    "        e.g : 1030,1035,1043                                              ",
73    " seriedescr : SerieDescription+SerieNumber use for directory name         ",
74    "              (instead of SeriesInstanceUID)                              ",
75    " skel     : name skeleton eg : patName_1.nema -> skel=patName_            ",
76    " noshadowseq: user doesn't want to load Private Sequences                 ",
77    " noshadow : user doesn't want to load Private groups (odd number)         ",
78    " noseq    : user doesn't want to load Sequences                           ",
79    " verbose  : user wants to run the program in 'verbose mode'               ",
80    " debug    : *developer*  wants to run the program in 'debug mode'         ",
81    FINISH_USAGE
82
83
84    // VERY IMPORTANT :
85    // Respect this order while creating 'UserFileIdentifier'
86    // (mind the order of the 'AddSeriesDetail' !)
87    
88    enum Index
89    {
90       IND_PatientName,
91       IND_StudyInstanceUID,
92       IND_SerieInstanceUID,
93       IND_SerieDescription,
94       IND_SerieNumber,
95       IND_FileName
96    };
97       
98    std::cout << "... inside " << argv[0] << std::endl;
99    
100    // ----- Initialize Arguments Manager ------
101       
102    GDCM_NAME_SPACE::ArgMgr *am = new GDCM_NAME_SPACE::ArgMgr(argc, argv);
103   
104    if (argc == 1 || am->ArgMgrDefined("usage")) 
105    {
106       am->ArgMgrUsage(usage); // Display 'usage'
107       delete am;
108       return 0;
109    }
110
111    const char *dirNamein;   
112    dirNamein  = am->ArgMgrGetString("dirin","."); 
113
114    const char *dirNameout;   
115    dirNameout  = am->ArgMgrGetString("dirout",".");  
116    
117    int loadMode = GDCM_NAME_SPACE::LD_ALL;
118    if ( am->ArgMgrDefined("noshadowseq") )
119       loadMode |= GDCM_NAME_SPACE::LD_NOSHADOWSEQ;
120    else 
121    {
122    if ( am->ArgMgrDefined("noshadow") )
123          loadMode |= GDCM_NAME_SPACE::LD_NOSHADOW;
124       if ( am->ArgMgrDefined("noseq") )
125          loadMode |= GDCM_NAME_SPACE::LD_NOSEQ;
126    }
127
128    if (am->ArgMgrDefined("debug"))
129       GDCM_NAME_SPACE::Debug::DebugOn();
130
131    bool verbose    = ( 0 != am->ArgMgrDefined("verbose") );
132    bool listonly   = ( 0 != am->ArgMgrDefined("listonly") );
133    bool seriedescr = ( 0 != am->ArgMgrDefined("seriedescr") );
134             
135    int nbSeriesToKeep;
136    int *seriesToKeep = am->ArgMgrGetListOfInt("keep", &nbSeriesToKeep);
137    int nbSeriesToDrop;
138    int *seriesToDrop = am->ArgMgrGetListOfInt("drop", &nbSeriesToDrop);
139  
140    if ( nbSeriesToKeep!=0 && nbSeriesToDrop!=0)
141    {
142       std::cout << "KEEP and DROP are mutually exclusive !" << std::endl;
143       delete am;
144       return 0;         
145    }
146
147    bool hasSkel = ( 0 != am->ArgMgrDefined("hasSkel") );    
148    const char *skel;
149    if (hasSkel)
150       skel = am->ArgMgrGetString("skel");   
151       
152       
153    const char *input   = am->ArgMgrGetString("input","DCM");
154    
155    // if unused Param we give up
156    if ( am->ArgMgrPrintUnusedLabels() )
157    { 
158       am->ArgMgrUsage(usage);
159       delete am;
160       return 0;
161    }
162    delete am;  // we don't need Argument Manager any longer
163
164    // ----- Begin Processing -----
165    
166      
167    // --> Check supposed-to-be-directory names
168    
169    if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(dirNamein) )
170    {
171       std::cout << "KO : [" << dirNamein << "] is not a Directory."
172                 << std::endl;
173       return 0;
174
175    }
176    else
177    {
178       std::cout << "OK : [" << dirNamein << "] is a Directory." << std::endl;
179    }
180
181    std::string systemCommand;
182    
183    std::cout << "Check for output directory :[" << dirNameout << "]."
184              <<std::endl;
185    if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(dirNameout) )    // dirout not found
186    {
187       std::string strDirNameout(dirNameout);          // to please gcc 4
188       systemCommand = "mkdir " +strDirNameout;        // create it!
189       if (verbose)
190          std::cout << systemCommand << std::endl;
191       system (systemCommand.c_str());
192       if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(dirNameout) ) // be sure it worked
193       {
194           std::cout << "KO : not a dir : [" << dirNameout << "] (creation failure ?)" 
195                     << std::endl;
196       return 0;
197
198       }
199       else
200       {
201         std::cout << "Directory [" << dirNameout << "] created." << std::endl;
202       }
203    }
204    else
205    {
206        std::cout << "Output Directory [" << dirNameout 
207                  << "] already exists; Used as is."
208                  << std::endl;
209    }
210    // --> End of checking supposed-to-be-directory names
211        
212    std::string strDirNamein(dirNamein);
213    // true ; get recursively the list of files
214    GDCM_NAME_SPACE::DirList dirList(strDirNamein, true); 
215    
216    if (listonly)
217    {
218       std::cout << "------------List of found files ------------" << std::endl;
219       dirList.Print();
220       std::cout << std::endl;
221    }
222
223
224 // ======================================= The job starts here =========================
225    
226    GDCM_NAME_SPACE::DirListType fileNames;
227    fileNames = dirList.GetFilenames();
228
229    GDCM_NAME_SPACE::SerieHelper *s;     // Needed to use SerieHelper::AddSeriesDetail()
230    s = GDCM_NAME_SPACE::SerieHelper::New();
231
232    std::string token = "%%%"; // Hope it's enough!
233   
234    GDCM_NAME_SPACE::File *f;
235    std::vector<std::string> tokens;
236    std::vector<std::string> tokensForFileName;
237    
238    if (verbose)
239       std::cout << "------------------Print Break levels-----------------" << std::endl;
240
241    std::string userFileIdentifier;
242    SortedFiles sf;
243
244
245    // VERY IMPORTANT :
246    // Respect the order you choosed in 'enum Index' !
247  
248 /*
249    enum Index
250    {
251       IND_PatientName,
252       IND_StudyInstanceUID,
253       IND_SerieInstanceUID,
254       IND_SerieDescription,
255       IND_SerieNumber,
256       IND_FileName
257    }; 
258 */     
259    s->AddSeriesDetail(0x0010, 0x0010, false); // Patient's Name (false : no convert)
260    
261    // You may prefer 0020 0010  Study ID
262    // use :
263    // s->AddSeriesDetail(0x0020, 0x0010, true); 
264    // Avoid using 0008 0020 Study Date, 
265    // since you may have more than one study, for a given Patient, at a given Date!
266    // or the field may be empty!   
267    s->AddSeriesDetail(0x0020, 0x000d, false); // Study Instance UID (false : no convert)
268
269
270    // You may prefer 0020 0011 Series Number
271    // use :
272    // s->AddSeriesDetail(0x0020, 0x0011, true);    
273    s->AddSeriesDetail(0x0020, 0x000e, false); // Series Instance UID (false : no convert)
274
275    s->AddSeriesDetail(0x0008, 0x103e, false); // Serie Description
276    s->AddSeriesDetail(0x0020, 0x0011, false);  // Serie Number (more than 1 serie may have the same Descr. don't 'convert!)
277    
278    // Feel free to add more fields, if they can help a suitable (for you)
279    // image sorting
280
281 // Loop on all the gdcm-readable files
282    for (GDCM_NAME_SPACE::DirListType::iterator it = fileNames.begin();
283                                     it != fileNames.end();
284                                   ++it)
285    {
286       f = GDCM_NAME_SPACE::File::New();
287       f->SetLoadMode(loadMode);
288       f->SetFileName( *it );
289       f->Load();
290
291       std::string strSeriesNumber;
292       int seriesNumber;
293       int j;
294
295       // keep only requested Series
296       bool keep = false;
297       if (nbSeriesToKeep != 0)
298       {
299          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
300          seriesNumber = atoi( strSeriesNumber.c_str() );
301          for (j=0; j<nbSeriesToKeep; j++)
302          {
303             if(seriesNumber == seriesToKeep[j])
304             {
305                keep = true;
306                break;
307             }
308          }
309          if ( !keep)
310          {
311             f->Delete();
312             continue;
313          }
314       }
315       // drop all unrequested Series
316       bool drop = false;
317       if (nbSeriesToDrop != 0)
318       {     
319          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
320          seriesNumber = atoi( strSeriesNumber.c_str() );
321          for (j=0;j<nbSeriesToDrop; j++)
322          {
323             if(seriesNumber == seriesToDrop[j])
324             { 
325                drop = true;
326                break;
327             }
328         }
329         if (drop)
330         {
331            f->Delete();
332            continue;
333         }
334       }
335
336       userFileIdentifier=s->CreateUserDefinedFileIdentifier(f);
337       tokens.clear();
338       GDCM_NAME_SPACE::Util::Tokenize (userFileIdentifier, tokens, token);
339
340       //int imageNum; // Within FileName
341       char newName[1024];
342       
343       ///this is a trick to build up a lexicographical compliant name :
344       ///     eg : fich001.ima vs fich100.ima as opposed to fich1.ima vs fich100.ima
345       std::string name = GDCM_NAME_SPACE::Util::GetName( *it );
346
347       if (hasSkel)
348       {
349          int imageNum; // Within FileName
350          GDCM_NAME_SPACE::Util::Tokenize (name, tokensForFileName, skel);
351          imageNum = atoi ( tokensForFileName[0].c_str() );
352          // probabely we could write something much more complicated using C++ !
353          sprintf (newName, "%s%06d.dcm", skel, imageNum);
354          tokens[IND_FileName] = newName;
355          tokensForFileName.clear();
356        }
357        else
358        {
359          tokens[IND_FileName] = name;
360        }   
361     
362          // Patient's Name
363          // Study Instance UID 
364          // Series Instance UID
365          // file Name
366
367       userFileIdentifier = tokens[IND_PatientName]      + token +
368                            tokens[IND_StudyInstanceUID] + token + 
369                            tokens[IND_SerieInstanceUID] + token +
370
371                            tokens[IND_SerieDescription] + token +
372                            tokens[IND_SerieNumber]      + token +
373                            tokens[IND_FileName];
374          
375       if (verbose) 
376          std::cout << "[" << userFileIdentifier  << "] : " << *it << std::endl;
377                
378       // storing in a map ensures automatic sorting !      
379       sf[userFileIdentifier] = f;
380    }
381    
382    if (verbose)
383       std::cout << "  " << std::endl;
384       
385    std::string fullFilename, lastFilename;
386    std::string previousPatientName, currentPatientName;
387    std::string previousStudyInstanceUID, currentStudyInstanceUID;   
388    std::string previousSerieInstanceUID, currentSerieInstanceUID;
389    
390    std::string currentSerieDescription, currentSerieNumber;   
391       
392    std::string writeDir, currentWriteDir;
393    std::string currentPatientWriteDir;
394    std::string currentStudyWriteDir;
395    std::string currentSerieWriteDir; 
396
397    std::string fullWriteFilename;
398            
399    writeDir = GDCM_NAME_SPACE::Util::NormalizePath(dirNameout);     
400    SortedFiles::iterator it2;
401  
402    previousPatientName            = "";
403    previousStudyInstanceUID       = "";    
404    previousSerieInstanceUID       = "";   
405        
406    GDCM_NAME_SPACE::File *currentFile;
407      
408    for (it2 = sf.begin() ; it2 != sf.end(); ++it2)
409    {  
410       currentFile = it2->second;
411        
412       fullFilename =  currentFile->GetFileName();
413       lastFilename =  GDCM_NAME_SPACE::Util::GetName( fullFilename );
414       if (verbose) 
415       std::cout <<" ------------------------------------------------------------------------------" 
416                 << std::endl << " Deal with [" << it2->first << "] : [" <<fullFilename << "]" 
417                 << std::endl;
418      
419       tokens.clear();
420       GDCM_NAME_SPACE::Util::Tokenize (it2->first, tokens, token);
421       
422       currentPatientName            = tokens[IND_PatientName];
423       currentStudyInstanceUID       = tokens[IND_StudyInstanceUID];      
424       currentSerieInstanceUID       = tokens[IND_SerieInstanceUID];
425       currentSerieDescription       = tokens[IND_SerieDescription];
426       currentSerieNumber            = tokens[IND_SerieNumber];
427              
428       if (previousPatientName != currentPatientName)
429       {  
430          previousPatientName = currentPatientName;
431          if (verbose)   
432             std::cout << "==== new Patient  [" << currentPatientName  << "]" << std::endl;
433     
434          previousPatientName            = currentPatientName;
435          previousStudyInstanceUID       = ""; 
436          previousSerieInstanceUID       = "";
437   
438          currentPatientWriteDir = writeDir + currentPatientName;
439
440          systemCommand   = "mkdir " + currentPatientWriteDir;
441          if (verbose || listonly)
442             std::cout << "[" << systemCommand << "]" << std::endl;
443          if (!listonly)               
444             system ( systemCommand.c_str() );
445       }
446       
447       if (previousStudyInstanceUID != currentStudyInstanceUID)
448       {        
449          previousStudyInstanceUID       = currentStudyInstanceUID;
450          if (verbose)   
451             std::cout << "==== === new Study [" << currentStudyInstanceUID << "]"
452                       << std::endl;      
453
454          currentStudyWriteDir  = currentPatientWriteDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR
455                              + currentStudyInstanceUID;
456          systemCommand   = "mkdir " + currentStudyWriteDir;
457          
458          if (listonly)
459            std::cout << "[" << systemCommand << "]" << std::endl;         
460          else            
461             system (systemCommand.c_str());
462
463       }  
464       
465       if (previousSerieInstanceUID != currentSerieInstanceUID)
466       {        
467          previousSerieInstanceUID       = currentSerieInstanceUID;
468          if (verbose)   
469             std::cout << "=== ==== === new Serie [" << currentSerieInstanceUID << "]"
470                       << std::endl;
471                             
472          if (seriedescr) // more human readable!
473             currentSerieWriteDir  = currentStudyWriteDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR
474                                   + currentSerieDescription + "_" + currentSerieNumber;
475          else
476             currentSerieWriteDir  = currentStudyWriteDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR
477                                   + currentSerieInstanceUID;         
478                                  
479          systemCommand   = "mkdir " + currentSerieWriteDir;
480          
481          if (listonly)
482             std::cout << "[" << systemCommand << "]" << std::endl;         
483          else             
484             system (systemCommand.c_str());
485       }            
486    
487       if ( GDCM_NAME_SPACE::Debug::GetDebugFlag())
488          std::cout << "--- --- --- --- --- " << it2->first << "  " 
489                    << (it2->second)->GetFileName() << " " 
490                    << GDCM_NAME_SPACE::Util::GetName( fullFilename ) << std::endl;
491  
492       // If you want to create file names of your own, here is the place!
493       // Just replace 'lastFilename' by anything that's better for you.               
494       fullWriteFilename = currentSerieWriteDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR 
495                                          + lastFilename; 
496
497       systemCommand   = "cp " + fullFilename + " " + fullWriteFilename;
498       
499       if (listonly)
500          std::cout << "[" << systemCommand << "]" << std::endl;         
501       else             
502          system (systemCommand.c_str());
503
504    }
505    return 0;
506  }
507