1 /*=========================================================================
4 Module: $RCSfile: PhilipsToBrucker2.cxx,v $
6 Date: $Date: 2006/02/01 10:46:53 $
7 Version: $Revision: 1.14 $
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.
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.
17 =========================================================================*/
18 #include "gdcmDocEntry.h"
19 #include "gdcmDicomDir.h"
20 #include "gdcmDicomDirPatient.h"
22 #include "gdcmFileHelper.h"
23 #include "gdcmDirList.h"
24 #include "gdcmDebug.h"
25 #include "gdcmArgMgr.h"
27 #include "gdcmSerieHelper.h"
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
42 typedef std::map<std::string, gdcm::File*> SortedFiles;
44 int main(int argc, char *argv[])
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, 0x1060) Trigger Time ",
55 " (0x0018, 0x1312) In-plane Phase Encoding Direction ",
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 ! -",
61 " - fills a tree-like structure of directories as : ",
65 " Images are (sorted by Trigger Time / ",
66 " Encoding Direction (Row, Column) ",
68 " 0x0021, 0x1020 : 'SLICE INDEX' ",
69 " 0x0021, 0x1040 : 'FRAME INDEX' ",
70 " 0x0020, 0x0012 : 'SESSION INDEX' (Acquisition Number) ",
72 " PhilipsToBrucker dirin=rootDirectoryName ",
73 " dirout=outputDirectoryName ",
74 " { [keep= list of seriesNumber to process] ",
75 " | [drop= list of seriesNumber to ignore] } ",
77 " [input = {ACR|DCM}] ",
78 " [extent=image suffix (.IMA, .NEMA, .DCM, ...)] ",
79 " [listonly] [split] ",
80 " [noshadowseq][noshadow][noseq] [verbose] [debug] ",
82 " dirout : will be created if doesn't exist ",
83 " keep : if user wants to process a limited number of series ",
84 " he gives the list of 'SeriesNumber' (tag 0020|0011) ",
85 " drop : if user wants to ignore a limited number of series ",
86 " he gives the list of 'SeriesNumber' (tag 0020|0011) ",
87 " SeriesNumber are short enough to be human readable ",
88 " e.g : 1030,1035,1043 ",
89 " taggrid : user knows all the images are 'grid' -ie : not 'col', not 'raw'",
90 " extent : DO NOT forget the leading '.' ! ",
91 " skel: name skeleton eg : patName_1.nema -> skel=patName_ ",
92 " split: creates a tree-like structure of directories as : ",
96 " Images are (sorted by Trigger Time / ",
97 " Encoding Direction (Row, Column) ",
98 " noshadowseq: user doesn't want to load Private Sequences ",
99 " noshadow : user doesn't want to load Private groups (odd number) ",
100 " noseq : user doesn't want to load Sequences ",
101 " verbose : user wants to run the program in 'verbose mode' ",
102 " debug : *developer* wants to run the program in 'debug mode' ",
105 // ----- Initialize Arguments Manager ------
107 gdcm::ArgMgr *am = new gdcm::ArgMgr(argc, argv);
109 if (argc == 1 || am->ArgMgrDefined("usage"))
111 am->ArgMgrUsage(usage); // Display 'usage'
116 const char *dirNamein;
117 dirNamein = am->ArgMgrGetString("dirin",".");
119 const char *dirNameout;
120 dirNameout = am->ArgMgrGetString("dirout",".");
122 int loadMode = gdcm::LD_ALL;
123 if ( am->ArgMgrDefined("noshadowseq") )
124 loadMode |= gdcm::LD_NOSHADOWSEQ;
127 if ( am->ArgMgrDefined("noshadow") )
128 loadMode |= gdcm::LD_NOSHADOW;
129 if ( am->ArgMgrDefined("noseq") )
130 loadMode |= gdcm::LD_NOSEQ;
133 if (am->ArgMgrDefined("debug"))
134 gdcm::Debug::DebugOn();
136 bool verbose = am->ArgMgrDefined("verbose");
137 bool split = am->ArgMgrDefined("split");
138 bool listonly = am->ArgMgrDefined("listonly");
141 int *seriesToKeep = am->ArgMgrGetListOfInt("keep", &nbSeriesToKeep);
143 int *seriesToDrop = am->ArgMgrGetListOfInt("drop", &nbSeriesToDrop);
145 if ( nbSeriesToKeep!=0 && nbSeriesToDrop!=0)
147 std::cout << "KEEP and DROP are mutually exclusive !" << std::endl;
152 int taggrid = am->ArgMgrDefined("taggrid");
154 int hasSkel = am->ArgMgrDefined("skel");
157 skel = am->ArgMgrGetString("skel");
159 const char *extent = am->ArgMgrGetString("extent",".DCM");
161 // if unused Param we give up
162 if ( am->ArgMgrPrintUnusedLabels() )
164 am->ArgMgrUsage(usage);
168 delete am; // we don't need Argument Manager any longer
170 // ----- Begin Processing -----
172 if ( ! gdcm::DirList::IsDirectory(dirNamein) )
174 std::cout << "KO : [" << dirNamein << "] is not a Directory." << std::endl;
179 std::cout << "OK : [" << dirNamein << "] is a Directory." << std::endl;
182 std::string systemCommand;
184 std::cout << "Check for output directory :[" << dirNameout << "]."
186 if ( ! gdcm::DirList::IsDirectory(dirNameout) ) // dirout not found
188 std::string strDirNameout(dirNameout); // to please gcc 4
189 systemCommand = "mkdir " +strDirNameout; // create it!
191 std::cout << systemCommand << std::endl;
192 system (systemCommand.c_str());
193 if ( ! gdcm::DirList::IsDirectory(dirNameout) ) // be sure it worked
195 std::cout << "KO : not a dir : [" << dirNameout << "] (creation failure ?)" << std::endl;
200 std::cout << "Directory [" << dirNameout << "] created." << std::endl;
205 std::cout << "Output Directory [" << dirNameout << "] already exists; Used as is." << std::endl;
208 std::string strDirNamein(dirNamein);
209 gdcm::DirList dirList(strDirNamein, true); // get recursively the list of files
213 std::cout << "------------List of found files ------------" << std::endl;
217 gdcm::DirListType fileNames;
218 fileNames = dirList.GetFilenames();
219 gdcm::SerieHelper *s; // Needed only to may use SerieHelper::AddSeriesDetail()
220 s = gdcm::SerieHelper::New();
222 std::string token = "%%%"; // Hope it's enough!
224 std::cout << "---------------Print Serie--------------" << std::endl;
225 s->SetDirectory(dirNamein, true); // true : recursive exploration
226 s->SetUseSeriesDetails(true);
227 s->AddSeriesDetail(0x0018, 0x1312);
232 gdcm::FileHelper *fh;
233 std::vector<std::string> tokens;
234 std::vector<std::string> tokensForFileName;
236 std::cout << "---------------Print Unique Series identifiers---------"
238 std::string uniqueSeriesIdentifier;
240 for (gdcm::DirListType::iterator it = fileNames.begin();
241 it != fileNames.end();
244 std::cout << "File Name : " << *it << std::endl;
245 f = gdcm::File::New();
246 f->SetLoadMode(gdcm::LD_ALL);
247 f->SetFileName( *it );
250 uniqueSeriesIdentifier=s->CreateUniqueSeriesIdentifier(f);
252 uniqueSeriesIdentifier << "]" << std::endl;
258 std::cout << "------------------Print Break levels-----------------" << std::endl;
260 std::string userFileIdentifier;
263 s->AddSeriesDetail(0x0010, 0x0010, false); // Patient's Name
264 s->AddSeriesDetail(0x0020, 0x000e, false); // Series Instance UID
265 s->AddSeriesDetail(0x0020, 0x0032, false); // Image Position (Patient)
266 s->AddSeriesDetail(0x0018, 0x1060, true); // Trigger Time (true: convert to keep numerical order)
267 s->AddSeriesDetail(0x0018, 0x1312, false); // In-plane Phase Encoding Direction
269 for (gdcm::DirListType::iterator it = fileNames.begin();
270 it != fileNames.end();
273 f = gdcm::File::New();
274 f->SetLoadMode(loadMode);
275 f->SetFileName( *it );
278 // keep only requested Series
279 std::string strSeriesNumber;
284 if (nbSeriesToKeep != 0)
286 strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
287 seriesNumber = atoi( strSeriesNumber.c_str() );
288 for (j=0;j<nbSeriesToKeep; j++)
290 if(seriesNumber == seriesToKeep[j])
302 // drop all unrequested Series
304 if (nbSeriesToDrop != 0)
306 strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
307 seriesNumber = atoi( strSeriesNumber.c_str() );
308 for (j=0;j<nbSeriesToDrop; j++)
310 if(seriesNumber == seriesToDrop[j])
323 userFileIdentifier=s->CreateUserDefinedFileIdentifier(f);
325 gdcm::Util::Tokenize (userFileIdentifier, tokens, token);
327 int imageNum; // Within FileName
330 if ( tokens[3] == "gdcmUnfound") // sometimes Trigger Time is not found. CreateUserDefinedFileIdentifier is not aware of the pb.
332 ///this is a trick to build up a lexicographical compliant name :
333 /// eg : fich001.ima vs fich100.ima as opposed to fich1.ima vs fich100.ima
334 std::string name = gdcm::Util::GetName( *it );
337 gdcm::Util::Tokenize (name, tokensForFileName, skel);
338 imageNum = atoi ( tokensForFileName[0].c_str() );
339 // probabely we could write something much more complicated using C++ !
340 sprintf (newName, "%s%06d%s", skel, imageNum, extent);
342 tokensForFileName.clear();
348 userFileIdentifier = tokens[0] + token + tokens[1] + token + tokens[2] + token
349 + tokens[3] + token + tokens[4] + token;
353 userFileIdentifier << "]" << std::endl;
355 // storing in a map ensures automatic sorting !
356 sf[userFileIdentifier] = f;
359 std::string fullFilename, lastFilename;
360 std::string previousPatientName, currentPatientName;
361 std::string previousSerieInstanceUID, currentSerieInstanceUID;
362 std::string previousImagePosition, currentImagePosition;
363 std::string previousPhaseEncodingDirection, currentPhaseEncodingDirection;
364 std::string previousTriggerTime, currentTriggerTime;
366 std::string writeDir, currentWriteDir;
367 std::string currentPatientWriteDir, currentSerieWriteDir,
368 currentPositionWriteDir, currentPhaseEncodingDirectionWriteDir;
370 std::string fullWriteFilename;
371 std::string strExtent(extent);
373 writeDir = gdcm::Util::NormalizePath(dirNameout);
374 SortedFiles::iterator it2;
376 previousPatientName = "";
377 previousSerieInstanceUID = "";
378 previousImagePosition = "";
379 previousPhaseEncodingDirection = "";
380 previousTriggerTime = "";
382 int sliceIndex = 0; // Is incremented *at the beginning* of processing
386 gdcm::File *currentFile;
388 for (it2 = sf.begin() ; it2 != sf.end(); ++it2)
390 currentFile = it2->second;
392 fullFilename = currentFile->GetFileName();
393 lastFilename = gdcm::Util::GetName( fullFilename );
394 std::cout << "Try to write [" <<lastFilename << "]" << std::endl;
397 gdcm::Util::Tokenize (it2->first, tokens, token);
399 currentPatientName = tokens[0];
400 currentSerieInstanceUID = tokens[1];
401 currentImagePosition = tokens[2];
402 currentTriggerTime = tokens[3];
403 currentPhaseEncodingDirection = tokens[4];
405 if ( currentImagePosition[0] == '-')
406 currentImagePosition[0] = 'M';
407 if ( currentImagePosition[0] == '+')
408 currentImagePosition[0] = 'P';
410 if (previousPatientName != currentPatientName)
412 previousPatientName = currentPatientName;
414 std::cout << "==== new Patient [" << currentPatientName << "]" << std::endl;
416 previousPatientName = currentPatientName;
417 previousSerieInstanceUID = ""; //currentSerieInstanceUID;
418 previousImagePosition = ""; //currentImagePosition;
419 previousTriggerTime = "";
420 previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
422 currentPatientWriteDir = writeDir + currentPatientName;
423 //if ( ! gdcm::DirList::IsDirectory(currentPatientWriteDir) )
425 systemCommand = "mkdir " + currentPatientWriteDir;
427 std::cout << systemCommand << std::endl;
428 system ( systemCommand.c_str() );
432 if (previousSerieInstanceUID != currentSerieInstanceUID)
435 std::cout << "==== === new Serie [" << currentSerieInstanceUID << "]"
439 currentSerieWriteDir = currentPatientWriteDir + gdcm::GDCM_FILESEPARATOR
440 + currentSerieInstanceUID;
441 systemCommand = "mkdir " + currentSerieWriteDir;
442 system (systemCommand.c_str());
444 previousSerieInstanceUID = currentSerieInstanceUID;
445 previousImagePosition = ""; //currentImagePosition;
446 previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
449 if (previousImagePosition != currentImagePosition)
454 std::cout << "=== === === new Position [" << currentImagePosition << "]"
458 currentPositionWriteDir = currentSerieWriteDir + gdcm::GDCM_FILESEPARATOR
459 + currentImagePosition;
460 systemCommand = "mkdir " + currentPositionWriteDir;
461 system (systemCommand.c_str());
463 previousImagePosition = currentImagePosition;
464 previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
466 sliceIndex = 1; // only *one* slice in a given directory
471 // We don't split on Row/Column!
473 if (previousPhaseEncodingDirection != currentPhaseEncodingDirection)
476 std::cout << "==== === === === new PhaseEncodingDirection ["
477 << currentPhaseEncodingDirection << "]" << std::endl;
481 currentPhaseEncodingDirectionWriteDir = currentPositionWriteDir
482 + gdcm::GDCM_FILESEPARATOR
483 + currentPhaseEncodingDirection;
484 systemCommand = "mkdir " + currentPhaseEncodingDirectionWriteDir;
485 system (systemCommand.c_str());
488 previousPhaseEncodingDirection = currentPhaseEncodingDirection;
493 std::cout << "--- --- --- --- --- " << (it2->second)->GetFileName()
496 if ( gdcm::Debug::GetDebugFlag())
497 std::cout << "--- --- --- --- --- " << it2->first << " "
498 << (it2->second)->GetFileName() << " "
499 << gdcm::Util::GetName( fullFilename ) << std::endl;
501 // Transform the image to be 'Brucker-Like'
502 // ----------------------------------------
504 // Deal with 0x0019, 0x1000 : 'FOV'
505 int nX = currentFile->GetXSize();
506 int nY = currentFile->GetYSize();
507 float pxSzX = currentFile->GetXSpacing();
508 float pxSzY = currentFile->GetYSpacing();
510 sprintf(fov, "%f\\%f",nX*pxSzX, nY*pxSzY);
511 if (currentFile->IsVRCoherent(0x0019) == 1 )
512 currentFile->InsertEntryString(fov, 0x0019, 0x1000, " ");
514 currentFile->InsertEntryString(fov, 0x0019, 0x1000, "DS");
517 // Deal with 0x0020, 0x0012 : 'SESSION INDEX' (Acquisition Number)
518 std::string chSessionIndex;
521 chSessionIndex = "1";
524 if (currentPhaseEncodingDirection == "COL" || currentPhaseEncodingDirection == "COL " || currentPhaseEncodingDirection == " COL")
525 chSessionIndex = "1";
526 else if (currentPhaseEncodingDirection == "ROW" || currentPhaseEncodingDirection == "ROW "|| currentPhaseEncodingDirection == " ROW")
527 chSessionIndex = "2";
530 std::cout << "====================== PhaseEncodingDirection "
531 << " neither COL nor ROW (?!?) : [ "
532 << currentPhaseEncodingDirection << "]" << std::endl;
533 chSessionIndex = "1";
536 if (currentFile->IsVRCoherent(0x0020) == 1 )
537 currentFile->InsertEntryString(chSessionIndex, 0x0020, 0x0012, " ");
539 currentFile->InsertEntryString(chSessionIndex, 0x0020, 0x0012, "IS");
541 // Deal with 0x0021, 0x1020 : 'SLICE INDEX'
542 char chSliceIndex[5];
543 sprintf(chSliceIndex, "%04d", sliceIndex);
544 std::string strChSliceIndex(chSliceIndex);
546 // Deal with 0x0021, 0x1040 : 'FRAME INDEX'
547 char chFrameIndex[5];
548 sprintf(chFrameIndex, "%04d", frameIndex);
550 std::string stringVR;
551 if (currentFile->IsVRCoherent(0x0021) == 1 )
555 currentFile->InsertEntryString(strChSliceIndex, 0x0021, 0x1020, stringVR);
556 currentFile->InsertEntryString(chFrameIndex, 0x0021, 0x1040, stringVR);
570 //fullWriteFilename = currentPhaseEncodingDirectionWriteDir + gdcm::GDCM_FILESEPARATOR
571 // + lastFilename + strExtent;
572 fullWriteFilename = currentPositionWriteDir + gdcm::GDCM_FILESEPARATOR
573 + lastFilename + strExtent;
575 fullWriteFilename = currentPatientWriteDir + gdcm::GDCM_FILESEPARATOR
576 + lastFilename + strExtent;
579 systemCommand = "cp " + fullFilename + " " + fullWriteFilename;
580 std::cout << systemCommand << std::endl;
581 system ( systemCommand.c_str() );
584 // Load the pixels in RAM.
586 fh = gdcm::FileHelper::New(currentFile);
587 fh->GetImageDataRaw(); // Don't convert (Gray Pixels + LUT) into (RGB pixels) ?!?
588 fh->SetWriteTypeToDcmExplVR();
589 // We didn't modify pixels -> keep unchanged the following :
590 // 'Media Storage SOP Class UID' (0x0002,0x0002)
591 // 'SOP Class UID' (0x0008,0x0016)
592 // 'Image Type' (0x0008,0x0008)
593 // 'Conversion Type' (0x0008,0x0064)
594 fh->SetKeepMediaStorageSOPClassUID(true);
595 if (!fh->Write(fullWriteFilename))
597 std::cout << "Fail to write :[" << fullWriteFilename << "]"