]> Creatis software - gdcm.git/blob - Example/MagnetomVisionToBrucker.cxx
Just to avoid further gcm unexpected crash :
[gdcm.git] / Example / MagnetomVisionToBrucker.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: MagnetomVisionToBrucker.cxx,v $
5   Language:  C++
6   Date:      $Date: 2006/01/31 11:42:08 $
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 MagnetomVisionToBrucker :\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 (RET)                          ",
54    "           (0x0018, 0x1060) Trigger Time                                  ",
55    " - fills a single level (*) Directory with *all* the files,               ",
56    "           converted into a Brucker-like Dicom, InTags compliant          ",
57    "   (*) actually : creates as many directories as Patients                 ",
58    "                  -that shouldn't appear, but being carefull is better ! -",
59    " or                                                                       ",
60    " - fills a tree-like structure of directories as :                        ",
61    "        - Patient                                                         ",
62    "        -- Serie                                                          ",
63    "        --- Position                                                      ",
64    "            Images are (sorted by Trigger Time /                          ",
65    "                     Encoding Direction (Row, Column)                     ",
66    "      use :                                                               ",
67    "           0x0021, 0x1020 : 'SLICE INDEX'                                 ",
68    "           0x0021, 0x1040 : 'FRAME INDEX'                                 ",
69    "           0x0020, 0x0012 : 'SESSION INDEX'  (Acquisition Number)         ",
70    " usage:                                                                   ",
71    " PhilipsToBrucker dirin=rootDirectoryName                                 ",
72    "                  dirout=outputDirectoryName                              ",
73    "                  {  [keep= list of seriesNumber to process]              ",
74    "                   | [drop= list of seriesNumber to ignore] }             ",
75    "                  [input = {ACR|DCM}]                                     ", 
76    "                  [extent=image suffix (.IMA, .NEMA, .DCM, ...)]          ",
77    "                  [listonly] [split]                                      ",
78    "                  [noshadowseq][noshadow][noseq] [verbose] [debug]        ",
79    "                                                                          ",
80    " dirout : will be created if doesn't exist                                ",
81    " keep : if user wants to process a limited number of series               ",
82    "            he gives the list of 'SeriesNumber' (tag 0020|0011)           ",
83    " drop : if user wants to ignore a limited number of series                ",
84    "            he gives the list of 'SeriesNumber' (tag 0020|0011)           ",   
85    "        SeriesNumber are short enough to be human readable                ",
86    "        e.g : 1030,1035,1043                                              ",
87    " extent : DO NOT forget the leading '.' !                                 ",
88    " split: creates a tree-like structure of directories as :                 ",
89    "        - Patient                                                         ",
90    "        -- Serie                                                          ",
91    "        --- Position                                                      ",
92    "            Images are (sorted by Trigger Time /                          ",
93    " noshadowseq: user doesn't want to load Private Sequences                 ",
94    " noshadow : user doesn't want to load Private groups (odd number)         ",
95    " noseq    : user doesn't want to load Sequences                           ",
96    " verbose  : user wants to run the program in 'verbose mode'               ",
97    " debug    : *developer*  wants to run the program in 'debug mode'         ",
98    FINISH_USAGE
99
100    // ----- Initialize Arguments Manager ------
101       
102    gdcm::ArgMgr *am = new gdcm::ArgMgr(argc, argv);
103   
104    if (argc == 1 || am->ArgMgrDefined("usage")) 
105    {
106       am->ArgMgrUsage(usage); // Display 'usage'
107       delete am;
108       return 0;
109    }
110
111    const char *dirNamein;   
112    dirNamein  = am->ArgMgrGetString("dirin","."); 
113
114    const char *dirNameout;   
115    dirNameout  = am->ArgMgrGetString("dirout",".");  
116    
117    int loadMode = gdcm::LD_ALL;
118    if ( am->ArgMgrDefined("noshadowseq") )
119       loadMode |= gdcm::LD_NOSHADOWSEQ;
120    else 
121    {
122    if ( am->ArgMgrDefined("noshadow") )
123          loadMode |= gdcm::LD_NOSHADOW;
124       if ( am->ArgMgrDefined("noseq") )
125          loadMode |= gdcm::LD_NOSEQ;
126    }
127
128    if (am->ArgMgrDefined("debug"))
129       gdcm::Debug::DebugOn();
130       
131    int verbose  = am->ArgMgrDefined("verbose");
132    int split    = am->ArgMgrDefined("split");
133    int listonly = am->ArgMgrDefined("listonly");
134          
135    int nbSeriesToKeep;
136    int *seriesToKeep = am->ArgMgrGetListOfInt("keep", &nbSeriesToKeep);
137    int nbSeriesToDrop;
138    int *seriesToDrop = am->ArgMgrGetListOfInt("drop", &nbSeriesToDrop);
139  
140    if ( nbSeriesToKeep!=0 && nbSeriesToDrop!=0)
141    {
142       std::cout << "KEEP and DROP are mutually exclusive !" << std::endl;
143       delete am;
144       return 0;         
145    }
146    
147    const char *extent  = am->ArgMgrGetString("extent",".DCM");
148    
149    // if unused Param we give up
150    if ( am->ArgMgrPrintUnusedLabels() )
151    { 
152       am->ArgMgrUsage(usage);
153       delete am;
154       return 0;
155    }
156    delete am;  // we don't need Argument Manager any longer
157
158    // ----- Begin Processing -----
159    
160    if ( ! gdcm::DirList::IsDirectory(dirNamein) )
161    {
162       std::cout << "KO : [" << dirNamein << "] is not a Directory." << std::endl;
163       exit(0);
164    }
165    else
166    {
167       std::cout << "OK : [" << dirNamein << "] is a Directory." << std::endl;
168    }
169
170    std::string systemCommand;
171    
172    std::cout << "Check for output directory :[" << dirNameout << "]."
173              <<std::endl;
174    if ( ! gdcm::DirList::IsDirectory(dirNameout) )    // dirout not found
175    {
176       std::string strDirNameout(dirNameout);          // to please gcc 4
177       systemCommand = "mkdir " +strDirNameout;        // create it!
178       if (verbose)
179          std::cout << systemCommand << std::endl;
180       system (systemCommand.c_str());
181       if ( ! gdcm::DirList::IsDirectory(dirNameout) ) // be sure it worked
182       {
183           std::cout << "KO : not a dir : [" << dirNameout << "] (creation failure ?)" << std::endl;
184           exit(0);
185       }
186       else
187       {
188         std::cout << "Directory [" << dirNameout << "] created." << std::endl;
189       }
190    }
191    else
192    {
193        std::cout << "Output Directory [" << dirNameout << "] already exists; Used as is." << std::endl;
194    }
195     
196    std::string strDirNamein(dirNamein);
197    gdcm::DirList dirList(strDirNamein, true); // get recursively the list of files
198    
199    if (listonly)
200    {
201       std::cout << "------------List of found files ------------" << std::endl;
202       dirList.Print();
203    }
204
205    gdcm::DirListType fileNames;
206    fileNames = dirList.GetFilenames();
207    gdcm::SerieHelper *s;              // Needed only to may use SerieHelper::AddSeriesDetail()
208    s = gdcm::SerieHelper::New();
209
210 /*       
211    std::cout << "---------------Print Serie--------------" << std::endl; 
212    s->SetDirectory(dirNamein, true); // true : recursive exploration 
213    s->SetUseSeriesDetails(true);  
214    s->AddSeriesDetail(0x0018, 0x1312);   
215    s->Print();
216 */
217   
218    gdcm::File *f;
219    gdcm::FileHelper *fh;
220 /*   
221    std::cout << "---------------Print Unique Series identifiers---------"  
222              << std::endl;     
223    std::string uniqueSeriesIdentifier;
224  
225    for (gdcm::DirListType::iterator it = fileNames.begin();  
226                                     it != fileNames.end();
227                                   ++it)
228    {
229       std::cout << "File Name : " << *it << std::endl;
230       f = gdcm::File::New();
231       f->SetLoadMode(gdcm::LD_ALL);
232       f->SetFileName( *it );
233       f->Load();
234         
235       uniqueSeriesIdentifier=s->CreateUniqueSeriesIdentifier(f);
236       std::cout << "                           [" <<
237                uniqueSeriesIdentifier  << "]" << std::endl;       
238       f->Delete();
239    }
240 */
241    
242    if (verbose)
243       std::cout << "------------------Print Break levels-----------------" << std::endl;
244
245    std::string userFileIdentifier; 
246    SortedFiles sf;
247
248    s->AddSeriesDetail(0x0010, 0x0010, false); // Patient's Name
249    s->AddSeriesDetail(0x0020, 0x0010, false); // Study ID - Siemens, in that time!
250    s->AddSeriesDetail(0x0020, 0x0030, false); // Image Position (RET)     
251    s->AddSeriesDetail(0x0020, 0x0013, false);  // Instance Number
252             //(called 'Trigger Time' in order not to change too much the code)
253       
254    for (gdcm::DirListType::iterator it = fileNames.begin();  
255                                     it != fileNames.end();
256                                   ++it)
257    {
258       f = gdcm::File::New();
259       f->SetLoadMode(loadMode);
260       f->SetFileName( *it );
261       f->Load();
262       
263       // keep only requested Series
264       std::string strSeriesNumber;
265       int seriesNumber;
266       int j;
267       
268       bool keep = false;
269       if (nbSeriesToKeep != 0)
270       {     
271          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
272          seriesNumber = atoi( strSeriesNumber.c_str() );
273          for (j=0;j<nbSeriesToKeep; j++)
274          {
275             if(seriesNumber == seriesToKeep[j])
276             {
277                keep = true;
278                break;
279             }
280          }
281          if ( !keep)
282          {
283             f->Delete();
284             continue;
285          } 
286       }
287       // drop all unrequested Series
288       bool drop = false;
289       if (nbSeriesToDrop != 0)
290       {     
291          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
292          seriesNumber = atoi( strSeriesNumber.c_str() );
293          for (j=0;j<nbSeriesToDrop; j++)
294          {
295             if(seriesNumber == seriesToDrop[j])
296             { 
297                drop = true;
298                break;
299             }
300         }
301         if (drop)
302         {
303            f->Delete();
304            continue;
305         }
306       }      
307
308       userFileIdentifier=s->CreateUserDefinedFileIdentifier(f); 
309      // userFileIdentifier += "_";
310       //userFileIdentifier += *it;       
311       std::cout << "                           [" <<
312               userFileIdentifier  << "]" << std::endl;
313       
314       // storing in a map ensures automatic sorting !      
315       sf[userFileIdentifier] = f;
316    }
317       
318    std::vector<std::string> tokens;
319    std::string fullFilename, lastFilename;
320    std::string previousPatientName, currentPatientName;
321    std::string previousSerieInstanceUID, currentSerieInstanceUID;
322    std::string previousImagePosition, currentImagePosition;
323    //std::string previousPhaseEncodingDirection, currentPhaseEncodingDirection;
324    std::string previousTriggerTime, currentTriggerTime;
325       
326    std::string writeDir, currentWriteDir;
327    std::string currentPatientWriteDir, currentSerieWriteDir, 
328                currentPositionWriteDir; // currentPhaseEncodingDirectionWriteDir;
329
330    std::string fullWriteFilename;
331    std::string strExtent(extent); 
332            
333    writeDir = gdcm::Util::NormalizePath(dirNameout);     
334    SortedFiles::iterator it2;
335  
336    previousPatientName            = "";
337    previousSerieInstanceUID       = "";   
338    previousImagePosition          = "";
339    //previousPhaseEncodingDirection = "";
340    previousTriggerTime            = "";
341    
342    int sliceIndex = 1;
343    int frameIndex = 1;
344    int flag       = 0;
345        
346    gdcm::File *currentFile;
347      
348    for (it2 = sf.begin() ; it2 != sf.end(); ++it2)
349    {  
350       currentFile = it2->second;
351        
352       fullFilename =  currentFile->GetFileName();
353       lastFilename =  gdcm::Util::GetName( fullFilename ); 
354       std::cout << "Try to write" <<lastFilename << std::endl;
355      
356       tokens.clear();
357       gdcm::Util::Tokenize (it2->first, tokens, "_");
358       
359       currentPatientName            = tokens[0];
360       currentSerieInstanceUID       = tokens[1];
361       currentImagePosition          = tokens[2];
362       currentTriggerTime            = tokens[3];
363       //currentPhaseEncodingDirection = tokens[4];           
364       
365       if ( currentImagePosition[0] == '-')
366           currentImagePosition[0] = 'M';
367       if ( currentImagePosition[0] == '+')
368           currentImagePosition[0] = 'P'; 
369       
370       if (previousPatientName != currentPatientName)
371       {
372          previousPatientName = currentPatientName;
373          if (verbose)   
374             std::cout << "==== new Patient  [" << currentPatientName  << "]" << std::endl;
375     
376          previousPatientName            = currentPatientName;
377          previousSerieInstanceUID       = ""; //currentSerieInstanceUID;
378          previousImagePosition          = ""; //currentImagePosition;
379          previousTriggerTime            = "";
380         // previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
381   
382          currentPatientWriteDir = writeDir + currentPatientName;
383          //if ( ! gdcm::DirList::IsDirectory(currentPatientWriteDir) )
384            {
385               systemCommand   = "mkdir " + currentPatientWriteDir;
386               if (verbose)
387                  std::cout << systemCommand << std::endl;
388               system ( systemCommand.c_str() );
389          }
390       }
391
392       if (previousSerieInstanceUID != currentSerieInstanceUID)
393       {        
394          if (verbose)   
395             std::cout << "==== === new Serie [" << currentSerieInstanceUID << "]"
396                       << std::endl;
397          if (split)
398          {
399              currentSerieWriteDir  = currentPatientWriteDir + gdcm::GDCM_FILESEPARATOR
400                              + currentSerieInstanceUID;
401              systemCommand   = "mkdir " + currentSerieWriteDir;  
402              system (systemCommand.c_str());
403          }
404          previousSerieInstanceUID       = currentSerieInstanceUID;
405          previousImagePosition          = ""; //currentImagePosition;
406          //previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
407       }
408
409       if (previousImagePosition != currentImagePosition)
410       {
411          frameIndex = 1;
412          flag = 0;        
413          if (verbose)   
414             std::cout << "=== === === new Position [" << currentImagePosition  << "]"
415                       << std::endl;
416          if (split)
417          {
418              currentPositionWriteDir  = currentSerieWriteDir + gdcm::GDCM_FILESEPARATOR
419                              + currentImagePosition;
420              systemCommand   = "mkdir " + currentPositionWriteDir;     
421              system (systemCommand.c_str()); 
422          }
423          previousImagePosition          = currentImagePosition;
424          //previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
425          sliceIndex += 1;
426       }      
427
428 // We don't split on Row/Column!
429 /*
430       if (previousPhaseEncodingDirection != currentPhaseEncodingDirection)
431       {        
432          if (verbose)   
433             std::cout << "==== === === === new PhaseEncodingDirection [" 
434                       << currentPhaseEncodingDirection  << "]" << std::endl;
435       
436          if (split)
437          {
438              currentPhaseEncodingDirectionWriteDir  = currentPositionWriteDir 
439                              + gdcm::GDCM_FILESEPARATOR
440                              + currentPhaseEncodingDirection;
441              systemCommand   = "mkdir " + currentPhaseEncodingDirectionWriteDir;     
442              system (systemCommand.c_str());     
443          }      
444     
445          previousPhaseEncodingDirection = currentPhaseEncodingDirection;
446       } 
447 */    
448       
449       if (verbose)
450          std::cout << "--- --- --- --- --- " << (it2->second)->GetFileName() 
451                    << std::endl;
452    
453       if ( gdcm::Debug::GetDebugFlag())
454          std::cout << "--- --- --- --- --- " << it2->first << "  " 
455                    << (it2->second)->GetFileName() << " " 
456                    << gdcm::Util::GetName( fullFilename ) << std::endl;           
457       
458       // Transform the image to be 'Brucker-Like'
459       // ----------------------------------------   
460     
461       // Deal with 0x0019, 0x1000 : 'FOV'
462       int nX = currentFile->GetXSize();
463       int nY = currentFile->GetYSize();
464       float pxSzX = currentFile->GetXSpacing();
465       float pxSzY = currentFile->GetYSpacing();
466       char fov[64];
467       sprintf(fov, "%f\\%f",nX*pxSzX, nY*pxSzY);
468       currentFile->InsertEntryString(fov, 0x0019, 0x1000, "DS");
469      
470       // Deal with 0x0020, 0x0012 : 'SESSION INDEX'  (Acquisition Number)
471       std::string chSessionIndex = "1";
472       /*
473       if (currentPhaseEncodingDirection == "ROW")
474          chSessionIndex = "1";
475       else
476          chSessionIndex = "2"; // suppose it's "COLUMN" !
477       currentFile->InsertEntryString(chSessionIndex, 0x0020, 0x0012, "IS");
478      */
479       // Deal with  0x0021, 0x1020 : 'SLICE INDEX'
480       char chSliceIndex[5];
481       sprintf(chSliceIndex, "%04d", sliceIndex);
482       std::string strChSliceIndex(chSliceIndex);
483       currentFile->InsertEntryString(strChSliceIndex, 0x0021, 0x1020, "IS");
484        
485       // Deal with  0x0021, 0x1040 : 'FRAME INDEX' 
486       char chFrameIndex[5];
487       sprintf(chFrameIndex, "%04d", frameIndex);
488       currentFile->InsertEntryString(chFrameIndex, 0x0021, 0x1040, "IS"); 
489       
490       if (flag == 0)
491       {       
492          flag = 1;
493       }
494       else
495       {
496          frameIndex++;
497          flag = 0;
498       }
499                     
500       if (split)
501       
502          //fullWriteFilename = currentPhaseEncodingDirectionWriteDir + gdcm::GDCM_FILESEPARATOR 
503          //                                + lastFilename + strExtent;      
504          fullWriteFilename = currentPositionWriteDir + gdcm::GDCM_FILESEPARATOR 
505                                          + lastFilename + strExtent; 
506       else
507          fullWriteFilename = currentPatientWriteDir + gdcm::GDCM_FILESEPARATOR 
508                                          + lastFilename + strExtent; 
509       
510       /*           
511       systemCommand  = "cp " + fullFilename + " " + fullWriteFilename;
512       std::cout << systemCommand << std::endl;
513       system (  systemCommand.c_str() );
514       */
515             
516       // Load the pixels in RAM.    
517       
518       fh = gdcm::FileHelper::New(currentFile);     
519       fh->GetImageDataRaw(); // Don't convert (Gray Pixels + LUT) into (RGB pixels) ?!?
520       fh->SetWriteTypeToDcmExplVR();
521       if (!fh->Write(fullWriteFilename))
522       {
523          std::cout << "Fail to write :[" << fullWriteFilename << "]"
524                    << std::endl;
525       } 
526       fh->Delete();                
527    }
528  }