1 #include "bruker2dicom.h"
5 bool Bruker2Dicom::Execute()
7 // ----- Begin Processing -----
9 bool bigEndian = GDCM_NAME_SPACE::Util::IsCurrentProcessorBigEndian();
11 if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(InputDirName) )
13 std::cout << "KO : [" << InputDirName << "] is not a Directory." << std::endl;
19 std::cout << "OK : [" << InputDirName << "] is a Directory." << std::endl;
22 std::string strDirNameOut(OutputDirName);
23 bool res=CreateDirectory(strDirNameOut);
25 std::cout << "[" << OutputDirName << "] Directory creation failure " << std::endl;
29 std::string strDirNamein(InputDirName);
30 GDCM_NAME_SPACE::DirList dirList(strDirNamein, false, true); // DON'T get recursively the list of files
31 std::string strDirNameout(OutputDirName);
36 std::cout << "------------List of found files ------------" << std::endl;
38 std::cout << std::endl;
44 // e.g : at level 0, in : B67d1.Bp1
46 // 1 2 3 4 5 6 AdjStatePerStudy subject
49 GDCM_NAME_SPACE::DirListType fileNames;
50 fileNames = dirList.GetFilenames();
52 std::string outputFileName;
54 // BrukerDataSet br_subject;
56 subject = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
57 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
60 std::cout << " Subject : [" << subject << "]" << std::endl;
61 canOpen =br_subject.LoadFile(subject);
65 std::cout << "Hopeless! no 'subject' found" << std::endl;
66 exit(0); /// \TODO throw an exception !
72 //br_subject.PrintSelf();
74 // get info for 'Study Description'
77 BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
78 acqp_protocol_location = b_protocol_location.GetStringValue()[0];
79 cleanString(acqp_protocol_location);
81 BrukerFieldData b_name=br_subject.GetFieldData("SUBJECT_name_string");
82 std::string subject_name = b_name.GetStringValue()[0];
83 strPatientName = subject_name;
84 cleanString(subject_name);
86 BrukerFieldData b_entry=br_subject.GetFieldData("SUBJECT_entry");
87 std::string subject_entry = b_entry.GetStringValue()[0];
88 //cleanString(subject_entry);
89 subject_entry = subject_entry.substr(11, subject_entry.size()-11);
91 BrukerFieldData b_position=br_subject.GetFieldData("SUBJECT_position");
92 std::string subject_position = b_position.GetStringValue()[0];
93 //cleanString(subject_position);
94 subject_position = subject_position.substr(9, subject_position.size()-9);
96 BrukerFieldData b_date=br_subject.GetFieldData("SUBJECT_date");
97 std::string subject_date = b_date.GetStringValue()[0];
98 strStudyTimeDate = subject_date;
99 cleanString(subject_date);
101 BrukerFieldData b_study_name=br_subject.GetFieldData("SUBJECT_study_name");
102 std::string subject_study_name = b_study_name.GetStringValue()[0];
103 subject_study_name = subject_study_name.substr(1, subject_study_name.size()-2);
104 cleanString(subject_date);
106 strStudyDescr = subject_name + "-" + subject_study_name + "-" + subject_entry + "-" + subject_position + "-" + subject_date;
108 char outputDirName[(unsigned int) PATH_MAX+2];
110 strStudyUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
112 // -----------------------------------------------------
113 // Iterate to ALL the objets(files/directories) found in the input directory
114 // (this is level ZERO)
115 // -----------------------------------------------------
117 GDCM_NAME_SPACE::DirListType::iterator it;
119 for (it = fileNames.begin();
120 it != fileNames.end();
123 if ( GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
126 std::cout << "[" << *it << "] is a directory" << std::endl;
128 //BrukerDataSet br_acqp;
131 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
134 br_acqp.LoadFile(strAcqp);
137 std::string acqp_scan_name;
138 std::string acqp_method;
139 std::string acqp_protocol_location;
141 BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
142 acqp_protocol_location = b_protocol_location.GetStringValue()[0];
143 cleanString(acqp_protocol_location);
145 BrukerFieldData b_scan_name=br_acqp.GetFieldData("ACQ_scan_name");
146 acqp_scan_name = b_scan_name.GetStringValue()[0];
147 cleanString(acqp_scan_name);
149 BrukerFieldData b_method=br_acqp.GetFieldData("ACQ_method");
150 acqp_method = b_method.GetStringValue()[0];
151 cleanString(acqp_method);
153 BrukerFieldData b_list_size = br_acqp.GetFieldData("ACQ_O1_list_size");
154 b_list_size.PrintSelf(); //JP
156 nbSlices = b_list_size.GetIntValue()[0];
158 strSerieDescr = GDCM_NAME_SPACE::Util::GetName(*it)
159 + "-" + acqp_protocol_location
160 + "-" + acqp_scan_name
161 + "-" + acqp_method.c_str();
163 sprintf(outputDirName, "%s%c%s", OutputDirName.c_str(),
164 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
165 strSerieDescr.c_str() );
167 std::cout << " ================================================================================\n"
168 << " ========================= [" << GDCM_NAME_SPACE::Util::GetName(*it).c_str()
169 << acqp_protocol_location.c_str()
170 << acqp_scan_name.c_str()
171 << acqp_method.c_str()
173 << " ================================================================================"
177 printf ("outputDirName [%s]\n", outputDirName);
179 DealWithNiveau1(*it, outputDirName);
181 } // end of : for (GDCM_NAME_SPACE::DirListType::iterator it
185 // =====================================================================
187 void Bruker2Dicom::DealWithNiveau1(std::string level1Directory, std::string currentOutputDirName) {
189 // e.g. : at level 1, in B67d1.Bp1/6
191 // acqp fid imnd pdata pulseprogram spnam0 spnam1
193 bool res = CreateDirectory(currentOutputDirName);
196 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
199 GDCM_NAME_SPACE::DirList dirList(level1Directory, false, true); // DON'T get recursively the list of files
200 GDCM_NAME_SPACE::DirListType fileNames;
201 fileNames = dirList.GetFilenames();
202 // -----------------------------------------------------
203 // Iterate to ALL the objets(files/directories) found in the input directory
204 // -----------------------------------------------------
205 GDCM_NAME_SPACE::DirListType::iterator it;
207 for (it = fileNames.begin();
208 it != fileNames.end();
211 if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
214 std::cout << "--- [" << *it << "] is a file" << std::endl;
218 char outputDirName[(unsigned int) PATH_MAX+2];
219 //std::string firstName;
221 for (it = fileNames.begin();
222 it != fileNames.end();
225 if ( GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
227 // will be always "pdata" ...
229 std::cout << "--- [" << *it << "] is a directory" << std::endl;
232 if (FileLine.startsWith("##$ACQ_size=")) {
233 if (FileLine.startsWith("##$NI=")) {
234 if (FileLine.startsWith("##$NR=")) {
235 if (FileLine.startsWith("##$ACQ_obj_order=")) {
236 if (FileLine.startsWith("##$ACQ_word_size=")) {
237 if (FileLine.startsWith("##$BYTORDA=")) {
238 if (FileLine.startsWith("##$PULPROG=")) {
241 sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
242 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
243 GDCM_NAME_SPACE::Util::GetName(*it).c_str());
246 std::string strMethod;
247 //std::string firstName = *(fileNames.begin());
249 strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin())) +
250 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
252 // std::cout << "---strMethod (for method)=> [" << strMethod << "]" << std::endl;
253 canOpen = br_method.LoadFile(strMethod);
256 strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
257 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
259 //std::cout << "---strMethod (for imnd) => [" << strMethod << "]" << std::endl;
260 canOpen = br_method.LoadFile(strMethod);
263 std::cout << "Hopeless! neither 'method' nor 'imnd' found" << std::endl;
264 exit(0); /// \TODO throw an exception !
268 std::cout << "open => [" << strMethod << "] successfully" << std::endl;
272 ##$PVM_Fov (dimension)
275 dans method (pour perfusion seulement?) :
276 ##$PVM_ObjOrderList=( 8 )
279 ##$PVM_SPackArrNSlices=( 2 )
282 DealWithNiveau2(*it,outputDirName );
287 // =====================================================================
289 void Bruker2Dicom::DealWithNiveau2(std::string level2Directory, std::string currentOutputDirName) {
291 // e.g. : at level 2 in B67d1.Bp1/6/pdata
293 // acqp fid imnd pdata pulseprogram spnam0 spnam1
296 bool res = CreateDirectory(currentOutputDirName);
299 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
303 GDCM_NAME_SPACE::DirList dirList(level2Directory, false, true); // DON'T get recursively the list of files
305 GDCM_NAME_SPACE::DirListType fileNames;
306 fileNames = dirList.GetFilenames();
308 char outputDirName[(unsigned int) PATH_MAX+2];
310 // -----------------------------------------------------
311 // Iterate to ALL the objets(files/directories) found in the input directory
312 // -----------------------------------------------------
313 GDCM_NAME_SPACE::DirListType::iterator it;
317 for (it = fileNames.begin();
318 it != fileNames.end();
321 if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
323 std::cout << "--- --- [" << *it << "] is a file" << std::endl;
328 for (it = fileNames.begin();
329 it != fileNames.end();
332 if ( GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
336 std::cout << "--- --- [" << *it << "] is a directory" << std::endl;
338 // sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
339 // GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
340 // GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
344 // (interest of previous method :
345 // If unaware user changed the pdata name, it goes on working
349 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
352 std::string str_isa_func_name;
353 canOpen = br_isa.LoadFile(str_isa);
356 sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
357 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
358 GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
363 BrukerFieldData b_isa_func_name = br_isa.GetFieldData("ISA_func_name");
365 str_isa_func_name = b_isa_func_name.GetStringValue()[0];
366 cleanString(str_isa_func_name);
368 sprintf(outputDirName, "%s%c%s-%s", currentOutputDirName.c_str(),
369 GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
370 GDCM_NAME_SPACE::Util::GetName(*it).c_str(),
371 str_isa_func_name.c_str());
373 DealWithNiveau3(*it, outputDirName);
380 // =====================================================================
383 void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string currentOutputDirName){
386 // e.g. at level 3, in
388 // just to be able to go on checking // JP
389 if ( GDCM_NAME_SPACE::Util::GetName(level3Directory) != "1")
392 bool res = CreateDirectory(currentOutputDirName);
396 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
400 GDCM_NAME_SPACE::DirList dirList(level3Directory, false, true); // DON'T get recursively the list of files
401 GDCM_NAME_SPACE::DirListType::iterator it;
402 GDCM_NAME_SPACE::DirListType fileNames;
403 fileNames = dirList.GetFilenames();
405 char original2dseqName [(unsigned int) PATH_MAX+2];
406 char currentOutputMhdDirName [(unsigned int) PATH_MAX+2];
408 char outputMhdFileName [(unsigned int) PATH_MAX+2];
409 char output2dseqSliceFileName[(unsigned int) PATH_MAX+6]; // think about extra '.dcm'
410 char output2dseqName [(unsigned int) PATH_MAX+6];
411 char output2dseqCartoName [(unsigned int) PATH_MAX+6];
413 char copyFile[PATH_MAX + PATH_MAX + 5]; // Should be enough!
416 //-------------- try d3proc;
417 char char_d3proc[(unsigned int) PATH_MAX+2];
419 sprintf(char_d3proc,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"d3proc" );
422 std::cout << "--- => [" << char_d3proc << "]" << std::endl;
423 std::string str_d3proc(char_d3proc);
424 canOpen = br_d3proc.LoadFile(str_d3proc);
428 std::cout << "Hopeless! no 'd3proc' found" << std::endl;
429 exit(0); /// \TODO throw an exception !
432 canOpen = br_d3proc.FillMap();
435 std::cout << "Hopeless! FillMap failed on 'd3proc'" << std::endl;
436 exit(0); /// \TODO throw an exception !
439 //-------------- end try d3proc;
442 // -------------------try reco
444 char char_reco[(unsigned int) PATH_MAX+2];
446 sprintf(char_reco,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
447 //str_d3proc = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
448 // GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
451 std::cout << "--- => [" << char_reco << "]" << std::endl;
452 std::string str_reco(char_reco);
453 canOpen = br_reco.LoadFile(str_reco);
455 if (!canOpen) // we try in directory ../1
458 std::cout << "[" << str_reco << "] not found " << std::endl;
459 std::string lastDirName = GDCM_NAME_SPACE::Util::GetPath(level3Directory);
460 //lastDirName = GDCM_NAME_SPACE::Util::GetPath(lastDirName);
461 sprintf(char_reco,"%s%c1%c%s", lastDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
463 canOpen = br_reco.LoadFile(str_reco);
466 std::cout << "Hopeless! cannot find 'reco' in [" << str_reco << "]" << std::endl;
467 exit(0); /// \TODO throw an exception !
471 canOpen = br_reco.FillMap();
474 std::cout << "Hopeless! FillMap failed on [" << str_reco << "]" << std::endl;
475 exit(0); /// \TODO throw an exception !
477 //std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
478 // br_reco.PrintSelf();
479 // std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
481 // -------------------end try reco
484 BrukerFieldData bX = br_d3proc.GetFieldData("IM_SIX");
485 int NX = bX.GetIntValue()[0];
487 std::cout << "IM_SIX " << NX << std::endl;
488 BrukerFieldData bY=br_d3proc.GetFieldData("IM_SIY");
489 int NY = bY.GetIntValue()[0];
491 std::cout << "IM_SIY " << NY << std::endl;
492 /// \todo : check if there are actually 3 dimensions or only 2
494 BrukerFieldData bZ= br_d3proc.GetFieldData("IM_SIZ");
495 int nbFrames = bZ.GetIntValue()[0];
496 std::cout << "IM_SIZ " << nbFrames << std::endl;
498 // WARNING DATTYPE is, either in {ip_short, ip_int, ip_char, ...}, or in {1, 2, 3, ...}
500 BrukerFieldData bDPT = br_d3proc.GetFieldData("DATTYPE");
502 std::string mhdDataPixelType;
504 getImhDataType(bDPT, mhdDataPixelType, pixelSize);
506 BrukerFieldData fov = br_method.GetFieldData("PVM_Fov");
507 double fovX = fov.GetDoubleValue()[0];
508 double fovY = fov.GetDoubleValue()[1];
510 std::cout << "FOV (ds method) " << fovX << " " << fovY << std::endl;
512 /// \TODO probabely a more sophisticated accessor will be necessary :
513 /// (cf : non contiguous slices, overlapping, slice thickness, space between clices, etc)
514 BrukerFieldData bsliceDistance = br_method.GetFieldData("PVM_SPackArrSliceDistance");
515 double sliceDistance = bsliceDistance.GetDoubleValue()[0];
519 sprintf(currentOutputMhdDirName, "%s%c%s", currentOutputDirName.c_str(),
520 GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "MhdFiles");
521 res = CreateDirectory( currentOutputMhdDirName );
523 std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
528 std::cout << "Directory creation [" << currentOutputDirName << "]" << std::endl;
531 std::cout << "nbFrames " << nbFrames << std::endl;
532 std::cout << "nbSlices " << nbSlices << std::endl;
534 int nbInstants = nbFrames/nbSlices;
535 std::cout << "nbInstants (deduced )" << nbInstants << std::endl;
538 FILE *fp; // for MHD files
540 sprintf( original2dseqName, "%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "2dseq");
543 // \TODO : tenir compte du bazar precedent
545 // load 2dseq in memory
547 fp = fopen(original2dseqName, "rb");
550 std::cout << "Cannot open [" << original2dseqName << "] for reading" << std::endl;
554 unsigned char * buffer_2dseq = new unsigned char[NX*NY*pixelSize*nbSlices*nbInstants];
555 ///\ TODO : find a safer way to be sure to read everything!
556 size_t lgr = fread(buffer_2dseq, 1, NX*NY*pixelSize*nbSlices*nbInstants, fp);
558 // This one will be important!
559 // ---------------------------
560 imageSet = CreateImageSet ( );
562 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
563 if (nbInstants==1) // creer un seul fichier .mhd pour toutes les Slices! (images natives)
565 std::cout << "Single instant : do not split" << std::endl;
568 sprintf(outputMhdFileName, "%s%cMhdData_Toutes_les_Slices.mhd", currentOutputMhdDirName,
569 GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
570 fp=fopen(outputMhdFileName, "w");
573 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
578 fprintf(fp, "ObjectType = Image\n");
579 fprintf(fp, "NDims = 3\n" );
580 fprintf(fp, "BinaryData = True \n" );
581 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
582 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices );
583 fprintf(fp, "HeaderSize = %d\n", 0);
584 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
585 fprintf(fp, "Position = 0 0 %d\n", 0 );
586 fprintf(fp, "Offset = 0 0 0\n" );
587 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
588 fprintf(fp, "ElementNumberOfChannels = 1\n" );
589 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
590 fprintf(fp, "ElementDataFile = %s\n", "../2dseq_toutes_les_Slices" );
593 sprintf(output2dseqSliceFileName, "%s%c2dseq_toutes_les_Slices",
594 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
595 fp=fopen(output2dseqSliceFileName, "wb");
598 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
602 fwrite( buffer_2dseq, NX*NY*pixelSize, nbSlices, fp);
605 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID();
609 sprintf(output2dseqSliceFileName, "%s%c2dseq_toutes_les_Slices.dcm",
610 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
612 /* ----------- Write Dicom Image ---------------*/
613 MakeDicomImage(buffer_2dseq,
618 fovX/NY, fovY/NY, sliceDistance,
619 output2dseqSliceFileName,
627 0,// index frame number
628 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
631 } // end if nbInstants = 1
633 else // more than ONE instant
636 // it's (slice1,slide2, ...)t1 ; (slice1,slide2, ...)t2 ; ...
638 unsigned char * pixelsForCurrentSlice = new unsigned char[NX*NY*pixelSize*nbInstants];
641 for (sliceNb=0; sliceNb<nbSlices; sliceNb++)
645 sprintf(outputMhdFileName, "%s%cMhdData_%03d.mhd", currentOutputMhdDirName,
646 GDCM_NAME_SPACE::GDCM_FILESEPARATOR, k );
648 std::cout << "--- Output MHD file [" << outputMhdFileName << "]" << std::endl;
649 fp=fopen(outputMhdFileName, "w");
652 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
657 /* ----------- Write MHD Image ---------------*/
659 // std::cout << "Open sucessfully[" << outputMhdFileName << "] for writting" << std::endl;
660 fprintf(fp, "ObjectType = Image\n");
661 fprintf(fp, "NDims = 3\n" );
662 fprintf(fp, "BinaryData = True \n" );
663 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
664 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbInstants);
665 fprintf(fp, "HeaderSize = %d\n", 0);
666 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, 1.0 ); // slice distance : no meaning for temporal serie
667 fprintf(fp, "Position = 0 0 %d\n", sliceNb );
668 fprintf(fp, "Offset = 0 0 0\n" );
669 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
670 fprintf(fp, "ElementNumberOfChannels = 1\n" );
671 fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );
672 fprintf(fp, "ElementDataFile = ..%c2dseq_Slice_%d\n", GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb );
676 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d",
677 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,sliceNb);
678 fp=fopen(output2dseqSliceFileName, "wb");
681 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
684 int frameSize = NX*NY*pixelSize;
685 for (instantNb=0; instantNb<nbInstants; instantNb++)
687 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
688 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
693 // std::cout << "end writting[" << output2dseqSliceFileName << "]" << std::endl;
700 sprintf(output2dseqSliceFileName, "%sdummy_buffer",
701 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
702 fp=fopen(output2dseqSliceFileName, "wb");
705 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
708 int frameSize = NX*NY*pixelSize;
709 for (instantNb=0; instantNb<nbInstants; instantNb++)
711 // std::cout << "------------SN " << sliceNb << " IN " << instantNb << " T " << nbSlices*instantNb + sliceNb << std::endl;
712 fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
718 fp=fopen(output2dseqSliceFileName, "rb");
721 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for reading" << std::endl;
724 fread( pixelsForCurrentSlice,
725 frameSize*nbInstants,
728 // end of desperate try !
731 /* ----------- Write Dicom Image ---------------*/
733 int frameSize = NX*NY*pixelSize;
734 for (instantNb=0; instantNb<nbInstants; instantNb++)
736 memcpy(pixelsForCurrentSlice + frameSize*instantNb, buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize, frameSize);
739 int indOfFirsImageWithinImageSet = nbSlices*instantNb;
740 sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d.dcm",
741 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb);
744 pixelsForCurrentSlice,
749 fovX/NY, fovY/NY, sliceDistance,
750 output2dseqSliceFileName,
759 GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
762 std::cout << "--- Output DCM file [" << output2dseqSliceFileName << "]" << std::endl;
768 delete [] pixelsForCurrentSlice;
769 } // end nbInstants == 1
770 delete [] buffer_2dseq;
774 // -----------------------------------------------------
775 // deal with MatLab-generated Carto file.
776 // -----------------------------------------------------
778 dealWithCarto(fileNames, NX, NY, nbSlices, fovX, fovY, sliceDistance,
779 copyFile, currentOutputDirName, outputMhdFileName, output2dseqCartoName);
783 // ===========================================================================================
785 void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX, int NY, int nbSlices,
786 double fovX, double fovY, double sliceDistance,
787 char *copyFile, std::string ¤tOutputDirName,
788 char *outputMhdFileName, char *output2dseqCartoName)
790 // -----------------------------------------------------
791 // deal with MatLab-generated Carto file.
792 // -----------------------------------------------------
794 char *code[] ={ "ADC", "adc", "TTP", "ttp", "PEAK", "peak" , ""}; // add more carto file name identifiers if necessary; end with ""
796 GDCM_NAME_SPACE::DirListType::iterator it;
797 char file_name_ident[500];
800 // Iterate to ALL the objets(files/directories) found in the input directory
801 for (it = fileNames.begin();
802 it != fileNames.end();
805 if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
808 std::cout << "--- [" << *it << "] is a file" << std::endl;
812 while (code[icode][0] != 0)
814 sprintf(file_name_ident, "2dseq_%s",code[icode]); // e.g "2dseq_ADC"
815 std::string::size_type loc = (*it).rfind(file_name_ident);
817 if ( loc != std::string::npos )
820 ///\ TODO : find a safer way to be sure to read everything!
821 unsigned char *buffer_carto = new unsigned char[NX*NY*sizeof(double)*nbSlices];
822 fp = fopen ( (*it).c_str(), "rb");
824 std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
827 fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
829 std::cout << "Deal with Carto file :[" <<*it << "], computed length : "
830 << NX*NY*sizeof(double)*nbSlices << std::endl;
831 std::string lastFileName = GDCM_NAME_SPACE::Util::GetName((*it).c_str());
834 // Copy the data file in the new directory
835 sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
836 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str());
838 sprintf(outputMhdFileName, "%s%c%s%s",
839 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".mhd" );
841 std::cout << "--- Output Carto MHD file [" << outputMhdFileName << "]" << std::endl;
844 fp=fopen(outputMhdFileName, "w");
847 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
851 fprintf(fp, "ObjectType = Image\n");
852 fprintf(fp, "NDims = 3\n" );
853 fprintf(fp, "BinaryData = True \n" );
854 fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
855 fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices);
856 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
857 fprintf(fp, "HeaderSize = %d\n", 0 );
858 fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
859 fprintf(fp, "Position = 0 0 0\n" );
860 fprintf(fp, "Offset = 0 0 0\n" );
861 fprintf(fp, "CenterOfRotation = 0 0 0\n" );
862 fprintf(fp, "ElementNumberOfChannels = 1\n" );
863 fprintf(fp, "ElementType = %s\n", "MET_DOUBLE" );
864 fprintf(fp, "ElementDataFile = %s\n", lastFileName.c_str() );
869 std::cout << "--- end write Carto MHD file [" << outputMhdFileName << "]" << std::endl;
872 // ----------- Write Dicom Image ---------------
876 sprintf(output2dseqCartoName, "%s%c%s%s",
877 currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".dcm" );
879 std::cout << "--- end create name output2dseqCartoName file [" << output2dseqCartoName << "]" << std::endl;
881 strSerieUID = GDCM_NAME_SPACE::Util::CreateUniqueUID(); //New SerieUID for each carto.
882 std::string strNewSerieDescr(strSerieDescr+ "_" +GDCM_NAME_SPACE::Util::GetName((*it).c_str()));
883 MakeDicomImage(buffer_carto,
888 fovX/NY, fovY/NY, sliceDistance,
889 output2dseqCartoName,
898 GDCM_NAME_SPACE::CREATED_IMAGE
902 delete [] buffer_carto;
904 std::cout << "--- End writing Carto DICOM file [" << output2dseqCartoName << "]" << std::endl;
905 break; // don't check for more ident on same file name!
911 } // end iterate on files
915 // ==========================================================================================================
917 bool Bruker2Dicom::CreateDirectory(std::string OutputDirName)
919 std::string systemCommand;
922 std::cout << "Check for output directory :[" << OutputDirName << "]."
924 if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(OutputDirName) ) // dirout not found
926 std::string strDirNameout(OutputDirName); // to please gcc 4
927 systemCommand = "mkdir " + strDirNameout; // create it!
929 std::cout << systemCommand << std::endl;
930 system (systemCommand.c_str());
931 if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(OutputDirName) ) // be sure it worked
934 std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
936 /// \todo : THROW AN EXCEPTION
941 std::cout << "Directory [" << OutputDirName << "] created." << std::endl;
947 std::cout << "Output Directory [" << OutputDirName << "] already exists; Used as is." << std::endl;
955 // ===========================================================================================
957 /// \TODO move cleanString to 'crea' ?
959 void Bruker2Dicom::cleanString(std::string &s)
962 if (s[l-1] == 0x0A || s[l-1] == 0x0D ) // CR or NL
967 if (s[l-1] == ' ' ) // blank space
975 std::string repChar("_");
976 GDCM_NAME_SPACE::Util::ReplaceSpecChar(s, repChar);
981 // ===========================================================================================
984 void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPixelType, int &pixelSize)
986 if(bDPT.GetDataType() == "string")
988 std::string brukerDataPixelType = bDPT.GetStringValue()[0];
989 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
990 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
992 if (brukerDataPixelType == "ip_short") {
993 mhdDataPixelType = "MET_USHORT";
996 if (brukerDataPixelType == "ip_int") {
997 mhdDataPixelType = "MET_UINT";
1000 if (brukerDataPixelType == "ip_char") {
1001 mhdDataPixelType = "MET_UCHAR";
1004 /// \TODO : finish the list
1006 case 0 : fp << "ElementType = MET_CHAR" << std::endl;
1008 case 1 : fp << "ElementType = MET_UCHAR" << std::endl;
1010 case 2 : fp << "ElementType = MET_SHORT" << std::endl;
1012 case 3 : fp << "ElementType = MET_USHORT" << std::endl;
1014 case 4 : fp << "ElementType = MET_INT" << std::endl;
1016 case 5 : fp << "ElementType = MET_UINT" << std::endl;
1018 case 6 : fp << "ElementType = MET_FLOAT" << std::endl;
1020 case 7 : fp << "ElementType = MET_DOUBLE" << std::endl;
1025 int brukerDataPixelType = bDPT.GetIntValue()[0];
1026 std::cout << "DATTYPE " << brukerDataPixelType << std::endl;
1027 //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1029 // Cross your fingers !!!
1031 // pb : found values : 2, 3, 5
1033 if (brukerDataPixelType == 2) {
1034 mhdDataPixelType = "MET_USHORT";
1037 if (brukerDataPixelType == 3) {
1038 mhdDataPixelType = "MET_USHORT";
1041 if (brukerDataPixelType == 1) {
1042 mhdDataPixelType = "MET_UCHAR";
1048 // ===========================================================================================
1050 std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
1052 std::vector<BrukerImage> imageSet;
1053 br_acqp.SetLoopStructure();
1054 std::vector<int> tempVect = br_acqp.GetLoopStructure() ;
1055 std::map<std::string, BrukerFieldData> map = br_acqp.GetBrukerHeaderMap();
1056 bool result = br_acqp.ObjectVaryingProperties.init(map,tempVect);
1058 br_acqp.SetImageLoopStructure();
1059 br_acqp.SetBrukerImageList();
1060 std::vector<std::vector<int> > brukerImageList = br_acqp.GetBrukerImageList();
1062 BrukerImage image(br_acqp,br_reco);
1063 image.Init(br_acqp,br_reco,1);
1065 for(int i=0;i<brukerImageList.size();i++)
1067 image.Init(br_acqp,br_reco,i);
1068 imageSet.push_back(image);
1071 // Just for checking
1074 std::vector<std::vector <double> > imageOrientation;
1075 std::vector <double> imagePosition;
1076 for(int i=0;i<brukerImageList.size();i++)
1078 // fread(buffer_2dseq, NX*NY*pixelSize*nbSlices*nbInstants, 1, fp);
1080 imagePosition = imageSet[i].getTranslationVectorRPS2XYZ();
1081 std::cout << "Position " << imagePosition[0] << " "
1082 << imagePosition[1] << " " << imagePosition[2] ;
1083 imageOrientation = imageSet[i].getRotationMatrixRPS2XYZ();
1084 std::cout << "\t Orientation " ;
1085 for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
1086 std::cout << imageOrientation[i1][i2] << " ";
1088 //std::cout << "\t Abs Time " << imageSet[i].getAbsoluteTimePosition();
1089 std::cout << "\t Relat Time " << imageSet[i].getRelativeTimePosition();
1091 std::cout << "\t [";
1092 for (int i3=0; i3<imageSet[i].getLoopStamp().size();i3++)
1093 std::cout << " " << imageSet[i].getLoopStamp()[i3];
1094 std::cout << "]" << std::endl;
1101 // ===========================================================================================
1103 void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels,
1108 double spacingX, double spacingY, double sliceDistance,
1109 std::string dcmImageName,
1110 const std::string &patientName,
1112 std::string &studyUID,
1113 std::string &serieUID,
1114 std::string &studyDescr,
1115 std::string &serieDescr,
1116 std::string &strStudyTimeDate,
1118 GDCM_NAME_SPACE::ImageContentType contentType
1121 std::ostringstream str;
1123 GDCM_NAME_SPACE::File *file;
1124 file = GDCM_NAME_SPACE::File::New();
1126 // Set the image size
1129 file->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
1132 file->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
1138 file->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames
1141 // Set the pixel type
1142 // //8, 16, 32, 64 (for double ?)
1145 file->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
1147 file->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
1150 str << pixelSize*8-1;
1151 file->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
1153 // Set the pixel representation // 0/1 , 0=unsigned
1154 file->InsertEntryString("1",0x0028,0x0103, "US"); // Pixel Representation
1156 // Set the samples per pixel // 1:Grey level, 3:RGB
1157 file->InsertEntryString("1",0x0028,0x0002, "US"); // Samples per Pixel
1159 // 0028 0030 DS 2 Pixel Spacing
1161 str << spacingX << "\\" << spacingY;
1162 file->InsertEntryString(str.str(),0x0028,0x0030, "DS"); // Pixel Spacing
1164 // 0018 0050 DS 1 Slice Thickness
1166 str << sliceDistance;
1167 file->InsertEntryString(str.str(),0x0018,0x0050, "DS");
1169 // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
1170 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1171 // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1174 // OK : MR is NOT multiframe, but I want just a quick an dirty solution
1175 // 1.2.840.10008.5.1.4.1.1.4 MR Image Storage
1176 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI"); // [Media Storage SOP Class UID]
1177 file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI"); // [SOP Class UID]
1179 // if (strlen(patientName) != 0)
1180 file->InsertEntryString(patientName.c_str(),0x0010,0x0010, "PN"); // Patient's Name
1182 file->InsertEntryString(studyUID, 0x0020, 0x000d, "UI");
1183 file->InsertEntryString(serieUID, 0x0020, 0x000e, "UI");
1185 // 0008 0020 DA 1 Study Date
1186 // 0008 0030 TM 1 Study Time
1188 /// \TODO split into 2 strings!
1189 file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
1190 file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),0x0008,0x0030, "TM");
1192 file->InsertEntryString(studyDescr,0x0008,0x1030, "LO"); // Study Description
1193 file->InsertEntryString(serieDescr,0x0008,0x103e, "LO"); // Series Description
1195 //0008|0060 [CS] [Modality]
1196 file->InsertEntryString("MR",0x0008,0x0060, "CS");
1198 // 0020 0037 DS 6 Image Orientation (Patient)
1199 char charImageOrientation[256];
1202 std::cout << "try charImageOrientation " <<
1203 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0] << " " <<
1204 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1] << " " <<
1205 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2] << " " <<
1206 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0] << " " <<
1207 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1] << " " <<
1208 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] << std::endl ;
1210 sprintf(charImageOrientation,"%f\\%f\\%f \\ %f\\%f\\%f",
1211 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0],
1212 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1],
1213 imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2],
1214 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0],
1215 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1],
1216 imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] ) ;
1218 file->InsertEntryString(charImageOrientation,0x0020,0x0037, "DS");
1221 // 0020 0032 DS 3 Image Position (Patient)
1223 char charImagePosition[256];
1224 sprintf(charImagePosition,"%f\\%f\\%f",
1225 imageSet[imgNum].getTranslationVectorRPS2XYZ()[0],
1226 imageSet[imgNum].getTranslationVectorRPS2XYZ()[1],
1227 imageSet[imgNum].getTranslationVectorRPS2XYZ()[2]);
1229 file->InsertEntryString(charImagePosition,0x0020,0x0032, "DS"); //0020 0032 DS 3 Image Position (Patient)
1233 // 0020 0x1041 DS 1 Slice Location
1234 // sprintf(charImagePosition,"%f",float(imgNum));
1235 // file->InsertEntryString(charImagePosition,0x0020,0x1041, "DS");
1237 // Set Rescale Intercept
1240 file->InsertEntryString(str.str(),0x0028,0x1052,"DS");
1242 // Set Rescale Slope
1245 file->InsertEntryString(str.str(),0x0028,0x1053,"DS");
1248 GDCM_NAME_SPACE::FileHelper *fileH;
1249 fileH = GDCM_NAME_SPACE::FileHelper::New(file);
1250 fileH->SetContentType(contentType);
1252 // cast is just to avoid warnings (*no* conversion is performed)
1253 //fileH->SetImageData((uint8_t *)img,int(maxX*maxY)*sizeof(uint16_t)); // troubles when maxX, mayY are *actually* float!
1255 //std::cout << "-------------------------------- X*Y*nbFrames*pixelSize " << X << " " << Y << " " << nbFrames << " " << pixelSize << std::endl;
1257 fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
1258 fileH->SetWriteModeToRaw();
1259 fileH->SetWriteTypeToDcmExplVR();
1260 if( !fileH->Write(dcmImageName))
1261 std::cout << "Failed for [" << dcmImageName << "]\n"
1262 << " File is unwrittable" << std::endl;