void StrokeMask:: Write(const std::string& filename, const TPixel& strokeValue) { typedef itk::Image<TPixel, 2> ImageType; typename ImageType::Pointer image = ImageType::New(); image->SetRegions(this->GetLargestPossibleRegion()); image->Allocate(); itk::ImageRegionConstIteratorWithIndex<StrokeMask> maskIterator(this, this->GetLargestPossibleRegion()); while(!maskIterator.IsAtEnd()) { if(maskIterator.Get() == StrokeMaskPixelTypeEnum::STROKE) { image->SetPixel(maskIterator.GetIndex(), strokeValue); } else { image->SetPixel(maskIterator.GetIndex(), itk::NumericTraits<TPixel>::Zero); } ++maskIterator; } typedef itk::ImageFileWriter<ImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename); writer->SetInput(image); writer->Update(); }
void SetOutputNames( typename WriterType::Pointer writer, const std::string& baseFileName, unsigned int numberOfImages ) { if( numberOfImages > 1 ) { itk::NumericSeriesFileNames::Pointer numericFileNameWriter = itk::NumericSeriesFileNames::New(); std::string finalFileName = baseFileName; std::string::size_type pos = baseFileName.find_last_of(".",baseFileName.length()-1); if(pos==std::string::npos) finalFileName.append(".%d.png"); else finalFileName.insert(pos,".%d"); MITK_DEBUG << "Filename: " << finalFileName; numericFileNameWriter->SetEndIndex(numberOfImages); numericFileNameWriter->SetSeriesFormat(finalFileName.c_str()); numericFileNameWriter->Modified(); writer->SetFileNames(numericFileNameWriter->GetFileNames()); } // if the given image is an 2D-png image, do not use the numericFileNameWriter // to generate the name, since it alters the fileName given as parameter else { writer->SetFileName( baseFileName.c_str() ); } }
void transform(string inputFilename, string outputFilename) { typedef itk::Image< TPixelType, N > ImageType; typedef itk::ImageFileReader< ImageType > ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; typename ReaderType::Pointer reader = ReaderType::New(); itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New(); reader->SetImageIO(io); reader->SetFileName(inputFilename); try { reader->Update(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught while reading image " << std::endl; std::cerr << e << std::endl; } typename WriterType::Pointer writer = WriterType::New(); writer->SetImageIO(io); writer->SetFileName(outputFilename); writer->SetInput(reader->GetOutput()); try { writer->Update(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught while writing image " << std::endl; std::cerr << e << std::endl; } }
void _mitkItkPictureWriteComposite(itk::Image< TPixel, VImageDimension >* itkImage, const std::string& fileName) { typedef itk::Image< TPixel, VImageDimension > TImageType; typedef itk::Image< TPixel, 2 > TImageType2D; typedef itk::ImageSeriesWriter< TImageType, TImageType2D > WriterType; typename WriterType::Pointer writer = WriterType::New(); // get the dimension info unsigned int numberOfImages = 1; if( itkImage->GetImageDimension() > 2) numberOfImages = itkImage->GetLargestPossibleRegion().GetSize()[2]; // create output name(s) SetOutputNames<WriterType>( writer, fileName, numberOfImages ); writer->SetInput( itkImage ); try { writer->Update(); } catch(const itk::ExceptionObject &e) { MITK_ERROR << "ITK Exception occured: " << e.what(); mitkThrow() << "Caught ITK exception while writing image with composite type \n" << e.what(); } }
template <typename T> int writeImage(typename T::Pointer im, const char* filename){ printf("Writing %s ... \n",filename); typedef typename itk::ImageFileWriter< T > WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename); writer->SetInput(im); try { writer->Update(); } catch(itk::ExceptionObject &err) { std::cerr << "ExceptionObject caught!" <<std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
template<class TImage> void ttt::JSONTissueTrackingProject::storeImage(const typename TImage::Pointer & image, const std::string & table,unsigned int frame) { std::stringstream ssQuery, ssFileName, ssPath; typedef itk::ImageFileWriter<TImage> WriterType; typename WriterType::Pointer writer = WriterType::New(); ssFileName << table << "-" << frame << ".tif"; ssPath << this->m_ProjectPath << "/" << ssFileName.str(); writer->SetFileName(ssPath.str()); writer->SetInput(image); writer->Update(); try { ssQuery << "INSERT into " << table << " (idProject, t, fileName) values (?, ?, ?) on duplicate key UPDATE fileName=VALUES(fileName)"; std::auto_ptr<sql::PreparedStatement> prep_stmt( m_DB->prepareStatement(ssQuery.str())); prep_stmt->setInt(1, m_ProjectID); //IDproject==2 prep_stmt->setInt(2, frame); //t==0 prep_stmt->setString(3, ssFileName.str()); prep_stmt->execute(); } catch (sql::SQLException &e) { /* The MySQL Connector/C++ throws three different exceptions: - sql::MethodNotImplementedException (derived from sql::SQLException) - sql::InvalidArgumentException (derived from sql::SQLException) - sql::SQLException (derived from std::runtime_error) */ cout << "# ERR: SQLException in " << __FILE__; // cout << "(" << EXAMPLE_FUNCTION << ") on line " << __LINE__ << endl; /* Use what() (derived from std::runtime_error) to fetch the error message */ cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } }
void _mitkItkPictureWriteComposite(itk::Image< TPixel, VImageDimension >* itkImage, const std::string& fileName) { typedef itk::Image< TPixel, VImageDimension > TImageType; typedef itk::ImageFileWriter< TImageType > WriterType; typename WriterType::Pointer simpleWriter = WriterType::New(); simpleWriter->SetFileName( fileName ); simpleWriter->SetInput( itkImage ); try { simpleWriter->Update(); } catch( itk::ExceptionObject &e) { std::cerr << "Caught exception while writing image with composite type: \n" << e.what(); } }
void ForegroundBackgroundSegmentMask:: Write(const std::string& filename, const ForegroundPixelValueWrapper<TPixel>& foregroundValue, const BackgroundPixelValueWrapper<TPixel>& backgroundValue) { typedef itk::Image<TPixel, 2> ImageType; typename ImageType::Pointer image = ImageType::New(); image->SetRegions(this->GetLargestPossibleRegion()); image->Allocate(); itk::ImageRegionConstIteratorWithIndex<ForegroundBackgroundSegmentMask> maskIterator(this, this->GetLargestPossibleRegion()); while(!maskIterator.IsAtEnd()) { if(maskIterator.Get() == ForegroundBackgroundSegmentMaskPixelTypeEnum::FOREGROUND) { image->SetPixel(maskIterator.GetIndex(), foregroundValue.Value); } else if(maskIterator.Get() == ForegroundBackgroundSegmentMaskPixelTypeEnum::BACKGROUND) { image->SetPixel(maskIterator.GetIndex(), backgroundValue.Value); } ++maskIterator; } typedef itk::ImageFileWriter<ImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename); writer->SetInput(image); writer->Update(); }
void DemonsRegistration::GenerateData2(const itk::Image<TPixel, VImageDimension>* itkImage1) { typedef typename itk::Image< TPixel, VImageDimension > FixedImageType; typedef typename itk::Image< TPixel, VImageDimension > MovingImageType; typedef float InternalPixelType; typedef typename itk::Image< InternalPixelType, VImageDimension > InternalImageType; typedef typename itk::CastImageFilter< FixedImageType, InternalImageType > FixedImageCasterType; typedef typename itk::CastImageFilter< MovingImageType, InternalImageType > MovingImageCasterType; typedef typename itk::Image< InternalPixelType, VImageDimension > InternalImageType; typedef typename itk::Vector< float, VImageDimension > VectorPixelType; typedef typename itk::Image< VectorPixelType, VImageDimension > DeformationFieldType; typedef typename itk::DemonsRegistrationFilter< InternalImageType, InternalImageType, DeformationFieldType> RegistrationFilterType; typedef typename itk::WarpImageFilter< MovingImageType, MovingImageType, DeformationFieldType > WarperType; typedef typename itk::LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; typedef TPixel OutputPixelType; typedef typename itk::Image< OutputPixelType, VImageDimension > OutputImageType; typedef typename itk::CastImageFilter< MovingImageType, OutputImageType > CastFilterType; typedef typename itk::ImageFileWriter< OutputImageType > WriterType; typedef typename itk::ImageFileWriter< DeformationFieldType > FieldWriterType; typename FixedImageType::Pointer fixedImage = FixedImageType::New(); mitk::CastToItkImage(m_ReferenceImage, fixedImage); typename MovingImageType::ConstPointer movingImage = itkImage1; if (fixedImage.IsNotNull() && movingImage.IsNotNull()) { typename RegistrationFilterType::Pointer filter = RegistrationFilterType::New(); this->AddStepsToDo(4); typename itk::ReceptorMemberCommand<DemonsRegistration>::Pointer command = itk::ReceptorMemberCommand<DemonsRegistration>::New(); command->SetCallbackFunction(this, &DemonsRegistration::SetProgress); filter->AddObserver( itk::IterationEvent(), command ); typename FixedImageCasterType::Pointer fixedImageCaster = FixedImageCasterType::New(); fixedImageCaster->SetInput(fixedImage); filter->SetFixedImage( fixedImageCaster->GetOutput() ); typename MovingImageCasterType::Pointer movingImageCaster = MovingImageCasterType::New(); movingImageCaster->SetInput(movingImage); filter->SetMovingImage(movingImageCaster->GetOutput()); filter->SetNumberOfIterations( m_Iterations ); filter->SetStandardDeviations( m_StandardDeviation ); filter->Update(); typename WarperType::Pointer warper = WarperType::New(); typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); warper->SetInput( movingImage ); warper->SetInterpolator( interpolator ); warper->SetOutputSpacing( fixedImage->GetSpacing() ); warper->SetOutputOrigin( fixedImage->GetOrigin() ); warper->SetOutputDirection( fixedImage->GetDirection()); warper->SetDisplacementField( filter->GetOutput() ); warper->Update(); Image::Pointer outputImage = this->GetOutput(); mitk::CastToMitkImage( warper->GetOutput(), outputImage ); typename WriterType::Pointer writer = WriterType::New(); typename CastFilterType::Pointer caster = CastFilterType::New(); writer->SetFileName( m_ResultName ); caster->SetInput( warper->GetOutput() ); writer->SetInput( caster->GetOutput() ); if(m_SaveResult) { writer->Update(); } if (VImageDimension == 2) { typedef DeformationFieldType VectorImage2DType; typedef typename DeformationFieldType::PixelType Vector2DType; typename VectorImage2DType::ConstPointer vectorImage2D = filter->GetOutput(); typename VectorImage2DType::RegionType region2D = vectorImage2D->GetBufferedRegion(); typename VectorImage2DType::IndexType index2D = region2D.GetIndex(); typename VectorImage2DType::SizeType size2D = region2D.GetSize(); typedef typename itk::Vector< float, 3 > Vector3DType; typedef typename itk::Image< Vector3DType, 3 > VectorImage3DType; typedef typename itk::ImageFileWriter< VectorImage3DType > WriterType; typename WriterType::Pointer writer3D = WriterType::New(); typename VectorImage3DType::Pointer vectorImage3D = VectorImage3DType::New(); typename VectorImage3DType::RegionType region3D; typename VectorImage3DType::IndexType index3D; typename VectorImage3DType::SizeType size3D; index3D[0] = index2D[0]; index3D[1] = index2D[1]; index3D[2] = 0; size3D[0] = size2D[0]; size3D[1] = size2D[1]; size3D[2] = 1; region3D.SetSize( size3D ); region3D.SetIndex( index3D ); typename VectorImage2DType::SpacingType spacing2D = vectorImage2D->GetSpacing(); typename VectorImage3DType::SpacingType spacing3D; spacing3D[0] = spacing2D[0]; spacing3D[1] = spacing2D[1]; spacing3D[2] = 1.0; vectorImage3D->SetSpacing( spacing3D ); vectorImage3D->SetRegions( region3D ); vectorImage3D->Allocate(); typedef typename itk::ImageRegionConstIterator< VectorImage2DType > Iterator2DType; typedef typename itk::ImageRegionIterator< VectorImage3DType > Iterator3DType; Iterator2DType it2( vectorImage2D, region2D ); Iterator3DType it3( vectorImage3D, region3D ); it2.GoToBegin(); it3.GoToBegin(); Vector2DType vector2D; Vector3DType vector3D; vector3D[2] = 0; // set Z component to zero. while( !it2.IsAtEnd() ) { vector2D = it2.Get(); vector3D[0] = vector2D[0]; vector3D[1] = vector2D[1]; it3.Set( vector3D ); ++it2; ++it3; } writer3D->SetInput( vectorImage3D ); m_DeformationField = vectorImage3D; writer3D->SetFileName( m_FieldName ); try { if(m_SaveField) { writer3D->Update(); } } catch( itk::ExceptionObject & excp ) { MITK_ERROR << excp << std::endl; } } else { typename FieldWriterType::Pointer fieldwriter = FieldWriterType::New(); fieldwriter->SetFileName(m_FieldName); fieldwriter->SetInput( filter->GetOutput() ); m_DeformationField = (itk::Image<itk::Vector<float, 3>,3> *)(filter->GetOutput()); if(m_SaveField) { fieldwriter->Update(); } } this->SetRemainingProgress(4); } }
int StartPeakExtraction(int argc, char* argv[]) { mitkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("image", "i", mitkCommandLineParser::InputFile, "Input image", "sh coefficient image", us::Any(), false); parser.addArgument("outroot", "o", mitkCommandLineParser::OutputDirectory, "Output directory", "output root", us::Any(), false); parser.addArgument("mask", "m", mitkCommandLineParser::InputFile, "Mask", "mask image"); parser.addArgument("normalization", "n", mitkCommandLineParser::Int, "Normalization", "0=no norm, 1=max norm, 2=single vec norm", 1, true); parser.addArgument("numpeaks", "p", mitkCommandLineParser::Int, "Max. number of peaks", "maximum number of extracted peaks", 2, true); parser.addArgument("peakthres", "r", mitkCommandLineParser::Float, "Peak threshold", "peak threshold relative to largest peak", 0.4, true); parser.addArgument("abspeakthres", "a", mitkCommandLineParser::Float, "Absolute peak threshold", "absolute peak threshold weighted with local GFA value", 0.06, true); parser.addArgument("shConvention", "s", mitkCommandLineParser::String, "Use specified SH-basis", "use specified SH-basis (MITK, FSL, MRtrix)", string("MITK"), true); parser.addArgument("noFlip", "f", mitkCommandLineParser::Bool, "No flip", "do not flip input image to match MITK coordinate convention"); parser.addArgument("clusterThres", "c", mitkCommandLineParser::Float, "Clustering threshold", "directions closer together than the specified angular threshold will be clustered (in rad)", 0.9); parser.addArgument("flipX", "fx", mitkCommandLineParser::Bool, "Flip X", "Flip peaks in x direction"); parser.addArgument("flipY", "fy", mitkCommandLineParser::Bool, "Flip Y", "Flip peaks in y direction"); parser.addArgument("flipZ", "fz", mitkCommandLineParser::Bool, "Flip Z", "Flip peaks in z direction"); parser.setCategory("Preprocessing Tools"); parser.setTitle("Peak Extraction"); parser.setDescription(""); parser.setContributor("MIC"); map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; // mandatory arguments string imageName = us::any_cast<string>(parsedArgs["image"]); string outRoot = us::any_cast<string>(parsedArgs["outroot"]); // optional arguments string maskImageName(""); if (parsedArgs.count("mask")) maskImageName = us::any_cast<string>(parsedArgs["mask"]); int normalization = 1; if (parsedArgs.count("normalization")) normalization = us::any_cast<int>(parsedArgs["normalization"]); int numPeaks = 2; if (parsedArgs.count("numpeaks")) numPeaks = us::any_cast<int>(parsedArgs["numpeaks"]); float peakThres = 0.4; if (parsedArgs.count("peakthres")) peakThres = us::any_cast<float>(parsedArgs["peakthres"]); float absPeakThres = 0.06; if (parsedArgs.count("abspeakthres")) absPeakThres = us::any_cast<float>(parsedArgs["abspeakthres"]); float clusterThres = 0.9; if (parsedArgs.count("clusterThres")) clusterThres = us::any_cast<float>(parsedArgs["clusterThres"]); bool noFlip = false; if (parsedArgs.count("noFlip")) noFlip = us::any_cast<bool>(parsedArgs["noFlip"]); bool flipX = false; if (parsedArgs.count("flipX")) flipX = us::any_cast<bool>(parsedArgs["flipX"]); bool flipY = false; if (parsedArgs.count("flipY")) flipY = us::any_cast<bool>(parsedArgs["flipY"]); bool flipZ = false; if (parsedArgs.count("flipZ")) flipZ = us::any_cast<bool>(parsedArgs["flipZ"]); std::cout << "image: " << imageName; std::cout << "outroot: " << outRoot; if (!maskImageName.empty()) std::cout << "mask: " << maskImageName; else std::cout << "no mask image selected"; std::cout << "numpeaks: " << numPeaks; std::cout << "peakthres: " << peakThres; std::cout << "abspeakthres: " << absPeakThres; std::cout << "shOrder: " << shOrder; try { mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(mitk::IOUtil::Load(imageName)[0].GetPointer()); mitk::Image::Pointer mask = dynamic_cast<mitk::Image*>(mitk::IOUtil::Load(maskImageName)[0].GetPointer()); typedef itk::Image<unsigned char, 3> ItkUcharImgType; typedef itk::FiniteDiffOdfMaximaExtractionFilter< float, shOrder, 20242 > MaximaExtractionFilterType; typename MaximaExtractionFilterType::Pointer filter = MaximaExtractionFilterType::New(); int toolkitConvention = 0; if (parsedArgs.count("shConvention")) { string convention = us::any_cast<string>(parsedArgs["shConvention"]).c_str(); if ( boost::algorithm::equals(convention, "FSL") ) { toolkitConvention = 1; std::cout << "Using FSL SH-basis"; } else if ( boost::algorithm::equals(convention, "MRtrix") ) { toolkitConvention = 2; std::cout << "Using MRtrix SH-basis"; } else std::cout << "Using MITK SH-basis"; } else std::cout << "Using MITK SH-basis"; ItkUcharImgType::Pointer itkMaskImage = nullptr; if (mask.IsNotNull()) { try{ itkMaskImage = ItkUcharImgType::New(); mitk::CastToItkImage(mask, itkMaskImage); filter->SetMaskImage(itkMaskImage); } catch(...) { } } if (toolkitConvention>0) { std::cout << "Converting coefficient image to MITK format"; typedef itk::ShCoefficientImageImporter< float, shOrder > ConverterType; typedef mitk::ImageToItk< itk::Image< float, 4 > > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(image); caster->Update(); itk::Image< float, 4 >::Pointer itkImage = caster->GetOutput(); typename ConverterType::Pointer converter = ConverterType::New(); if (noFlip) { converter->SetInputImage(itkImage); } else { std::cout << "Flipping image"; itk::FixedArray<bool, 4> flipAxes; flipAxes[0] = true; flipAxes[1] = true; flipAxes[2] = false; flipAxes[3] = false; itk::FlipImageFilter< itk::Image< float, 4 > >::Pointer flipper = itk::FlipImageFilter< itk::Image< float, 4 > >::New(); flipper->SetInput(itkImage); flipper->SetFlipAxes(flipAxes); flipper->Update(); itk::Image< float, 4 >::Pointer flipped = flipper->GetOutput(); itk::Matrix< double,4,4 > m = itkImage->GetDirection(); m[0][0] *= -1; m[1][1] *= -1; flipped->SetDirection(m); itk::Point< float, 4 > o = itkImage->GetOrigin(); o[0] -= (flipped->GetLargestPossibleRegion().GetSize(0)-1); o[1] -= (flipped->GetLargestPossibleRegion().GetSize(1)-1); flipped->SetOrigin(o); converter->SetInputImage(flipped); } std::cout << "Starting conversion"; switch (toolkitConvention) { case 1: converter->SetToolkit(ConverterType::FSL); filter->SetToolkit(MaximaExtractionFilterType::FSL); break; case 2: converter->SetToolkit(ConverterType::MRTRIX); filter->SetToolkit(MaximaExtractionFilterType::MRTRIX); break; default: converter->SetToolkit(ConverterType::FSL); filter->SetToolkit(MaximaExtractionFilterType::FSL); break; } converter->GenerateData(); filter->SetInput(converter->GetCoefficientImage()); } else { try{ typedef mitk::ImageToItk< typename MaximaExtractionFilterType::CoefficientImageType > CasterType; typename CasterType::Pointer caster = CasterType::New(); caster->SetInput(image); caster->Update(); filter->SetInput(caster->GetOutput()); } catch(...) { std::cout << "wrong image type"; return EXIT_FAILURE; } } filter->SetMaxNumPeaks(numPeaks); filter->SetPeakThreshold(peakThres); filter->SetAbsolutePeakThreshold(absPeakThres); filter->SetAngularThreshold(1); filter->SetClusteringThreshold(clusterThres); filter->SetFlipX(flipX); filter->SetFlipY(flipY); filter->SetFlipZ(flipZ); switch (normalization) { case 0: filter->SetNormalizationMethod(MaximaExtractionFilterType::NO_NORM); break; case 1: filter->SetNormalizationMethod(MaximaExtractionFilterType::MAX_VEC_NORM); break; case 2: filter->SetNormalizationMethod(MaximaExtractionFilterType::SINGLE_VEC_NORM); break; } std::cout << "Starting extraction"; filter->Update(); // write direction image { typename MaximaExtractionFilterType::PeakImageType::Pointer itkImg = filter->GetPeakImage(); string outfilename = outRoot; outfilename.append("_PEAKS.nrrd"); typedef itk::ImageFileWriter< typename MaximaExtractionFilterType::PeakImageType > WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfilename); writer->SetInput(itkImg); writer->Update(); } // write num directions image { ItkUcharImgType::Pointer numDirImage = filter->GetNumDirectionsImage(); if (itkMaskImage.IsNotNull()) { numDirImage->SetDirection(itkMaskImage->GetDirection()); numDirImage->SetOrigin(itkMaskImage->GetOrigin()); } string outfilename = outRoot.c_str(); outfilename.append("_NUM_PEAKS.nrrd"); typedef itk::ImageFileWriter< ItkUcharImgType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfilename); writer->SetInput(numDirImage); writer->Update(); } } catch (itk::ExceptionObject e) { std::cout << e; return EXIT_FAILURE; } catch (std::exception e) { std::cout << e.what(); return EXIT_FAILURE; } catch (...) { std::cout << "ERROR!?!"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
void mitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T> ::Update() { // save input image to nrrd file in temp-folder char filename[512]; srand((unsigned)time(0)); int random_integer = rand(); sprintf( filename, "dwi_%d.nhdr",random_integer); typedef mitk::NrrdDiffusionImageWriter<D> WriterType; typename WriterType::Pointer nrrdWriter = WriterType::New(); nrrdWriter->SetInput( m_Input ); //nrrdWriter->SetDirections(m_Input->GetDirections()); //nrrdWriter->SetB_Value(m_Input->GetB_Value()); nrrdWriter->SetFileName(filename); try { nrrdWriter->Update(); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; } file_replace(filename,"vector","list"); // build up correct command from input params char command[4096]; sprintf( command, "tend estim -i %s -B kvp -o tensors_%d.nhdr -knownB0 true", filename, random_integer); //m_DiffusionImages; if(m_EstimateErrorImage) { sprintf( command, "%s -ee error_image_%d.nhdr", command, random_integer); } if(m_Sigma != -19191919) { sprintf( command, "%s -sigma %f", command, m_Sigma); } switch(m_EstimationMethod) { case TeemTensorEstimationMethodsLLS: sprintf( command, "%s -est lls", command); break; case TeemTensorEstimationMethodsMLE: sprintf( command, "%s -est mle", command); break; case TeemTensorEstimationMethodsNLS: sprintf( command, "%s -est nls", command); break; case TeemTensorEstimationMethodsWLS: sprintf( command, "%s -est wls", command); break; } sprintf( command, "%s -wlsi %d", command, m_NumIterations); if(m_ConfidenceThreshold != -19191919.0) { sprintf( command, "%s -t %f", command, m_ConfidenceThreshold); } sprintf( command, "%s -soft %f", command, m_ConfidenceFuzzyness); sprintf( command, "%s -mv %f", command, m_MinPlausibleValue); // call tend estim command std::cout << "Calling <" << command << ">" << std::endl; int success = system(command); if(!success) { MITK_ERROR << "system command could not be called!"; } remove(filename); sprintf( filename, "dwi_%d.raw", random_integer); remove(filename); // change kind from tensor to vector sprintf( filename, "tensors_%d.nhdr", random_integer); file_replace(filename,"3D-masked-symmetric-matrix","vector"); // read result as mitk::Image and provide it in m_Output typedef itk::ImageFileReader<VectorImageType> FileReaderType; typename FileReaderType::Pointer reader = FileReaderType::New(); reader->SetFileName(filename); reader->Update(); typename VectorImageType::Pointer vecImage = reader->GetOutput(); remove(filename); sprintf( filename, "tensors_%d.raw", random_integer); remove(filename); typename ItkTensorImageType::Pointer itkTensorImage = ItkTensorImageType::New(); itkTensorImage->SetSpacing( vecImage->GetSpacing() ); // Set the image spacing itkTensorImage->SetOrigin( vecImage->GetOrigin() ); // Set the image origin itkTensorImage->SetDirection( vecImage->GetDirection() ); // Set the image direction itkTensorImage->SetLargestPossibleRegion( vecImage->GetLargestPossibleRegion() ); itkTensorImage->SetBufferedRegion( vecImage->GetLargestPossibleRegion() ); itkTensorImage->SetRequestedRegion( vecImage->GetLargestPossibleRegion() ); itkTensorImage->Allocate(); itk::ImageRegionIterator<VectorImageType> it(vecImage, vecImage->GetLargestPossibleRegion()); itk::ImageRegionIterator<ItkTensorImageType> it2(itkTensorImage, itkTensorImage->GetLargestPossibleRegion()); it2 = it2.Begin(); //#pragma omp parallel private (it) { for(it=it.Begin();!it.IsAtEnd(); ++it, ++it2) { //#pragma omp single nowait { VectorType vec = it.Get(); TensorType tensor; for(int i=1;i<7;i++) tensor[i-1] = vec[i] * vec[0]; it2.Set( tensor ); } } // end for } // end ompparallel m_OutputItk = mitk::TensorImage::New(); m_OutputItk->InitializeByItk(itkTensorImage.GetPointer()); m_OutputItk->SetVolume( itkTensorImage->GetBufferPointer() ); // in case: read resulting error-image and provide it in m_ErrorImage if(m_EstimateErrorImage) { // open error image here } }
int changeOrientationMethod(string inputFilename, string outputFilename, OrientationType orientation, bool changeOrientation, bool displayInitialOrientation, bool displayAvailableOrientation) { typedef itk::Image< TPixelType, N > ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; typedef itk::ImageFileWriter<ImageType> WriterType; typename ReaderType::Pointer reader = ReaderType::New(); itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New(); reader->SetImageIO(io); reader->SetFileName(inputFilename); OrientImage<ImageType> orientationFilter; orientationFilter.setInputImage(reader->GetOutput()); if (displayInitialOrientation) { try { io->SetFileName(inputFilename); io->ReadImageInformation(); //reader->Update(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught while reading input image " << std::endl; std::cerr << e << std::endl; } typename ImageType::DirectionType direction; vector<double> dir0 = io->GetDirection(0); for (int i=0; i<dir0.size(); i++) direction(i,0) = dir0[i]; vector<double> dir1 = io->GetDirection(1); for (int i=0; i<dir1.size(); i++) direction(i,1) = dir1[i]; vector<double> dir2 = io->GetDirection(2); for (int i=0; i<dir2.size(); i++) direction(i,2) = dir2[i]; cout << direction << endl; cout << "Input image orientation : " << FlagToString(orientationFilter.getOrientationFromDirection(direction)) << endl; } if (changeOrientation) { try { io->SetFileName(inputFilename); io->ReadImageInformation(); //reader->Update(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught while reading input image " << std::endl; std::cerr << e << std::endl; } orientationFilter.orientation(orientation); typename WriterType::Pointer writer = WriterType::New(); writer->SetImageIO(io); writer->SetFileName(outputFilename); writer->SetInput(orientationFilter.getOutputImage()); try { writer->Write(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught while writing output image " << std::endl; std::cerr << e << std::endl; } } return EXIT_SUCCESS; }
void operator()( const Parameter ¶m ) { OSLM_DEBUG( "itk::ImageSeriesWriter with PIXELTYPE "<< fwTools::DynamicType::string<PIXELTYPE>() ); ::fwData::Image::sptr image = param.m_dataImage; // VAG attention : ImageFileReader ne notifie AUCUNE progressEvent mais son ImageIO oui!!!! mais ImageFileReader ne permet pas de l'atteindre // car soit mis a la mano ou alors construit lors de l'Update donc trop tard // Il faut dont creer une ImageIO a la mano (*1*): affecter l'observation sur IO (*2*) et mettre le IO dans le reader (voir *3*) // Reader IO (*1*) typename itk::ImageIOBase::Pointer imageIOWrite = itk::ImageIOFactory::CreateImageIO( "image.jpg", itk::ImageIOFactory::WriteMode); assert( imageIOWrite.IsNotNull() ); // create writer typedef itk::Image< PIXELTYPE, 3> itkImageType; typedef itk::Image< unsigned char, 2 > Image2DType; typedef typename itk::ImageSeriesWriter< itkImageType, Image2DType > WriterType; typename WriterType::Pointer writer = WriterType::New(); // set observation (*2*) itk::LightProcessObject::Pointer castHelper= (itk::LightProcessObject *)(imageIOWrite.GetPointer()); assert( castHelper.IsNotNull() ); Progressor progress(castHelper, param.m_fwWriter, param.m_filename); // create itk Image typename itkImageType::Pointer itkImage = ::fwItkIO::itkImageFactory<itkImageType>( image ); typedef ::itk::IntensityWindowingImageFilter< itkImageType, itkImageType > RescaleFilterType; typename RescaleFilterType::Pointer rescaleFilter = RescaleFilterType::New(); double min, max; ::fwData::Composite::sptr poolTF; poolTF = image->getField< ::fwData::Composite>( ::fwComEd::Dictionary::m_transferFunctionCompositeId ); if(poolTF) { ::fwData::Composite::iterator iter = poolTF->find(::fwData::TransferFunction::s_DEFAULT_TF_NAME); if(iter != poolTF->end()) { ::fwData::TransferFunction::sptr tf; tf = ::fwData::TransferFunction::dynamicCast(iter->second); min = tf->getWLMinMax().first; max = tf->getWLMinMax().second; } } else { ::fwComEd::fieldHelper::MedicalImageHelpers::getMinMax(image, min, max); } rescaleFilter->SetWindowMinimum( min ); rescaleFilter->SetWindowMaximum( max ); rescaleFilter->SetOutputMinimum( 0 ); rescaleFilter->SetOutputMaximum( 255 ); rescaleFilter->InPlaceOff(); rescaleFilter->SetInput( itkImage ); rescaleFilter->Update(); writer->SetInput( rescaleFilter->GetOutput() ); typedef itk::NumericSeriesFileNames NameGeneratorType; NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New(); std::string format = param.m_filename; format += "/%04d.jpg"; nameGenerator->SetSeriesFormat( format.c_str() ); nameGenerator->SetStartIndex( 1 ); nameGenerator->SetEndIndex( image->getSize()[2] ); nameGenerator->SetIncrementIndex( 1 ); writer->SetFileNames( nameGenerator->GetFileNames() ); writer->SetImageIO( imageIOWrite ); // save image; writer->Update(); }