]> Creatis software - gdcm.git/blob - Example/PhilipsToBrucker.cxx
Display some more informations
[gdcm.git] / Example / PhilipsToBrucker.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: PhilipsToBrucker.cxx,v $
5   Language:  C++
6   Date:      $Date: 2006/01/10 16:04:18 $
7   Version:   $Revision: 1.4 $
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     
176    std::string strDirNamein(dirNamein);
177    gdcm::DirList dirList(strDirNamein, true); // get recursively the list of files
178    
179 /*   
180    std::cout << "---------------List of found files ------------" << std::endl;
181    dirList.Print();
182  */   
183
184    gdcm::DirListType fileNames;
185    fileNames = dirList.GetFilenames();
186    gdcm::SerieHelper *s;              // Needed only to may use SerieHelper::AddSeriesDetail()
187    s = gdcm::SerieHelper::New();
188
189 /*       
190    std::cout << "---------------Print Serie--------------" << std::endl; 
191    s->SetDirectory(dirNamein, true); // true : recursive exploration 
192    s->SetUseSeriesDetails(true);  
193    s->AddSeriesDetail(0x0018, 0x1312);   
194    s->Print();
195 */
196   
197    gdcm::File *f;
198    gdcm::FileHelper *fh;
199 /*   
200    std::cout << "---------------Print Unique Series identifiers---------"  
201              << std::endl;     
202    std::string uniqueSeriesIdentifier;
203  
204    for (gdcm::DirListType::iterator it = fileNames.begin();  
205                                     it != fileNames.end();
206                                   ++it)
207    {
208       std::cout << "File Name : " << *it << std::endl;
209       f = gdcm::File::New();
210       f->SetLoadMode(gdcm::LD_ALL);
211       f->SetFileName( *it );
212       f->Load();
213         
214       uniqueSeriesIdentifier=s->CreateUniqueSeriesIdentifier(f);
215       std::cout << "                           [" <<
216                uniqueSeriesIdentifier  << "]" << std::endl;       
217       f->Delete();
218    }
219 */
220    
221    if (verbose)
222       std::cout << "------------------Print Break levels-----------------" 
223                 << std::endl;
224
225    std::string userFileIdentifier; 
226    SortedFiles sf;
227
228    s->AddSeriesDetail(0x0010, 0x0010, false); // Patient's Name
229    s->AddSeriesDetail(0x0020, 0x000e, false); // Series Instance UID
230    s->AddSeriesDetail(0x0020, 0x0032, false); // Image Position (Patient)     
231    s->AddSeriesDetail(0x0018, 0x1312, false); // In-plane Phase Encoding Direction 
232    s->AddSeriesDetail(0x0018, 0x1060, true);  // Trigger Time 
233    
234    for (gdcm::DirListType::iterator it = fileNames.begin();  
235                                     it != fileNames.end();
236                                   ++it)
237    {
238       f = gdcm::File::New();
239       f->SetLoadMode(loadMode);
240       f->SetFileName( *it );
241       f->Load();
242       
243       // keep only requested Series
244       std::string strSeriesNumber;
245       int seriesNumber;
246       int j;
247       
248       bool keep = false;
249       if (nbSeriesToKeep != 0)
250       {     
251          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
252          seriesNumber = atoi( strSeriesNumber.c_str() );
253          for (j=0;j<nbSeriesToKeep; j++)
254          {
255             if(seriesNumber == seriesToKeep[j])
256             {
257                keep = true;
258                break;
259             }
260          }
261          if ( !keep)
262          {
263             f->Delete();
264             continue;
265          } 
266       }
267       // drop all unrequested Series
268       bool drop = false;
269       if (nbSeriesToDrop != 0)
270       {     
271          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
272          seriesNumber = atoi( strSeriesNumber.c_str() );
273          for (j=0;j<nbSeriesToDrop; j++)
274          {
275             if(seriesNumber == seriesToDrop[j])
276             { 
277                drop = true;
278                break;
279             }
280         }
281         if (drop)
282         {
283            f->Delete();
284            continue;
285         }
286       }      
287
288       userFileIdentifier=s->CreateUserDefinedFileIdentifier(f);        
289       //std::cout << "                           [" <<
290       //        userFileIdentifier  << "]" << std::endl;
291       
292       // storing in a map ensures automatic sorting !      
293       sf[userFileIdentifier] = f;
294    }
295       
296    std::vector<std::string> tokens;
297    std::string fullFilename, lastFilename;
298    std::string previousPatientName, currentPatientName;
299    std::string previousSerieInstanceUID, currentSerieInstanceUID;
300    std::string previousImagePosition, currentImagePosition;
301    std::string previousPhaseEncodingDirection, currentPhaseEncodingDirection;
302    
303    std::string writeDir, currentWriteDir;
304    
305    writeDir = gdcm::Util::NormalizePath(dirNameout);     
306    SortedFiles::iterator it2;
307  
308    previousPatientName            = "";
309    previousSerieInstanceUID       = "";   
310    previousImagePosition          = "";
311    previousPhaseEncodingDirection = "";
312    
313    int sliceIndex = 0;
314    int frameIndex = 0;
315       
316    gdcm::File *currentFile;
317      
318    for (it2 = sf.begin() ; it2 != sf.end(); ++it2)
319    {  
320       currentFile = it2->second;
321        
322       fullFilename =  currentFile->GetFileName();
323       lastFilename =  gdcm::Util::GetName( fullFilename ); 
324
325       
326       tokens.clear();
327       gdcm::Util::Tokenize (it2->first, tokens, "_");
328       
329       currentPatientName            = tokens[0];
330       currentSerieInstanceUID       = tokens[1];
331       currentImagePosition          = tokens[2];
332       currentPhaseEncodingDirection = tokens[3];     
333       
334       if (previousPatientName != currentPatientName)
335       {
336          previousPatientName = currentPatientName;
337          if (verbose)   
338             std::cout << "==== new Patient " << currentPatientName << std::endl;
339          previousPatientName            = currentPatientName;
340          previousSerieInstanceUID       = ""; //currentSerieInstanceUID;
341          previousImagePosition          = ""; //currentImagePosition;
342          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
343  
344          currentWriteDir = writeDir + currentPatientName;
345          if ( ! gdcm::DirList::IsDirectory(currentWriteDir) )
346            {
347               systemCommand   = "mkdir " + currentWriteDir;
348               if (verbose)
349                  std::cout << systemCommand << std::endl;
350               system ( systemCommand.c_str() );
351          }
352       }
353
354       if (previousSerieInstanceUID != currentSerieInstanceUID)
355       {        
356          if (verbose)   
357             std::cout << "==== === new Serie " << currentSerieInstanceUID 
358                       << std::endl;
359          previousSerieInstanceUID       = currentSerieInstanceUID;
360          previousImagePosition          = ""; //currentImagePosition;
361          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
362       }
363
364       if (previousImagePosition != currentImagePosition)
365       {        
366          if (verbose)   
367             std::cout << "=== === === new Position " << currentImagePosition 
368                       << std::endl;
369          previousImagePosition          = currentImagePosition;
370          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
371          sliceIndex += 1;
372       }      
373
374       if (previousPhaseEncodingDirection != currentPhaseEncodingDirection)
375       {        
376          if (verbose)   
377             std::cout << "==== === === === new PhaseEncodingDirection " 
378                       << currentPhaseEncodingDirection << std::endl;
379          previousPhaseEncodingDirection = currentPhaseEncodingDirection;
380       }      
381       frameIndex++; 
382       if (verbose)
383          std::cout << "--- --- --- --- --- " << (it2->second)->GetFileName() 
384                    << std::endl;
385       if ( gdcm::Debug::GetDebugFlag())
386          std::cout << "--- --- --- --- --- " << it2->first << "  " 
387                    << (it2->second)->GetFileName() << " " 
388                    << gdcm::Util::GetName( fullFilename ) << std::endl;           
389       
390       // Transform the image to be 'Brucker-Like'
391       // ----------------------------------------   
392     
393       // Deal with 0x0019, 0x1000 : 'FOV'
394       int nX = currentFile->GetXSize();
395       int nY = currentFile->GetYSize();
396       float pxSzX = currentFile->GetXSpacing();
397       float pxSzY = currentFile->GetYSpacing();
398       char fov[64];
399       sprintf(fov, "%f\\%f",nX*pxSzX, nY*pxSzY);
400       currentFile->InsertEntryString(fov, 0x0019, 0x1000, "DS");
401      
402       // Deal with 0x0020, 0x0012 : 'SESSION INDEX'
403       std::string chSessionIndex;
404       if (currentPhaseEncodingDirection == "ROW")
405          chSessionIndex = "1";
406       else
407          chSessionIndex = "2"; // suppose it's "COLUMN" !
408       currentFile->InsertEntryString(chSessionIndex, 0x0020, 0x0012, "IS");
409    
410       // Deal with  0x0021, 01020 : 'SLICE INDEX'
411       char chSliceIndex[5];
412       sprintf(chSliceIndex, "%04d", sliceIndex);
413       std::string strChSliceIndex(chSliceIndex);
414       currentFile->InsertEntryString(strChSliceIndex, 0x0021, 0x1020, "IS");
415        
416       // Deal with  0x0021, 01040 : 'FRAME INDEX' 
417       char chFrameIndex[5];
418       sprintf(chFrameIndex, "%04d", frameIndex);
419       currentFile->InsertEntryString(chFrameIndex, 0x0021, 0x1040, "IS"); 
420                     
421       std::string strExtent(extent);
422       std::string fullWriteFilename = currentWriteDir + gdcm::GDCM_FILESEPARATOR + lastFilename + strExtent;
423       
424       /*           
425       systemCommand  = "cp " + fullFilename + " " + fullWriteFilename;
426       std::cout << systemCommand << std::endl;
427       system (  systemCommand.c_str() );
428       */
429             
430       // Load the pixels in RAM.
431       
432       
433       fh = gdcm::FileHelper::New(currentFile);     
434       fh->GetImageDataRaw(); // Don't convert (Gray Pixels + LUT) into (RGB pixels) ?!?
435       fh->SetWriteTypeToDcmExplVR();
436       fh->Write(fullWriteFilename);
437       fh->gdcm::FileHelper::Delete();                
438    }
439  }