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