]> Creatis software - gdcm.git/blob - Example/SplitIntoXCoherentDirectories.cxx
like exXCoherentFileSet, but user is allowed to 'COPY' the files in a Directory
[gdcm.git] / Example / SplitIntoXCoherentDirectories.cxx
1 /*=========================================================================
2   
3   Program:   gdcm
4   Module:    $RCSfile: SplitIntoXCoherentDirectories.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/10/01 09:40:32 $
7   Version:   $Revision: 1.1 $
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 "gdcmSerieHelper.h"
19 #include "gdcmFileHelper.h"
20 #include "gdcmFile.h"
21 #include "gdcmDebug.h"
22 #include <iostream>
23 #include "gdcmDirList.h"
24 #include "gdcmUtil.h"
25 #include "gdcmArgMgr.h"
26 #include "gdcmDictSet.h"  // for GetName 
27 int main(int argc, char *argv[])
28 {
29
30    START_USAGE(usage)
31    "\n exXCoherentFileSet :\n                                                 ",
32    "Shows the various 'XCoherent' Filesets within a directory                 ",
33    "Optionaly copis the images in a Directories tree                          ",
34    "usage: exXCoherentFileSet {dirin=inputDirectoryName}                      ",
35    "                           dirout=outputDirectoryName                     ",
36    "                       { tag=group-elem | pos | ori } [sort]              ",
37    "                       [{ write | copy }] [studyUID = ]                   ", 
38    "                       [ { [noshadowseq] | [noshadow][noseq] } ] [debug]  ",
39    "                                                                          ",
40    "       dirin : user wants to analyze *all* the files                      ",
41    "                            within the directory                          ",
42    "       copy  : user wants to copy the files into a directories tree       ",
43    "       write : user wants to rewrite the files into a directories tree    ",
44    "               each directory with the same 'Series Instance UID'         ", 
45    "       dirout : will be created if doesn't exist                          ",
46    "       pos  : user wants to split each Single SerieUID Fileset on the     ",
47    "                         'Image Position '                                ",
48    "       ori  : user wants to split each Single SerieUID Fileset on the     ",
49    "                         'Image Orientation '                             ",
50    "       tag : group-elem    (in hexa, no space)                            ",
51    "                       the user wants to split on                         ",
52    "       sort :  user wants FileHelper to sort the images                   ",
53    "               Warning : will probabely crah if sort has no meaning       ",
54    "                (not only look at image names)                            ",
55    "       studyUID   : *aware* user wants to add the serie                   ",
56    "                                             to an already existing study ",
57    "       verbose    : user wants to run the program in 'verbose mode'       ",
58    "       debug      : developper wants to run the program in 'debug mode'   ",
59    FINISH_USAGE
60
61    // ----- Initialize Arguments Manager ------
62
63    GDCM_NAME_SPACE::ArgMgr *am = new GDCM_NAME_SPACE::ArgMgr(argc, argv);
64
65    if (am->ArgMgrDefined("usage") || argc == 1)
66    {
67       am->ArgMgrUsage(usage); // Display 'usage'
68       delete am;
69       return 0;
70    }
71
72    if (am->ArgMgrDefined("debug"))
73       GDCM_NAME_SPACE::Debug::DebugOn();
74  
75    int loadMode;
76    int maxSize;
77    
78    const char *dirName  = am->ArgMgrGetString("dirin");
79    if (dirName == 0)
80    {
81        std::cout <<std::endl
82                  << "'dirin=' must be present;" 
83                  <<  std::endl;
84        am->ArgMgrUsage(usage); // Display 'usage'  
85        delete am;
86        return 0;
87    }
88
89    const char *dirNameout;   
90    dirNameout  = am->ArgMgrGetString("dirout",".");
91
92    bool pos  =    ( 0 != am->ArgMgrDefined("pos") ); 
93    bool ori  =    ( 0 != am->ArgMgrDefined("ori") );   
94    bool sort =    ( 0 != am->ArgMgrDefined("sort") );
95    bool copy =    ( 0 != am->ArgMgrDefined("copy") );
96    bool write =   ( 0 != am->ArgMgrDefined("write") );   
97    bool verbose = ( 0 != am->ArgMgrDefined("verbose") );
98    bool tag     = ( 0 != am->ArgMgrDefined("tag") );
99    
100    if( copy && write )
101    {
102       std::cout << "COPY and WRITE are mutually exclusive" << std::endl;
103       delete am;
104       return 0;      
105    }   
106
107    if( (tag && (pos || ori)) || (pos && (tag || ori)) || (ori && (tag || pos)) )
108    {
109       std::cout << " POS, ORI and TAG are mutually exclusive" << std::endl;
110       delete am;
111       return 0;      
112    }
113    
114    if( (!tag && !pos && !ori))
115    {
116       std::cout << " One of POS, ORI and TAG is mandatory!" << std::endl;
117       delete am;
118       return 0;      
119    }         
120    int nb;
121    uint16_t *groupelem;
122    if (tag)
123    {
124       groupelem = am->ArgMgrGetXInt16Enum("tag", &nb);
125       if (nb != 1)
126       {
127          std::cout << "TAG : one and only one group,elem!" << std::endl;
128          delete am;
129          return 0;
130       }
131    }      
132
133    bool userDefinedStudy = ( 0 != am->ArgMgrDefined("userDefinedStudy") );
134    const char *studyUID  = am->ArgMgrGetString("studyUID");
135             
136    /* if unused Param we give up */
137    if ( am->ArgMgrPrintUnusedLabels() )
138    {
139       am->ArgMgrUsage(usage);
140       delete am;
141       return 0;
142    } 
143  
144    delete am;  // ------ we don't need Arguments Manager any longer ------
145
146
147       
148    GDCM_NAME_SPACE::SerieHelper *s;  
149    s = GDCM_NAME_SPACE::SerieHelper::New();
150    
151    GDCM_NAME_SPACE::File *f;
152    
153    GDCM_NAME_SPACE::DirList dirlist(dirName, true); // recursive exploration
154    GDCM_NAME_SPACE::DirListType fileNames = dirlist.GetFilenames();
155
156    GDCM_NAME_SPACE::FileList *l = new GDCM_NAME_SPACE::FileList;
157 // Loop on all the gdcm-readable files
158    for (GDCM_NAME_SPACE::DirListType::iterator it = fileNames.begin();
159                                     it != fileNames.end();
160                                   ++it)
161    {
162       if (verbose)
163          std::cout << *it << std::endl;
164  
165       if (write) {
166          loadMode = GDCM_NAME_SPACE::LD_ALL; // load any DataElement
167           maxSize  = 0x7fff;                  // load any length
168       } else {
169          loadMode = GDCM_NAME_SPACE::LD_NOSEQ | GDCM_NAME_SPACE::LD_NOSHADOW ; 
170          maxSize  = 0x0100;      
171       }
172
173       f = GDCM_NAME_SPACE::File::New();
174       f->SetLoadMode(loadMode);   
175       f->SetMaxSizeLoadEntry(maxSize); 
176       f->SetFileName( *it );
177       f->Load();
178       l->push_back(f);     
179    }
180
181    std::string systemCommand;
182    std::string filenameout;   
183    if (write || copy) { 
184       if (verbose)
185          std::cout << "Check for output directory :[" << dirNameout << "]."
186                    <<std::endl;
187       if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(dirNameout) )    // dirout not found
188       {
189          std::string strDirNameout(dirNameout);          // to please gcc 4
190          systemCommand = "mkdir " +strDirNameout;        // create it!
191          if (verbose)
192             std::cout << systemCommand << std::endl;
193          system (systemCommand.c_str());
194          if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(dirNameout) ) // be sure it worked
195          {
196              std::cout << "KO : not a dir : [" << dirNameout << "] (creation failure ?)" 
197                        << std::endl;
198          return 0;
199          }
200          else
201          {
202             if (verbose)
203                std::cout << "Directory [" << dirNameout << "] created." << std::endl;
204          }
205       }
206       else
207       {
208          if (verbose)
209             std::cout << "Output Directory [" << dirNameout 
210                       << "] already exists; Used as is."
211                       << std::endl;
212       }      
213    }
214    
215       // --> End of checking supposed-to-be-directory names
216
217    int nbFiles;
218    std::string fileName;
219
220    // For all the Single SerieUID Files Sets of the GDCM_NAME_SPACE::Serie
221
222    //GDCM_NAME_SPACE::FileList *l = s->GetFirstSingleSerieUIDFileSet();//===> Ignore 'Serie UID"
223
224    GDCM_NAME_SPACE::XCoherentFileSetmap xcm;
225
226    std::string serieUID;
227    std::string currentSerieWriteDir = "";
228    std::string xCoherentWriteDir = "";
229    std::string xCoherentName = ""; 
230    std::string serieDirectory;
231    std::string lastFilename;
232    std::string rep("_");
233    int controlCount = 0;
234    
235    // 'Study Instance UID'
236    // The user is allowed to create his own Study, 
237    //          keeping the same 'Study Instance UID' for various images
238    // The user may add images to a 'Manufacturer Study',
239    //          adding new Series to an already existing Study
240    std::string strStudyUID;
241    if (write) {
242       if ( !userDefinedStudy )
243          strStudyUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
244       else
245          strStudyUID = studyUID;
246    }
247
248 //   while (l) // for each 'Single SerieUID FileSet' //===> Ignore 'Serie UID"
249 //   { 
250       nbFiles = l->size() ;
251       if ( l->size() > 2 ) // ignore a Directory with less than 2 images.
252                            // Why not ? Just an example, for testing!
253       {
254           // Just not to make too many modif in the code
255           serieUID = "aaaa"; //s->GetCurrentSerieUIDFileSetUID();
256           GDCM_NAME_SPACE::Util::ReplaceSpecChar(serieUID, rep);
257  
258           // --- for write
259           if (write || copy)
260           {
261              currentSerieWriteDir = currentSerieWriteDir + dirNameout;
262              unsigned int l = strlen(dirNameout)-1;
263              if ( dirNameout[l] != '/'  &&  dirNameout[l] != '\\')
264                 currentSerieWriteDir = currentSerieWriteDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR;
265     
266              currentSerieWriteDir = currentSerieWriteDir + serieUID;
267              if (verbose)
268                 std::cout << "[" << currentSerieWriteDir<< "]" << std::endl;
269             // if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(currentSerieWriteDir) )
270              {     
271                 systemCommand   = "mkdir " + currentSerieWriteDir;
272                 system( systemCommand.c_str());
273                 if (verbose)
274                    std::cout <<  "1 " <<systemCommand << std::endl;
275              }
276          } 
277           // --- end for write
278     
279          std::cout << "Split the 'Single SerieUID' FileSet :[" 
280                    << serieUID
281                    << "]  " << nbFiles << " long" << std::endl;
282          std::cout << "-----------------------------------" << std::endl;
283   
284          if (ori) 
285             xcm = s->SplitOnOrientation(l);
286          else if (pos)
287             xcm = s->SplitOnPosition(l);
288          else if (groupelem != 0) {
289  
290             std:: cout << GDCM_NAME_SPACE::Global::GetDicts()->GetDefaultPubDict()->GetEntry(groupelem[0],groupelem[1])->GetName() << std::endl;
291  
292             xcm = s->SplitOnTagValue(l, groupelem[0],groupelem[1] );
293          }
294  
295          GDCM_NAME_SPACE::FileHelper *fh;
296  
297          for (GDCM_NAME_SPACE::XCoherentFileSetmap::iterator i = xcm.begin(); 
298                                                   i != xcm.end();
299                                                 ++i)
300          {
301             xCoherentName = (*i).first;
302             if (verbose)
303                std::cout << "xCoherentName = " << xCoherentName << std::endl;
304              GDCM_NAME_SPACE::Util::ReplaceSpecChar(xCoherentName, rep);
305              // --- for write
306              if (write || copy)
307              { 
308                 xCoherentWriteDir = currentSerieWriteDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR+ xCoherentName;
309                // if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(xCoherentWriteDir) )
310                 {      
311                    systemCommand   = "mkdir " + xCoherentWriteDir;
312                    system( systemCommand.c_str());
313                    if (verbose)
314                       std::cout << "2 " << systemCommand << std::endl;       
315                 }
316             } 
317             // --- end for write
318     
319             if (ori) 
320                std::cout << "Orientation : ";
321             else if (pos) 
322                std::cout << "Position : ";
323             else if (groupelem != 0)    
324                std::cout << "Tag (" << std::hex << groupelem[0]
325                          << "|" << groupelem[1] << ") value : ";
326             std::cout << "[" << (*i).first << "]" << std::endl;
327         
328             if (verbose)
329                std::cout << "xCoherentName [" << xCoherentName << "]" << std::endl;
330     
331            // Within a 'just to see' program, 
332            // OrderFileList() causes trouble, since some files
333            // (eg:MIP views) don't have 'Position', now considered as mandatory
334            // --> Activated on user demand.
335            
336             if (sort) {
337               s->OrderFileList((*i).second);  // sort the XCoherent Fileset
338               std::cout << "ZSpacing for the file set " << s->GetZSpacing()
339                         << std::endl;
340             } 
341
342             std::string strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
343
344             for (GDCM_NAME_SPACE::FileList::iterator it2 =  ((*i).second)->begin();
345                                           it2 != ((*i).second)->end();
346                                         ++it2)
347             {
348                controlCount ++;
349                fileName = (*it2)->GetFileName();
350                std::cout << "    " << fileName << std::endl;
351     
352                // --- for write
353                lastFilename =  GDCM_NAME_SPACE::Util::GetName( fileName );
354                filenameout = xCoherentWriteDir  + GDCM_NAME_SPACE::GDCM_FILESEPARATOR+ lastFilename;   
355                if (write)
356                {  
357                   fh = GDCM_NAME_SPACE::FileHelper::New( (*it2) );  
358                   fh->SetKeepOverlays( true );       
359                   fh->InsertEntryString(strSerieUID,0x0020,0x000e,"UI");
360                   unsigned int dataSize  = fh->GetImageDataRawSize();
361                   uint8_t *imageData = fh->GetImageDataRaw();// somewhat important : Loads the Pixels in memory !
362                   if (!imageData)
363                      std::cout << "fail to read [" << (*it2)->GetFileName() << std::endl; 
364                   fh->SetWriteTypeToDcmExplVR();
365                   fh->SetContentType(GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE);
366                   if (!fh->Write(filenameout))
367                   {
368                      std::cout << "Fail to write :[" << filenameout << "]"
369                                << std::endl;
370                   }
371                } 
372                else if (copy)
373                {
374                    systemCommand   = "cp " + fileName + " " + filenameout;
375                    system( systemCommand.c_str());
376                } 
377                if (verbose)
378                      std::cout << "3 " << systemCommand << std::endl;
379                fh->Delete();
380             } 
381
382             std::cout << std::endl;   
383          }
384       }
385      // l = s->GetNextSingleSerieUIDFileSet(); //===> Ignore 'Serie UID"
386     
387    if ( controlCount == 0 )
388       std::cout << "No suitable file was found!" << std::endl;
389  
390    s->Delete();
391    return 0;
392 }