1 /*=========================================================================
4 Module: $RCSfile: ToInTag.cxx,v $
6 Date: $Date: 2006/06/07 12:23:25 $
7 Version: $Revision: 1.4 $
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
41 typedef std::map<std::string, gdcm::File*> SortedFiles;
43 int main(int argc, char *argv[])
47 " - explores recursively the given directory, ",
48 " - keeps the requested series/ drops the unrequested series ",
49 " - orders the gdcm-readable found Files according to their ",
50 " (0x0010, 0x0010) Patient's Name ",
51 " (0x0020, 0x000e) Series Instance UID ",
52 " (0x0020, 0x0032) Image Position (Patient) ",
53 " (0x0018, 0x1060) Trigger Time ",
54 " (0x0018, 0x1312) In-plane Phase Encoding Direction ",
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 ! -",
60 " - fills a tree-like structure of directories as : ",
64 " Images are (sorted by Trigger Time / ",
65 " Encoding Direction (Row, Column) ",
67 " 0x0021, 0x1020 : 'SLICE INDEX' ",
68 " 0x0021, 0x1040 : 'FRAME INDEX' ",
69 " 0x0020, 0x0012 : 'SESSION INDEX' (Acquisition Number) ",
71 " PhilipsToBrucker dirin=rootDirectoryName ",
72 " dirout=outputDirectoryName ",
73 " { [keep= list of seriesNumber to process] ",
74 " | [drop= list of seriesNumber to ignore] } ",
76 " [input = {ACR|DCM}] ",
77 " [extent=image suffix (.IMA, .NEMA, .DCM, ...)] ",
78 " [listonly] [split] ",
79 " [noshadowseq][noshadow][noseq] [verbose] [debug] ",
81 " dirout : will be created if doesn't exist ",
82 " keep : if user wants to process a limited number of series ",
83 " he gives the list of 'SeriesNumber' (tag 0020|0011) ",
84 " drop : if user wants to ignore a limited number of series ",
85 " he gives the list of 'SeriesNumber' (tag 0020|0011) ",
86 " SeriesNumber are short enough to be human readable ",
87 " e.g : 1030,1035,1043 ",
88 " taggrid : user knows all the images are 'grid' -ie : not 'col', not 'raw'",
89 " extent : DO NOT forget the leading '.' ! ",
90 " skel: name skeleton eg : patName_1.nema -> skel=patName_ ",
91 " split: creates a tree-like structure of directories as : ",
95 " Images are (sorted by Trigger Time / ",
96 " Encoding Direction (Row, Column) ",
97 " noshadowseq: user doesn't want to load Private Sequences ",
98 " noshadow : user doesn't want to load Private groups (odd number) ",
99 " noseq : user doesn't want to load Sequences ",
100 " verbose : user wants to run the program in 'verbose mode' ",
101 " debug : *developer* wants to run the program in 'debug mode' ",
104 std::cout << "inside ToInTag" << std::endl;
106 // ----- Initialize Arguments Manager ------
108 gdcm::ArgMgr *am = new gdcm::ArgMgr(argc, argv);
110 if (argc == 1 || am->ArgMgrDefined("usage"))
112 am->ArgMgrUsage(usage); // Display 'usage'
117 const char *dirNamein;
118 dirNamein = am->ArgMgrGetString("dirin",".");
120 const char *dirNameout;
121 dirNameout = am->ArgMgrGetString("dirout",".");
123 int loadMode = gdcm::LD_ALL;
124 if ( am->ArgMgrDefined("noshadowseq") )
125 loadMode |= gdcm::LD_NOSHADOWSEQ;
128 if ( am->ArgMgrDefined("noshadow") )
129 loadMode |= gdcm::LD_NOSHADOW;
130 if ( am->ArgMgrDefined("noseq") )
131 loadMode |= gdcm::LD_NOSEQ;
134 if (am->ArgMgrDefined("debug"))
135 gdcm::Debug::DebugOn();
137 int verbose = am->ArgMgrDefined("verbose");
138 int split = am->ArgMgrDefined("split");
139 int listonly = am->ArgMgrDefined("listonly");
142 int *seriesToKeep = am->ArgMgrGetListOfInt("keep", &nbSeriesToKeep);
144 int *seriesToDrop = am->ArgMgrGetListOfInt("drop", &nbSeriesToDrop);
146 if ( nbSeriesToKeep!=0 && nbSeriesToDrop!=0)
148 std::cout << "KEEP and DROP are mutually exclusive !" << std::endl;
153 int taggrid = am->ArgMgrDefined("taggrid");
155 int hasSkel = am->ArgMgrDefined("skel");
158 skel = am->ArgMgrGetString("skel");
160 const char *extent = am->ArgMgrGetString("extent",".DCM");
162 // if unused Param we give up
163 if ( am->ArgMgrPrintUnusedLabels() )
165 am->ArgMgrUsage(usage);
169 delete am; // we don't need Argument Manager any longer
171 // ----- Begin Processing -----
173 if ( ! gdcm::DirList::IsDirectory(dirNamein) )
175 std::cout << "KO : [" << dirNamein << "] is not a Directory." << std::endl;
181 std::cout << "OK : [" << dirNamein << "] is a Directory." << std::endl;
184 std::string systemCommand;
186 std::cout << "Check for output directory :[" << dirNameout << "]."
188 if ( ! gdcm::DirList::IsDirectory(dirNameout) ) // dirout not found
190 std::string strDirNameout(dirNameout); // to please gcc 4
191 systemCommand = "mkdir " +strDirNameout; // create it!
193 std::cout << systemCommand << std::endl;
194 system (systemCommand.c_str());
195 if ( ! gdcm::DirList::IsDirectory(dirNameout) ) // be sure it worked
197 std::cout << "KO : not a dir : [" << dirNameout << "] (creation failure ?)" << std::endl;
203 std::cout << "Directory [" << dirNameout << "] created." << std::endl;
208 std::cout << "Output Directory [" << dirNameout << "] already exists; Used as is." << std::endl;
211 std::string strDirNamein(dirNamein);
212 gdcm::DirList dirList(strDirNamein, true); // get recursively the list of files
216 std::cout << "------------List of found files ------------" << std::endl;
220 gdcm::DirListType fileNames;
221 fileNames = dirList.GetFilenames();
222 gdcm::SerieHelper *s; // Needed only to may use SerieHelper::AddSeriesDetail()
223 s = gdcm::SerieHelper::New();
225 std::string token = "%%%"; // Hope it's enough!
227 std::cout << "---------------Print Serie--------------" << std::endl;
228 s->SetDirectory(dirNamein, true); // true : recursive exploration
229 s->SetUseSeriesDetails(true);
230 s->AddSeriesDetail(0x0018, 0x1312);
235 gdcm::FileHelper *fh;
236 std::vector<std::string> tokens;
237 std::vector<std::string> tokensForFileName;
239 std::cout << "---------------Print Unique Series identifiers---------"
241 std::string uniqueSeriesIdentifier;
243 for (gdcm::DirListType::iterator it) = fileNames.begin();
244 it != fileNames.end();
247 std::cout << "File Name : " << *it << std::endl;
248 f = gdcm::File::New();
249 f->SetLoadMode(gdcm::LD_ALL);
250 f->SetFileName( *it );
253 uniqueSeriesIdentifier=s->CreateUniqueSeriesIdentifier(f);
255 uniqueSeriesIdentifier << "]" << std::endl;
261 std::cout << "------------------Print Break levels-----------------" << std::endl;
263 std::string userFileIdentifier;
266 s->AddSeriesDetail(0x0010, 0x0010, false); // Patient's Name
267 s->AddSeriesDetail(0x0020, 0x000e, false); // Series Instance UID
268 s->AddSeriesDetail(0x0020, 0x0032, false); // Image Position (Patient)
269 s->AddSeriesDetail(0x0018, 0x1060, true); // Trigger Time (true: convert to keep numerical order)
270 s->AddSeriesDetail(0x0018, 0x1312, false); // In-plane Phase Encoding Direction
272 //uint8_t *imageData; // Useless : pixels will not be loaded
273 // (images are overwritten)
275 for (gdcm::DirListType::iterator it = fileNames.begin();
276 it != fileNames.end();
279 f = gdcm::File::New();
280 f->SetLoadMode(loadMode);
281 f->SetFileName( *it );
285 std::string strSeriesNumber;
289 // keep only requested Series
291 if (nbSeriesToKeep != 0)
293 strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
294 seriesNumber = atoi( strSeriesNumber.c_str() );
295 for (j=0;j<nbSeriesToKeep; j++)
297 if(seriesNumber == seriesToKeep[j])
309 // drop all unrequested Series
311 if (nbSeriesToDrop != 0)
313 strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
314 seriesNumber = atoi( strSeriesNumber.c_str() );
315 for (j=0;j<nbSeriesToDrop; j++)
317 if(seriesNumber == seriesToDrop[j])
330 userFileIdentifier=s->CreateUserDefinedFileIdentifier(f);
332 gdcm::Util::Tokenize (userFileIdentifier, tokens, token);
334 int imageNum; // Within FileName
337 if ( tokens[3] == "gdcmUnfound") // sometimes Trigger Time is not found. CreateUserDefinedFileIdentifier is not aware of the pb.
339 ///this is a trick to build up a lexicographical compliant name :
340 /// eg : fich001.ima vs fich100.ima as opposed to fich1.ima vs fich100.ima
341 std::string name = gdcm::Util::GetName( *it );
344 gdcm::Util::Tokenize (name, tokensForFileName, skel);
345 imageNum = atoi ( tokensForFileName[0].c_str() );
346 // probabely we could write something much more complicated using C++ !
347 sprintf (newName, "%s%06d%s", skel, imageNum, extent);
349 tokensForFileName.clear();
355 userFileIdentifier = tokens[0] + token + tokens[1] + token + tokens[2] + token
356 + tokens[3] + token + tokens[4] + token;
359 std::cout << "[" << userFileIdentifier << "]" << std::endl;
361 // storing in a map ensures automatic sorting !
362 sf[userFileIdentifier] = f;
365 std::string fullFilename, lastFilename;
366 std::string previousPatientName, currentPatientName;
367 std::string previousSerieInstanceUID, currentSerieInstanceUID;
368 std::string previousImagePosition, currentImagePosition;
369 std::string previousPhaseEncodingDirection, currentPhaseEncodingDirection;
370 std::string previousTriggerTime, currentTriggerTime;
372 std::string writeDir, currentWriteDir;
373 std::string currentPatientWriteDir, currentSerieWriteDir,
374 currentPositionWriteDir, currentPhaseEncodingDirectionWriteDir;
376 std::string fullWriteFilename;
377 std::string strExtent(extent);
379 writeDir = gdcm::Util::NormalizePath(dirNameout);
380 SortedFiles::iterator it2;
382 previousPatientName = "";
383 previousSerieInstanceUID = "";
384 previousImagePosition = "";
385 previousPhaseEncodingDirection = "";
386 previousTriggerTime = "";
388 int sliceIndex = 0; // Is incremented *at the beginning* of processing
392 gdcm::File *currentFile;
394 for (it2 = sf.begin() ; it2 != sf.end(); ++it2)
396 currentFile = it2->second;
398 fullFilename = currentFile->GetFileName();
399 lastFilename = gdcm::Util::GetName( fullFilename );
400 std::cout << "Rewrite [" <<lastFilename << "]" << std::endl;
403 gdcm::Util::Tokenize (it2->first, tokens, token);
405 currentPatientName = tokens[0];
406 currentSerieInstanceUID = tokens[1];
407 currentImagePosition = tokens[2];
408 currentTriggerTime = tokens[3];
409 currentPhaseEncodingDirection = tokens[4];
411 if ( currentImagePosition[0] == '-')
412 currentImagePosition[0] = 'M';
413 if ( currentImagePosition[0] == '+')
414 currentImagePosition[0] = 'P';
416 if (previousPatientName != currentPatientName)
418 previousPatientName = currentPatientName;
420 std::cout << "==== new Patient [" << currentPatientName << "]" << std::endl;
422 previousPatientName = currentPatientName;
423 previousSerieInstanceUID = ""; //currentSerieInstanceUID;
424 previousImagePosition = ""; //currentImagePosition;
425 previousTriggerTime = "";
426 previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
428 currentPatientWriteDir = writeDir + currentPatientName;
429 //if ( ! gdcm::DirList::IsDirectory(currentPatientWriteDir) )
431 systemCommand = "mkdir " + currentPatientWriteDir;
433 std::cout << systemCommand << std::endl;
434 system ( systemCommand.c_str() );
438 if (previousSerieInstanceUID != currentSerieInstanceUID)
441 std::cout << "==== === new Serie [" << currentSerieInstanceUID << "]"
445 currentSerieWriteDir = currentPatientWriteDir + gdcm::GDCM_FILESEPARATOR
446 + currentSerieInstanceUID;
447 systemCommand = "mkdir " + currentSerieWriteDir;
448 system (systemCommand.c_str());
450 previousSerieInstanceUID = currentSerieInstanceUID;
451 previousImagePosition = ""; //currentImagePosition;
452 previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
455 if (previousImagePosition != currentImagePosition)
460 std::cout << "=== === === new Position [" << currentImagePosition << "]"
464 currentPositionWriteDir = currentSerieWriteDir + gdcm::GDCM_FILESEPARATOR
465 + currentImagePosition;
466 systemCommand = "mkdir " + currentPositionWriteDir;
467 system (systemCommand.c_str());
469 previousImagePosition = currentImagePosition;
470 previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
472 sliceIndex = 1; // only *one* slice in a given directory
477 // We don't split on Row/Column!
479 if (previousPhaseEncodingDirection != currentPhaseEncodingDirection)
482 std::cout << "==== === === === new PhaseEncodingDirection ["
483 << currentPhaseEncodingDirection << "]" << std::endl;
487 currentPhaseEncodingDirectionWriteDir = currentPositionWriteDir
488 + gdcm::GDCM_FILESEPARATOR
489 + currentPhaseEncodingDirection;
490 systemCommand = "mkdir " + currentPhaseEncodingDirectionWriteDir;
491 system (systemCommand.c_str());
494 previousPhaseEncodingDirection = currentPhaseEncodingDirection;
499 std::cout << "--- --- --- --- --- " << (it2->second)->GetFileName()
502 if ( gdcm::Debug::GetDebugFlag())
503 std::cout << "--- --- --- --- --- " << it2->first << " "
504 << (it2->second)->GetFileName() << " "
505 << gdcm::Util::GetName( fullFilename ) << std::endl;
507 // Transform the image to be 'Brucker-Like'
508 // ----------------------------------------
510 // Deal with 0x0019, 0x1000 : 'FOV'
511 int nX = currentFile->GetXSize();
512 int nY = currentFile->GetYSize();
513 float pxSzX = currentFile->GetXSpacing();
514 float pxSzY = currentFile->GetYSpacing();
516 sprintf(fov, "%f\\%f",nX*pxSzX, nY*pxSzY);
517 if (currentFile->IsVRCoherent(0x0019) == 1 )
518 currentFile->InsertEntryString(fov, 0x0019, 0x1000, " ");
520 currentFile->InsertEntryString(fov, 0x0019, 0x1000, "DS");
523 // Deal with 0x0020, 0x0012 : 'SESSION INDEX' (Acquisition Number)
524 std::string chSessionIndex;
527 chSessionIndex = "1";
530 if (currentPhaseEncodingDirection == "COL" || currentPhaseEncodingDirection == "COL " || currentPhaseEncodingDirection == " COL")
531 chSessionIndex = "1";
532 else if (currentPhaseEncodingDirection == "ROW" || currentPhaseEncodingDirection == "ROW "|| currentPhaseEncodingDirection == " ROW")
533 chSessionIndex = "2";
536 std::cout << "====================== PhaseEncodingDirection "
537 << " neither COL nor ROW (?!?) : [ "
538 << currentPhaseEncodingDirection << "]" << std::endl;
539 chSessionIndex = "1";
542 if (currentFile->IsVRCoherent(0x0020) == 1 )
543 currentFile->InsertEntryString(chSessionIndex, 0x0020, 0x0012, " ");
545 currentFile->InsertEntryString(chSessionIndex, 0x0020, 0x0012, "IS");
547 // Deal with 0x0021, 0x1020 : 'SLICE INDEX'
548 char chSliceIndex[5];
549 sprintf(chSliceIndex, "%04d", sliceIndex);
550 std::string strChSliceIndex(chSliceIndex);
552 // Deal with 0x0021, 0x1040 : 'FRAME INDEX'
553 char chFrameIndex[5];
554 sprintf(chFrameIndex, "%04d", frameIndex);
556 std::string stringVR;
557 if (currentFile->IsVRCoherent(0x0021) == 1 )
562 currentFile->InsertEntryString(strChSliceIndex, 0x0021, 0x1020, stringVR);
563 currentFile->InsertEntryString(chFrameIndex, 0x0021, 0x1040, stringVR);
566 std::string strImagePositionPatient = currentFile->GetEntryString(0x0020, 0x0032 );
567 if (strImagePositionPatient == gdcm::GDCM_UNFOUND)
568 currentFile->InsertEntryString(currentFile->GetEntryString(0x0020, 0x0030), 0x0020, 0x0032, "DS" );
570 std::string strImageOrientationPatient = f->GetEntryString(0x0020, 0x0037 );
571 if (strImageOrientationPatient == gdcm::GDCM_UNFOUND)
572 currentFile->InsertEntryString(currentFile->GetEntryString(0x0020, 0x0035), 0x0020, 0x0037, "DS" );
591 //fullWriteFilename = currentPhaseEncodingDirectionWriteDir + gdcm::GDCM_FILESEPARATOR
592 // + lastFilename + strExtent;
593 fullWriteFilename = currentPositionWriteDir + gdcm::GDCM_FILESEPARATOR
594 + lastFilename + strExtent;
596 fullWriteFilename = currentPatientWriteDir + gdcm::GDCM_FILESEPARATOR
597 + lastFilename + strExtent;
600 systemCommand = "cp " + fullFilename + " " + fullWriteFilename;
601 std::cout << systemCommand << std::endl;
602 system ( systemCommand.c_str() );
605 // Load the pixels in RAM.
607 fh = gdcm::FileHelper::New(currentFile);
608 uint8_t *imageData = fh->GetImageDataRaw(); // Don't convert (Gray Pixels + LUT) into (RGB pixels) ?!?
609 fh->SetWriteTypeToDcmExplVR();
610 // We didn't modify pixels -> keep unchanged the following :
611 // 'Media Storage SOP Class UID' (0x0002,0x0002)
612 // 'SOP Class UID' (0x0008,0x0016)
613 // 'Image Type' (0x0008,0x0008)
614 // 'Conversion Type' (0x0008,0x0064)
616 // Put to Black the burnt-in number.
617 nX = currentFile->GetXSize();
618 nY = currentFile->GetYSize();
619 for(int y=nY-15; y<nY; y++)
620 for(int x=nX/3; x<nX/2+50; x++)
621 imageData[ y*nX*2 + x ] = 0;
623 fh->SetContentType(gdcm::UNMODIFIED_PIXELS_IMAGE);
624 if (!fh->Write(fullWriteFilename))
626 std::cout << "Fail to write :[" << fullWriteFilename << "]"