1 #include "bruker2dicom.h"
2 #include <boost/filesystem/path.hpp>
3 #include <boost/filesystem/operations.hpp>
5 #ifndef PATH_MAX // If not defined yet : do it
11 bool Bruker2Dicom::Execute()
13 // ----- Check input values -----
15 bool bigEndian = GDCM_NAME_SPACE::Util::IsCurrentProcessorBigEndian();
17 //if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(InputDirName) )
18 if ( ! boost::filesystem::is_directory(InputDirName) )
20 std::cout << "KO : [" << InputDirName << "] is not a Directory." << std::endl;
26 std::cout << "OK : [" << InputDirName << "] is a Directory." << std::endl;
29 std::string strDirNameOut(OutputDirName);
30 bool res=CreateDirectory(strDirNameOut);
32 std::cout << "[" << OutputDirName << "] Directory creation failure " << std::endl;
36 std::string strDirNamein(InputDirName);
37 GDCM_NAME_SPACE::DirList dirList(strDirNamein, false, true); // DON'T get recursively the list of files
38 std::string strDirNameout(OutputDirName);
43 std::cout << "------------List of found files ------------" << std::endl;
45 std::cout << std::endl;
51 // e.g : at level 0, in : B67d1.Bp1
53 // 1 2 3 4 5 6 AdjStatePerStudy subject
56 GDCM_NAME_SPACE::DirListType fileNames;
57 fileNames = dirList.GetFilenames();
59 std::string outputFileName;
61 // BrukerDataSet br_subject;
63 subject = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
64 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
67 std::cout << " Subject : [" << subject << "]" << std::endl;
68 canOpen =br_subject.LoadFile(subject);
72 std::cout << "Hopeless! no 'subject' found" << std::endl;
73 exit(0); /// \TODO throw an exception !
79 //br_subject.PrintSelf();
81 // get info for 'Study Description'
84 BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
85 acqp_protocol_location = b_protocol_location.GetStringValue()[0];
86 cleanString(acqp_protocol_location);
88 BrukerFieldData b_name=br_subject.GetFieldData("SUBJECT_name_string");
89 std::string subject_name = b_name.GetStringValue()[0];
90 strPatientName = subject_name;
91 cleanString(subject_name);
93 BrukerFieldData b_entry=br_subject.GetFieldData("SUBJECT_entry");
94 std::string subject_entry = b_entry.GetStringValue()[0];
95 //cleanString(subject_entry);
96 subject_entry = subject_entry.substr(11, subject_entry.size()-11);
98 BrukerFieldData b_position=br_subject.GetFieldData("SUBJECT_position");
99 std::string subject_position = b_position.GetStringValue()[0];
100 //cleanString(subject_position);
101 subject_position = subject_position.substr(9, subject_position.size()-9);
103 BrukerFieldData b_date=br_subject.GetFieldData("SUBJECT_date");
104 std::string subject_date = b_date.GetStringValue()[0];
105 strStudyTimeDate = subject_date;
106 cleanString(subject_date);
108 BrukerFieldData b_study_name=br_subject.GetFieldData("SUBJECT_study_name");
109 std::string subject_study_name = b_study_name.GetStringValue()[0];
110 subject_study_name = subject_study_name.substr(1, subject_study_name.size()-2);
111 cleanString(subject_date);
113 strStudyDescr = subject_name + "." + subject_study_name + "." + subject_entry + "." + subject_position + "." + subject_date;
115 char outputDirName[(unsigned int) PATH_MAX+2];
117 strStudyUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
119 // -----------------------------------------------------
120 // Iterate to ALL the objets(files/directories) found in the input directory
121 // (this is level ZERO)
122 // each Directory (name : 1, 2, 3, ...) will be a Dicom Serie
123 // -----------------------------------------------------
125 GDCM_NAME_SPACE::DirListType::iterator it;
127 for (it = fileNames.begin();
128 it != fileNames.end();
131 if ( !boost::filesystem::is_regular(*it) ) // check twice !
132 if ( boost::filesystem::is_directory(*it) )
135 std::cout << "[" << *it << "] is a directory" << std::endl;
137 //BrukerDataSet br_acqp;
140 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
143 br_acqp.LoadFile(strAcqp);
146 std::string acqp_scan_name;
147 std::string acqp_method;
148 std::string acqp_protocol_location;
150 BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
151 acqp_protocol_location = b_protocol_location.GetStringValue()[0];
152 cleanString(acqp_protocol_location);
154 BrukerFieldData b_scan_name=br_acqp.GetFieldData("ACQ_scan_name");
155 acqp_scan_name = b_scan_name.GetStringValue()[0];
156 cleanString(acqp_scan_name);
158 BrukerFieldData b_method=br_acqp.GetFieldData("ACQ_method");
159 acqp_method = b_method.GetStringValue()[0];
160 cleanString(acqp_method);
162 BrukerFieldData b_list_size = br_acqp.GetFieldData("ACQ_O1_list_size");
163 b_list_size.PrintSelf(); //JP
165 nbSlices = b_list_size.GetIntValue()[0];
167 strSerieDescr = GDCM_NAME_SPACE::Util::GetName(*it)
168 + "." + acqp_protocol_location
169 + "." + acqp_scan_name
170 + "." + acqp_method.c_str();
172 sprintf(outputDirName, "%s%c%s", OutputDirName.c_str(),
173 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
174 strSerieDescr.c_str() );
176 std::cout << " ================================================================================\n"
177 << " === [" << GDCM_NAME_SPACE::Util::GetName(*it) << "] -> [" << strSerieDescr << "]\n"
178 << " ================================================================================"
182 std::cout << " ================================================================================\n"
183 << " ========================= [" << GDCM_NAME_SPACE::Util::GetName(*it).c_str()
184 << acqp_protocol_location.c_str()
185 << acqp_scan_name.c_str()
186 << acqp_method.c_str()
188 << " ================================================================================"
192 printf ("outputDirName [%s]\n", outputDirName);
194 DealWithNiveau1(*it, outputDirName);
196 } // end of : for (GDCM_NAME_SPACE::DirListType::iterator it
200 // =====================================================================
202 void Bruker2Dicom::DealWithNiveau1(std::string level1Directory, std::string currentOutputDirName) {
204 // e.g. : at level 1, in B67d1.Bp1/6
206 // acqp fid imnd pdata pulseprogram spnam0 spnam1
208 bool res = CreateDirectory(currentOutputDirName);
211 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
214 GDCM_NAME_SPACE::DirList dirList(level1Directory, false, true); // DON'T get recursively the list of files
215 GDCM_NAME_SPACE::DirListType fileNames;
216 fileNames = dirList.GetFilenames();
217 // -----------------------------------------------------
218 // Iterate to ALL the objets(files/directories) found in the input directory
219 // -----------------------------------------------------
220 GDCM_NAME_SPACE::DirListType::iterator it;
222 for (it = fileNames.begin();
223 it != fileNames.end();
226 if ( boost::filesystem::is_regular(*it) )
227 //if ( ! boost::filesystem::is_directory(*it) )
230 std::cout << "--- [" << *it << "] is a file" << std::endl;
234 char outputDirName[(unsigned int) PATH_MAX+2];
235 //std::string firstName;
237 for (it = fileNames.begin();
238 it != fileNames.end();
241 if ( !boost::filesystem::is_regular(*it) ) // check twice !
242 if ( boost::filesystem::is_directory(*it) )
244 // will be always "pdata" ...
246 std::cout << "--- [" << *it << "] is a directory" << std::endl;
249 if (FileLine.startsWith("##$ACQ_size=")) {
250 if (FileLine.startsWith("##$NI=")) {
251 if (FileLine.startsWith("##$NR=")) {
252 if (FileLine.startsWith("##$ACQ_obj_order=")) {
253 if (FileLine.startsWith("##$ACQ_word_size=")) {
254 if (FileLine.startsWith("##$BYTORDA=")) {
255 if (FileLine.startsWith("##$PULPROG=")) {
258 sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
259 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
260 GDCM_NAME_SPACE::Util::GetName(*it).c_str());
263 std::string strMethod;
264 //std::string firstName = *(fileNames.begin());
266 strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin())) +
267 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
269 // std::cout << "---strMethod (for method)=> [" << strMethod << "]" << std::endl;
270 canOpen = br_method.LoadFile(strMethod);
273 strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
274 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
276 //std::cout << "---strMethod (for imnd) => [" << strMethod << "]" << std::endl;
277 canOpen = br_method.LoadFile(strMethod);
280 std::cout << "Hopeless! neither 'method' nor 'imnd' found" << std::endl;
281 exit(0); /// \TODO throw an exception !
285 std::cout << "open => [" << strMethod << "] successfully" << std::endl;
289 ##$PVM_Fov (dimension)
292 dans method (pour perfusion seulement?) :
293 ##$PVM_ObjOrderList=( 8 )
296 ##$PVM_SPackArrNSlices=( 2 )
299 DealWithNiveau2(*it,outputDirName );
304 // =====================================================================
306 void Bruker2Dicom::DealWithNiveau2(std::string level2Directory, std::string currentOutputDirName) {
308 // e.g. : at level 2 in B67d1.Bp1/6/pdata
310 // acqp fid imnd pdata pulseprogram spnam0 spnam1
313 bool res = CreateDirectory(currentOutputDirName);
316 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
320 GDCM_NAME_SPACE::DirList dirList(level2Directory, false, true); // DON'T get recursively the list of files
322 GDCM_NAME_SPACE::DirListType fileNames;
323 fileNames = dirList.GetFilenames();
325 char outputDirName[(unsigned int) PATH_MAX+2];
327 // -----------------------------------------------------
328 // Iterate to ALL the objets(files/directories) found in the input directory
329 // -----------------------------------------------------
330 GDCM_NAME_SPACE::DirListType::iterator it;
334 for (it = fileNames.begin();
335 it != fileNames.end();
338 if ( !boost::filesystem::is_regular(*it) )
339 //if ( ! boost::filesystem::is_directory(*it) )
341 std::cout << "--- --- [" << *it << "] is a file" << std::endl;
346 for (it = fileNames.begin();
347 it != fileNames.end();
350 if ( !boost::filesystem::is_regular(*it) ) // check twice !
351 if ( boost::filesystem::is_directory(*it) )
355 std::cout << "--- --- [" << *it << "] is a directory" << std::endl;
357 // sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
358 // GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
359 // GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
363 // (interest of previous method :
364 // If unaware user changed the pdata name, it goes on working
368 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
371 std::string str_isa_func_name;
372 canOpen = br_isa.LoadFile(str_isa);
375 sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
376 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
377 GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
382 BrukerFieldData b_isa_func_name = br_isa.GetFieldData("ISA_func_name");
384 str_isa_func_name = b_isa_func_name.GetStringValue()[0];
385 cleanString(str_isa_func_name);
387 sprintf(outputDirName, "%s%c%s.%s", currentOutputDirName.c_str(),
388 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
389 GDCM_NAME_SPACE::Util::GetName(*it).c_str(),
390 str_isa_func_name.c_str());
392 DealWithNiveau3(*it, outputDirName);
399 // =====================================================================
402 void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string currentOutputDirName){
405 // e.g. at level 3, in
407 // just to be able to go on checking // JP
408 if ( GDCM_NAME_SPACE::Util::GetName(level3Directory) != "1")
411 bool res = CreateDirectory(currentOutputDirName);
415 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
419 GDCM_NAME_SPACE::DirList dirList(level3Directory, false, true); // DON'T get recursively the list of files
420 GDCM_NAME_SPACE::DirListType::iterator it;
421 GDCM_NAME_SPACE::DirListType fileNames;
422 fileNames = dirList.GetFilenames();
424 char original2dseqName [(unsigned int) PATH_MAX+2];
425 char currentOutputMhdDirName [(unsigned int) PATH_MAX+2];
427 char outputMhdFileName [(unsigned int) PATH_MAX+2];
428 char output2dseqSliceFileName[(unsigned int) PATH_MAX+6]; // think about extra '.dcm'
429 char output2dseqName [(unsigned int) PATH_MAX+6];
430 char output2dseqCartoName [(unsigned int) PATH_MAX+6];
432 char copyFile[PATH_MAX + PATH_MAX + 5]; // Should be enough!
435 //-------------- try d3proc;
436 char char_d3proc[(unsigned int) PATH_MAX+2];
438 sprintf(char_d3proc,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"d3proc" );
441 std::cout << "--- => [" << char_d3proc << "]" << std::endl;
442 std::string str_d3proc(char_d3proc);
443 canOpen = br_d3proc.LoadFile(str_d3proc);
447 std::cout << "Hopeless! no 'd3proc' found" << std::endl;
448 exit(0); /// \TODO throw an exception !
451 canOpen = br_d3proc.FillMap();
454 std::cout << "Hopeless! FillMap failed on 'd3proc'" << std::endl;
455 exit(0); /// \TODO throw an exception !
458 //-------------- end try d3proc;
461 // -------------------try reco
463 char char_reco[(unsigned int) PATH_MAX+2];
465 sprintf(char_reco,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
466 //str_d3proc = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
467 // GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
470 std::cout << "--- => [" << char_reco << "]" << std::endl;
471 std::string str_reco(char_reco);
472 canOpen = br_reco.LoadFile(str_reco);
474 if (!canOpen) // we try in directory ../1
477 std::cout << "[" << str_reco << "] not found " << std::endl;
478 std::string lastDirName = GDCM_NAME_SPACE::Util::GetPath(level3Directory);
479 //lastDirName = GDCM_NAME_SPACE::Util::GetPath(lastDirName);
480 sprintf(char_reco,"%s%c1%c%s", lastDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
482 canOpen = br_reco.LoadFile(str_reco);
485 std::cout << "Hopeless! cannot find 'reco' in [" << str_reco << "]" << std::endl;
486 exit(0); /// \TODO throw an exception !
490 canOpen = br_reco.FillMap();
493 std::cout << "Hopeless! FillMap failed on [" << str_reco << "]" << std::endl;
494 exit(0); /// \TODO throw an exception !
496 //std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
497 // br_reco.PrintSelf();
498 // std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
500 // -------------------end try reco
503 BrukerFieldData bX = br_d3proc.GetFieldData("IM_SIX");
504 int NX = bX.GetIntValue()[0];
506 std::cout << "IM_SIX " << NX << std::endl;
507 BrukerFieldData bY=br_d3proc.GetFieldData("IM_SIY");
508 int NY = bY.GetIntValue()[0];
510 std::cout << "IM_SIY " << NY << std::endl;
511 /// \todo : check if there are actually 3 dimensions or only 2
513 BrukerFieldData bZ= br_d3proc.GetFieldData("IM_SIZ");
514 int nbFrames = bZ.GetIntValue()[0];
515 std::cout << "IM_SIZ " << nbFrames << std::endl;
517 // WARNING DATTYPE is, either in {ip_short, ip_int, ip_char, ...}, or in {1, 2, 3, ...}
519 BrukerFieldData bDPT = br_d3proc.GetFieldData("DATTYPE");
521 std::string mhdDataPixelType;
523 getImhDataType(bDPT, mhdDataPixelType, pixelSize);
525 BrukerFieldData fov = br_method.GetFieldData("PVM_Fov");
526 double fovX = fov.GetDoubleValue()[0];
527 double fovY = fov.GetDoubleValue()[1];
529 std::cout << "FOV (ds method) " << fovX << " " << fovY << std::endl;
531 /// \TODO probabely a more sophisticated accessor will be necessary :
532 /// (cf : non contiguous slices, overlapping, slice thickness, space between clices, etc)
533 BrukerFieldData bsliceDistance = br_method.GetFieldData("PVM_SPackArrSliceDistance");
534 double sliceDistance = bsliceDistance.GetDoubleValue()[0];
538 sprintf(currentOutputMhdDirName, "%s%c%s", currentOutputDirName.c_str(),
539 GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "MhdFiles");
540 res = CreateDirectory( currentOutputMhdDirName );
542 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
547 std::cout << "Directory creation [" << currentOutputDirName << "]" << std::endl;
550 std::cout << "nbFrames " << nbFrames << std::endl;
551 std::cout << "nbSlices " << nbSlices << std::endl;
553 int nbInstants = nbFrames/nbSlices;
554 std::cout << "nbInstants (deduced )" << nbInstants << std::endl;
557 FILE *fp; // for MHD files
559 sprintf( original2dseqName, "%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "2dseq");
562 // \TODO : tenir compte du bazar precedent
564 // load 2dseq in memory
566 fp = fopen(original2dseqName, "rb");
569 std::cout << "Cannot open [" << original2dseqName << "] for reading" << std::endl;
573 unsigned char *buffer_2dseq = new unsigned char[NX*NY*pixelSize*nbSlices*nbInstants];
574 ///\ TODO : find a safer way to be sure to read everything!
575 size_t lgr = fread(buffer_2dseq, 1, NX*NY*pixelSize*nbSlices*nbInstants, fp);
577 // This one will be important!
578 // ---------------------------
579 imageSet = CreateImageSet ( );
581 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
582 if (nbInstants==1) // creer un seul fichier .mhd pour toutes les Slices! (images natives)
584 std::cout << "Single instant : do not split" << std::endl;
587 sprintf(outputMhdFileName, "%s%cMhdData_All_the_Slices.mhd", currentOutputMhdDirName,
588 GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
589 fp=fopen(outputMhdFileName, "w");
592 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
597 fprintf(fp, "ObjectType = Image\n");
598 fprintf(fp, "NDims = 3\n" );
599 fprintf(fp, "BinaryData = True \n" );
600 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
601 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices );
602 fprintf(fp, "HeaderSize = %d\n", 0);
603 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
604 fprintf(fp, "Position = 0 0 %d\n", 0 );
605 fprintf(fp, "Offset = 0 0 0\n" );
606 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
607 fprintf(fp, "ElementNumberOfChannels = 1\n" );
608 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
609 fprintf(fp, "ElementDataFile = %s\n", "../2dseq_All_the_Slices" );
612 sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices",
613 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
614 fp=fopen(output2dseqSliceFileName, "wb");
617 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
621 fwrite( buffer_2dseq, NX*NY*pixelSize, nbSlices, fp);
624 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
628 sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices.dcm",
629 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
631 /* ----------- Write Dicom Image ---------------*/
632 MakeDicomImage(buffer_2dseq,
637 fovX/NY, fovY/NY, sliceDistance,
638 output2dseqSliceFileName,
646 0,// index frame number
647 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
650 } // end if nbInstants = 1
652 else // more than ONE instant
655 // it's (slice1,slide2, ...)t1 ; (slice1,slide2, ...)t2 ; ...
657 unsigned char *pixelsForCurrentSlice = new unsigned char[NX*NY*pixelSize*nbInstants];
660 for (sliceNb=0; sliceNb<nbSlices; sliceNb++)
664 sprintf(outputMhdFileName, "%s%cMhdData_%03d.mhd", currentOutputMhdDirName,
665 GDCM_NAME_SPACE::GDCM_FILESEPARATOR, k );
667 std::cout << "--- Output MHD file [" << outputMhdFileName << "]" << std::endl;
668 fp=fopen(outputMhdFileName, "w");
671 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
676 /* ----------- Write MHD Image ---------------*/
678 // std::cout << "Open sucessfully[" << outputMhdFileName << "] for writting" << std::endl;
679 fprintf(fp, "ObjectType = Image\n");
680 fprintf(fp, "NDims = 3\n" );
681 fprintf(fp, "BinaryData = True \n" );
682 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
683 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbInstants);
684 fprintf(fp, "HeaderSize = %d\n", 0);
685 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, 1.0 ); // slice distance : no meaning for temporal serie
686 fprintf(fp, "Position = 0 0 %d\n", sliceNb );
687 fprintf(fp, "Offset = 0 0 0\n" );
688 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
689 fprintf(fp, "ElementNumberOfChannels = 1\n" );
690 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
691 fprintf(fp, "ElementDataFile = ..%c2dseq_Slice_%d\n", GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb );
695 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d",
696 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,sliceNb);
697 fp=fopen(output2dseqSliceFileName, "wb");
700 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
703 int frameSize = NX*NY*pixelSize;
704 for (instantNb=0; instantNb<nbInstants; instantNb++)
706 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
707 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
712 // std::cout << "end writting[" << output2dseqSliceFileName << "]" << std::endl;
719 sprintf(output2dseqSliceFileName, "%sdummy_buffer",
720 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
721 fp=fopen(output2dseqSliceFileName, "wb");
724 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
727 int frameSize = NX*NY*pixelSize;
728 for (instantNb=0; instantNb<nbInstants; instantNb++)
730 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
731 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
737 fp=fopen(output2dseqSliceFileName, "rb");
740 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for reading" << std::endl;
743 fread( pixelsForCurrentSlice,
744 frameSize*nbInstants,
747 // end of desperate try !
750 /* ----------- Write Dicom Image ---------------*/
752 int frameSize = NX*NY*pixelSize;
753 for (instantNb=0; instantNb<nbInstants; instantNb++)
755 memcpy(pixelsForCurrentSlice + frameSize*instantNb, buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize, frameSize);
758 int indOfFirsImageWithinImageSet = nbSlices*instantNb;
759 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d.dcm",
760 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb);
763 pixelsForCurrentSlice,
768 fovX/NY, fovY/NY, sliceDistance,
769 output2dseqSliceFileName,
778 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
781 std::cout << "--- Output DCM file [" << output2dseqSliceFileName << "]" << std::endl;
787 delete [] pixelsForCurrentSlice;
788 } // end nbInstants == 1
789 delete [] buffer_2dseq;
793 // -----------------------------------------------------
794 // deal with MatLab-generated Carto file.
795 // -----------------------------------------------------
797 dealWithCarto(fileNames, NX, NY, nbSlices, fovX, fovY, sliceDistance,
798 copyFile, currentOutputDirName, outputMhdFileName, output2dseqCartoName);
802 // ===========================================================================================
804 void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX, int NY, int nbSlices,
805 double fovX, double fovY, double sliceDistance,
806 char *copyFile, std::string ¤tOutputDirName,
807 char *outputMhdFileName, char *output2dseqCartoName)
809 // -----------------------------------------------------
810 // deal with MatLab-generated Carto file.
811 // -----------------------------------------------------
813 char *code[] ={ "ADC", "adc", "TTP", "ttp", "PEAK", "peak" , ""}; // add more carto file name identifiers if necessary; end with ""
815 GDCM_NAME_SPACE::DirListType::iterator it;
816 char file_name_ident[500];
819 // Iterate to ALL the objets(files/directories) found in the input directory
820 for (it = fileNames.begin();
821 it != fileNames.end();
824 if ( boost::filesystem::is_regular(*it) )
825 //if ( ! boost::filesystem::is_directory(*it) )
828 std::cout << "--- [" << *it << "] is a file" << std::endl;
832 while (code[icode][0] != 0)
834 sprintf(file_name_ident, "2dseq_%s",code[icode]); // e.g "2dseq_ADC"
835 std::string::size_type loc = (*it).rfind(file_name_ident);
837 if ( loc != std::string::npos )
840 ///\ TODO : find a safer way to be sure to read everything!
841 unsigned char *buffer_carto = new unsigned char[NX*NY*sizeof(double)*nbSlices];
842 fp = fopen ( (*it).c_str(), "rb");
844 std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
847 fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
849 std::cout << "Deal with Carto file :[" <<*it << "], computed length : "
850 << NX*NY*sizeof(double)*nbSlices << std::endl;
851 std::string lastFileName = GDCM_NAME_SPACE::Util::GetName((*it).c_str());
854 // Copy the data file in the new directory
855 sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
856 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str());
858 sprintf(outputMhdFileName, "%s%c%s%s",
859 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".mhd" );
861 std::cout << "--- Output Carto MHD file [" << outputMhdFileName << "]" << std::endl;
864 fp=fopen(outputMhdFileName, "w");
867 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
871 fprintf(fp, "ObjectType = Image\n");
872 fprintf(fp, "NDims = 3\n" );
873 fprintf(fp, "BinaryData = True \n" );
874 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
875 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices);
876 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
877 fprintf(fp, "HeaderSize = %d\n", 0 );
878 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
879 fprintf(fp, "Position = 0 0 0\n" );
880 fprintf(fp, "Offset = 0 0 0\n" );
881 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
882 fprintf(fp, "ElementNumberOfChannels = 1\n" );
883 fprintf(fp, "ElementType = %s\n", "MET_DOUBLE" );
884 fprintf(fp, "ElementDataFile = %s\n", lastFileName.c_str() );
889 std::cout << "--- end write Carto MHD file [" << outputMhdFileName << "]" << std::endl;
892 // ----------- Write Dicom Image ---------------
896 sprintf(output2dseqCartoName, "%s%c%s%s",
897 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".dcm" );
899 std::cout << "--- end create name output2dseqCartoName file [" << output2dseqCartoName << "]" << std::endl;
901 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID(); //New SerieUID for each carto.
902 std::string strNewSerieDescr(strSerieDescr+ "_" +GDCM_NAME_SPACE::Util::GetName((*it).c_str()));
903 MakeDicomImage(buffer_carto,
908 fovX/NY, fovY/NY, sliceDistance,
909 output2dseqCartoName,
918 GDCM_NAME_SPACE::CREATED_IMAGE
922 delete [] buffer_carto;
924 std::cout << "--- End writing Carto DICOM file [" << output2dseqCartoName << "]" << std::endl;
925 break; // don't check for more ident on same file name!
931 } // end iterate on files
935 // ==========================================================================================================
937 bool Bruker2Dicom::CreateDirectory(std::string OutputDirName)
939 std::string systemCommand;
942 std::cout << "Check for output directory :[" << OutputDirName << "]."
944 if ( ! boost::filesystem::is_directory(OutputDirName) ) // dirout not found
946 std::string strDirNameout(OutputDirName); // to please gcc 4
947 systemCommand = "mkdir " + strDirNameout; // create it!
949 std::cout << systemCommand << std::endl;
950 system (systemCommand.c_str());
951 if ( ! boost::filesystem::is_directory(OutputDirName) ) // be sure it worked
954 std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
956 /// \todo : THROW AN EXCEPTION
961 std::cout << "Directory [" << OutputDirName << "] created." << std::endl;
967 std::cout << "Output Directory [" << OutputDirName << "] already exists; Used as is." << std::endl;
975 // ===========================================================================================
977 /// \TODO move cleanString to 'crea' ?
979 void Bruker2Dicom::cleanString(std::string &s)
982 if (s[l-1] == 0x0A || s[l-1] == 0x0D ) // CR or NL
987 if (s[l-1] == ' ' ) // blank space
995 std::string repChar("_");
996 GDCM_NAME_SPACE::Util::ReplaceSpecChar(s, repChar);
1001 // ===========================================================================================
1004 void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPixelType, int &pixelSize)
1006 if(bDPT.GetDataType() == "string")
1008 std::string brukerDataPixelType = bDPT.GetStringValue()[0];
1009 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
1010 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1012 if (brukerDataPixelType == "ip_short") {
1013 mhdDataPixelType = "MET_USHORT";
1016 if (brukerDataPixelType == "ip_int") {
1017 mhdDataPixelType = "MET_UINT";
1020 if (brukerDataPixelType == "ip_char") {
1021 mhdDataPixelType = "MET_UCHAR";
1024 /// \TODO : finish the list
1026 case 0 : fp << "ElementType = MET_CHAR" << std::endl;
1028 case 1 : fp << "ElementType = MET_UCHAR" << std::endl;
1030 case 2 : fp << "ElementType = MET_SHORT" << std::endl;
1032 case 3 : fp << "ElementType = MET_USHORT" << std::endl;
1034 case 4 : fp << "ElementType = MET_INT" << std::endl;
1036 case 5 : fp << "ElementType = MET_UINT" << std::endl;
1038 case 6 : fp << "ElementType = MET_FLOAT" << std::endl;
1040 case 7 : fp << "ElementType = MET_DOUBLE" << std::endl;
1045 int brukerDataPixelType = bDPT.GetIntValue()[0];
1046 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
1047 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1049 // Cross your fingers !!!
1051 // pb : found values : 2, 3, 5
1053 if (brukerDataPixelType == 2) {
1054 mhdDataPixelType = "MET_USHORT";
1057 if (brukerDataPixelType == 3) {
1058 mhdDataPixelType = "MET_USHORT";
1061 if (brukerDataPixelType == 1) {
1062 mhdDataPixelType = "MET_UCHAR";
1068 // ===========================================================================================
1070 std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
1072 std::vector<BrukerImage> imageSet;
1073 br_acqp.SetLoopStructure();
1074 std::vector<int> tempVect = br_acqp.GetLoopStructure() ;
1075 std::map<std::string, BrukerFieldData> map = br_acqp.GetBrukerHeaderMap();
1076 bool result = br_acqp.ObjectVaryingProperties.init(map,tempVect);
1078 br_acqp.SetImageLoopStructure();
1079 br_acqp.SetBrukerImageList();
1080 std::vector<std::vector<int> > brukerImageList = br_acqp.GetBrukerImageList();
1082 BrukerImage image(br_acqp,br_reco);
1083 image.Init(br_acqp,br_reco,1);
1085 for(int i=0;i<brukerImageList.size();i++)
1087 image.Init(br_acqp,br_reco,i);
1088 imageSet.push_back(image);
1091 // Just for checking
1094 std::vector<std::vector <double> > imageOrientation;
1095 std::vector <double> imagePosition;
1096 for(int i=0;i<brukerImageList.size();i++)
1098 // fread(buffer_2dseq, NX*NY*pixelSize*nbSlices*nbInstants, 1, fp);
1100 imagePosition = imageSet[i].getTranslationVectorRPS2XYZ();
1101 std::cout << "Position " << imagePosition[0] << " "
1102 << imagePosition[1] << " " << imagePosition[2] ;
1103 imageOrientation = imageSet[i].getRotationMatrixRPS2XYZ();
1104 std::cout << "\t Orientation " ;
1105 for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
1106 std::cout << imageOrientation[i1][i2] << " ";
1108 //std::cout << "\t Abs Time " << imageSet[i].getAbsoluteTimePosition();
1109 std::cout << "\t Relat Time " << imageSet[i].getRelativeTimePosition();
1111 std::cout << "\t [";
1112 for (int i3=0; i3<imageSet[i].getLoopStamp().size();i3++)
1113 std::cout << " " << imageSet[i].getLoopStamp()[i3];
1114 std::cout << "]" << std::endl;
1121 // ===========================================================================================
1123 void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels,
1128 double spacingX, double spacingY, double sliceDistance,
1129 std::string dcmImageName,
1130 const std::string &patientName,
1132 std::string &studyUID,
1133 std::string &serieUID,
1134 std::string &studyDescr,
1135 std::string &serieDescr,
1136 std::string &strStudyTimeDate,
1138 GDCM_NAME_SPACE::ImageContentType contentType
1141 std::ostringstream str;
1143 GDCM_NAME_SPACE::File *file;
1144 file = GDCM_NAME_SPACE::File::New();
1146 // Set the image size
1149 file->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
1152 file->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
1158 file->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames
1161 // Set the pixel type
1162 // //8, 16, 32, 64 (for double ?)
1165 file->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
1167 file->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
1170 str << pixelSize*8-1;
1171 file->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
1173 // Set the pixel representation // 0/1 , 0=unsigned
1174 file->InsertEntryString("1",0x0028,0x0103, "US"); // Pixel Representation
1176 // Set the samples per pixel // 1:Grey level, 3:RGB
1177 file->InsertEntryString("1",0x0028,0x0002, "US"); // Samples per Pixel
1179 // 0028 0030 DS 2 Pixel Spacing
1181 str << spacingX << "\\" << spacingY;
1182 file->InsertEntryString(str.str(),0x0028,0x0030, "DS"); // Pixel Spacing
1184 // 0018 0050 DS 1 Slice Thickness
1186 str << sliceDistance;
1187 file->InsertEntryString(str.str(),0x0018,0x0050, "DS");
1189 // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
1190 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1191 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1194 // OK : MR is NOT multiframe, but I want just a quick an dirty solution
1195 // 1.2.840.10008.5.1.4.1.1.4 MR Image Storage
1196 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1197 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1199 // if (strlen(patientName) != 0)
1200 file->InsertEntryString(patientName.c_str(),0x0010,0x0010, "PN"); // Patient's Name
1202 file->InsertEntryString(studyUID, 0x0020, 0x000d, "UI");
1203 file->InsertEntryString(serieUID, 0x0020, 0x000e, "UI");
1205 // 0008 0020 DA 1 Study Date
1206 // 0008 0030 TM 1 Study Time
1208 /// \TODO split into 2 strings!
1209 file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
1210 file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),0x0008,0x0030, "TM");
1212 file->InsertEntryString(studyDescr,0x0008,0x1030, "LO"); // Study Description
1213 file->InsertEntryString(serieDescr,0x0008,0x103e, "LO"); // Series Description
1215 //0008|0060 [CS] [Modality]
1216 file->InsertEntryString("MR",0x0008,0x0060, "CS");
1218 // 0020 0037 DS 6 Image Orientation (Patient)
1219 char charImageOrientation[256];
1222 std::cout << "try charImageOrientation " <<
1223 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0] << " " <<
1224 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1] << " " <<
1225 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2] << " " <<
1226 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0] << " " <<
1227 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1] << " " <<
1228 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] << std::endl ;
1230 sprintf(charImageOrientation,"%f\\%f\\%f \\ %f\\%f\\%f",
1231 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0],
1232 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1],
1233 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2],
1234 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0],
1235 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1],
1236 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] ) ;
1238 file->InsertEntryString(charImageOrientation,0x0020,0x0037, "DS");
1241 // 0020 0032 DS 3 Image Position (Patient)
1243 char charImagePosition[256];
1244 sprintf(charImagePosition,"%f\\%f\\%f",
1245 imageSet[imgNum].getTranslationVectorRPS2XYZ()[0],
1246 imageSet[imgNum].getTranslationVectorRPS2XYZ()[1],
1247 imageSet[imgNum].getTranslationVectorRPS2XYZ()[2]);
1249 file->InsertEntryString(charImagePosition,0x0020,0x0032, "DS"); //0020 0032 DS 3 Image Position (Patient)
1253 // 0020 0x1041 DS 1 Slice Location
1254 // sprintf(charImagePosition,"%f",float(imgNum));
1255 // file->InsertEntryString(charImagePosition,0x0020,0x1041, "DS");
1257 // Set Rescale Intercept
1260 file->InsertEntryString(str.str(),0x0028,0x1052,"DS");
1262 // Set Rescale Slope
1265 file->InsertEntryString(str.str(),0x0028,0x1053,"DS");
1268 GDCM_NAME_SPACE::FileHelper *fileH;
1269 fileH = GDCM_NAME_SPACE::FileHelper::New(file);
1270 fileH->SetContentType(contentType);
1272 // cast is just to avoid warnings (*no* conversion is performed)
1273 //fileH->SetImageData((uint8_t *)img,int(maxX*maxY)*sizeof(uint16_t)); // troubles when maxX, mayY are *actually* float!
1275 //std::cout << "-------------------------------- X*Y*nbFrames*pixelSize " << X << " " << Y << " " << nbFrames << " " << pixelSize << std::endl;
1277 fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
1278 fileH->SetWriteModeToRaw();
1279 fileH->SetWriteTypeToDcmExplVR();
1280 if( !fileH->Write(dcmImageName))
1281 std::cout << "Failed for [" << dcmImageName << "]\n"
1282 << " File is unwrittable" << std::endl;