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 strStudyDescr = subject_name + "." + subject_study_name + "." + subject_entry + "." + subject_position + "." + subject_date;
112 char outputDirName[(unsigned int) PATH_MAX+2];
114 strStudyUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
116 // -----------------------------------------------------
117 // Iterate to ALL the objets(files/directories) found in the input directory
118 // (this is level ZERO)
119 // each Directory (name : 1, 2, 3, ...) will be a Dicom Serie
120 // -----------------------------------------------------
122 GDCM_NAME_SPACE::DirListType::iterator it;
124 for (it = fileNames.begin();
125 it != fileNames.end();
128 if ( boost::filesystem::is_directory(*it) )
131 std::cout << "[" << *it << "] is a directory" << std::endl;
133 //BrukerDataSet br_acqp;
136 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
139 br_acqp.LoadFile(strAcqp);
142 std::string acqp_scan_name;
143 std::string acqp_method;
144 std::string acqp_protocol_location;
146 BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
147 acqp_protocol_location = b_protocol_location.GetStringValue()[0];
148 cleanString(acqp_protocol_location);
150 BrukerFieldData b_scan_name=br_acqp.GetFieldData("ACQ_scan_name");
151 acqp_scan_name = b_scan_name.GetStringValue()[0];
152 cleanString(acqp_scan_name);
154 BrukerFieldData b_method=br_acqp.GetFieldData("ACQ_method");
155 acqp_method = b_method.GetStringValue()[0];
156 cleanString(acqp_method);
158 BrukerFieldData b_list_size = br_acqp.GetFieldData("ACQ_O1_list_size");
159 b_list_size.PrintSelf(); //JP
161 nbSlices = b_list_size.GetIntValue()[0];
163 strSerieDescr = GDCM_NAME_SPACE::Util::GetName(*it)
164 + "." + acqp_protocol_location
165 + "." + acqp_scan_name
166 + "." + acqp_method.c_str();
168 sprintf(outputDirName, "%s%c%s", OutputDirName.c_str(),
169 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
170 strSerieDescr.c_str() );
172 std::cout << " ================================================================================\n"
173 << " === [" << GDCM_NAME_SPACE::Util::GetName(*it) << "] -> [" << strSerieDescr << "]\n"
174 << " ================================================================================"
178 std::cout << " ================================================================================\n"
179 << " ========================= [" << GDCM_NAME_SPACE::Util::GetName(*it).c_str()
180 << acqp_protocol_location.c_str()
181 << acqp_scan_name.c_str()
182 << acqp_method.c_str()
184 << " ================================================================================"
188 printf ("outputDirName [%s]\n", outputDirName);
190 DealWithNiveau1(*it, outputDirName);
192 } // end of : for (GDCM_NAME_SPACE::DirListType::iterator it
196 // =====================================================================
198 void Bruker2Dicom::DealWithNiveau1(std::string level1Directory, std::string currentOutputDirName) {
200 // e.g. : at level 1, in B67d1.Bp1/6
202 // acqp fid imnd pdata pulseprogram spnam0 spnam1
204 bool res = CreateDirectory(currentOutputDirName);
207 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
210 GDCM_NAME_SPACE::DirList dirList(level1Directory, false, true); // DON'T get recursively the list of files
211 GDCM_NAME_SPACE::DirListType fileNames;
212 fileNames = dirList.GetFilenames();
213 // -----------------------------------------------------
214 // Iterate to ALL the objets(files/directories) found in the input directory
215 // -----------------------------------------------------
216 GDCM_NAME_SPACE::DirListType::iterator it;
218 for (it = fileNames.begin();
219 it != fileNames.end();
222 if ( boost::filesystem::is_regular(*it) )
223 //if ( ! boost::filesystem::is_directory(*it) )
226 std::cout << "--- [" << *it << "] is a file." << std::endl;
230 char outputDirName[(unsigned int) PATH_MAX+2];
231 //std::string firstName;
233 for (it = fileNames.begin();
234 it != fileNames.end();
237 if ( boost::filesystem::is_directory(*it) )
239 // will be always "pdata" ...
241 std::cout << "--- [" << *it << "] is a directory" << std::endl;
244 if (FileLine.startsWith("##$ACQ_size=")) {
245 if (FileLine.startsWith("##$NI=")) {
246 if (FileLine.startsWith("##$NR=")) {
247 if (FileLine.startsWith("##$ACQ_obj_order=")) {
248 if (FileLine.startsWith("##$ACQ_word_size=")) {
249 if (FileLine.startsWith("##$BYTORDA=")) {
250 if (FileLine.startsWith("##$PULPROG=")) {
253 sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
254 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
255 GDCM_NAME_SPACE::Util::GetName(*it).c_str());
258 std::string strMethod;
259 //std::string firstName = *(fileNames.begin());
261 strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin())) +
262 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
264 // std::cout << "---strMethod (for method)=> [" << strMethod << "]" << std::endl;
265 canOpen = br_method.LoadFile(strMethod);
268 strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
269 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
271 //std::cout << "---strMethod (for imnd) => [" << strMethod << "]" << std::endl;
272 canOpen = br_method.LoadFile(strMethod);
275 std::cout << "Hopeless! neither 'method' nor 'imnd' found" << std::endl;
276 exit(0); /// \TODO throw an exception !
280 std::cout << "open => [" << strMethod << "] successfully" << std::endl;
284 ##$PVM_Fov (dimension)
287 dans method (pour perfusion seulement?) :
288 ##$PVM_ObjOrderList=( 8 )
291 ##$PVM_SPackArrNSlices=( 2 )
294 DealWithNiveau2(*it,outputDirName );
299 // =====================================================================
301 void Bruker2Dicom::DealWithNiveau2(std::string level2Directory, std::string currentOutputDirName) {
303 // e.g. : at level 2 in B67d1.Bp1/6/pdata
305 // acqp fid imnd pdata pulseprogram spnam0 spnam1
308 bool res = CreateDirectory(currentOutputDirName);
311 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
315 GDCM_NAME_SPACE::DirList dirList(level2Directory, false, true); // DON'T get recursively the list of files
317 GDCM_NAME_SPACE::DirListType fileNames;
318 fileNames = dirList.GetFilenames();
320 char outputDirName[(unsigned int) PATH_MAX+2];
322 // -----------------------------------------------------
323 // Iterate to ALL the objets(files/directories) found in the input directory
324 // -----------------------------------------------------
325 GDCM_NAME_SPACE::DirListType::iterator it;
329 for (it = fileNames.begin();
330 it != fileNames.end();
333 if ( ! boost::filesystem::is_directory(*it) )
335 std::cout << "--- --- [" << *it << "] is a file.." << std::endl;
340 for (it = fileNames.begin();
341 it != fileNames.end();
344 if ( boost::filesystem::is_directory(*it) )
348 std::cout << "--- --- [" << *it << "] is a directory" << std::endl;
350 // sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
351 // GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
352 // GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
356 // (interest of previous method :
357 // If unaware user changed the pdata name, it goes on working
361 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
364 std::string str_isa_func_name;
365 canOpen = br_isa.LoadFile(str_isa);
368 sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
369 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
370 GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
375 BrukerFieldData b_isa_func_name = br_isa.GetFieldData("ISA_func_name");
377 str_isa_func_name = b_isa_func_name.GetStringValue()[0];
378 cleanString(str_isa_func_name);
380 sprintf(outputDirName, "%s%c%s.%s", currentOutputDirName.c_str(),
381 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
382 GDCM_NAME_SPACE::Util::GetName(*it).c_str(),
383 str_isa_func_name.c_str());
385 DealWithNiveau3(*it, outputDirName);
392 // =====================================================================
395 void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string currentOutputDirName){
398 // e.g. at level 3, in
400 // just to be able to go on checking // JP
401 if ( GDCM_NAME_SPACE::Util::GetName(level3Directory) != "1")
404 bool res = CreateDirectory(currentOutputDirName);
408 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
412 GDCM_NAME_SPACE::DirList dirList(level3Directory, false, true); // DON'T get recursively the list of files
413 GDCM_NAME_SPACE::DirListType::iterator it;
414 GDCM_NAME_SPACE::DirListType fileNames;
415 fileNames = dirList.GetFilenames();
417 char original2dseqName [(unsigned int) PATH_MAX+2];
418 char currentOutputMhdDirName [(unsigned int) PATH_MAX+2];
420 char outputMhdFileName [(unsigned int) PATH_MAX+2];
421 char output2dseqSliceFileName[(unsigned int) PATH_MAX+6]; // think about extra '.dcm'
422 char output2dseqName [(unsigned int) PATH_MAX+6];
423 char output2dseqCartoName [(unsigned int) PATH_MAX+6];
425 char copyFile[PATH_MAX + PATH_MAX + 5]; // Should be enough!
428 //-------------- try d3proc;
429 char char_d3proc[(unsigned int) PATH_MAX+2];
431 sprintf(char_d3proc,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"d3proc" );
434 std::cout << "try d3proc: --- => [" << char_d3proc << "]" << std::endl;
435 std::string str_d3proc(char_d3proc);
436 canOpen = br_d3proc.LoadFile(str_d3proc);
440 std::cout << "Hopeless! no 'd3proc' found" << std::endl;
441 exit(0); /// \TODO throw an exception !
444 canOpen = br_d3proc.FillMap();
447 std::cout << "Hopeless! FillMap failed on 'd3proc'" << std::endl;
448 exit(0); /// \TODO throw an exception !
451 //-------------- end try d3proc;
454 // -------------------try reco
456 char char_reco[(unsigned int) PATH_MAX+2];
458 sprintf(char_reco,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
459 //str_d3proc = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
460 // GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
463 std::cout << "try reco --- => [" << char_reco << "]" << std::endl;
464 std::string str_reco(char_reco);
465 canOpen = br_reco.LoadFile(str_reco);
467 if (!canOpen) // we try in directory ../1
470 std::cout << "[" << str_reco << "] not found " << std::endl;
471 std::string lastDirName = GDCM_NAME_SPACE::Util::GetPath(level3Directory);
472 //lastDirName = GDCM_NAME_SPACE::Util::GetPath(lastDirName);
473 sprintf(char_reco,"%s%c1%c%s", lastDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
475 canOpen = br_reco.LoadFile(str_reco);
478 std::cout << "Hopeless! cannot find 'reco' in [" << str_reco << "]" << std::endl;
479 exit(0); /// \TODO throw an exception !
483 canOpen = br_reco.FillMap();
486 std::cout << "Hopeless! FillMap failed on [" << str_reco << "]" << std::endl;
487 exit(0); /// \TODO throw an exception !
489 //std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
490 // br_reco.PrintSelf();
491 // std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
493 // -------------------end try reco
496 BrukerFieldData bX = br_d3proc.GetFieldData("IM_SIX");
497 int NX = bX.GetIntValue()[0];
499 std::cout << "IM_SIX " << NX << std::endl;
500 BrukerFieldData bY=br_d3proc.GetFieldData("IM_SIY");
501 int NY = bY.GetIntValue()[0];
503 std::cout << "IM_SIY " << NY << std::endl;
504 /// \todo : check if there are actually 3 dimensions or only 2
506 BrukerFieldData bZ= br_d3proc.GetFieldData("IM_SIZ");
507 int nbFrames = bZ.GetIntValue()[0];
508 std::cout << "IM_SIZ " << nbFrames << std::endl;
510 // WARNING DATTYPE is, either in {ip_short, ip_int, ip_char, ...}, or in {1, 2, 3, ...}
512 BrukerFieldData bDPT = br_d3proc.GetFieldData("DATTYPE");
514 std::string mhdDataPixelType;
516 getImhDataType(bDPT, mhdDataPixelType, pixelSize);
518 BrukerFieldData fov = br_method.GetFieldData("PVM_Fov");
519 double fovX = fov.GetDoubleValue()[0];
520 double fovY = fov.GetDoubleValue()[1];
522 std::cout << "FOV (ds method) " << fovX << " " << fovY << std::endl;
524 /// \TODO probabely a more sophisticated accessor will be necessary :
525 /// (cf : non contiguous slices, overlapping, slice thickness, space between slices, etc)
526 BrukerFieldData bsliceDistance = br_method.GetFieldData("PVM_SPackArrSliceDistance");
527 double sliceDistance = bsliceDistance.GetDoubleValue()[0];
531 sprintf(currentOutputMhdDirName, "%s%c%s", currentOutputDirName.c_str(),
532 GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "MhdFiles");
533 res = CreateDirectory( currentOutputMhdDirName );
535 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
540 std::cout << "Directory creation [" << currentOutputDirName << "]" << std::endl;
543 std::cout << "nbFrames " << nbFrames << std::endl;
544 std::cout << "nbSlices " << nbSlices << std::endl;
546 int nbInstants = nbFrames/nbSlices;
547 std::cout << "nbInstants (deduced )" << nbInstants << std::endl;
550 FILE *fp; // for MHD files
552 sprintf( original2dseqName, "%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "2dseq");
555 // \TODO : tenir compte du bazar precedent
557 // load 2dseq in memory
559 fp = fopen(original2dseqName, "rb");
562 std::cout << "Cannot open [" << original2dseqName << "] for reading" << std::endl;
566 unsigned char *buffer_2dseq = new unsigned char[NX*NY*pixelSize*nbSlices*nbInstants];
567 ///\ TODO : find a safer way to be sure to read everything!
568 size_t lgr = fread(buffer_2dseq, 1, NX*NY*pixelSize*nbSlices*nbInstants, fp);
570 // This one will be important!
571 // ---------------------------
572 imageSet = CreateImageSet ( );
574 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
575 if (nbInstants==1) // creer un seul fichier .mhd pour toutes les Slices! (images natives)
577 std::cout << "Single instant : do not split" << std::endl;
580 sprintf(outputMhdFileName, "%s%cMhdData_All_the_Slices.mhd", currentOutputMhdDirName,
581 GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
582 fp=fopen(outputMhdFileName, "w");
585 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
590 fprintf(fp, "ObjectType = Image\n");
591 fprintf(fp, "NDims = 3\n" );
592 fprintf(fp, "BinaryData = True \n" );
593 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
594 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices );
595 fprintf(fp, "HeaderSize = %d\n", 0);
596 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
597 fprintf(fp, "Position = 0 0 %d\n", 0 );
598 fprintf(fp, "Offset = 0 0 0\n" );
599 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
600 fprintf(fp, "ElementNumberOfChannels = 1\n" );
601 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
602 fprintf(fp, "ElementDataFile = %s\n", "../2dseq_All_the_Slices" );
605 sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices",
606 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
607 fp=fopen(output2dseqSliceFileName, "wb");
610 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
614 fwrite( buffer_2dseq, NX*NY*pixelSize, nbSlices, fp);
617 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
621 sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices.dcm",
622 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
624 /* ----------- Write Dicom Image ---------------*/
625 MakeDicomImage(buffer_2dseq,
630 fovX/NY, fovY/NY, sliceDistance,
631 output2dseqSliceFileName,
639 0,// index frame number
640 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
643 } // end if nbInstants = 1
645 else // more than ONE instant
648 // it's (slice1,slide2, ...)t1 ; (slice1,slide2, ...)t2 ; ...
650 unsigned char *pixelsForCurrentSlice = new unsigned char[NX*NY*pixelSize*nbInstants];
653 for (sliceNb=0; sliceNb<nbSlices; sliceNb++)
657 sprintf(outputMhdFileName, "%s%cMhdData_%03d.mhd", currentOutputMhdDirName,
658 GDCM_NAME_SPACE::GDCM_FILESEPARATOR, k );
660 std::cout << "--- Output MHD file [" << outputMhdFileName << "]" << std::endl;
661 fp=fopen(outputMhdFileName, "w");
664 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
669 /* ----------- Write MHD Image ---------------*/
671 // std::cout << "Open sucessfully[" << outputMhdFileName << "] for writting" << std::endl;
672 fprintf(fp, "ObjectType = Image\n");
673 fprintf(fp, "NDims = 3\n" );
674 fprintf(fp, "BinaryData = True \n" );
675 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
676 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbInstants);
677 fprintf(fp, "HeaderSize = %d\n", 0);
678 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, 1.0 ); // slice distance : no meaning for temporal serie
679 fprintf(fp, "Position = 0 0 %d\n", sliceNb );
680 fprintf(fp, "Offset = 0 0 0\n" );
681 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
682 fprintf(fp, "ElementNumberOfChannels = 1\n" );
683 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
684 fprintf(fp, "ElementDataFile = ..%c2dseq_Slice_%d\n", GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb );
688 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d",
689 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,sliceNb);
690 fp=fopen(output2dseqSliceFileName, "wb");
693 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
696 int frameSize = NX*NY*pixelSize;
697 for (instantNb=0; instantNb<nbInstants; instantNb++)
699 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
700 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
705 // std::cout << "end writting[" << output2dseqSliceFileName << "]" << std::endl;
712 sprintf(output2dseqSliceFileName, "%sdummy_buffer",
713 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
714 fp=fopen(output2dseqSliceFileName, "wb");
717 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
720 int frameSize = NX*NY*pixelSize;
721 for (instantNb=0; instantNb<nbInstants; instantNb++)
723 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
724 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
730 fp=fopen(output2dseqSliceFileName, "rb");
733 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for reading" << std::endl;
736 fread( pixelsForCurrentSlice,
737 frameSize*nbInstants,
740 // end of desperate try !
743 /* ----------- Write Dicom Image ---------------*/
745 int frameSize = NX*NY*pixelSize;
746 for (instantNb=0; instantNb<nbInstants; instantNb++)
748 memcpy(pixelsForCurrentSlice + frameSize*instantNb, buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize, frameSize);
751 int indOfFirsImageWithinImageSet = nbSlices*instantNb;
752 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d.dcm",
753 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb);
756 pixelsForCurrentSlice,
761 fovX/NY, fovY/NY, sliceDistance,
762 output2dseqSliceFileName,
771 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
774 std::cout << "--- Output DCM file [" << output2dseqSliceFileName << "]" << std::endl;
780 delete [] pixelsForCurrentSlice;
781 } // end nbInstants == 1
782 delete [] buffer_2dseq;
786 // -----------------------------------------------------
787 // deal with MatLab-generated Carto file.
788 // -----------------------------------------------------
790 dealWithCarto(fileNames, NX, NY, nbSlices, fovX, fovY, sliceDistance,
791 copyFile, currentOutputDirName, outputMhdFileName, output2dseqCartoName);
795 // ===========================================================================================
797 void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX, int NY, int nbSlices,
798 double fovX, double fovY, double sliceDistance,
799 char *copyFile, std::string ¤tOutputDirName,
800 char *outputMhdFileName, char *output2dseqCartoName)
802 // -----------------------------------------------------
803 // deal with MatLab-generated Carto file.
804 // -----------------------------------------------------
806 char *code[] ={ "ADC", "adc", "TTP", "ttp", "PEAK", "peak" , ""}; // add more carto file name identifiers if necessary; end with ""
808 GDCM_NAME_SPACE::DirListType::iterator it;
809 char file_name_ident[500];
812 // Iterate to ALL the objets(files/directories) found in the input directory
813 for (it = fileNames.begin();
814 it != fileNames.end();
817 if ( boost::filesystem::is_regular(*it) )
818 //if ( ! boost::filesystem::is_directory(*it) )
821 std::cout << "--- [" << *it << "] is a file..." << std::endl;
825 while (code[icode][0] != 0)
827 sprintf(file_name_ident, "2dseq_%s",code[icode]); // e.g "2dseq_ADC"
828 std::string::size_type loc = (*it).rfind(file_name_ident);
830 if ( loc != std::string::npos )
833 ///\ TODO : find a safer way to be sure to read everything!
834 unsigned char *buffer_carto = new unsigned char[NX*NY*sizeof(double)*nbSlices];
835 fp = fopen ( (*it).c_str(), "rb");
837 std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
840 fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
842 std::cout << "Deal with Carto file :[" <<*it << "], computed length : "
843 << NX*NY*sizeof(double)*nbSlices << std::endl;
844 std::string lastFileName = GDCM_NAME_SPACE::Util::GetName((*it).c_str());
847 // Copy the data file in the new directory
848 sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
849 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str());
851 sprintf(outputMhdFileName, "%s%c%s%s",
852 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".mhd" );
854 std::cout << "--- Output Carto MHD file [" << outputMhdFileName << "]" << std::endl;
857 fp=fopen(outputMhdFileName, "w");
860 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
864 fprintf(fp, "ObjectType = Image\n");
865 fprintf(fp, "NDims = 3\n" );
866 fprintf(fp, "BinaryData = True \n" );
867 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
868 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices);
869 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
870 fprintf(fp, "HeaderSize = %d\n", 0 );
871 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
872 fprintf(fp, "Position = 0 0 0\n" );
873 fprintf(fp, "Offset = 0 0 0\n" );
874 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
875 fprintf(fp, "ElementNumberOfChannels = 1\n" );
876 fprintf(fp, "ElementType = %s\n", "MET_DOUBLE" );
877 fprintf(fp, "ElementDataFile = %s\n", lastFileName.c_str() );
882 std::cout << "--- end write Carto MHD file [" << outputMhdFileName << "]" << std::endl;
885 // ----------- Write Dicom Image ---------------
889 sprintf(output2dseqCartoName, "%s%c%s%s",
890 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".dcm" );
892 std::cout << "--- end create name output2dseqCartoName file [" << output2dseqCartoName << "]" << std::endl;
894 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID(); //New SerieUID for each carto.
895 std::string strNewSerieDescr(strSerieDescr+ "_" +GDCM_NAME_SPACE::Util::GetName((*it).c_str()));
896 MakeDicomImage(buffer_carto,
901 fovX/NY, fovY/NY, sliceDistance,
902 output2dseqCartoName,
911 GDCM_NAME_SPACE::CREATED_IMAGE
915 delete [] buffer_carto;
917 std::cout << "--- End writing Carto DICOM file [" << output2dseqCartoName << "]" << std::endl;
918 break; // don't check for more ident on same file name!
924 } // end iterate on files
928 // ==========================================================================================================
930 bool Bruker2Dicom::CreateDirectory(std::string OutputDirName)
932 std::string systemCommand;
935 std::cout << "Check for output directory :[" << OutputDirName << "]."
937 if ( ! boost::filesystem::is_directory(OutputDirName) ) // dirout not found
939 std::string strDirNameout(OutputDirName); // to please gcc 4
940 systemCommand = "mkdir " + strDirNameout; // create it!
942 std::cout << systemCommand << std::endl;
943 system (systemCommand.c_str());
944 if ( ! boost::filesystem::is_directory(OutputDirName) ) // be sure it worked
947 std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
949 /// \todo : THROW AN EXCEPTION
954 std::cout << "Directory [" << OutputDirName << "] created." << std::endl;
960 std::cout << "Output Directory [" << OutputDirName << "] already exists; Used as is." << std::endl;
968 // ===========================================================================================
970 /// \TODO move cleanString to 'crea' ?
972 void Bruker2Dicom::cleanString(std::string &s)
975 if (s[l-1] == 0x0A || s[l-1] == 0x0D ) // CR or NL
980 if (s[l-1] == ' ' ) // blank space
988 std::string repChar("_");
989 GDCM_NAME_SPACE::Util::ReplaceSpecChar(s, repChar);
994 // ===========================================================================================
997 void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPixelType, int &pixelSize)
999 if(bDPT.GetDataType() == "string")
1001 std::string brukerDataPixelType = bDPT.GetStringValue()[0];
1002 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
1003 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1005 if (brukerDataPixelType == "ip_short") {
1006 mhdDataPixelType = "MET_USHORT";
1009 if (brukerDataPixelType == "ip_int") {
1010 mhdDataPixelType = "MET_UINT";
1013 if (brukerDataPixelType == "ip_char") {
1014 mhdDataPixelType = "MET_UCHAR";
1017 /// \TODO : finish the list
1019 case 0 : fp << "ElementType = MET_CHAR" << std::endl;
1021 case 1 : fp << "ElementType = MET_UCHAR" << std::endl;
1023 case 2 : fp << "ElementType = MET_SHORT" << std::endl;
1025 case 3 : fp << "ElementType = MET_USHORT" << std::endl;
1027 case 4 : fp << "ElementType = MET_INT" << std::endl;
1029 case 5 : fp << "ElementType = MET_UINT" << std::endl;
1031 case 6 : fp << "ElementType = MET_FLOAT" << std::endl;
1033 case 7 : fp << "ElementType = MET_DOUBLE" << std::endl;
1038 int brukerDataPixelType = bDPT.GetIntValue()[0];
1039 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
1040 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1042 // Cross your fingers !!!
1044 // pb : found values : 2, 3, 5
1046 if (brukerDataPixelType == 2) {
1047 mhdDataPixelType = "MET_USHORT";
1050 if (brukerDataPixelType == 3) {
1051 mhdDataPixelType = "MET_USHORT";
1054 if (brukerDataPixelType == 1) {
1055 mhdDataPixelType = "MET_UCHAR";
1061 // ===========================================================================================
1063 std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
1065 std::vector<BrukerImage> imageSet;
1066 br_acqp.SetLoopStructure();
1067 std::vector<int> tempVect = br_acqp.GetLoopStructure() ;
1068 std::map<std::string, BrukerFieldData> map = br_acqp.GetBrukerHeaderMap();
1069 bool result = br_acqp.ObjectVaryingProperties.init(map,tempVect);
1071 br_acqp.SetImageLoopStructure();
1072 br_acqp.SetBrukerImageList();
1073 std::vector<std::vector<int> > brukerImageList = br_acqp.GetBrukerImageList();
1075 BrukerImage image(br_acqp,br_reco);
1076 image.Init(br_acqp,br_reco,1);
1078 for(int i=0;i<brukerImageList.size();i++)
1080 image.Init(br_acqp,br_reco,i);
1081 imageSet.push_back(image);
1084 // Just for checking
1087 std::vector<std::vector <double> > imageOrientation;
1088 std::vector <double> imagePosition;
1089 for(int i=0;i<brukerImageList.size();i++)
1091 // fread(buffer_2dseq, NX*NY*pixelSize*nbSlices*nbInstants, 1, fp);
1093 imagePosition = imageSet[i].getTranslationVectorRPS2XYZ();
1094 std::cout << "Position " << imagePosition[0] << " "
1095 << imagePosition[1] << " " << imagePosition[2] ;
1096 imageOrientation = imageSet[i].getRotationMatrixRPS2XYZ();
1097 std::cout << "\t Orientation " ;
1098 for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
1099 std::cout << imageOrientation[i1][i2] << " ";
1101 //std::cout << "\t Abs Time " << imageSet[i].getAbsoluteTimePosition();
1102 std::cout << "\t Relat Time " << imageSet[i].getRelativeTimePosition();
1104 std::cout << "\t [";
1105 for (int i3=0; i3<imageSet[i].getLoopStamp().size();i3++)
1106 std::cout << " " << imageSet[i].getLoopStamp()[i3];
1107 std::cout << "]" << std::endl;
1113 // ===========================================================================================
1115 void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels,
1120 double spacingX, double spacingY, double sliceDistance,
1121 std::string dcmImageName,
1122 const std::string &patientName,
1124 std::string &studyUID,
1125 std::string &serieUID,
1126 std::string &studyDescr,
1127 std::string &serieDescr,
1128 std::string &strStudyTimeDate,
1130 GDCM_NAME_SPACE::ImageContentType contentType
1133 std::ostringstream str;
1135 GDCM_NAME_SPACE::File *file;
1136 file = GDCM_NAME_SPACE::File::New();
1138 // Set the image size
1141 file->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
1144 file->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
1150 file->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames
1153 // Set the pixel type
1154 // //8, 16, 32, 64 (for double ?)
1157 file->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
1159 file->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
1162 str << pixelSize*8-1;
1163 file->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
1165 // Set the pixel representation // 0/1 , 0=unsigned
1166 file->InsertEntryString("1",0x0028,0x0103, "US"); // Pixel Representation
1168 // Set the samples per pixel // 1:Grey level, 3:RGB
1169 file->InsertEntryString("1",0x0028,0x0002, "US"); // Samples per Pixel
1171 // 0028 0030 DS 2 Pixel Spacing
1173 str << spacingX << "\\" << spacingY;
1174 file->InsertEntryString(str.str(),0x0028,0x0030, "DS"); // Pixel Spacing
1176 // 0018 0050 DS 1 Slice Thickness
1178 str << sliceDistance;
1179 file->InsertEntryString(str.str(),0x0018,0x0050, "DS");
1181 // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
1182 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1183 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1186 // OK : MR is NOT multiframe, but I want just a quick an dirty solution
1187 // 1.2.840.10008.5.1.4.1.1.4 MR Image Storage
1188 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1189 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1191 // if (strlen(patientName) != 0)
1192 file->InsertEntryString(patientName.c_str(),0x0010,0x0010, "PN"); // Patient's Name
1194 file->InsertEntryString(studyUID, 0x0020, 0x000d, "UI");
1195 file->InsertEntryString(serieUID, 0x0020, 0x000e, "UI");
1197 // 0008 0020 DA 1 Study Date
1198 // 0008 0030 TM 1 Study Time
1200 /// \TODO split into 2 strings!
1201 file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
1202 file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),0x0008,0x0030, "TM");
1204 file->InsertEntryString(studyDescr,0x0008,0x1030, "LO"); // Study Description
1205 file->InsertEntryString(serieDescr,0x0008,0x103e, "LO"); // Series Description
1207 //0008|0060 [CS] [Modality]
1208 file->InsertEntryString("MR",0x0008,0x0060, "CS");
1210 // 0020 0037 DS 6 Image Orientation (Patient)
1211 char charImageOrientation[256];
1214 std::cout << "try charImageOrientation " <<
1215 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0] << " " <<
1216 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1] << " " <<
1217 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2] << " " <<
1218 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0] << " " <<
1219 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1] << " " <<
1220 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] << std::endl ;
1222 sprintf(charImageOrientation,"%f\\%f\\%f \\ %f\\%f\\%f",
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] ) ;
1230 file->InsertEntryString(charImageOrientation,0x0020,0x0037, "DS");
1233 // 0020 0032 DS 3 Image Position (Patient)
1235 char charImagePosition[256];
1236 sprintf(charImagePosition,"%f\\%f\\%f",
1237 imageSet[imgNum].getTranslationVectorRPS2XYZ()[0],
1238 imageSet[imgNum].getTranslationVectorRPS2XYZ()[1],
1239 imageSet[imgNum].getTranslationVectorRPS2XYZ()[2]);
1241 file->InsertEntryString(charImagePosition,0x0020,0x0032, "DS"); //0020 0032 DS 3 Image Position (Patient)
1245 // 0020 0x1041 DS 1 Slice Location
1246 // sprintf(charImagePosition,"%f",float(imgNum));
1247 // file->InsertEntryString(charImagePosition,0x0020,0x1041, "DS");
1249 // Set Rescale Intercept
1252 file->InsertEntryString(str.str(),0x0028,0x1052,"DS");
1254 // Set Rescale Slope
1257 file->InsertEntryString(str.str(),0x0028,0x1053,"DS");
1260 GDCM_NAME_SPACE::FileHelper *fileH;
1261 fileH = GDCM_NAME_SPACE::FileHelper::New(file);
1262 fileH->SetContentType(contentType);
1264 // cast is just to avoid warnings (*no* conversion is performed)
1265 //fileH->SetImageData((uint8_t *)img,int(maxX*maxY)*sizeof(uint16_t)); // troubles when maxX, mayY are *actually* float!
1267 //std::cout << "-------------------------------- X*Y*nbFrames*pixelSize " << X << " " << Y << " " << nbFrames << " " << pixelSize << std::endl;
1269 fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
1270 fileH->SetWriteModeToRaw();
1271 fileH->SetWriteTypeToDcmExplVR();
1272 if( !fileH->Write(dcmImageName))
1273 std::cout << "Failed for [" << dcmImageName << "]\n"
1274 << " File is unwrittable" << std::endl;