1 #include "bruker2dicom.h"
3 #ifndef PATH_MAX // If not defined yet : do it
9 bool Bruker2Dicom::Execute()
11 // ----- Begin Processing -----
13 bool bigEndian = GDCM_NAME_SPACE::Util::IsCurrentProcessorBigEndian();
15 if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(InputDirName) )
17 std::cout << "KO : [" << InputDirName << "] is not a Directory." << std::endl;
23 std::cout << "OK : [" << InputDirName << "] is a Directory." << std::endl;
26 std::string strDirNameOut(OutputDirName);
27 bool res=CreateDirectory(strDirNameOut);
29 std::cout << "[" << OutputDirName << "] Directory creation failure " << std::endl;
33 std::string strDirNamein(InputDirName);
34 GDCM_NAME_SPACE::DirList dirList(strDirNamein, false, true); // DON'T get recursively the list of files
35 std::string strDirNameout(OutputDirName);
40 std::cout << "------------List of found files ------------" << std::endl;
42 std::cout << std::endl;
48 // e.g : at level 0, in : B67d1.Bp1
50 // 1 2 3 4 5 6 AdjStatePerStudy subject
53 GDCM_NAME_SPACE::DirListType fileNames;
54 fileNames = dirList.GetFilenames();
56 std::string outputFileName;
58 // BrukerDataSet br_subject;
60 subject = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
61 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
64 std::cout << " Subject : [" << subject << "]" << std::endl;
65 canOpen =br_subject.LoadFile(subject);
69 std::cout << "Hopeless! no 'subject' found" << std::endl;
70 exit(0); /// \TODO throw an exception !
76 //br_subject.PrintSelf();
78 // get info for 'Study Description'
81 BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
82 acqp_protocol_location = b_protocol_location.GetStringValue()[0];
83 cleanString(acqp_protocol_location);
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 // -----------------------------------------------------
121 GDCM_NAME_SPACE::DirListType::iterator it;
123 for (it = fileNames.begin();
124 it != fileNames.end();
127 if ( GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
130 std::cout << "[" << *it << "] is a directory" << std::endl;
132 //BrukerDataSet br_acqp;
135 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
138 br_acqp.LoadFile(strAcqp);
141 std::string acqp_scan_name;
142 std::string acqp_method;
143 std::string acqp_protocol_location;
145 BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
146 acqp_protocol_location = b_protocol_location.GetStringValue()[0];
147 cleanString(acqp_protocol_location);
149 BrukerFieldData b_scan_name=br_acqp.GetFieldData("ACQ_scan_name");
150 acqp_scan_name = b_scan_name.GetStringValue()[0];
151 cleanString(acqp_scan_name);
153 BrukerFieldData b_method=br_acqp.GetFieldData("ACQ_method");
154 acqp_method = b_method.GetStringValue()[0];
155 cleanString(acqp_method);
157 BrukerFieldData b_list_size = br_acqp.GetFieldData("ACQ_O1_list_size");
158 b_list_size.PrintSelf(); //JP
160 nbSlices = b_list_size.GetIntValue()[0];
162 strSerieDescr = GDCM_NAME_SPACE::Util::GetName(*it)
163 + "-" + acqp_protocol_location
164 + "-" + acqp_scan_name
165 + "-" + acqp_method.c_str();
167 sprintf(outputDirName, "%s%c%s", OutputDirName.c_str(),
168 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
169 strSerieDescr.c_str() );
171 std::cout << " ================================================================================\n"
172 << " ========================= [" << GDCM_NAME_SPACE::Util::GetName(*it).c_str()
173 << acqp_protocol_location.c_str()
174 << acqp_scan_name.c_str()
175 << acqp_method.c_str()
177 << " ================================================================================"
181 printf ("outputDirName [%s]\n", outputDirName);
183 DealWithNiveau1(*it, outputDirName);
185 } // end of : for (GDCM_NAME_SPACE::DirListType::iterator it
189 // =====================================================================
191 void Bruker2Dicom::DealWithNiveau1(std::string level1Directory, std::string currentOutputDirName) {
193 // e.g. : at level 1, in B67d1.Bp1/6
195 // acqp fid imnd pdata pulseprogram spnam0 spnam1
197 bool res = CreateDirectory(currentOutputDirName);
200 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
203 GDCM_NAME_SPACE::DirList dirList(level1Directory, false, true); // DON'T get recursively the list of files
204 GDCM_NAME_SPACE::DirListType fileNames;
205 fileNames = dirList.GetFilenames();
206 // -----------------------------------------------------
207 // Iterate to ALL the objets(files/directories) found in the input directory
208 // -----------------------------------------------------
209 GDCM_NAME_SPACE::DirListType::iterator it;
211 for (it = fileNames.begin();
212 it != fileNames.end();
215 if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(*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 ( GDCM_NAME_SPACE::DirList::IsDirectory(*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 ( ! GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
327 std::cout << "--- --- [" << *it << "] is a file" << std::endl;
332 for (it = fileNames.begin();
333 it != fileNames.end();
336 if ( GDCM_NAME_SPACE::DirList::IsDirectory(*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 << "--- => [" << 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 << "--- => [" << 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 clices, 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 ( );
566 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
567 if (nbInstants==1) // creer un seul fichier .mhd pour toutes les Slices! (images natives)
569 std::cout << "Single instant : do not split" << std::endl;
572 sprintf(outputMhdFileName, "%s%cMhdData_Toutes_les_Slices.mhd", currentOutputMhdDirName,
573 GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
574 fp=fopen(outputMhdFileName, "w");
577 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
582 fprintf(fp, "ObjectType = Image\n");
583 fprintf(fp, "NDims = 3\n" );
584 fprintf(fp, "BinaryData = True \n" );
585 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
586 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices );
587 fprintf(fp, "HeaderSize = %d\n", 0);
588 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
589 fprintf(fp, "Position = 0 0 %d\n", 0 );
590 fprintf(fp, "Offset = 0 0 0\n" );
591 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
592 fprintf(fp, "ElementNumberOfChannels = 1\n" );
593 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
594 fprintf(fp, "ElementDataFile = %s\n", "../2dseq_toutes_les_Slices" );
597 sprintf(output2dseqSliceFileName, "%s%c2dseq_toutes_les_Slices",
598 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
599 fp=fopen(output2dseqSliceFileName, "wb");
602 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
606 fwrite( buffer_2dseq, NX*NY*pixelSize, nbSlices, fp);
609 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
613 sprintf(output2dseqSliceFileName, "%s%c2dseq_toutes_les_Slices.dcm",
614 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
616 /* ----------- Write Dicom Image ---------------*/
617 MakeDicomImage(buffer_2dseq,
622 fovX/NY, fovY/NY, sliceDistance,
623 output2dseqSliceFileName,
631 0,// index frame number
632 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
635 } // end if nbInstants = 1
637 else // more than ONE instant
640 // it's (slice1,slide2, ...)t1 ; (slice1,slide2, ...)t2 ; ...
642 unsigned char * pixelsForCurrentSlice = new unsigned char[NX*NY*pixelSize*nbInstants];
645 for (sliceNb=0; sliceNb<nbSlices; sliceNb++)
649 sprintf(outputMhdFileName, "%s%cMhdData_%03d.mhd", currentOutputMhdDirName,
650 GDCM_NAME_SPACE::GDCM_FILESEPARATOR, k );
652 std::cout << "--- Output MHD file [" << outputMhdFileName << "]" << std::endl;
653 fp=fopen(outputMhdFileName, "w");
656 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
661 /* ----------- Write MHD Image ---------------*/
663 // std::cout << "Open sucessfully[" << outputMhdFileName << "] for writting" << std::endl;
664 fprintf(fp, "ObjectType = Image\n");
665 fprintf(fp, "NDims = 3\n" );
666 fprintf(fp, "BinaryData = True \n" );
667 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
668 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbInstants);
669 fprintf(fp, "HeaderSize = %d\n", 0);
670 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, 1.0 ); // slice distance : no meaning for temporal serie
671 fprintf(fp, "Position = 0 0 %d\n", sliceNb );
672 fprintf(fp, "Offset = 0 0 0\n" );
673 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
674 fprintf(fp, "ElementNumberOfChannels = 1\n" );
675 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
676 fprintf(fp, "ElementDataFile = ..%c2dseq_Slice_%d\n", GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb );
680 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d",
681 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,sliceNb);
682 fp=fopen(output2dseqSliceFileName, "wb");
685 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
688 int frameSize = NX*NY*pixelSize;
689 for (instantNb=0; instantNb<nbInstants; instantNb++)
691 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
692 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
697 // std::cout << "end writting[" << output2dseqSliceFileName << "]" << std::endl;
704 sprintf(output2dseqSliceFileName, "%sdummy_buffer",
705 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
706 fp=fopen(output2dseqSliceFileName, "wb");
709 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
712 int frameSize = NX*NY*pixelSize;
713 for (instantNb=0; instantNb<nbInstants; instantNb++)
715 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
716 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
722 fp=fopen(output2dseqSliceFileName, "rb");
725 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for reading" << std::endl;
728 fread( pixelsForCurrentSlice,
729 frameSize*nbInstants,
732 // end of desperate try !
735 /* ----------- Write Dicom Image ---------------*/
737 int frameSize = NX*NY*pixelSize;
738 for (instantNb=0; instantNb<nbInstants; instantNb++)
740 memcpy(pixelsForCurrentSlice + frameSize*instantNb, buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize, frameSize);
743 int indOfFirsImageWithinImageSet = nbSlices*instantNb;
744 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d.dcm",
745 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb);
748 pixelsForCurrentSlice,
753 fovX/NY, fovY/NY, sliceDistance,
754 output2dseqSliceFileName,
763 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
766 std::cout << "--- Output DCM file [" << output2dseqSliceFileName << "]" << std::endl;
772 delete [] pixelsForCurrentSlice;
773 } // end nbInstants == 1
774 delete [] buffer_2dseq;
778 // -----------------------------------------------------
779 // deal with MatLab-generated Carto file.
780 // -----------------------------------------------------
782 dealWithCarto(fileNames, NX, NY, nbSlices, fovX, fovY, sliceDistance,
783 copyFile, currentOutputDirName, outputMhdFileName, output2dseqCartoName);
787 // ===========================================================================================
789 void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX, int NY, int nbSlices,
790 double fovX, double fovY, double sliceDistance,
791 char *copyFile, std::string ¤tOutputDirName,
792 char *outputMhdFileName, char *output2dseqCartoName)
794 // -----------------------------------------------------
795 // deal with MatLab-generated Carto file.
796 // -----------------------------------------------------
798 char *code[] ={ "ADC", "adc", "TTP", "ttp", "PEAK", "peak" , ""}; // add more carto file name identifiers if necessary; end with ""
800 GDCM_NAME_SPACE::DirListType::iterator it;
801 char file_name_ident[500];
804 // Iterate to ALL the objets(files/directories) found in the input directory
805 for (it = fileNames.begin();
806 it != fileNames.end();
809 if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
812 std::cout << "--- [" << *it << "] is a file" << std::endl;
816 while (code[icode][0] != 0)
818 sprintf(file_name_ident, "2dseq_%s",code[icode]); // e.g "2dseq_ADC"
819 std::string::size_type loc = (*it).rfind(file_name_ident);
821 if ( loc != std::string::npos )
824 ///\ TODO : find a safer way to be sure to read everything!
825 unsigned char *buffer_carto = new unsigned char[NX*NY*sizeof(double)*nbSlices];
826 fp = fopen ( (*it).c_str(), "rb");
828 std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
831 fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
833 std::cout << "Deal with Carto file :[" <<*it << "], computed length : "
834 << NX*NY*sizeof(double)*nbSlices << std::endl;
835 std::string lastFileName = GDCM_NAME_SPACE::Util::GetName((*it).c_str());
838 // Copy the data file in the new directory
839 sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
840 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str());
842 sprintf(outputMhdFileName, "%s%c%s%s",
843 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".mhd" );
845 std::cout << "--- Output Carto MHD file [" << outputMhdFileName << "]" << std::endl;
848 fp=fopen(outputMhdFileName, "w");
851 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
855 fprintf(fp, "ObjectType = Image\n");
856 fprintf(fp, "NDims = 3\n" );
857 fprintf(fp, "BinaryData = True \n" );
858 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
859 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices);
860 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
861 fprintf(fp, "HeaderSize = %d\n", 0 );
862 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
863 fprintf(fp, "Position = 0 0 0\n" );
864 fprintf(fp, "Offset = 0 0 0\n" );
865 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
866 fprintf(fp, "ElementNumberOfChannels = 1\n" );
867 fprintf(fp, "ElementType = %s\n", "MET_DOUBLE" );
868 fprintf(fp, "ElementDataFile = %s\n", lastFileName.c_str() );
873 std::cout << "--- end write Carto MHD file [" << outputMhdFileName << "]" << std::endl;
876 // ----------- Write Dicom Image ---------------
880 sprintf(output2dseqCartoName, "%s%c%s%s",
881 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".dcm" );
883 std::cout << "--- end create name output2dseqCartoName file [" << output2dseqCartoName << "]" << std::endl;
885 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID(); //New SerieUID for each carto.
886 std::string strNewSerieDescr(strSerieDescr+ "_" +GDCM_NAME_SPACE::Util::GetName((*it).c_str()));
887 MakeDicomImage(buffer_carto,
892 fovX/NY, fovY/NY, sliceDistance,
893 output2dseqCartoName,
902 GDCM_NAME_SPACE::CREATED_IMAGE
906 delete [] buffer_carto;
908 std::cout << "--- End writing Carto DICOM file [" << output2dseqCartoName << "]" << std::endl;
909 break; // don't check for more ident on same file name!
915 } // end iterate on files
919 // ==========================================================================================================
921 bool Bruker2Dicom::CreateDirectory(std::string OutputDirName)
923 std::string systemCommand;
926 std::cout << "Check for output directory :[" << OutputDirName << "]."
928 if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(OutputDirName) ) // dirout not found
930 std::string strDirNameout(OutputDirName); // to please gcc 4
931 systemCommand = "mkdir " + strDirNameout; // create it!
933 std::cout << systemCommand << std::endl;
934 system (systemCommand.c_str());
935 if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(OutputDirName) ) // be sure it worked
938 std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
940 /// \todo : THROW AN EXCEPTION
945 std::cout << "Directory [" << OutputDirName << "] created." << std::endl;
951 std::cout << "Output Directory [" << OutputDirName << "] already exists; Used as is." << std::endl;
959 // ===========================================================================================
961 /// \TODO move cleanString to 'crea' ?
963 void Bruker2Dicom::cleanString(std::string &s)
966 if (s[l-1] == 0x0A || s[l-1] == 0x0D ) // CR or NL
971 if (s[l-1] == ' ' ) // blank space
979 std::string repChar("_");
980 GDCM_NAME_SPACE::Util::ReplaceSpecChar(s, repChar);
985 // ===========================================================================================
988 void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPixelType, int &pixelSize)
990 if(bDPT.GetDataType() == "string")
992 std::string brukerDataPixelType = bDPT.GetStringValue()[0];
993 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
994 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
996 if (brukerDataPixelType == "ip_short") {
997 mhdDataPixelType = "MET_USHORT";
1000 if (brukerDataPixelType == "ip_int") {
1001 mhdDataPixelType = "MET_UINT";
1004 if (brukerDataPixelType == "ip_char") {
1005 mhdDataPixelType = "MET_UCHAR";
1008 /// \TODO : finish the list
1010 case 0 : fp << "ElementType = MET_CHAR" << std::endl;
1012 case 1 : fp << "ElementType = MET_UCHAR" << std::endl;
1014 case 2 : fp << "ElementType = MET_SHORT" << std::endl;
1016 case 3 : fp << "ElementType = MET_USHORT" << std::endl;
1018 case 4 : fp << "ElementType = MET_INT" << std::endl;
1020 case 5 : fp << "ElementType = MET_UINT" << std::endl;
1022 case 6 : fp << "ElementType = MET_FLOAT" << std::endl;
1024 case 7 : fp << "ElementType = MET_DOUBLE" << std::endl;
1029 int brukerDataPixelType = bDPT.GetIntValue()[0];
1030 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
1031 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1033 // Cross your fingers !!!
1035 // pb : found values : 2, 3, 5
1037 if (brukerDataPixelType == 2) {
1038 mhdDataPixelType = "MET_USHORT";
1041 if (brukerDataPixelType == 3) {
1042 mhdDataPixelType = "MET_USHORT";
1045 if (brukerDataPixelType == 1) {
1046 mhdDataPixelType = "MET_UCHAR";
1052 // ===========================================================================================
1054 std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
1056 std::vector<BrukerImage> imageSet;
1057 br_acqp.SetLoopStructure();
1058 std::vector<int> tempVect = br_acqp.GetLoopStructure() ;
1059 std::map<std::string, BrukerFieldData> map = br_acqp.GetBrukerHeaderMap();
1060 bool result = br_acqp.ObjectVaryingProperties.init(map,tempVect);
1062 br_acqp.SetImageLoopStructure();
1063 br_acqp.SetBrukerImageList();
1064 std::vector<std::vector<int> > brukerImageList = br_acqp.GetBrukerImageList();
1066 BrukerImage image(br_acqp,br_reco);
1067 image.Init(br_acqp,br_reco,1);
1069 for(int i=0;i<brukerImageList.size();i++)
1071 image.Init(br_acqp,br_reco,i);
1072 imageSet.push_back(image);
1075 // Just for checking
1078 std::vector<std::vector <double> > imageOrientation;
1079 std::vector <double> imagePosition;
1080 for(int i=0;i<brukerImageList.size();i++)
1082 // fread(buffer_2dseq, NX*NY*pixelSize*nbSlices*nbInstants, 1, fp);
1084 imagePosition = imageSet[i].getTranslationVectorRPS2XYZ();
1085 std::cout << "Position " << imagePosition[0] << " "
1086 << imagePosition[1] << " " << imagePosition[2] ;
1087 imageOrientation = imageSet[i].getRotationMatrixRPS2XYZ();
1088 std::cout << "\t Orientation " ;
1089 for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
1090 std::cout << imageOrientation[i1][i2] << " ";
1092 //std::cout << "\t Abs Time " << imageSet[i].getAbsoluteTimePosition();
1093 std::cout << "\t Relat Time " << imageSet[i].getRelativeTimePosition();
1095 std::cout << "\t [";
1096 for (int i3=0; i3<imageSet[i].getLoopStamp().size();i3++)
1097 std::cout << " " << imageSet[i].getLoopStamp()[i3];
1098 std::cout << "]" << std::endl;
1105 // ===========================================================================================
1107 void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels,
1112 double spacingX, double spacingY, double sliceDistance,
1113 std::string dcmImageName,
1114 const std::string &patientName,
1116 std::string &studyUID,
1117 std::string &serieUID,
1118 std::string &studyDescr,
1119 std::string &serieDescr,
1120 std::string &strStudyTimeDate,
1122 GDCM_NAME_SPACE::ImageContentType contentType
1125 std::ostringstream str;
1127 GDCM_NAME_SPACE::File *file;
1128 file = GDCM_NAME_SPACE::File::New();
1130 // Set the image size
1133 file->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
1136 file->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
1142 file->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames
1145 // Set the pixel type
1146 // //8, 16, 32, 64 (for double ?)
1149 file->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
1151 file->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
1154 str << pixelSize*8-1;
1155 file->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
1157 // Set the pixel representation // 0/1 , 0=unsigned
1158 file->InsertEntryString("1",0x0028,0x0103, "US"); // Pixel Representation
1160 // Set the samples per pixel // 1:Grey level, 3:RGB
1161 file->InsertEntryString("1",0x0028,0x0002, "US"); // Samples per Pixel
1163 // 0028 0030 DS 2 Pixel Spacing
1165 str << spacingX << "\\" << spacingY;
1166 file->InsertEntryString(str.str(),0x0028,0x0030, "DS"); // Pixel Spacing
1168 // 0018 0050 DS 1 Slice Thickness
1170 str << sliceDistance;
1171 file->InsertEntryString(str.str(),0x0018,0x0050, "DS");
1173 // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
1174 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1175 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1178 // OK : MR is NOT multiframe, but I want just a quick an dirty solution
1179 // 1.2.840.10008.5.1.4.1.1.4 MR Image Storage
1180 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1181 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1183 // if (strlen(patientName) != 0)
1184 file->InsertEntryString(patientName.c_str(),0x0010,0x0010, "PN"); // Patient's Name
1186 file->InsertEntryString(studyUID, 0x0020, 0x000d, "UI");
1187 file->InsertEntryString(serieUID, 0x0020, 0x000e, "UI");
1189 // 0008 0020 DA 1 Study Date
1190 // 0008 0030 TM 1 Study Time
1192 /// \TODO split into 2 strings!
1193 file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
1194 file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),0x0008,0x0030, "TM");
1196 file->InsertEntryString(studyDescr,0x0008,0x1030, "LO"); // Study Description
1197 file->InsertEntryString(serieDescr,0x0008,0x103e, "LO"); // Series Description
1199 //0008|0060 [CS] [Modality]
1200 file->InsertEntryString("MR",0x0008,0x0060, "CS");
1202 // 0020 0037 DS 6 Image Orientation (Patient)
1203 char charImageOrientation[256];
1206 std::cout << "try charImageOrientation " <<
1207 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0] << " " <<
1208 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1] << " " <<
1209 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2] << " " <<
1210 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0] << " " <<
1211 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1] << " " <<
1212 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] << std::endl ;
1214 sprintf(charImageOrientation,"%f\\%f\\%f \\ %f\\%f\\%f",
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] ) ;
1222 file->InsertEntryString(charImageOrientation,0x0020,0x0037, "DS");
1225 // 0020 0032 DS 3 Image Position (Patient)
1227 char charImagePosition[256];
1228 sprintf(charImagePosition,"%f\\%f\\%f",
1229 imageSet[imgNum].getTranslationVectorRPS2XYZ()[0],
1230 imageSet[imgNum].getTranslationVectorRPS2XYZ()[1],
1231 imageSet[imgNum].getTranslationVectorRPS2XYZ()[2]);
1233 file->InsertEntryString(charImagePosition,0x0020,0x0032, "DS"); //0020 0032 DS 3 Image Position (Patient)
1237 // 0020 0x1041 DS 1 Slice Location
1238 // sprintf(charImagePosition,"%f",float(imgNum));
1239 // file->InsertEntryString(charImagePosition,0x0020,0x1041, "DS");
1241 // Set Rescale Intercept
1244 file->InsertEntryString(str.str(),0x0028,0x1052,"DS");
1246 // Set Rescale Slope
1249 file->InsertEntryString(str.str(),0x0028,0x1053,"DS");
1252 GDCM_NAME_SPACE::FileHelper *fileH;
1253 fileH = GDCM_NAME_SPACE::FileHelper::New(file);
1254 fileH->SetContentType(contentType);
1256 // cast is just to avoid warnings (*no* conversion is performed)
1257 //fileH->SetImageData((uint8_t *)img,int(maxX*maxY)*sizeof(uint16_t)); // troubles when maxX, mayY are *actually* float!
1259 //std::cout << "-------------------------------- X*Y*nbFrames*pixelSize " << X << " " << Y << " " << nbFrames << " " << pixelSize << std::endl;
1261 fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
1262 fileH->SetWriteModeToRaw();
1263 fileH->SetWriteTypeToDcmExplVR();
1264 if( !fileH->Write(dcmImageName))
1265 std::cout << "Failed for [" << dcmImageName << "]\n"
1266 << " File is unwrittable" << std::endl;