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