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;
62 // BrukerDataSet br_subject;
64 subject = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
65 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
68 std::cout << " Subject : [" << subject << "]" << std::endl;
69 canOpen =br_subject.LoadFile(subject);
73 std::cout << "Hopeless! no 'subject' found" << std::endl;
74 exit(0); /// \TODO throw an exception !
80 //br_subject.PrintSelf();
82 // get info for 'Study Description'
85 BrukerFieldData b_name=br_subject.GetFieldData("SUBJECT_name_string");
86 std::string subject_name = b_name.GetStringValue()[0];
87 strPatientName = subject_name;
88 cleanString(subject_name);
90 BrukerFieldData b_entry=br_subject.GetFieldData("SUBJECT_entry");
91 std::string subject_entry = b_entry.GetStringValue()[0];
92 //cleanString(subject_entry);
93 subject_entry = subject_entry.substr(11, subject_entry.size()-11);
95 BrukerFieldData b_position=br_subject.GetFieldData("SUBJECT_position");
96 std::string subject_position = b_position.GetStringValue()[0];
97 //cleanString(subject_position);
98 subject_position = subject_position.substr(9, subject_position.size()-9);
100 BrukerFieldData b_date=br_subject.GetFieldData("SUBJECT_date");
101 std::string subject_date = b_date.GetStringValue()[0];
102 strStudyTimeDate = subject_date;
103 cleanString(subject_date);
105 BrukerFieldData b_study_name=br_subject.GetFieldData("SUBJECT_study_name");
106 std::string subject_study_name = b_study_name.GetStringValue()[0];
107 subject_study_name = subject_study_name.substr(1, subject_study_name.size()-2);
108 cleanString(subject_date);
110 // subject_name is already in 'Patient Name'
111 strStudyDescr = /*subject_name + "." + */ subject_study_name + "." + subject_entry + "." + subject_position + "." + subject_date;
113 char outputDirName[(unsigned int) PATH_MAX+2];
115 strStudyUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
117 // -----------------------------------------------------
118 // Iterate to ALL the objets(files/directories) found in the input directory
119 // (this is level ZERO)
120 // each Directory (name : 1, 2, 3, ...) will be a Dicom Serie
121 // -----------------------------------------------------
123 GDCM_NAME_SPACE::DirListType::iterator it;
125 for (it = fileNames.begin();
126 it != fileNames.end();
129 if ( boost::filesystem::is_directory(*it) )
132 std::cout << "[" << *it << "] is a directory" << std::endl;
134 //BrukerDataSet br_acqp;
137 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
140 br_acqp.LoadFile(strAcqp);
143 std::string acqp_scan_name;
144 std::string acqp_method;
145 std::string acqp_protocol_location;
147 BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
148 acqp_protocol_location = b_protocol_location.GetStringValue()[0];
149 cleanString(acqp_protocol_location);
151 BrukerFieldData b_scan_name=br_acqp.GetFieldData("ACQ_scan_name");
152 acqp_scan_name = b_scan_name.GetStringValue()[0];
153 cleanString(acqp_scan_name);
155 BrukerFieldData b_method=br_acqp.GetFieldData("ACQ_method");
156 acqp_method = b_method.GetStringValue()[0];
157 cleanString(acqp_method);
159 BrukerFieldData b_list_size = br_acqp.GetFieldData("ACQ_O1_list_size");
160 b_list_size.PrintSelf(); //JP
162 nbSlices = b_list_size.GetIntValue()[0];
164 strSerieDescr = GDCM_NAME_SPACE::Util::GetName(*it)
165 /* + "." + acqp_protocol_location */ // always the same (in each acquisition)
166 + "." + acqp_scan_name
167 + "." + acqp_method.c_str();
169 sprintf(outputDirName, "%s%c%s", OutputDirName.c_str(),
170 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
171 strSerieDescr.c_str() );
173 std::cout << " ================================================================================\n"
174 << " === [" << GDCM_NAME_SPACE::Util::GetName(*it) << "] -> [" << strSerieDescr << "]\n"
175 << " ================================================================================"
180 printf ("outputDirName [%s]\n", outputDirName);
182 DealWithNiveau1(*it, outputDirName);
184 } // end of : for (GDCM_NAME_SPACE::DirListType::iterator it
188 // =====================================================================
190 void Bruker2Dicom::DealWithNiveau1(std::string level1Directory, std::string currentOutputDirName) {
192 // e.g. : at level 1, in B67d1.Bp1/6
194 // acqp fid imnd pdata pulseprogram spnam0 spnam1
196 bool res = CreateDirectory(currentOutputDirName);
199 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
202 GDCM_NAME_SPACE::DirList dirList(level1Directory, false, true); // DON'T get recursively the list of files
203 GDCM_NAME_SPACE::DirListType fileNames;
204 fileNames = dirList.GetFilenames();
205 // -----------------------------------------------------
206 // Iterate to ALL the objets(files/directories) found in the input directory
207 // -----------------------------------------------------
208 GDCM_NAME_SPACE::DirListType::iterator it;
210 for (it = fileNames.begin();
211 it != fileNames.end();
214 if ( boost::filesystem::is_regular(*it) )
215 //if ( ! boost::filesystem::is_directory(*it) )
218 std::cout << "--- [" << *it << "] is a file." << std::endl;
222 char outputDirName[(unsigned int) PATH_MAX+2];
223 //std::string firstName;
225 for (it = fileNames.begin();
226 it != fileNames.end();
229 if ( boost::filesystem::is_directory(*it) )
231 // will be always "pdata" ...
233 std::cout << "--- [" << *it << "] is a directory" << std::endl;
236 if (FileLine.startsWith("##$ACQ_size=")) {
237 if (FileLine.startsWith("##$NI=")) {
238 if (FileLine.startsWith("##$NR=")) {
239 if (FileLine.startsWith("##$ACQ_obj_order=")) {
240 if (FileLine.startsWith("##$ACQ_word_size=")) {
241 if (FileLine.startsWith("##$BYTORDA=")) {
242 if (FileLine.startsWith("##$PULPROG=")) {
245 sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
246 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
247 GDCM_NAME_SPACE::Util::GetName(*it).c_str());
250 std::string strMethod;
251 //std::string firstName = *(fileNames.begin());
253 strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin())) +
254 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
256 // std::cout << "---strMethod (for method)=> [" << strMethod << "]" << std::endl;
257 canOpen = br_method.LoadFile(strMethod);
260 strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
261 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
263 //std::cout << "---strMethod (for imnd) => [" << strMethod << "]" << std::endl;
264 canOpen = br_method.LoadFile(strMethod);
267 std::cout << "Hopeless! neither 'method' nor 'imnd' found" << std::endl;
268 exit(0); /// \TODO throw an exception !
272 std::cout << "open => [" << strMethod << "] successfully" << std::endl;
276 ##$PVM_Fov (dimension)
279 dans method (pour perfusion seulement?) :
280 ##$PVM_ObjOrderList=( 8 )
283 ##$PVM_SPackArrNSlices=( 2 )
286 DealWithNiveau2(*it,outputDirName );
291 // =====================================================================
293 void Bruker2Dicom::DealWithNiveau2(std::string level2Directory, std::string currentOutputDirName) {
295 // e.g. : at level 2 in B67d1.Bp1/6/pdata
297 // acqp fid imnd pdata pulseprogram spnam0 spnam1
300 bool res = CreateDirectory(currentOutputDirName);
303 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
307 GDCM_NAME_SPACE::DirList dirList(level2Directory, false, true); // DON'T get recursively the list of files
309 GDCM_NAME_SPACE::DirListType fileNames;
310 fileNames = dirList.GetFilenames();
312 char outputDirName[(unsigned int) PATH_MAX+2];
314 // -----------------------------------------------------
315 // Iterate to ALL the objets(files/directories) found in the input directory
316 // -----------------------------------------------------
317 GDCM_NAME_SPACE::DirListType::iterator it;
321 for (it = fileNames.begin();
322 it != fileNames.end();
325 if ( ! boost::filesystem::is_directory(*it) )
327 std::cout << "--- --- [" << *it << "] is a file.." << std::endl;
332 for (it = fileNames.begin();
333 it != fileNames.end();
336 if ( boost::filesystem::is_directory(*it) )
340 std::cout << "--- --- [" << *it << "] is a directory" << std::endl;
342 // sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
343 // GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
344 // GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
348 // (interest of previous method :
349 // If unaware user changed the pdata name, it goes on working
353 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
356 std::string str_isa_func_name;
357 canOpen = br_isa.LoadFile(str_isa);
360 sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
361 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
362 GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
367 BrukerFieldData b_isa_func_name = br_isa.GetFieldData("ISA_func_name");
369 str_isa_func_name = b_isa_func_name.GetStringValue()[0];
370 cleanString(str_isa_func_name);
372 sprintf(outputDirName, "%s%c%s.%s", currentOutputDirName.c_str(),
373 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
374 GDCM_NAME_SPACE::Util::GetName(*it).c_str(),
375 str_isa_func_name.c_str());
377 DealWithNiveau3(*it, outputDirName);
384 // =====================================================================
387 void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string currentOutputDirName){
390 // e.g. at level 3, in
392 // just to be able to go on checking // JP
393 if ( GDCM_NAME_SPACE::Util::GetName(level3Directory) != "1")
396 bool res = CreateDirectory(currentOutputDirName);
400 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
404 GDCM_NAME_SPACE::DirList dirList(level3Directory, false, true); // DON'T get recursively the list of files
405 GDCM_NAME_SPACE::DirListType::iterator it;
406 GDCM_NAME_SPACE::DirListType fileNames;
407 fileNames = dirList.GetFilenames();
409 char original2dseqName [(unsigned int) PATH_MAX+2];
410 char currentOutputMhdDirName [(unsigned int) PATH_MAX+2];
412 char outputMhdFileName [(unsigned int) PATH_MAX+2];
413 char output2dseqSliceFileName[(unsigned int) PATH_MAX+6]; // think about extra '.dcm'
414 char output2dseqName [(unsigned int) PATH_MAX+6];
415 char output2dseqCartoName [(unsigned int) PATH_MAX+6];
417 char copyFile[PATH_MAX + PATH_MAX + 5]; // Should be enough!
420 //-------------- try d3proc;
421 char char_d3proc[(unsigned int) PATH_MAX+2];
423 sprintf(char_d3proc,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"d3proc" );
426 std::cout << "try d3proc: --- => [" << char_d3proc << "]" << std::endl;
427 std::string str_d3proc(char_d3proc);
428 canOpen = br_d3proc.LoadFile(str_d3proc);
432 std::cout << "Hopeless! no 'd3proc' found" << std::endl;
433 exit(0); /// \TODO throw an exception !
436 canOpen = br_d3proc.FillMap();
439 std::cout << "Hopeless! FillMap failed on 'd3proc'" << std::endl;
440 exit(0); /// \TODO throw an exception !
443 //-------------- end try d3proc;
446 // -------------------try reco
448 char char_reco[(unsigned int) PATH_MAX+2];
450 sprintf(char_reco,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
451 //str_d3proc = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
452 // GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
455 std::cout << "try reco --- => [" << char_reco << "]" << std::endl;
456 std::string str_reco(char_reco);
457 canOpen = br_reco.LoadFile(str_reco);
459 if (!canOpen) // we try in directory ../1
462 std::cout << "[" << str_reco << "] not found " << std::endl;
463 std::string lastDirName = GDCM_NAME_SPACE::Util::GetPath(level3Directory);
464 //lastDirName = GDCM_NAME_SPACE::Util::GetPath(lastDirName);
465 sprintf(char_reco,"%s%c1%c%s", lastDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
467 canOpen = br_reco.LoadFile(str_reco);
470 std::cout << "Hopeless! cannot find 'reco' in [" << str_reco << "]" << std::endl;
471 exit(0); /// \TODO throw an exception !
475 canOpen = br_reco.FillMap();
478 std::cout << "Hopeless! FillMap failed on [" << str_reco << "]" << std::endl;
479 exit(0); /// \TODO throw an exception !
481 //std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
482 // br_reco.PrintSelf();
483 // std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
485 // -------------------end try reco
488 BrukerFieldData bX = br_d3proc.GetFieldData("IM_SIX");
489 int NX = bX.GetIntValue()[0];
491 std::cout << "IM_SIX " << NX << std::endl;
492 BrukerFieldData bY=br_d3proc.GetFieldData("IM_SIY");
493 int NY = bY.GetIntValue()[0];
495 std::cout << "IM_SIY " << NY << std::endl;
496 /// \todo : check if there are actually 3 dimensions or only 2
498 BrukerFieldData bZ= br_d3proc.GetFieldData("IM_SIZ");
499 int nbFrames = bZ.GetIntValue()[0];
500 std::cout << "IM_SIZ " << nbFrames << std::endl;
502 // WARNING DATTYPE is, either in {ip_short, ip_int, ip_char, ...}, or in {1, 2, 3, ...}
504 BrukerFieldData bDPT = br_d3proc.GetFieldData("DATTYPE");
506 std::string mhdDataPixelType;
508 getImhDataType(bDPT, mhdDataPixelType, pixelSize);
510 BrukerFieldData fov = br_method.GetFieldData("PVM_Fov");
511 double fovX = fov.GetDoubleValue()[0];
512 double fovY = fov.GetDoubleValue()[1];
514 std::cout << "FOV (ds method) " << fovX << " " << fovY << std::endl;
516 /// \TODO probabely a more sophisticated accessor will be necessary :
517 /// (cf : non contiguous slices, overlapping, slice thickness, space between slices, etc)
518 BrukerFieldData bsliceDistance = br_method.GetFieldData("PVM_SPackArrSliceDistance");
519 double sliceDistance = bsliceDistance.GetDoubleValue()[0];
523 sprintf(currentOutputMhdDirName, "%s%c%s", currentOutputDirName.c_str(),
524 GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "MhdFiles");
525 res = CreateDirectory( currentOutputMhdDirName );
527 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
532 std::cout << "Directory creation [" << currentOutputDirName << "]" << std::endl;
535 std::cout << "nbFrames " << nbFrames << std::endl;
536 std::cout << "nbSlices " << nbSlices << std::endl;
538 int nbInstants = nbFrames/nbSlices;
539 std::cout << "nbInstants (deduced )" << nbInstants << std::endl;
542 FILE *fp; // for MHD files
544 sprintf( original2dseqName, "%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "2dseq");
547 // \TODO : tenir compte du bazar precedent
549 // load 2dseq in memory
551 fp = fopen(original2dseqName, "rb");
554 std::cout << "Cannot open [" << original2dseqName << "] for reading" << std::endl;
558 unsigned char *buffer_2dseq = new unsigned char[NX*NY*pixelSize*nbSlices*nbInstants];
559 ///\ TODO : find a safer way to be sure to read everything!
560 size_t lgr = fread(buffer_2dseq, 1, NX*NY*pixelSize*nbSlices*nbInstants, fp);
562 // This one will be important!
563 // ---------------------------
564 imageSet = CreateImageSet ( );
567 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
568 if (nbInstants==1) // creer un seul fichier .mhd pour toutes les Slices! (images natives)
570 std::cout << "Single instant : do not split" << std::endl;
573 sprintf(outputMhdFileName, "%s%cMhdData_All_the_Slices.mhd", currentOutputMhdDirName,
574 GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
575 fp=fopen(outputMhdFileName, "w");
578 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
583 fprintf(fp, "ObjectType = Image\n");
584 fprintf(fp, "NDims = 3\n" );
585 fprintf(fp, "BinaryData = True \n" );
586 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
587 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices );
588 fprintf(fp, "HeaderSize = %d\n", 0);
589 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
590 fprintf(fp, "Position = 0 0 %d\n", 0 );
591 fprintf(fp, "Offset = 0 0 0\n" );
592 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
593 fprintf(fp, "ElementNumberOfChannels = 1\n" );
594 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
595 fprintf(fp, "ElementDataFile = %s\n", "../2dseq_All_the_Slices" );
598 sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices",
599 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
600 fp=fopen(output2dseqSliceFileName, "wb");
603 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
607 fwrite( buffer_2dseq, NX*NY*pixelSize, nbSlices, fp);
611 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
615 sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices.dcm",
616 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
618 /* ----------- Write Dicom Image ---------------*/
619 MakeDicomImage(buffer_2dseq,
624 fovX/NY, fovY/NY, sliceDistance,
625 output2dseqSliceFileName,
633 0,// index frame number
634 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
637 } // end if nbInstants = 1
639 else // more than ONE instant
642 // it's (slice1,slide2, ...)t1 ; (slice1,slide2, ...)t2 ; ...
644 unsigned char *pixelsForCurrentSlice = new unsigned char[NX*NY*pixelSize*nbInstants];
647 for (sliceNb=0; sliceNb<nbSlices; sliceNb++)
651 sprintf(outputMhdFileName, "%s%cMhdData_%03d.mhd", currentOutputMhdDirName,
652 GDCM_NAME_SPACE::GDCM_FILESEPARATOR, k );
654 std::cout << "--- Output MHD file [" << outputMhdFileName << "]" << std::endl;
655 fp=fopen(outputMhdFileName, "w");
658 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
663 /* ----------- Write MHD Image ---------------*/
665 // std::cout << "Open sucessfully[" << outputMhdFileName << "] for writting" << std::endl;
666 fprintf(fp, "ObjectType = Image\n");
667 fprintf(fp, "NDims = 3\n" );
668 fprintf(fp, "BinaryData = True \n" );
669 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
670 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbInstants);
671 fprintf(fp, "HeaderSize = %d\n", 0);
672 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, 1.0 ); // slice distance : no meaning for temporal serie
673 fprintf(fp, "Position = 0 0 %d\n", sliceNb );
674 fprintf(fp, "Offset = 0 0 0\n" );
675 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
676 fprintf(fp, "ElementNumberOfChannels = 1\n" );
677 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
678 fprintf(fp, "ElementDataFile = ..%c2dseq_Slice_%d\n", GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb );
682 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d",
683 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,sliceNb);
684 fp=fopen(output2dseqSliceFileName, "wb");
687 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
690 int frameSize = NX*NY*pixelSize;
691 for (instantNb=0; instantNb<nbInstants; instantNb++)
693 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
694 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
699 // std::cout << "end writting[" << output2dseqSliceFileName << "]" << std::endl;
706 sprintf(output2dseqSliceFileName, "%sdummy_buffer",
707 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
708 fp=fopen(output2dseqSliceFileName, "wb");
711 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
714 int frameSize = NX*NY*pixelSize;
715 for (instantNb=0; instantNb<nbInstants; instantNb++)
717 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
718 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
724 fp=fopen(output2dseqSliceFileName, "rb");
727 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for reading" << std::endl;
730 fread( pixelsForCurrentSlice,
731 frameSize*nbInstants,
734 // end of desperate try !
737 /* ----------- Write Dicom Image ---------------*/
739 int frameSize = NX*NY*pixelSize;
740 for (instantNb=0; instantNb<nbInstants; instantNb++)
742 memcpy(pixelsForCurrentSlice + frameSize*instantNb, buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize, frameSize);
745 int indOfFirsImageWithinImageSet = nbSlices*instantNb;
746 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d.dcm",
747 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb);
750 pixelsForCurrentSlice,
755 fovX/NY, fovY/NY, sliceDistance,
756 output2dseqSliceFileName,
765 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
768 std::cout << "--- Output DCM file [" << output2dseqSliceFileName << "]" << std::endl;
774 delete [] pixelsForCurrentSlice;
775 } // end nbInstants == 1
776 delete [] buffer_2dseq;
780 // -----------------------------------------------------
781 // deal with MatLab-generated Carto file.
782 // -----------------------------------------------------
784 dealWithCarto(fileNames, NX, NY, nbSlices, fovX, fovY, sliceDistance,
785 copyFile, currentOutputDirName, outputMhdFileName, output2dseqCartoName);
789 // ===========================================================================================
791 void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX, int NY, int nbSlices,
792 double fovX, double fovY, double sliceDistance,
793 char *copyFile, std::string ¤tOutputDirName,
794 char *outputMhdFileName, char *output2dseqCartoName)
796 // -----------------------------------------------------
797 // deal with MatLab-generated Carto file.
798 // -----------------------------------------------------
800 char *code[] ={ "ADC", "adc", "TTP", "ttp", "PEAK", "peak" , ""}; // add more carto file name identifiers if necessary; end with ""
802 GDCM_NAME_SPACE::DirListType::iterator it;
803 char file_name_ident[500];
806 // Iterate to ALL the objets(files/directories) found in the input directory
807 for (it = fileNames.begin();
808 it != fileNames.end();
811 if ( boost::filesystem::is_regular(*it) )
812 //if ( ! boost::filesystem::is_directory(*it) )
815 std::cout << "--- [" << *it << "] is a file..." << std::endl;
819 while (code[icode][0] != 0)
821 sprintf(file_name_ident, "2dseq_%s",code[icode]); // e.g "2dseq_ADC"
822 std::string::size_type loc = (*it).rfind(file_name_ident);
824 if ( loc != std::string::npos )
827 ///\ TODO : find a safer way to be sure to read everything!
828 unsigned char *buffer_carto = new unsigned char[NX*NY*sizeof(double)*nbSlices];
829 fp = fopen ( (*it).c_str(), "rb");
831 std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
834 fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
836 std::cout << "Deal with Carto file :[" <<*it << "], computed length : "
837 << NX*NY*sizeof(double)*nbSlices << std::endl;
838 std::string lastFileName = GDCM_NAME_SPACE::Util::GetName((*it).c_str());
841 // Copy the data file in the new directory
842 sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
843 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str());
845 sprintf(outputMhdFileName, "%s%c%s%s",
846 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".mhd" );
848 std::cout << "--- Output Carto MHD file [" << outputMhdFileName << "]" << std::endl;
851 fp=fopen(outputMhdFileName, "w");
854 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
858 fprintf(fp, "ObjectType = Image\n");
859 fprintf(fp, "NDims = 3\n" );
860 fprintf(fp, "BinaryData = True \n" );
861 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
862 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices);
863 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
864 fprintf(fp, "HeaderSize = %d\n", 0 );
865 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
866 fprintf(fp, "Position = 0 0 0\n" );
867 fprintf(fp, "Offset = 0 0 0\n" );
868 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
869 fprintf(fp, "ElementNumberOfChannels = 1\n" );
870 fprintf(fp, "ElementType = %s\n", "MET_DOUBLE" );
871 fprintf(fp, "ElementDataFile = %s\n", lastFileName.c_str() );
876 std::cout << "--- end write Carto MHD file [" << outputMhdFileName << "]" << std::endl;
879 // ----------- Write Dicom Image ---------------
883 sprintf(output2dseqCartoName, "%s%c%s%s",
884 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".dcm" );
886 std::cout << "--- end create name output2dseqCartoName file [" << output2dseqCartoName << "]" << std::endl;
888 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID(); //New SerieUID for each carto.
889 std::string strNewSerieDescr(strSerieDescr+ "_" +GDCM_NAME_SPACE::Util::GetName((*it).c_str()));
890 MakeDicomImage(buffer_carto,
895 fovX/NY, fovY/NY, sliceDistance,
896 output2dseqCartoName,
905 GDCM_NAME_SPACE::CREATED_IMAGE
909 delete [] buffer_carto;
911 std::cout << "--- End writing Carto DICOM file [" << output2dseqCartoName << "]" << std::endl;
912 break; // don't check for more ident on same file name!
918 } // end iterate on files
922 // ==========================================================================================================
924 bool Bruker2Dicom::CreateDirectory(std::string OutputDirName)
926 std::string systemCommand;
929 std::cout << "Check for output directory :[" << OutputDirName << "]."
931 if ( ! boost::filesystem::is_directory(OutputDirName) ) // dirout not found
933 std::string strDirNameout(OutputDirName); // to please gcc 4
934 systemCommand = "mkdir " + strDirNameout; // create it!
936 std::cout << systemCommand << std::endl;
937 system (systemCommand.c_str());
938 if ( ! boost::filesystem::is_directory(OutputDirName) ) // be sure it worked
941 std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
943 /// \todo : THROW AN EXCEPTION
948 std::cout << "Directory [" << OutputDirName << "] created." << std::endl;
954 std::cout << "Output Directory [" << OutputDirName << "] already exists; Used as is." << std::endl;
962 // ===========================================================================================
964 /// \TODO move cleanString to 'crea' ?
966 void Bruker2Dicom::cleanString(std::string &s)
969 if (s[l-1] == 0x0A || s[l-1] == 0x0D ) // CR or NL
974 if (s[l-1] == ' ' ) // blank space
982 std::string repChar("_");
983 GDCM_NAME_SPACE::Util::ReplaceSpecChar(s, repChar);
988 // ===========================================================================================
991 void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPixelType, int &pixelSize)
993 if(bDPT.GetDataType() == "string")
995 std::string brukerDataPixelType = bDPT.GetStringValue()[0];
996 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
997 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
999 if (brukerDataPixelType == "ip_short") {
1000 mhdDataPixelType = "MET_USHORT";
1003 if (brukerDataPixelType == "ip_int") {
1004 mhdDataPixelType = "MET_UINT";
1007 if (brukerDataPixelType == "ip_char") {
1008 mhdDataPixelType = "MET_UCHAR";
1011 /// \TODO : finish the list
1013 case 0 : fp << "ElementType = MET_CHAR" << std::endl;
1015 case 1 : fp << "ElementType = MET_UCHAR" << std::endl;
1017 case 2 : fp << "ElementType = MET_SHORT" << std::endl;
1019 case 3 : fp << "ElementType = MET_USHORT" << std::endl;
1021 case 4 : fp << "ElementType = MET_INT" << std::endl;
1023 case 5 : fp << "ElementType = MET_UINT" << std::endl;
1025 case 6 : fp << "ElementType = MET_FLOAT" << std::endl;
1027 case 7 : fp << "ElementType = MET_DOUBLE" << std::endl;
1032 int brukerDataPixelType = bDPT.GetIntValue()[0];
1033 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
1034 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1036 // Cross your fingers !!!
1038 // pb : found values : 2, 3, 5
1040 if (brukerDataPixelType == 2) {
1041 mhdDataPixelType = "MET_USHORT";
1044 if (brukerDataPixelType == 3) {
1045 mhdDataPixelType = "MET_USHORT";
1048 if (brukerDataPixelType == 1) {
1049 mhdDataPixelType = "MET_UCHAR";
1055 // ===========================================================================================
1057 std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
1059 std::vector<BrukerImage> imageSet;
1060 br_acqp.SetLoopStructure();
1061 std::vector<int> tempVect = br_acqp.GetLoopStructure() ;
1062 std::map<std::string, BrukerFieldData> map = br_acqp.GetBrukerHeaderMap();
1063 bool result = br_acqp.ObjectVaryingProperties.init(map,tempVect);
1065 br_acqp.SetImageLoopStructure();
1066 br_acqp.SetBrukerImageList();
1067 std::vector<std::vector<int> > brukerImageList = br_acqp.GetBrukerImageList();
1069 BrukerImage image(br_acqp,br_reco);
1070 image.Init(br_acqp,br_reco,1);
1072 for(int i=0;i<brukerImageList.size();i++)
1074 image.Init(br_acqp,br_reco,i);
1075 imageSet.push_back(image);
1078 // Just for checking
1081 std::vector<std::vector <double> > imageOrientation;
1082 std::vector <double> imagePosition;
1083 for(int i=0;i<brukerImageList.size();i++)
1085 // fread(buffer_2dseq, NX*NY*pixelSize*nbSlices*nbInstants, 1, fp);
1087 imagePosition = imageSet[i].getTranslationVectorRPS2XYZ();
1088 std::cout << "Position " << imagePosition[0] << " "
1089 << imagePosition[1] << " " << imagePosition[2] ;
1090 imageOrientation = imageSet[i].getRotationMatrixRPS2XYZ();
1091 std::cout << "\t Orientation " ;
1092 for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
1093 std::cout << imageOrientation[i1][i2] << " ";
1095 //std::cout << "\t Abs Time " << imageSet[i].getAbsoluteTimePosition();
1096 std::cout << "\t Relat Time " << imageSet[i].getRelativeTimePosition();
1098 std::cout << "\t [";
1099 for (int i3=0; i3<imageSet[i].getLoopStamp().size();i3++)
1100 std::cout << " " << imageSet[i].getLoopStamp()[i3];
1101 std::cout << "]" << std::endl;
1107 // ===========================================================================================
1109 void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels,
1114 double spacingX, double spacingY, double sliceDistance,
1115 std::string dcmImageName,
1116 const std::string &patientName,
1118 std::string &studyUID,
1119 std::string &serieUID,
1120 std::string &studyDescr,
1121 std::string &serieDescr,
1122 std::string &strStudyTimeDate,
1124 GDCM_NAME_SPACE::ImageContentType contentType
1127 std::ostringstream str;
1129 GDCM_NAME_SPACE::File *file;
1130 file = GDCM_NAME_SPACE::File::New();
1132 // Set the image size
1135 file->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
1138 file->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
1144 file->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames
1147 // Set the pixel type
1148 // //8, 16, 32, 64 (for double ?)
1151 file->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
1153 file->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
1156 str << pixelSize*8-1;
1157 file->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
1159 // Set the pixel representation // 0/1 , 0=unsigned
1160 file->InsertEntryString("1",0x0028,0x0103, "US"); // Pixel Representation
1162 // Set the samples per pixel // 1:Grey level, 3:RGB
1163 file->InsertEntryString("1",0x0028,0x0002, "US"); // Samples per Pixel
1165 // 0028 0030 DS 2 Pixel Spacing
1167 str << spacingX << "\\" << spacingY;
1168 file->InsertEntryString(str.str(),0x0028,0x0030, "DS"); // Pixel Spacing
1170 // 0018 0050 DS 1 Slice Thickness
1172 str << sliceDistance;
1173 file->InsertEntryString(str.str(),0x0018,0x0050, "DS");
1175 // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
1176 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1177 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1180 // OK : MR is NOT multiframe, but I want just a quick an dirty solution
1181 // 1.2.840.10008.5.1.4.1.1.4 MR Image Storage
1182 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1183 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1185 // if (strlen(patientName) != 0)
1186 file->InsertEntryString(patientName.c_str(),0x0010,0x0010, "PN"); // Patient's Name
1188 file->InsertEntryString(studyUID, 0x0020, 0x000d, "UI");
1189 file->InsertEntryString(serieUID, 0x0020, 0x000e, "UI");
1191 // 0008 0020 DA 1 Study Date
1192 // 0008 0030 TM 1 Study Time
1194 /// \TODO split into 2 strings!
1195 file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
1196 file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),0x0008,0x0030, "TM");
1198 file->InsertEntryString(studyDescr,0x0008,0x1030, "LO"); // Study Description
1199 file->InsertEntryString(serieDescr,0x0008,0x103e, "LO"); // Series Description
1201 //0008|0060 [CS] [Modality]
1202 file->InsertEntryString("MR",0x0008,0x0060, "CS");
1204 // 0020 0037 DS 6 Image Orientation (Patient)
1205 char charImageOrientation[256];
1208 std::cout << "try charImageOrientation " <<
1209 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0] << " " <<
1210 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1] << " " <<
1211 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2] << " " <<
1212 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0] << " " <<
1213 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1] << " " <<
1214 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] << std::endl ;
1216 sprintf(charImageOrientation,"%f\\%f\\%f \\ %f\\%f\\%f",
1217 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0],
1218 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1],
1219 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2],
1220 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0],
1221 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1],
1222 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] ) ;
1224 file->InsertEntryString(charImageOrientation,0x0020,0x0037, "DS");
1227 // 0020 0032 DS 3 Image Position (Patient)
1229 char charImagePosition[256];
1230 sprintf(charImagePosition,"%f\\%f\\%f",
1231 imageSet[imgNum].getTranslationVectorRPS2XYZ()[0],
1232 imageSet[imgNum].getTranslationVectorRPS2XYZ()[1],
1233 imageSet[imgNum].getTranslationVectorRPS2XYZ()[2]);
1235 file->InsertEntryString(charImagePosition,0x0020,0x0032, "DS"); //0020 0032 DS 3 Image Position (Patient)
1239 // 0020 0x1041 DS 1 Slice Location
1240 // sprintf(charImagePosition,"%f",float(imgNum));
1241 // file->InsertEntryString(charImagePosition,0x0020,0x1041, "DS");
1243 // Set Rescale Intercept
1246 file->InsertEntryString(str.str(),0x0028,0x1052,"DS");
1248 // Set Rescale Slope
1251 file->InsertEntryString(str.str(),0x0028,0x1053,"DS");
1254 GDCM_NAME_SPACE::FileHelper *fileH;
1255 fileH = GDCM_NAME_SPACE::FileHelper::New(file);
1256 fileH->SetContentType(contentType);
1258 // cast is just to avoid warnings (*no* conversion is performed)
1259 //fileH->SetImageData((uint8_t *)img,int(maxX*maxY)*sizeof(uint16_t)); // troubles when maxX, mayY are *actually* float!
1261 //std::cout << "-------------------------------- X*Y*nbFrames*pixelSize " << X << " " << Y << " " << nbFrames << " " << pixelSize << std::endl;
1263 fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
1264 fileH->SetWriteModeToRaw();
1265 fileH->SetWriteTypeToDcmExplVR();
1266 if( !fileH->Write(dcmImageName))
1267 std::cout << "Failed for [" << dcmImageName << "]\n"
1268 << " File is unwrittable" << std::endl;