]> Creatis software - gdcm.git/blob - Example/PhilipsToBrucker.cxx
PhilipsToBrucker -> second stage : deal with series selection
[gdcm.git] / Example / PhilipsToBrucker.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: PhilipsToBrucker.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/12/22 15:03:52 $
7   Version:   $Revision: 1.2 $
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 "gdcmDirList.h"
23 #include "gdcmDebug.h"
24 #include "gdcmArgMgr.h"
25 #include "gdcmUtil.h"
26 #include "gdcmSerieHelper.h"
27
28 #include <iostream>
29
30 /**
31   * \brief   
32   *          - explores recursively the given directory
33   *          - keeps the requested series
34   *          - orders the gdcm-readable found Files
35   *            according to their Patient/Study/Serie/Image characteristics
36   *          - fills a single level Directory with *all* the files,
37   *            converted into a Brucker-like Dicom, Intags compliant
38   *          
39   */  
40
41 typedef std::map<std::string, gdcm::File*> SortedFiles;
42
43 int main(int argc, char *argv[]) 
44 {
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    std::cout << nbSeriesToKeep << "  " <<   nbSeriesToDrop << std::endl;
123    if ( nbSeriesToKeep!=0 && nbSeriesToDrop!=0)
124    {
125       std::cout << "KEEP and DROP are mutually exclusive !" << std::endl;
126       delete am;
127       return 0;         
128    }
129    
130    char *extent  = am->ArgMgrGetString("extent",".DCM");
131         
132    // if unused Param we give up
133    if ( am->ArgMgrPrintUnusedLabels() )
134    { 
135       am->ArgMgrUsage(usage);
136       delete am;
137       return 0;
138    }
139    delete am;  // we don't need Argument Manager any longer
140
141    // ----- Begin Processing -----
142    
143    if ( ! gdcm::DirList::IsDirectory(dirNamein) )
144    {
145       std::cout << "not a directory : [" << dirNamein << "]" << std::endl;
146       exit(0);
147    }
148    std::string systemCommand;
149    if ( ! gdcm::DirList::IsDirectory(dirNameout) ) // dirout not found
150    {
151       std::string strDirNameout(dirNameout); // to please gcc 4
152       systemCommand = "mkdir " +strDirNameout;      // create it!
153       system (systemCommand.c_str());
154       if ( ! gdcm::DirList::IsDirectory(dirNameout) ) // be sure it worked
155       {
156           std::cout << "not a dir : [" << dirNameout << "]" << std::endl;
157           exit(0);
158       }
159    }
160     
161    std::string strDirNamein(dirNamein);
162    gdcm::DirList dirList(strDirNamein, true); // get recursively the list of files
163    
164  /*  
165    std::cout << "---------------File list found ------------" << std::endl;
166    dirList.Print();
167  */   
168
169    gdcm::DirListType fileNames;
170    fileNames = dirList.GetFilenames();
171    gdcm::SerieHelper *s;     // Needed only to may use SerieHelper::AddSeriesDetail()
172    s = gdcm::SerieHelper::New();
173
174 /*       
175    std::cout << "---------------Print Serie--------------" << std::endl; 
176    s->SetDirectory(dirNamein, true); // true : recursive exploration 
177    s->SetUseSeriesDetails(true);  
178    s->AddSeriesDetail(0x0018, 0x1312);   
179    s->Print();
180 */
181   
182    gdcm::File *f;
183
184 /*    
185    std::cout << "---------------Print Unique Series identifiers---------"  
186              << std::endl;     
187    std::string uniqueSeriesIdentifier;
188  
189    for (gdcm::DirListType::iterator it = fileNames.begin();  
190                                     it != fileNames.end();
191                                   ++it)
192    {
193       std::cout << "File Name : " << *it << std::endl;
194       f = gdcm::File::New();
195       f->SetLoadMode(gdcm::LD_ALL);
196       f->SetFileName( *it );
197       f->Load();
198         
199       uniqueSeriesIdentifier=s->CreateUniqueSeriesIdentifier(f);
200       std::cout << "                           [" <<
201                uniqueSeriesIdentifier  << "]" << std::endl;       
202       f->Delete();
203    }
204 */
205    
206    if (verbose)
207       std::cout << "------------------Print Break levels-----------------" 
208                 << std::endl;
209
210    std::string userFileIdentifier; 
211    SortedFiles sf;
212
213    s->AddSeriesDetail(0x0010, 0x0010, false); // Patient's Name
214    s->AddSeriesDetail(0x0020, 0x000e, false); // Series Instance UID
215    s->AddSeriesDetail(0x0020, 0x0032, false); // Image Position (Patient)     
216    s->AddSeriesDetail(0x0018, 0x1312, false); // In-plane Phase Encoding Direction 
217    s->AddSeriesDetail(0x0018, 0x1060, true);  // Trigger Time 
218    
219    for (gdcm::DirListType::iterator it = fileNames.begin();  
220                                     it != fileNames.end();
221                                   ++it)
222    {
223       f = gdcm::File::New();
224       f->SetLoadMode(loadMode);
225       f->SetFileName( *it );
226       f->Load();
227       
228       // keep only requested Series
229       std::string strSeriesNumber;
230       int seriesNumber;
231       int j;
232       
233       bool keep = false;
234       if (nbSeriesToKeep != 0)
235       {     
236          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
237          seriesNumber = atoi( strSeriesNumber.c_str() );
238          for (j=0;j<nbSeriesToKeep; j++)
239          {
240             if(seriesNumber == seriesToKeep[j])
241             {
242                keep = true;
243                break;
244             }
245          }
246          if ( !keep)
247             continue; 
248       }
249       // drop all unrequested Series
250       bool drop = false;
251       if (nbSeriesToDrop != 0)
252       {     
253          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
254          seriesNumber = atoi( strSeriesNumber.c_str() );
255          for (j=0;j<nbSeriesToDrop; j++)
256          {
257             if(seriesNumber == seriesToDrop[j])
258             { 
259                drop = true;
260                break;
261             }
262         }
263         if (drop)
264            continue;
265       }      
266
267       userFileIdentifier=s->CreateUserDefinedFileIdentifier(f);        
268       //std::cout << "                           [" <<
269       //        userFileIdentifier  << "]" << std::endl;
270       
271       // storing in a map ensures automatic sorting !      
272       sf[userFileIdentifier] = f;
273    }
274       
275    std::vector<std::string> tokens;
276    std::string fullFilename, lastFilename;
277    std::string previousPatientName, currentPatientName;
278    std::string previousSerieInstanceUID, currentSerieInstanceUID;
279    std::string previousImagePosition, currentImagePosition;
280    std::string previousPhaseEncodingDirection, currentPhaseEncodingDirection;
281    
282    std::string writeDir, currentWriteDir;
283    
284    writeDir = gdcm::Util::NormalizePath(dirNameout);     
285    SortedFiles::iterator it2;
286  
287    previousPatientName            = "";
288    previousSerieInstanceUID       = "";   
289    previousImagePosition          = "";
290    previousPhaseEncodingDirection = "";
291    
292    int sliceIndex = 0;
293    int frameIndex = 0;
294       
295    gdcm::File *currentFile;
296      
297    for (it2 = sf.begin() ; it2 != sf.end(); ++it2)
298    {  
299       currentFile = it2->second;
300        
301       fullFilename =  currentFile->GetFileName();
302       lastFilename =  gdcm::Util::GetName( fullFilename ); 
303       if (verbose)
304          std::cout << "==== === === ===    " << it2->first << "  " 
305                    << (it2->second)->GetFileName() << " " 
306                    << gdcm::Util::GetName( fullFilename ) <<std::endl;
307       
308       tokens.clear();
309       gdcm::Util::Tokenize (it2->first, tokens, "_");
310       
311       currentPatientName            = tokens[0];
312       currentSerieInstanceUID       = tokens[1];
313       currentImagePosition          = tokens[2];
314       currentPhaseEncodingDirection = tokens[3];     
315       
316       if (previousPatientName != currentPatientName)
317       {
318          previousPatientName = currentPatientName;
319          if (verbose)   
320             std::cout << "==== new Patient " << currentPatientName << std::endl;
321          previousPatientName            = currentPatientName;
322          previousSerieInstanceUID       = currentSerieInstanceUID;
323          previousImagePosition          = currentImagePosition;
324          previousPhaseEncodingDirection = currentPhaseEncodingDirection;
325  
326          currentWriteDir = writeDir + currentPatientName;
327          if ( ! gdcm::DirList::IsDirectory(currentWriteDir) )
328            {
329               systemCommand   = "mkdir " + currentWriteDir;
330               system ( systemCommand.c_str() );
331          }
332       }
333
334       if (previousSerieInstanceUID != currentSerieInstanceUID)
335       {        
336          if (verbose)   
337             std::cout << "==== === new Serie " << currentSerieInstanceUID 
338                       << std::endl;
339          previousSerieInstanceUID       = currentSerieInstanceUID;
340          previousImagePosition          = currentImagePosition;
341          previousPhaseEncodingDirection = currentPhaseEncodingDirection;
342       }
343
344       if (previousImagePosition != currentImagePosition)
345       {        
346          if (verbose)   
347             std::cout << "==== === === new Position " << currentImagePosition 
348                       << std::endl;
349          previousImagePosition          = currentImagePosition;
350          previousPhaseEncodingDirection = currentPhaseEncodingDirection;
351          sliceIndex += 1;
352       }      
353
354       if (previousPhaseEncodingDirection != currentPhaseEncodingDirection)
355       {        
356          if (verbose)   
357             std::cout << "==== === === === new PhaseEncodingDirection " 
358                       << currentImagePosition << std::endl;
359          previousPhaseEncodingDirection = currentPhaseEncodingDirection;
360       }
361       
362       frameIndex++;
363       
364       
365       // Transform the image to be 'Brucker-Like'
366       // ----------------------------------------   
367     
368       // Deal with 0x0019, 0x1000 : 'FOV'
369       int nX = currentFile->GetXSize();
370       int nY = currentFile->GetYSize();
371       float pxSzX = currentFile->GetXSpacing();
372       float pxSzY = currentFile->GetYSpacing();
373       char fov[64];
374       sprintf(fov, "%f\\%f",nX*pxSzX, nY*pxSzY);
375       std::cout << fov << std::endl;      
376       currentFile->InsertEntryString(fov, 0x0019, 0x1000, "DS");
377      
378       // Deal with 0x0020, 0x0012 : 'SESSION INDEX'
379       std::string chSessionIndex;
380       if (currentPhaseEncodingDirection == "ROW")
381          chSessionIndex = "1";
382       else
383          chSessionIndex = "2"; // suppose it's "COLUMN" !
384       currentFile->InsertEntryString(chSessionIndex, 0x0020, 0x0012, "IS");
385    
386       // Deal with  0x0021, 01020 : 'SLICE INDEX'
387       char chSliceIndex[5];
388       sprintf(chSliceIndex, "%04d", sliceIndex);
389       std::string strChSliceIndex(chSliceIndex);
390       currentFile->InsertEntryString(strChSliceIndex, 0x0021, 0x1020, "IS");
391        
392       // Deal with  0x0021, 01040 : 'FRAME INDEX' 
393       char chFrameIndex[5];
394       sprintf(chFrameIndex, "%04d", frameIndex);
395       currentFile->InsertEntryString(chFrameIndex, 0x0021, 0x1040, "IS"); 
396                     
397       std::string strExtent(extent);    
398       systemCommand  = "cp " + fullFilename + " " + currentWriteDir + 
399                        "/" + lastFilename + strExtent;
400       std::cout << systemCommand << std::endl;
401       //system (  systemCommand.c_str() );
402            
403    }
404  }