1 #include "bruker2dicom.h"
2 #include <boost/filesystem/path.hpp>
3 #include <boost/filesystem/operations.hpp>
5 #ifndef PATH_MAX // If not defined yet : do it
11 bool Bruker2Dicom::Execute()
13 // ----- Check input values -----
15 bool bigEndian = GDCM_NAME_SPACE::Util::IsCurrentProcessorBigEndian();
17 //if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(InputDirName) )
18 if ( ! boost::filesystem::is_directory(InputDirName) )
20 std::cout << "KO : [" << InputDirName << "] is not a Directory." << std::endl;
26 std::cout << "OK : [" << InputDirName << "] is a Directory." << std::endl;
29 std::string strDirNameOut(OutputDirName);
30 bool res=CreateDirectory(strDirNameOut);
32 std::cout << "[" << OutputDirName << "] Directory creation failure " << std::endl;
36 std::string strDirNamein(InputDirName);
37 GDCM_NAME_SPACE::DirList dirList(strDirNamein, false, true); // DON'T get recursively the list of files
38 std::string strDirNameout(OutputDirName);
43 std::cout << "------------List of found files ------------" << std::endl;
45 std::cout << std::endl;
51 // e.g : at level 0, in : B67d1.Bp1
53 // 1 2 3 4 5 6 AdjStatePerStudy subject
56 GDCM_NAME_SPACE::DirListType fileNames;
57 fileNames = dirList.GetFilenames();
59 std::string outputFileName;
61 // BrukerDataSet br_subject;
63 subject = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
64 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
67 std::cout << " Subject : [" << subject << "]" << std::endl;
68 canOpen =br_subject.LoadFile(subject);
72 std::cout << "Hopeless! no 'subject' found" << std::endl;
73 exit(0); /// \TODO throw an exception !
79 //br_subject.PrintSelf();
81 // get info for 'Study Description'
84 BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
85 acqp_protocol_location = b_protocol_location.GetStringValue()[0];
86 cleanString(acqp_protocol_location);
88 BrukerFieldData b_name=br_subject.GetFieldData("SUBJECT_name_string");
89 std::string subject_name = b_name.GetStringValue()[0];
90 strPatientName = subject_name;
91 cleanString(subject_name);
93 BrukerFieldData b_entry=br_subject.GetFieldData("SUBJECT_entry");
94 std::string subject_entry = b_entry.GetStringValue()[0];
95 //cleanString(subject_entry);
96 subject_entry = subject_entry.substr(11, subject_entry.size()-11);
98 BrukerFieldData b_position=br_subject.GetFieldData("SUBJECT_position");
99 std::string subject_position = b_position.GetStringValue()[0];
100 //cleanString(subject_position);
101 subject_position = subject_position.substr(9, subject_position.size()-9);
103 BrukerFieldData b_date=br_subject.GetFieldData("SUBJECT_date");
104 std::string subject_date = b_date.GetStringValue()[0];
105 strStudyTimeDate = subject_date;
106 cleanString(subject_date);
108 BrukerFieldData b_study_name=br_subject.GetFieldData("SUBJECT_study_name");
109 std::string subject_study_name = b_study_name.GetStringValue()[0];
110 subject_study_name = subject_study_name.substr(1, subject_study_name.size()-2);
111 cleanString(subject_date);
113 strStudyDescr = subject_name + "." + subject_study_name + "." + subject_entry + "." + subject_position + "." + subject_date;
115 char outputDirName[(unsigned int) PATH_MAX+2];
117 strStudyUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
119 // -----------------------------------------------------
120 // Iterate to ALL the objets(files/directories) found in the input directory
121 // (this is level ZERO)
122 // each Directory (name : 1, 2, 3, ...) will be a Dicom Serie
123 // -----------------------------------------------------
125 GDCM_NAME_SPACE::DirListType::iterator it;
127 for (it = fileNames.begin();
128 it != fileNames.end();
131 if ( boost::filesystem::is_directory(*it) )
134 std::cout << "[" << *it << "] is a directory" << std::endl;
136 //BrukerDataSet br_acqp;
139 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
142 br_acqp.LoadFile(strAcqp);
145 std::string acqp_scan_name;
146 std::string acqp_method;
147 std::string acqp_protocol_location;
149 BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
150 acqp_protocol_location = b_protocol_location.GetStringValue()[0];
151 cleanString(acqp_protocol_location);
153 BrukerFieldData b_scan_name=br_acqp.GetFieldData("ACQ_scan_name");
154 acqp_scan_name = b_scan_name.GetStringValue()[0];
155 cleanString(acqp_scan_name);
157 BrukerFieldData b_method=br_acqp.GetFieldData("ACQ_method");
158 acqp_method = b_method.GetStringValue()[0];
159 cleanString(acqp_method);
161 BrukerFieldData b_list_size = br_acqp.GetFieldData("ACQ_O1_list_size");
162 b_list_size.PrintSelf(); //JP
164 nbSlices = b_list_size.GetIntValue()[0];
166 strSerieDescr = GDCM_NAME_SPACE::Util::GetName(*it)
167 + "." + acqp_protocol_location
168 + "." + acqp_scan_name
169 + "." + acqp_method.c_str();
171 sprintf(outputDirName, "%s%c%s", OutputDirName.c_str(),
172 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
173 strSerieDescr.c_str() );
175 std::cout << " ================================================================================\n"
176 << " === [" << GDCM_NAME_SPACE::Util::GetName(*it) << "] -> [" << strSerieDescr << "]\n"
177 << " ================================================================================"
181 std::cout << " ================================================================================\n"
182 << " ========================= [" << GDCM_NAME_SPACE::Util::GetName(*it).c_str()
183 << acqp_protocol_location.c_str()
184 << acqp_scan_name.c_str()
185 << acqp_method.c_str()
187 << " ================================================================================"
191 printf ("outputDirName [%s]\n", outputDirName);
193 DealWithNiveau1(*it, outputDirName);
195 } // end of : for (GDCM_NAME_SPACE::DirListType::iterator it
199 // =====================================================================
201 void Bruker2Dicom::DealWithNiveau1(std::string level1Directory, std::string currentOutputDirName) {
203 // e.g. : at level 1, in B67d1.Bp1/6
205 // acqp fid imnd pdata pulseprogram spnam0 spnam1
207 bool res = CreateDirectory(currentOutputDirName);
210 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
213 GDCM_NAME_SPACE::DirList dirList(level1Directory, false, true); // DON'T get recursively the list of files
214 GDCM_NAME_SPACE::DirListType fileNames;
215 fileNames = dirList.GetFilenames();
216 // -----------------------------------------------------
217 // Iterate to ALL the objets(files/directories) found in the input directory
218 // -----------------------------------------------------
219 GDCM_NAME_SPACE::DirListType::iterator it;
221 for (it = fileNames.begin();
222 it != fileNames.end();
225 if ( ! boost::filesystem::is_directory(*it) )
228 std::cout << "--- [" << *it << "] is a file" << std::endl;
232 char outputDirName[(unsigned int) PATH_MAX+2];
233 //std::string firstName;
235 for (it = fileNames.begin();
236 it != fileNames.end();
239 if ( boost::filesystem::is_directory(*it) )
241 // will be always "pdata" ...
243 std::cout << "--- [" << *it << "] is a directory" << std::endl;
246 if (FileLine.startsWith("##$ACQ_size=")) {
247 if (FileLine.startsWith("##$NI=")) {
248 if (FileLine.startsWith("##$NR=")) {
249 if (FileLine.startsWith("##$ACQ_obj_order=")) {
250 if (FileLine.startsWith("##$ACQ_word_size=")) {
251 if (FileLine.startsWith("##$BYTORDA=")) {
252 if (FileLine.startsWith("##$PULPROG=")) {
255 sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
256 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
257 GDCM_NAME_SPACE::Util::GetName(*it).c_str());
260 std::string strMethod;
261 //std::string firstName = *(fileNames.begin());
263 strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin())) +
264 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
266 // std::cout << "---strMethod (for method)=> [" << strMethod << "]" << std::endl;
267 canOpen = br_method.LoadFile(strMethod);
270 strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
271 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
273 //std::cout << "---strMethod (for imnd) => [" << strMethod << "]" << std::endl;
274 canOpen = br_method.LoadFile(strMethod);
277 std::cout << "Hopeless! neither 'method' nor 'imnd' found" << std::endl;
278 exit(0); /// \TODO throw an exception !
282 std::cout << "open => [" << strMethod << "] successfully" << std::endl;
286 ##$PVM_Fov (dimension)
289 dans method (pour perfusion seulement?) :
290 ##$PVM_ObjOrderList=( 8 )
293 ##$PVM_SPackArrNSlices=( 2 )
296 DealWithNiveau2(*it,outputDirName );
301 // =====================================================================
303 void Bruker2Dicom::DealWithNiveau2(std::string level2Directory, std::string currentOutputDirName) {
305 // e.g. : at level 2 in B67d1.Bp1/6/pdata
307 // acqp fid imnd pdata pulseprogram spnam0 spnam1
310 bool res = CreateDirectory(currentOutputDirName);
313 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
317 GDCM_NAME_SPACE::DirList dirList(level2Directory, false, true); // DON'T get recursively the list of files
319 GDCM_NAME_SPACE::DirListType fileNames;
320 fileNames = dirList.GetFilenames();
322 char outputDirName[(unsigned int) PATH_MAX+2];
324 // -----------------------------------------------------
325 // Iterate to ALL the objets(files/directories) found in the input directory
326 // -----------------------------------------------------
327 GDCM_NAME_SPACE::DirListType::iterator it;
331 for (it = fileNames.begin();
332 it != fileNames.end();
335 if ( ! boost::filesystem::is_directory(*it) )
337 std::cout << "--- --- [" << *it << "] is a file" << std::endl;
342 for (it = fileNames.begin();
343 it != fileNames.end();
346 if ( boost::filesystem::is_directory(*it) )
350 std::cout << "--- --- [" << *it << "] is a directory" << std::endl;
352 // sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
353 // GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
354 // GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
358 // (interest of previous method :
359 // If unaware user changed the pdata name, it goes on working
363 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
366 std::string str_isa_func_name;
367 canOpen = br_isa.LoadFile(str_isa);
370 sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
371 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
372 GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
377 BrukerFieldData b_isa_func_name = br_isa.GetFieldData("ISA_func_name");
379 str_isa_func_name = b_isa_func_name.GetStringValue()[0];
380 cleanString(str_isa_func_name);
382 sprintf(outputDirName, "%s%c%s.%s", currentOutputDirName.c_str(),
383 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
384 GDCM_NAME_SPACE::Util::GetName(*it).c_str(),
385 str_isa_func_name.c_str());
387 DealWithNiveau3(*it, outputDirName);
394 // =====================================================================
397 void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string currentOutputDirName){
400 // e.g. at level 3, in
402 // just to be able to go on checking // JP
403 if ( GDCM_NAME_SPACE::Util::GetName(level3Directory) != "1")
406 bool res = CreateDirectory(currentOutputDirName);
410 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
414 GDCM_NAME_SPACE::DirList dirList(level3Directory, false, true); // DON'T get recursively the list of files
415 GDCM_NAME_SPACE::DirListType::iterator it;
416 GDCM_NAME_SPACE::DirListType fileNames;
417 fileNames = dirList.GetFilenames();
419 char original2dseqName [(unsigned int) PATH_MAX+2];
420 char currentOutputMhdDirName [(unsigned int) PATH_MAX+2];
422 char outputMhdFileName [(unsigned int) PATH_MAX+2];
423 char output2dseqSliceFileName[(unsigned int) PATH_MAX+6]; // think about extra '.dcm'
424 char output2dseqName [(unsigned int) PATH_MAX+6];
425 char output2dseqCartoName [(unsigned int) PATH_MAX+6];
427 char copyFile[PATH_MAX + PATH_MAX + 5]; // Should be enough!
430 //-------------- try d3proc;
431 char char_d3proc[(unsigned int) PATH_MAX+2];
433 sprintf(char_d3proc,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"d3proc" );
436 std::cout << "--- => [" << char_d3proc << "]" << std::endl;
437 std::string str_d3proc(char_d3proc);
438 canOpen = br_d3proc.LoadFile(str_d3proc);
442 std::cout << "Hopeless! no 'd3proc' found" << std::endl;
443 exit(0); /// \TODO throw an exception !
446 canOpen = br_d3proc.FillMap();
449 std::cout << "Hopeless! FillMap failed on 'd3proc'" << std::endl;
450 exit(0); /// \TODO throw an exception !
453 //-------------- end try d3proc;
456 // -------------------try reco
458 char char_reco[(unsigned int) PATH_MAX+2];
460 sprintf(char_reco,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
461 //str_d3proc = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
462 // GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
465 std::cout << "--- => [" << char_reco << "]" << std::endl;
466 std::string str_reco(char_reco);
467 canOpen = br_reco.LoadFile(str_reco);
469 if (!canOpen) // we try in directory ../1
472 std::cout << "[" << str_reco << "] not found " << std::endl;
473 std::string lastDirName = GDCM_NAME_SPACE::Util::GetPath(level3Directory);
474 //lastDirName = GDCM_NAME_SPACE::Util::GetPath(lastDirName);
475 sprintf(char_reco,"%s%c1%c%s", lastDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
477 canOpen = br_reco.LoadFile(str_reco);
480 std::cout << "Hopeless! cannot find 'reco' in [" << str_reco << "]" << std::endl;
481 exit(0); /// \TODO throw an exception !
485 canOpen = br_reco.FillMap();
488 std::cout << "Hopeless! FillMap failed on [" << str_reco << "]" << std::endl;
489 exit(0); /// \TODO throw an exception !
491 //std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
492 // br_reco.PrintSelf();
493 // std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
495 // -------------------end try reco
498 BrukerFieldData bX = br_d3proc.GetFieldData("IM_SIX");
499 int NX = bX.GetIntValue()[0];
501 std::cout << "IM_SIX " << NX << std::endl;
502 BrukerFieldData bY=br_d3proc.GetFieldData("IM_SIY");
503 int NY = bY.GetIntValue()[0];
505 std::cout << "IM_SIY " << NY << std::endl;
506 /// \todo : check if there are actually 3 dimensions or only 2
508 BrukerFieldData bZ= br_d3proc.GetFieldData("IM_SIZ");
509 int nbFrames = bZ.GetIntValue()[0];
510 std::cout << "IM_SIZ " << nbFrames << std::endl;
512 // WARNING DATTYPE is, either in {ip_short, ip_int, ip_char, ...}, or in {1, 2, 3, ...}
514 BrukerFieldData bDPT = br_d3proc.GetFieldData("DATTYPE");
516 std::string mhdDataPixelType;
518 getImhDataType(bDPT, mhdDataPixelType, pixelSize);
520 BrukerFieldData fov = br_method.GetFieldData("PVM_Fov");
521 double fovX = fov.GetDoubleValue()[0];
522 double fovY = fov.GetDoubleValue()[1];
524 std::cout << "FOV (ds method) " << fovX << " " << fovY << std::endl;
526 /// \TODO probabely a more sophisticated accessor will be necessary :
527 /// (cf : non contiguous slices, overlapping, slice thickness, space between clices, etc)
528 BrukerFieldData bsliceDistance = br_method.GetFieldData("PVM_SPackArrSliceDistance");
529 double sliceDistance = bsliceDistance.GetDoubleValue()[0];
533 sprintf(currentOutputMhdDirName, "%s%c%s", currentOutputDirName.c_str(),
534 GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "MhdFiles");
535 res = CreateDirectory( currentOutputMhdDirName );
537 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
542 std::cout << "Directory creation [" << currentOutputDirName << "]" << std::endl;
545 std::cout << "nbFrames " << nbFrames << std::endl;
546 std::cout << "nbSlices " << nbSlices << std::endl;
548 int nbInstants = nbFrames/nbSlices;
549 std::cout << "nbInstants (deduced )" << nbInstants << std::endl;
552 FILE *fp; // for MHD files
554 sprintf( original2dseqName, "%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "2dseq");
557 // \TODO : tenir compte du bazar precedent
559 // load 2dseq in memory
561 fp = fopen(original2dseqName, "rb");
564 std::cout << "Cannot open [" << original2dseqName << "] for reading" << std::endl;
568 unsigned char *buffer_2dseq = new unsigned char[NX*NY*pixelSize*nbSlices*nbInstants];
569 ///\ TODO : find a safer way to be sure to read everything!
570 size_t lgr = fread(buffer_2dseq, 1, NX*NY*pixelSize*nbSlices*nbInstants, fp);
572 // This one will be important!
573 // ---------------------------
574 imageSet = CreateImageSet ( );
576 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
577 if (nbInstants==1) // creer un seul fichier .mhd pour toutes les Slices! (images natives)
579 std::cout << "Single instant : do not split" << std::endl;
582 sprintf(outputMhdFileName, "%s%cMhdData_All_the_Slices.mhd", currentOutputMhdDirName,
583 GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
584 fp=fopen(outputMhdFileName, "w");
587 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
592 fprintf(fp, "ObjectType = Image\n");
593 fprintf(fp, "NDims = 3\n" );
594 fprintf(fp, "BinaryData = True \n" );
595 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
596 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices );
597 fprintf(fp, "HeaderSize = %d\n", 0);
598 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
599 fprintf(fp, "Position = 0 0 %d\n", 0 );
600 fprintf(fp, "Offset = 0 0 0\n" );
601 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
602 fprintf(fp, "ElementNumberOfChannels = 1\n" );
603 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
604 fprintf(fp, "ElementDataFile = %s\n", "../2dseq_All_the_Slices" );
607 sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices",
608 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
609 fp=fopen(output2dseqSliceFileName, "wb");
612 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
616 fwrite( buffer_2dseq, NX*NY*pixelSize, nbSlices, fp);
619 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
623 sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices.dcm",
624 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
626 /* ----------- Write Dicom Image ---------------*/
627 MakeDicomImage(buffer_2dseq,
632 fovX/NY, fovY/NY, sliceDistance,
633 output2dseqSliceFileName,
641 0,// index frame number
642 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
645 } // end if nbInstants = 1
647 else // more than ONE instant
650 // it's (slice1,slide2, ...)t1 ; (slice1,slide2, ...)t2 ; ...
652 unsigned char *pixelsForCurrentSlice = new unsigned char[NX*NY*pixelSize*nbInstants];
655 for (sliceNb=0; sliceNb<nbSlices; sliceNb++)
659 sprintf(outputMhdFileName, "%s%cMhdData_%03d.mhd", currentOutputMhdDirName,
660 GDCM_NAME_SPACE::GDCM_FILESEPARATOR, k );
662 std::cout << "--- Output MHD file [" << outputMhdFileName << "]" << std::endl;
663 fp=fopen(outputMhdFileName, "w");
666 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
671 /* ----------- Write MHD Image ---------------*/
673 // std::cout << "Open sucessfully[" << outputMhdFileName << "] for writting" << std::endl;
674 fprintf(fp, "ObjectType = Image\n");
675 fprintf(fp, "NDims = 3\n" );
676 fprintf(fp, "BinaryData = True \n" );
677 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
678 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbInstants);
679 fprintf(fp, "HeaderSize = %d\n", 0);
680 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, 1.0 ); // slice distance : no meaning for temporal serie
681 fprintf(fp, "Position = 0 0 %d\n", sliceNb );
682 fprintf(fp, "Offset = 0 0 0\n" );
683 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
684 fprintf(fp, "ElementNumberOfChannels = 1\n" );
685 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
686 fprintf(fp, "ElementDataFile = ..%c2dseq_Slice_%d\n", GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb );
690 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d",
691 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,sliceNb);
692 fp=fopen(output2dseqSliceFileName, "wb");
695 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
698 int frameSize = NX*NY*pixelSize;
699 for (instantNb=0; instantNb<nbInstants; instantNb++)
701 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
702 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
707 // std::cout << "end writting[" << output2dseqSliceFileName << "]" << std::endl;
714 sprintf(output2dseqSliceFileName, "%sdummy_buffer",
715 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
716 fp=fopen(output2dseqSliceFileName, "wb");
719 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
722 int frameSize = NX*NY*pixelSize;
723 for (instantNb=0; instantNb<nbInstants; instantNb++)
725 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
726 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
732 fp=fopen(output2dseqSliceFileName, "rb");
735 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for reading" << std::endl;
738 fread( pixelsForCurrentSlice,
739 frameSize*nbInstants,
742 // end of desperate try !
745 /* ----------- Write Dicom Image ---------------*/
747 int frameSize = NX*NY*pixelSize;
748 for (instantNb=0; instantNb<nbInstants; instantNb++)
750 memcpy(pixelsForCurrentSlice + frameSize*instantNb, buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize, frameSize);
753 int indOfFirsImageWithinImageSet = nbSlices*instantNb;
754 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d.dcm",
755 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb);
758 pixelsForCurrentSlice,
763 fovX/NY, fovY/NY, sliceDistance,
764 output2dseqSliceFileName,
773 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
776 std::cout << "--- Output DCM file [" << output2dseqSliceFileName << "]" << std::endl;
782 delete [] pixelsForCurrentSlice;
783 } // end nbInstants == 1
784 delete [] buffer_2dseq;
788 // -----------------------------------------------------
789 // deal with MatLab-generated Carto file.
790 // -----------------------------------------------------
792 dealWithCarto(fileNames, NX, NY, nbSlices, fovX, fovY, sliceDistance,
793 copyFile, currentOutputDirName, outputMhdFileName, output2dseqCartoName);
797 // ===========================================================================================
799 void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX, int NY, int nbSlices,
800 double fovX, double fovY, double sliceDistance,
801 char *copyFile, std::string ¤tOutputDirName,
802 char *outputMhdFileName, char *output2dseqCartoName)
804 // -----------------------------------------------------
805 // deal with MatLab-generated Carto file.
806 // -----------------------------------------------------
808 char *code[] ={ "ADC", "adc", "TTP", "ttp", "PEAK", "peak" , ""}; // add more carto file name identifiers if necessary; end with ""
810 GDCM_NAME_SPACE::DirListType::iterator it;
811 char file_name_ident[500];
814 // Iterate to ALL the objets(files/directories) found in the input directory
815 for (it = fileNames.begin();
816 it != fileNames.end();
819 if ( ! boost::filesystem::is_directory(*it) )
822 std::cout << "--- [" << *it << "] is a file" << std::endl;
826 while (code[icode][0] != 0)
828 sprintf(file_name_ident, "2dseq_%s",code[icode]); // e.g "2dseq_ADC"
829 std::string::size_type loc = (*it).rfind(file_name_ident);
831 if ( loc != std::string::npos )
834 ///\ TODO : find a safer way to be sure to read everything!
835 unsigned char *buffer_carto = new unsigned char[NX*NY*sizeof(double)*nbSlices];
836 fp = fopen ( (*it).c_str(), "rb");
838 std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
841 fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
843 std::cout << "Deal with Carto file :[" <<*it << "], computed length : "
844 << NX*NY*sizeof(double)*nbSlices << std::endl;
845 std::string lastFileName = GDCM_NAME_SPACE::Util::GetName((*it).c_str());
848 // Copy the data file in the new directory
849 sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
850 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str());
852 sprintf(outputMhdFileName, "%s%c%s%s",
853 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".mhd" );
855 std::cout << "--- Output Carto MHD file [" << outputMhdFileName << "]" << std::endl;
858 fp=fopen(outputMhdFileName, "w");
861 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
865 fprintf(fp, "ObjectType = Image\n");
866 fprintf(fp, "NDims = 3\n" );
867 fprintf(fp, "BinaryData = True \n" );
868 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
869 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices);
870 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
871 fprintf(fp, "HeaderSize = %d\n", 0 );
872 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
873 fprintf(fp, "Position = 0 0 0\n" );
874 fprintf(fp, "Offset = 0 0 0\n" );
875 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
876 fprintf(fp, "ElementNumberOfChannels = 1\n" );
877 fprintf(fp, "ElementType = %s\n", "MET_DOUBLE" );
878 fprintf(fp, "ElementDataFile = %s\n", lastFileName.c_str() );
883 std::cout << "--- end write Carto MHD file [" << outputMhdFileName << "]" << std::endl;
886 // ----------- Write Dicom Image ---------------
890 sprintf(output2dseqCartoName, "%s%c%s%s",
891 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".dcm" );
893 std::cout << "--- end create name output2dseqCartoName file [" << output2dseqCartoName << "]" << std::endl;
895 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID(); //New SerieUID for each carto.
896 std::string strNewSerieDescr(strSerieDescr+ "_" +GDCM_NAME_SPACE::Util::GetName((*it).c_str()));
897 MakeDicomImage(buffer_carto,
902 fovX/NY, fovY/NY, sliceDistance,
903 output2dseqCartoName,
912 GDCM_NAME_SPACE::CREATED_IMAGE
916 delete [] buffer_carto;
918 std::cout << "--- End writing Carto DICOM file [" << output2dseqCartoName << "]" << std::endl;
919 break; // don't check for more ident on same file name!
925 } // end iterate on files
929 // ==========================================================================================================
931 bool Bruker2Dicom::CreateDirectory(std::string OutputDirName)
933 std::string systemCommand;
936 std::cout << "Check for output directory :[" << OutputDirName << "]."
938 if ( ! boost::filesystem::is_directory(OutputDirName) ) // dirout not found
940 std::string strDirNameout(OutputDirName); // to please gcc 4
941 systemCommand = "mkdir " + strDirNameout; // create it!
943 std::cout << systemCommand << std::endl;
944 system (systemCommand.c_str());
945 if ( ! boost::filesystem::is_directory(OutputDirName) ) // be sure it worked
948 std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
950 /// \todo : THROW AN EXCEPTION
955 std::cout << "Directory [" << OutputDirName << "] created." << std::endl;
961 std::cout << "Output Directory [" << OutputDirName << "] already exists; Used as is." << std::endl;
969 // ===========================================================================================
971 /// \TODO move cleanString to 'crea' ?
973 void Bruker2Dicom::cleanString(std::string &s)
976 if (s[l-1] == 0x0A || s[l-1] == 0x0D ) // CR or NL
981 if (s[l-1] == ' ' ) // blank space
989 std::string repChar("_");
990 GDCM_NAME_SPACE::Util::ReplaceSpecChar(s, repChar);
995 // ===========================================================================================
998 void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPixelType, int &pixelSize)
1000 if(bDPT.GetDataType() == "string")
1002 std::string brukerDataPixelType = bDPT.GetStringValue()[0];
1003 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
1004 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1006 if (brukerDataPixelType == "ip_short") {
1007 mhdDataPixelType = "MET_USHORT";
1010 if (brukerDataPixelType == "ip_int") {
1011 mhdDataPixelType = "MET_UINT";
1014 if (brukerDataPixelType == "ip_char") {
1015 mhdDataPixelType = "MET_UCHAR";
1018 /// \TODO : finish the list
1020 case 0 : fp << "ElementType = MET_CHAR" << std::endl;
1022 case 1 : fp << "ElementType = MET_UCHAR" << std::endl;
1024 case 2 : fp << "ElementType = MET_SHORT" << std::endl;
1026 case 3 : fp << "ElementType = MET_USHORT" << std::endl;
1028 case 4 : fp << "ElementType = MET_INT" << std::endl;
1030 case 5 : fp << "ElementType = MET_UINT" << std::endl;
1032 case 6 : fp << "ElementType = MET_FLOAT" << std::endl;
1034 case 7 : fp << "ElementType = MET_DOUBLE" << std::endl;
1039 int brukerDataPixelType = bDPT.GetIntValue()[0];
1040 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
1041 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1043 // Cross your fingers !!!
1045 // pb : found values : 2, 3, 5
1047 if (brukerDataPixelType == 2) {
1048 mhdDataPixelType = "MET_USHORT";
1051 if (brukerDataPixelType == 3) {
1052 mhdDataPixelType = "MET_USHORT";
1055 if (brukerDataPixelType == 1) {
1056 mhdDataPixelType = "MET_UCHAR";
1062 // ===========================================================================================
1064 std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
1066 std::vector<BrukerImage> imageSet;
1067 br_acqp.SetLoopStructure();
1068 std::vector<int> tempVect = br_acqp.GetLoopStructure() ;
1069 std::map<std::string, BrukerFieldData> map = br_acqp.GetBrukerHeaderMap();
1070 bool result = br_acqp.ObjectVaryingProperties.init(map,tempVect);
1072 br_acqp.SetImageLoopStructure();
1073 br_acqp.SetBrukerImageList();
1074 std::vector<std::vector<int> > brukerImageList = br_acqp.GetBrukerImageList();
1076 BrukerImage image(br_acqp,br_reco);
1077 image.Init(br_acqp,br_reco,1);
1079 for(int i=0;i<brukerImageList.size();i++)
1081 image.Init(br_acqp,br_reco,i);
1082 imageSet.push_back(image);
1085 // Just for checking
1088 std::vector<std::vector <double> > imageOrientation;
1089 std::vector <double> imagePosition;
1090 for(int i=0;i<brukerImageList.size();i++)
1092 // fread(buffer_2dseq, NX*NY*pixelSize*nbSlices*nbInstants, 1, fp);
1094 imagePosition = imageSet[i].getTranslationVectorRPS2XYZ();
1095 std::cout << "Position " << imagePosition[0] << " "
1096 << imagePosition[1] << " " << imagePosition[2] ;
1097 imageOrientation = imageSet[i].getRotationMatrixRPS2XYZ();
1098 std::cout << "\t Orientation " ;
1099 for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
1100 std::cout << imageOrientation[i1][i2] << " ";
1102 //std::cout << "\t Abs Time " << imageSet[i].getAbsoluteTimePosition();
1103 std::cout << "\t Relat Time " << imageSet[i].getRelativeTimePosition();
1105 std::cout << "\t [";
1106 for (int i3=0; i3<imageSet[i].getLoopStamp().size();i3++)
1107 std::cout << " " << imageSet[i].getLoopStamp()[i3];
1108 std::cout << "]" << std::endl;
1115 // ===========================================================================================
1117 void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels,
1122 double spacingX, double spacingY, double sliceDistance,
1123 std::string dcmImageName,
1124 const std::string &patientName,
1126 std::string &studyUID,
1127 std::string &serieUID,
1128 std::string &studyDescr,
1129 std::string &serieDescr,
1130 std::string &strStudyTimeDate,
1132 GDCM_NAME_SPACE::ImageContentType contentType
1135 std::ostringstream str;
1137 GDCM_NAME_SPACE::File *file;
1138 file = GDCM_NAME_SPACE::File::New();
1140 // Set the image size
1143 file->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
1146 file->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
1152 file->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames
1155 // Set the pixel type
1156 // //8, 16, 32, 64 (for double ?)
1159 file->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
1161 file->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
1164 str << pixelSize*8-1;
1165 file->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
1167 // Set the pixel representation // 0/1 , 0=unsigned
1168 file->InsertEntryString("1",0x0028,0x0103, "US"); // Pixel Representation
1170 // Set the samples per pixel // 1:Grey level, 3:RGB
1171 file->InsertEntryString("1",0x0028,0x0002, "US"); // Samples per Pixel
1173 // 0028 0030 DS 2 Pixel Spacing
1175 str << spacingX << "\\" << spacingY;
1176 file->InsertEntryString(str.str(),0x0028,0x0030, "DS"); // Pixel Spacing
1178 // 0018 0050 DS 1 Slice Thickness
1180 str << sliceDistance;
1181 file->InsertEntryString(str.str(),0x0018,0x0050, "DS");
1183 // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
1184 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1185 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1188 // OK : MR is NOT multiframe, but I want just a quick an dirty solution
1189 // 1.2.840.10008.5.1.4.1.1.4 MR Image Storage
1190 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1191 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1193 // if (strlen(patientName) != 0)
1194 file->InsertEntryString(patientName.c_str(),0x0010,0x0010, "PN"); // Patient's Name
1196 file->InsertEntryString(studyUID, 0x0020, 0x000d, "UI");
1197 file->InsertEntryString(serieUID, 0x0020, 0x000e, "UI");
1199 // 0008 0020 DA 1 Study Date
1200 // 0008 0030 TM 1 Study Time
1202 /// \TODO split into 2 strings!
1203 file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
1204 file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),0x0008,0x0030, "TM");
1206 file->InsertEntryString(studyDescr,0x0008,0x1030, "LO"); // Study Description
1207 file->InsertEntryString(serieDescr,0x0008,0x103e, "LO"); // Series Description
1209 //0008|0060 [CS] [Modality]
1210 file->InsertEntryString("MR",0x0008,0x0060, "CS");
1212 // 0020 0037 DS 6 Image Orientation (Patient)
1213 char charImageOrientation[256];
1216 std::cout << "try charImageOrientation " <<
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] << std::endl ;
1224 sprintf(charImageOrientation,"%f\\%f\\%f \\ %f\\%f\\%f",
1225 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0],
1226 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1],
1227 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2],
1228 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0],
1229 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1],
1230 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] ) ;
1232 file->InsertEntryString(charImageOrientation,0x0020,0x0037, "DS");
1235 // 0020 0032 DS 3 Image Position (Patient)
1237 char charImagePosition[256];
1238 sprintf(charImagePosition,"%f\\%f\\%f",
1239 imageSet[imgNum].getTranslationVectorRPS2XYZ()[0],
1240 imageSet[imgNum].getTranslationVectorRPS2XYZ()[1],
1241 imageSet[imgNum].getTranslationVectorRPS2XYZ()[2]);
1243 file->InsertEntryString(charImagePosition,0x0020,0x0032, "DS"); //0020 0032 DS 3 Image Position (Patient)
1247 // 0020 0x1041 DS 1 Slice Location
1248 // sprintf(charImagePosition,"%f",float(imgNum));
1249 // file->InsertEntryString(charImagePosition,0x0020,0x1041, "DS");
1251 // Set Rescale Intercept
1254 file->InsertEntryString(str.str(),0x0028,0x1052,"DS");
1256 // Set Rescale Slope
1259 file->InsertEntryString(str.str(),0x0028,0x1053,"DS");
1262 GDCM_NAME_SPACE::FileHelper *fileH;
1263 fileH = GDCM_NAME_SPACE::FileHelper::New(file);
1264 fileH->SetContentType(contentType);
1266 // cast is just to avoid warnings (*no* conversion is performed)
1267 //fileH->SetImageData((uint8_t *)img,int(maxX*maxY)*sizeof(uint16_t)); // troubles when maxX, mayY are *actually* float!
1269 //std::cout << "-------------------------------- X*Y*nbFrames*pixelSize " << X << " " << Y << " " << nbFrames << " " << pixelSize << std::endl;
1271 fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
1272 fileH->SetWriteModeToRaw();
1273 fileH->SetWriteTypeToDcmExplVR();
1274 if( !fileH->Write(dcmImageName))
1275 std::cout << "Failed for [" << dcmImageName << "]\n"
1276 << " File is unwrittable" << std::endl;